Add backups, currencies and dashboard APIs, and scope access by guard_name.
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-31 18:14:47 +05:00
parent 0d000f9af6
commit 28509eb4ca
65 changed files with 9132 additions and 296 deletions

View File

@@ -82,3 +82,35 @@ jobs:
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy:
name: Deploy binary to server
needs: ci
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache-dependency-path: go.sum
- name: Set up SSH agent
uses: webfactory/ssh-agent@v0.9.0
with:
ssh-private-key: ${{ secrets.DEPLOY_SSH_KEY }}
- name: Trust deploy host
run: ssh-keyscan -H "${DEPLOY_HOST#*@}" >> ~/.ssh/known_hosts
env:
DEPLOY_HOST: ${{ vars.DEPLOY_HOST || 'ubuntu@216.250.10.141' }}
- name: Deploy
run: make deploy
env:
DEPLOY_HOST: ${{ vars.DEPLOY_HOST || 'ubuntu@216.250.10.141' }}

3
.gitignore vendored
View File

@@ -1,6 +1,7 @@
# Binaries
online-back
myapp
app
*.exe
*.exe~
*.dll
@@ -31,6 +32,8 @@ logs/
# Uploaded files (keep directory structure)
public/images/*
!public/images/.gitkeep
public/backups/*
!public/backups/.gitkeep
# IDE & editors
.idea/

View File

@@ -19,3 +19,23 @@ seed:
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
# migrate-rollback:
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
# ---------------------------------------------------------------------------
# Deploy: build + upload only (PM2-ni serwerde özüň restart et)
# ---------------------------------------------------------------------------
DEPLOY_HOST ?= ubuntu@216.250.10.141
DEPLOY_DIR ?= /home/ubuntu
BINARY ?= myapp
.PHONY: build-linux deploy swagger
swagger:
swag init -g app.go
build-linux:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -o $(BINARY) ./app.go
deploy: build-linux
ssh $(DEPLOY_HOST) 'mkdir -p $(DEPLOY_DIR)'
scp ./$(BINARY) $(DEPLOY_HOST):$(DEPLOY_DIR)/$(BINARY).new
ssh $(DEPLOY_HOST) 'cd $(DEPLOY_DIR) && chmod +x $(BINARY).new && mv $(BINARY).new $(BINARY)'

6
app.go
View File

@@ -46,10 +46,16 @@ import (
// @tag.description Loan repayments
// @tag.name card-orders
// @tag.description Card orders
// @tag.name card-rekwizit-orders
// @tag.description Card rekwizit (card details) orders
// @tag.name activity-logs
// @tag.description User activity audit trail
// @tag.name visa-master-payment-orders
// @tag.description Visa/Master student-transfer payment orders
// @tag.name backups
// @tag.description Database SQL backups
// @tag.name currencies
// @tag.description Currency exchange rates
func main() {
cfg := config.GetConfig()
logger := logging.GetLogger()

View File

@@ -16,6 +16,7 @@ DROP TABLE IF EXISTS card_types;
DROP TABLE IF EXISTS branch_user;
DROP TABLE IF EXISTS branches;
DROP TABLE IF EXISTS provinces;
DROP TABLE IF EXISTS permission_user;
DROP TABLE IF EXISTS permission_role;
DROP TABLE IF EXISTS role_user;
DROP TABLE IF EXISTS permissions;
@@ -24,3 +25,46 @@ DROP TABLE IF EXISTS registration_verifications;
DROP INDEX IF EXISTS idx_users_phone;
DROP INDEX IF EXISTS idx_users_username;
DROP TABLE IF EXISTS users;
DROP INDEX IF EXISTS idx_currencies_updated_by;
DROP INDEX IF EXISTS idx_currencies_created_by;
DROP INDEX IF EXISTS idx_currencies_to;
DROP INDEX IF EXISTS idx_currencies_from;
DROP INDEX IF EXISTS idx_backups_created_by;
DROP INDEX IF EXISTS idx_backups_created_at;
DROP INDEX IF EXISTS idx_visa_master_payment_orders_branch_id;
DROP INDEX IF EXISTS idx_visa_master_payment_orders_user_id;
DROP INDEX IF EXISTS idx_loan_paid_off_letters_branch_id;
DROP INDEX IF EXISTS idx_loan_paid_off_letters_user_id;
DROP INDEX IF EXISTS idx_loan_orders_branch_id;
DROP INDEX IF EXISTS idx_loan_orders_user_id;
DROP INDEX IF EXISTS idx_card_rekwizit_orders_branch_id;
DROP INDEX IF EXISTS idx_card_rekwizit_orders_user_id;
DROP INDEX IF EXISTS idx_card_pin_orders_branch_id;
DROP INDEX IF EXISTS idx_card_pin_orders_user_id;
DROP INDEX IF EXISTS idx_card_orders_branch_id;
DROP INDEX IF EXISTS idx_card_orders_user_id;
DROP INDEX IF EXISTS idx_cards_user_id;
DROP INDEX IF EXISTS idx_branches_province_id;
DROP INDEX IF EXISTS idx_branch_user_branch_id;
DROP INDEX IF EXISTS idx_branch_user_user_id;
DROP INDEX IF EXISTS idx_permissions_code;
DROP INDEX IF EXISTS idx_roles_code;
DROP INDEX IF EXISTS idx_permission_role_role_id;
DROP INDEX IF EXISTS idx_permission_user_user_id;
DROP INDEX IF EXISTS idx_role_user_user_id;
DROP TABLE IF EXISTS currencies;
DROP TABLE IF EXISTS backups;
DROP TABLE IF EXISTS card_balances;
DROP TABLE IF EXISTS card_rekwizit_orders;

View File

@@ -76,6 +76,22 @@ CREATE TABLE IF NOT EXISTS permission_role (
CONSTRAINT permission_role_permission_id_role_id_key UNIQUE (permission_id, role_id)
);
-- Per-user permission override on top of the role's baseline: 'allow' grants
-- a permission the user's role does not have, 'deny' revokes one the role
-- does grant. An admin can flip their mind by re-assigning the same
-- permission/user pair with a different effect (upsert), rather than having
-- to delete the old override first.
CREATE TABLE IF NOT EXISTS permission_user (
id bigserial PRIMARY KEY,
permission_id bigint REFERENCES permissions(id),
user_id bigint REFERENCES users(id),
effect character varying(10) NOT NULL DEFAULT 'allow',
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT permission_user_permission_id_user_id_key UNIQUE (permission_id, user_id),
CONSTRAINT permission_user_effect_chk CHECK (effect IN ('allow', 'deny'))
);
CREATE TABLE IF NOT EXISTS provinces (
id bigserial PRIMARY KEY,
name json NOT NULL DEFAULT '{}'::json,
@@ -409,3 +425,134 @@ CREATE TABLE IF NOT EXISTS activity_logs (
CREATE INDEX IF NOT EXISTS idx_activity_logs_user_id ON activity_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_activity_logs_module ON activity_logs(module);
CREATE INDEX IF NOT EXISTS idx_activity_logs_created_at ON activity_logs(created_at);
CREATE TABLE IF NOT EXISTS card_rekwizit_orders (
id bigserial PRIMARY KEY,
unique_id character varying(255),
user_id bigint,
card_type_id bigint NOT NULL,
card_number character varying(255) NOT NULL,
card_month character varying(255) NOT NULL,
card_year character varying(255) NOT NULL,
region character varying(255) NOT NULL,
branch_id bigint NOT NULL,
customer_name character varying(255) NOT NULL,
customer_surname character varying(255) NOT NULL,
customer_patronic_name character varying(255),
born_at date NOT NULL,
phone character varying(255) NOT NULL,
passport_serie character varying(255) NOT NULL,
passport_id character varying(255) NOT NULL,
passport_one text NOT NULL,
passport_two text NOT NULL,
passport_three text NOT NULL,
passport_four text NOT NULL,
status character varying(255) DEFAULT 'pending'::character varying,
notes text,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT card_rekwizit_orders_card_type_id_fkey
FOREIGN KEY (card_type_id) REFERENCES card_types(id),
CONSTRAINT card_rekwizit_orders_branch_id_fkey
FOREIGN KEY (branch_id) REFERENCES branches(id),
CONSTRAINT card_rekwizit_orders_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE card_balances (
id bigserial PRIMARY KEY,
passport_number TEXT NOT NULL,
card_number TEXT NOT NULL,
card_last4 CHAR(4) GENERATED ALWAYS AS (right(card_number, 4)) STORED,
expiry_month SMALLINT NOT NULL,
expiry_year SMALLINT NOT NULL,
expiry_at DATE GENERATED ALWAYS AS
(make_date(expiry_year, expiry_month, 1)) STORED,
balance_amount NUMERIC(18,2),
balance_currency CHAR(3) DEFAULT 'TMT',
status TEXT NOT NULL DEFAULT 'pending',
checked_at TIMESTAMPTZ,
created_by BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted_at TIMESTAMPTZ,
CONSTRAINT chk_month CHECK (expiry_month BETWEEN 1 AND 12),
CONSTRAINT chk_card CHECK (card_number ~ '^[0-9]{16,19}$'),
CONSTRAINT chk_status CHECK (status IN ('pending','success','failed','expired'))
);
CREATE TABLE IF NOT EXISTS backups (
id bigserial PRIMARY KEY,
file_name character varying(255) NOT NULL,
size_bytes bigint NOT NULL DEFAULT 0,
status character varying(50) NOT NULL DEFAULT 'pending',
error_message text,
created_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT backups_file_name_key UNIQUE (file_name),
CONSTRAINT backups_created_by_fkey
FOREIGN KEY (created_by) REFERENCES users(id),
CONSTRAINT backups_status_chk CHECK (status IN ('pending', 'completed', 'failed'))
);
CREATE TABLE IF NOT EXISTS currencies (
id bigserial PRIMARY KEY,
currency_from character varying(10) NOT NULL,
currency_to character varying(10) NOT NULL,
value numeric(18, 8) NOT NULL,
created_by bigint,
updated_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT currencies_from_to_key UNIQUE (currency_from, currency_to),
CONSTRAINT currencies_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id),
CONSTRAINT currencies_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES users(id)
);
-- Indexes for hot filter/join columns: role_user, permission_role and
-- branch_user are queried on every authenticated request (RBAC role and
-- branch resolution), and every order table below is list-filtered by
-- user_id/branch_id. Postgres does not index foreign key columns
-- automatically, so without these every one of those lookups was a full
-- table scan.
CREATE INDEX IF NOT EXISTS idx_role_user_user_id ON role_user(user_id);
CREATE INDEX IF NOT EXISTS idx_permission_role_role_id ON permission_role(role_id);
CREATE INDEX IF NOT EXISTS idx_permission_user_user_id ON permission_user(user_id);
CREATE INDEX IF NOT EXISTS idx_roles_code ON roles(code);
CREATE INDEX IF NOT EXISTS idx_permissions_code ON permissions(code);
CREATE INDEX IF NOT EXISTS idx_branch_user_user_id ON branch_user(user_id);
CREATE INDEX IF NOT EXISTS idx_branch_user_branch_id ON branch_user(branch_id);
CREATE INDEX IF NOT EXISTS idx_branches_province_id ON branches(province_id);
CREATE INDEX IF NOT EXISTS idx_cards_user_id ON cards(user_id);
CREATE INDEX IF NOT EXISTS idx_card_orders_user_id ON card_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_card_orders_branch_id ON card_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_card_pin_orders_user_id ON card_pin_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_card_pin_orders_branch_id ON card_pin_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_card_rekwizit_orders_user_id ON card_rekwizit_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_card_rekwizit_orders_branch_id ON card_rekwizit_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_loan_orders_user_id ON loan_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_loan_orders_branch_id ON loan_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_loan_paid_off_letters_user_id ON loan_paid_off_letters(user_id);
CREATE INDEX IF NOT EXISTS idx_loan_paid_off_letters_branch_id ON loan_paid_off_letters(branch_id);
CREATE INDEX IF NOT EXISTS idx_visa_master_payment_orders_user_id ON visa_master_payment_orders(user_id);
CREATE INDEX IF NOT EXISTS idx_visa_master_payment_orders_branch_id ON visa_master_payment_orders(branch_id);
CREATE INDEX IF NOT EXISTS idx_backups_created_at ON backups(created_at);
CREATE INDEX IF NOT EXISTS idx_backups_created_by ON backups(created_by);
CREATE INDEX IF NOT EXISTS idx_currencies_from ON currencies(currency_from);
CREATE INDEX IF NOT EXISTS idx_currencies_to ON currencies(currency_to);
CREATE INDEX IF NOT EXISTS idx_currencies_created_by ON currencies(created_by);
CREATE INDEX IF NOT EXISTS idx_currencies_updated_by ON currencies(updated_by);

View File

@@ -0,0 +1 @@
UPDATE roles SET guard_name = 'admin' WHERE code = 'operator';

View File

@@ -0,0 +1,7 @@
-- Guard enforces API access by roles.guard_name:
-- web = customer (own data)
-- operator = branch staff
-- admin = admin / manager / superadmin
UPDATE roles SET guard_name = 'web' WHERE code = 'user';
UPDATE roles SET guard_name = 'operator' WHERE code = 'operator';
UPDATE roles SET guard_name = 'admin' WHERE code IN ('admin', 'superadmin', 'manager');

View File

@@ -11,10 +11,13 @@ BEGIN;
TRUNCATE TABLE
activity_logs,
backups,
currencies,
visa_master_payment_orders,
loan_paid_off_letters,
loans,
loan_orders,
card_rekwizit_orders,
card_pin_orders,
card_orders,
cards,
@@ -107,7 +110,7 @@ INSERT INTO roles (code, name, guard_name) VALUES
('superadmin', 'Super Administrator', 'admin'),
('admin', 'Administrator', 'admin'),
('manager', 'Branch Manager', 'admin'),
('operator', 'Operator', 'admin'),
('operator', 'Operator', 'operator'),
('user', 'User', 'web');
INSERT INTO permissions (code, name, guard_name) VALUES
@@ -125,7 +128,11 @@ INSERT INTO permissions (code, name, guard_name) VALUES
('card-orders.manage', 'Manage card orders', 'admin'),
('loans.view', 'View loans', 'admin'),
('loans.manage', 'Manage loans', 'admin'),
('activity-logs.view', 'View activity logs', 'admin');
('activity-logs.view', 'View activity logs', 'admin'),
('backups.view', 'View backups', 'admin'),
('backups.manage', 'Manage backups', 'admin'),
('currencies.view', 'View currencies', 'admin'),
('currencies.manage', 'Manage currencies', 'admin');
INSERT INTO role_user (role_id, user_id)
SELECT r.id, u.id
@@ -392,12 +399,12 @@ INSERT INTO loan_order_required_docs (name, value, active) VALUES
-- Cards belonging to users
-- ---------------------------------------------------------------------------
INSERT INTO cards (user_id, number, name, month, year, type) VALUES
(5, '4169740012345678', 'SERDAR MYRADOW', '12', '28', 'visa'),
(6, '4169740087654321', 'GULNAR ORAZOWA', '06', '27', 'visa'),
(8, '5536910011223344', 'MAYA HALYLOWA', '03', '29', 'mastercard'),
(7, '9860010055667788', 'DOVRAN ANNAYEW', '09', '26', 'altyn'),
(9, '4169740011112222', 'KERIM ATAYEW', '08', '28', 'visa'),
(10, '5536910055556666', 'LEYLA GURBANOWA', '11', '29', 'mastercard');
(5, '4169740012345678', 'SERDAR MYRADOW', '12', '28', '1'),
(6, '4169740087654321', 'GULNAR ORAZOWA', '06', '27', '1'),
(8, '5536910011223344', 'MAYA HALYLOWA', '03', '29', '3'),
(7, '9860010055667788', 'DOVRAN ANNAYEW', '09', '26', '4'),
(9, '4169740011112222', 'KERIM ATAYEW', '08', '28', '1'),
(10, '5536910055556666', 'LEYLA GURBANOWA', '11', '29', '3');
-- ---------------------------------------------------------------------------
-- Card orders
@@ -479,6 +486,42 @@ INSERT INTO card_pin_orders (
'rejected', 'Passport mismatch'
);
-- ---------------------------------------------------------------------------
-- Card rekwizit orders
-- ---------------------------------------------------------------------------
INSERT INTO card_rekwizit_orders (
unique_id, user_id, card_type_id, card_number, card_month, card_year,
region, branch_id,
customer_name, customer_surname, customer_patronic_name, born_at, phone,
passport_serie, passport_id,
passport_one, passport_two, passport_three, passport_four,
status, notes
) VALUES
(
'CRO-2026-0001', 6, 1, '4169740088776655', '08', '2028',
'AG', 1,
'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03', '+993 61 92 92 48',
'I-AG', '654321',
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
'pending', 'Card details request'
),
(
'CRO-2026-0002', 8, 3, '9860010011223344', '11', '2027',
'BL', 4,
'Maya', 'Halylowa', 'Saparowna', '1992-07-19', '+993 61 92 92 48',
'I-BL', '445566',
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
'approved', 'Details issued'
),
(
'CRO-2026-0003', NULL, 2, '4169740077001122', '01', '2030',
'AH', 3,
'Leyla', 'Garayeva', 'Meredowna', '1993-04-08', '+993 61 92 92 48',
'I-AH', '778899',
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
'rejected', 'Expired card'
);
-- ---------------------------------------------------------------------------
-- Loan orders
-- ---------------------------------------------------------------------------
@@ -666,6 +709,19 @@ INSERT INTO visa_master_payment_orders (
true
);
-- ---------------------------------------------------------------------------
-- Currency rates (Walýuta kursy)
-- ---------------------------------------------------------------------------
INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by) VALUES
('EUR', 'TMT', 3.812, 2, 2),
('USD', 'TMT', 3.5175, 2, 2),
('EUR', 'RUB', 80.23, 2, 1),
('USD', 'RUB', 74.0455, 2, 2),
('RUB', 'TMT', 0.047504, 2, 2),
('USD', 'USD', 250, 1, 1),
('GBP', 'TMT', 4.45, 2, 2),
('CNY', 'TMT', 0.485, 2, 3);
-- ---------------------------------------------------------------------------
-- Activity logs
-- ---------------------------------------------------------------------------
@@ -701,11 +757,14 @@ UNION ALL SELECT 'loan_order_required_docs', count(*) FROM loan_order_required_d
UNION ALL SELECT 'cards', count(*) FROM cards
UNION ALL SELECT 'card_orders', count(*) FROM card_orders
UNION ALL SELECT 'card_pin_orders', count(*) FROM card_pin_orders
UNION ALL SELECT 'card_rekwizit_orders', count(*) FROM card_rekwizit_orders
UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders
UNION ALL SELECT 'loans', count(*) FROM loans
UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters
UNION ALL SELECT 'visa_master_payment_orders', count(*) FROM visa_master_payment_orders
UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications
UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs
UNION ALL SELECT 'backups', count(*) FROM backups
UNION ALL SELECT 'currencies', count(*) FROM currencies
ORDER BY 1;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -16,17 +16,23 @@ var swaggerTagOrder = []struct {
{Name: "role-users", Description: "Role users"},
{Name: "permission", Description: "Permissions"},
{Name: "permission-roles", Description: "Permission roles"},
{Name: "permission-users", Description: "Per-user permission overrides"},
{Name: "payment-card", Description: "Payment cards"},
{Name: "reason-card", Description: "Reason cards"},
{Name: "cards", Description: "Cards"},
{Name: "card-balances", Description: "Card balances"},
{Name: "card-orders", Description: "Card orders"},
{Name: "card-pin-orders", Description: "Card pin orders"},
{Name: "card-rekwizit-orders", Description: "Card rekwizit (card details) orders"},
{Name: "loan-type", Description: "Loan types"},
{Name: "loan-document", Description: "Loan required documents"},
{Name: "loan-orders", Description: "Loan orders"},
{Name: "loans-repayment", Description: "Loan repayments"},
{Name: "loan-paid-off-letters", Description: "Loan paid-off letters"},
{Name: "file-upload", Description: "File upload"},
{Name: "backups", Description: "Database SQL backups"},
{Name: "currencies", Description: "Currency exchange rates"},
{Name: "dashboard", Description: "Admin dashboard overview"},
}
func init() {

View File

@@ -0,0 +1,233 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/backup"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[backup.BackupDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) backup.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "backups", backupColumnsSQL, scanBackup),
logger: logger,
}
}
var backupColumns = []string{
"id", "file_name", "size_bytes", "status", "error_message",
"created_by", "created_at", "updated_at",
}
var backupColumnsSQL = strings.Join(backupColumns, ", ")
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
const backupFromClause = ` FROM backups b
LEFT JOIN users u ON u.id = b.created_by`
var backupSelectColumns = prefixed("b", backupColumns) + `,
` + userDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func prefixed(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
func (r *repository) List(ctx context.Context, filter backup.ListFilter) (backup.ListBackupDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM backups b`+whereClause, args...).Scan(&count); err != nil {
return backup.ListBackupDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY b.created_at DESC, b.id DESC LIMIT $%d OFFSET $%d`,
backupSelectColumns, backupFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return backup.ListBackupDTO{}, err
}
defer rows.Close()
var items []backup.BackupDTO
for rows.Next() {
item, err := scanBackupWithUser(rows)
if err != nil {
return backup.ListBackupDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return backup.ListBackupDTO{}, err
}
return backup.ListBackupDTO{Count: count, Backups: items}, nil
}
func buildListQuery(filter backup.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.Search != "" {
args = append(args, likePattern(filter.Search))
conditions = append(conditions, fmt.Sprintf(`b.file_name ILIKE $%d ESCAPE '\'`, len(args)))
}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("b.status = $%d", len(args)))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
return "%" + escapeLike(term) + "%"
}
func escapeLike(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) (backup.BackupDTO, error) {
query := `SELECT ` + backupSelectColumns + backupFromClause + ` WHERE b.id = $1`
return scanBackupWithUser(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto backup.CreateBackupDTO) (backup.BackupDTO, error) {
query := `
WITH inserted AS (
INSERT INTO backups (file_name, created_by)
VALUES ($1, $2)
RETURNING ` + backupColumnsSQL + `
)
SELECT ` + backupSelectColumns + `
FROM inserted b
LEFT JOIN users u ON u.id = b.created_by`
return scanBackupWithUser(r.client.QueryRow(ctx, query, dto.FileName, dto.CreatedBy))
}
func (r *repository) Finish(ctx context.Context, id int64, sizeBytes int64, status string, errMsg *string) (backup.BackupDTO, error) {
query := `
WITH updated AS (
UPDATE backups SET
size_bytes = $1,
status = $2,
error_message = $3,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4
RETURNING ` + backupColumnsSQL + `
)
SELECT ` + backupSelectColumns + `
FROM updated b
LEFT JOIN users u ON u.id = b.created_by`
item, err := scanBackupWithUser(r.client.QueryRow(ctx, query, sizeBytes, status, errMsg, id))
if err != nil {
return backup.BackupDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func (r *repository) CountByFilePrefix(ctx context.Context, prefix string) (int64, error) {
var count int64
err := r.client.QueryRow(ctx,
`SELECT COUNT(*) FROM backups WHERE file_name LIKE $1 ESCAPE '\'`,
escapeLike(prefix)+"%",
).Scan(&count)
return count, err
}
func scanBackup(row genericrepo.Scanner) (backup.BackupDTO, error) {
return scanBackupRow(row, false)
}
func scanBackupWithUser(row genericrepo.Scanner) (backup.BackupDTO, error) {
return scanBackupRow(row, true)
}
func scanBackupRow(row genericrepo.Scanner, withUser bool) (backup.BackupDTO, error) {
var item backup.BackupDTO
dest := []interface{}{
&item.Id, &item.FileName, &item.SizeBytes, &item.Status, &item.ErrorMessage,
&item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
}
var userName, userUsername, userPhone, userEmail string
if withUser {
dest = append(dest, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return backup.BackupDTO{}, err
}
item.Size = formatSize(item.SizeBytes)
if withUser {
if item.CreatedById != nil {
item.CreatedBy = &backup.UserInfo{
Id: *item.CreatedById,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
} else {
item.CreatedBy = &backup.UserInfo{Name: "System", Username: "system"}
}
}
return item, nil
}
func formatSize(bytes int64) string {
const (
kb = 1024
mb = 1024 * 1024
gb = 1024 * 1024 * 1024
)
switch {
case bytes >= gb:
return fmt.Sprintf("%.1f GB", float64(bytes)/float64(gb))
case bytes >= mb:
if bytes%mb == 0 {
return fmt.Sprintf("%d MB", bytes/mb)
}
return fmt.Sprintf("%.1f MB", float64(bytes)/float64(mb))
case bytes >= kb:
return fmt.Sprintf("%d KB", bytes/kb)
default:
return fmt.Sprintf("%d B", bytes)
}
}

41
internal/backup/dto.go Normal file
View File

@@ -0,0 +1,41 @@
package backup
import "time"
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type BackupDTO struct {
Id int64 `json:"id"`
FileName string `json:"fileName"`
SizeBytes int64 `json:"sizeBytes"`
Size string `json:"size"`
Status string `json:"status"`
ErrorMessage *string `json:"errorMessage,omitempty"`
CreatedById *int64 `json:"-"`
CreatedBy *UserInfo `json:"createdBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateBackupDTO struct {
FileName string
CreatedBy *int64
}
type ListFilter struct {
Search string
Status *string
Page int
Limit int
}
type ListBackupDTO struct {
Count int64 `json:"count"`
Backups []BackupDTO `json:"backups"`
}

55
internal/backup/dump.go Normal file
View File

@@ -0,0 +1,55 @@
package backup
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"time"
"online-back/internal/config"
)
const dumpTimeout = 10 * time.Minute
type Dumper interface {
Dump(ctx context.Context, destPath string) error
}
type PgDumper struct {
storage config.StorageConfig
}
func NewPgDumper(storage config.StorageConfig) *PgDumper {
return &PgDumper{storage: storage}
}
func (d *PgDumper) Dump(ctx context.Context, destPath string) error {
ctx, cancel := context.WithTimeout(ctx, dumpTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, "pg_dump",
"-h", d.storage.Host,
"-p", d.storage.Port,
"-U", d.storage.Username,
"-d", d.storage.Database,
"--no-owner",
"--no-acl",
"-f", destPath,
)
cmd.Env = append(os.Environ(), "PGPASSWORD="+d.storage.Password)
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
if len(msg) > 512 {
msg = msg[:512]
}
return fmt.Errorf("pg_dump: %s", msg)
}
return nil
}

203
internal/backup/handler.go Normal file
View File

@@ -0,0 +1,203 @@
package backup
import (
"errors"
"net/http"
"os"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/backups"
type handler struct {
logger *logging.Logger
service *Service
}
func NewHandler(logger *logging.Logger, service *Service) handlers.Handler {
return &handler{logger: logger, service: service}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.POST("", h.create)
group.GET("/:id/download", h.download)
group.GET("/:id", h.getByID)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List backups
// @Description Returns paginated SQL backup files
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param search query string false "Filter by file name"
// @Param status query string false "Filter by status (pending, completed, failed)"
// @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 /backups [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.service.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list backups failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get backup by ID
// @Description Returns a single backup record
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param id path int true "Backup ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups/{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.service.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 backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create SQL backup
// @Description Runs pg_dump and stores the resulting .sql file
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Success 201 {object} appresult.AppSuccess
// @Failure 500 {object} appresult.AppError
// @Router /backups [post]
func (h *handler) create(c *gin.Context) {
item, err := h.service.Create(c.Request.Context(), currentUserID(c))
if err != nil {
h.logger.Errorf("create backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// download godoc
// @Summary Download backup SQL file
// @Description Downloads the .sql dump for a completed backup
// @Tags backups
// @Produce application/sql
// @Security BearerAuth
// @Param id path int true "Backup ID"
// @Success 200 {file} file
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups/{id}/download [get]
func (h *handler) download(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, path, err := h.service.FilePath(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("download backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if item.Status != "completed" {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if _, err := os.Stat(path); err != nil {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.FileAttachment(path, item.FileName)
}
// delete godoc
// @Summary Delete backup
// @Description Deletes a backup record and its SQL file
// @Tags backups
// @Produce json
// @Security BearerAuth
// @Param id path int true "Backup ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /backups/{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.service.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 backup failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("backup removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := parsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit, Search: queryValue(c, "search", "q")}
if raw := queryValue(c, "status"); raw != "" {
filter.Status = &raw
}
return filter, true
}

81
internal/backup/http.go Normal file
View File

@@ -0,0 +1,81 @@
package backup
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func parsePageLimit(c *gin.Context) (page, limit int, ok bool) {
page = defaultPage
limit = defaultLimit
if raw := queryValue(c, "page"); raw != "" {
p, err := strconv.Atoi(raw)
if err != nil || p < 1 {
return 0, 0, false
}
page = p
}
if raw := queryValue(c, "limit"); raw != "" {
l, err := strconv.Atoi(raw)
if err != nil || l < 1 {
return 0, 0, false
}
if l > maxLimit {
l = maxLimit
}
limit = l
}
return page, limit, true
}
func currentUserID(c *gin.Context) *int64 {
rawID, exists := c.Get("id")
if !exists {
return nil
}
switch id := rawID.(type) {
case int64:
if id > 0 {
return &id
}
case int:
if id > 0 {
v := int64(id)
return &v
}
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
if err == nil && parsed > 0 {
return &parsed
}
}
return nil
}

154
internal/backup/service.go Normal file
View File

@@ -0,0 +1,154 @@
package backup
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"unicode"
"online-back/pkg/logging"
)
type Service struct {
repo Repository
dumper Dumper
dir string
logger *logging.Logger
}
func NewService(repo Repository, dumper Dumper, dir string, logger *logging.Logger) *Service {
return &Service{repo: repo, dumper: dumper, dir: dir, logger: logger}
}
func (s *Service) List(ctx context.Context, filter ListFilter) (ListBackupDTO, error) {
return s.repo.List(ctx, filter)
}
func (s *Service) GetByID(ctx context.Context, id int64) (BackupDTO, error) {
return s.repo.GetByID(ctx, id)
}
func (s *Service) Create(ctx context.Context, userID *int64) (BackupDTO, error) {
if err := os.MkdirAll(s.dir, 0o750); err != nil {
return BackupDTO{}, fmt.Errorf("create backup dir: %w", err)
}
fileName, err := s.nextFileName(ctx)
if err != nil {
return BackupDTO{}, err
}
item, err := s.repo.Create(ctx, CreateBackupDTO{FileName: fileName, CreatedBy: userID})
if err != nil {
return BackupDTO{}, err
}
dest, err := s.absPath(fileName)
if err != nil {
_, _ = s.repo.Finish(ctx, item.Id, 0, "failed", errString(err))
return BackupDTO{}, err
}
if dumpErr := s.dumper.Dump(ctx, dest); dumpErr != nil {
_ = os.Remove(dest)
msg := dumpErr.Error()
s.logger.Errorf("sql backup dump failed: %v", dumpErr)
return s.repo.Finish(ctx, item.Id, 0, "failed", &msg)
}
info, statErr := os.Stat(dest)
if statErr != nil {
_ = os.Remove(dest)
msg := statErr.Error()
return s.repo.Finish(ctx, item.Id, 0, "failed", &msg)
}
return s.repo.Finish(ctx, item.Id, info.Size(), "completed", nil)
}
func (s *Service) Delete(ctx context.Context, id int64) error {
item, err := s.repo.GetByID(ctx, id)
if err != nil {
return err
}
if err := s.repo.Delete(ctx, id); err != nil {
return err
}
if path, pathErr := s.absPath(item.FileName); pathErr == nil {
if rmErr := os.Remove(path); rmErr != nil && !os.IsNotExist(rmErr) {
s.logger.Errorf("remove backup file %s: %v", item.FileName, rmErr)
}
}
return nil
}
func (s *Service) FilePath(ctx context.Context, id int64) (BackupDTO, string, error) {
item, err := s.repo.GetByID(ctx, id)
if err != nil {
return BackupDTO{}, "", err
}
path, err := s.absPath(item.FileName)
if err != nil {
return BackupDTO{}, "", err
}
return item, path, nil
}
func (s *Service) nextFileName(ctx context.Context) (string, error) {
day := time.Now().UTC().Format("2006_01_02")
prefix := "backup_" + day + "_"
n, err := s.repo.CountByFilePrefix(ctx, prefix)
if err != nil {
return "", err
}
return fmt.Sprintf("backup_%s_%02d.sql", day, n+1), nil
}
func (s *Service) absPath(fileName string) (string, error) {
if !validBackupFileName(fileName) {
return "", fmt.Errorf("invalid backup file name")
}
dir, err := filepath.Abs(s.dir)
if err != nil {
return "", err
}
full, err := filepath.Abs(filepath.Join(dir, fileName))
if err != nil {
return "", err
}
sep := string(os.PathSeparator)
if full != dir && !strings.HasPrefix(full, dir+sep) {
return "", fmt.Errorf("invalid backup path")
}
return full, nil
}
func validBackupFileName(name string) bool {
if name == "" || name != filepath.Base(name) || strings.Contains(name, "..") {
return false
}
if !strings.HasPrefix(name, "backup_") || !strings.HasSuffix(name, ".sql") {
return false
}
for _, r := range name {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.' {
continue
}
return false
}
return true
}
func errString(err error) *string {
if err == nil {
return nil
}
msg := err.Error()
return &msg
}

View File

@@ -0,0 +1,24 @@
package backup
import "testing"
func TestValidBackupFileName(t *testing.T) {
tests := []struct {
name string
ok bool
}{
{"backup_2026_05_22_01.sql", true},
{"backup_2026_08_29_12.sql", true},
{"", false},
{"../etc/passwd", false},
{"backup_2026_05_22_01.sql/../../x", false},
{"foo.sql", false},
{"backup_2026_05_22_01.sql.exe", false},
{"backup_2026_05_22_01.sql ", false},
}
for _, tt := range tests {
if got := validBackupFileName(tt.name); got != tt.ok {
t.Errorf("validBackupFileName(%q) = %v, want %v", tt.name, got, tt.ok)
}
}
}

View File

@@ -0,0 +1,12 @@
package backup
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListBackupDTO, error)
GetByID(ctx context.Context, id int64) (BackupDTO, error)
Create(ctx context.Context, dto CreateBackupDTO) (BackupDTO, error)
Finish(ctx context.Context, id int64, sizeBytes int64, status string, errMsg *string) (BackupDTO, error)
Delete(ctx context.Context, id int64) error
CountByFilePrefix(ctx context.Context, prefix string) (int64, error)
}

View File

@@ -0,0 +1,228 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/cards/cardbalance"
"online-back/internal/cards/shared"
"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
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardbalance.Repository {
return &repository{client: client, logger: logger}
}
// cardBalanceColumns lists the columns returned to callers. card_last4 and
// expiry_at are DB-generated (see migration), so they are never written but
// are always readable; the raw card_number is intentionally excluded here so
// full PANs never leave the API - only the masked last4 is exposed.
var cardBalanceColumns = []string{
"id", "passport_number", "card_last4", "expiry_month", "expiry_year", "expiry_at",
"balance_amount", "balance_currency", "status", "checked_at",
"created_by", "created_at", "updated_at",
}
var cardBalanceColumnsSQL = strings.Join(cardBalanceColumns, ", ")
var cardBalanceWritableColumns = []string{
"passport_number", "card_number", "expiry_month", "expiry_year",
"balance_amount", "balance_currency", "status", "checked_at", "created_by",
}
var cardBalanceWritableColumnsSQL = strings.Join(cardBalanceWritableColumns, ", ")
const cardBalanceFromClause = ` FROM card_balances cb
LEFT JOIN users u ON u.id = cb.created_by`
var cardBalanceSelectColumns = shared.PrefixedColumns("cb", cardBalanceColumns) + `,
COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, ''), ` + shared.UserDisplaySQL
func resolveStatus(status *string) string {
if status == nil || strings.TrimSpace(*status) == "" {
return "pending"
}
return *status
}
func resolveCurrency(currency *string) string {
if currency == nil || strings.TrimSpace(*currency) == "" {
return "TMT"
}
return *currency
}
func createArgs(dto cardbalance.CreateCardBalanceDTO) []interface{} {
return []interface{}{
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.CreatedBy),
}
}
func updateArgs(dto cardbalance.UpdateCardBalanceDTO) []interface{} {
return []interface{}{
dto.PassportNumber, dto.CardNumber, dto.ExpiryMonth, dto.ExpiryYear,
dto.BalanceAmount, resolveCurrency(dto.BalanceCurrency), resolveStatus(dto.Status),
shared.OptionalTime(dto.CheckedAt), shared.OptionalInt64(dto.CreatedBy),
}
}
func (r *repository) List(ctx context.Context, filter cardbalance.ListFilter) (cardbalance.ListCardBalanceDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_balances cb`+whereClause, args...).Scan(&count); err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY cb.id DESC LIMIT $%d OFFSET $%d`,
cardBalanceSelectColumns, cardBalanceFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
defer rows.Close()
var items []cardbalance.CardBalanceDTO
for rows.Next() {
item, err := scanCardBalanceWithJoins(rows)
if err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardbalance.ListCardBalanceDTO{}, err
}
return cardbalance.ListCardBalanceDTO{Count: count, CardBalances: items}, nil
}
func buildListQuery(filter cardbalance.ListFilter) (whereClause string, args []interface{}) {
conditions := []string{"cb.deleted_at IS NULL"}
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("cb.status = $%d", len(args)))
}
if filter.PassportNumber != "" {
args = append(args, filter.PassportNumber)
conditions = append(conditions, fmt.Sprintf("cb.passport_number = $%d", len(args)))
}
if filter.CreatedBy != nil {
args = append(args, *filter.CreatedBy)
conditions = append(conditions, fmt.Sprintf("cb.created_by = $%d", len(args)))
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func (r *repository) GetByID(ctx context.Context, id int64) (cardbalance.CardBalanceDTO, error) {
query := `SELECT ` + cardBalanceSelectColumns + cardBalanceFromClause + ` WHERE cb.id = $1 AND cb.deleted_at IS NULL`
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardbalance.CreateCardBalanceDTO) (cardbalance.CardBalanceDTO, 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 card_balances (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted cb
LEFT JOIN users u ON u.id = cb.created_by`,
cardBalanceWritableColumnsSQL, strings.Join(placeholders, ", "),
cardBalanceColumnsSQL, cardBalanceSelectColumns,
)
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardbalance.UpdateCardBalanceDTO) (cardbalance.CardBalanceDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardBalanceWritableColumns))
for i, column := range cardBalanceWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_balances SET %s, updated_at = now()
WHERE id = $%d AND deleted_at IS NULL
RETURNING %s
)
SELECT %s
FROM updated cb
LEFT JOIN users u ON u.id = cb.created_by`,
strings.Join(assignments, ", "), len(args), cardBalanceColumnsSQL, cardBalanceSelectColumns,
)
return scanCardBalanceWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `UPDATE card_balances SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
func scanCardBalanceWithJoins(row genericrepo.Scanner) (cardbalance.CardBalanceDTO, error) {
var item cardbalance.CardBalanceDTO
var userUsername, userPhone, userEmail, userName string
dest := []interface{}{
&item.Id, &item.PassportNumber, &item.CardLast4, &item.ExpiryMonth, &item.ExpiryYear, &item.ExpiryAt,
&item.BalanceAmount, &item.BalanceCurrency, &item.Status, &item.CheckedAt,
&item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
&userUsername, &userPhone, &userEmail, &userName,
}
if err := row.Scan(dest...); err != nil {
return cardbalance.CardBalanceDTO{}, err
}
if item.CreatedById != nil {
item.CreatedBy = &shared.UserInfo{
Id: *item.CreatedById,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}

View File

@@ -0,0 +1,61 @@
package cardbalance
import (
"time"
"online-back/internal/cards/shared"
)
type CardBalanceDTO struct {
Id int64 `json:"id"`
PassportNumber string `json:"passportNumber"`
CardLast4 string `json:"cardLast4"`
ExpiryMonth int16 `json:"expiryMonth"`
ExpiryYear int16 `json:"expiryYear"`
ExpiryAt time.Time `json:"expiryAt"`
BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency string `json:"balanceCurrency"`
Status string `json:"status"`
CheckedAt *time.Time `json:"checkedAt"`
CreatedById *int64 `json:"-"`
CreatedBy *shared.UserInfo `json:"createdBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardBalanceDTO struct {
PassportNumber string `json:"passportNumber" binding:"required"`
CardNumber string `json:"cardNumber" binding:"required"`
ExpiryMonth int16 `json:"expiryMonth" binding:"required"`
ExpiryYear int16 `json:"expiryYear" binding:"required"`
BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency *string `json:"balanceCurrency"`
Status *string `json:"status"`
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
}
type UpdateCardBalanceDTO struct {
PassportNumber string `json:"passportNumber" binding:"required"`
CardNumber string `json:"cardNumber" binding:"required"`
ExpiryMonth int16 `json:"expiryMonth" binding:"required"`
ExpiryYear int16 `json:"expiryYear" binding:"required"`
BalanceAmount *float64 `json:"balanceAmount"`
BalanceCurrency *string `json:"balanceCurrency"`
Status *string `json:"status"`
CheckedAt *shared.FlexibleTime `json:"checkedAt" swaggertype:"string" format:"date-time"`
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
}
type ListFilter struct {
Status *string
PassportNumber string
CreatedBy *int64
Page int
Limit int
}
type ListCardBalanceDTO struct {
Count int64 `json:"count"`
CardBalances []CardBalanceDTO `json:"cardBalances"`
}

View File

@@ -0,0 +1,224 @@
package cardbalance
import (
"errors"
"net/http"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/card-balances"
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 card balances
// @Description Returns paginated card balance checks with optional filters
// @Tags card-balances
// @Produce json
// @Security BearerAuth
// @Param status query string false "Filter by status"
// @Param passport_number query string false "Filter by passport number"
// @Param created_by query int false "Filter by creator user 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 /card-balances [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 card balances failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card balance by ID
// @Description Returns a single card balance check
// @Tags card-balances
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card balance ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.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 card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card balance
// @Description Creates a new card balance check record
// @Tags card-balances
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardBalanceDTO true "Card balance payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardBalanceDTO
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 card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card balance
// @Description Updates an existing card balance check record
// @Tags card-balances
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card balance ID"
// @Param body body UpdateCardBalanceDTO true "Card balance payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateCardBalanceDTO
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 card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card balance
// @Description Soft-deletes a card balance check record
// @Tags card-balances
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card balance ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-balances/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.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 card balance failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("card balance removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := shared.QueryValue(c, "passport_number", "passportNumber"); raw != "" {
filter.PassportNumber = raw
}
if id, ok := shared.OptionalQueryID(c, "created_by", "createdBy"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CreatedBy = id
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package cardbalance
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardBalanceDTO, error)
GetByID(ctx context.Context, id int64) (CardBalanceDTO, error)
Create(ctx context.Context, dto CreateCardBalanceDTO) (CardBalanceDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardBalanceDTO) (CardBalanceDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -98,7 +98,7 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
@@ -260,7 +260,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
@@ -272,5 +272,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -97,7 +97,7 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
@@ -251,7 +251,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
@@ -263,5 +263,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -0,0 +1,276 @@
package db
import (
"context"
"fmt"
"strings"
"online-back/internal/cards/cardrekwizit"
"online-back/internal/cards/shared"
"online-back/internal/identity/rbac"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[cardrekwizit.CardRekwizitOrderDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) cardrekwizit.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "card_rekwizit_orders", cardRekwizitOrderColumnsSQL, scanCardRekwizitOrder),
logger: logger,
}
}
var cardRekwizitOrderWritableColumns = []string{
"unique_id", "user_id", "card_type_id", "card_number", "card_month", "card_year",
"region", "branch_id",
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
"status", "notes",
}
var cardRekwizitOrderColumns = append(append([]string{"id"}, cardRekwizitOrderWritableColumns...), "created_at", "updated_at")
var cardRekwizitOrderColumnsSQL = strings.Join(cardRekwizitOrderColumns, ", ")
var cardRekwizitOrderWritableColumnsSQL = strings.Join(cardRekwizitOrderWritableColumns, ", ")
const cardRekwizitOrderFromClause = ` FROM card_rekwizit_orders cro
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
LEFT JOIN branches b ON b.id = cro.branch_id
LEFT JOIN users u ON u.id = cro.user_id`
var cardRekwizitOrderSelectColumns = shared.PrefixedColumns("cro", cardRekwizitOrderColumns) + `,
ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func resolveStatus(status *string) *string {
if status == nil || strings.TrimSpace(*status) == "" {
pending := "pending"
return &pending
}
return status
}
func createArgs(dto cardrekwizit.CreateCardRekwizitOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(),
dto.CardNumber, dto.CardMonth, dto.CardYear,
dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt.Time(), dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
resolveStatus(dto.Status), dto.Notes,
}
}
func updateArgs(dto cardrekwizit.UpdateCardRekwizitOrderDTO) []interface{} {
return []interface{}{
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(),
dto.CardNumber, dto.CardMonth, dto.CardYear,
dto.Region, dto.BranchId.Int64(),
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt.Time(), dto.Phone,
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
resolveStatus(dto.Status), dto.Notes,
}
}
func (r *repository) List(ctx context.Context, filter cardrekwizit.ListFilter) (cardrekwizit.ListCardRekwizitOrderDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_rekwizit_orders cro`+whereClause, args...).Scan(&count); err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY cro.id LIMIT $%d OFFSET $%d`,
cardRekwizitOrderSelectColumns, cardRekwizitOrderFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
defer rows.Close()
var items []cardrekwizit.CardRekwizitOrderDTO
for rows.Next() {
item, err := scanCardRekwizitOrderWithJoins(rows)
if err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return cardrekwizit.ListCardRekwizitOrderDTO{}, err
}
return cardrekwizit.ListCardRekwizitOrderDTO{Count: count, CardRekwizitOrders: items}, nil
}
func buildListQuery(filter cardrekwizit.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.Status != nil {
args = append(args, *filter.Status)
conditions = append(conditions, fmt.Sprintf("cro.status = $%d", len(args)))
}
if len(filter.BranchIds) > 0 {
conditions, args = rbac.AppendBranchIDs(conditions, args, "cro.branch_id", filter.BranchIds)
} else if filter.BranchId != nil {
args = append(args, *filter.BranchId)
conditions = append(conditions, fmt.Sprintf("cro.branch_id = $%d", len(args)))
}
if filter.UserId != nil {
args = append(args, *filter.UserId)
conditions = append(conditions, fmt.Sprintf("cro.user_id = $%d", len(args)))
}
if filter.CardTypeId != nil {
args = append(args, *filter.CardTypeId)
conditions = append(conditions, fmt.Sprintf("cro.card_type_id = $%d", len(args)))
}
if filter.Region != "" {
args = append(args, filter.Region)
conditions = append(conditions, fmt.Sprintf("cro.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) (cardrekwizit.CardRekwizitOrderDTO, error) {
query := `SELECT ` + cardRekwizitOrderSelectColumns + cardRekwizitOrderFromClause + ` WHERE cro.id = $1`
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto cardrekwizit.CreateCardRekwizitOrderDTO) (cardrekwizit.CardRekwizitOrderDTO, 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 card_rekwizit_orders (%s) VALUES (%s)
RETURNING %s
)
SELECT %s
FROM inserted cro
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
LEFT JOIN branches b ON b.id = cro.branch_id
LEFT JOIN users u ON u.id = cro.user_id`,
cardRekwizitOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
cardRekwizitOrderColumnsSQL, cardRekwizitOrderSelectColumns,
)
return scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, args...))
}
func (r *repository) Update(ctx context.Context, id int64, dto cardrekwizit.UpdateCardRekwizitOrderDTO) (cardrekwizit.CardRekwizitOrderDTO, error) {
args := updateArgs(dto)
assignments := make([]string, len(cardRekwizitOrderWritableColumns))
for i, column := range cardRekwizitOrderWritableColumns {
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
}
args = append(args, id)
query := fmt.Sprintf(`
WITH updated AS (
UPDATE card_rekwizit_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $%d
RETURNING %s
)
SELECT %s
FROM updated cro
LEFT JOIN card_types ct ON ct.id = cro.card_type_id
LEFT JOIN branches b ON b.id = cro.branch_id
LEFT JOIN users u ON u.id = cro.user_id`,
strings.Join(assignments, ", "), len(args), cardRekwizitOrderColumnsSQL, cardRekwizitOrderSelectColumns,
)
item, err := scanCardRekwizitOrderWithJoins(r.client.QueryRow(ctx, query, args...))
if err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
return item, nil
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func scanCardRekwizitOrder(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderDTO, error) {
return scanCardRekwizitOrderRow(row, false)
}
func scanCardRekwizitOrderWithJoins(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderDTO, error) {
return scanCardRekwizitOrderRow(row, true)
}
func scanCardRekwizitOrderRow(row genericrepo.Scanner, withJoins bool) (cardrekwizit.CardRekwizitOrderDTO, error) {
var item cardrekwizit.CardRekwizitOrderDTO
dest := []interface{}{
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId,
&item.CardNumber, &item.CardMonth, &item.CardYear,
&item.Region, &item.BranchId,
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.Phone,
&item.PassportSerie, &item.PassportId, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour,
&item.Status, &item.Notes,
&item.CreatedAt, &item.UpdatedAt,
}
var cardTypeNameJSON, branchNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withJoins {
dest = append(dest, &cardTypeNameJSON, &branchNameJSON, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
if !withJoins {
return item, nil
}
var cardTypeName, branchName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
return cardrekwizit.CardRekwizitOrderDTO{}, err
}
if item.CardTypeId != 0 {
item.CardType = &shared.NamedInfo{Id: item.CardTypeId, Name: cardTypeName}
}
if item.BranchId != 0 {
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
return item, nil
}

View File

@@ -0,0 +1,101 @@
package cardrekwizit
import (
"time"
"online-back/internal/cards/shared"
)
type CardRekwizitOrderDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
CardTypeId int64 `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CardNumber string `json:"cardNumber"`
CardMonth string `json:"cardMonth"`
CardYear string `json:"cardYear"`
Region string `json:"region"`
BranchId int64 `json:"-"`
Branch *shared.NamedInfo `json:"branch,omitempty"`
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"`
PassportOne string `json:"passportOne"`
PassportTwo string `json:"passportTwo"`
PassportThree string `json:"passportThree"`
PassportFour string `json:"passportFour"`
Status *string `json:"status"`
Notes *string `json:"notes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardRekwizitOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber string `json:"cardNumber" binding:"required"`
CardMonth string `json:"cardMonth" binding:"required"`
CardYear string `json:"cardYear" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
Phone string `json:"phone" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" 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"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type UpdateCardRekwizitOrderDTO struct {
UniqueId *string `json:"uniqueId"`
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
CardNumber string `json:"cardNumber" binding:"required"`
CardMonth string `json:"cardMonth" binding:"required"`
CardYear string `json:"cardYear" binding:"required"`
Region string `json:"region" binding:"required"`
BranchId shared.FlexibleInt64 `json:"branchId" binding:"required" swaggertype:"integer"`
CustomerName string `json:"customerName" binding:"required"`
CustomerSurname string `json:"customerSurname" binding:"required"`
CustomerPatronicName *string `json:"customerPatronicName"`
BornAt shared.FlexibleTime `json:"bornAt" binding:"required" swaggertype:"string" format:"date"`
Phone string `json:"phone" binding:"required"`
PassportSerie string `json:"passportSerie" binding:"required"`
PassportId string `json:"passportId" 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"`
Status *string `json:"status"`
Notes *string `json:"notes"`
}
type ListFilter struct {
Status *string
BranchId *int64
BranchIds []int64
UserId *int64
CardTypeId *int64
Region string
Page int
Limit int
}
type ListCardRekwizitOrderDTO struct {
Count int64 `json:"count"`
CardRekwizitOrders []CardRekwizitOrderDTO `json:"cardRekwizitOrders"`
}

View File

@@ -0,0 +1,267 @@
package cardrekwizit
import (
"errors"
"net/http"
"online-back/internal/appresult"
"online-back/internal/cards/shared"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/card-rekwizit-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 card rekwizit orders
// @Description Returns paginated card rekwizit (card details) orders with optional filters
// @Tags card-rekwizit-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 card_type_id query int false "Filter by card type 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 /card-rekwizit-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 card rekwizit orders failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get card rekwizit order by ID
// @Description Returns a single card rekwizit order
// @Tags card-rekwizit-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card rekwizit order ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := shared.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 card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create card rekwizit order
// @Description Creates a new card rekwizit (card details) order
// @Tags card-rekwizit-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCardRekwizitOrderDTO true "Card rekwizit order payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCardRekwizitOrderDTO
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 card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update card rekwizit order
// @Description Updates an existing card rekwizit order
// @Tags card-rekwizit-orders
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card rekwizit order ID"
// @Param body body UpdateCardRekwizitOrderDTO true "Card rekwizit order payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
return
}
var dto UpdateCardRekwizitOrderDTO
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 card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete card rekwizit order
// @Description Deletes a card rekwizit order
// @Tags card-rekwizit-orders
// @Produce json
// @Security BearerAuth
// @Param id path int true "Card rekwizit order ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /card-rekwizit-orders/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := shared.ParseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if !h.guardBranchByID(c, id) {
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 card rekwizit order failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("card rekwizit order removed"))
}
func parseListFilter(c *gin.Context) (ListFilter, bool) {
page, limit, ok := shared.ParsePageLimit(c)
if !ok {
return ListFilter{}, false
}
filter := ListFilter{Page: page, Limit: limit}
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.BranchId = id
}
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.UserId = id
}
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
return ListFilter{}, false
} else if id != nil {
filter.CardTypeId = id
}
if raw := shared.QueryValue(c, "status"); raw != "" {
filter.Status = &raw
}
if raw := shared.QueryValue(c, "region"); raw != "" {
filter.Region = raw
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return false
}
if err != nil {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -0,0 +1,11 @@
package cardrekwizit
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCardRekwizitOrderDTO, error)
GetByID(ctx context.Context, id int64) (CardRekwizitOrderDTO, error)
Create(ctx context.Context, dto CreateCardRekwizitOrderDTO) (CardRekwizitOrderDTO, error)
Update(ctx context.Context, id int64, dto UpdateCardRekwizitOrderDTO) (CardRekwizitOrderDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -3,6 +3,7 @@ package db
import (
"context"
"fmt"
"strconv"
"strings"
"online-back/internal/cards/cards"
@@ -40,10 +41,11 @@ var cardColumnsSQL = strings.Join(cardColumns, ", ")
var cardWritableColumnsSQL = strings.Join(cardWritableColumns, ", ")
const cardFromClause = ` FROM cards c
LEFT JOIN card_types ct ON ct.id::text = c.type
LEFT JOIN users u ON u.id = c.user_id`
var cardSelectColumns = shared.PrefixedColumns("c", cardColumns) + `, ` +
shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
var cardSelectColumns = shared.PrefixedColumns("c", cardColumns) + `,
ct.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
func createArgs(dto cards.CreateCardDTO) []interface{} {
return []interface{}{
@@ -139,6 +141,7 @@ func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards
)
SELECT %s
FROM inserted c
LEFT JOIN card_types ct ON ct.id::text = c.type
LEFT JOIN users u ON u.id = c.user_id`,
cardWritableColumnsSQL, strings.Join(placeholders, ", "),
cardColumnsSQL, cardSelectColumns,
@@ -164,6 +167,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
)
SELECT %s
FROM updated c
LEFT JOIN card_types ct ON ct.id::text = c.type
LEFT JOIN users u ON u.id = c.user_id`,
strings.Join(assignments, ", "), len(args), cardColumnsSQL, cardSelectColumns,
)
@@ -194,22 +198,43 @@ func scanCardRow(row genericrepo.Scanner, withUser bool) (cards.CardDTO, error)
&item.CreatedAt, &item.UpdatedAt,
}
var cardTypeNameJSON []byte
var userName, userUsername, userPhone, userEmail string
if withUser {
dest = append(dest, &userName, &userUsername, &userPhone, &userEmail)
dest = append(dest, &cardTypeNameJSON, &userName, &userUsername, &userPhone, &userEmail)
}
if err := row.Scan(dest...); err != nil {
return cards.CardDTO{}, err
}
if withUser && item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
if withUser {
var cardTypeName shared.LocalizedText
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
return cards.CardDTO{}, err
}
if id := parseCardTypeID(item.Type); id != 0 {
item.CardType = &shared.NamedInfo{Id: id, Name: cardTypeName}
}
if item.UserId != nil {
item.User = &shared.UserInfo{
Id: *item.UserId,
Name: userName,
Username: userUsername,
Phone: userPhone,
Email: userEmail,
}
}
}
return item, nil
}
func parseCardTypeID(raw *string) int64 {
if raw == nil {
return 0
}
id, err := strconv.ParseInt(strings.TrimSpace(*raw), 10, 64)
if err != nil {
return 0
}
return id
}

View File

@@ -7,16 +7,17 @@ import (
)
type CardDTO struct {
Id int64 `json:"id"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Number string `json:"number"`
Name string `json:"name"`
Month string `json:"month"`
Year *string `json:"year"`
Type *string `json:"type"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Id int64 `json:"id"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
Number string `json:"number"`
Name string `json:"name"`
Month string `json:"month"`
Year *string `json:"year"`
Type *string `json:"-"`
CardType *shared.NamedInfo `json:"cardType,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateCardDTO struct {

View File

@@ -94,6 +94,9 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardOwned(c, item.UserId) {
return
}
if item.UserId != nil && !rbac.GuardUser(c, *item.UserId) {
return
}
@@ -236,7 +239,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
}
func (h *handler) guardCardByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)

View File

@@ -1,13 +1,18 @@
// Package cards groups payment cards, card orders, PIN orders, visa/master
// payment orders, and their reference data (reasons, payment card types)
// under one bounded context, replacing the flat internal/admin/* listing.
// Package cards groups payment cards, card orders, PIN orders, rekwizit
// (card details) orders, visa/master payment orders, and their reference
// data (reasons, payment card types) under one bounded context, replacing
// the flat internal/admin/* listing.
package cards
import (
"online-back/internal/cards/cardbalance"
cardbalancedb "online-back/internal/cards/cardbalance/db"
"online-back/internal/cards/cardorder"
cardorderdb "online-back/internal/cards/cardorder/db"
"online-back/internal/cards/cardpinorders"
cardpinordersdb "online-back/internal/cards/cardpinorders/db"
"online-back/internal/cards/cardrekwizit"
cardrekwizitdb "online-back/internal/cards/cardrekwizit/db"
cardentity "online-back/internal/cards/cards"
cardentitydb "online-back/internal/cards/cards/db"
"online-back/internal/cards/paymentcard"
@@ -32,9 +37,11 @@ func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
return []handlers.Handler{
cardbalance.NewHandler(logger, cardbalancedb.NewRepository(client, logger)),
cardentity.NewHandler(logger, cardentitydb.NewRepository(client, logger)),
cardorder.NewHandler(logger, cardorderdb.NewRepository(client, logger)),
cardpinorders.NewHandler(logger, cardpinordersdb.NewRepository(client, logger)),
cardrekwizit.NewHandler(logger, cardrekwizitdb.NewRepository(client, logger)),
paymentcard.NewHandler(logger, paymentcarddb.NewRepository(client, logger)),
reasonscard.NewHandler(logger, reasonscarddb.NewRepository(client, logger)),
visamaster.NewHandler(logger, visamasterdb.NewRepository(client, logger)),

View File

@@ -97,7 +97,7 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
@@ -249,7 +249,7 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
@@ -261,5 +261,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -0,0 +1,242 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/currency"
"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[currency.CurrencyDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) currency.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "currencies", currencyColumnsSQL, scanCurrency),
logger: logger,
}
}
var currencyColumns = []string{
"id", "currency_from", "currency_to", "value",
"created_by", "updated_by", "created_at", "updated_at",
}
var currencyColumnsSQL = strings.Join(currencyColumns, ", ")
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', %s.first_name, %s.last_name)), ''), NULLIF(%s.name, ''), %s.username, '')`
const currencyFromClause = ` FROM currencies c
LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by`
var currencySelectColumns = prefixed("c", currencyColumns) + `,
` + fmt.Sprintf(userDisplaySQL, "cu", "cu", "cu", "cu") + `, COALESCE(cu.username, ''), COALESCE(cu.phone, ''), COALESCE(cu.email, ''),
` + fmt.Sprintf(userDisplaySQL, "uu", "uu", "uu", "uu") + `, COALESCE(uu.username, ''), COALESCE(uu.phone, ''), COALESCE(uu.email, '')`
func prefixed(alias string, cols []string) string {
parts := make([]string, len(cols))
for i, col := range cols {
parts[i] = alias + "." + col
}
return strings.Join(parts, ", ")
}
func (r *repository) List(ctx context.Context, filter currency.ListFilter) (currency.ListCurrencyDTO, error) {
whereClause, args := buildListQuery(filter)
var count int64
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM currencies c`+whereClause, args...).Scan(&count); err != nil {
return currency.ListCurrencyDTO{}, err
}
offset := (filter.Page - 1) * filter.Limit
limitPlaceholder := len(args) + 1
offsetPlaceholder := len(args) + 2
query := fmt.Sprintf(
`SELECT %s%s%s ORDER BY c.id DESC LIMIT $%d OFFSET $%d`,
currencySelectColumns, currencyFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
)
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
if err != nil {
return currency.ListCurrencyDTO{}, err
}
defer rows.Close()
var items []currency.CurrencyDTO
for rows.Next() {
item, err := scanCurrencyWithUsers(rows)
if err != nil {
return currency.ListCurrencyDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return currency.ListCurrencyDTO{}, err
}
return currency.ListCurrencyDTO{Count: count, Currencies: items}, nil
}
func buildListQuery(filter currency.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.Search != "" {
args = append(args, likePattern(filter.Search))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`(
c.currency_from ILIKE $%[1]d ESCAPE '\' OR c.currency_to ILIKE $%[1]d ESCAPE '\'
)`, n))
}
if filter.CurrencyFrom != "" {
args = append(args, filter.CurrencyFrom)
conditions = append(conditions, fmt.Sprintf("c.currency_from = $%d", len(args)))
}
if filter.CurrencyTo != "" {
args = append(args, filter.CurrencyTo)
conditions = append(conditions, fmt.Sprintf("c.currency_to = $%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) (currency.CurrencyDTO, error) {
query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1`
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, id))
}
func (r *repository) Create(ctx context.Context, dto currency.CreateCurrencyDTO) (currency.CurrencyDTO, error) {
from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value)
query := `
WITH inserted AS (
INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by)
VALUES ($1, $2, $3::numeric, $4, $4)
RETURNING ` + currencyColumnsSQL + `
)
SELECT ` + currencySelectColumns + `
FROM inserted c
LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by`
return scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy))
}
func (r *repository) Update(ctx context.Context, id int64, dto currency.UpdateCurrencyDTO) (currency.CurrencyDTO, error) {
from, to, value := normalizeRate(dto.CurrencyFrom, dto.CurrencyTo, dto.Value)
query := `
WITH updated AS (
UPDATE currencies SET
currency_from = $1, currency_to = $2, value = $3::numeric,
updated_by = $4,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $5
RETURNING ` + currencyColumnsSQL + `
)
SELECT ` + currencySelectColumns + `
FROM updated c
LEFT JOIN users cu ON cu.id = c.created_by
LEFT JOIN users uu ON uu.id = c.updated_by`
item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.UpdatedBy, id))
if errors.Is(err, pgx.ErrNoRows) {
return currency.CurrencyDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func normalizeRate(from, to string, value currency.RateValue) (string, string, string) {
return strings.ToUpper(strings.TrimSpace(from)),
strings.ToUpper(strings.TrimSpace(to)),
strings.TrimSpace(value.String())
}
func scanCurrency(row genericrepo.Scanner) (currency.CurrencyDTO, error) {
return scanCurrencyRow(row, false)
}
func scanCurrencyWithUsers(row genericrepo.Scanner) (currency.CurrencyDTO, error) {
return scanCurrencyRow(row, true)
}
func scanCurrencyRow(row genericrepo.Scanner, withUsers bool) (currency.CurrencyDTO, error) {
var item currency.CurrencyDTO
var value string
dest := []interface{}{
&item.Id, &item.CurrencyFrom, &item.CurrencyTo, &value,
&item.CreatedById, &item.UpdatedById, &item.CreatedAt, &item.UpdatedAt,
}
var createdName, createdUsername, createdPhone, createdEmail string
var updatedName, updatedUsername, updatedPhone, updatedEmail string
if withUsers {
dest = append(dest,
&createdName, &createdUsername, &createdPhone, &createdEmail,
&updatedName, &updatedUsername, &updatedPhone, &updatedEmail,
)
}
if err := row.Scan(dest...); err != nil {
return currency.CurrencyDTO{}, err
}
item.Value = currency.RateValue(trimNumeric(value))
if withUsers {
item.CreatedBy = userInfo(item.CreatedById, createdName, createdUsername, createdPhone, createdEmail)
item.UpdatedBy = userInfo(item.UpdatedById, updatedName, updatedUsername, updatedPhone, updatedEmail)
}
return item, nil
}
func userInfo(id *int64, name, username, phone, email string) *currency.UserInfo {
if id == nil {
return nil
}
return &currency.UserInfo{
Id: *id,
Name: name,
Username: username,
Phone: phone,
Email: email,
}
}
func trimNumeric(raw string) string {
raw = strings.TrimSpace(raw)
if !strings.Contains(raw, ".") {
return raw
}
raw = strings.TrimRight(raw, "0")
raw = strings.TrimRight(raw, ".")
if raw == "" {
return "0"
}
return raw
}

88
internal/currency/dto.go Normal file
View File

@@ -0,0 +1,88 @@
package currency
import (
"encoding/json"
"strings"
"time"
)
type RateValue string
func (v RateValue) String() string { return string(v) }
func (v RateValue) MarshalJSON() ([]byte, error) {
s := strings.TrimSpace(string(v))
if s == "" {
return []byte("0"), nil
}
return []byte(s), nil
}
func (v *RateValue) UnmarshalJSON(b []byte) error {
raw := strings.TrimSpace(string(b))
if raw == "" || raw == "null" {
*v = ""
return nil
}
var n json.Number
if err := json.Unmarshal(b, &n); err == nil {
*v = RateValue(n.String())
return nil
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
*v = RateValue(strings.TrimSpace(s))
return nil
}
type CurrencyDTO struct {
Id int64 `json:"id"`
CurrencyFrom string `json:"currencyFrom"`
CurrencyTo string `json:"currencyTo"`
Value RateValue `json:"value" swaggertype:"number"`
CreatedById *int64 `json:"-"`
CreatedBy *UserInfo `json:"createdBy,omitempty"`
UpdatedById *int64 `json:"-"`
UpdatedBy *UserInfo `json:"updatedBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type UserInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
Phone string `json:"phone"`
Email string `json:"email"`
}
type CreateCurrencyDTO struct {
CurrencyFrom string `json:"currencyFrom" binding:"required"`
CurrencyTo string `json:"currencyTo" binding:"required"`
Value RateValue `json:"value" binding:"required" swaggertype:"number"`
CreatedBy *int64 `json:"-"`
}
type UpdateCurrencyDTO struct {
CurrencyFrom string `json:"currencyFrom" binding:"required"`
CurrencyTo string `json:"currencyTo" binding:"required"`
Value RateValue `json:"value" binding:"required" swaggertype:"number"`
UpdatedBy *int64 `json:"-"`
}
type ListFilter struct {
Search string
CurrencyFrom string
CurrencyTo string
Page int
Limit int
}
type ListCurrencyDTO struct {
Count int64 `json:"count"`
Currencies []CurrencyDTO `json:"currencies"`
}

View File

@@ -0,0 +1,280 @@
package currency
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 = "/currencies"
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 currency rates
// @Description Returns paginated currency exchange rates
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param search query string false "Filter by currency code"
// @Param currency_from query string false "Filter by source currency"
// @Param currency_to query string false "Filter by target currency"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} ListCurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies [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 currencies failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get currency rate by ID
// @Description Returns a single currency exchange rate
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Success 200 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{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 currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create currency rate
// @Description Creates a new currency exchange rate
// @Tags currencies
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateCurrencyDTO true "Currency rate payload"
// @Success 201 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies [post]
func (h *handler) create(c *gin.Context) {
var dto CreateCurrencyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.CreatedBy = currentUserID(c)
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update currency rate
// @Description Updates an existing currency exchange rate
// @Tags currencies
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Param body body UpdateCurrencyDTO true "Currency rate payload"
// @Success 200 {object} CurrencyDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{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 UpdateCurrencyDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.UpdatedBy = currentUserID(c)
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 currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete currency rate
// @Description Deletes a currency exchange rate
// @Tags currencies
// @Produce json
// @Security BearerAuth
// @Param id path int true "Currency ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /currencies/{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 currency failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("currency 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 := queryValue(c, "page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := queryValue(c, "limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return ListFilter{}, false
}
if limit > maxLimit {
limit = maxLimit
}
filter.Limit = limit
}
filter.Search = queryValue(c, "search", "q")
filter.CurrencyFrom = strings.ToUpper(queryValue(c, "currency_from", "currencyFrom"))
filter.CurrencyTo = strings.ToUpper(queryValue(c, "currency_to", "currencyTo"))
return filter, true
}
func queryValue(c *gin.Context, keys ...string) string {
for _, key := range keys {
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
return raw
}
}
return ""
}
func currentUserID(c *gin.Context) *int64 {
rawID, exists := c.Get("id")
if !exists {
return nil
}
switch id := rawID.(type) {
case int64:
if id > 0 {
return &id
}
case int:
if id > 0 {
v := int64(id)
return &v
}
case string:
parsed, err := strconv.ParseInt(id, 10, 64)
if err == nil && parsed > 0 {
return &parsed
}
}
return nil
}

View File

@@ -0,0 +1,11 @@
package currency
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListCurrencyDTO, error)
GetByID(ctx context.Context, id int64) (CurrencyDTO, error)
Create(ctx context.Context, dto CreateCurrencyDTO) (CurrencyDTO, error)
Update(ctx context.Context, id int64, dto UpdateCurrencyDTO) (CurrencyDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -0,0 +1,393 @@
package db
import (
"context"
"fmt"
"math"
"strings"
"time"
"online-back/internal/dashboard"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) dashboard.Repository {
return &repository{client: client, logger: logger}
}
func (r *repository) Overview(ctx context.Context, filter dashboard.OverviewFilter) (dashboard.OverviewDTO, error) {
now := time.Now().UTC()
win := currentPeriodWindow(now)
loanOrders, err := r.loanOrdersMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
activeCards, err := r.activeCardsMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
activeCustomers, err := r.activeCustomersMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
onlinePayments, err := r.onlinePaymentsMetric(ctx, filter.BranchIds, win)
if err != nil {
return dashboard.OverviewDTO{}, err
}
trendPoints, err := r.monthlyTrend(ctx, filter.BranchIds, filter.Year)
if err != nil {
return dashboard.OverviewDTO{}, err
}
loanStatus, err := r.loanStatusBreakdown(ctx, filter.BranchIds)
if err != nil {
return dashboard.OverviewDTO{}, err
}
weeklyOrders, err := r.weeklyOrders(ctx, filter.BranchIds, now)
if err != nil {
return dashboard.OverviewDTO{}, err
}
recentActivity, err := r.recentActivity(ctx, filter.BranchIds, filter.RecentLimit)
if err != nil {
return dashboard.OverviewDTO{}, err
}
return dashboard.OverviewDTO{
Stats: dashboard.StatsDTO{
LoanOrders: loanOrders,
ActiveCards: activeCards,
ActiveCustomers: activeCustomers,
OnlinePayments: onlinePayments,
},
Trend: dashboard.TrendDTO{Year: filter.Year, Points: trendPoints},
LoanStatus: loanStatus,
WeeklyOrders: weeklyOrders,
RecentActivity: recentActivity,
}, nil
}
// periodWindow holds the current-month-to-date range plus the same elapsed
// window one month earlier, so a KPI's "vs last month" change compares like
// with like instead of a partial month against a full one.
type periodWindow struct {
curStart, curEnd time.Time
prevStart, prevEnd time.Time
}
func currentPeriodWindow(now time.Time) periodWindow {
curStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
prevAnchor := curStart.AddDate(0, -1, 0)
prevStart := time.Date(prevAnchor.Year(), prevAnchor.Month(), 1, 0, 0, 0, 0, time.UTC)
return periodWindow{
curStart: curStart,
curEnd: now,
prevStart: prevStart,
prevEnd: prevStart.Add(now.Sub(curStart)),
}
}
func percentChange(cur, prev int64) *float64 {
if prev == 0 {
return nil
}
pct := round2((float64(cur) - float64(prev)) / float64(prev) * 100)
return &pct
}
func round2(v float64) float64 {
return math.Round(v*100) / 100
}
// scanMetric runs a query shaped as "total, current-window count,
// previous-window count" and turns it into a StatMetricDTO.
func (r *repository) scanMetric(ctx context.Context, query string, args ...interface{}) (dashboard.StatMetricDTO, error) {
var total, cur, prev int64
if err := r.client.QueryRow(ctx, query, args...).Scan(&total, &cur, &prev); err != nil {
return dashboard.StatMetricDTO{}, err
}
return dashboard.StatMetricDTO{Count: total, ChangePercent: percentChange(cur, prev)}, nil
}
func metricSQL(fromAndWhere string) string {
return fmt.Sprintf(`
SELECT
COUNT(*),
COUNT(*) FILTER (WHERE created_at >= $1 AND created_at < $2),
COUNT(*) FILTER (WHERE created_at >= $3 AND created_at < $4)
%s`, fromAndWhere)
}
func (r *repository) loanOrdersMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := ""
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(extra)+4)
}
query := metricSQL(`FROM loan_orders WHERE true` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func (r *repository) activeCardsMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := ""
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where = fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = c.user_id AND bu.branch_id = ANY($%d))", len(extra)+4)
}
query := metricSQL(`FROM cards c WHERE true` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func (r *repository) activeCustomersMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := " AND u.role = 'user' AND u.active = true"
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = u.id AND bu.branch_id = ANY($%d))", len(extra)+4)
}
query := metricSQL(`FROM users u WHERE true` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func (r *repository) onlinePaymentsMetric(ctx context.Context, branchIds []int64, win periodWindow) (dashboard.StatMetricDTO, error) {
where := ""
var extra []interface{}
if len(branchIds) > 0 {
extra = append(extra, branchIds)
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(extra)+4)
}
query := metricSQL(`FROM visa_master_payment_orders WHERE true` + where)
return r.scanMetric(ctx, query, append(dateArgs(win), extra...)...)
}
func dateArgs(win periodWindow) []interface{} {
return []interface{}{win.curStart, win.curEnd, win.prevStart, win.prevEnd}
}
// monthlyTrend groups loan_orders and card_orders (both "sargytlar" —
// orders raised by customers) by calendar month for the requested year.
func (r *repository) monthlyTrend(ctx context.Context, branchIds []int64, year int) ([]dashboard.TrendPointDTO, error) {
loanCounts, err := r.monthlyCounts(ctx, "loan_orders", branchIds, year)
if err != nil {
return nil, err
}
cardCounts, err := r.monthlyCounts(ctx, "card_orders", branchIds, year)
if err != nil {
return nil, err
}
points := make([]dashboard.TrendPointDTO, 12)
for month := 1; month <= 12; month++ {
points[month-1] = dashboard.TrendPointDTO{
Month: month,
Loans: loanCounts[month],
Cards: cardCounts[month],
}
}
return points, nil
}
func (r *repository) monthlyCounts(ctx context.Context, table string, branchIds []int64, year int) (map[int]int64, error) {
args := []interface{}{year}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = " AND branch_id = ANY($2)"
}
query := fmt.Sprintf(`
SELECT EXTRACT(MONTH FROM created_at)::int, COUNT(*)
FROM %s
WHERE EXTRACT(YEAR FROM created_at) = $1%s
GROUP BY 1`, table, where)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[int]int64, 12)
for rows.Next() {
var month int
var count int64
if err := rows.Scan(&month, &count); err != nil {
return nil, err
}
counts[month] = count
}
return counts, rows.Err()
}
// weeklyOrders covers the last 7 calendar days including today.
func (r *repository) weeklyOrders(ctx context.Context, branchIds []int64, now time.Time) ([]dashboard.WeeklyPointDTO, error) {
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
start := today.AddDate(0, 0, -6)
loanCounts, err := r.dailyCounts(ctx, "loan_orders", branchIds, start)
if err != nil {
return nil, err
}
cardCounts, err := r.dailyCounts(ctx, "card_orders", branchIds, start)
if err != nil {
return nil, err
}
points := make([]dashboard.WeeklyPointDTO, 7)
for i := 0; i < 7; i++ {
day := start.AddDate(0, 0, i)
key := day.Format("2006-01-02")
points[i] = dashboard.WeeklyPointDTO{
Date: key,
Weekday: int(day.Weekday()+6)%7 + 1, // Monday=1 .. Sunday=7
Loans: loanCounts[key],
Cards: cardCounts[key],
}
}
return points, nil
}
func (r *repository) dailyCounts(ctx context.Context, table string, branchIds []int64, start time.Time) (map[string]int64, error) {
args := []interface{}{start}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = " AND branch_id = ANY($2)"
}
query := fmt.Sprintf(`
SELECT created_at::date, COUNT(*)
FROM %s
WHERE created_at >= $1%s
GROUP BY 1`, table, where)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[string]int64, 7)
for rows.Next() {
var day time.Time
var count int64
if err := rows.Scan(&day, &count); err != nil {
return nil, err
}
counts[day.Format("2006-01-02")] = count
}
return counts, rows.Err()
}
var loanStatusOrder = []string{
dashboard.LoanStatusSatisfied,
dashboard.LoanStatusPending,
dashboard.LoanStatusProcessing,
dashboard.LoanStatusCancelled,
dashboard.LoanStatusRegistered,
}
// loanStatusBucketSQL folds the free-text loan_orders.status column into
// the five buckets the dashboard donut chart renders. Anything unrecognized
// (including NULL, i.e. a freshly created order) falls into "registered".
const loanStatusBucketSQL = `
CASE
WHEN lower(coalesce(status, '')) IN ('approved', 'satisfied', 'completed') THEN 'satisfied'
WHEN lower(coalesce(status, '')) = 'pending' THEN 'pending'
WHEN lower(coalesce(status, '')) IN ('review', 'processing', 'in_process', 'in-process') THEN 'processing'
WHEN lower(coalesce(status, '')) IN ('rejected', 'cancelled', 'canceled', 'declined') THEN 'cancelled'
ELSE 'registered'
END`
func (r *repository) loanStatusBreakdown(ctx context.Context, branchIds []int64) ([]dashboard.LoanStatusShareDTO, error) {
args := []interface{}{}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = " AND branch_id = ANY($1)"
}
query := fmt.Sprintf(`
SELECT %s, COUNT(*)
FROM loan_orders
WHERE true%s
GROUP BY 1`, loanStatusBucketSQL, where)
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
counts := make(map[string]int64, len(loanStatusOrder))
var total int64
for rows.Next() {
var bucket string
var count int64
if err := rows.Scan(&bucket, &count); err != nil {
return nil, err
}
counts[bucket] = count
total += count
}
if err := rows.Err(); err != nil {
return nil, err
}
shares := make([]dashboard.LoanStatusShareDTO, 0, len(loanStatusOrder))
for _, bucket := range loanStatusOrder {
count := counts[bucket]
var pct float64
if total > 0 {
pct = round2(float64(count) / float64(total) * 100)
}
shares = append(shares, dashboard.LoanStatusShareDTO{Status: bucket, Count: count, Percent: pct})
}
return shares, nil
}
func (r *repository) recentActivity(ctx context.Context, branchIds []int64, limit int) ([]dashboard.RecentActivityDTO, error) {
args := []interface{}{}
where := ""
if len(branchIds) > 0 {
args = append(args, branchIds)
where = fmt.Sprintf(" AND branch_id = ANY($%d)", len(args))
}
args = append(args, limit)
query := fmt.Sprintf(`
SELECT id, unique_id, customer_name, customer_surname, loan_amount, status, created_at
FROM loan_orders
WHERE true%s
ORDER BY created_at DESC, id DESC
LIMIT $%d`, where, len(args))
rows, err := r.client.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var items []dashboard.RecentActivityDTO
for rows.Next() {
var item dashboard.RecentActivityDTO
var firstName, lastName string
if err := rows.Scan(&item.Id, &item.UniqueId, &firstName, &lastName, &item.Amount, &item.Status, &item.CreatedAt); err != nil {
return nil, err
}
item.CustomerName = strings.TrimSpace(firstName + " " + lastName)
items = append(items, item)
}
return items, rows.Err()
}

78
internal/dashboard/dto.go Normal file
View File

@@ -0,0 +1,78 @@
package dashboard
import "time"
// StatMetricDTO is a single KPI card: a running total plus the percent
// change of new records this calendar month-to-date versus the same
// elapsed window last month. ChangePercent is nil when last month's
// window has zero records, since a percent change against zero is
// undefined.
type StatMetricDTO struct {
Count int64 `json:"count"`
ChangePercent *float64 `json:"changePercent"`
}
type StatsDTO struct {
LoanOrders StatMetricDTO `json:"loanOrders"`
ActiveCards StatMetricDTO `json:"activeCards"`
ActiveCustomers StatMetricDTO `json:"activeCustomers"`
OnlinePayments StatMetricDTO `json:"onlinePayments"`
}
type TrendPointDTO struct {
Month int `json:"month"`
Loans int64 `json:"loans"`
Cards int64 `json:"cards"`
}
type TrendDTO struct {
Year int `json:"year"`
Points []TrendPointDTO `json:"points"`
}
// LoanStatusShareDTO buckets loan_orders.status into one of five
// normalized states so the UI can render a stable donut chart regardless
// of the raw status text stored on the row.
type LoanStatusShareDTO struct {
Status string `json:"status"`
Count int64 `json:"count"`
Percent float64 `json:"percent"`
}
const (
LoanStatusSatisfied = "satisfied"
LoanStatusPending = "pending"
LoanStatusProcessing = "processing"
LoanStatusCancelled = "cancelled"
LoanStatusRegistered = "registered"
)
type WeeklyPointDTO struct {
Date string `json:"date"`
Weekday int `json:"weekday"`
Loans int64 `json:"loans"`
Cards int64 `json:"cards"`
}
type RecentActivityDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
CustomerName string `json:"customerName"`
Amount *string `json:"amount"`
Status *string `json:"status"`
CreatedAt time.Time `json:"createdAt"`
}
type OverviewDTO struct {
Stats StatsDTO `json:"stats"`
Trend TrendDTO `json:"trend"`
LoanStatus []LoanStatusShareDTO `json:"loanStatus"`
WeeklyOrders []WeeklyPointDTO `json:"weeklyOrders"`
RecentActivity []RecentActivityDTO `json:"recentActivity"`
}
type OverviewFilter struct {
BranchIds []int64
Year int
RecentLimit int
}

View File

@@ -0,0 +1,93 @@
package dashboard
import (
"net/http"
"strconv"
"time"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
)
const baseURL = "/dashboard"
const (
defaultRecentLimit = 10
maxRecentLimit = 50
)
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("/overview", h.overview)
}
// overview godoc
// @Summary Dashboard overview
// @Description Returns the KPI cards, loan/card trend, loan status breakdown, weekly order counts, and recent activity feed for the admin dashboard
// @Tags dashboard
// @Produce json
// @Security BearerAuth
// @Param year query int false "Year for the monthly trend chart" default(current year)
// @Param recent_limit query int false "Number of recent activity items to return" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/overview [get]
func (h *handler) overview(c *gin.Context) {
filter, ok := parseOverviewFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.Overview(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("dashboard overview failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
func parseOverviewFilter(c *gin.Context) (OverviewFilter, bool) {
filter := OverviewFilter{
Year: time.Now().Year(),
RecentLimit: defaultRecentLimit,
}
if raw := c.Query("year"); raw != "" {
year, err := strconv.Atoi(raw)
if err != nil || year < 2000 || year > 2100 {
return OverviewFilter{}, false
}
filter.Year = year
}
if raw := c.Query("recent_limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return OverviewFilter{}, false
}
if limit > maxRecentLimit {
limit = maxRecentLimit
}
filter.RecentLimit = limit
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}

View File

@@ -0,0 +1,7 @@
package dashboard
import "context"
type Repository interface {
Overview(ctx context.Context, filter OverviewFilter) (OverviewDTO, error)
}

View File

@@ -2,9 +2,16 @@ package handlermanager
import (
"net/http"
"path/filepath"
"online-back/internal/backup"
backupdb "online-back/internal/backup/db"
"online-back/internal/cards"
"online-back/internal/config"
"online-back/internal/currency"
currencydb "online-back/internal/currency/db"
"online-back/internal/dashboard"
dashboarddb "online-back/internal/dashboard/db"
"online-back/internal/identity"
"online-back/internal/identity/activitylog"
activitylogdb "online-back/internal/identity/activitylog/db"
@@ -48,7 +55,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
"Authorization",
"Cache-Control",
},
ExposeHeaders: []string{"Content-Length"},
ExposeHeaders: []string{"Content-Length", "Content-Disposition"},
}))
adminGroup := router.Group(adminAPIPrefix)
@@ -61,6 +68,17 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin.
org.Register(adminGroup, client, logger)
lending.Register(adminGroup, client, logger)
cards.Register(adminGroup, client, logger)
currency.NewHandler(logger, currencydb.NewRepository(client, logger)).Register(adminGroup)
dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger)).Register(adminGroup)
backupDir := filepath.Join(cfg.PublicFilePath, "backups")
backupSvc := backup.NewService(
backupdb.NewRepository(client, logger),
backup.NewPgDumper(cfg.Storage),
backupDir,
logger,
)
backup.NewHandler(logger, backupSvc).Register(adminGroup)
return router
}

View File

@@ -0,0 +1,70 @@
package db
import (
"context"
"errors"
"online-back/internal/identity/permissionuser"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) permissionuser.Repository {
return &repository{client: client, logger: logger}
}
func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
query := `
WITH upserted AS (
INSERT INTO permission_user (permission_id, user_id, effect)
VALUES ($1, $2, $3)
ON CONFLICT (permission_id, user_id) DO UPDATE SET
effect = EXCLUDED.effect,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
RETURNING id, permission_id, user_id, effect, created_at, updated_at
)
SELECT upserted.id, upserted.permission_id, p.name, upserted.user_id, u.name, upserted.effect, upserted.created_at, upserted.updated_at
FROM upserted
JOIN permissions p ON p.id = upserted.permission_id
JOIN users u ON u.id = upserted.user_id`
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId, dto.Effect)
return scanPermissionUser(row)
}
func (r *repository) Delete(ctx context.Context, id int64) error {
tag, err := r.client.Exec(ctx, `DELETE FROM permission_user WHERE id = $1`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return pgx.ErrNoRows
}
return nil
}
type scannable interface {
Scan(dest ...interface{}) error
}
func scanPermissionUser(row scannable) (permissionuser.PermissionUserDTO, error) {
var item permissionuser.PermissionUserDTO
err := row.Scan(
&item.Id, &item.PermissionId, &item.PermissionName, &item.UserId, &item.UserName, &item.Effect, &item.CreatedAt, &item.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return permissionuser.PermissionUserDTO{}, err
}
if err != nil {
return permissionuser.PermissionUserDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,20 @@
package permissionuser
import "time"
type PermissionUserDTO struct {
Id int64 `json:"id"`
UserId int64 `json:"userId"`
UserName string `json:"userName"`
PermissionId int64 `json:"permissionId"`
PermissionName string `json:"permissionName"`
Effect string `json:"effect"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreatePermissionUserDTO struct {
PermissionId int64 `json:"permissionId" binding:"required"`
UserId int64 `json:"userId" binding:"required"`
Effect string `json:"effect" binding:"required,oneof=allow deny"`
}

View File

@@ -0,0 +1,99 @@
package permissionuser
import (
"errors"
"net/http"
"strconv"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/permission-users"
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.POST("", h.create)
group.DELETE("/:id", h.delete)
}
// create godoc
// @Summary Assign a permission override to a user
// @Description Grants ("allow") or revokes ("deny") a permission for a specific user on top of their role, or updates the effect if the pair is already assigned
// @Tags permission-users
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreatePermissionUserDTO true "Permission-user payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-users [post]
func (h *handler) create(c *gin.Context) {
var dto CreatePermissionUserDTO
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 permission user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Remove a user's permission override
// @Description Deletes a permission-user assignment, falling back to the user's role for that permission
// @Tags permission-users
// @Produce json
// @Security BearerAuth
// @Param id path int true "Permission-user ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /permission-users/{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 permission user failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("permission user 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
}

View File

@@ -0,0 +1,8 @@
package permissionuser
import "context"
type Repository interface {
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
Delete(ctx context.Context, id int64) error
}

View File

@@ -16,13 +16,17 @@ import (
)
const (
roleUser = "user"
roleOperator = "operator"
adminPrefix = "/api/admin"
contextRole = "role"
roleUser = "user"
roleOperator = "operator"
guardWeb = "web"
guardOperator = "operator"
guardAdmin = "admin"
adminPrefix = "/api/admin"
contextRole = "role"
contextGuard = "guard"
)
func RequirePermission(service *Service, code string) gin.HandlerFunc {
func RequirePermission(service Authorizer, code string) gin.HandlerFunc {
return func(c *gin.Context) {
rawID, exists := c.Get("id")
if !exists {
@@ -46,7 +50,7 @@ func RequirePermission(service *Service, code string) gin.HandlerFunc {
}
}
func Guard(service *Service) gin.HandlerFunc {
func Guard(service Authorizer) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodOptions || isPublicAdminPath(c.Request.URL.Path) {
c.Next()
@@ -59,26 +63,34 @@ func Guard(service *Service) gin.HandlerFunc {
return
}
code, err := service.RoleCode(c.Request.Context(), userID)
code, guardName, err := service.RoleLookup(c.Request.Context(), userID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
guard := effectiveGuard(code, guardName)
c.Set("id", strconv.FormatInt(userID, 10))
c.Set(contextRole, code)
c.Set(contextGuard, guard)
c.Set(contextService, service)
switch code {
case roleOperator:
switch guard {
case guardOperator:
enforceOperator(c, service, userID)
return
case roleUser, "":
case guardWeb:
if code == "" {
c.Set(contextRole, roleUser)
}
if !userRoleAllows(c.Request.Method, c.Request.URL.Path) {
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
scopeOwnedLists(c, userID)
if !enforceOwnWrites(c, userID) {
return
}
c.Next()
return
default:
@@ -88,7 +100,7 @@ func Guard(service *Service) gin.HandlerFunc {
}
}
func enforceOperator(c *gin.Context, service *Service, userID int64) {
func enforceOperator(c *gin.Context, service Authorizer, userID int64) {
ids, err := service.BranchIDs(c.Request.Context(), userID)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
@@ -113,6 +125,28 @@ func enforceOperator(c *gin.Context, service *Service, userID int64) {
c.Next()
}
func effectiveGuard(code, guardName string) string {
code = strings.ToLower(strings.TrimSpace(code))
guard := strings.ToLower(strings.TrimSpace(guardName))
switch code {
case "admin", "superadmin", "manager":
return guardAdmin
case roleOperator:
return guardOperator
}
switch guard {
case guardWeb, guardOperator, guardAdmin:
return guard
}
if code == roleUser || code == "" {
return guardWeb
}
return guardAdmin
}
func isPublicAdminPath(path string) bool {
switch strings.TrimSuffix(path, "/") {
case adminPrefix + "/login",
@@ -128,19 +162,31 @@ func isPublicAdminPath(path string) bool {
}
func userRoleAllows(method, path string) bool {
if method != http.MethodGet {
return false
}
rest := strings.TrimSuffix(strings.TrimPrefix(path, adminPrefix), "/")
rest := adminREST(path)
if rest == "" {
return false
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
for _, prefix := range userRolePrefixes {
if matchesPrefix(rest, userCatalogPrefixes) {
return method == http.MethodGet
}
if matchesPrefix(rest, userSelfPrefixes) {
if rest == "/profile" || strings.HasPrefix(rest, "/profile/") {
return method == http.MethodGet || method == http.MethodPut || method == http.MethodPatch
}
return method == http.MethodGet || method == http.MethodPost
}
if matchesPrefix(rest, userOwnedPrefixes) {
switch method {
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
return true
}
}
return false
}
func matchesPrefix(rest string, prefixes []string) bool {
for _, prefix := range prefixes {
if rest == prefix || strings.HasPrefix(rest, prefix+"/") {
return true
}
@@ -148,6 +194,41 @@ func userRoleAllows(method, path string) bool {
return false
}
func enforceOwnWrites(c *gin.Context, userID int64) bool {
if !matchesPrefix(adminREST(c.Request.URL.Path), userOwnedPrefixes) {
return true
}
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
return true
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
return false
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
if len(bytes.TrimSpace(body)) == 0 {
return true
}
var payload map[string]interface{}
if err := json.Unmarshal(body, &payload); err != nil {
return true
}
payload["userId"] = userID
payload["user_id"] = userID
rewritten, err := json.Marshal(payload)
if err != nil {
return true
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(rewritten))
c.Request.ContentLength = int64(len(rewritten))
return true
}
func scopeOwnedLists(c *gin.Context, userID int64) {
rest := strings.TrimSuffix(strings.TrimPrefix(c.Request.URL.Path, adminPrefix), "/")
if rest == "" {
@@ -232,27 +313,28 @@ func bearerToken(header string) string {
return strings.TrimSpace(header)
}
var userRolePrefixes = []string{
"/profile",
"/cards",
"/card-orders",
"/card-pin-orders",
var userCatalogPrefixes = []string{
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
"/loan-orders",
"/loan-types",
"/loans-documents",
"/loans-repayment",
"/loan-paid-off-letters",
"/currencies",
}
var userSelfPrefixes = []string{
"/profile",
"/file",
}
var userOwnedPrefixes = []string{
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/loan-orders",
"/loans-repayment",
"/loan-paid-off-letters",
}
func operatorRoleAllows(method, path string) bool {
@@ -280,7 +362,7 @@ func operatorProfileOrFile(path string) bool {
return rest == "/profile" || rest == "/file" || strings.HasPrefix(rest, "/file/")
}
func operatorWriteAllowed(c *gin.Context, service *Service, branchIDs []int64) bool {
func operatorWriteAllowed(c *gin.Context, service Authorizer, branchIDs []int64) bool {
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
@@ -345,6 +427,7 @@ var operatorWritePrefixes = []string{
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/visa-master-payment-orders",
"/loan-orders",
"/loans-repayment",
@@ -354,10 +437,12 @@ var operatorWritePrefixes = []string{
var operatorGetPrefixes = []string{
"/profile",
"/file",
"/dashboard",
"/users",
"/cards",
"/card-orders",
"/card-pin-orders",
"/card-rekwizit-orders",
"/payment-cards",
"/reasons-cards",
"/visa-master-payment-orders",
@@ -368,4 +453,5 @@ var operatorGetPrefixes = []string{
"/loan-paid-off-letters",
"/provinces",
"/branches",
"/currencies",
}

View File

@@ -0,0 +1,599 @@
package rbac
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
func TestUserRoleAllows(t *testing.T) {
tests := []struct {
method, path string
want bool
}{
{http.MethodGet, "/api/admin/currencies", true},
{http.MethodGet, "/api/admin/currencies/3", true},
{http.MethodPost, "/api/admin/currencies", false},
{http.MethodPut, "/api/admin/currencies/3", false},
{http.MethodDelete, "/api/admin/currencies/3", false},
{http.MethodGet, "/api/admin/backups", false},
{http.MethodGet, "/api/admin/backups/1", false},
{http.MethodPost, "/api/admin/backups", false},
{http.MethodGet, "/api/admin/cards", true},
{http.MethodPost, "/api/admin/cards", true},
{http.MethodPut, "/api/admin/cards/9", true},
{http.MethodDelete, "/api/admin/cards/9", true},
{http.MethodGet, "/api/admin/card-orders/9", true},
{http.MethodPost, "/api/admin/card-orders", true},
{http.MethodPut, "/api/admin/loan-orders/2", true},
{http.MethodDelete, "/api/admin/loan-orders/2", true},
{http.MethodGet, "/api/admin/card-balances", false},
{http.MethodGet, "/api/admin/profile", true},
{http.MethodPut, "/api/admin/profile", true},
{http.MethodPost, "/api/admin/file", true},
{http.MethodDelete, "/api/admin/profile", false},
{http.MethodGet, "/api/admin/users", false},
{http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/loan-types", true},
{http.MethodPost, "/api/admin/loan-types", false},
{http.MethodPost, "/api/admin/loan-orders", true},
{http.MethodGet, "/api/admin/loans-repayment", true},
{http.MethodPost, "/api/admin/loans-repayment", true},
{http.MethodDelete, "/api/admin/loan-paid-off-letters/4", true},
{http.MethodPatch, "/api/admin/cards/9", true},
}
for _, tt := range tests {
if got := userRoleAllows(tt.method, tt.path); got != tt.want {
t.Errorf("userRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
}
}
}
func TestOperatorRoleAllows(t *testing.T) {
tests := []struct {
method, path string
want bool
}{
{http.MethodGet, "/api/admin/currencies", true},
{http.MethodGet, "/api/admin/currencies/1", true},
{http.MethodPost, "/api/admin/currencies", false},
{http.MethodPut, "/api/admin/currencies/1", false},
{http.MethodDelete, "/api/admin/currencies/1", false},
{http.MethodGet, "/api/admin/backups", false},
{http.MethodPost, "/api/admin/backups", false},
{http.MethodGet, "/api/admin/card-orders", true},
{http.MethodPost, "/api/admin/card-orders", true},
{http.MethodDelete, "/api/admin/card-orders/2", true},
{http.MethodGet, "/api/admin/dashboard", true},
{http.MethodGet, "/api/admin/users", true},
{http.MethodPost, "/api/admin/users", true},
{http.MethodGet, "/api/admin/activity-logs", false},
{http.MethodGet, "/api/admin/provinces", true},
{http.MethodPost, "/api/admin/provinces", false},
{http.MethodGet, "/api/admin/card-balances", false},
}
for _, tt := range tests {
if got := operatorRoleAllows(tt.method, tt.path); got != tt.want {
t.Errorf("operatorRoleAllows(%s %s) = %v, want %v", tt.method, tt.path, got, tt.want)
}
}
}
func TestUserPrefixDoesNotBleedIntoOtherModules(t *testing.T) {
if userRoleAllows(http.MethodGet, "/api/admin/card-balances") {
t.Fatal("/cards must not grant /card-balances")
}
if operatorRoleAllows(http.MethodGet, "/api/admin/card-balances") {
t.Fatal("operator /cards must not grant /card-balances")
}
}
func TestIsPublicAdminPath(t *testing.T) {
public := []string{
"/api/admin/login",
"/api/admin/token",
"/api/admin/register",
"/api/admin/register/verify",
"/api/admin/forgot-password",
"/api/admin/forgot-password/verify",
"/api/admin/login/",
}
for _, path := range public {
if !isPublicAdminPath(path) {
t.Errorf("expected public %s", path)
}
}
private := []string{"/api/admin/currencies", "/api/admin/backups", "/api/admin/users"}
for _, path := range private {
if isPublicAdminPath(path) {
t.Errorf("expected private %s", path)
}
}
}
func TestAdminREST(t *testing.T) {
if got := adminREST("/api/admin/currencies/4"); got != "/currencies/4" {
t.Fatalf("got %q", got)
}
if got := adminREST("/api/admin/currencies/"); got != "/currencies" {
t.Fatalf("got %q", got)
}
if got := adminREST("/api/admin"); got != "" {
t.Fatalf("got %q", got)
}
}
func TestScopeOwnedListsInjectsUserID(t *testing.T) {
gin.SetMode(gin.TestMode)
paths := []string{
"/api/admin/cards?page=1",
"/api/admin/loan-orders",
"/api/admin/loans-repayment",
"/api/admin/loan-paid-off-letters",
}
for _, path := range paths {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, path, nil)
scopeOwnedLists(c, 42)
if got := c.Request.URL.Query().Get("user_id"); got != "42" {
t.Errorf("%s user_id=%q", path, got)
}
}
}
func TestScopeOwnedListsSkipsReferenceData(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/currencies", nil)
scopeOwnedLists(c, 42)
if got := c.Request.URL.Query().Get("user_id"); got != "" {
t.Fatalf("currencies must not be scoped by user_id, got %q", got)
}
}
func TestGuardMatrix(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
role string
branches []int64
method string
path string
want int
}{
{"user GET currencies", roleUser, nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"user POST currencies", roleUser, nil, http.MethodPost, "/api/admin/currencies", http.StatusForbidden},
{"user GET backups", roleUser, nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
{"user GET cards", roleUser, nil, http.MethodGet, "/api/admin/cards", http.StatusOK},
{"user POST cards", roleUser, nil, http.MethodPost, "/api/admin/cards", http.StatusOK},
{"user PUT card-orders", roleUser, nil, http.MethodPut, "/api/admin/card-orders/3", http.StatusOK},
{"user DELETE loan-orders", roleUser, nil, http.MethodDelete, "/api/admin/loan-orders/3", http.StatusOK},
{"user PATCH cards", roleUser, nil, http.MethodPatch, "/api/admin/cards/3", http.StatusOK},
{"user POST loans-repayment", roleUser, nil, http.MethodPost, "/api/admin/loans-repayment", http.StatusOK},
{"user PUT profile", roleUser, nil, http.MethodPut, "/api/admin/profile", http.StatusOK},
{"user POST file", roleUser, nil, http.MethodPost, "/api/admin/file", http.StatusOK},
{"user GET users", roleUser, nil, http.MethodGet, "/api/admin/users", http.StatusForbidden},
{"no-role GET currencies", "", nil, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"no-role GET backups", "", nil, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
{"operator GET currencies", roleOperator, []int64{1}, http.MethodGet, "/api/admin/currencies", http.StatusOK},
{"operator POST currencies", roleOperator, []int64{1}, http.MethodPost, "/api/admin/currencies", http.StatusForbidden},
{"operator GET backups", roleOperator, []int64{1}, http.MethodGet, "/api/admin/backups", http.StatusForbidden},
{"operator GET card-orders", roleOperator, []int64{1}, http.MethodGet, "/api/admin/card-orders", http.StatusOK},
{"operator POST card-orders", roleOperator, []int64{1}, http.MethodPost, "/api/admin/card-orders", http.StatusOK},
{"operator no branch GET currencies", roleOperator, nil, http.MethodGet, "/api/admin/currencies", http.StatusForbidden},
{"operator no branch GET profile", roleOperator, nil, http.MethodGet, "/api/admin/profile", http.StatusOK},
{"admin GET backups", "admin", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
{"admin POST currencies", "admin", nil, http.MethodPost, "/api/admin/currencies", http.StatusOK},
{"superadmin DELETE backups", "superadmin", nil, http.MethodDelete, "/api/admin/backups/1", http.StatusOK},
{"manager GET backups", "manager", nil, http.MethodGet, "/api/admin/backups", http.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status := serveGuard(&stubAuth{role: tt.role, branches: tt.branches}, tt.method, tt.path, "7", nil)
if status != tt.want {
t.Fatalf("status=%d want=%d", status, tt.want)
}
})
}
if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodPost, "/api/admin/cards", "7", nil); status != http.StatusOK {
t.Fatalf("web guard custom role status=%d", status)
}
if status := serveGuard(&stubAuth{role: "customer", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
t.Fatalf("web guard backups status=%d", status)
}
if status := serveGuard(&stubAuth{role: "teller", guard: guardOperator, branches: []int64{1}}, http.MethodPost, "/api/admin/card-orders", "7", nil); status != http.StatusOK {
t.Fatalf("operator guard custom role status=%d", status)
}
if status := serveGuard(&stubAuth{role: "auditor", guard: guardAdmin}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
t.Fatalf("admin guard custom role status=%d", status)
}
if status := serveGuard(&stubAuth{role: roleOperator, guard: guardAdmin, branches: []int64{1}}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusForbidden {
t.Fatalf("legacy operator+admin guard must stay operator, status=%d", status)
}
if status := serveGuard(&stubAuth{role: "superadmin", guard: guardWeb}, http.MethodGet, "/api/admin/backups", "7", nil); status != http.StatusOK {
t.Fatalf("superadmin code must stay admin even if guard is web, status=%d", status)
}
}
func TestGuardOptionsAndPublicSkipAuthz(t *testing.T) {
gin.SetMode(gin.TestMode)
auth := &stubAuth{role: roleUser}
if status := serveGuard(auth, http.MethodOptions, "/api/admin/backups", "7", nil); status != http.StatusOK {
t.Fatalf("OPTIONS status=%d", status)
}
if status := serveGuard(auth, http.MethodGet, "/api/admin/login", "7", nil); status != http.StatusOK {
t.Fatalf("public login status=%d", status)
}
}
func TestGuardWithoutUserPassesThrough(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(Guard(&stubAuth{role: roleUser}))
r.GET("/api/admin/backups", func(c *gin.Context) { c.Status(http.StatusOK) })
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/admin/backups", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d", w.Code)
}
}
func TestGuardRoleLookupError(t *testing.T) {
gin.SetMode(gin.TestMode)
status := serveGuard(&stubAuth{roleErr: errors.New("db down")}, http.MethodGet, "/api/admin/currencies", "7", nil)
if status != http.StatusInternalServerError {
t.Fatalf("status=%d", status)
}
}
func TestOperatorWriteAllowedBranchScope(t *testing.T) {
gin.SetMode(gin.TestMode)
auth := &stubAuth{role: roleOperator, branches: []int64{1, 2}, visible: true}
allowed := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":1}`))
if allowed != http.StatusOK {
t.Fatalf("own branch status=%d", allowed)
}
denied := serveGuard(auth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"branchId":99}`))
if denied != http.StatusForbidden {
t.Fatalf("foreign branch status=%d", denied)
}
}
func TestOperatorWriteAllowedUserVisibility(t *testing.T) {
gin.SetMode(gin.TestMode)
okAuth := &stubAuth{role: roleOperator, branches: []int64{1}, visible: true}
if status := serveGuard(okAuth, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusOK {
t.Fatalf("visible user status=%d", status)
}
hidden := &stubAuth{role: roleOperator, branches: []int64{1}, visible: false}
if status := serveGuard(hidden, http.MethodPost, "/api/admin/card-orders", "7", []byte(`{"userId":15}`)); status != http.StatusForbidden {
t.Fatalf("hidden user status=%d", status)
}
}
func TestRequirePermission(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", "3")
c.Next()
})
r.GET("/x", RequirePermission(&stubAuth{perms: map[string]bool{"currencies.view": true}}, "currencies.view"), okHandler)
r.POST("/x", RequirePermission(&stubAuth{perms: map[string]bool{}}, "currencies.manage"), okHandler)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/x", nil))
if w.Code != http.StatusOK {
t.Fatalf("granted status=%d", w.Code)
}
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/x", nil))
if w.Code != http.StatusForbidden {
t.Fatalf("denied status=%d", w.Code)
}
}
func TestAllowsBranchAndGuardUser(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if !AllowsBranch(c, 1) {
t.Fatal("no scope should allow any branch")
}
if !GuardUser(c, 9) {
t.Fatal("no scope should allow any user")
}
c.Set(contextBranchIDs, []int64{1, 2})
if !AllowsBranch(c, 2) {
t.Fatal("expected branch 2 allowed")
}
if AllowsBranch(c, 9) {
t.Fatal("expected branch 9 denied")
}
c.Set(contextService, &stubAuth{visible: true})
if !GuardUser(c, 15) {
t.Fatal("expected visible user allowed")
}
c.Set(contextService, &stubAuth{visible: false})
if GuardUser(c, 15) {
t.Fatal("expected hidden user denied")
}
}
func TestBindBranchIDs(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
var dest []int64
BindBranchIDs(c, &dest)
if dest != nil {
t.Fatalf("expected empty dest, got %v", dest)
}
c.Set(contextBranchIDs, []int64{4, 5})
BindBranchIDs(c, &dest)
if len(dest) != 2 || dest[0] != 4 {
t.Fatalf("dest=%v", dest)
}
}
func TestClaimAndContextUserID(t *testing.T) {
if id, ok := claimUserID(jwt.MapClaims{"id": float64(12)}); !ok || id != 12 {
t.Fatalf("float id=%d ok=%v", id, ok)
}
if id, ok := claimUserID(jwt.MapClaims{"id": "8"}); !ok || id != 8 {
t.Fatalf("string id=%d ok=%v", id, ok)
}
if _, ok := claimUserID(jwt.MapClaims{"id": 0}); ok {
t.Fatal("zero id should fail")
}
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set("id", "21")
if id, ok := parseContextUserID(c); !ok || id != 21 {
t.Fatalf("context id=%d ok=%v", id, ok)
}
}
func TestBearerToken(t *testing.T) {
if got := bearerToken("Bearer abc"); got != "abc" {
t.Fatalf("got %q", got)
}
if got := bearerToken("abc"); got != "abc" {
t.Fatalf("got %q", got)
}
}
func TestUserInBranchSQLIncludesNewOrderTables(t *testing.T) {
sql := UserInBranchSQL("c.user_id", 3)
for _, table := range []string{
"branch_user", "card_orders", "loan_orders", "card_pin_orders",
"card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters",
} {
if !strings.Contains(sql, table) {
t.Errorf("missing %s", table)
}
}
if strings.Count(sql, "$3") != 7 {
t.Fatalf("$3 count=%d", strings.Count(sql, "$3"))
}
}
func serveGuard(auth Authorizer, method, path, userID string, body []byte) int {
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", userID)
c.Next()
})
r.Use(Guard(auth))
handler := func(c *gin.Context) { c.Status(http.StatusOK) }
r.GET("/api/admin/*rest", handler)
r.POST("/api/admin/*rest", handler)
r.PUT("/api/admin/*rest", handler)
r.PATCH("/api/admin/*rest", handler)
r.DELETE("/api/admin/*rest", handler)
r.OPTIONS("/api/admin/*rest", handler)
var req *http.Request
if body != nil {
req = httptest.NewRequest(method, path, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
} else {
req = httptest.NewRequest(method, path, nil)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w.Code
}
func okHandler(c *gin.Context) { c.Status(http.StatusOK) }
type stubAuth struct {
role string
guard string
roleErr error
branches []int64
visible bool
visibleErr error
perms map[string]bool
}
func (s *stubAuth) RoleLookup(context.Context, int64) (string, string, error) {
return s.role, s.guard, s.roleErr
}
func (s *stubAuth) BranchIDs(context.Context, int64) ([]int64, error) {
return s.branches, nil
}
func (s *stubAuth) HasPermission(_ context.Context, _ int64, code string) (bool, error) {
return s.perms[code], nil
}
func (s *stubAuth) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) {
return s.visible, s.visibleErr
}
var _ Authorizer = (*stubAuth)(nil)
var _ Authorizer = (*Service)(nil)
func TestEffectiveGuard(t *testing.T) {
tests := []struct {
code, guard, want string
}{
{roleUser, guardWeb, guardWeb},
{roleOperator, guardOperator, guardOperator},
{"admin", guardAdmin, guardAdmin},
{"customer", guardWeb, guardWeb},
{"teller", guardOperator, guardOperator},
{"auditor", guardAdmin, guardAdmin},
{roleUser, "", guardWeb},
{roleOperator, "", guardOperator},
{"admin", "", guardAdmin},
{"", "", guardWeb},
{roleOperator, guardAdmin, guardOperator},
{roleOperator, guardWeb, guardOperator},
{"superadmin", guardWeb, guardAdmin},
{"admin", guardWeb, guardAdmin},
{"manager", guardOperator, guardAdmin},
}
for _, tt := range tests {
if got := effectiveGuard(tt.code, tt.guard); got != tt.want {
t.Errorf("effectiveGuard(%q, %q)=%q want %q", tt.code, tt.guard, got, tt.want)
}
}
}
func TestContainsInt64(t *testing.T) {
if !containsInt64([]int64{1, 2, 3}, 2) {
t.Fatal("expected 2")
}
if containsInt64([]int64{1, 2, 3}, 9) {
t.Fatal("did not expect 9")
}
}
func TestHasBranchScope(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if HasBranchScope(c) {
t.Fatal("expected no scope")
}
c.Set(contextBranchIDs, []int64{1})
if !HasBranchScope(c) {
t.Fatal("expected scope")
}
}
func TestEnforceOwnWritesRewritesUserID(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("id", "7")
c.Next()
})
r.Use(Guard(&stubAuth{role: roleUser}))
r.POST("/api/admin/cards", func(c *gin.Context) {
body, _ := io.ReadAll(c.Request.Body)
c.String(http.StatusOK, string(body))
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/admin/cards", bytes.NewReader([]byte(`{"userId":99,"number":"1"}`)))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d", w.Code)
}
if !strings.Contains(w.Body.String(), `"userId":7`) {
t.Fatalf("userId not rewritten: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), `"user_id":7`) {
t.Fatalf("user_id not rewritten: %s", w.Body.String())
}
}
func TestGuardOwnedOwnScope(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Set(contextRole, roleUser)
c.Set(contextGuard, guardWeb)
c.Set("id", "7")
own := int64(7)
if !GuardOwned(c, &own) {
t.Fatal("own record should pass")
}
other := int64(9)
if GuardOwned(c, &other) {
t.Fatal("foreign record should fail")
}
if GuardOwned(c, nil) {
t.Fatal("nil owner should fail")
}
if GuardUser(c, 9) {
t.Fatal("GuardUser should deny other users")
}
if !GuardUser(c, 7) {
t.Fatal("GuardUser should allow current user")
}
}
func TestSkipRecordGuard(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
if !SkipRecordGuard(c) {
t.Fatal("admin with no role/branches should skip")
}
c.Set(contextRole, roleUser)
c.Set(contextGuard, guardWeb)
if SkipRecordGuard(c) {
t.Fatal("user must not skip record guard")
}
c.Set(contextRole, roleOperator)
c.Set(contextGuard, guardOperator)
c.Set(contextBranchIDs, []int64{1})
if SkipRecordGuard(c) {
t.Fatal("operator with branches must not skip")
}
}

View File

@@ -27,6 +27,49 @@ func HasBranchScope(c *gin.Context) bool {
return len(BranchIDsFrom(c)) > 0
}
func RoleFrom(c *gin.Context) string {
raw, _ := c.Get(contextRole)
role, _ := raw.(string)
return role
}
func GuardFrom(c *gin.Context) string {
raw, _ := c.Get(contextGuard)
guard, _ := raw.(string)
return guard
}
func IsOwnScope(c *gin.Context) bool {
return GuardFrom(c) == guardWeb
}
func SkipRecordGuard(c *gin.Context) bool {
return !HasBranchScope(c) && !IsOwnScope(c)
}
func CurrentUserID(c *gin.Context) (int64, bool) {
return parseContextUserID(c)
}
func GuardOwned(c *gin.Context, ownerID *int64) bool {
if !IsOwnScope(c) {
return true
}
current, ok := CurrentUserID(c)
if !ok || ownerID == nil || *ownerID != current {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
return true
}
func GuardOrder(c *gin.Context, ownerID *int64, branchID int64) bool {
if IsOwnScope(c) {
return GuardOwned(c, ownerID)
}
return GuardBranch(c, branchID)
}
func AllowsBranch(c *gin.Context, branchID int64) bool {
ids := BranchIDsFrom(c)
if len(ids) == 0 {
@@ -52,6 +95,10 @@ func GuardBranch(c *gin.Context, branchID int64) bool {
}
func GuardUser(c *gin.Context, userID int64) bool {
if IsOwnScope(c) {
id := userID
return GuardOwned(c, &id)
}
ids := BranchIDsFrom(c)
if len(ids) == 0 {
return true
@@ -61,7 +108,7 @@ func GuardUser(c *gin.Context, userID int64) bool {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
}
service, _ := raw.(*Service)
service, _ := raw.(Authorizer)
if service == nil {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return false
@@ -89,9 +136,10 @@ func UserInBranchSQL(userExpr string, placeholder int) string {
OR EXISTS (SELECT 1 FROM card_orders co WHERE co.user_id = %s AND co.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_orders lo WHERE lo.user_id = %s AND lo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM card_pin_orders cpo WHERE cpo.user_id = %s AND cpo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM card_rekwizit_orders cro WHERE cro.user_id = %s AND cro.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM visa_master_payment_orders vmo WHERE vmo.user_id = %s AND vmo.branch_id = ANY($%d))
OR EXISTS (SELECT 1 FROM loan_paid_off_letters lpl WHERE lpl.user_id = %s AND lpl.branch_id = ANY($%d))
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
)`, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder, userExpr, placeholder)
}
func containsInt64(ids []int64, want int64) bool {

View File

@@ -17,15 +17,40 @@ func NewService(client postgresql.Client) *Service {
return &Service{client: client}
}
// Authorizer is the lookup Guard, RequirePermission and GuardUser need.
type Authorizer interface {
RoleLookup(ctx context.Context, userID int64) (code, guardName string, err error)
BranchIDs(ctx context.Context, userID int64) ([]int64, error)
HasPermission(ctx context.Context, userID int64, code string) (bool, error)
UserVisibleInBranches(ctx context.Context, userID int64, branchIDs []int64) (bool, error)
}
// HasPermission checks the role's baseline grant, then lets a per-user
// permission_user override win: an explicit "deny" always wins (even over
// another allow), an explicit "allow" grants a permission the role does
// not, and no override falls back to the role.
func (s *Service) HasPermission(ctx context.Context, userID int64, code string) (bool, error) {
const query = `
SELECT EXISTS (
SELECT 1
FROM role_user ru
JOIN permission_role pr ON pr.role_id = ru.role_id
JOIN permissions p ON p.id = pr.permission_id
WHERE ru.user_id = $1 AND p.code = $2
)`
SELECT
CASE
WHEN EXISTS (
SELECT 1 FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'deny'
) THEN false
WHEN EXISTS (
SELECT 1 FROM permission_user pu
JOIN permissions p ON p.id = pu.permission_id
WHERE pu.user_id = $1 AND p.code = $2 AND pu.effect = 'allow'
) THEN true
ELSE EXISTS (
SELECT 1
FROM role_user ru
JOIN permission_role pr ON pr.role_id = ru.role_id
JOIN permissions p ON p.id = pr.permission_id
WHERE ru.user_id = $1 AND p.code = $2
)
END`
var granted bool
if err := s.client.QueryRow(ctx, query, userID, code).Scan(&granted); err != nil {
@@ -34,21 +59,21 @@ func (s *Service) HasPermission(ctx context.Context, userID int64, code string)
return granted, nil
}
func (s *Service) RoleCode(ctx context.Context, userID int64) (string, error) {
func (s *Service) RoleLookup(ctx context.Context, userID int64) (string, string, error) {
const query = `
SELECT r.code
SELECT r.code, r.guard_name
FROM role_user ru
JOIN roles r ON r.id = ru.role_id
WHERE ru.user_id = $1
ORDER BY ru.id
LIMIT 1`
var code string
err := s.client.QueryRow(ctx, query, userID).Scan(&code)
var code, guardName string
err := s.client.QueryRow(ctx, query, userID).Scan(&code, &guardName)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
return "", "", nil
}
return code, err
return code, guardName, err
}
func (s *Service) BranchIDs(ctx context.Context, userID int64) ([]int64, error) {

View File

@@ -10,6 +10,8 @@ import (
permissiondb "online-back/internal/identity/permission/db"
"online-back/internal/identity/permissionrole"
permissionroledb "online-back/internal/identity/permissionrole/db"
"online-back/internal/identity/permissionuser"
permissionuserdb "online-back/internal/identity/permissionuser/db"
"online-back/internal/identity/role"
roledb "online-back/internal/identity/role/db"
"online-back/internal/identity/roleusers"
@@ -43,6 +45,7 @@ func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handl
permission.NewHandler(logger, permissiondb.NewRepository(client, logger)),
roleusers.NewHandler(logger, roleusersdb.NewRepository(client, logger)),
permissionrole.NewHandler(logger, permissionroledb.NewRepository(client, logger)),
permissionuser.NewHandler(logger, permissionuserdb.NewRepository(client, logger)),
userbranch.NewHandler(logger, userbranchdb.NewRepository(client, logger)),
}
}

View File

@@ -1,64 +0,0 @@
package loanorders_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"online-back/internal/lending/loanorders"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
func mobileCreateBody() []byte {
body, _ := json.Marshal(map[string]any{
"source": "mobile", "loanType": "1", "region": "Ahal", "branchId": "1",
"customerName": "Kerim", "customerSurname": "Atayew",
"passportAddress": "Ashgabat", "realAddress": "Ashgabat",
"passportSerie": "I-AG", "passportId": "101010",
"passportGivenAt": "2017-01-15", "passportGivenBy": "Police",
"bornPlace": "Ashgabat", "bornAt": "1989-03-21",
"phone": "+993 61 92 92 48", "education": "higher", "marriageStatus": "married",
"passportOne": "a.jpg", "passportTwo": "b.jpg", "passportThree": "c.jpg", "passportFour": "d.jpg",
"satisfiable": "yes", "guarantorNote": "Brother", "loanAmount": "20000",
})
return body
}
func TestCreateLoanOrderDTOBindMobilePayload(t *testing.T) {
var dto loanorders.CreateLoanOrderDTO
if err := json.Unmarshal(mobileCreateBody(), &dto); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if dto.LoanType.Int64() != 1 || dto.BranchId.Int64() != 1 {
t.Fatalf("ids: loanType=%d branchId=%d", dto.LoanType.Int64(), dto.BranchId.Int64())
}
if dto.Region != "Ahal" {
t.Fatalf("region=%q", dto.Region)
}
if dto.BornAt.Time().Format("2006-01-02") != "1989-03-21" {
t.Fatalf("bornAt=%v", dto.BornAt.Time())
}
if dto.PassportGivenAt.Time().Format("2006-01-02") != "2017-01-15" {
t.Fatalf("passportGivenAt=%v", dto.PassportGivenAt.Time())
}
}
func TestCreateLoanOrderGinBindRequired(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(mobileCreateBody()))
c.Request.Header.Set("Content-Type", "application/json")
var dto loanorders.CreateLoanOrderDTO
if err := c.ShouldBindBodyWith(&dto, binding.JSON); err != nil {
t.Fatalf("ShouldBindJSON: %v", err)
}
if dto.LoanType.Int64() != 1 || dto.Region != "Ahal" {
t.Fatalf("unexpected dto loanType=%d region=%q", dto.LoanType.Int64(), dto.Region)
}
}

View File

@@ -38,7 +38,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
// list godoc
// @Summary List loan orders
// @Description Returns paginated loan orders with optional filters
// @Description Returns paginated loan orders created from the web with optional filters
// @Tags loan-orders
// @Produce json
// @Security BearerAuth
@@ -58,6 +58,7 @@ func (h *handler) list(c *gin.Context) {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
filter.Source = "web"
h.respondList(c, filter)
}
@@ -127,7 +128,7 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
@@ -324,7 +325,7 @@ func queryValue(c *gin.Context, keys ...string) string {
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
@@ -336,5 +337,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -128,6 +128,11 @@ func buildListQuery(filter loanpaidletter.ListFilter) (whereClause string, args
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 {

View File

@@ -7,32 +7,32 @@ import (
)
type LoanPaidLetterDTO struct {
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Region string `json:"region"`
Id int64 `json:"id"`
UniqueId *string `json:"uniqueId"`
Region string `json:"region"`
RegionName shared.LocalizedText `json:"regionName"`
BranchId int64 `json:"-"`
Branch *shared.BranchInfo `json:"branch,omitempty"`
ProvinceId *int64 `json:"-"`
Province *shared.NamedInfo `json:"province,omitempty"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
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"`
BranchId int64 `json:"-"`
Branch *shared.BranchInfo `json:"branch,omitempty"`
ProvinceId *int64 `json:"-"`
Province *shared.NamedInfo `json:"province,omitempty"`
UserId *int64 `json:"-"`
User *shared.UserInfo `json:"user,omitempty"`
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 {
@@ -81,6 +81,7 @@ type ListFilter struct {
PassportId string
Name string
Status *string
UserId *int64
BranchId *int64
BranchIds []int64
Region string
@@ -95,12 +96,12 @@ type ListLoanPaidLetterDTO struct {
// BranchByProvinceDTO is a compact branch row for province-scoped pickers.
type BranchByProvinceDTO struct {
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Id int64 `json:"id"`
UniqueCode string `json:"uniqueCode"`
Name shared.LocalizedText `json:"name"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
Active bool `json:"active"`
Region string `json:"region"`
ProvinceId *int64 `json:"provinceId"`
Active bool `json:"active"`
}
type ListBranchesByProvinceDTO struct {

View File

@@ -138,7 +138,7 @@ func (h *handler) getByID(c *gin.Context) {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !rbac.GuardBranch(c, item.BranchId) {
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
return
}
@@ -314,12 +314,24 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.BranchId = &id
}
raw := strings.TrimSpace(c.Query("user_id"))
if raw == "" {
raw = strings.TrimSpace(c.Query("userId"))
}
if raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)
@@ -331,5 +343,5 @@ func (h *handler) guardBranchByID(c *gin.Context, id int64) bool {
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return false
}
return rbac.GuardBranch(c, item.BranchId)
return rbac.GuardOrder(c, item.UserId, item.BranchId)
}

View File

@@ -81,6 +81,11 @@ func buildListQuery(filter loansrepayment.ListFilter) (whereClause string, args
conditions = append(conditions, fmt.Sprintf("l.passport_id ILIKE $%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 {
args = append(args, filter.BranchIds)
conditions = append(conditions, rbac.UserInBranchSQL("l.user_id", len(args)))

View File

@@ -33,6 +33,7 @@ type UpdateLoanRepaymentDTO struct {
type ListFilter struct {
PassportId string
UserId *int64
BranchIds []int64
Page int
Limit int

View File

@@ -250,12 +250,24 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter.PassportId = raw
}
raw := strings.TrimSpace(c.Query("user_id"))
if raw == "" {
raw = strings.TrimSpace(c.Query("userId"))
}
if raw != "" {
id, ok := parseID(raw)
if !ok {
return ListFilter{}, false
}
filter.UserId = &id
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
func (h *handler) guardUserByID(c *gin.Context, id int64) bool {
if !rbac.HasBranchScope(c) {
if rbac.SkipRecordGuard(c) {
return true
}
item, err := h.repository.GetByID(c.Request.Context(), id)

View File

@@ -37,7 +37,7 @@ func NewClient(ctx context.Context, maxAttempts int, sc config.StorageConfig) (*
cfg.MaxConns = int32(sc.PgPoolMaxConn)
cfg.HealthCheckPeriod = 2 * time.Second
cfg.MaxConnLifetime = 24 * time.Hour
cfg.MaxConnIdleTime = 2 * time.Second
cfg.MaxConnIdleTime = 30 * time.Minute
cfg.ConnConfig.ConnectTimeout = 1 * time.Second
cfg.ConnConfig.DialFunc = (&net.Dialer{

View File

@@ -35,7 +35,7 @@ func generateTokenPair(id int, admin bool) (map[string]string, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": id,
"admin": admin,
"exp": time.Now().Add(time.Hour).Unix(),
"exp": time.Now().Add(7*24*time.Hour).Unix(),
})
access, err := accessToken.SignedString(secret)

1
public/backups/.gitkeep Normal file
View File

@@ -0,0 +1 @@