Compare commits
66 Commits
514b9ca5fc
...
payment-hi
| Author | SHA1 | Date | |
|---|---|---|---|
| f067872cd7 | |||
| 6dd6110914 | |||
| a3cbb52f4b | |||
| ef3a1baee2 | |||
| ae6bf0b7e3 | |||
| c209f338c2 | |||
| a715cd23ea | |||
| e5f01d0e94 | |||
| 965b00dba5 | |||
| 29867561d1 | |||
| ebedeba009 | |||
| 7e403dab13 | |||
| 60787c8149 | |||
| 3b33e25703 | |||
| 0de3900ed1 | |||
| 94eb2aa4e9 | |||
| 27ad42528c | |||
| 15774d2bc4 | |||
| 69d1495b1f | |||
| a44c10d445 | |||
| 68ead82827 | |||
| 4f3631c70d | |||
| 6f54e9c20b | |||
| 5ab17b1539 | |||
| 19a1f70588 | |||
| 8b73df4435 | |||
| 0058411cdd | |||
| e47e8c24d0 | |||
| c01429d2a4 | |||
| 323e131216 | |||
| f0ecf23879 | |||
| d6a1053003 | |||
| 205aaafc63 | |||
| f2b55f9896 | |||
| ac94e0dd8a | |||
| 235ef5ec9e | |||
| febd190d6e | |||
| 99788a853f | |||
| 23d208769c | |||
| f42ad01828 | |||
| 87e4b33322 | |||
| 45378559ca | |||
| 599c12ef87 | |||
| 6c7c402390 | |||
| 848a07324f | |||
| c6b9cb7462 | |||
| b8455625b5 | |||
| 0971158e98 | |||
| d3e188affe | |||
| e0d03730de | |||
| d1a6fcaadc | |||
| 28509eb4ca | |||
| 0d000f9af6 | |||
| 6683826662 | |||
| 0098422798 | |||
| 1fd0abbcb2 | |||
| 427d5b4e07 | |||
| 8795ae2195 | |||
| 7225dc0399 | |||
| d7cdd53597 | |||
| 2853bed2ec | |||
| 9c07439089 | |||
| 6191b7536c | |||
| 71479f4355 | |||
| fb65d35d3c | |||
| 0788585c0e |
26
.dockerignore
Normal file
26
.dockerignore
Normal file
@@ -0,0 +1,26 @@
|
||||
.git
|
||||
.github
|
||||
.cursor
|
||||
.claude
|
||||
.DS_Store
|
||||
logs
|
||||
tmp
|
||||
temp
|
||||
dist
|
||||
*.md
|
||||
*.log
|
||||
*.tar
|
||||
*.tar.gz
|
||||
coverage.out
|
||||
coverage.html
|
||||
config.yaml
|
||||
config.local.yaml
|
||||
docker-compose.yaml
|
||||
docker-compose.override.yaml
|
||||
docker-compose.override.yml
|
||||
deployment/minio.deb
|
||||
myapp
|
||||
public/images/*
|
||||
!public/images/.gitkeep
|
||||
public/backups/*
|
||||
!public/backups/.gitkeep
|
||||
116
.github/workflows/ci-cd.yml
vendored
Normal file
116
.github/workflows/ci-cd.yml
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
name: CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: cicd-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
name: Vet, test, build
|
||||
runs-on: ubuntu-latest
|
||||
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: Vet
|
||||
run: go vet ./...
|
||||
|
||||
- name: Test
|
||||
run: go test -race -count=1 -shuffle=on ./...
|
||||
|
||||
- name: Build
|
||||
run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o myapp ./app.go
|
||||
|
||||
image:
|
||||
name: Docker image
|
||||
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
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Provide config for image build
|
||||
run: test -f config.yaml || cp config.example.yaml config.yaml
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=sha
|
||||
type=semver,pattern={{version}}
|
||||
type=ref,event=tag
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
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' }}
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@@ -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/
|
||||
@@ -54,6 +57,9 @@ Desktop.ini
|
||||
docker-compose.override.yaml
|
||||
docker-compose.override.yml
|
||||
|
||||
# Local MinIO Ubuntu package (do not commit)
|
||||
deployment/minio.deb
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
@@ -71,3 +77,6 @@ bank_db_schema.drawio
|
||||
# Debug
|
||||
__debug_bin
|
||||
debug
|
||||
|
||||
# Docker image bundles (make docker-bundle)
|
||||
dist/
|
||||
|
||||
41
Dockerfile
41
Dockerfile
@@ -1,30 +1,39 @@
|
||||
#!/bin/ash
|
||||
# Specifies a parent image
|
||||
# Offline build: nothing in this file touches the network.
|
||||
# - Go modules come from the committed vendor/ directory.
|
||||
# - The runtime stage is postgres:14.1-alpine, the same image main-db uses,
|
||||
# so pg_dump (backups), tzdata and CA certificates are already there and no
|
||||
# `apk add` is needed. Its layers are shared with main-db on the server.
|
||||
# The server only needs the base images loaded once (see `make docker-bundle`).
|
||||
#
|
||||
# No "# syntax=" directive on purpose: it makes BuildKit pull a frontend image.
|
||||
|
||||
FROM golang:1.26.4-alpine AS builder
|
||||
|
||||
# Creates an app directory to hold your app’s source code
|
||||
WORKDIR /build
|
||||
|
||||
# Installs Go dependencies
|
||||
COPY go.mod ./
|
||||
COPY go.sum ./
|
||||
RUN go mod download
|
||||
ENV CGO_ENABLED=0 \
|
||||
GOOS=linux \
|
||||
GOARCH=amd64 \
|
||||
GOFLAGS=-mod=vendor \
|
||||
GOPROXY=off
|
||||
|
||||
COPY . .
|
||||
|
||||
# Builds your app with optional configuration
|
||||
RUN GOARCH=amd64 GOOS=linux go build -o myapp ./app.go
|
||||
RUN go build -trimpath -ldflags="-s -w" -o myapp ./app.go
|
||||
|
||||
FROM scratch
|
||||
FROM postgres:14.1-alpine
|
||||
|
||||
WORKDIR /app/
|
||||
# Fresher CA bundle than the 2021 one in postgres:14.1-alpine (HTTPS to mpi.gov.tm).
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /build/myapp .
|
||||
COPY --from=builder /build/config.yaml .
|
||||
|
||||
# Tells Docker which network port your container listens on
|
||||
# config.yaml is mounted at runtime (see docker-compose.yaml), not baked in.
|
||||
RUN mkdir -p /app/public/images /app/public/backups /app/logs
|
||||
|
||||
EXPOSE 5050
|
||||
#ENTRYPOINT ["/app/myapp"]
|
||||
CMD ["/app/myapp"]
|
||||
|
||||
|
||||
# Replaces the postgres docker-entrypoint.sh inherited from the base image.
|
||||
ENTRYPOINT ["/app/myapp"]
|
||||
|
||||
44
Makefile
44
Makefile
@@ -19,3 +19,47 @@ 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)'
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Docker (serwerde internet ýok). Papka serwere göni göçürilýär:
|
||||
# 1) internet bar maşynda: make docker-bundle → dist/ içine ähli image-ler
|
||||
# 2) serwerde: make docker-load (bir gezek, ýa-da täze bundle-da)
|
||||
# docker compose up -d --build (internetsiz build)
|
||||
# ---------------------------------------------------------------------------
|
||||
DOCKER_PLATFORM ?= linux/amd64
|
||||
DOCKER_BASE_IMAGES ?= golang:1.26.4-alpine postgres:14.1-alpine
|
||||
DOCKER_IMAGES ?= main-app:latest main-minio:latest $(DOCKER_BASE_IMAGES)
|
||||
DOCKER_BUNDLE ?= dist/online-back-images.tar.gz
|
||||
|
||||
.PHONY: docker-bundle docker-load
|
||||
|
||||
docker-bundle:
|
||||
for img in $(DOCKER_BASE_IMAGES); do \
|
||||
docker image inspect $$img >/dev/null 2>&1 || docker pull --platform $(DOCKER_PLATFORM) $$img || exit 1; \
|
||||
done
|
||||
DOCKER_DEFAULT_PLATFORM=$(DOCKER_PLATFORM) docker compose build
|
||||
mkdir -p $(dir $(DOCKER_BUNDLE))
|
||||
docker save $(DOCKER_IMAGES) | gzip > $(DOCKER_BUNDLE)
|
||||
|
||||
docker-load:
|
||||
gunzip -c $(DOCKER_BUNDLE) | docker load
|
||||
|
||||
28
README.md
28
README.md
@@ -56,14 +56,21 @@ Additional Swagger endpoints (categories, settings) are documented but not yet i
|
||||
├── config.yaml # Runtime configuration
|
||||
├── docker-compose.yaml # Local development stack
|
||||
├── db/migrations/ # SQL migrations
|
||||
├── db/seed.sql # Consolidated, idempotent seed data
|
||||
├── docs/ # Generated Swagger docs
|
||||
├── internal/
|
||||
│ ├── admin/auth/ # Admin auth handlers & repository
|
||||
│ ├── appresult/ # Response helpers & JWT middleware
|
||||
│ ├── config/ # Config loader
|
||||
│ └── handlers/manager/ # Route registration
|
||||
│ ├── shared/ # Cross-module DTOs, HTTP/SQL/query helpers
|
||||
│ ├── handlers/manager/ # Route registration (composition root)
|
||||
│ ├── identity/ # auth, rbac, permission, role, user, userbranch, activitylog
|
||||
│ ├── cards/ # card orders, balances, PIN orders, rekwizit, etc.
|
||||
│ ├── lending/ # loan orders, repayments, documents, letters, types
|
||||
│ ├── org/ # branches, provinces
|
||||
│ ├── currency/, dashboard/, backup/
|
||||
└── pkg/
|
||||
├── client/postgresql/ # PostgreSQL connection pool
|
||||
├── repository/genericrepo/ # Shared List/GetByID/Delete repository helper
|
||||
├── logging/ # Structured logging
|
||||
└── utils/ # JWT & file utilities
|
||||
```
|
||||
@@ -165,6 +172,23 @@ make migrate-rollback
|
||||
|
||||
Migration files live in `db/migrations/`.
|
||||
|
||||
> **Current practice:** the schema currently lives in a single `db/migrations/20260702125108_init.{up,down}.sql` pair, edited in place as the schema evolves rather than appended to. This means an already-migrated database won't pick up later edits to `init` automatically (`golang-migrate` sees it as already applied) — a fresh `make migrate` against an empty database is the reliable path. Switching to append-only migrations going forward is worth deciding on as a team.
|
||||
|
||||
Seed data (`db/seed.sql`) loads a consolidated, idempotent set of test accounts/roles/branches:
|
||||
|
||||
```bash
|
||||
make seed
|
||||
```
|
||||
|
||||
## Roles & permissions (RBAC)
|
||||
|
||||
- **Permission = module.** One code per module (`cards`, `loans`, `users`, `roles`, `branches`, `provinces`, `currencies`, `payment-settings`, `backups`, `activity-logs`, `dashboard`), defined in `internal/identity/rbac/perm`. Holding it grants read and write in that module. The catalog is synced to the `permissions` table on startup; the API only lets roles pick from it.
|
||||
- **Role = permissions + scope.** `scope` decides whose records: `own` (clients — only their own), `branch` (the user's `branch_user` branches, possibly several), `all` (every branch). E.g. a head of loans is `scope=all` + `loans`. `is_super` roles hold every permission; `is_system` roles (`superadmin`, `user`) cannot be deleted or re-scoped.
|
||||
- **One role per user:** `users.role_id`.
|
||||
- **Every `/api/admin` route declares its policy** with `rbac.Group(router, path, policy)` — `Require(perm.X)`, `RequireStaff`, `Catalog`, `StaffRead`, `Staff`, `Authenticated`, `Public`. Startup fails if a route has none, and an undeclared route is denied at runtime.
|
||||
- **No escalation:** a caller can only create/assign roles within their own scope and permissions, cannot touch superadmin unless superadmin, cannot change their own role, and cannot remove the last superadmin.
|
||||
- Principals are cached per user; DB triggers bump `rbac_version` on role/permission/branch changes, which clears the cache within ~2s.
|
||||
|
||||
## Development
|
||||
|
||||
### Run tests
|
||||
|
||||
@@ -235,7 +235,7 @@ Admin users for the back-office panel.
|
||||
| avatar | varchar(250) | |
|
||||
| social_media | json | |
|
||||
| light_mode | integer | Default `1` |
|
||||
| role | varchar(250) | Default `'user'` |
|
||||
| role_id | bigint | FK → roles.id, NOT NULL |
|
||||
| status | boolean | Default `true` |
|
||||
| created_at | timestamp UTC | |
|
||||
| updated_at | timestamp UTC | |
|
||||
|
||||
8
app.go
8
app.go
@@ -46,8 +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()
|
||||
|
||||
@@ -12,10 +12,11 @@ storage:
|
||||
password: <your-db-password>
|
||||
pg_pool_max_conn: 10
|
||||
minio:
|
||||
endpoint: example-minio:9000 # use localhost:9003 when running outside Docker
|
||||
access_key: <your-minio-access-key>
|
||||
secret_key: <your-minio-secret-key>
|
||||
endpoint: 127.0.0.1:9000
|
||||
access_key: TX3H1H6XTS288QW07S8Z
|
||||
secret_key: FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
bucket: dev-minio
|
||||
use_ssl: false
|
||||
app_version: 0.0.1
|
||||
public_file_path: ./public
|
||||
public_file_path: ./public
|
||||
public_base_url: https://your-api-domain.example # used to build the GBÜS payment callback (returnUrl)
|
||||
@@ -1,7 +1,56 @@
|
||||
DROP TABLE IF EXISTS payment_texts;
|
||||
DROP TABLE IF EXISTS rbac_version;
|
||||
DROP FUNCTION IF EXISTS rbac_bump_version() CASCADE;
|
||||
|
||||
DROP TABLE IF EXISTS visa_master_payment_logs;
|
||||
DROP TABLE IF EXISTS visa_master_order_payments;
|
||||
DROP TABLE IF EXISTS payment_settings;
|
||||
|
||||
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_balances_branch_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_users_role_id;
|
||||
DROP INDEX IF EXISTS idx_branch_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;
|
||||
|
||||
DROP INDEX IF EXISTS idx_activity_logs_created_at;
|
||||
DROP INDEX IF EXISTS idx_activity_logs_module;
|
||||
DROP INDEX IF EXISTS idx_activity_logs_user_id;
|
||||
DROP TABLE IF EXISTS activity_logs;
|
||||
DROP TABLE IF EXISTS visa_master_payment_orders;
|
||||
DROP TABLE IF EXISTS loan_paid_off_letters;
|
||||
DROP TABLE IF EXISTS loans;
|
||||
DROP TABLE IF EXISTS loan_orders;
|
||||
@@ -12,14 +61,22 @@ DROP TABLE IF EXISTS loan_order_required_docs;
|
||||
DROP TABLE IF EXISTS loan_types;
|
||||
DROP TABLE IF EXISTS card_states;
|
||||
DROP TABLE IF EXISTS card_types;
|
||||
|
||||
DROP INDEX IF EXISTS branch_user_branch_id_user_id_idx;
|
||||
DROP TABLE IF EXISTS branch_user;
|
||||
|
||||
DROP INDEX IF EXISTS branches_unique_code_idx;
|
||||
DROP TABLE IF EXISTS branches;
|
||||
|
||||
DROP TABLE IF EXISTS provinces;
|
||||
DROP TABLE IF EXISTS permission_user;
|
||||
DROP TABLE IF EXISTS role_user;
|
||||
DROP TABLE IF EXISTS permissions;
|
||||
DROP TABLE IF EXISTS roles;
|
||||
|
||||
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 TABLE IF EXISTS role_permissions;
|
||||
DROP TABLE IF EXISTS permissions;
|
||||
DROP INDEX IF EXISTS roles_code_uq;
|
||||
DROP TABLE IF EXISTS roles;
|
||||
|
||||
@@ -1,4 +1,57 @@
|
||||
-- 1. Identity
|
||||
-- RBAC: permission = modul (bir permission her modul üçin), rol = permission-lar + scope
|
||||
-- (own | branch | all). Her ulanyjynyň bir roly bar (users.role_id).
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
scope character varying(16) NOT NULL,
|
||||
is_super boolean NOT NULL DEFAULT false,
|
||||
is_system boolean NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT roles_scope_check CHECK (scope IN ('own', 'branch', 'all'))
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS roles_code_uq ON roles (code) WHERE deleted_at IS NULL;
|
||||
|
||||
-- Katalog kodda (internal/identity/rbac/perm); app başlanda şu sanawy sinhronlaýar.
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
code character varying(64) PRIMARY KEY,
|
||||
name character varying(255) NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
INSERT INTO permissions (code, name) VALUES
|
||||
('dashboard', 'Dashboard'),
|
||||
('cards', 'Cards'),
|
||||
('loans', 'Loans'),
|
||||
('users', 'Users'),
|
||||
('roles', 'Roles'),
|
||||
('branches', 'Branches'),
|
||||
('provinces', 'Provinces'),
|
||||
('currencies', 'Currencies'),
|
||||
('payment-settings', 'Payment settings'),
|
||||
('backups', 'Backups'),
|
||||
('activity-logs', 'Activity logs')
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role_permissions (
|
||||
role_id bigint NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
|
||||
permission_code character varying(64) NOT NULL REFERENCES permissions(code) ON DELETE CASCADE,
|
||||
PRIMARY KEY (role_id, permission_code)
|
||||
);
|
||||
|
||||
INSERT INTO roles (code, name, scope, is_super, is_system) VALUES
|
||||
('superadmin', 'Superadmin', 'all', true, true),
|
||||
('user', 'User', 'own', false, true)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO role_permissions (role_id, permission_code)
|
||||
SELECT r.id, x.code
|
||||
FROM roles r CROSS JOIN (VALUES ('cards'), ('loans')) x(code)
|
||||
WHERE r.code = 'user'
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id bigserial PRIMARY KEY,
|
||||
email character varying(250) NOT NULL DEFAULT '',
|
||||
@@ -11,19 +64,20 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
avatar character varying(250) NOT NULL DEFAULT '',
|
||||
social_media json NOT NULL DEFAULT '{}'::json,
|
||||
light_mode integer NOT NULL DEFAULT 1,
|
||||
role character varying(250) NOT NULL DEFAULT 'user',
|
||||
role_id bigint NOT NULL REFERENCES roles(id),
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username
|
||||
ON users (LOWER(username))
|
||||
WHERE username <> '';
|
||||
WHERE username <> '' AND deleted_at IS NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone
|
||||
ON users (phone)
|
||||
WHERE phone <> '';
|
||||
WHERE phone <> '' AND deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS registration_verifications (
|
||||
id bigserial PRIMARY KEY,
|
||||
@@ -38,53 +92,19 @@ CREATE TABLE IF NOT EXISTS registration_verifications (
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS roles (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(255) NOT NULL DEFAULT '',
|
||||
name character varying(255) NOT NULL,
|
||||
guard_name character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
role_id bigint REFERENCES roles(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permission_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
permission_id bigint REFERENCES permissions(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
-- 2. Geography
|
||||
CREATE TABLE IF NOT EXISTS provinces (
|
||||
id bigserial PRIMARY KEY,
|
||||
name json NOT NULL DEFAULT '{}'::json,
|
||||
region json NOT NULL DEFAULT '{}'::json,
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS branches (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_code character varying(255) UNIQUE,
|
||||
unique_code character varying(255),
|
||||
name json NOT NULL DEFAULT '{}'::json,
|
||||
address json NOT NULL DEFAULT '{}'::json,
|
||||
region character varying(20) NOT NULL DEFAULT '',
|
||||
@@ -101,19 +121,31 @@ CREATE TABLE IF NOT EXISTS branches (
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT branches_province_id_fkey
|
||||
FOREIGN KEY (province_id) REFERENCES provinces(id) ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS branches_unique_code_idx
|
||||
ON branches (unique_code)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS branch_user (
|
||||
id bigserial PRIMARY KEY,
|
||||
branch_id bigint REFERENCES branches(id),
|
||||
user_id bigint REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- 3. Catalogs
|
||||
-- branch_user is many-to-many (a user may be assigned to several branches at
|
||||
-- once); this index only stops the same pair being assigned twice while
|
||||
-- active, so re-assigning it can be a no-op instead of a duplicate row.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS branch_user_branch_id_user_id_idx
|
||||
ON branch_user (branch_id, user_id)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS card_types (
|
||||
id bigserial PRIMARY KEY,
|
||||
name json NOT NULL DEFAULT '{}'::json,
|
||||
@@ -121,7 +153,8 @@ CREATE TABLE IF NOT EXISTS card_types (
|
||||
notes character varying(255) NOT NULL DEFAULT '',
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS card_states (
|
||||
@@ -131,7 +164,8 @@ CREATE TABLE IF NOT EXISTS card_states (
|
||||
notes character varying(255) NOT NULL DEFAULT '',
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS loan_types (
|
||||
@@ -142,7 +176,8 @@ CREATE TABLE IF NOT EXISTS loan_types (
|
||||
notes json NOT NULL DEFAULT '{}'::json,
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
||||
@@ -151,10 +186,10 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
||||
value text NOT NULL DEFAULT '',
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- 4. Cards
|
||||
CREATE TABLE IF NOT EXISTS cards (
|
||||
id bigserial PRIMARY KEY,
|
||||
user_id bigint,
|
||||
@@ -165,6 +200,7 @@ CREATE TABLE IF NOT EXISTS cards (
|
||||
type character varying(250),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT cards_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
@@ -174,7 +210,7 @@ CREATE TABLE IF NOT EXISTS card_orders (
|
||||
unique_id character varying(255),
|
||||
card_state_id bigint NOT NULL,
|
||||
card_type_id bigint NOT NULL,
|
||||
region character varying(2) 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,
|
||||
@@ -202,6 +238,7 @@ CREATE TABLE IF NOT EXISTS card_orders (
|
||||
paid boolean NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT card_orders_card_state_id_fkey
|
||||
FOREIGN KEY (card_state_id) REFERENCES card_states(id),
|
||||
CONSTRAINT card_orders_card_type_id_fkey
|
||||
@@ -218,7 +255,7 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
|
||||
user_id bigint,
|
||||
card_type_id bigint NOT NULL,
|
||||
card_number character varying(255),
|
||||
region character varying(2) 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,
|
||||
@@ -235,6 +272,7 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
|
||||
notes character varying(250),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT card_pin_orders_card_type_id_fkey
|
||||
FOREIGN KEY (card_type_id) REFERENCES card_types(id),
|
||||
CONSTRAINT card_pin_orders_branch_id_fkey
|
||||
@@ -243,14 +281,13 @@ CREATE TABLE IF NOT EXISTS card_pin_orders (
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
-- 5. Loans
|
||||
CREATE TABLE IF NOT EXISTS loan_orders (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_id character varying(255),
|
||||
source character varying(255) DEFAULT 'web'::character varying,
|
||||
user_id bigint,
|
||||
loan_type bigint NOT NULL,
|
||||
region character varying(2) 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,
|
||||
@@ -314,7 +351,8 @@ CREATE TABLE IF NOT EXISTS loan_orders (
|
||||
satisfiable character varying(255),
|
||||
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
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS loans (
|
||||
@@ -325,6 +363,7 @@ CREATE TABLE IF NOT EXISTS loans (
|
||||
account_number character varying(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT loans_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
@@ -332,7 +371,7 @@ CREATE TABLE IF NOT EXISTS loans (
|
||||
CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_id character varying(255),
|
||||
region character varying(2) NOT NULL,
|
||||
region character varying(255) NOT NULL,
|
||||
branch_id bigint NOT NULL,
|
||||
user_id bigint,
|
||||
customer_name character varying(255) NOT NULL,
|
||||
@@ -351,13 +390,49 @@ CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
|
||||
loan_file 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,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT loan_paid_off_letters_branch_id_fkey
|
||||
FOREIGN KEY (branch_id) REFERENCES branches(id),
|
||||
CONSTRAINT loan_paid_off_letters_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
-- 6. Logs
|
||||
CREATE TABLE IF NOT EXISTS visa_master_payment_orders (
|
||||
id bigserial PRIMARY KEY,
|
||||
unique_id character varying(255),
|
||||
type character varying(255),
|
||||
passport_name character varying(255) NOT NULL,
|
||||
passport_surname character varying(255) NOT NULL,
|
||||
phone character varying(255) NOT NULL,
|
||||
email character varying(255),
|
||||
region character varying(255) NOT NULL,
|
||||
branch_id bigint NOT NULL,
|
||||
user_id bigint,
|
||||
address character varying(255) NOT NULL,
|
||||
sender_datas json DEFAULT '{}'::json,
|
||||
payment_reciever json DEFAULT '[]'::json,
|
||||
documents json DEFAULT '{}'::json,
|
||||
status character varying(255) DEFAULT 'pending',
|
||||
notes character varying(255),
|
||||
sender_full_name character varying(255) NOT NULL,
|
||||
sender_passport_serie character varying(255) NOT NULL,
|
||||
sender_passport_number character varying(255) NOT NULL,
|
||||
sender_deposit_account character varying(255) NOT NULL,
|
||||
reciever_full_name character varying(255),
|
||||
reciever_passport_serie character varying(255),
|
||||
reciever_passport_number character varying(255),
|
||||
reciever_deposit_account character varying(255),
|
||||
paid boolean NOT NULL DEFAULT false,
|
||||
amount_usd numeric(18, 2),
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT visa_master_payment_orders_branch_id_fkey
|
||||
FOREIGN KEY (branch_id) REFERENCES branches(id),
|
||||
CONSTRAINT visa_master_payment_orders_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS activity_logs (
|
||||
id bigserial PRIMARY KEY,
|
||||
user_id bigint,
|
||||
@@ -376,3 +451,292 @@ 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,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
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 IF NOT EXISTS 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,
|
||||
|
||||
branch_id BIGINT,
|
||||
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')),
|
||||
CONSTRAINT card_balances_branch_id_fkey
|
||||
FOREIGN KEY (branch_id) REFERENCES branches(id)
|
||||
);
|
||||
|
||||
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,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT backups_created_by_fkey
|
||||
FOREIGN KEY (created_by) REFERENCES users(id),
|
||||
CONSTRAINT backups_status_chk CHECK (status IN ('pending', 'completed', 'failed'))
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS backups_file_name_idx
|
||||
ON backups (file_name)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
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,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT currencies_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id),
|
||||
CONSTRAINT currencies_updated_by_fkey FOREIGN KEY (updated_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS currencies_from_to_idx
|
||||
ON currencies (currency_from, currency_to)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
-- Single-row, admin-configurable commission fees used on every Töleg
|
||||
-- (Visa/Master/Sber money-transfer) payout. Visa/Master orders use
|
||||
-- bank_fee_tmt + gbus_fee_tmt; Sber orders use their own sber_bank_fee_tmt
|
||||
-- plus a USD-denominated tveb_fee_usd (converted to TMT at payout time via
|
||||
-- the USD rate) - Sber has no GBÜS fee. max_amount_usd is the single
|
||||
-- admin-configurable payout cap (converted to TMT at the current rate in
|
||||
-- /quote and /pay) instead of a per-order value the client supplied when
|
||||
-- creating the order.
|
||||
CREATE TABLE IF NOT EXISTS payment_settings (
|
||||
id smallint PRIMARY KEY DEFAULT 1,
|
||||
bank_fee_tmt numeric(12, 2) NOT NULL DEFAULT 100,
|
||||
gbus_fee_tmt numeric(12, 2) NOT NULL DEFAULT 15,
|
||||
sber_bank_fee_tmt numeric(12, 2) NOT NULL DEFAULT 100,
|
||||
tveb_fee_usd numeric(12, 2) NOT NULL DEFAULT 18,
|
||||
max_amount_usd numeric(12, 2) NOT NULL DEFAULT 250,
|
||||
updated_by bigint,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT payment_settings_single_row CHECK (id = 1),
|
||||
CONSTRAINT payment_settings_updated_by_fkey
|
||||
FOREIGN KEY (updated_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
INSERT INTO payment_settings (id, bank_fee_tmt, gbus_fee_tmt, sber_bank_fee_tmt, tveb_fee_usd)
|
||||
VALUES (1, 100, 15, 100, 18)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Every payout attempt for a visa/master/sber order, as its own row - a full
|
||||
-- audit trail (including failed gateway attempts) rather than columns on the
|
||||
-- order itself, so a retry after a failure doesn't erase what the previous
|
||||
-- attempt did. The Sber-specific columns (exchange_rate_rub, tveb_fee_usd,
|
||||
-- tveb_fee_tmt) stay null for non-Sber attempts, same as gbus_fee_tmt stays
|
||||
-- null for Sber ones. gateway_status/gateway_reference/gateway_response
|
||||
-- track the GBÜS register→callback round trip (pending until the callback
|
||||
-- verifies the outcome server-to-server).
|
||||
CREATE TABLE IF NOT EXISTS visa_master_order_payments (
|
||||
id bigserial PRIMARY KEY,
|
||||
order_id bigint NOT NULL,
|
||||
user_id bigint NOT NULL,
|
||||
payment_period date NOT NULL,
|
||||
exchange_rate_usd numeric(18, 8) NOT NULL,
|
||||
exchange_rate_rub numeric(18, 8),
|
||||
amount_tmt numeric(18, 2) NOT NULL,
|
||||
bank_fee_tmt numeric(12, 2) NOT NULL,
|
||||
gbus_fee_tmt numeric(12, 2),
|
||||
tveb_fee_usd numeric(12, 2),
|
||||
tveb_fee_tmt numeric(12, 2),
|
||||
total_amount_tmt numeric(18, 2) NOT NULL,
|
||||
gateway_status character varying(32) NOT NULL DEFAULT 'pending',
|
||||
gateway_reference character varying(255),
|
||||
gateway_response jsonb,
|
||||
-- orderNumber sent to GBÜS register.do and shown on its hosted payment
|
||||
-- page ("Номер заказа"): ddMMyyHHmmss in Ashgabat time, e.g.
|
||||
-- 290926133808 for 29.09.2026 13:38:08. GBÜS rejects a repeated
|
||||
-- orderNumber per merchant, hence the unique index below.
|
||||
order_number character varying(32),
|
||||
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,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
CONSTRAINT visa_master_order_payments_order_id_fkey
|
||||
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
|
||||
CONSTRAINT visa_master_order_payments_user_id_fkey
|
||||
FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
CONSTRAINT visa_master_order_payments_created_by_fkey
|
||||
FOREIGN KEY (created_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS visa_master_order_payments_order_id_idx ON visa_master_order_payments (order_id);
|
||||
CREATE INDEX IF NOT EXISTS visa_master_order_payments_user_id_idx ON visa_master_order_payments (user_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS visa_master_order_payments_order_number_idx
|
||||
ON visa_master_order_payments (order_number);
|
||||
|
||||
-- Every individual step taken while processing a payout (validated, rate
|
||||
-- fetched, gateway request sent, gateway response received, order marked
|
||||
-- paid/attempt recorded) as its own row, so there's a step-by-step,
|
||||
-- timestamped record of what actually happened for a given order -
|
||||
-- evidence if a payout is later disputed, independent of (and more
|
||||
-- granular than) the one summary row in visa_master_order_payments.
|
||||
CREATE TABLE IF NOT EXISTS visa_master_payment_logs (
|
||||
id bigserial PRIMARY KEY,
|
||||
order_id bigint NOT NULL,
|
||||
step character varying(100) NOT NULL,
|
||||
detail jsonb,
|
||||
created_by bigint,
|
||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT visa_master_payment_logs_order_id_fkey
|
||||
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
|
||||
CONSTRAINT visa_master_payment_logs_created_by_fkey
|
||||
FOREIGN KEY (created_by) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS visa_master_payment_logs_order_id_idx ON visa_master_payment_logs (order_id);
|
||||
|
||||
-- Admin-editable texts shown to clients around a visa/master/sber payout
|
||||
-- (e.g. the warning before paying). Clients look a text up by its fixed
|
||||
-- code, so codes are seeded here and never created/deleted from the admin
|
||||
-- UI - only name/text/is_active are editable. text is {"tm","ru","en"}.
|
||||
CREATE TABLE IF NOT EXISTS payment_texts (
|
||||
id bigserial PRIMARY KEY,
|
||||
code character varying(64) NOT NULL,
|
||||
name character varying(255) NOT NULL,
|
||||
text jsonb NOT NULL DEFAULT '{"tm":"","ru":"","en":""}'::jsonb,
|
||||
is_active boolean NOT NULL DEFAULT true,
|
||||
updated_by bigint,
|
||||
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT payment_texts_code_key UNIQUE (code),
|
||||
CONSTRAINT payment_texts_updated_by_fkey
|
||||
FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
INSERT INTO payment_texts (code, name, text) VALUES
|
||||
('payment_warning_text', 'Visa/Master töleg duýduryş',
|
||||
'{"tm":"Dogry töleg aýyny saýlamagyňyzy haýyş edýäris","ru":"","en":""}'::jsonb),
|
||||
('sber_payment_warning', 'Sber töleg duýduryş',
|
||||
'{"tm":"Sber töleg duýduryş","ru":"","en":""}'::jsonb)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- Indexes for hot filter/join columns: users.role_id 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_users_role_id ON users(role_id);
|
||||
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_card_balances_branch_id ON card_balances(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);
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- RBAC cache wersiýasy: trigger-ler bilen artdyrylýar; app cache-i şony görüp arassalaýar
|
||||
-- ---------------------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS rbac_version (
|
||||
id int PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
version bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
INSERT INTO rbac_version (id, version) VALUES (1, 0) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE OR REPLACE FUNCTION rbac_bump_version() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
UPDATE rbac_version SET version = version + 1 WHERE id = 1;
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE OR REPLACE TRIGGER rbac_bump_roles
|
||||
AFTER INSERT OR UPDATE OR DELETE ON roles
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
|
||||
CREATE OR REPLACE TRIGGER rbac_bump_role_permissions
|
||||
AFTER INSERT OR UPDATE OR DELETE ON role_permissions
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
|
||||
CREATE OR REPLACE TRIGGER rbac_bump_users
|
||||
AFTER UPDATE OF role_id, deleted_at OR DELETE ON users
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
|
||||
CREATE OR REPLACE TRIGGER rbac_bump_branch_user
|
||||
AFTER INSERT OR UPDATE OR DELETE ON branch_user
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
|
||||
CREATE OR REPLACE TRIGGER rbac_bump_branches
|
||||
AFTER UPDATE OF deleted_at OR DELETE ON branches
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION rbac_bump_version();
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX IF EXISTS idx_visa_master_order_payments_status_id;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- payment-history lists newest-first (ORDER BY p.id DESC) and is commonly
|
||||
-- filtered to one gateway_status; without this, a rare status (e.g.
|
||||
-- pending) means walking the whole primary key backwards to fill a page.
|
||||
CREATE INDEX IF NOT EXISTS idx_visa_master_order_payments_status_id
|
||||
ON visa_master_order_payments (gateway_status, id DESC)
|
||||
WHERE deleted_at IS NULL;
|
||||
@@ -0,0 +1 @@
|
||||
DROP INDEX IF EXISTS visa_master_payment_logs_order_step_idx;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- payment-history reads each attempt's register/callback log rows
|
||||
-- (formUrl, returnUrl, first callback) by order and step; without this
|
||||
-- every row of a page scans all of its order's logs.
|
||||
CREATE INDEX IF NOT EXISTS visa_master_payment_logs_order_step_idx
|
||||
ON visa_master_payment_logs (order_id, step);
|
||||
887
db/seed.sql
887
db/seed.sql
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,33 @@
|
||||
FROM quay.io/minio/minio
|
||||
# MinIO no longer publishes images (quay.io/minio/minio and minio/minio are not
|
||||
# pullable), so the server binary comes from minio.deb next to this file.
|
||||
# Both stages use golang:1.26.4-alpine, which is already in the offline bundle,
|
||||
# so this builds without network.
|
||||
|
||||
FROM golang:1.26.4-alpine AS extract
|
||||
|
||||
WORKDIR /tmp/deb
|
||||
|
||||
COPY minio.deb .
|
||||
|
||||
# A .deb is an ar archive and busybox here has no `ar`, so read it by hand:
|
||||
# 8-byte magic, then per member a 60-byte header (name at 1-16, size at 49-58),
|
||||
# the data, and one pad byte when the size is odd.
|
||||
RUN set -e; \
|
||||
f=minio.deb; off=8; total=$(stat -c %s "$f"); \
|
||||
while [ "$off" -lt "$total" ]; do \
|
||||
name=$(tail -c +$((off + 1)) "$f" | head -c 16 | tr -d ' /'); \
|
||||
size=$(tail -c +$((off + 49)) "$f" | head -c 10 | tr -d ' '); \
|
||||
if [ "$name" = "data.tar.gz" ]; then \
|
||||
tail -c +$((off + 61)) "$f" | head -c "$size" | tar -xzf - ./usr/local/bin/minio; \
|
||||
break; \
|
||||
fi; \
|
||||
off=$((off + 60 + size + size % 2)); \
|
||||
done; \
|
||||
./usr/local/bin/minio --version
|
||||
|
||||
FROM golang:1.26.4-alpine
|
||||
|
||||
COPY --from=extract /tmp/deb/usr/local/bin/minio /usr/bin/minio
|
||||
|
||||
RUN mkdir /storage
|
||||
|
||||
@@ -8,4 +37,4 @@ ENV MINIO_VOLUMES="/storage"
|
||||
EXPOSE 9000
|
||||
EXPOSE 9093
|
||||
|
||||
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
|
||||
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
|
||||
|
||||
74
deployment/install-minio-ubuntu.sh
Executable file
74
deployment/install-minio-ubuntu.sh
Executable file
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Native MinIO for Ubuntu (no Docker). Binds only to 127.0.0.1.
|
||||
#
|
||||
# Fresh install (keeps existing data if present):
|
||||
# sudo bash install-minio-ubuntu.sh /path/to/minio.deb
|
||||
#
|
||||
# Wipe data + config, then install:
|
||||
# sudo bash install-minio-ubuntu.sh --wipe /path/to/minio.deb
|
||||
|
||||
WIPE=0
|
||||
DEB_PATH=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--wipe) WIPE=1 ;;
|
||||
*) DEB_PATH="$arg" ;;
|
||||
esac
|
||||
done
|
||||
DEB_PATH="${DEB_PATH:-./minio.deb}"
|
||||
ENV_SRC="$(cd "$(dirname "$0")" && pwd)/minio.env"
|
||||
|
||||
if [[ "$(id -u)" -ne 0 ]]; then
|
||||
echo "run as root: sudo bash $0 [--wipe] $DEB_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "$DEB_PATH" ]]; then
|
||||
echo "deb not found: $DEB_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! -f "$ENV_SRC" ]]; then
|
||||
echo "env file not found: $ENV_SRC" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
systemctl stop minio 2>/dev/null || true
|
||||
systemctl reset-failed minio 2>/dev/null || true
|
||||
pkill -x minio 2>/dev/null || true
|
||||
sleep 1
|
||||
|
||||
if [[ "$WIPE" -eq 1 ]]; then
|
||||
echo "wiping /data/minio and /etc/default/minio"
|
||||
rm -rf /data/minio
|
||||
rm -f /etc/default/minio
|
||||
fi
|
||||
|
||||
port_busy() {
|
||||
local port="$1"
|
||||
ss -H -tln | awk '{print $4}' | grep -E ":${port}$" >/dev/null
|
||||
}
|
||||
|
||||
for port in 9000 9001; do
|
||||
if port_busy "$port"; then
|
||||
echo "port $port is already in use:" >&2
|
||||
ss -tlnp | grep -E ":${port}\\b" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
id minio-user >/dev/null 2>&1 || useradd --system --home-dir /data/minio --shell /sbin/nologin minio-user
|
||||
mkdir -p /data/minio
|
||||
chown -R minio-user:minio-user /data/minio
|
||||
|
||||
cp "$ENV_SRC" /etc/default/minio
|
||||
chmod 600 /etc/default/minio
|
||||
|
||||
dpkg -i "$DEB_PATH"
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable minio
|
||||
systemctl start minio
|
||||
systemctl --no-pager --full status minio
|
||||
6
deployment/minio.env
Normal file
6
deployment/minio.env
Normal file
@@ -0,0 +1,6 @@
|
||||
MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
|
||||
MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
MINIO_VOLUMES=/data/minio
|
||||
MINIO_ADDRESS=127.0.0.1:9000
|
||||
MINIO_CONSOLE_ADDRESS=127.0.0.1:9001
|
||||
MINIO_OPTS=
|
||||
@@ -1,5 +1,6 @@
|
||||
services:
|
||||
main-db:
|
||||
# Keep in sync with the runtime stage in Dockerfile: pg_dump must match this major version.
|
||||
image: postgres:14.1-alpine
|
||||
container_name: "main-db"
|
||||
restart: always
|
||||
@@ -11,38 +12,51 @@ services:
|
||||
- '5424:5432'
|
||||
volumes:
|
||||
- main-db-storage:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U bank_admin -d bank_db"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
main-server:
|
||||
image: main-app
|
||||
image: main-app:latest
|
||||
restart: unless-stopped
|
||||
container_name: "main-app"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
- TZ=Asia/Ashgabat
|
||||
ports:
|
||||
- "5050:5050"
|
||||
volumes:
|
||||
# Inside this network the config must point at main-db:5432 and main-minio:9000.
|
||||
- ./config.yaml:/app/config.yaml:ro
|
||||
- ./public:/app/public
|
||||
- ./logs:/app/logs
|
||||
depends_on:
|
||||
- main-db
|
||||
- main-minio
|
||||
main-db:
|
||||
condition: service_healthy
|
||||
main-minio:
|
||||
condition: service_started
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
main-minio:
|
||||
image: main-minio:latest
|
||||
container_name: "main-minio"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: deployment/Dockerfile.minio
|
||||
context: ./deployment
|
||||
dockerfile: Dockerfile.minio
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
|
||||
- MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||
ports:
|
||||
- '9003:9000'
|
||||
- '9093:9093'
|
||||
- '127.0.0.1:9003:9000'
|
||||
- '127.0.0.1:9093:9093'
|
||||
volumes:
|
||||
- main-minio-storage:/storage
|
||||
networks:
|
||||
@@ -54,4 +68,4 @@ volumes:
|
||||
|
||||
networks:
|
||||
myNetwork:
|
||||
driver: bridge
|
||||
driver: bridge
|
||||
|
||||
4980
docs/docs.go
4980
docs/docs.go
File diff suppressed because it is too large
Load Diff
4980
docs/swagger.json
4980
docs/swagger.json
File diff suppressed because it is too large
Load Diff
3486
docs/swagger.yaml
3486
docs/swagger.yaml
File diff suppressed because it is too large
Load Diff
@@ -13,20 +13,24 @@ var swaggerTagOrder = []struct {
|
||||
{Name: "branch-users", Description: "Branch users"},
|
||||
{Name: "user", Description: "Users"},
|
||||
{Name: "role", Description: "Roles"},
|
||||
{Name: "role-users", Description: "Role users"},
|
||||
{Name: "permission", Description: "Permissions"},
|
||||
{Name: "permission-users", Description: "Permission users"},
|
||||
{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: "payment-texts", Description: "Payment warning texts (Visa/Master, Sber)"},
|
||||
{Name: "dashboard", Description: "Admin dashboard overview"},
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
BIN
internal/.DS_Store
vendored
BIN
internal/.DS_Store
vendored
Binary file not shown.
928
internal/analytics/db/postgresql.go
Normal file
928
internal/analytics/db/postgresql.go
Normal file
@@ -0,0 +1,928 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/internal/analytics"
|
||||
"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) analytics.Repository {
|
||||
return &repository{client: client, logger: logger}
|
||||
}
|
||||
|
||||
// orderTables maps each order type to its table. Every table has branch_id,
|
||||
// region, status, created_at, updated_at and deleted_at, so they can be
|
||||
// unioned into one "orders" set.
|
||||
var orderTables = []struct{ typ, table string }{
|
||||
{analytics.OrderLoan, "loan_orders"},
|
||||
{analytics.OrderLoanLetter, "loan_paid_off_letters"},
|
||||
{analytics.OrderCard, "card_orders"},
|
||||
{analytics.OrderCardPin, "card_pin_orders"},
|
||||
{analytics.OrderCardRekwizit, "card_rekwizit_orders"},
|
||||
{analytics.OrderVisaMaster, "visa_master_payment_orders"},
|
||||
}
|
||||
|
||||
// statusBucketSQL folds a free-text status column into open / approved /
|
||||
// rejected / other. NULL and empty mean a fresh order nobody has handled.
|
||||
func statusBucketSQL(col string) string {
|
||||
return fmt.Sprintf(`
|
||||
CASE
|
||||
WHEN lower(coalesce(%[1]s, '')) IN ('', 'pending', 'new', 'registered', 'review', 'processing', 'in_process', 'in-process') THEN 'open'
|
||||
WHEN lower(%[1]s) IN ('approved', 'satisfied', 'completed', 'paid', 'success', 'done', 'accepted') THEN 'approved'
|
||||
WHEN lower(%[1]s) IN ('rejected', 'cancelled', 'canceled', 'declined', 'failed') THEN 'rejected'
|
||||
ELSE 'other'
|
||||
END`, col)
|
||||
}
|
||||
|
||||
// sqlArgs collects positional arguments and hands out their $n placeholders.
|
||||
type sqlArgs []interface{}
|
||||
|
||||
func (a *sqlArgs) add(v interface{}) string {
|
||||
*a = append(*a, v)
|
||||
return fmt.Sprintf("$%d", len(*a))
|
||||
}
|
||||
|
||||
// rangeCond returns " AND <col> >= $x AND <col> < $y".
|
||||
func rangeCond(args *sqlArgs, col string, f analytics.Filter) string {
|
||||
return fmt.Sprintf(" AND %s >= %s AND %s < %s", col, args.add(f.From), col, args.add(f.To))
|
||||
}
|
||||
|
||||
// branchCond returns " AND <col> = ANY($x)" for branch-scope callers.
|
||||
func branchCond(args *sqlArgs, col string, f analytics.Filter) string {
|
||||
if len(f.BranchIds) == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(" AND %s = ANY(%s)", col, args.add(f.BranchIds))
|
||||
}
|
||||
|
||||
// ordersUnionSQL unions the caller's visible order tables into rows of
|
||||
// (type, branch_id, region, bucket, created_at, updated_at). withRange
|
||||
// limits rows to the filter's date range.
|
||||
func ordersUnionSQL(args *sqlArgs, f analytics.Filter, withRange bool) string {
|
||||
var tables []string
|
||||
for _, t := range orderTables {
|
||||
if containsString(f.Types, t.typ) {
|
||||
tables = append(tables, t.typ, t.table)
|
||||
}
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
// Keep the column shape so callers' queries still run and return
|
||||
// nothing; add no args, since no placeholder would use them.
|
||||
return `SELECT ''::text AS type, 0::bigint AS branch_id, ''::text AS region, ''::text AS bucket, now()::timestamp AS created_at, now()::timestamp AS updated_at WHERE false`
|
||||
}
|
||||
|
||||
cond := branchCond(args, "branch_id", f)
|
||||
if withRange {
|
||||
cond += rangeCond(args, "created_at", f)
|
||||
}
|
||||
parts := make([]string, 0, len(tables)/2)
|
||||
for i := 0; i < len(tables); i += 2 {
|
||||
parts = append(parts, fmt.Sprintf(
|
||||
`SELECT '%s' AS type, branch_id, coalesce(region, '') AS region, %s AS bucket, created_at, updated_at FROM %s WHERE deleted_at IS NULL%s`,
|
||||
tables[i], statusBucketSQL("status"), tables[i+1], cond))
|
||||
}
|
||||
return strings.Join(parts, "\nUNION ALL\n")
|
||||
}
|
||||
|
||||
func round2(v float64) float64 {
|
||||
return math.Round(v*100) / 100
|
||||
}
|
||||
|
||||
func pct(part, total int64) float64 {
|
||||
if total == 0 {
|
||||
return 0
|
||||
}
|
||||
return round2(float64(part) / float64(total) * 100)
|
||||
}
|
||||
|
||||
func ratePtr(part, total int64) *float64 {
|
||||
if total == 0 {
|
||||
return nil
|
||||
}
|
||||
v := pct(part, total)
|
||||
return &v
|
||||
}
|
||||
|
||||
func roundPtr(v *float64) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
r := round2(*v)
|
||||
return &r
|
||||
}
|
||||
|
||||
// withPercent fills Percent on counts relative to their sum.
|
||||
func withPercent(items []analytics.CountDTO) []analytics.CountDTO {
|
||||
var total int64
|
||||
for _, it := range items {
|
||||
total += it.Count
|
||||
}
|
||||
for i := range items {
|
||||
items[i].Percent = pct(items[i].Count, total)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (r *repository) countsByKey(ctx context.Context, query string, args ...interface{}) ([]analytics.CountDTO, error) {
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []analytics.CountDTO{}
|
||||
for rows.Next() {
|
||||
var it analytics.CountDTO
|
||||
if err := rows.Scan(&it.Key, &it.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, it)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return withPercent(items), nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- finance
|
||||
|
||||
// paymentsFromSQL is the FROM/WHERE shared by payment queries: payments in
|
||||
// range, joined to their order for branch scoping.
|
||||
func paymentsFromSQL(args *sqlArgs, f analytics.Filter) string {
|
||||
return `
|
||||
FROM visa_master_order_payments p
|
||||
JOIN visa_master_payment_orders o ON o.id = p.order_id AND o.deleted_at IS NULL
|
||||
WHERE p.deleted_at IS NULL` + rangeCond(args, "p.created_at", f) + branchCond(args, "o.branch_id", f)
|
||||
}
|
||||
|
||||
func (r *repository) Finance(ctx context.Context, f analytics.Filter) (analytics.FinanceDTO, error) {
|
||||
out := analytics.FinanceDTO{Gateway: []analytics.CountDTO{}, Monthly: []analytics.FinanceMonthDTO{}}
|
||||
|
||||
var args sqlArgs
|
||||
query := `
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(SUM(p.amount_tmt), 0)::float8,
|
||||
COALESCE(SUM(p.bank_fee_tmt), 0)::float8,
|
||||
COALESCE(SUM(p.gbus_fee_tmt), 0)::float8,
|
||||
COALESCE(SUM(p.tveb_fee_tmt), 0)::float8,
|
||||
COALESCE(SUM(p.total_amount_tmt), 0)::float8` + paymentsFromSQL(&args, f) + ` AND p.gateway_status = 'success'`
|
||||
pt := &out.Payments
|
||||
if err := r.client.QueryRow(ctx, query, args...).Scan(
|
||||
&pt.Count, &pt.AmountTmt, &pt.BankFeeTmt, &pt.GbusFeeTmt, &pt.TvebFeeTmt, &pt.TotalTmt,
|
||||
); err != nil {
|
||||
return out, err
|
||||
}
|
||||
pt.AmountTmt, pt.BankFeeTmt = round2(pt.AmountTmt), round2(pt.BankFeeTmt)
|
||||
pt.GbusFeeTmt, pt.TvebFeeTmt, pt.TotalTmt = round2(pt.GbusFeeTmt), round2(pt.TvebFeeTmt), round2(pt.TotalTmt)
|
||||
if pt.Count > 0 {
|
||||
pt.AvgTotalTmt = round2(pt.TotalTmt / float64(pt.Count))
|
||||
}
|
||||
|
||||
args = nil
|
||||
gateway, err := r.countsByKey(ctx, `SELECT p.gateway_status, COUNT(*)`+paymentsFromSQL(&args, f)+` GROUP BY 1 ORDER BY 2 DESC`, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Gateway = gateway
|
||||
var success, failed int64
|
||||
for _, g := range gateway {
|
||||
switch g.Key {
|
||||
case "success":
|
||||
success = g.Count
|
||||
case "failed":
|
||||
failed = g.Count
|
||||
}
|
||||
}
|
||||
out.GatewaySuccessRate = ratePtr(success, success+failed)
|
||||
|
||||
monthly, err := r.financeMonthly(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Monthly = monthly
|
||||
|
||||
loanRequested, err := r.loanRequested(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.LoanRequested = loanRequested
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *repository) financeMonthly(ctx context.Context, f analytics.Filter) ([]analytics.FinanceMonthDTO, error) {
|
||||
var args sqlArgs
|
||||
query := `
|
||||
SELECT to_char(date_trunc('month', p.created_at), 'YYYY-MM'), COUNT(*),
|
||||
COALESCE(SUM(p.total_amount_tmt), 0)::float8, COALESCE(SUM(p.bank_fee_tmt), 0)::float8` +
|
||||
paymentsFromSQL(&args, f) + ` AND p.gateway_status = 'success' GROUP BY 1`
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
byMonth := map[string]analytics.FinanceMonthDTO{}
|
||||
for rows.Next() {
|
||||
var m analytics.FinanceMonthDTO
|
||||
if err := rows.Scan(&m.Month, &m.Count, &m.TotalTmt, &m.BankFeeTmt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.TotalTmt, m.BankFeeTmt = round2(m.TotalTmt), round2(m.BankFeeTmt)
|
||||
byMonth[m.Month] = m
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// One point per month in range, zero-filled, so the chart has no gaps.
|
||||
out := []analytics.FinanceMonthDTO{}
|
||||
last := f.To.Add(-time.Nanosecond)
|
||||
for m := time.Date(f.From.Year(), f.From.Month(), 1, 0, 0, 0, 0, time.UTC); !m.After(last); m = m.AddDate(0, 1, 0) {
|
||||
key := m.Format("2006-01")
|
||||
point, ok := byMonth[key]
|
||||
if !ok {
|
||||
point = analytics.FinanceMonthDTO{Month: key}
|
||||
}
|
||||
out = append(out, point)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// loanAmountSQL parses the free-text loan_amount ("30 000", "30,000.50")
|
||||
// into numeric, NULL when it is not a plain number after stripping.
|
||||
const loanAmountSQL = `
|
||||
CASE WHEN regexp_replace(coalesce(loan_amount, ''), '[^0-9.]', '', 'g') ~ '^[0-9]+(\.[0-9]+)?$'
|
||||
THEN regexp_replace(loan_amount, '[^0-9.]', '', 'g')::numeric
|
||||
END`
|
||||
|
||||
func (r *repository) loanRequested(ctx context.Context, f analytics.Filter) (analytics.LoanRequestedDTO, error) {
|
||||
var out analytics.LoanRequestedDTO
|
||||
var args sqlArgs
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
COUNT(amt),
|
||||
COALESCE(SUM(amt), 0)::float8,
|
||||
COUNT(*) FILTER (WHERE amt IS NULL AND trim(coalesce(loan_amount, '')) <> '')
|
||||
FROM (
|
||||
SELECT loan_amount, %s AS amt
|
||||
FROM loan_orders
|
||||
WHERE deleted_at IS NULL%s%s
|
||||
) x`, loanAmountSQL, rangeCond(&args, "created_at", f), branchCond(&args, "branch_id", f))
|
||||
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.Count, &out.TotalTmt, &out.Unparsed); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.TotalTmt = round2(out.TotalTmt)
|
||||
if out.Count > 0 {
|
||||
out.AvgTmt = round2(out.TotalTmt / float64(out.Count))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- backlog
|
||||
|
||||
func (r *repository) Backlog(ctx context.Context, f analytics.Filter) (analytics.BacklogResponseDTO, error) {
|
||||
out := analytics.BacklogResponseDTO{Items: []analytics.BacklogDTO{}}
|
||||
|
||||
// The open queue is current state, so it ignores the date range; only
|
||||
// the "finished" figures are limited to orders created in range.
|
||||
var args sqlArgs
|
||||
union := ordersUnionSQL(&args, f, false)
|
||||
from, to := args.add(f.From), args.add(f.To)
|
||||
query := fmt.Sprintf(`
|
||||
WITH o AS (%s), now_utc AS (SELECT (now() AT TIME ZONE 'UTC') AS ts)
|
||||
SELECT
|
||||
o.type,
|
||||
COUNT(*) FILTER (WHERE bucket = 'open'),
|
||||
COUNT(*) FILTER (WHERE bucket = 'open' AND created_at > n.ts - interval '1 day'),
|
||||
COUNT(*) FILTER (WHERE bucket = 'open' AND created_at <= n.ts - interval '1 day' AND created_at > n.ts - interval '3 days'),
|
||||
COUNT(*) FILTER (WHERE bucket = 'open' AND created_at <= n.ts - interval '3 days'),
|
||||
MIN(created_at) FILTER (WHERE bucket = 'open'),
|
||||
(EXTRACT(EPOCH FROM n.ts - MIN(created_at) FILTER (WHERE bucket = 'open')) / 86400)::float8,
|
||||
COUNT(*) FILTER (WHERE bucket <> 'open' AND created_at >= %[2]s AND created_at < %[3]s),
|
||||
(AVG(EXTRACT(EPOCH FROM updated_at - created_at) / 3600)
|
||||
FILTER (WHERE bucket <> 'open' AND created_at >= %[2]s AND created_at < %[3]s))::float8
|
||||
FROM o CROSS JOIN now_utc n
|
||||
GROUP BY o.type, n.ts`, union, from, to)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
byType := map[string]analytics.BacklogDTO{}
|
||||
for rows.Next() {
|
||||
var it analytics.BacklogDTO
|
||||
var oldest *time.Time
|
||||
if err := rows.Scan(&it.Type, &it.Open, &it.Under1Day, &it.From1To3Days, &it.Over3Days,
|
||||
&oldest, &it.OldestOpenDays, &it.Finished, &it.AvgProcessHours); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
if oldest != nil {
|
||||
s := oldest.UTC().Format(time.RFC3339)
|
||||
it.OldestOpenAt = &s
|
||||
}
|
||||
it.OldestOpenDays = roundPtr(it.OldestOpenDays)
|
||||
it.AvgProcessHours = roundPtr(it.AvgProcessHours)
|
||||
byType[it.Type] = it
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Stable order, zero rows included, so the UI table never reshuffles.
|
||||
for _, t := range orderTables {
|
||||
if !containsString(f.Types, t.typ) {
|
||||
continue
|
||||
}
|
||||
it, ok := byType[t.typ]
|
||||
if !ok {
|
||||
it = analytics.BacklogDTO{Type: t.typ}
|
||||
}
|
||||
out.Items = append(out.Items, it)
|
||||
}
|
||||
|
||||
if containsString(f.Types, analytics.OrderVisaMaster) {
|
||||
timing, err := r.visaMasterTiming(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.VisaMasterTiming = timing
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *repository) visaMasterTiming(ctx context.Context, f analytics.Filter) (analytics.VisaMasterTimingDTO, error) {
|
||||
var out analytics.VisaMasterTimingDTO
|
||||
var args sqlArgs
|
||||
query := `
|
||||
WITH t AS (
|
||||
SELECT l.order_id,
|
||||
MIN(l.created_at) AS started,
|
||||
MAX(l.created_at) FILTER (WHERE l.step = 'payment_finalized') AS finished
|
||||
FROM visa_master_payment_logs l
|
||||
JOIN visa_master_payment_orders o ON o.id = l.order_id AND o.deleted_at IS NULL
|
||||
WHERE true` + rangeCond(&args, "l.created_at", f) + branchCond(&args, "o.branch_id", f) + `
|
||||
GROUP BY l.order_id
|
||||
), m AS (
|
||||
SELECT EXTRACT(EPOCH FROM finished - started) / 60 AS minutes FROM t WHERE finished IS NOT NULL
|
||||
)
|
||||
SELECT COUNT(*), AVG(minutes)::float8,
|
||||
(percentile_cont(0.9) WITHIN GROUP (ORDER BY minutes))::float8, MAX(minutes)::float8
|
||||
FROM m`
|
||||
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.Orders, &out.AvgMinutes, &out.P90Minutes, &out.MaxMinutes); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.AvgMinutes, out.P90Minutes, out.MaxMinutes = roundPtr(out.AvgMinutes), roundPtr(out.P90Minutes), roundPtr(out.MaxMinutes)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func containsString(list []string, v string) bool {
|
||||
for _, s := range list {
|
||||
if s == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- branches
|
||||
|
||||
func (r *repository) Branches(ctx context.Context, f analytics.Filter) (analytics.BranchesDTO, error) {
|
||||
out := analytics.BranchesDTO{Branches: []analytics.BranchStatDTO{}, Regions: []analytics.CountDTO{}}
|
||||
|
||||
var bargs sqlArgs
|
||||
branchQuery := `SELECT id, name, region FROM branches WHERE deleted_at IS NULL` + branchCond(&bargs, "id", f) + ` ORDER BY id`
|
||||
rows, err := r.client.Query(ctx, branchQuery, bargs...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
byID := map[int64]*analytics.BranchStatDTO{}
|
||||
var order []int64
|
||||
for rows.Next() {
|
||||
var b analytics.BranchStatDTO
|
||||
var name []byte
|
||||
if err := rows.Scan(&b.BranchId, &name, &b.Region); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
b.Name = json.RawMessage(name)
|
||||
b.Orders = map[string]int64{}
|
||||
byID[b.BranchId] = &b
|
||||
order = append(order, b.BranchId)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
|
||||
var args sqlArgs
|
||||
query := fmt.Sprintf(`
|
||||
WITH o AS (%s)
|
||||
SELECT branch_id, type, COUNT(*),
|
||||
COUNT(*) FILTER (WHERE bucket = 'open'),
|
||||
COUNT(*) FILTER (WHERE bucket = 'approved'),
|
||||
COUNT(*) FILTER (WHERE bucket = 'rejected'),
|
||||
COUNT(*) FILTER (WHERE bucket <> 'open'),
|
||||
COALESCE(SUM(EXTRACT(EPOCH FROM updated_at - created_at) / 3600) FILTER (WHERE bucket <> 'open'), 0)::float8
|
||||
FROM o
|
||||
GROUP BY branch_id, type`, ordersUnionSQL(&args, f, true))
|
||||
rows, err = r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
finished := map[int64]int64{}
|
||||
hours := map[int64]float64{}
|
||||
for rows.Next() {
|
||||
var branchID, total, open, approved, rejected, fin int64
|
||||
var typ string
|
||||
var h float64
|
||||
if err := rows.Scan(&branchID, &typ, &total, &open, &approved, &rejected, &fin, &h); err != nil {
|
||||
rows.Close()
|
||||
return out, err
|
||||
}
|
||||
b, ok := byID[branchID]
|
||||
if !ok {
|
||||
continue // order on a deleted branch
|
||||
}
|
||||
b.Orders[typ] = total
|
||||
b.Total += total
|
||||
b.Open += open
|
||||
b.Approved += approved
|
||||
b.Rejected += rejected
|
||||
finished[branchID] += fin
|
||||
hours[branchID] += h
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
|
||||
for _, id := range order {
|
||||
b := byID[id]
|
||||
b.ApprovalRate = ratePtr(b.Approved, b.Approved+b.Rejected)
|
||||
if finished[id] > 0 {
|
||||
avg := round2(hours[id] / float64(finished[id]))
|
||||
b.AvgProcessHours = &avg
|
||||
}
|
||||
out.Branches = append(out.Branches, *b)
|
||||
}
|
||||
sort.SliceStable(out.Branches, func(i, j int) bool { return out.Branches[i].Total > out.Branches[j].Total })
|
||||
|
||||
args = nil
|
||||
regions, err := r.countsByKey(ctx, fmt.Sprintf(`
|
||||
WITH o AS (%s)
|
||||
SELECT CASE WHEN region = '' THEN 'unknown' ELSE region END, COUNT(*) FROM o GROUP BY 1 ORDER BY 2 DESC`,
|
||||
ordersUnionSQL(&args, f, true)), args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Regions = regions
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- products
|
||||
|
||||
func (r *repository) Products(ctx context.Context, f analytics.Filter) (analytics.ProductsDTO, error) {
|
||||
out := analytics.ProductsDTO{
|
||||
LoanSources: []analytics.CountDTO{},
|
||||
LoanTypes: []analytics.NamedCountDTO{},
|
||||
CardTypes: []analytics.NamedCountDTO{},
|
||||
CardOrderPay: []analytics.CountDTO{},
|
||||
}
|
||||
|
||||
if containsString(f.Types, analytics.OrderLoan) {
|
||||
var args sqlArgs
|
||||
sources, err := r.countsByKey(ctx, `
|
||||
SELECT coalesce(nullif(trim(source), ''), 'web'), COUNT(*)
|
||||
FROM loan_orders WHERE deleted_at IS NULL`+rangeCond(&args, "created_at", f)+branchCond(&args, "branch_id", f)+`
|
||||
GROUP BY 1 ORDER BY 2 DESC`, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.LoanSources = sources
|
||||
|
||||
args = nil
|
||||
loanTypes, err := r.namedCounts(ctx, `
|
||||
SELECT t.id, t.name, COUNT(o.id)
|
||||
FROM loan_types t
|
||||
LEFT JOIN loan_orders o ON o.loan_type = t.id AND o.deleted_at IS NULL`+
|
||||
rangeCond(&args, "o.created_at", f)+branchCond(&args, "o.branch_id", f)+`
|
||||
WHERE t.deleted_at IS NULL
|
||||
GROUP BY t.id ORDER BY 3 DESC, t.id`, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.LoanTypes = loanTypes
|
||||
}
|
||||
|
||||
if containsString(f.Types, analytics.OrderCard) {
|
||||
var args sqlArgs
|
||||
cardTypes, err := r.namedCounts(ctx, `
|
||||
SELECT t.id, t.name, COUNT(o.id)
|
||||
FROM card_types t
|
||||
LEFT JOIN card_orders o ON o.card_type_id = t.id AND o.deleted_at IS NULL`+
|
||||
rangeCond(&args, "o.created_at", f)+branchCond(&args, "o.branch_id", f)+`
|
||||
WHERE t.deleted_at IS NULL
|
||||
GROUP BY t.id ORDER BY 3 DESC, t.id`, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.CardTypes = cardTypes
|
||||
|
||||
args = nil
|
||||
pay, err := r.countsByKey(ctx, `
|
||||
SELECT CASE WHEN paid THEN 'paid' ELSE 'unpaid' END, COUNT(*)
|
||||
FROM card_orders WHERE deleted_at IS NULL`+rangeCond(&args, "created_at", f)+branchCond(&args, "branch_id", f)+`
|
||||
GROUP BY 1 ORDER BY 1`, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.CardOrderPay = pay
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *repository) namedCounts(ctx context.Context, query string, args ...interface{}) ([]analytics.NamedCountDTO, error) {
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []analytics.NamedCountDTO{}
|
||||
var total int64
|
||||
for rows.Next() {
|
||||
var it analytics.NamedCountDTO
|
||||
var name []byte
|
||||
if err := rows.Scan(&it.Id, &name, &it.Count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
it.Name = json.RawMessage(name)
|
||||
total += it.Count
|
||||
items = append(items, it)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].Percent = pct(items[i].Count, total)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- customers
|
||||
|
||||
var ageGroupOrder = []string{"under25", "25-34", "35-44", "45-54", "55+", "unknown"}
|
||||
|
||||
const ageGroupSQL = `
|
||||
CASE
|
||||
WHEN born_at IS NULL THEN 'unknown'
|
||||
WHEN date_part('year', age(born_at)) < 25 THEN 'under25'
|
||||
WHEN date_part('year', age(born_at)) < 35 THEN '25-34'
|
||||
WHEN date_part('year', age(born_at)) < 45 THEN '35-44'
|
||||
WHEN date_part('year', age(born_at)) < 55 THEN '45-54'
|
||||
ELSE '55+'
|
||||
END`
|
||||
|
||||
const guarantorsSQL = `
|
||||
CASE
|
||||
WHEN trim(coalesce(guarantor_2_name, '')) <> '' THEN 'two'
|
||||
WHEN trim(coalesce(guarantor_name, '')) <> '' THEN 'one'
|
||||
ELSE 'none'
|
||||
END`
|
||||
|
||||
// Older rows spell some education values differently from the form's options
|
||||
// (higher/secondary vs high/school); fold them so each level is one group.
|
||||
const educationSQL = `
|
||||
CASE lower(trim(coalesce(education, '')))
|
||||
WHEN '' THEN 'unknown'
|
||||
WHEN 'higher' THEN 'high'
|
||||
WHEN 'secondary' THEN 'school'
|
||||
ELSE lower(trim(education))
|
||||
END`
|
||||
|
||||
// Form options are upper case (MARRIED, SINGLE, ...); older rows are lower case.
|
||||
const marriageSQL = `coalesce(nullif(upper(trim(marriage_status)), ''), 'unknown')`
|
||||
|
||||
func (r *repository) Customers(ctx context.Context, f analytics.Filter) (analytics.CustomersDTO, error) {
|
||||
out := analytics.CustomersDTO{
|
||||
AgeGroups: []analytics.ApprovalCountDTO{},
|
||||
Education: []analytics.ApprovalCountDTO{},
|
||||
MarriageStatus: []analytics.ApprovalCountDTO{},
|
||||
Guarantors: []analytics.ApprovalCountDTO{},
|
||||
}
|
||||
if !containsString(f.Types, analytics.OrderLoan) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var err error
|
||||
if out.AgeGroups, err = r.loanApprovalBy(ctx, f, ageGroupSQL); err != nil {
|
||||
return out, err
|
||||
}
|
||||
sortByOrder(out.AgeGroups, ageGroupOrder)
|
||||
if out.Education, err = r.loanApprovalBy(ctx, f, educationSQL); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if out.MarriageStatus, err = r.loanApprovalBy(ctx, f, marriageSQL); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if out.Guarantors, err = r.loanApprovalBy(ctx, f, guarantorsSQL); err != nil {
|
||||
return out, err
|
||||
}
|
||||
sortByOrder(out.Guarantors, []string{"none", "one", "two"})
|
||||
|
||||
// Every order falls in exactly one age group, so its totals are the overall ones.
|
||||
for _, g := range out.AgeGroups {
|
||||
out.Total += g.Count
|
||||
out.Approved += g.Approved
|
||||
out.Rejected += g.Rejected
|
||||
out.Open += g.Open
|
||||
}
|
||||
out.ApprovalRate = ratePtr(out.Approved, out.Approved+out.Rejected)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// loanApprovalBy groups loan orders in range by keyExpr with approved,
|
||||
// rejected and open counts per group.
|
||||
func (r *repository) loanApprovalBy(ctx context.Context, f analytics.Filter, keyExpr string) ([]analytics.ApprovalCountDTO, error) {
|
||||
var args sqlArgs
|
||||
query := fmt.Sprintf(`
|
||||
SELECT k, COUNT(*), COUNT(*) FILTER (WHERE bucket = 'approved'), COUNT(*) FILTER (WHERE bucket = 'rejected'),
|
||||
COUNT(*) FILTER (WHERE bucket = 'open')
|
||||
FROM (
|
||||
SELECT %s AS k, %s AS bucket
|
||||
FROM loan_orders
|
||||
WHERE deleted_at IS NULL%s%s
|
||||
) x
|
||||
GROUP BY k ORDER BY 2 DESC, k`,
|
||||
keyExpr, statusBucketSQL("status"), rangeCond(&args, "created_at", f), branchCond(&args, "branch_id", f))
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []analytics.ApprovalCountDTO{}
|
||||
var total int64
|
||||
for rows.Next() {
|
||||
var it analytics.ApprovalCountDTO
|
||||
if err := rows.Scan(&it.Key, &it.Count, &it.Approved, &it.Rejected, &it.Open); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
it.ApprovalRate = ratePtr(it.Approved, it.Approved+it.Rejected)
|
||||
total += it.Count
|
||||
items = append(items, it)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].Percent = pct(items[i].Count, total)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func sortByOrder(items []analytics.ApprovalCountDTO, order []string) {
|
||||
rank := make(map[string]int, len(order))
|
||||
for i, k := range order {
|
||||
rank[k] = i
|
||||
}
|
||||
sort.SliceStable(items, func(i, j int) bool { return rank[items[i].Key] < rank[items[j].Key] })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- system
|
||||
|
||||
func (r *repository) System(ctx context.Context, f analytics.Filter, opts analytics.SystemOptions) (analytics.SystemDTO, error) {
|
||||
out := analytics.SystemDTO{
|
||||
Operators: []analytics.OperatorActivityDTO{},
|
||||
ModuleErrors: []analytics.ModuleErrorDTO{},
|
||||
PeakHours: []analytics.HeatmapCellDTO{},
|
||||
}
|
||||
|
||||
if opts.Registration {
|
||||
reg, err := r.registrationFunnel(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Registration = ®
|
||||
}
|
||||
|
||||
if opts.Operators {
|
||||
operators, err := r.operators(ctx, f, opts.OperatorLimit)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Operators = operators
|
||||
|
||||
moduleErrors, err := r.moduleErrors(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.ModuleErrors = moduleErrors
|
||||
}
|
||||
|
||||
peak, err := r.peakHours(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.PeakHours = peak
|
||||
|
||||
if opts.CardBalances {
|
||||
cb, err := r.cardBalances(ctx, f)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.CardBalances = &cb
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *repository) registrationFunnel(ctx context.Context, f analytics.Filter) (analytics.RegistrationFunnelDTO, error) {
|
||||
var out analytics.RegistrationFunnelDTO
|
||||
var args sqlArgs
|
||||
query := `
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM users u
|
||||
WHERE u.deleted_at IS NULL
|
||||
AND u.role_id = (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL)` +
|
||||
rangeCond(&args, "u.created_at", f) + `),
|
||||
COUNT(*) FILTER (WHERE v.expires_at < (now() AT TIME ZONE 'UTC')),
|
||||
COUNT(*) FILTER (WHERE v.expires_at >= (now() AT TIME ZONE 'UTC')),
|
||||
COALESCE(SUM(v.attempts), 0)
|
||||
FROM registration_verifications v
|
||||
WHERE true` + rangeCond(&args, "v.created_at", f)
|
||||
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.Completed, &out.Abandoned, &out.WaitingCode, &out.WrongCodeTries); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Started = out.Completed + out.Abandoned + out.WaitingCode
|
||||
out.ConversionPct = ratePtr(out.Completed, out.Started)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// activityUserCond limits activity_logs to users of the caller's branches.
|
||||
func activityUserCond(args *sqlArgs, f analytics.Filter) string {
|
||||
if len(f.BranchIds) == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(` AND EXISTS (SELECT 1 FROM branch_user bu WHERE bu.user_id = a.user_id AND bu.branch_id = ANY(%s) AND bu.deleted_at IS NULL)`,
|
||||
args.add(f.BranchIds))
|
||||
}
|
||||
|
||||
func (r *repository) operators(ctx context.Context, f analytics.Filter, limit int) ([]analytics.OperatorActivityDTO, error) {
|
||||
var args sqlArgs
|
||||
where := rangeCond(&args, "a.created_at", f) + activityUserCond(&args, f)
|
||||
query := fmt.Sprintf(`
|
||||
SELECT a.user_id,
|
||||
MAX(coalesce(nullif(trim(u.first_name || ' ' || u.last_name), ''), nullif(u.name, ''), u.username)),
|
||||
COUNT(*),
|
||||
COUNT(*) FILTER (WHERE a.status_code >= 400),
|
||||
MAX(a.created_at)
|
||||
FROM activity_logs a
|
||||
JOIN users u ON u.id = a.user_id
|
||||
WHERE a.user_id IS NOT NULL%s
|
||||
GROUP BY a.user_id
|
||||
ORDER BY 3 DESC
|
||||
LIMIT %s`, where, args.add(limit))
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []analytics.OperatorActivityDTO{}
|
||||
for rows.Next() {
|
||||
var it analytics.OperatorActivityDTO
|
||||
var last time.Time
|
||||
if err := rows.Scan(&it.UserId, &it.Name, &it.Actions, &it.Errors, &last); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := last.UTC().Format(time.RFC3339)
|
||||
it.LastSeen = &s
|
||||
items = append(items, it)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (r *repository) moduleErrors(ctx context.Context, f analytics.Filter) ([]analytics.ModuleErrorDTO, error) {
|
||||
var args sqlArgs
|
||||
query := `
|
||||
SELECT coalesce(nullif(a.module, ''), 'unknown'), COUNT(*), COUNT(*) FILTER (WHERE a.status_code >= 400)
|
||||
FROM activity_logs a
|
||||
WHERE true` + rangeCond(&args, "a.created_at", f) + activityUserCond(&args, f) + `
|
||||
GROUP BY 1
|
||||
ORDER BY 3 DESC, 2 DESC`
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []analytics.ModuleErrorDTO{}
|
||||
for rows.Next() {
|
||||
var it analytics.ModuleErrorDTO
|
||||
if err := rows.Scan(&it.Module, &it.Requests, &it.Errors); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
it.ErrorRate = pct(it.Errors, it.Requests)
|
||||
items = append(items, it)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
// peakHours counts orders in range by weekday and hour in Ashgabat time
|
||||
// (created_at is stored as UTC wall-clock time).
|
||||
func (r *repository) peakHours(ctx context.Context, f analytics.Filter) ([]analytics.HeatmapCellDTO, error) {
|
||||
var args sqlArgs
|
||||
query := fmt.Sprintf(`
|
||||
WITH o AS (%s), l AS (
|
||||
SELECT (created_at AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Ashgabat' AS ts FROM o
|
||||
)
|
||||
SELECT EXTRACT(ISODOW FROM ts)::int, EXTRACT(HOUR FROM ts)::int, COUNT(*)
|
||||
FROM l GROUP BY 1, 2`, ordersUnionSQL(&args, f, true))
|
||||
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var grid [7][24]int64
|
||||
for rows.Next() {
|
||||
var weekday, hour int
|
||||
var count int64
|
||||
if err := rows.Scan(&weekday, &hour, &count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if weekday >= 1 && weekday <= 7 && hour >= 0 && hour < 24 {
|
||||
grid[weekday-1][hour] = count
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Full 7x24 grid so the heatmap needs no gap filling client-side.
|
||||
cells := make([]analytics.HeatmapCellDTO, 0, 7*24)
|
||||
for d := 0; d < 7; d++ {
|
||||
for h := 0; h < 24; h++ {
|
||||
cells = append(cells, analytics.HeatmapCellDTO{Weekday: d + 1, Hour: h, Count: grid[d][h]})
|
||||
}
|
||||
}
|
||||
return cells, nil
|
||||
}
|
||||
|
||||
func (r *repository) cardBalances(ctx context.Context, f analytics.Filter) (analytics.CardBalanceStatsDTO, error) {
|
||||
out := analytics.CardBalanceStatsDTO{Statuses: []analytics.CountDTO{}}
|
||||
|
||||
var args sqlArgs
|
||||
statuses, err := r.countsByKey(ctx, `
|
||||
SELECT status, COUNT(*) FROM card_balances
|
||||
WHERE deleted_at IS NULL`+rangeCond(&args, "created_at", f)+branchCond(&args, "branch_id", f)+`
|
||||
GROUP BY 1 ORDER BY 2 DESC`, args...)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Statuses = statuses
|
||||
var success, failed int64
|
||||
for _, s := range statuses {
|
||||
switch s.Key {
|
||||
case "success":
|
||||
success = s.Count
|
||||
case "failed":
|
||||
failed = s.Count
|
||||
}
|
||||
}
|
||||
out.FailureRate = ratePtr(failed, success+failed)
|
||||
|
||||
// A card is valid through the last day of its expiry month; this counts
|
||||
// distinct checked cards whose last valid day falls in the next 30 days.
|
||||
args = nil
|
||||
query := `
|
||||
SELECT COUNT(DISTINCT card_number) FROM card_balances
|
||||
WHERE deleted_at IS NULL
|
||||
AND (expiry_at + interval '1 month' - interval '1 day')::date BETWEEN current_date AND current_date + 30` +
|
||||
branchCond(&args, "branch_id", f)
|
||||
if err := r.client.QueryRow(ctx, query, args...).Scan(&out.ExpiringIn30d); err != nil {
|
||||
return out, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
217
internal/analytics/dto.go
Normal file
217
internal/analytics/dto.go
Normal file
@@ -0,0 +1,217 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Filter narrows every analytics query to [From, To) and, for branch-scope
|
||||
// callers, to their branches.
|
||||
type Filter struct {
|
||||
BranchIds []int64
|
||||
// Types are the order types the caller may see; queries over "all
|
||||
// orders" union only these tables.
|
||||
Types []string
|
||||
From time.Time
|
||||
To time.Time // exclusive
|
||||
}
|
||||
|
||||
// Order types: one per customer-facing order table.
|
||||
const (
|
||||
OrderLoan = "loan"
|
||||
OrderLoanLetter = "loan_paid_off_letter"
|
||||
OrderCard = "card"
|
||||
OrderCardPin = "card_pin"
|
||||
OrderCardRekwizit = "card_rekwizit"
|
||||
OrderVisaMaster = "visa_master"
|
||||
)
|
||||
|
||||
type CountDTO struct {
|
||||
Key string `json:"key"`
|
||||
Count int64 `json:"count"`
|
||||
Percent float64 `json:"percent"`
|
||||
}
|
||||
|
||||
// ---- /finance ----
|
||||
|
||||
// PaymentTotalsDTO sums successful payouts only (gateway_status = success).
|
||||
// BankFeeTmt is the bank's own fee; GBÜS and TVEB fees are reported apart
|
||||
// since they go to those parties.
|
||||
type PaymentTotalsDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
AmountTmt float64 `json:"amountTmt"`
|
||||
BankFeeTmt float64 `json:"bankFeeTmt"`
|
||||
GbusFeeTmt float64 `json:"gbusFeeTmt"`
|
||||
TvebFeeTmt float64 `json:"tvebFeeTmt"`
|
||||
TotalTmt float64 `json:"totalTmt"`
|
||||
AvgTotalTmt float64 `json:"avgTotalTmt"`
|
||||
}
|
||||
|
||||
type FinanceMonthDTO struct {
|
||||
Month string `json:"month"` // YYYY-MM
|
||||
Count int64 `json:"count"`
|
||||
TotalTmt float64 `json:"totalTmt"`
|
||||
BankFeeTmt float64 `json:"bankFeeTmt"`
|
||||
}
|
||||
|
||||
// LoanRequestedDTO sums loan_orders.loan_amount, a free-text column; rows
|
||||
// whose amount does not parse as a number are counted in Unparsed.
|
||||
type LoanRequestedDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
TotalTmt float64 `json:"totalTmt"`
|
||||
AvgTmt float64 `json:"avgTmt"`
|
||||
Unparsed int64 `json:"unparsed"`
|
||||
}
|
||||
|
||||
type FinanceDTO struct {
|
||||
Payments PaymentTotalsDTO `json:"payments"`
|
||||
Gateway []CountDTO `json:"gateway"`
|
||||
GatewaySuccessRate *float64 `json:"gatewaySuccessRate"`
|
||||
Monthly []FinanceMonthDTO `json:"monthly"`
|
||||
LoanRequested LoanRequestedDTO `json:"loanRequested"`
|
||||
}
|
||||
|
||||
// ---- /backlog ----
|
||||
|
||||
// BacklogDTO is one order type's open queue, aged by created_at, plus the
|
||||
// average time finished orders took (updated_at - created_at, so any later
|
||||
// edit makes it an upper bound rather than an exact figure).
|
||||
type BacklogDTO struct {
|
||||
Type string `json:"type"`
|
||||
Open int64 `json:"open"`
|
||||
Under1Day int64 `json:"under1Day"`
|
||||
From1To3Days int64 `json:"from1To3Days"`
|
||||
Over3Days int64 `json:"over3Days"`
|
||||
OldestOpenAt *string `json:"oldestOpenAt"`
|
||||
OldestOpenDays *float64 `json:"oldestOpenDays"`
|
||||
Finished int64 `json:"finished"`
|
||||
AvgProcessHours *float64 `json:"avgProcessHours"`
|
||||
}
|
||||
|
||||
// VisaMasterTimingDTO is exact payout timing from visa_master_payment_logs:
|
||||
// first logged step to payment_finalized, per order.
|
||||
type VisaMasterTimingDTO struct {
|
||||
Orders int64 `json:"orders"`
|
||||
AvgMinutes *float64 `json:"avgMinutes"`
|
||||
P90Minutes *float64 `json:"p90Minutes"`
|
||||
MaxMinutes *float64 `json:"maxMinutes"`
|
||||
}
|
||||
|
||||
type BacklogResponseDTO struct {
|
||||
Items []BacklogDTO `json:"items"`
|
||||
VisaMasterTiming VisaMasterTimingDTO `json:"visaMasterTiming"`
|
||||
}
|
||||
|
||||
// ---- /branches ----
|
||||
|
||||
type BranchStatDTO struct {
|
||||
BranchId int64 `json:"branchId"`
|
||||
Name json.RawMessage `json:"name"`
|
||||
Region string `json:"region"`
|
||||
Orders map[string]int64 `json:"orders"`
|
||||
Total int64 `json:"total"`
|
||||
Open int64 `json:"open"`
|
||||
Approved int64 `json:"approved"`
|
||||
Rejected int64 `json:"rejected"`
|
||||
ApprovalRate *float64 `json:"approvalRate"`
|
||||
AvgProcessHours *float64 `json:"avgProcessHours"`
|
||||
}
|
||||
|
||||
type BranchesDTO struct {
|
||||
Branches []BranchStatDTO `json:"branches"`
|
||||
Regions []CountDTO `json:"regions"`
|
||||
}
|
||||
|
||||
// ---- /products ----
|
||||
|
||||
type NamedCountDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Name json.RawMessage `json:"name"`
|
||||
Count int64 `json:"count"`
|
||||
Percent float64 `json:"percent"`
|
||||
}
|
||||
|
||||
type ProductsDTO struct {
|
||||
LoanSources []CountDTO `json:"loanSources"`
|
||||
LoanTypes []NamedCountDTO `json:"loanTypes"`
|
||||
CardTypes []NamedCountDTO `json:"cardTypes"`
|
||||
CardOrderPay []CountDTO `json:"cardOrderPay"` // paid / unpaid
|
||||
}
|
||||
|
||||
// ---- /customers ----
|
||||
|
||||
// ApprovalCountDTO is a CountDTO plus how many of those loan orders were
|
||||
// approved / rejected / still open, so the UI can show approval rate per group.
|
||||
type ApprovalCountDTO struct {
|
||||
Key string `json:"key"`
|
||||
Count int64 `json:"count"`
|
||||
Percent float64 `json:"percent"`
|
||||
Approved int64 `json:"approved"`
|
||||
Rejected int64 `json:"rejected"`
|
||||
Open int64 `json:"open"`
|
||||
ApprovalRate *float64 `json:"approvalRate"`
|
||||
}
|
||||
|
||||
type CustomersDTO struct {
|
||||
Total int64 `json:"total"`
|
||||
Approved int64 `json:"approved"`
|
||||
Rejected int64 `json:"rejected"`
|
||||
Open int64 `json:"open"`
|
||||
ApprovalRate *float64 `json:"approvalRate"`
|
||||
AgeGroups []ApprovalCountDTO `json:"ageGroups"`
|
||||
Education []ApprovalCountDTO `json:"education"`
|
||||
MarriageStatus []ApprovalCountDTO `json:"marriageStatus"`
|
||||
Guarantors []ApprovalCountDTO `json:"guarantors"` // none / one / two
|
||||
}
|
||||
|
||||
// ---- /system ----
|
||||
|
||||
// RegistrationFunnelDTO: a verification row is deleted once registration
|
||||
// completes, so Completed counts new customer accounts and the rows still
|
||||
// present are unfinished. Password resets reuse the same table, so
|
||||
// Abandoned/WaitingCode slightly overcount registrations.
|
||||
type RegistrationFunnelDTO struct {
|
||||
Started int64 `json:"started"`
|
||||
Completed int64 `json:"completed"`
|
||||
Abandoned int64 `json:"abandoned"` // code expired, never finished
|
||||
WaitingCode int64 `json:"waitingCode"` // code still valid
|
||||
WrongCodeTries int64 `json:"wrongCodeTries"`
|
||||
ConversionPct *float64 `json:"conversionPct"`
|
||||
}
|
||||
|
||||
type OperatorActivityDTO struct {
|
||||
UserId int64 `json:"userId"`
|
||||
Name string `json:"name"`
|
||||
Actions int64 `json:"actions"`
|
||||
Errors int64 `json:"errors"`
|
||||
LastSeen *string `json:"lastSeen"`
|
||||
}
|
||||
|
||||
type ModuleErrorDTO struct {
|
||||
Module string `json:"module"`
|
||||
Requests int64 `json:"requests"`
|
||||
Errors int64 `json:"errors"`
|
||||
ErrorRate float64 `json:"errorRate"`
|
||||
}
|
||||
|
||||
// HeatmapCellDTO: Weekday is Monday=1 .. Sunday=7, Hour is 0..23, both in
|
||||
// Asia/Ashgabat time.
|
||||
type HeatmapCellDTO struct {
|
||||
Weekday int `json:"weekday"`
|
||||
Hour int `json:"hour"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
type CardBalanceStatsDTO struct {
|
||||
Statuses []CountDTO `json:"statuses"`
|
||||
FailureRate *float64 `json:"failureRate"`
|
||||
ExpiringIn30d int64 `json:"expiringIn30d"`
|
||||
}
|
||||
|
||||
type SystemDTO struct {
|
||||
Registration *RegistrationFunnelDTO `json:"registration"`
|
||||
Operators []OperatorActivityDTO `json:"operators"`
|
||||
ModuleErrors []ModuleErrorDTO `json:"moduleErrors"`
|
||||
PeakHours []HeatmapCellDTO `json:"peakHours"`
|
||||
CardBalances *CardBalanceStatsDTO `json:"cardBalances"`
|
||||
}
|
||||
266
internal/analytics/handler.go
Normal file
266
internal/analytics/handler.go
Normal file
@@ -0,0 +1,266 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Lives under the dashboard URL but is its own module; rbac picks the
|
||||
// longest registered prefix, so this group's policy applies here.
|
||||
const baseURL = "/dashboard/analytics"
|
||||
|
||||
const (
|
||||
dateLayout = "2006-01-02"
|
||||
maxRangeDays = 366 * 3
|
||||
defaultOperatorLimit = 10
|
||||
maxOperatorLimit = 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 := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard))
|
||||
group.GET("/finance", h.finance)
|
||||
group.GET("/backlog", h.backlog)
|
||||
group.GET("/branches", h.branches)
|
||||
group.GET("/products", h.products)
|
||||
group.GET("/customers", h.customers)
|
||||
group.GET("/system", h.system)
|
||||
}
|
||||
|
||||
// finance godoc
|
||||
// @Summary Dashboard analytics: finance
|
||||
// @Description Successful visa/master payouts (amount, bank/GBÜS/TVEB fees), gateway status breakdown and success rate, monthly payout totals, and the total loan amount requested. Payouts need the cards permission, the loan total the loans permission.
|
||||
// @Tags dashboard-analytics
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
|
||||
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/analytics/finance [get]
|
||||
func (h *handler) finance(c *gin.Context) {
|
||||
filter, ok := h.parseFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.repository.Finance(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.fail(c, "finance", err)
|
||||
return
|
||||
}
|
||||
if !rbac.Can(c, perm.Cards) {
|
||||
result.Payments = PaymentTotalsDTO{}
|
||||
result.Gateway = []CountDTO{}
|
||||
result.GatewaySuccessRate = nil
|
||||
result.Monthly = []FinanceMonthDTO{}
|
||||
}
|
||||
if !rbac.Can(c, perm.Loans) {
|
||||
result.LoanRequested = LoanRequestedDTO{}
|
||||
}
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// backlog godoc
|
||||
// @Summary Dashboard analytics: backlog
|
||||
// @Description Open (unhandled) orders per order type aged under 1 day / 1-3 days / over 3 days, the oldest open order, and the average processing time of orders finished in range; plus exact visa/master payout timing from the payment log. Order types are limited to the modules the caller can open.
|
||||
// @Tags dashboard-analytics
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
|
||||
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/analytics/backlog [get]
|
||||
func (h *handler) backlog(c *gin.Context) {
|
||||
filter, ok := h.parseFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.repository.Backlog(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.fail(c, "backlog", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// branches godoc
|
||||
// @Summary Dashboard analytics: branches
|
||||
// @Description Per-branch leaderboard (orders per type, open/approved/rejected, approval rate, average processing hours) and order counts per region, for orders created in range.
|
||||
// @Tags dashboard-analytics
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
|
||||
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/analytics/branches [get]
|
||||
func (h *handler) branches(c *gin.Context) {
|
||||
filter, ok := h.parseFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.repository.Branches(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.fail(c, "branches", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// products godoc
|
||||
// @Summary Dashboard analytics: products
|
||||
// @Description Loan orders by source (web/mobile) and loan type, card orders by card type, and paid vs unpaid card orders, for orders created in range.
|
||||
// @Tags dashboard-analytics
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
|
||||
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/analytics/products [get]
|
||||
func (h *handler) products(c *gin.Context) {
|
||||
filter, ok := h.parseFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.repository.Products(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.fail(c, "products", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// customers godoc
|
||||
// @Summary Dashboard analytics: customers
|
||||
// @Description Loan applicants in range by age group, education, marriage status and number of guarantors, each with its approval rate. Needs the loans permission.
|
||||
// @Tags dashboard-analytics
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
|
||||
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/analytics/customers [get]
|
||||
func (h *handler) customers(c *gin.Context) {
|
||||
filter, ok := h.parseFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result, err := h.repository.Customers(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.fail(c, "customers", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// system godoc
|
||||
// @Summary Dashboard analytics: system
|
||||
// @Description Registration funnel (all-scope callers with the users permission), operator activity and error rate per module (activity-logs permission), order peak hours heatmap in Ashgabat time, and card balance check stats (cards permission). Widgets the caller cannot see are null or empty.
|
||||
// @Tags dashboard-analytics
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year)
|
||||
// @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today)
|
||||
// @Param operator_limit query int false "Number of operators to return" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/analytics/system [get]
|
||||
func (h *handler) system(c *gin.Context) {
|
||||
filter, ok := h.parseFilter(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
opts := SystemOptions{
|
||||
// Registrations are not tied to a branch, so branch-scope callers
|
||||
// would otherwise see bank-wide numbers.
|
||||
Registration: rbac.Can(c, perm.Users) && len(filter.BranchIds) == 0,
|
||||
Operators: rbac.Can(c, perm.ActivityLogs),
|
||||
CardBalances: rbac.Can(c, perm.Cards),
|
||||
OperatorLimit: defaultOperatorLimit,
|
||||
}
|
||||
if raw := c.Query("operator_limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
opts.OperatorLimit = min(limit, maxOperatorLimit)
|
||||
}
|
||||
|
||||
result, err := h.repository.System(c.Request.Context(), filter, opts)
|
||||
if err != nil {
|
||||
h.fail(c, "system", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
func (h *handler) fail(c *gin.Context, widget string, err error) {
|
||||
h.logger.Errorf("dashboard analytics %s failed: %v", widget, err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
}
|
||||
|
||||
// parseFilter reads from/to (inclusive dates, default: this year so far),
|
||||
// the caller's branch scope, and the order types their permissions allow.
|
||||
// It writes the 400 itself and returns false on bad input.
|
||||
func (h *handler) parseFilter(c *gin.Context) (Filter, bool) {
|
||||
now := time.Now().UTC()
|
||||
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
|
||||
from := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
to := today
|
||||
|
||||
var err error
|
||||
if raw := c.Query("from"); raw != "" {
|
||||
if from, err = time.Parse(dateLayout, raw); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return Filter{}, false
|
||||
}
|
||||
}
|
||||
if raw := c.Query("to"); raw != "" {
|
||||
if to, err = time.Parse(dateLayout, raw); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return Filter{}, false
|
||||
}
|
||||
}
|
||||
if to.Before(from) || to.Sub(from) > maxRangeDays*24*time.Hour {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return Filter{}, false
|
||||
}
|
||||
|
||||
filter := Filter{From: from, To: to.AddDate(0, 0, 1)}
|
||||
if rbac.Can(c, perm.Loans) {
|
||||
filter.Types = append(filter.Types, OrderLoan, OrderLoanLetter)
|
||||
}
|
||||
if rbac.Can(c, perm.Cards) {
|
||||
filter.Types = append(filter.Types, OrderCard, OrderCardPin, OrderCardRekwizit, OrderVisaMaster)
|
||||
}
|
||||
rbac.BindBranchIDs(c, &filter.BranchIds)
|
||||
return filter, true
|
||||
}
|
||||
21
internal/analytics/storage.go
Normal file
21
internal/analytics/storage.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package analytics
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Finance(ctx context.Context, filter Filter) (FinanceDTO, error)
|
||||
Backlog(ctx context.Context, filter Filter) (BacklogResponseDTO, error)
|
||||
Branches(ctx context.Context, filter Filter) (BranchesDTO, error)
|
||||
Products(ctx context.Context, filter Filter) (ProductsDTO, error)
|
||||
Customers(ctx context.Context, filter Filter) (CustomersDTO, error)
|
||||
System(ctx context.Context, filter Filter, opts SystemOptions) (SystemDTO, error)
|
||||
}
|
||||
|
||||
// SystemOptions says which /system widgets the caller may see, so the
|
||||
// repository skips queries whose result would be redacted anyway.
|
||||
type SystemOptions struct {
|
||||
Registration bool
|
||||
Operators bool
|
||||
CardBalances bool
|
||||
OperatorLimit int
|
||||
}
|
||||
@@ -7,10 +7,16 @@ var (
|
||||
ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002")
|
||||
ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003")
|
||||
ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004")
|
||||
ErrForbidden = NewAppError(nil, "Sana rugsat yok.", "SE-00011")
|
||||
ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007")
|
||||
ErrConflict = NewAppError(nil, "A user with this phone or username already exists.", "SE-00008")
|
||||
ErrInvalidCode = NewAppError(nil, "Invalid or expired verification code.", "SE-00009")
|
||||
ErrPasswordMismatch = NewAppError(nil, "Password confirmation does not match.", "SE-00010")
|
||||
ErrDuplicate = NewAppError(nil, "A record with these values already exists.", "SE-00012")
|
||||
ErrRoleInUse = NewAppError(nil, "The role is still assigned to users.", "SE-00013")
|
||||
ErrLastSuperadmin = NewAppError(nil, "The last superadmin cannot be removed or demoted.", "SE-00014")
|
||||
ErrUnknownRole = NewAppError(nil, "Role not found.", "SE-00015")
|
||||
ErrSystemRole = NewAppError(nil, "System roles cannot be deleted or have their scope changed.", "SE-00016")
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
|
||||
217
internal/backup/db/postgresql.go
Normal file
217
internal/backup/db/postgresql.go
Normal file
@@ -0,0 +1,217 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/backup"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[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 backupFromClause = ` FROM backups b
|
||||
LEFT JOIN users u ON u.id = b.created_by`
|
||||
|
||||
var backupSelectColumns = shared.PrefixedColumns("b", backupColumns) + `,
|
||||
` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
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{}) {
|
||||
conditions := []string{"b.deleted_at IS NULL"}
|
||||
|
||||
if filter.Search != "" {
|
||||
args = append(args, shared.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)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
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 AND b.deleted_at IS NULL`
|
||||
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
41
internal/backup/dto.go
Normal 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
55
internal/backup/dump.go
Normal 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
|
||||
}
|
||||
206
internal/backup/handler.go
Normal file
206
internal/backup/handler.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"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 := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Backups))
|
||||
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 := shared.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 := shared.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 := shared.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
|
||||
}
|
||||
69
internal/backup/http.go
Normal file
69
internal/backup/http.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
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 = shared.DefaultPage
|
||||
limit = shared.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 > shared.MaxLimit {
|
||||
l = shared.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
154
internal/backup/service.go
Normal 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
|
||||
}
|
||||
24
internal/backup/service_test.go
Normal file
24
internal/backup/service_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
12
internal/backup/storage.go
Normal file
12
internal/backup/storage.go
Normal 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)
|
||||
}
|
||||
251
internal/cards/cardbalance/db/postgresql.go
Normal file
251
internal/cards/cardbalance/db/postgresql.go
Normal file
@@ -0,0 +1,251 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardbalance"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/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",
|
||||
"branch_id", "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", "branch_id", "created_by",
|
||||
}
|
||||
|
||||
var cardBalanceWritableColumnsSQL = strings.Join(cardBalanceWritableColumns, ", ")
|
||||
|
||||
const cardBalanceFromClause = ` FROM card_balances cb
|
||||
LEFT JOIN users u ON u.id = cb.created_by
|
||||
LEFT JOIN branches b ON b.id = cb.branch_id`
|
||||
|
||||
var cardBalanceSelectColumns = shared.PrefixedColumns("cb", cardBalanceColumns) + `,
|
||||
COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, ''), ` + shared.UserDisplaySQL + `, b.name`
|
||||
|
||||
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.BranchId), 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.BranchId), 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)))
|
||||
}
|
||||
|
||||
if len(filter.BranchIds) > 0 {
|
||||
conditions, args = rbac.AppendBranchIDs(conditions, args, "cb.branch_id", filter.BranchIds)
|
||||
} else if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("cb.branch_id = $%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
|
||||
LEFT JOIN branches b ON b.id = cb.branch_id`,
|
||||
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
|
||||
LEFT JOIN branches b ON b.id = cb.branch_id`,
|
||||
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 branchID sql.NullInt64
|
||||
var branchNameJSON []byte
|
||||
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,
|
||||
&branchID, &item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
|
||||
&userUsername, &userPhone, &userEmail, &userName, &branchNameJSON,
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cardbalance.CardBalanceDTO{}, err
|
||||
}
|
||||
|
||||
if branchID.Valid {
|
||||
item.BranchId = branchID.Int64
|
||||
var branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return cardbalance.CardBalanceDTO{}, err
|
||||
}
|
||||
item.Branch = &shared.NamedInfo{Id: item.BranchId, Name: branchName}
|
||||
}
|
||||
|
||||
if item.CreatedById != nil {
|
||||
item.CreatedBy = &shared.UserInfo{
|
||||
Id: *item.CreatedById,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
67
internal/cards/cardbalance/dto.go
Normal file
67
internal/cards/cardbalance/dto.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package cardbalance
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/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"`
|
||||
BranchId int64 `json:"-"`
|
||||
Branch *shared.NamedInfo `json:"branch,omitempty"`
|
||||
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"`
|
||||
BranchId *shared.FlexibleInt64 `json:"branchId" swaggertype:"integer"`
|
||||
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"`
|
||||
BranchId *shared.FlexibleInt64 `json:"branchId" swaggertype:"integer"`
|
||||
CreatedBy *shared.FlexibleInt64 `json:"createdBy" swaggertype:"integer"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
PassportNumber string
|
||||
CreatedBy *int64
|
||||
BranchId *int64
|
||||
BranchIds []int64
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardBalanceDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardBalances []CardBalanceDTO `json:"cardBalances"`
|
||||
}
|
||||
260
internal/cards/cardbalance/handler.go
Normal file
260
internal/cards/cardbalance/handler.go
Normal file
@@ -0,0 +1,260 @@
|
||||
package cardbalance
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"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 := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
|
||||
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
|
||||
}
|
||||
if !rbac.GuardOrder(c, item.CreatedById, item.BranchId) {
|
||||
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
|
||||
}
|
||||
|
||||
if !h.guardCardBalanceByID(c, id) {
|
||||
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 !h.guardCardBalanceByID(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 balance failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card balance removed"))
|
||||
}
|
||||
|
||||
func (h *handler) guardCardBalanceByID(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.CreatedById, item.BranchId)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if id, ok := shared.OptionalQueryID(c, "branch_id", "branchId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.BranchId = id
|
||||
}
|
||||
|
||||
rbac.BindBranchIDs(c, &filter.BranchIds)
|
||||
return filter, true
|
||||
}
|
||||
11
internal/cards/cardbalance/storage.go
Normal file
11
internal/cards/cardbalance/storage.go
Normal 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
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardorder"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -25,8 +27,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.R
|
||||
}
|
||||
}
|
||||
|
||||
// cardOrderWritableColumns lists every card_orders column except id, created_at and
|
||||
// updated_at, in the exact order CreateCardOrderDTO/UpdateCardOrderDTO fields are read.
|
||||
var cardOrderWritableColumns = []string{
|
||||
"unique_id", "card_state_id", "card_type_id", "region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "old_surname", "citizenship",
|
||||
@@ -41,6 +41,22 @@ var cardOrderColumnsSQL = strings.Join(cardOrderColumns, ", ")
|
||||
|
||||
var cardOrderWritableColumnsSQL = strings.Join(cardOrderWritableColumns, ", ")
|
||||
|
||||
const cardOrderFromClause = ` FROM card_orders co
|
||||
LEFT JOIN card_states cs ON cs.id = co.card_state_id
|
||||
LEFT JOIN card_types ct ON ct.id = co.card_type_id
|
||||
LEFT JOIN branches b ON b.id = co.branch_id
|
||||
LEFT JOIN users u ON u.id = co.user_id`
|
||||
|
||||
var cardOrderSelectColumns = shared.PrefixedColumns("co", cardOrderColumns) + `,
|
||||
cs.name, ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
const cardOrderListFromClause = cardOrderFromClause + `
|
||||
LEFT JOIN provinces bp ON bp.id = b.province_id`
|
||||
|
||||
var cardOrderListColumns = `co.id, co.unique_id, co.customer_name, co.customer_surname, co.customer_patronic_name,
|
||||
co.phone, co.card_type_id, ct.name, co.card_state_id, cs.name, co.branch_id, b.name, bp.name, co.region,
|
||||
co.passport_serie, co.passport_id, co.user_id, ` + shared.UserDisplaySQL + `, co.status, co.paid, co.created_at`
|
||||
|
||||
func resolveStatus(status *string) *string {
|
||||
if status == nil || strings.TrimSpace(*status) == "" {
|
||||
pending := "pending"
|
||||
@@ -58,77 +74,102 @@ func resolvePaid(paid *bool) bool {
|
||||
|
||||
func createArgs(dto cardorder.CreateCardOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, resolvePaid(dto.Paid),
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, shared.OptionalInt64(dto.UserId), resolvePaid(dto.Paid),
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.CardStateId, dto.CardTypeId, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt, dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.UniqueId, dto.CardStateId.Int64(), dto.CardTypeId.Int64(), dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.OldSurname, dto.Citizenship,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportGivenAt.Time(), dto.PassportGivenBy, dto.BornPlace,
|
||||
dto.JobLocation, dto.PassportAddress, dto.RealAddress, dto.Phone, dto.PhoneAdditional,
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, dto.UserId, dto.Paid,
|
||||
resolveStatus(dto.Status), dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour, dto.Notes, shared.OptionalInt64(dto.UserId), dto.Paid,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_orders co`+whereClause, args...).Scan(&count); err != nil {
|
||||
return cardorder.ListCardOrderDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY co.id LIMIT $%d OFFSET $%d`,
|
||||
cardOrderListColumns, cardOrderListFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return cardorder.ListCardOrderDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []cardorder.CardOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanCardOrderListItem(rows)
|
||||
if err != nil {
|
||||
return cardorder.ListCardOrderDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return cardorder.ListCardOrderDTO{}, err
|
||||
}
|
||||
|
||||
return cardorder.ListCardOrderDTO{Count: count, CardOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardorder.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"co.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("co.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
if len(filter.BranchIds) > 0 {
|
||||
conditions, args = rbac.AppendBranchIDs(conditions, args, "co.branch_id", filter.BranchIds)
|
||||
} else if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("co.branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("co.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardStateId != nil {
|
||||
args = append(args, *filter.CardStateId)
|
||||
conditions = append(conditions, fmt.Sprintf("card_state_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("co.card_state_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardTypeId != nil {
|
||||
args = append(args, *filter.CardTypeId)
|
||||
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("co.card_type_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
conditions = append(conditions, fmt.Sprintf("co.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
query := `SELECT ` + cardOrderSelectColumns + cardOrderFromClause + ` WHERE co.id = $1 AND co.deleted_at IS NULL`
|
||||
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDTO) (cardorder.CardOrderDTO, error) {
|
||||
@@ -139,12 +180,22 @@ func (r *repository) Create(ctx context.Context, dto cardorder.CreateCardOrderDT
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO card_orders (%s) VALUES (%s) RETURNING %s`,
|
||||
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardOrderColumnsSQL,
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO card_orders (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted co
|
||||
LEFT JOIN card_states cs ON cs.id = co.card_state_id
|
||||
LEFT JOIN card_types ct ON ct.id = co.card_type_id
|
||||
LEFT JOIN branches b ON b.id = co.branch_id
|
||||
LEFT JOIN users u ON u.id = co.user_id`,
|
||||
cardOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
cardOrderColumnsSQL, cardOrderSelectColumns,
|
||||
)
|
||||
|
||||
return scanCardOrder(r.client.QueryRow(ctx, query, args...))
|
||||
return scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateCardOrderDTO) (cardorder.CardOrderDTO, error) {
|
||||
@@ -156,12 +207,22 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateC
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL,
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated co
|
||||
LEFT JOIN card_states cs ON cs.id = co.card_state_id
|
||||
LEFT JOIN card_types ct ON ct.id = co.card_type_id
|
||||
LEFT JOIN branches b ON b.id = co.branch_id
|
||||
LEFT JOIN users u ON u.id = co.user_id`,
|
||||
strings.Join(assignments, ", "), len(args), cardOrderColumnsSQL, cardOrderSelectColumns,
|
||||
)
|
||||
|
||||
item, err := scanCardOrder(r.client.QueryRow(ctx, query, args...))
|
||||
item, err := scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
@@ -173,17 +234,110 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
}
|
||||
|
||||
func scanCardOrder(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
|
||||
return scanCardOrderRow(row, false)
|
||||
}
|
||||
|
||||
func scanCardOrderListItem(row genericrepo.Scanner) (cardorder.CardOrderListItemDTO, error) {
|
||||
var item cardorder.CardOrderListItemDTO
|
||||
var cardTypeId, cardStateId, branchId int64
|
||||
var userId *int64
|
||||
var cardTypeNameJSON, cardStateNameJSON, branchNameJSON, provinceNameJSON []byte
|
||||
var userName string
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName,
|
||||
&item.Phone, &cardTypeId, &cardTypeNameJSON, &cardStateId, &cardStateNameJSON, &branchId, &branchNameJSON, &provinceNameJSON, &item.Region,
|
||||
&item.PassportSerie, &item.PassportId, &userId, &userName, &item.Status, &item.Paid, &item.CreatedAt,
|
||||
); err != nil {
|
||||
return cardorder.CardOrderListItemDTO{}, err
|
||||
}
|
||||
|
||||
var cardTypeName, cardStateName, branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
||||
return cardorder.CardOrderListItemDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(cardStateNameJSON, &cardStateName); err != nil {
|
||||
return cardorder.CardOrderListItemDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return cardorder.CardOrderListItemDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
||||
return cardorder.CardOrderListItemDTO{}, err
|
||||
}
|
||||
if cardTypeId != 0 {
|
||||
item.CardType = &shared.NamedInfo{Id: cardTypeId, Name: cardTypeName}
|
||||
}
|
||||
if cardStateId != 0 {
|
||||
item.CardState = &shared.NamedInfo{Id: cardStateId, Name: cardStateName}
|
||||
}
|
||||
if branchId != 0 {
|
||||
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
|
||||
}
|
||||
if userId != nil {
|
||||
item.User = &cardorder.ListUserDTO{Id: *userId, Name: userName}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func scanCardOrderWithJoins(row genericrepo.Scanner) (cardorder.CardOrderDTO, error) {
|
||||
return scanCardOrderRow(row, true)
|
||||
}
|
||||
|
||||
func scanCardOrderRow(row genericrepo.Scanner, withJoins bool) (cardorder.CardOrderDTO, error) {
|
||||
var item cardorder.CardOrderDTO
|
||||
err := row.Scan(
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.UniqueId, &item.CardStateId, &item.CardTypeId, &item.Region, &item.BranchId,
|
||||
&item.CustomerName, &item.CustomerSurname, &item.CustomerPatronicName, &item.BornAt, &item.OldSurname, &item.Citizenship,
|
||||
&item.PassportSerie, &item.PassportId, &item.PassportGivenAt, &item.PassportGivenBy, &item.BornPlace,
|
||||
&item.JobLocation, &item.PassportAddress, &item.RealAddress, &item.Phone, &item.PhoneAdditional,
|
||||
&item.Status, &item.PassportOne, &item.PassportTwo, &item.PassportThree, &item.PassportFour, &item.Notes, &item.UserId, &item.Paid,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
}
|
||||
|
||||
var cardStateNameJSON, cardTypeNameJSON, branchNameJSON []byte
|
||||
var userName, userUsername, userPhone, userEmail string
|
||||
if withJoins {
|
||||
dest = append(dest,
|
||||
&cardStateNameJSON, &cardTypeNameJSON, &branchNameJSON,
|
||||
&userName, &userUsername, &userPhone, &userEmail,
|
||||
)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
if !withJoins {
|
||||
return item, nil
|
||||
}
|
||||
|
||||
var cardStateName, cardTypeName, branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(cardStateNameJSON, &cardStateName); err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return cardorder.CardOrderDTO{}, err
|
||||
}
|
||||
if item.CardStateId != 0 {
|
||||
item.CardState = &shared.NamedInfo{Id: item.CardStateId, Name: cardStateName}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,109 +1,118 @@
|
||||
package cardorder
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type CardOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"cardStateId"`
|
||||
CardTypeId int64 `json:"cardTypeId"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt"`
|
||||
PassportGivenBy string `json:"passportGivenBy"`
|
||||
BornPlace string `json:"bornPlace"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Paid bool `json:"paid"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"-"`
|
||||
CardState *shared.NamedInfo `json:"cardState,omitempty"`
|
||||
CardTypeId int64 `json:"-"`
|
||||
CardType *shared.NamedInfo `json:"cardType,omitempty"`
|
||||
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"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt"`
|
||||
PassportGivenBy string `json:"passportGivenBy"`
|
||||
BornPlace string `json:"bornPlace"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne"`
|
||||
PassportTwo string `json:"passportTwo"`
|
||||
PassportThree string `json:"passportThree"`
|
||||
PassportFour string `json:"passportFour"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"-"`
|
||||
User *shared.UserInfo `json:"user,omitempty"`
|
||||
Paid bool `json:"paid"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateCardOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"cardStateId" binding:"required"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Paid *bool `json:"paid"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
|
||||
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
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" swaggertype:"string" format:"date"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
Paid *bool `json:"paid"`
|
||||
}
|
||||
|
||||
type UpdateCardOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId int64 `json:"cardStateId" binding:"required"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt time.Time `json:"passportGivenAt" binding:"required"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Paid bool `json:"paid"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardStateId shared.FlexibleInt64 `json:"cardStateId" binding:"required" swaggertype:"integer"`
|
||||
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
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" swaggertype:"string" format:"date"`
|
||||
OldSurname *string `json:"oldSurname"`
|
||||
Citizenship string `json:"citizenship" binding:"required"`
|
||||
PassportSerie string `json:"passportSerie" binding:"required"`
|
||||
PassportId string `json:"passportId" binding:"required"`
|
||||
PassportGivenAt shared.FlexibleTime `json:"passportGivenAt" swaggertype:"string" format:"date"`
|
||||
PassportGivenBy string `json:"passportGivenBy" binding:"required"`
|
||||
BornPlace string `json:"bornPlace" binding:"required"`
|
||||
JobLocation *string `json:"jobLocation"`
|
||||
PassportAddress *string `json:"passportAddress"`
|
||||
RealAddress *string `json:"realAddress"`
|
||||
Phone *string `json:"phone"`
|
||||
PhoneAdditional *string `json:"phoneAdditional"`
|
||||
Status *string `json:"status"`
|
||||
PassportOne string `json:"passportOne" binding:"required"`
|
||||
PassportTwo string `json:"passportTwo" binding:"required"`
|
||||
PassportThree string `json:"passportThree" binding:"required"`
|
||||
PassportFour string `json:"passportFour" binding:"required"`
|
||||
Notes *string `json:"notes"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
Paid bool `json:"paid"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status *string
|
||||
BranchId *int64
|
||||
BranchIds []int64
|
||||
UserId *int64
|
||||
CardStateId *int64
|
||||
CardTypeId *int64
|
||||
@@ -112,7 +121,35 @@ type ListFilter struct {
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardOrders []CardOrderDTO `json:"cardOrders"`
|
||||
// CardOrderListItemDTO is the list row; addresses, passport issue details
|
||||
// and scans come from GET /card-orders/:id.
|
||||
type CardOrderListItemDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
Phone *string `json:"phone"`
|
||||
CardType *shared.NamedInfo `json:"cardType,omitempty"`
|
||||
CardState *shared.NamedInfo `json:"cardState,omitempty"`
|
||||
Branch *shared.NamedInfo `json:"branch,omitempty"`
|
||||
// ProvinceName is the branch's province (etrap).
|
||||
ProvinceName shared.LocalizedText `json:"provinceName"`
|
||||
Region string `json:"region"`
|
||||
PassportSerie string `json:"passportSerie"`
|
||||
PassportId string `json:"passportId"`
|
||||
User *ListUserDTO `json:"user,omitempty"`
|
||||
Status *string `json:"status"`
|
||||
Paid bool `json:"paid"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type ListUserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ListCardOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardOrders []CardOrderListItemDTO `json:"cardOrders"`
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@ package cardorder
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
@@ -82,7 +83,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -98,6 +99,9 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
@@ -116,7 +120,8 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
// @Router /card-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateCardOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||
h.logger.Errorf("create card order bind failed: %v", err)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
@@ -146,14 +151,19 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if !h.guardBranchByID(c, id) {
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateCardOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||
h.logger.Errorf("update card order bind failed: %v", err)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
@@ -185,12 +195,16 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-orders/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
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
|
||||
@@ -203,81 +217,61 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card order removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
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 raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
if id, ok := shared.OptionalQueryID(c, "card_state_id", "cardStateId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.CardStateId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_state_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardStateId = &id
|
||||
if id, ok := shared.OptionalQueryID(c, "card_type_id", "cardTypeId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.CardTypeId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("card_type_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardTypeId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
if raw := shared.QueryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); 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)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardpinorders"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -25,8 +27,6 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorde
|
||||
}
|
||||
}
|
||||
|
||||
// cardPinOrderWritableColumns lists every card_pin_orders column except id, created_at and
|
||||
// updated_at, in the exact order CreateCardPinOrderDTO/UpdateCardPinOrderDTO fields are read.
|
||||
var cardPinOrderWritableColumns = []string{
|
||||
"unique_id", "user_id", "card_type_id", "card_number", "region", "branch_id",
|
||||
"customer_name", "customer_surname", "customer_patronic_name", "born_at", "phone",
|
||||
@@ -40,10 +40,18 @@ var cardPinOrderColumnsSQL = strings.Join(cardPinOrderColumns, ", ")
|
||||
|
||||
var cardPinOrderWritableColumnsSQL = strings.Join(cardPinOrderWritableColumns, ", ")
|
||||
|
||||
const cardPinOrderFromClause = ` FROM card_pin_orders cpo
|
||||
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
|
||||
LEFT JOIN branches b ON b.id = cpo.branch_id
|
||||
LEFT JOIN users u ON u.id = cpo.user_id`
|
||||
|
||||
var cardPinOrderSelectColumns = shared.PrefixedColumns("cpo", cardPinOrderColumns) + `,
|
||||
ct.name, b.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
|
||||
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(), dto.CardNumber, dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.Phone,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.Status, dto.Notes,
|
||||
}
|
||||
@@ -51,8 +59,8 @@ func createArgs(dto cardpinorders.CreateCardPinOrderDTO) []interface{} {
|
||||
|
||||
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.UserId, dto.CardTypeId, dto.CardNumber, dto.Region, dto.BranchId,
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, dto.BornAt, dto.Phone,
|
||||
dto.UniqueId, shared.OptionalInt64(dto.UserId), dto.CardTypeId.Int64(), dto.CardNumber, dto.Region, dto.BranchId.Int64(),
|
||||
dto.CustomerName, dto.CustomerSurname, dto.CustomerPatronicName, shared.OptionalTime(dto.BornAt), dto.Phone,
|
||||
dto.PassportSerie, dto.PassportId, dto.PassportOne, dto.PassportTwo, dto.PassportThree, dto.PassportFour,
|
||||
dto.Status, dto.Notes,
|
||||
}
|
||||
@@ -61,51 +69,87 @@ func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
|
||||
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM card_pin_orders cpo`+whereClause, args...).Scan(&count); err != nil {
|
||||
return cardpinorders.ListCardPinOrderDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT cpo.id, cpo.unique_id, cpo.card_number, cpo.customer_name, cpo.customer_surname,
|
||||
cpo.region, bp.name, cpo.phone, cpo.status, cpo.created_at
|
||||
FROM card_pin_orders cpo
|
||||
LEFT JOIN branches b ON b.id = cpo.branch_id
|
||||
LEFT JOIN provinces bp ON bp.id = b.province_id%s ORDER BY cpo.id LIMIT $%d OFFSET $%d`,
|
||||
whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return cardpinorders.ListCardPinOrderDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []cardpinorders.CardPinOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
var item cardpinorders.CardPinOrderListItemDTO
|
||||
var provinceNameJSON []byte
|
||||
if err := rows.Scan(
|
||||
&item.Id, &item.UniqueId, &item.CardNumber, &item.CustomerName, &item.CustomerSurname,
|
||||
&item.Region, &provinceNameJSON, &item.Phone, &item.Status, &item.CreatedAt,
|
||||
); err != nil {
|
||||
return cardpinorders.ListCardPinOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
||||
return cardpinorders.ListCardPinOrderDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return cardpinorders.ListCardPinOrderDTO{}, err
|
||||
}
|
||||
|
||||
return cardpinorders.ListCardPinOrderDTO{Count: count, CardPinOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cardpinorders.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"cpo.deleted_at IS NULL"}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("status = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.BranchId != nil {
|
||||
if len(filter.BranchIds) > 0 {
|
||||
conditions, args = rbac.AppendBranchIDs(conditions, args, "cpo.branch_id", filter.BranchIds)
|
||||
} else if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("branch_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.CardTypeId != nil {
|
||||
args = append(args, *filter.CardTypeId)
|
||||
conditions = append(conditions, fmt.Sprintf("card_type_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.card_type_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("region = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
conditions = append(conditions, fmt.Sprintf("cpo.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cardpinorders.CardPinOrderDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
query := `SELECT ` + cardPinOrderSelectColumns + cardPinOrderFromClause + ` WHERE cpo.id = $1 AND cpo.deleted_at IS NULL`
|
||||
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
|
||||
@@ -116,12 +160,21 @@ func (r *repository) Create(ctx context.Context, dto cardpinorders.CreateCardPin
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO card_pin_orders (%s) VALUES (%s) RETURNING %s`,
|
||||
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "), cardPinOrderColumnsSQL,
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO card_pin_orders (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted cpo
|
||||
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
|
||||
LEFT JOIN branches b ON b.id = cpo.branch_id
|
||||
LEFT JOIN users u ON u.id = cpo.user_id`,
|
||||
cardPinOrderWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
cardPinOrderColumnsSQL, cardPinOrderSelectColumns,
|
||||
)
|
||||
|
||||
return scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
|
||||
return scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
|
||||
@@ -133,12 +186,21 @@ func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.Upd
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL,
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE card_pin_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated cpo
|
||||
LEFT JOIN card_types ct ON ct.id = cpo.card_type_id
|
||||
LEFT JOIN branches b ON b.id = cpo.branch_id
|
||||
LEFT JOIN users u ON u.id = cpo.user_id`,
|
||||
strings.Join(assignments, ", "), len(args), cardPinOrderColumnsSQL, cardPinOrderSelectColumns,
|
||||
)
|
||||
|
||||
item, err := scanCardPinOrder(r.client.QueryRow(ctx, query, args...))
|
||||
item, err := scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cardpinorders.CardPinOrderDTO{}, err
|
||||
}
|
||||
@@ -150,16 +212,57 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
}
|
||||
|
||||
func scanCardPinOrder(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
|
||||
return scanCardPinOrderRow(row, false)
|
||||
}
|
||||
|
||||
func scanCardPinOrderWithJoins(row genericrepo.Scanner) (cardpinorders.CardPinOrderDTO, error) {
|
||||
return scanCardPinOrderRow(row, true)
|
||||
}
|
||||
|
||||
func scanCardPinOrderRow(row genericrepo.Scanner, withJoins bool) (cardpinorders.CardPinOrderDTO, error) {
|
||||
var item cardpinorders.CardPinOrderDTO
|
||||
err := row.Scan(
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.UniqueId, &item.UserId, &item.CardTypeId, &item.CardNumber, &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,
|
||||
)
|
||||
if err != nil {
|
||||
}
|
||||
|
||||
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 cardpinorders.CardPinOrderDTO{}, err
|
||||
}
|
||||
if !withJoins {
|
||||
return item, nil
|
||||
}
|
||||
|
||||
var cardTypeName, branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
||||
return cardpinorders.CardPinOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return cardpinorders.CardPinOrderDTO{}, 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
|
||||
}
|
||||
|
||||
@@ -1,79 +1,87 @@
|
||||
package cardpinorders
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type CardPinOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CardTypeId int64 `json:"cardTypeId"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
Region string `json:"region"`
|
||||
BranchId int64 `json:"branchId"`
|
||||
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"`
|
||||
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"`
|
||||
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 CreateCardPinOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone *string `json:"phone"`
|
||||
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"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
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" swaggertype:"string" format:"date"`
|
||||
Phone *string `json:"phone"`
|
||||
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 UpdateCardPinOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
CardTypeId int64 `json:"cardTypeId" binding:"required"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
CustomerSurname string `json:"customerSurname" binding:"required"`
|
||||
CustomerPatronicName *string `json:"customerPatronicName"`
|
||||
BornAt *time.Time `json:"bornAt"`
|
||||
Phone *string `json:"phone"`
|
||||
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"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
UserId *shared.FlexibleInt64 `json:"userId" swaggertype:"integer"`
|
||||
CardTypeId shared.FlexibleInt64 `json:"cardTypeId" binding:"required" swaggertype:"integer"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
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" swaggertype:"string" format:"date"`
|
||||
Phone *string `json:"phone"`
|
||||
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
|
||||
@@ -81,7 +89,23 @@ type ListFilter struct {
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardPinOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardPinOrders []CardPinOrderDTO `json:"cardPinOrders"`
|
||||
// CardPinOrderListItemDTO is the list row; card type, branch, passport and
|
||||
// scans come from GET /card-pin-orders/:id.
|
||||
type CardPinOrderListItemDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardNumber *string `json:"cardNumber"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
Region string `json:"region"`
|
||||
// ProvinceName is the branch's province (etrap).
|
||||
ProvinceName shared.LocalizedText `json:"provinceName"`
|
||||
Phone *string `json:"phone"`
|
||||
Status *string `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type ListCardPinOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardPinOrders []CardPinOrderListItemDTO `json:"cardPinOrders"`
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@ package cardpinorders
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
@@ -81,7 +82,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -97,6 +98,9 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if !rbac.GuardOrder(c, item.UserId, item.BranchId) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
@@ -145,12 +149,16 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if !h.guardBranchByID(c, id) {
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateCardPinOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
@@ -184,12 +192,16 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /card-pin-orders/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
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
|
||||
@@ -202,73 +214,55 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card pin order removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
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 raw := c.Query("branch_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.BranchId = &id
|
||||
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
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 := c.Query("card_type_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.CardTypeId = &id
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("status")); raw != "" {
|
||||
if raw := shared.QueryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); 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)
|
||||
}
|
||||
|
||||
316
internal/cards/cardrekwizit/db/postgresql.go
Normal file
316
internal/cards/cardrekwizit/db/postgresql.go
Normal file
@@ -0,0 +1,316 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cardrekwizit"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[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, '')`
|
||||
|
||||
const cardRekwizitOrderListFromClause = cardRekwizitOrderFromClause + `
|
||||
LEFT JOIN provinces bp ON bp.id = b.province_id`
|
||||
|
||||
var cardRekwizitOrderListColumns = `cro.id, cro.unique_id, cro.card_type_id, ct.name,
|
||||
cro.customer_name, cro.customer_surname, cro.user_id, ` + shared.UserDisplaySQL + `,
|
||||
cro.region, cro.branch_id, b.name, bp.name, cro.status`
|
||||
|
||||
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`,
|
||||
cardRekwizitOrderListColumns, cardRekwizitOrderListFromClause, 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()
|
||||
|
||||
items := []cardrekwizit.CardRekwizitOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanCardRekwizitOrderListItem(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{}) {
|
||||
conditions := []string{"cro.deleted_at IS NULL"}
|
||||
|
||||
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)))
|
||||
}
|
||||
|
||||
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 AND cro.deleted_at IS NULL`
|
||||
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 AND deleted_at IS NULL
|
||||
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 scanCardRekwizitOrderListItem(row genericrepo.Scanner) (cardrekwizit.CardRekwizitOrderListItemDTO, error) {
|
||||
var item cardrekwizit.CardRekwizitOrderListItemDTO
|
||||
var cardTypeId, branchId int64
|
||||
var userId *int64
|
||||
var cardTypeNameJSON, branchNameJSON, provinceNameJSON []byte
|
||||
var userName string
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &cardTypeId, &cardTypeNameJSON,
|
||||
&item.CustomerName, &item.CustomerSurname, &userId, &userName,
|
||||
&item.Region, &branchId, &branchNameJSON, &provinceNameJSON, &item.Status,
|
||||
); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
||||
}
|
||||
|
||||
var cardTypeName, branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(cardTypeNameJSON, &cardTypeName); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
||||
return cardrekwizit.CardRekwizitOrderListItemDTO{}, err
|
||||
}
|
||||
if cardTypeId != 0 {
|
||||
item.CardType = &shared.NamedInfo{Id: cardTypeId, Name: cardTypeName}
|
||||
}
|
||||
if branchId != 0 {
|
||||
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
|
||||
}
|
||||
if userId != nil {
|
||||
item.User = &cardrekwizit.ListUserDTO{Id: *userId, Name: userName}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
122
internal/cards/cardrekwizit/dto.go
Normal file
122
internal/cards/cardrekwizit/dto.go
Normal file
@@ -0,0 +1,122 @@
|
||||
package cardrekwizit
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/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
|
||||
}
|
||||
|
||||
// CardRekwizitOrderListItemDTO is the list row; card number, passport and
|
||||
// scans come from GET /card-rekwizit-orders/:id.
|
||||
type CardRekwizitOrderListItemDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
CardType *shared.NamedInfo `json:"cardType,omitempty"`
|
||||
CustomerName string `json:"customerName"`
|
||||
CustomerSurname string `json:"customerSurname"`
|
||||
User *ListUserDTO `json:"user,omitempty"`
|
||||
Region string `json:"region"`
|
||||
Branch *shared.NamedInfo `json:"branch,omitempty"`
|
||||
// ProvinceName is the branch's province (etrap).
|
||||
ProvinceName shared.LocalizedText `json:"provinceName"`
|
||||
Status *string `json:"status"`
|
||||
}
|
||||
|
||||
type ListUserDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ListCardRekwizitOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
CardRekwizitOrders []CardRekwizitOrderListItemDTO `json:"cardRekwizitOrders"`
|
||||
}
|
||||
268
internal/cards/cardrekwizit/handler.go
Normal file
268
internal/cards/cardrekwizit/handler.go
Normal file
@@ -0,0 +1,268 @@
|
||||
package cardrekwizit
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"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 := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
|
||||
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)
|
||||
}
|
||||
11
internal/cards/cardrekwizit/storage.go
Normal file
11
internal/cards/cardrekwizit/storage.go
Normal 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
|
||||
}
|
||||
@@ -3,9 +3,12 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/cards"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -37,6 +40,13 @@ 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) + `,
|
||||
ct.name, ` + shared.UserDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
func createArgs(dto cards.CreateCardDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
|
||||
@@ -52,36 +62,64 @@ func updateArgs(dto cards.UpdateCardDTO) []interface{} {
|
||||
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM cards c`+whereClause, args...).Scan(&count); err != nil {
|
||||
return cards.ListCardDTO{}, 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 LIMIT $%d OFFSET $%d`,
|
||||
cardSelectColumns, cardFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return cards.ListCardDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []cards.CardDTO
|
||||
for rows.Next() {
|
||||
item, err := scanCardWithUser(rows)
|
||||
if err != nil {
|
||||
return cards.ListCardDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return cards.ListCardDTO{}, err
|
||||
}
|
||||
|
||||
return cards.ListCardDTO{Count: count, Cards: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter cards.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
conditions := []string{"c.deleted_at IS NULL"}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("c.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(filter.BranchIds) > 0 {
|
||||
args = append(args, filter.BranchIds)
|
||||
conditions = append(conditions, rbac.UserInBranchSQL("c.user_id", len(args)))
|
||||
}
|
||||
|
||||
if filter.Type != nil {
|
||||
args = append(args, *filter.Type)
|
||||
conditions = append(conditions, fmt.Sprintf("type = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
conditions = append(conditions, fmt.Sprintf("c.type = $%d", len(args)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
query := `SELECT ` + cardSelectColumns + cardFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
|
||||
return scanCardWithUser(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards.CardDTO, error) {
|
||||
@@ -92,12 +130,20 @@ func (r *repository) Create(ctx context.Context, dto cards.CreateCardDTO) (cards
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`INSERT INTO cards (%s) VALUES (%s) RETURNING %s`,
|
||||
cardWritableColumnsSQL, strings.Join(placeholders, ", "), cardColumnsSQL,
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO cards (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
return scanCard(r.client.QueryRow(ctx, query, args...))
|
||||
return scanCardWithUser(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardDTO) (cards.CardDTO, error) {
|
||||
@@ -109,12 +155,20 @@ func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardD
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(
|
||||
`UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') WHERE id = $%d RETURNING %s`,
|
||||
strings.Join(assignments, ", "), len(args), cardColumnsSQL,
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE cards SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
item, err := scanCard(r.client.QueryRow(ctx, query, args...))
|
||||
item, err := scanCardWithUser(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
@@ -126,13 +180,57 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
}
|
||||
|
||||
func scanCard(row genericrepo.Scanner) (cards.CardDTO, error) {
|
||||
return scanCardRow(row, false)
|
||||
}
|
||||
|
||||
func scanCardWithUser(row genericrepo.Scanner) (cards.CardDTO, error) {
|
||||
return scanCardRow(row, true)
|
||||
}
|
||||
|
||||
func scanCardRow(row genericrepo.Scanner, withUser bool) (cards.CardDTO, error) {
|
||||
var item cards.CardDTO
|
||||
err := row.Scan(
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type,
|
||||
&item.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
}
|
||||
|
||||
var cardTypeNameJSON []byte
|
||||
var userName, userUsername, userPhone, userEmail string
|
||||
if withUser {
|
||||
dest = append(dest, &cardTypeNameJSON, &userName, &userUsername, &userPhone, &userEmail)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return cards.CardDTO{}, err
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
package cards
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type CardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"userId"`
|
||||
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 {
|
||||
@@ -33,10 +39,11 @@ type UpdateCardDTO struct {
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
Type *string
|
||||
Page int
|
||||
Limit int
|
||||
UserId *int64
|
||||
BranchIds []int64
|
||||
Type *string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListCardDTO struct {
|
||||
|
||||
@@ -3,11 +3,12 @@ package cards
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
@@ -78,7 +79,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /cards/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -94,6 +95,16 @@ 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
|
||||
}
|
||||
if item.UserId == nil && rbac.HasBranchScope(c) {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
@@ -142,12 +153,16 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /cards/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if !h.guardCardByID(c, id) {
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateCardDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
@@ -181,12 +196,16 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /cards/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if !h.guardCardByID(c, id) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
@@ -199,53 +218,43 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("card 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,
|
||||
page, limit, ok := shared.ParsePageLimit(c)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter := ListFilter{Page: page, Limit: limit}
|
||||
|
||||
if id, ok := shared.OptionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("type")); raw != "" {
|
||||
if raw := shared.QueryValue(c, "type"); raw != "" {
|
||||
filter.Type = &raw
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
rbac.BindBranchIDs(c, &filter.BranchIds)
|
||||
return filter, true
|
||||
}
|
||||
|
||||
func (h *handler) guardCardByID(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
|
||||
}
|
||||
if item.UserId == nil {
|
||||
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
return false
|
||||
}
|
||||
return rbac.GuardUser(c, *item.UserId)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/paymentcard"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -48,7 +49,7 @@ func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []i
|
||||
var conditions []string
|
||||
|
||||
if filter.CardName != "" {
|
||||
args = append(args, likePattern(filter.CardName))
|
||||
args = append(args, shared.LikePattern(filter.CardName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
c.name->>'en' ILIKE $%[1]d OR c.name->>'ru' ILIKE $%[1]d OR c.name->>'tm' ILIKE $%[1]d
|
||||
@@ -67,13 +68,6 @@ func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []i
|
||||
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) (paymentcard.PaymentCardDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
@@ -106,7 +100,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE card_types SET
|
||||
price = $1, name = $2, notes = $3, active = $4
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||
@@ -119,7 +113,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
|
||||
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE card_types SET active = $1
|
||||
WHERE id = $2
|
||||
WHERE id = $2 AND deleted_at IS NULL
|
||||
RETURNING %s`, cardReturningColumns)
|
||||
|
||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
|
||||
@@ -133,7 +127,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
|
||||
func marshalName(title shared.LocalizedText) ([]byte, error) {
|
||||
return json.Marshal(title)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +1,27 @@
|
||||
package paymentcard
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
import "online-back/internal/shared"
|
||||
|
||||
type PaymentCardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Price string `json:"price"`
|
||||
Title LocalizedText `json:"title"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
Id int64 `json:"id"`
|
||||
Price string `json:"price"`
|
||||
Title shared.LocalizedText `json:"title"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CreatePaymentCardDTO struct {
|
||||
Price string `json:"price" binding:"required"`
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active *bool `json:"active"`
|
||||
Price string `json:"price" binding:"required"`
|
||||
Title shared.LocalizedText `json:"title" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdatePaymentCardDTO struct {
|
||||
Price string `json:"price" binding:"required"`
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
Price string `json:"price" binding:"required"`
|
||||
Title shared.LocalizedText `json:"title" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdatePaymentCardActiveDTO struct {
|
||||
|
||||
@@ -4,10 +4,12 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -26,7 +28,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.Catalog(perm.Cards))
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
@@ -79,7 +81,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -143,7 +145,7 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -184,7 +186,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{id}/active [put]
|
||||
func (h *handler) updateActive(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -223,7 +225,7 @@ func (h *handler) updateActive(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /payment-cards/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -241,47 +243,18 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("payment card 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,
|
||||
page, limit, ok := shared.ParsePageLimit(c)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter := ListFilter{Page: page, Limit: limit}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("card_name")); raw != "" {
|
||||
if raw := shared.QueryValue(c, "card_name", "cardName"); raw != "" {
|
||||
filter.CardName = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
if raw := shared.QueryValue(c, "active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/reasonscard"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
@@ -47,7 +48,7 @@ func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (r
|
||||
func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.ReasonName != "" {
|
||||
args = append(args, likePattern(filter.ReasonName))
|
||||
args = append(args, shared.LikePattern(filter.ReasonName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
r.name->>'en' ILIKE $%[1]d OR r.name->>'ru' ILIKE $%[1]d OR r.name->>'tm' ILIKE $%[1]d
|
||||
@@ -61,13 +62,6 @@ func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []i
|
||||
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) (reasonscard.ReasonCardDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
@@ -101,7 +95,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
|
||||
UPDATE card_states SET
|
||||
price = $1, name = $2, notes = $3, active = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5
|
||||
WHERE id = $5 AND deleted_at IS NULL
|
||||
RETURNING %s`, reasonReturningColumns)
|
||||
|
||||
item, err := scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||
@@ -115,7 +109,7 @@ func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
|
||||
func marshalName(title shared.LocalizedText) ([]byte, error) {
|
||||
return json.Marshal(title)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,33 @@
|
||||
package reasonscard
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type ReasonCardDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Title LocalizedText `json:"title"`
|
||||
Price string `json:"price"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Id int64 `json:"id"`
|
||||
Title shared.LocalizedText `json:"title"`
|
||||
Price string `json:"price"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateReasonCardDTO struct {
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Price string `json:"price" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active *bool `json:"active"`
|
||||
Title shared.LocalizedText `json:"title" binding:"required"`
|
||||
Price string `json:"price" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateReasonCardDTO struct {
|
||||
Title LocalizedText `json:"title" binding:"required"`
|
||||
Price string `json:"price" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
Title shared.LocalizedText `json:"title" binding:"required"`
|
||||
Price string `json:"price" binding:"required"`
|
||||
Notes string `json:"notes"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
|
||||
@@ -3,11 +3,12 @@ package reasonscard
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.Catalog(perm.Cards))
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
@@ -77,7 +78,7 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /reasons-cards/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -141,7 +142,7 @@ func (h *handler) create(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /reasons-cards/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -180,7 +181,7 @@ func (h *handler) update(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /reasons-cards/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
@@ -198,43 +199,14 @@ func (h *handler) delete(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("reason card 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,
|
||||
page, limit, ok := shared.ParsePageLimit(c)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter := ListFilter{Page: page, Limit: limit}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("reason_name")); raw != "" {
|
||||
if raw := shared.QueryValue(c, "reason_name", "reasonName"); raw != "" {
|
||||
filter.ReasonName = raw
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
// Package cards groups payment cards, card orders, PIN orders, and their
|
||||
// reference data (reasons, payment card types) under one bounded context,
|
||||
// replacing the flat internal/admin/* listing.
|
||||
// Package cards groups payment cards, card orders, PIN orders, 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"
|
||||
paymentcarddb "online-back/internal/cards/paymentcard/db"
|
||||
"online-back/internal/cards/reasonscard"
|
||||
reasonscarddb "online-back/internal/cards/reasonscard/db"
|
||||
"online-back/internal/cards/visamaster"
|
||||
visamasterdb "online-back/internal/cards/visamaster/db"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
@@ -30,10 +37,13 @@ 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)),
|
||||
}
|
||||
}
|
||||
|
||||
345
internal/cards/visamaster/db/postgresql.go
Normal file
345
internal/cards/visamaster/db/postgresql.go
Normal file
@@ -0,0 +1,345 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/cards/visamaster"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[visamaster.VisaMasterPaymentOrderDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) visamaster.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "visa_master_payment_orders", orderColumnsSQL, scanOrder),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const orderFromClause = ` FROM visa_master_payment_orders o
|
||||
LEFT JOIN branches b ON b.id = o.branch_id
|
||||
LEFT JOIN users u ON u.id = o.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`
|
||||
|
||||
var orderWritableColumns = []string{
|
||||
"unique_id", "type", "passport_name", "passport_surname", "phone", "email",
|
||||
"region", "branch_id", "user_id", "address",
|
||||
"sender_datas", "payment_reciever", "documents",
|
||||
"status", "notes",
|
||||
"sender_full_name", "sender_passport_serie", "sender_passport_number", "sender_deposit_account",
|
||||
"reciever_full_name", "reciever_passport_serie", "reciever_passport_number", "reciever_deposit_account",
|
||||
"amount_usd", "paid",
|
||||
}
|
||||
|
||||
var orderColumns = append(append([]string{"id"}, orderWritableColumns...), "created_at", "updated_at")
|
||||
|
||||
var orderColumnsSQL = strings.Join(orderColumns, ", ")
|
||||
|
||||
var orderWritableColumnsSQL = strings.Join(orderWritableColumns, ", ")
|
||||
|
||||
var orderSelectColumns = shared.PrefixedColumns("o", orderColumns) + `, p.region, b.name, COALESCE(b.unique_code, ''), COALESCE(b.region, ''), b.province_id, p.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 resolvePaid(paid *bool) bool {
|
||||
if paid == nil {
|
||||
return false
|
||||
}
|
||||
return *paid
|
||||
}
|
||||
|
||||
func jsonArg(raw json.RawMessage, fallback string) []byte {
|
||||
if len(raw) == 0 {
|
||||
return []byte(fallback)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func createArgs(dto visamaster.CreateVisaMasterPaymentOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email,
|
||||
dto.Region, dto.BranchId, dto.UserId, dto.Address,
|
||||
jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`),
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
|
||||
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
|
||||
dto.AmountUsd, resolvePaid(dto.Paid),
|
||||
}
|
||||
}
|
||||
|
||||
func updateArgs(dto visamaster.UpdateVisaMasterPaymentOrderDTO) []interface{} {
|
||||
return []interface{}{
|
||||
dto.UniqueId, dto.Type, dto.PassportName, dto.PassportSurname, dto.Phone, dto.Email,
|
||||
dto.Region, dto.BranchId, dto.UserId, dto.Address,
|
||||
jsonArg(dto.SenderDatas, `{}`), jsonArg(dto.PaymentReciever, `[]`), jsonArg(dto.Documents, `{}`),
|
||||
resolveStatus(dto.Status), dto.Notes,
|
||||
dto.SenderFullName, dto.SenderPassportSerie, dto.SenderPassportNumber, dto.SenderDepositAccount,
|
||||
dto.RecieverFullName, dto.RecieverPassportSerie, dto.RecieverPassportNumber, dto.RecieverDepositAccount,
|
||||
dto.AmountUsd, dto.Paid,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter visamaster.ListFilter) (visamaster.ListVisaMasterPaymentOrderDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM visa_master_payment_orders o`+whereClause, args...).Scan(&count); err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT o.id, o.unique_id, o.type, o.created_at, o.region, p.region, o.branch_id, b.name, p.name,
|
||||
o.passport_name, o.passport_surname, o.phone, o.status, o.paid, `+paidThisMonthSQL+`
|
||||
FROM visa_master_payment_orders o
|
||||
LEFT JOIN branches b ON b.id = o.branch_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id%s ORDER BY o.id DESC LIMIT $%d OFFSET $%d`,
|
||||
whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := []visamaster.VisaMasterPaymentOrderListItemDTO{}
|
||||
for rows.Next() {
|
||||
item, err := scanOrderListItem(rows)
|
||||
if err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
return visamaster.ListVisaMasterPaymentOrderDTO{Count: count, VisaMasterPaymentOrders: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter visamaster.ListFilter) (whereClause string, args []interface{}) {
|
||||
conditions := []string{"o.deleted_at IS NULL"}
|
||||
|
||||
if filter.Name != "" {
|
||||
args = append(args, shared.LikePattern(filter.Name))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
o.passport_name ILIKE $%[1]d OR o.passport_surname ILIKE $%[1]d
|
||||
OR o.sender_full_name ILIKE $%[1]d OR COALESCE(o.reciever_full_name, '') ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
// Case-insensitive and trimmed, the same match visamasterpay uses to
|
||||
// pick Sber fees and credentials.
|
||||
if filter.Type != "" {
|
||||
args = append(args, strings.TrimSpace(filter.Type))
|
||||
conditions = append(conditions, fmt.Sprintf("LOWER(TRIM(o.type)) = LOWER($%d)", len(args)))
|
||||
}
|
||||
|
||||
if filter.ExcludeType != "" {
|
||||
args = append(args, strings.TrimSpace(filter.ExcludeType))
|
||||
conditions = append(conditions, fmt.Sprintf("LOWER(TRIM(COALESCE(o.type, ''))) <> LOWER($%d)", len(args)))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("o.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(filter.BranchIds) > 0 {
|
||||
conditions, args = rbac.AppendBranchIDs(conditions, args, "o.branch_id", filter.BranchIds)
|
||||
} else if filter.BranchId != nil {
|
||||
args = append(args, *filter.BranchId)
|
||||
conditions = append(conditions, fmt.Sprintf("o.branch_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("o.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, filter.Region)
|
||||
conditions = append(conditions, fmt.Sprintf("o.region = $%d", len(args)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
query := `SELECT ` + orderSelectColumns + orderFromClause + ` WHERE o.id = $1 AND o.deleted_at IS NULL`
|
||||
return scanOrder(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto visamaster.CreateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
args := createArgs(dto)
|
||||
|
||||
placeholders := make([]string, len(args))
|
||||
for i := range args {
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH inserted AS (
|
||||
INSERT INTO visa_master_payment_orders (%s) VALUES (%s)
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM inserted o
|
||||
LEFT JOIN branches b ON b.id = o.branch_id
|
||||
LEFT JOIN users u ON u.id = o.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`,
|
||||
orderWritableColumnsSQL, strings.Join(placeholders, ", "),
|
||||
orderColumnsSQL, orderSelectColumns,
|
||||
)
|
||||
|
||||
return scanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto visamaster.UpdateVisaMasterPaymentOrderDTO) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
args := updateArgs(dto)
|
||||
|
||||
assignments := make([]string, len(orderWritableColumns))
|
||||
for i, column := range orderWritableColumns {
|
||||
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||
}
|
||||
args = append(args, id)
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
WITH updated AS (
|
||||
UPDATE visa_master_payment_orders SET %s, updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $%d AND deleted_at IS NULL
|
||||
RETURNING %s
|
||||
)
|
||||
SELECT %s
|
||||
FROM updated o
|
||||
LEFT JOIN branches b ON b.id = o.branch_id
|
||||
LEFT JOIN users u ON u.id = o.user_id
|
||||
LEFT JOIN provinces p ON p.id = b.province_id`,
|
||||
strings.Join(assignments, ", "), len(args), orderColumnsSQL, orderSelectColumns,
|
||||
)
|
||||
|
||||
item, err := scanOrder(r.client.QueryRow(ctx, query, args...))
|
||||
if err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanOrder(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||
var item visamaster.VisaMasterPaymentOrderDTO
|
||||
var senderDatas, paymentReciever, documents []byte
|
||||
var regionNameJSON, branchNameJSON, provinceNameJSON []byte
|
||||
var branchRegion, userName, userUsername, userPhone, userEmail string
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Type, &item.PassportName, &item.PassportSurname, &item.Phone, &item.Email,
|
||||
&item.Region, &item.BranchId, &item.UserId, &item.Address,
|
||||
&senderDatas, &paymentReciever, &documents,
|
||||
&item.Status, &item.Notes,
|
||||
&item.SenderFullName, &item.SenderPassportSerie, &item.SenderPassportNumber, &item.SenderDepositAccount,
|
||||
&item.RecieverFullName, &item.RecieverPassportSerie, &item.RecieverPassportNumber, &item.RecieverDepositAccount,
|
||||
&item.AmountUsd, &item.Paid, &item.CreatedAt, &item.UpdatedAt,
|
||||
®ionNameJSON, &branchNameJSON, &item.Branch.UniqueCode, &branchRegion, &item.Branch.ProvinceId, &provinceNameJSON,
|
||||
&userName, &userUsername, &userPhone, &userEmail,
|
||||
)
|
||||
if err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
item.SenderDatas = jsonOrDefault(senderDatas, `{}`)
|
||||
item.PaymentReciever = jsonOrDefault(paymentReciever, `[]`)
|
||||
item.Documents = jsonOrDefault(documents, `{}`)
|
||||
|
||||
item.Branch.Id = item.BranchId
|
||||
item.Branch.Region = branchRegion
|
||||
if err := shared.UnmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &item.Branch.Name); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.Branch.ProvinceName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||
}
|
||||
|
||||
if item.UserId != nil {
|
||||
item.User = &shared.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
}
|
||||
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func jsonOrDefault(raw []byte, fallback string) json.RawMessage {
|
||||
if len(raw) == 0 {
|
||||
return json.RawMessage(fallback)
|
||||
}
|
||||
return json.RawMessage(raw)
|
||||
}
|
||||
|
||||
// paidThisMonthSQL: the order has a successful payment whose payment_period
|
||||
// falls in the current month in Ashgabat time (UTC+5, as visamasterpay).
|
||||
const paidThisMonthSQL = `EXISTS (
|
||||
SELECT 1 FROM visa_master_order_payments vp
|
||||
WHERE vp.order_id = o.id AND vp.gateway_status = 'success' AND vp.deleted_at IS NULL
|
||||
AND date_trunc('month', vp.payment_period) = date_trunc('month', (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + INTERVAL '5 hours')
|
||||
)`
|
||||
|
||||
func scanOrderListItem(row genericrepo.Scanner) (visamaster.VisaMasterPaymentOrderListItemDTO, error) {
|
||||
var item visamaster.VisaMasterPaymentOrderListItemDTO
|
||||
var branchId int64
|
||||
var regionNameJSON, branchNameJSON, provinceNameJSON []byte
|
||||
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.UniqueId, &item.Type, &item.CreatedAt, &item.Region, ®ionNameJSON, &branchId, &branchNameJSON, &provinceNameJSON,
|
||||
&item.PassportName, &item.PassportSurname, &item.Phone, &item.Status, &item.Paid, &item.PaidThisMonth,
|
||||
); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
|
||||
}
|
||||
|
||||
if err := shared.UnmarshalLocalized(regionNameJSON, &item.RegionName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
|
||||
}
|
||||
var branchName shared.LocalizedText
|
||||
if err := shared.UnmarshalLocalized(branchNameJSON, &branchName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
|
||||
}
|
||||
if err := shared.UnmarshalLocalized(provinceNameJSON, &item.ProvinceName); err != nil {
|
||||
return visamaster.VisaMasterPaymentOrderListItemDTO{}, err
|
||||
}
|
||||
if branchId != 0 {
|
||||
item.Branch = &shared.NamedInfo{Id: branchId, Name: branchName}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
150
internal/cards/visamaster/dto.go
Normal file
150
internal/cards/visamaster/dto.go
Normal file
@@ -0,0 +1,150 @@
|
||||
package visamaster
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"online-back/internal/shared"
|
||||
)
|
||||
|
||||
type BranchInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name shared.LocalizedText `json:"name"`
|
||||
Region string `json:"region"`
|
||||
ProvinceId *int64 `json:"provinceId"`
|
||||
ProvinceName shared.LocalizedText `json:"provinceName"`
|
||||
}
|
||||
|
||||
type VisaMasterPaymentOrderDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Type *string `json:"type"`
|
||||
PassportName string `json:"passportName"`
|
||||
PassportSurname string `json:"passportSurname"`
|
||||
Phone string `json:"phone"`
|
||||
Email *string `json:"email"`
|
||||
Region string `json:"region"`
|
||||
RegionName shared.LocalizedText `json:"regionName,omitempty"`
|
||||
BranchId int64 `json:"-"`
|
||||
Branch BranchInfo `json:"branch"`
|
||||
UserId *int64 `json:"-"`
|
||||
User *shared.UserInfo `json:"user,omitempty"`
|
||||
Address string `json:"address"`
|
||||
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
|
||||
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
|
||||
Documents json.RawMessage `json:"documents" swaggertype:"object"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
SenderFullName string `json:"senderFullName"`
|
||||
SenderPassportSerie string `json:"senderPassportSerie"`
|
||||
SenderPassportNumber string `json:"senderPassportNumber"`
|
||||
SenderDepositAccount string `json:"senderDepositAccount"`
|
||||
RecieverFullName *string `json:"recieverFullName"`
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
AmountUsd *float64 `json:"amountUsd"`
|
||||
Paid bool `json:"paid"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateVisaMasterPaymentOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Type *string `json:"type"`
|
||||
PassportName string `json:"passportName" binding:"required"`
|
||||
PassportSurname string `json:"passportSurname" binding:"required"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Address string `json:"address" binding:"required"`
|
||||
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
|
||||
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
|
||||
Documents json.RawMessage `json:"documents" swaggertype:"object"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
SenderFullName string `json:"senderFullName" binding:"required"`
|
||||
SenderPassportSerie string `json:"senderPassportSerie" binding:"required"`
|
||||
SenderPassportNumber string `json:"senderPassportNumber" binding:"required"`
|
||||
SenderDepositAccount string `json:"senderDepositAccount" binding:"required"`
|
||||
RecieverFullName *string `json:"recieverFullName"`
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
AmountUsd float64 `json:"amountUsd"`
|
||||
Paid *bool `json:"paid"`
|
||||
}
|
||||
|
||||
type UpdateVisaMasterPaymentOrderDTO struct {
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Type *string `json:"type"`
|
||||
PassportName string `json:"passportName" binding:"required"`
|
||||
PassportSurname string `json:"passportSurname" binding:"required"`
|
||||
Phone string `json:"phone" binding:"required"`
|
||||
Email *string `json:"email"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
BranchId int64 `json:"branchId" binding:"required"`
|
||||
UserId *int64 `json:"userId"`
|
||||
Address string `json:"address" binding:"required"`
|
||||
SenderDatas json.RawMessage `json:"senderDatas" swaggertype:"object"`
|
||||
PaymentReciever json.RawMessage `json:"paymentReciever" swaggertype:"array,object"`
|
||||
Documents json.RawMessage `json:"documents" swaggertype:"object"`
|
||||
Status *string `json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
SenderFullName string `json:"senderFullName" binding:"required"`
|
||||
SenderPassportSerie string `json:"senderPassportSerie" binding:"required"`
|
||||
SenderPassportNumber string `json:"senderPassportNumber" binding:"required"`
|
||||
SenderDepositAccount string `json:"senderDepositAccount" binding:"required"`
|
||||
RecieverFullName *string `json:"recieverFullName"`
|
||||
RecieverPassportSerie *string `json:"recieverPassportSerie"`
|
||||
RecieverPassportNumber *string `json:"recieverPassportNumber"`
|
||||
RecieverDepositAccount *string `json:"recieverDepositAccount"`
|
||||
AmountUsd float64 `json:"amountUsd"`
|
||||
Paid bool `json:"paid"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Name string
|
||||
// Type narrows to one order type; ExcludeType drops one (the Visa/Master
|
||||
// page hides sber, which has its own page).
|
||||
Type string
|
||||
ExcludeType string
|
||||
Status *string
|
||||
BranchId *int64
|
||||
BranchIds []int64
|
||||
UserId *int64
|
||||
Region string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
// VisaMasterPaymentOrderListItemDTO is the list row (visa/master and sber);
|
||||
// sender, receiver, documents and amounts come from GET /visa-master-payment-orders/:id.
|
||||
type VisaMasterPaymentOrderListItemDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueId *string `json:"uniqueId"`
|
||||
Type *string `json:"type"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Region string `json:"region"`
|
||||
// RegionName is the welaýat of the branch's province (Mary, Lebap, ...).
|
||||
RegionName shared.LocalizedText `json:"regionName"`
|
||||
Branch *shared.NamedInfo `json:"branch,omitempty"`
|
||||
// ProvinceName is the branch's province (etrap).
|
||||
ProvinceName shared.LocalizedText `json:"provinceName"`
|
||||
PassportName string `json:"passportName"`
|
||||
PassportSurname string `json:"passportSurname"`
|
||||
Phone string `json:"phone"`
|
||||
Status *string `json:"status"`
|
||||
Paid bool `json:"paid"`
|
||||
// PaidThisMonth: a successful payment exists for the current month's
|
||||
// payment period (Ashgabat time).
|
||||
PaidThisMonth bool `json:"paidThisMonth"`
|
||||
}
|
||||
|
||||
type ListVisaMasterPaymentOrderDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
VisaMasterPaymentOrders []VisaMasterPaymentOrderListItemDTO `json:"visaMasterPaymentOrders"`
|
||||
}
|
||||
307
internal/cards/visamaster/handler.go
Normal file
307
internal/cards/visamaster/handler.go
Normal file
@@ -0,0 +1,307 @@
|
||||
package visamaster
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
// orderTypeSber is the type value of Sber orders, matched case-insensitively
|
||||
// like visamasterpay does when it picks Sber fees and credentials.
|
||||
const orderTypeSber = "sber"
|
||||
|
||||
const baseURL = "/visa-master-payment-orders"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := rbac.Group(router, baseURL, rbac.Require(perm.Cards))
|
||||
group.GET("", h.list)
|
||||
group.GET("/sber", h.listSber)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.POST("", h.create)
|
||||
group.PUT("/:id", h.update)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List visa/master payment orders
|
||||
// @Description Returns paginated visa/master payment orders; sber orders are excluded (see /visa-master-payment-orders/sber)
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param name query string false "Filter by passport name or surname"
|
||||
// @Param type query string false "Filter by order type (e.g. student), case-insensitive"
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
filter.ExcludeType = orderTypeSber
|
||||
h.respondList(c, filter)
|
||||
}
|
||||
|
||||
// listSber godoc
|
||||
// @Summary List sber payment orders
|
||||
// @Description Returns paginated payment orders of type sber
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param name query string false "Filter by passport name or surname"
|
||||
// @Param status query string false "Filter by status"
|
||||
// @Param branch_id query int false "Filter by branch ID"
|
||||
// @Param user_id query int false "Filter by user ID"
|
||||
// @Param region query string false "Filter by region"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders/sber [get]
|
||||
func (h *handler) listSber(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
filter.Type = orderTypeSber
|
||||
h.respondList(c, filter)
|
||||
}
|
||||
|
||||
func (h *handler) respondList(c *gin.Context, filter ListFilter) {
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list visa master payment orders failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get visa/master payment order by ID
|
||||
// @Description Returns a single visa/master payment order with branch and user details
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Visa/master payment order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := 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 visa master payment 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 visa/master payment order
|
||||
// @Description Creates a new visa/master payment order
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateVisaMasterPaymentOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||
if err != nil {
|
||||
h.logger.Errorf("create visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update visa/master payment order
|
||||
// @Description Updates an existing visa/master payment order
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Visa/master payment order ID"
|
||||
// @Param body body UpdateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders/{id} [put]
|
||||
func (h *handler) update(c *gin.Context) {
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if !h.guardBranchByID(c, id) {
|
||||
return
|
||||
}
|
||||
|
||||
var dto UpdateVisaMasterPaymentOrderDTO
|
||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.repository.Update(c.Request.Context(), id, dto)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("update visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete visa/master payment order
|
||||
// @Description Deletes a visa/master payment order
|
||||
// @Tags visa-master-payment-orders
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Visa/master payment order ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /visa-master-payment-orders/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := 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 visa master payment order failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("visa master payment order removed"))
|
||||
}
|
||||
|
||||
func 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, "name"); raw != "" {
|
||||
filter.Name = raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "type"); raw != "" {
|
||||
filter.Type = raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
|
||||
if raw := shared.QueryValue(c, "region"); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
11
internal/cards/visamaster/storage.go
Normal file
11
internal/cards/visamaster/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package visamaster
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListVisaMasterPaymentOrderDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (VisaMasterPaymentOrderDTO, error)
|
||||
Create(ctx context.Context, dto CreateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateVisaMasterPaymentOrderDTO) (VisaMasterPaymentOrderDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -16,6 +16,7 @@ type Config struct {
|
||||
Port string `yaml:"port" env-default:"8080"`
|
||||
} `yaml:"listen"`
|
||||
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
||||
PublicBaseURL string `yaml:"public_base_url" env-required:"true"`
|
||||
Storage StorageConfig `yaml:"storage"`
|
||||
Minio MinioConfig `yaml:"minio"`
|
||||
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
||||
|
||||
242
internal/currency/db/postgresql.go
Normal file
242
internal/currency/db/postgresql.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/currency"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"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 = shared.PrefixedColumns("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 (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{}) {
|
||||
conditions := []string{"c.deleted_at IS NULL"}
|
||||
|
||||
if filter.Search != "" {
|
||||
args = append(args, shared.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)))
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (currency.CurrencyDTO, error) {
|
||||
query := `SELECT ` + currencySelectColumns + currencyFromClause + ` WHERE c.id = $1 AND c.deleted_at IS NULL`
|
||||
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`
|
||||
|
||||
item, err := scanCurrencyWithUsers(r.client.QueryRow(ctx, query, from, to, value, dto.CreatedBy))
|
||||
if isUniqueViolation(err) {
|
||||
return currency.CurrencyDTO{}, currency.ErrDuplicate
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
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 AND deleted_at IS NULL
|
||||
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
|
||||
}
|
||||
if isUniqueViolation(err) {
|
||||
return currency.CurrencyDTO{}, currency.ErrDuplicate
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// isUniqueViolation reports whether err is a Postgres unique-constraint
|
||||
// violation (e.g. the currencies_from_to_idx partial unique index rejecting
|
||||
// a duplicate active currency_from/currency_to pair), so callers can map it
|
||||
// to a clean 409 instead of letting it fall through as a generic 500.
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
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 ¤cy.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
88
internal/currency/dto.go
Normal 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"`
|
||||
}
|
||||
279
internal/currency/handler.go
Normal file
279
internal/currency/handler.go
Normal file
@@ -0,0 +1,279 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"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 := rbac.Group(router, baseURL, rbac.Catalog(perm.Currencies))
|
||||
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 := 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 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 409 {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 errors.Is(err, ErrDuplicate) {
|
||||
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
|
||||
return
|
||||
}
|
||||
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 409 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /currencies/{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 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 errors.Is(err, ErrDuplicate) {
|
||||
c.JSON(http.StatusConflict, appresult.ErrDuplicate)
|
||||
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 := 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 currency failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("currency removed"))
|
||||
}
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{Page: shared.DefaultPage, Limit: shared.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 > shared.MaxLimit {
|
||||
limit = shared.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
|
||||
}
|
||||
19
internal/currency/storage.go
Normal file
19
internal/currency/storage.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// ErrDuplicate is returned by Repository.Create/Update when the
|
||||
// currency_from/currency_to pair already exists among active (non-deleted)
|
||||
// rows, so the handler can respond with a clean 409 instead of a raw 500.
|
||||
var ErrDuplicate = errors.New("currency pair already exists")
|
||||
|
||||
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
|
||||
}
|
||||
393
internal/dashboard/db/postgresql.go
Normal file
393
internal/dashboard/db/postgresql.go
Normal 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 deleted_at IS NULL` + 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) AND bu.deleted_at IS NULL)", len(extra)+4)
|
||||
}
|
||||
query := metricSQL(`FROM cards c WHERE c.deleted_at IS NULL` + 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_id = (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL) 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) AND bu.deleted_at IS NULL)", len(extra)+4)
|
||||
}
|
||||
query := metricSQL(`FROM users u WHERE u.deleted_at IS NULL` + 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 deleted_at IS NULL` + 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 AND deleted_at IS NULL%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 AND deleted_at IS NULL%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 deleted_at IS NULL%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 deleted_at IS NULL%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
78
internal/dashboard/dto.go
Normal 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
|
||||
}
|
||||
149
internal/dashboard/handler.go
Normal file
149
internal/dashboard/handler.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/sysstats"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const baseURL = "/dashboard"
|
||||
|
||||
const (
|
||||
defaultRecentLimit = 10
|
||||
maxRecentLimit = 50
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
// diskPaths are the mount points reported by /server-stats.
|
||||
diskPaths []string
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository, diskPaths []string) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository, diskPaths: diskPaths}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard))
|
||||
group.GET("/overview", h.overview)
|
||||
group.GET("/server-stats", h.serverStats)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
redactByPermission(&result, rbac.Can(c, perm.Cards), rbac.Can(c, perm.Loans))
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// serverStats godoc
|
||||
// @Summary Server statistics
|
||||
// @Description Returns host CPU, RAM and disk usage plus the API process's own memory and uptime. CPU usage is sampled over ~250ms; host fields are null when the OS cannot report them.
|
||||
// @Tags dashboard
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} appresult.AppSuccess{data=sysstats.Stats}
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /dashboard/server-stats [get]
|
||||
func (h *handler) serverStats(c *gin.Context) {
|
||||
stats, err := sysstats.Collect(c.Request.Context(), h.diskPaths)
|
||||
if err != nil {
|
||||
h.logger.Errorf("dashboard server stats failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(stats))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// redactByPermission blanks the widgets of modules the caller cannot open, so
|
||||
// e.g. a head of loans sees every branch's loan numbers but no card numbers.
|
||||
func redactByPermission(o *OverviewDTO, cards, loans bool) {
|
||||
if !cards {
|
||||
o.Stats.ActiveCards = StatMetricDTO{}
|
||||
o.Stats.OnlinePayments = StatMetricDTO{}
|
||||
}
|
||||
if !loans {
|
||||
o.Stats.LoanOrders = StatMetricDTO{}
|
||||
o.LoanStatus = []LoanStatusShareDTO{}
|
||||
o.RecentActivity = []RecentActivityDTO{}
|
||||
}
|
||||
for i := range o.Trend.Points {
|
||||
if !cards {
|
||||
o.Trend.Points[i].Cards = 0
|
||||
}
|
||||
if !loans {
|
||||
o.Trend.Points[i].Loans = 0
|
||||
}
|
||||
}
|
||||
for i := range o.WeeklyOrders {
|
||||
if !cards {
|
||||
o.WeeklyOrders[i].Cards = 0
|
||||
}
|
||||
if !loans {
|
||||
o.WeeklyOrders[i].Loans = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
7
internal/dashboard/storage.go
Normal file
7
internal/dashboard/storage.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package dashboard
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Overview(ctx context.Context, filter OverviewFilter) (OverviewDTO, error)
|
||||
}
|
||||
@@ -1,16 +1,30 @@
|
||||
package handlermanager
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"online-back/internal/analytics"
|
||||
analyticsdb "online-back/internal/analytics/db"
|
||||
"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"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/lending"
|
||||
"online-back/internal/org"
|
||||
"online-back/internal/payment"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/paymentgateway"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -47,18 +61,51 @@ 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)
|
||||
adminGroup.Use(activitylog.Record(activitylogdb.NewRepository(client, logger), logger))
|
||||
if err := perm.Sync(context.Background(), client); err != nil {
|
||||
logger.Fatalf("rbac: sync permission catalog: %v", err)
|
||||
}
|
||||
adminGroup.Use(rbac.Guard(rbac.NewService(client)))
|
||||
|
||||
// Each bounded context registers its own modules' handlers.
|
||||
// Add new modules inside the relevant context's router.go rather than here.
|
||||
identity.Register(adminGroup, client, logger)
|
||||
identity.Register(adminGroup, router, client, logger)
|
||||
org.Register(adminGroup, client, logger)
|
||||
lending.Register(adminGroup, client, logger)
|
||||
cards.Register(adminGroup, client, logger)
|
||||
currencyRepo := currencydb.NewRepository(client, logger)
|
||||
payment.Register(adminGroup, client, logger, currencyRepo, paymentGatewayClient(cfg, logger), cfg.PublicBaseURL)
|
||||
currency.NewHandler(logger, currencyRepo).Register(adminGroup)
|
||||
dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger), []string{"/", cfg.PublicFilePath}).Register(adminGroup)
|
||||
analytics.NewHandler(logger, analyticsdb.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)
|
||||
|
||||
// Deny by default: every admin route must declare its policy via rbac.Group.
|
||||
if err := rbac.VerifyRoutes(router.Routes(), adminAPIPrefix); err != nil {
|
||||
logger.Fatal(err)
|
||||
}
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
// paymentGatewayClient picks the real GBÜS client outside debug mode, and
|
||||
// the logging stub in debug mode, so local/dev runs never hit the live
|
||||
// bank gateway by accident.
|
||||
func paymentGatewayClient(cfg *config.Config, logger *logging.Logger) paymentgateway.Client {
|
||||
if cfg.IsDebug != nil && *cfg.IsDebug {
|
||||
return paymentgateway.NewLogClient(logger)
|
||||
}
|
||||
return paymentgateway.NewHTTPClient(logger)
|
||||
}
|
||||
|
||||
@@ -12,16 +12,14 @@ import (
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[activitylog.ActivityLogDTO]
|
||||
logger *logging.Logger
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) activitylog.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "activity_logs", activityLogColumnsSQL, scanActivityLog),
|
||||
logger: logger,
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,13 +29,45 @@ var activityLogColumns = []string{
|
||||
|
||||
var activityLogColumnsSQL = strings.Join(activityLogColumns, ", ")
|
||||
|
||||
const activityLogFromClause = ` FROM activity_logs al
|
||||
LEFT JOIN users u ON u.id = al.user_id
|
||||
LEFT JOIN roles r ON r.id = u.role_id`
|
||||
|
||||
const activityLogSelectColumns = `al.id, al.user_id, al.method, al.path, al.module, al.action, al.status_code, al.request_body, al.ip, al.created_at, COALESCE(u.username, ''), COALESCE(r.code, '')`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter activitylog.ListFilter) (activitylog.ListActivityLogDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id DESC")
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM activity_logs al`+whereClause, args...).Scan(&count); err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY al.id DESC LIMIT $%d OFFSET $%d`,
|
||||
activityLogSelectColumns, activityLogFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []activitylog.ActivityLogDTO
|
||||
for rows.Next() {
|
||||
item, err := scanActivityLog(rows)
|
||||
if err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return activitylog.ListActivityLogDTO{}, err
|
||||
}
|
||||
|
||||
return activitylog.ListActivityLogDTO{Count: count, Logs: items}, nil
|
||||
}
|
||||
@@ -47,17 +77,17 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("user_id = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("al.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Module != "" {
|
||||
args = append(args, filter.Module)
|
||||
conditions = append(conditions, fmt.Sprintf("module = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("al.module = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.Action != "" {
|
||||
args = append(args, filter.Action)
|
||||
conditions = append(conditions, fmt.Sprintf("action = $%d", len(args)))
|
||||
conditions = append(conditions, fmt.Sprintf("al.action = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
@@ -68,12 +98,21 @@ func buildListQuery(filter activitylog.ListFilter) (whereClause string, args []i
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (activitylog.ActivityLogDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
query := `SELECT ` + activityLogSelectColumns + activityLogFromClause + ` WHERE al.id = $1`
|
||||
return scanActivityLog(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityLogDTO) (activitylog.ActivityLogDTO, error) {
|
||||
query := `INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING ` + activityLogColumnsSQL
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
|
||||
RETURNING ` + activityLogColumnsSQL + `
|
||||
)
|
||||
SELECT ` + activityLogSelectColumns + `
|
||||
FROM inserted al
|
||||
LEFT JOIN users u ON u.id = al.user_id
|
||||
LEFT JOIN roles r ON r.id = u.role_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query,
|
||||
dto.UserId, dto.Method, dto.Path, dto.Module, dto.Action, dto.StatusCode, dto.RequestBody, dto.Ip,
|
||||
@@ -84,14 +123,23 @@ func (r *repository) Create(ctx context.Context, dto activitylog.CreateActivityL
|
||||
func scanActivityLog(row genericrepo.Scanner) (activitylog.ActivityLogDTO, error) {
|
||||
var item activitylog.ActivityLogDTO
|
||||
var requestBody []byte
|
||||
var username, role string
|
||||
|
||||
err := row.Scan(
|
||||
&item.Id, &item.UserId, &item.Method, &item.Path, &item.Module, &item.Action,
|
||||
&item.StatusCode, &requestBody, &item.Ip, &item.CreatedAt,
|
||||
&username, &role,
|
||||
)
|
||||
if err != nil {
|
||||
return activitylog.ActivityLogDTO{}, err
|
||||
}
|
||||
item.RequestBody = requestBody
|
||||
if item.UserId != nil {
|
||||
item.User = &activitylog.UserInfo{
|
||||
Id: *item.UserId,
|
||||
Username: username,
|
||||
Role: role,
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
@@ -5,9 +5,16 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type UserInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type ActivityLogDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UserId *int64 `json:"userId"`
|
||||
User *UserInfo `json:"user"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Module string `json:"module"`
|
||||
|
||||
@@ -4,9 +4,13 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -27,14 +31,14 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
||||
// Register only wires read endpoints: activity log entries are written by
|
||||
// the Record middleware, never through the API.
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.ActivityLogs))
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List activity logs
|
||||
// @Description Returns a paginated audit trail of user actions (create/update/delete)
|
||||
// @Description Returns a paginated audit trail of user actions (create/update/delete). Each log includes the actor's username and role code.
|
||||
// @Tags activity-logs
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
@@ -77,9 +81,15 @@ func (h *handler) list(c *gin.Context) {
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /activity-logs/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
id, ok := shared.ParseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
// GET /activity-logs/card-orders → list that module instead of 400.
|
||||
q := c.Request.URL.Query()
|
||||
if q.Get("module") == "" {
|
||||
q.Set("module", c.Param("id"))
|
||||
c.Request.URL.RawQuery = q.Encode()
|
||||
}
|
||||
h.list(c)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -97,38 +107,22 @@ func (h *handler) getByID(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
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,
|
||||
Page: shared.DefaultPage,
|
||||
Limit: shared.DefaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("user_id"); raw != "" {
|
||||
id, ok := parseID(raw)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.UserId = &id
|
||||
if id, ok := optionalQueryID(c, "user_id", "userId"); !ok {
|
||||
return ListFilter{}, false
|
||||
} else if id != nil {
|
||||
filter.UserId = id
|
||||
}
|
||||
|
||||
filter.Module = c.Query("module")
|
||||
filter.Action = c.Query("action")
|
||||
filter.Module = queryValue(c, "module")
|
||||
filter.Action = queryValue(c, "action")
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
if raw := queryValue(c, "page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
@@ -136,13 +130,37 @@ func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
if raw := queryValue(c, "limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
if err != nil || limit < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
if limit > shared.MaxLimit {
|
||||
limit = shared.MaxLimit
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
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 optionalQueryID(c *gin.Context, keys ...string) (*int64, bool) {
|
||||
raw := queryValue(c, keys...)
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, ok := shared.ParseID(raw)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
97
internal/identity/activitylog/handler_test.go
Normal file
97
internal/identity/activitylog/handler_test.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"online-back/internal/shared"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type stubRepository struct {
|
||||
mu sync.Mutex
|
||||
listFilter ListFilter
|
||||
listResult ListActivityLogDTO
|
||||
created []CreateActivityLogDTO
|
||||
}
|
||||
|
||||
func (s *stubRepository) List(_ context.Context, filter ListFilter) (ListActivityLogDTO, error) {
|
||||
s.listFilter = filter
|
||||
return s.listResult, nil
|
||||
}
|
||||
|
||||
func (s *stubRepository) GetByID(_ context.Context, _ int64) (ActivityLogDTO, error) {
|
||||
return ActivityLogDTO{}, nil
|
||||
}
|
||||
|
||||
func (s *stubRepository) Create(_ context.Context, dto CreateActivityLogDTO) (ActivityLogDTO, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.created = append(s.created, dto)
|
||||
return ActivityLogDTO{Id: 1}, nil
|
||||
}
|
||||
|
||||
func (s *stubRepository) createdEntries() []CreateActivityLogDTO {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]CreateActivityLogDTO, len(s.created))
|
||||
copy(out, s.created)
|
||||
return out
|
||||
}
|
||||
|
||||
func TestParseListFilterIgnoresUndefinedAndCapsLimit(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
req := httptest.NewRequest(http.MethodGet, "/activity-logs?user_id=undefined&module=card-orders&limit=1000&page=2", nil)
|
||||
c.Request = req
|
||||
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
t.Fatal("expected filter to parse")
|
||||
}
|
||||
if filter.UserId != nil {
|
||||
t.Fatalf("user_id should be ignored, got %v", *filter.UserId)
|
||||
}
|
||||
if filter.Module != "card-orders" {
|
||||
t.Fatalf("module=%q", filter.Module)
|
||||
}
|
||||
if filter.Limit != shared.MaxLimit {
|
||||
t.Fatalf("limit=%d", filter.Limit)
|
||||
}
|
||||
if filter.Page != 2 {
|
||||
t.Fatalf("page=%d", filter.Page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetByIDListsModuleWhenPathIsNotNumeric(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
repo := &stubRepository{listResult: ListActivityLogDTO{Count: 0, Logs: []ActivityLogDTO{}}}
|
||||
h := &handler{logger: logging.GetLogger(), repository: repo}
|
||||
|
||||
r := gin.New()
|
||||
group := r.Group("/activity-logs")
|
||||
group.GET("", h.list)
|
||||
group.GET("/:id", h.getByID)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/activity-logs/card-orders?limit=1000", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if repo.listFilter.Module != "card-orders" {
|
||||
t.Fatalf("module=%q", repo.listFilter.Module)
|
||||
}
|
||||
if repo.listFilter.Limit != shared.MaxLimit {
|
||||
t.Fatalf("limit=%d", repo.listFilter.Limit)
|
||||
}
|
||||
}
|
||||
@@ -15,53 +15,87 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// sensitiveFieldSubstrings marks request body keys that must never be
|
||||
// persisted verbatim (login passwords, branch billing credentials, etc).
|
||||
var sensitiveFieldSubstrings = []string{"password", "token", "secret"}
|
||||
|
||||
const writeTimeout = 5 * time.Second
|
||||
const (
|
||||
writeTimeout = 5 * time.Second
|
||||
queueSize = 1024
|
||||
workers = 2
|
||||
)
|
||||
|
||||
type recorder struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
queue chan CreateActivityLogDTO
|
||||
}
|
||||
|
||||
// Record returns a global gin middleware that persists every mutating
|
||||
// (POST/PUT/PATCH/DELETE) request made by an authenticated user into
|
||||
// activity_logs - e.g. creating a card or attaching a user to a branch.
|
||||
// Read-only (GET) requests are not recorded. It must run after
|
||||
// appresult.JwtTokenCheck has set "id" in the context, which happens
|
||||
// naturally here since c.Next() runs the rest of the chain first.
|
||||
// Read-only (GET) requests are not recorded. After the handler finishes
|
||||
// the entry is queued (the client is not blocked) and a small worker
|
||||
// pool writes it. JwtTokenCheck sets "id" during c.Next(), which is why
|
||||
// the user is read afterwards.
|
||||
func Record(repository Repository, logger *logging.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !shouldRecord(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
return newRecorder(repository, logger).handle
|
||||
}
|
||||
|
||||
body := readAndRestoreBody(c)
|
||||
func newRecorder(repository Repository, logger *logging.Logger) *recorder {
|
||||
r := &recorder{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
queue: make(chan CreateActivityLogDTO, queueSize),
|
||||
}
|
||||
for i := 0; i < workers; i++ {
|
||||
go r.worker()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *recorder) handle(c *gin.Context) {
|
||||
if !shouldRecord(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID := currentUserID(c)
|
||||
if userID == nil {
|
||||
return
|
||||
body := readAndRestoreBody(c)
|
||||
|
||||
c.Next()
|
||||
|
||||
userID := currentUserID(c)
|
||||
if userID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
id := *userID
|
||||
module, action := describeRoute(c)
|
||||
r.enqueue(CreateActivityLogDTO{
|
||||
UserId: &id,
|
||||
Method: c.Request.Method,
|
||||
Path: c.Request.URL.Path,
|
||||
Module: module,
|
||||
Action: action,
|
||||
StatusCode: c.Writer.Status(),
|
||||
RequestBody: redact(body),
|
||||
Ip: c.ClientIP(),
|
||||
})
|
||||
}
|
||||
|
||||
func (r *recorder) enqueue(entry CreateActivityLogDTO) {
|
||||
select {
|
||||
case r.queue <- entry:
|
||||
default:
|
||||
r.logger.Errorf("activity log queue full, dropping %s %s", entry.Method, entry.Path)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *recorder) worker() {
|
||||
for entry := range r.queue {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
|
||||
if _, err := r.repository.Create(ctx, entry); err != nil {
|
||||
r.logger.Errorf("record activity log failed: %v", err)
|
||||
}
|
||||
|
||||
module, action := describeRoute(c)
|
||||
entry := CreateActivityLogDTO{
|
||||
UserId: userID,
|
||||
Method: c.Request.Method,
|
||||
Path: c.Request.URL.Path,
|
||||
Module: module,
|
||||
Action: action,
|
||||
StatusCode: c.Writer.Status(),
|
||||
RequestBody: redact(body),
|
||||
Ip: c.ClientIP(),
|
||||
}
|
||||
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), writeTimeout)
|
||||
defer cancel()
|
||||
if _, err := repository.Create(ctx, entry); err != nil {
|
||||
logger.Errorf("record activity log failed: %v", err)
|
||||
}
|
||||
}()
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,9 +114,13 @@ func readAndRestoreBody(c *gin.Context) []byte {
|
||||
}
|
||||
data, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(nil))
|
||||
return nil
|
||||
}
|
||||
// Restore Body for ShouldBindJSON and cache it so ShouldBindBodyWithJSON
|
||||
// still works after this middleware has already consumed the stream.
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(data))
|
||||
c.Set(gin.BodyBytesKey, data)
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
71
internal/identity/activitylog/middleware_test.go
Normal file
71
internal/identity/activitylog/middleware_test.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package activitylog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestRecordLeavesJSONBodyForHandler(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
repo := &stubRepository{}
|
||||
r := gin.New()
|
||||
r.Use(Record(repo, logging.GetLogger()))
|
||||
r.POST("/api/admin/card-orders", func(c *gin.Context) {
|
||||
c.Set("id", "3")
|
||||
var dto struct {
|
||||
CustomerName string `json:"customerName" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto)
|
||||
})
|
||||
|
||||
body := `{"customerName":"Simple","region":"Aşgabat"}`
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/card-orders", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
var created []CreateActivityLogDTO
|
||||
for time.Now().Before(deadline) {
|
||||
created = repo.createdEntries()
|
||||
if len(created) > 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if len(created) == 0 {
|
||||
t.Fatal("expected activity log to be recorded")
|
||||
}
|
||||
if created[0].Module != "card-orders" {
|
||||
t.Fatalf("module=%q", created[0].Module)
|
||||
}
|
||||
if created[0].StatusCode != http.StatusCreated {
|
||||
t.Fatalf("statusCode=%d", created[0].StatusCode)
|
||||
}
|
||||
|
||||
var logged map[string]interface{}
|
||||
if err := json.Unmarshal(created[0].RequestBody, &logged); err != nil {
|
||||
t.Fatalf("request body: %v", err)
|
||||
}
|
||||
if logged["customerName"] != "Simple" {
|
||||
t.Fatalf("logged body=%v", logged)
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,18 @@ package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"online-back/internal/identity/auth"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
@@ -29,19 +34,50 @@ func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Reposi
|
||||
const (
|
||||
loginByNameQuery = `
|
||||
SELECT id, password FROM users
|
||||
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
|
||||
OR LOWER(TRIM(username)) = LOWER(TRIM($1))
|
||||
WHERE (LOWER(TRIM(name)) = LOWER(TRIM($1))
|
||||
OR LOWER(TRIM(username)) = LOWER(TRIM($1)))
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1`
|
||||
loginByPhoneQuery = `
|
||||
SELECT id, password FROM users
|
||||
WHERE phone = $1
|
||||
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2)
|
||||
WHERE (phone = $1
|
||||
OR ($2 <> '' AND regexp_replace(phone, '[^0-9]', '', 'g') = $2))
|
||||
AND deleted_at IS NULL
|
||||
LIMIT 1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
|
||||
profileQuery = `SELECT id, name, first_name, last_name, phone, avatar, created_at
|
||||
FROM users WHERE id = $1`
|
||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1 AND deleted_at IS NULL`
|
||||
)
|
||||
|
||||
const profileFromClause = ` FROM users u
|
||||
LEFT JOIN roles r ON r.id = u.role_id AND r.deleted_at IS NULL`
|
||||
|
||||
const profileBranchesJSON = `COALESCE((
|
||||
SELECT json_agg(jsonb_build_object(
|
||||
'id', b.id,
|
||||
'uniqueCode', COALESCE(b.unique_code, ''),
|
||||
'name', b.name
|
||||
) ORDER BY b.id)
|
||||
FROM (
|
||||
SELECT DISTINCT ON (b.id) b.id, b.unique_code, b.name
|
||||
FROM branch_user bu
|
||||
JOIN branches b ON b.id = bu.branch_id
|
||||
WHERE bu.user_id = u.id AND bu.deleted_at IS NULL AND b.deleted_at IS NULL
|
||||
ORDER BY b.id
|
||||
) b
|
||||
), '[]'::json)`
|
||||
|
||||
// profilePermissionsJSON: every permission for an is_super role, else the
|
||||
// role's own; ordered as rbac/perm.All by the caller.
|
||||
const profilePermissionsJSON = `COALESCE((
|
||||
SELECT json_agg(jsonb_build_object('code', p.code, 'name', p.name))
|
||||
FROM permissions p
|
||||
WHERE r.is_super OR EXISTS (
|
||||
SELECT 1 FROM role_permissions rp WHERE rp.role_id = r.id AND rp.permission_code = p.code
|
||||
)
|
||||
), '[]'::json)`
|
||||
|
||||
const profileQuery = `SELECT u.id, u.name, u.first_name, u.last_name, u.phone, u.avatar, u.created_at,
|
||||
r.id, r.code, r.name, r.scope, COALESCE(r.is_super, false), ` + profileBranchesJSON + `, ` + profilePermissionsJSON + profileFromClause + ` WHERE u.id = $1 AND u.deleted_at IS NULL`
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
|
||||
phone := strings.TrimSpace(dto.Phone)
|
||||
if phone != "" {
|
||||
@@ -66,31 +102,37 @@ func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredenti
|
||||
}
|
||||
|
||||
func (r *repository) GetProfile(ctx context.Context, id int) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
err := r.client.QueryRow(ctx, profileQuery, id).Scan(
|
||||
&profile.Id,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
&profile.LastName,
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
)
|
||||
return profile, err
|
||||
return scanProfile(r.client.QueryRow(ctx, profileQuery, id))
|
||||
}
|
||||
|
||||
const updateProfileQuery = `
|
||||
UPDATE users SET
|
||||
name = $1, first_name = $2, last_name = $3, phone = $4, avatar = $5,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $6
|
||||
RETURNING id, name, first_name, last_name, phone, avatar, created_at`
|
||||
WHERE id = $6 AND deleted_at IS NULL`
|
||||
|
||||
func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateProfileDTO) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
err := r.client.QueryRow(ctx, updateProfileQuery,
|
||||
tag, err := r.client.Exec(ctx, updateProfileQuery,
|
||||
dto.Name, dto.FirstName, dto.LastName, dto.Phone, dto.Avatar, id,
|
||||
).Scan(
|
||||
)
|
||||
if err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return auth.UserProfileDTO{}, pgx.ErrNoRows
|
||||
}
|
||||
return r.GetProfile(ctx, id)
|
||||
}
|
||||
|
||||
func scanProfile(row genericrepo.Scanner) (auth.UserProfileDTO, error) {
|
||||
var profile auth.UserProfileDTO
|
||||
var roleID sql.NullInt64
|
||||
var roleCode, roleName, roleScope sql.NullString
|
||||
var roleSuper bool
|
||||
var branchesJSON []byte
|
||||
var permissionsJSON []byte
|
||||
|
||||
err := row.Scan(
|
||||
&profile.Id,
|
||||
&profile.Name,
|
||||
&profile.FirstName,
|
||||
@@ -98,19 +140,52 @@ func (r *repository) UpdateProfile(ctx context.Context, id int, dto auth.UpdateP
|
||||
&profile.Phone,
|
||||
&profile.Avatar,
|
||||
&profile.CreatedAt,
|
||||
&roleID,
|
||||
&roleCode,
|
||||
&roleName,
|
||||
&roleScope,
|
||||
&roleSuper,
|
||||
&branchesJSON,
|
||||
&permissionsJSON,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
return profile, err
|
||||
|
||||
if roleID.Valid {
|
||||
profile.Role = &auth.ProfileRoleDTO{
|
||||
Id: roleID.Int64,
|
||||
Code: roleCode.String,
|
||||
Name: roleName.String,
|
||||
Scope: roleScope.String,
|
||||
IsSuper: roleSuper,
|
||||
}
|
||||
}
|
||||
|
||||
profile.Branches = []auth.ProfileBranchDTO{}
|
||||
if len(branchesJSON) > 0 && string(branchesJSON) != "null" {
|
||||
if err := json.Unmarshal(branchesJSON, &profile.Branches); err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
profile.Permissions = []auth.ProfilePermissionDTO{}
|
||||
if len(permissionsJSON) > 0 && string(permissionsJSON) != "null" {
|
||||
if err := json.Unmarshal(permissionsJSON, &profile.Permissions); err != nil {
|
||||
return auth.UserProfileDTO{}, err
|
||||
}
|
||||
}
|
||||
sortByCatalog(profile.Permissions)
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func (r *repository) UserExists(ctx context.Context, username, phone string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM users
|
||||
WHERE LOWER(username) = LOWER($1)
|
||||
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2
|
||||
WHERE (LOWER(username) = LOWER($1)
|
||||
OR regexp_replace(phone, '[^0-9]', '', 'g') = $2)
|
||||
AND deleted_at IS NULL
|
||||
)`
|
||||
var exists bool
|
||||
err := r.client.QueryRow(ctx, query, username, digitString(phone)).Scan(&exists)
|
||||
@@ -177,8 +252,8 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
|
||||
|
||||
var userID int
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO users (name, username, phone, password, role, active, email)
|
||||
VALUES ($1, $2, $3, $4, 'user', true, '')
|
||||
INSERT INTO users (name, username, phone, password, role_id, active, email)
|
||||
VALUES ($1, $2, $3, $4, (SELECT id FROM roles WHERE code = 'user' AND deleted_at IS NULL), true, '')
|
||||
RETURNING id`,
|
||||
v.Name, v.Username, v.Phone, v.Password,
|
||||
).Scan(&userID)
|
||||
@@ -203,7 +278,7 @@ func (r *repository) CompleteRegistration(ctx context.Context, v auth.Verificati
|
||||
func (r *repository) GetUserByName(ctx context.Context, name string) (auth.UserIdentity, error) {
|
||||
const query = `
|
||||
SELECT id, name, username, phone FROM users
|
||||
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1))
|
||||
WHERE LOWER(TRIM(name)) = LOWER(TRIM($1)) AND deleted_at IS NULL
|
||||
LIMIT 1`
|
||||
|
||||
var user auth.UserIdentity
|
||||
@@ -225,7 +300,7 @@ func (r *repository) CompletePasswordReset(ctx context.Context, userID int, veri
|
||||
UPDATE users SET
|
||||
password = $1,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $2`, passwordHash, userID)
|
||||
WHERE id = $2 AND deleted_at IS NULL`, passwordHash, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -249,3 +324,13 @@ func digitString(s string) string {
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func sortByCatalog(perms []auth.ProfilePermissionDTO) {
|
||||
order := make(map[perm.Code]int, len(perm.All))
|
||||
for i, d := range perm.All {
|
||||
order[d.Code] = i
|
||||
}
|
||||
sort.SliceStable(perms, func(i, j int) bool {
|
||||
return order[perm.Code(perms[i].Code)] < order[perm.Code(perms[j].Code)]
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,14 +12,44 @@ type RefreshTokenDTO struct {
|
||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
||||
}
|
||||
|
||||
type LocalizedText struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type ProfileRoleDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
IsSuper bool `json:"isSuper"`
|
||||
}
|
||||
|
||||
type ProfileBranchDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
UniqueCode string `json:"uniqueCode"`
|
||||
Name LocalizedText `json:"name"`
|
||||
}
|
||||
|
||||
// ProfilePermissionDTO is one module the caller can open; the front-end
|
||||
// builds its menu from this list.
|
||||
type ProfilePermissionDTO struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type UserProfileDTO struct {
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Id int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Phone string `json:"phone"`
|
||||
Avatar string `json:"avatar"`
|
||||
Role *ProfileRoleDTO `json:"role"`
|
||||
Branches []ProfileBranchDTO `json:"branches"`
|
||||
Permissions []ProfilePermissionDTO `json:"permissions"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UpdateProfileDTO struct {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/sms"
|
||||
|
||||
@@ -35,16 +36,16 @@ func NewHandler(logger *logging.Logger, repository Repository, sender sms.Sender
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.POST(loginURL, h.login)
|
||||
router.POST(tokenURL, h.refreshToken)
|
||||
router.POST(registerURL, h.register)
|
||||
router.POST(verifyURL, h.verify)
|
||||
router.POST(forgotPasswordURL, h.forgotPassword)
|
||||
router.POST(resetPasswordURL, h.resetPassword)
|
||||
rbac.Group(router, loginURL, rbac.Public()).POST("", h.login)
|
||||
rbac.Group(router, tokenURL, rbac.Public()).POST("", h.refreshToken)
|
||||
rbac.Group(router, registerURL, rbac.Public()).POST("", h.register)
|
||||
rbac.Group(router, verifyURL, rbac.Public()).POST("", h.verify)
|
||||
rbac.Group(router, forgotPasswordURL, rbac.Public()).POST("", h.forgotPassword)
|
||||
rbac.Group(router, resetPasswordURL, rbac.Public()).POST("", h.resetPassword)
|
||||
|
||||
protected := router.Group("", appresult.JwtTokenCheck())
|
||||
protected.GET(profileURL, h.getProfile)
|
||||
protected.PUT(profileURL, h.updateProfile)
|
||||
profile := rbac.Group(router, profileURL, rbac.Authenticated())
|
||||
profile.GET("", h.getProfile)
|
||||
profile.PUT("", h.updateProfile)
|
||||
}
|
||||
|
||||
// login godoc
|
||||
@@ -242,7 +243,7 @@ func (h *handler) refreshToken(c *gin.Context) {
|
||||
|
||||
// getProfile godoc
|
||||
// @Summary Get profile
|
||||
// @Description Returns the authenticated user's profile
|
||||
// @Description Returns the authenticated user's profile with role, branches, and permissions grouped by saha (module)
|
||||
// @Tags auth
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
package auth
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizePhone(t *testing.T) {
|
||||
tests := []struct {
|
||||
in, want string
|
||||
}{
|
||||
{"+99361531216", "+993 61 53 12 16"},
|
||||
{"+993 61 92 92 48", "+993 61 92 92 48"},
|
||||
{"+99361929248", "+993 61 92 92 48"},
|
||||
{"99361929248", "+993 61 92 92 48"},
|
||||
{"61929248", "+993 61 92 92 48"},
|
||||
{"8 61929248", "+993 61 92 92 48"},
|
||||
{"61 92 92 48", "+993 61 92 92 48"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got, err := NormalizePhone(tt.in)
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizePhone(%q) unexpected error: %v", tt.in, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("NormalizePhone(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := NormalizePhone("123"); err != ErrInvalidPhone {
|
||||
t.Errorf("NormalizePhone(123) error = %v, want ErrInvalidPhone", err)
|
||||
}
|
||||
|
||||
validPrefixes := []string{"61", "62", "63", "64", "65", "71", "72"}
|
||||
for _, prefix := range validPrefixes {
|
||||
in := prefix + "929248"
|
||||
if _, err := NormalizePhone(in); err != nil {
|
||||
t.Errorf("NormalizePhone(%q) unexpected error: %v", in, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"60929248", "66929248", "70929248", "73929248", "81929248",
|
||||
"+99366531216", "+99360929248",
|
||||
}
|
||||
for _, in := range invalid {
|
||||
if _, err := NormalizePhone(in); err != ErrInvalidPhone {
|
||||
t.Errorf("NormalizePhone(%q) error = %v, want ErrInvalidPhone", in, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type fakeRepo struct {
|
||||
exists bool
|
||||
usernameTaken bool
|
||||
verification Verification
|
||||
getErr error
|
||||
userID int
|
||||
userByName UserIdentity
|
||||
userByNameErr error
|
||||
loginUser UserCredentials
|
||||
loginErr error
|
||||
lastLogin LoginDTO
|
||||
}
|
||||
|
||||
func (f *fakeRepo) Login(_ context.Context, dto LoginDTO) (UserCredentials, error) {
|
||||
f.lastLogin = dto
|
||||
if f.loginErr != nil {
|
||||
return UserCredentials{}, f.loginErr
|
||||
}
|
||||
return f.loginUser, nil
|
||||
}
|
||||
func (f *fakeRepo) GetUserByID(context.Context, int) (UserCredentials, error) {
|
||||
return UserCredentials{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) GetProfile(context.Context, int) (UserProfileDTO, error) {
|
||||
return UserProfileDTO{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) UpdateProfile(context.Context, int, UpdateProfileDTO) (UserProfileDTO, error) {
|
||||
return UserProfileDTO{}, errors.New("not implemented")
|
||||
}
|
||||
func (f *fakeRepo) UserExists(context.Context, string, string) (bool, error) {
|
||||
return f.exists, nil
|
||||
}
|
||||
func (f *fakeRepo) UsernameTaken(context.Context, string, string) (bool, error) {
|
||||
return f.usernameTaken, nil
|
||||
}
|
||||
func (f *fakeRepo) UpsertVerification(_ context.Context, v Verification) error {
|
||||
f.verification = v
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) GetVerificationByPhone(context.Context, string) (Verification, error) {
|
||||
return f.verification, f.getErr
|
||||
}
|
||||
func (f *fakeRepo) IncrementVerifyAttempts(context.Context, int64) error {
|
||||
f.verification.Attempts++
|
||||
return nil
|
||||
}
|
||||
func (f *fakeRepo) CompleteRegistration(context.Context, Verification) (int, error) {
|
||||
return f.userID, nil
|
||||
}
|
||||
func (f *fakeRepo) GetUserByName(context.Context, string) (UserIdentity, error) {
|
||||
if f.userByNameErr != nil {
|
||||
return UserIdentity{}, f.userByNameErr
|
||||
}
|
||||
return f.userByName, nil
|
||||
}
|
||||
func (f *fakeRepo) CompletePasswordReset(context.Context, int, int64, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeSMS struct {
|
||||
phone, message string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSMS) Send(_ context.Context, phone, message string) error {
|
||||
f.phone = phone
|
||||
f.message = message
|
||||
return f.err
|
||||
}
|
||||
|
||||
func validRegisterDTO() RegisterDTO {
|
||||
return RegisterDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Phone: "+993 61 92 92 48",
|
||||
Username: "berdi",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "secret1",
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRequiresNameOrPhone(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Password: "secret1",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginIgnoresInvalidPhoneWhenNamePresent(t *testing.T) {
|
||||
repo := &fakeRepo{loginErr: errors.New("stop after lookup")}
|
||||
_, _ = NewService(repo, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Name: "admin",
|
||||
Phone: "string",
|
||||
Password: "Test1234!",
|
||||
})
|
||||
if repo.lastLogin.Name != "admin" {
|
||||
t.Fatalf("name = %q, want admin", repo.lastLogin.Name)
|
||||
}
|
||||
if repo.lastLogin.Phone != "" {
|
||||
t.Fatalf("phone = %q, want empty", repo.lastLogin.Phone)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginInvalidPhoneWithoutName(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Phone: "string",
|
||||
Password: "secret1",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginWrongPassword(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("secret1"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = NewService(&fakeRepo{loginUser: UserCredentials{Id: 7, Password: string(hash)}}, &fakeSMS{}).Login(context.Background(), LoginDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Password: "wrong",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCredentials) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCredentials", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterPasswordMismatch(t *testing.T) {
|
||||
dto := validRegisterDTO()
|
||||
dto.PasswordConfirm = "other"
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).Register(context.Background(), dto)
|
||||
if !errors.Is(err, ErrPasswordMismatch) {
|
||||
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterConflict(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{exists: true}, &fakeSMS{}).Register(context.Background(), validRegisterDTO())
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("error = %v, want ErrConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterSendsSMS(t *testing.T) {
|
||||
repo := &fakeRepo{}
|
||||
sender := &fakeSMS{}
|
||||
result, err := NewService(repo, sender).Register(context.Background(), validRegisterDTO())
|
||||
if err != nil {
|
||||
t.Fatalf("Register: %v", err)
|
||||
}
|
||||
if result.Phone != "+993 61 92 92 48" {
|
||||
t.Errorf("phone = %q", result.Phone)
|
||||
}
|
||||
if result.ExpiresIn != 60 {
|
||||
t.Errorf("expiresIn = %d", result.ExpiresIn)
|
||||
}
|
||||
if sender.phone != result.Phone {
|
||||
t.Errorf("sms phone = %q", sender.phone)
|
||||
}
|
||||
if !strings.Contains(sender.message, "123456") {
|
||||
t.Errorf("sms message = %q", sender.message)
|
||||
}
|
||||
if repo.verification.Password == "secret1" {
|
||||
t.Fatal("password stored in plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyWrongCode(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &fakeRepo{verification: Verification{
|
||||
ID: 1,
|
||||
Phone: "+993 61 92 92 48",
|
||||
CodeHash: string(hash),
|
||||
ExpiresAt: time.Now().UTC().Add(time.Minute),
|
||||
}}
|
||||
_, err = NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
|
||||
Phone: "+993 61 92 92 48",
|
||||
Code: "000000",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
if repo.verification.Attempts != 1 {
|
||||
t.Errorf("attempts = %d, want 1", repo.verification.Attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExpiredCode(t *testing.T) {
|
||||
repo := &fakeRepo{verification: Verification{
|
||||
ExpiresAt: time.Now().UTC().Add(-time.Minute),
|
||||
}}
|
||||
_, err := NewService(repo, &fakeSMS{}).Verify(context.Background(), VerifyDTO{
|
||||
Phone: "+993 61 92 92 48",
|
||||
Code: "123456",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgotPasswordRequiresName(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{})
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgotPasswordNotFound(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{userByNameErr: ErrNotFound}, &fakeSMS{}).ForgotPassword(context.Background(), ForgotPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
})
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("error = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgotPasswordSendsSMS(t *testing.T) {
|
||||
repo := &fakeRepo{userByName: UserIdentity{
|
||||
Id: 7,
|
||||
Name: "Berdi Berdiyew",
|
||||
Username: "berdi",
|
||||
Phone: "+993 61 92 92 48",
|
||||
}}
|
||||
sender := &fakeSMS{}
|
||||
result, err := NewService(repo, sender).ForgotPassword(context.Background(), ForgotPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ForgotPassword: %v", err)
|
||||
}
|
||||
if result.Phone != "+993 61 92 92 48" {
|
||||
t.Errorf("phone = %q", result.Phone)
|
||||
}
|
||||
if sender.phone != result.Phone {
|
||||
t.Errorf("sms phone = %q", sender.phone)
|
||||
}
|
||||
if !strings.Contains(sender.message, "123456") {
|
||||
t.Errorf("sms message = %q", sender.message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswordMismatch(t *testing.T) {
|
||||
_, err := NewService(&fakeRepo{}, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Code: "123456",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "other",
|
||||
})
|
||||
if !errors.Is(err, ErrPasswordMismatch) {
|
||||
t.Fatalf("error = %v, want ErrPasswordMismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswordWrongCode(t *testing.T) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := &fakeRepo{
|
||||
userByName: UserIdentity{Id: 7, Phone: "+993 61 92 92 48"},
|
||||
verification: Verification{
|
||||
ID: 1,
|
||||
Phone: "+993 61 92 92 48",
|
||||
CodeHash: string(hash),
|
||||
ExpiresAt: time.Now().UTC().Add(time.Minute),
|
||||
},
|
||||
}
|
||||
_, err = NewService(repo, &fakeSMS{}).ResetPassword(context.Background(), ResetPasswordDTO{
|
||||
Name: "Berdi Berdiyew",
|
||||
Code: "000000",
|
||||
Password: "secret1",
|
||||
PasswordConfirm: "secret1",
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidCode) {
|
||||
t.Fatalf("error = %v, want ErrInvalidCode", err)
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/identity/permission"
|
||||
"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[permission.PermissionDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) permission.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "permissions p", permissionColumns, scanPermission),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const permissionColumns = `p.id, p.code, p.name, p.guard_name, p.created_at, p.updated_at`
|
||||
|
||||
const permissionReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permission.ListFilter) (permission.ListPermissionDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return permission.ListPermissionDTO{}, err
|
||||
}
|
||||
|
||||
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permission.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`p.name ILIKE $%d`, n))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (permission.PermissionDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permission.CreatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
INSERT INTO permissions (code, name, guard_name)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
return scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto permission.UpdatePermissionDTO) (permission.PermissionDTO, error) {
|
||||
query := fmt.Sprintf(`
|
||||
UPDATE permissions SET
|
||||
code = $1, name = $2, guard_name = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING %s`, permissionReturningColumns)
|
||||
|
||||
item, err := scanPermission(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func scanPermission(row genericrepo.Scanner) (permission.PermissionDTO, error) {
|
||||
var item permission.PermissionDTO
|
||||
if err := row.Scan(
|
||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
||||
); err != nil {
|
||||
return permission.PermissionDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package permission
|
||||
|
||||
import "time"
|
||||
|
||||
type PermissionDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
GuardName string `json:"guardName"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdatePermissionDTO struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
GuardName string `json:"guardName" binding:"required"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
PermissionName string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListPermissionDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Permissions []PermissionDTO `json:"permissions"`
|
||||
}
|
||||
@@ -1,242 +1,40 @@
|
||||
package permission
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/internal/identity/rbac"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/permissions"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
// handler serves the permission catalog. Permissions are defined in code
|
||||
// (rbac/perm) - one per module - so there is nothing to create or edit here;
|
||||
// roles pick from this list via POST/PUT /roles.
|
||||
type handler struct{}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{logger: logger, repository: repository}
|
||||
func NewHandler() handlers.Handler {
|
||||
return &handler{}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Roles))
|
||||
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 permissions
|
||||
// @Description Returns paginated permissions with optional filters
|
||||
// @Description Returns the permission catalog: one code per module, in display order. Holding a code grants read and write in that module; the role's scope decides which records.
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by name"
|
||||
// @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 /permissions [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 permissions failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get permission by ID
|
||||
// @Description Returns a single permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create permission
|
||||
// @Description Creates a new permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreatePermissionDTO true "Permission payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreatePermissionDTO
|
||||
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 failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update permission
|
||||
// @Description Updates an existing permission
|
||||
// @Tags permission
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Param body body UpdatePermissionDTO true "Permission payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{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 UpdatePermissionDTO
|
||||
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 permission failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete permission
|
||||
// @Description Deletes a permission
|
||||
// @Tags permission
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Permission ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permissions/{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 failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission removed"))
|
||||
}
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
filter := ListFilter{
|
||||
Page: defaultPage,
|
||||
Limit: defaultLimit,
|
||||
}
|
||||
|
||||
if raw := c.Query("page"); raw != "" {
|
||||
page, err := strconv.Atoi(raw)
|
||||
if err != nil || page < 1 {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Page = page
|
||||
}
|
||||
|
||||
if raw := c.Query("limit"); raw != "" {
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Limit = limit
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("permission_name")); raw != "" {
|
||||
filter.PermissionName = raw
|
||||
}
|
||||
|
||||
return filter, true
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(perm.All))
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
package permission
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (PermissionDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionDTO) (PermissionDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdatePermissionDTO) (PermissionDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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}
|
||||
}
|
||||
|
||||
const permissionUserFromClause = ` FROM permission_user pu
|
||||
JOIN permissions p ON p.id = pu.permission_id
|
||||
JOIN users u ON u.id = pu.user_id`
|
||||
|
||||
const permissionUserSelectColumns = `pu.id, pu.permission_id, p.name, pu.user_id, u.name, pu.created_at, pu.updated_at`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter permissionuser.ListFilter) (permissionuser.ListPermissionUserDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*)`+permissionUserFromClause+whereClause, args...).Scan(&count); err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
|
||||
query := `SELECT ` + permissionUserSelectColumns + permissionUserFromClause + whereClause + ` ORDER BY pu.id DESC`
|
||||
rows, err := r.client.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []permissionuser.PermissionUserDTO
|
||||
for rows.Next() {
|
||||
item, err := scanPermissionUser(rows)
|
||||
if err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return permissionuser.ListPermissionUserDTO{}, err
|
||||
}
|
||||
|
||||
return permissionuser.ListPermissionUserDTO{Count: count, Items: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter permissionuser.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.UserId != nil {
|
||||
args = append(args, *filter.UserId)
|
||||
conditions = append(conditions, fmt.Sprintf("pu.user_id = $%d", len(args)))
|
||||
}
|
||||
|
||||
if filter.PermissionName != "" {
|
||||
args = append(args, likePattern(filter.PermissionName))
|
||||
conditions = append(conditions, fmt.Sprintf("p.name ILIKE $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return "%" + term + "%"
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto permissionuser.CreatePermissionUserDTO) (permissionuser.PermissionUserDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO permission_user (permission_id, user_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, permission_id, user_id, created_at, updated_at
|
||||
)
|
||||
SELECT inserted.id, inserted.permission_id, p.name, inserted.user_id, u.name, inserted.created_at, inserted.updated_at
|
||||
FROM inserted
|
||||
JOIN permissions p ON p.id = inserted.permission_id
|
||||
JOIN users u ON u.id = inserted.user_id`
|
||||
|
||||
row := r.client.QueryRow(ctx, query, dto.PermissionId, dto.UserId)
|
||||
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.CreatedAt, &item.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return permissionuser.PermissionUserDTO{}, err
|
||||
}
|
||||
if err != nil {
|
||||
return permissionuser.PermissionUserDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ListPermissionUserDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Items []PermissionUserDTO `json:"items"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
UserId *int64
|
||||
PermissionName string
|
||||
}
|
||||
|
||||
type CreatePermissionUserDTO struct {
|
||||
PermissionId int64 `json:"permissionId" binding:"required"`
|
||||
UserId int64 `json:"userId" binding:"required"`
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
package permissionuser
|
||||
|
||||
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 = "/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.GET("", h.list)
|
||||
group.POST("", h.create)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List permission users
|
||||
// @Description Returns the authenticated user's permission-user assignments with the related user and permission
|
||||
// @Tags permission-users
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param permission_name query string false "Filter by permission name"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 401 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /permission-users [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
userID, ok := currentUserID(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
filter := ListFilter{
|
||||
UserId: &userID,
|
||||
PermissionName: strings.TrimSpace(c.Query("permission_name")),
|
||||
}
|
||||
|
||||
result, err := h.repository.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list permission users failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Assign user to permission
|
||||
// @Description Creates a permission-user assignment
|
||||
// @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 user from permission
|
||||
// @Description Deletes a permission-user assignment
|
||||
// @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
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
return parseID(id)
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package permissionuser
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListPermissionUserDTO, error)
|
||||
Create(ctx context.Context, dto CreatePermissionUserDTO) (PermissionUserDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
@@ -1,38 +1,358 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/config"
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// RequirePermission returns a gin middleware that 403s unless the
|
||||
// authenticated user (set by appresult.JwtTokenCheck, which must run first)
|
||||
// has been directly granted the given permission code. Not currently
|
||||
// attached to any route.
|
||||
func RequirePermission(service *Service, code string) gin.HandlerFunc {
|
||||
const (
|
||||
contextPrincipal = "rbacPrincipal"
|
||||
contextService = "rbacService"
|
||||
)
|
||||
|
||||
// Public: no token (login, register, payment callback).
|
||||
func Public() Policy {
|
||||
return Policy{name: "public", read: rule{kind: rulePublic}, write: rule{kind: rulePublic}}
|
||||
}
|
||||
|
||||
// Authenticated: any logged-in user, clients included (profile, file).
|
||||
func Authenticated() Policy {
|
||||
return Policy{name: "authenticated", read: rule{kind: ruleAuthenticated}, write: rule{kind: ruleAuthenticated}}
|
||||
}
|
||||
|
||||
// Staff: any logged-in user whose role scope is not own.
|
||||
func Staff() Policy {
|
||||
return Policy{name: "staff", read: rule{kind: ruleStaff}, write: rule{kind: ruleStaff}}
|
||||
}
|
||||
|
||||
// Require: code for every method. Own-scope callers are limited to their
|
||||
// own records, branch-scope callers to their branches.
|
||||
func Require(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code)}
|
||||
return Policy{name: "require:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// RequireStaff: Require, but never for own-scope callers.
|
||||
func RequireStaff(code perm.Code) Policy {
|
||||
r := rule{kind: rulePermission, perm: string(code), staffOnly: true}
|
||||
return Policy{name: "require-staff:" + string(code), read: r, write: r}
|
||||
}
|
||||
|
||||
// Catalog: reference data every logged-in user reads (loan types, branches,
|
||||
// currencies, ...); writes need code and a staff scope.
|
||||
func Catalog(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "catalog:" + string(code),
|
||||
read: rule{kind: ruleAuthenticated},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// StaffRead: any staff member reads, writes need code.
|
||||
func StaffRead(code perm.Code) Policy {
|
||||
return Policy{
|
||||
name: "staff-read:" + string(code),
|
||||
read: rule{kind: ruleStaff},
|
||||
write: rule{kind: rulePermission, perm: string(code), staffOnly: true},
|
||||
}
|
||||
}
|
||||
|
||||
// Guard runs on every /api/admin request before the route's group
|
||||
// middleware: it resolves the route's policy (deny if none), and for
|
||||
// non-public routes loads the caller's principal into the context.
|
||||
func Guard(service Authorizer) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
if c.Request.Method == http.MethodOptions || c.FullPath() == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := strconv.ParseInt(rawID.(string), 10, 64)
|
||||
policy, ok := routes.lookup(c.FullPath())
|
||||
if !ok {
|
||||
abortForbidden(c, "route has no rbac policy", nil)
|
||||
return
|
||||
}
|
||||
if policy.public() {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := requestUserID(c)
|
||||
if !ok {
|
||||
// The group's JwtTokenCheck answers with the proper 401/403.
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
principal, err := service.Load(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
granted, err := service.HasPermission(c.Request.Context(), userID, code)
|
||||
if err != nil || !granted {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrUnauthorized)
|
||||
logging.GetLogger().Errorf("rbac: load principal %d failed: %v", userID, err)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if principal == nil {
|
||||
abortForbidden(c, "user or role not found", logrus.Fields{"userId": userID})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("id", strconv.FormatInt(userID, 10))
|
||||
c.Set(contextPrincipal, principal)
|
||||
c.Set(contextService, service)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func (p Policy) handler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
r := p.ruleFor(c.Request.Method)
|
||||
principal := PrincipalFrom(c)
|
||||
if principal == nil {
|
||||
abortForbidden(c, "no principal", nil)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.kind {
|
||||
case ruleAuthenticated:
|
||||
case ruleStaff:
|
||||
if principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID})
|
||||
return
|
||||
}
|
||||
case rulePermission:
|
||||
if !principal.Can(perm.Code(r.perm)) {
|
||||
abortForbidden(c, "missing permission", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if r.staffOnly && principal.Scope == ScopeOwn {
|
||||
abortForbidden(c, "staff only", logrus.Fields{"userId": principal.UserID, "permission": r.perm})
|
||||
return
|
||||
}
|
||||
if !enforceScope(c, principal) {
|
||||
return
|
||||
}
|
||||
default:
|
||||
abortForbidden(c, "unknown rule", nil)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// enforceScope applies the role's data scope to a permission-gated request.
|
||||
// own: list queries and write bodies are pinned to the caller's user id.
|
||||
// branch: the caller must have branches, and write bodies may only name
|
||||
// those branches (and, on update, users visible in them).
|
||||
func enforceScope(c *gin.Context, p *Principal) bool {
|
||||
switch p.Scope {
|
||||
case ScopeAll:
|
||||
return true
|
||||
case ScopeOwn:
|
||||
pinOwnQuery(c, p.UserID)
|
||||
return pinOwnBody(c, p.UserID)
|
||||
case ScopeBranch:
|
||||
if len(p.BranchIDs) == 0 {
|
||||
abortForbidden(c, "branch scope without assigned branches", logrus.Fields{"userId": p.UserID})
|
||||
return false
|
||||
}
|
||||
return branchWriteAllowed(c, p.BranchIDs)
|
||||
}
|
||||
abortForbidden(c, "unknown scope", logrus.Fields{"userId": p.UserID, "scope": p.Scope})
|
||||
return false
|
||||
}
|
||||
|
||||
func pinOwnQuery(c *gin.Context, userID int64) {
|
||||
query := c.Request.URL.Query()
|
||||
id := strconv.FormatInt(userID, 10)
|
||||
query.Set("user_id", id)
|
||||
query.Set("created_by", id)
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
}
|
||||
|
||||
func pinOwnBody(c *gin.Context, userID int64) bool {
|
||||
if !isWrite(c.Request.Method) || c.Request.Method == http.MethodDelete {
|
||||
return true
|
||||
}
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
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
|
||||
payload["createdBy"] = userID
|
||||
payload["created_by"] = 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 branchWriteAllowed(c *gin.Context, branchIDs []int64) bool {
|
||||
switch c.Request.Method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
default:
|
||||
return true
|
||||
}
|
||||
body, ok := readBody(c)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
BranchId *int64 `json:"branchId"`
|
||||
UserId *int64 `json:"userId"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
if payload.BranchId != nil && *payload.BranchId > 0 && !containsInt64(branchIDs, *payload.BranchId) {
|
||||
abortForbidden(c, "payload branchId not in caller's branches", logrus.Fields{
|
||||
"requestedBranchId": *payload.BranchId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
// A new order's customer has no record in the branch yet; the branchId
|
||||
// check above already scopes the create, so only reassignment (PUT/PATCH)
|
||||
// has to name a user visible in the caller's branches.
|
||||
if c.Request.Method == http.MethodPost || payload.UserId == nil || *payload.UserId <= 0 {
|
||||
return true
|
||||
}
|
||||
service := serviceFrom(c)
|
||||
if service == nil {
|
||||
abortForbidden(c, "no rbac service", nil)
|
||||
return false
|
||||
}
|
||||
visible, err := service.UserVisibleInBranches(c.Request.Context(), *payload.UserId, branchIDs)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return false
|
||||
}
|
||||
if !visible {
|
||||
abortForbidden(c, "payload userId not visible in caller's branches", logrus.Fields{
|
||||
"requestedUserId": *payload.UserId,
|
||||
"allowedBranchIds": branchIDs,
|
||||
})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func readBody(c *gin.Context) ([]byte, bool) {
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return nil, false
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
|
||||
return body, true
|
||||
}
|
||||
|
||||
func isWrite(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// abortForbidden logs which rbac check denied the request before writing the
|
||||
// 403, since appresult.ErrForbidden alone doesn't say.
|
||||
func abortForbidden(c *gin.Context, reason string, fields logrus.Fields) {
|
||||
entry := logging.GetLogger().WithFields(logrus.Fields{
|
||||
"method": c.Request.Method,
|
||||
"path": c.Request.URL.Path,
|
||||
})
|
||||
for k, v := range fields {
|
||||
entry = entry.WithField(k, v)
|
||||
}
|
||||
entry.Warn("rbac forbidden: " + reason)
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, appresult.ErrForbidden)
|
||||
}
|
||||
|
||||
func requestUserID(c *gin.Context) (int64, bool) {
|
||||
if id, ok := parseContextUserID(c); ok {
|
||||
return id, true
|
||||
}
|
||||
|
||||
token := bearerToken(c.GetHeader("Authorization"))
|
||||
if token == "" {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
claims, err := appresult.TokenClaims(token, config.GetConfig().JwtKey)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return claimUserID(claims)
|
||||
}
|
||||
|
||||
func parseContextUserID(c *gin.Context) (int64, bool) {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
parsed, err := strconv.ParseInt(id, 10, 64)
|
||||
return parsed, err == nil && parsed > 0
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func claimUserID(claims jwt.MapClaims) (int64, bool) {
|
||||
switch id := claims["id"].(type) {
|
||||
case float64:
|
||||
return int64(id), id > 0
|
||||
case int64:
|
||||
return id, id > 0
|
||||
case int:
|
||||
return int64(id), id > 0
|
||||
case string:
|
||||
parsed, err := strconv.ParseInt(id, 10, 64)
|
||||
return parsed, err == nil && parsed > 0
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func bearerToken(header string) string {
|
||||
const prefix = "Bearer "
|
||||
if strings.HasPrefix(header, prefix) {
|
||||
return strings.TrimSpace(header[len(prefix):])
|
||||
}
|
||||
return strings.TrimSpace(header)
|
||||
}
|
||||
|
||||
99
internal/identity/rbac/perm/perm.go
Normal file
99
internal/identity/rbac/perm/perm.go
Normal file
@@ -0,0 +1,99 @@
|
||||
// Package perm is the single source of truth for permission codes. One code
|
||||
// per module: holding it grants every action (read and write) in that module;
|
||||
// which records the caller sees is decided by the role's scope, not here.
|
||||
//
|
||||
// The admin UI can only assign these codes to roles - it cannot create,
|
||||
// rename or delete them. Sync writes this list into the permissions table on
|
||||
// startup so role_permissions' foreign key always matches the code.
|
||||
package perm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"online-back/pkg/client/postgresql"
|
||||
)
|
||||
|
||||
type Code string
|
||||
|
||||
const (
|
||||
Dashboard Code = "dashboard"
|
||||
Cards Code = "cards"
|
||||
Loans Code = "loans"
|
||||
Users Code = "users"
|
||||
Roles Code = "roles"
|
||||
Branches Code = "branches"
|
||||
Provinces Code = "provinces"
|
||||
Currencies Code = "currencies"
|
||||
PaymentSettings Code = "payment-settings"
|
||||
Backups Code = "backups"
|
||||
ActivityLogs Code = "activity-logs"
|
||||
)
|
||||
|
||||
type Def struct {
|
||||
Code Code `json:"code"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// All is also the display order for the admin UI and the profile.
|
||||
var All = []Def{
|
||||
{Dashboard, "Dolandyryş paneli"},
|
||||
{Cards, "Kartlar"},
|
||||
{Loans, "Karzlar"},
|
||||
{Users, "Ulanyjylar"},
|
||||
{Roles, "Rollar"},
|
||||
{Branches, "Şahamçalar"},
|
||||
{Provinces, "Welaýatlar"},
|
||||
{Currencies, "Walýutalar"},
|
||||
{PaymentSettings, "Töleg sazlamalary"},
|
||||
{Backups, "Ätiýaçlyk nusgalary"},
|
||||
{ActivityLogs, "Hereket žurnaly"},
|
||||
}
|
||||
|
||||
var known = func() map[Code]struct{} {
|
||||
m := make(map[Code]struct{}, len(All))
|
||||
for _, d := range All {
|
||||
m[d.Code] = struct{}{}
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
func Valid(code Code) bool {
|
||||
_, ok := known[code]
|
||||
return ok
|
||||
}
|
||||
|
||||
func Codes() []Code {
|
||||
out := make([]Code, len(All))
|
||||
for i, d := range All {
|
||||
out[i] = d.Code
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Sync upserts All into the permissions table and removes codes no longer
|
||||
// in the catalog (role_permissions rows go with them via ON DELETE CASCADE).
|
||||
func Sync(ctx context.Context, client postgresql.Client) error {
|
||||
tx, err := client.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
codes := make([]string, len(All))
|
||||
names := make([]string, len(All))
|
||||
for i, d := range All {
|
||||
codes[i] = string(d.Code)
|
||||
names[i] = d.Name
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO permissions (code, name)
|
||||
SELECT * FROM unnest($1::varchar[], $2::varchar[])
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name`, codes, names); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM permissions WHERE NOT (code = ANY($1::varchar[]))`, codes); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
155
internal/identity/rbac/principal.go
Normal file
155
internal/identity/rbac/principal.go
Normal file
@@ -0,0 +1,155 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
)
|
||||
|
||||
// Scope decides which records a role's permissions apply to. It is the only
|
||||
// data-visibility knob: "what can I do" is the permission list, "on whose
|
||||
// records" is the scope.
|
||||
type Scope string
|
||||
|
||||
const (
|
||||
ScopeOwn Scope = "own" // only records the caller owns (clients)
|
||||
ScopeBranch Scope = "branch" // records of the caller's branch_user branches
|
||||
ScopeAll Scope = "all" // every branch
|
||||
)
|
||||
|
||||
// Name is the Turkmen display label for the admin UI.
|
||||
func (s Scope) Name() string {
|
||||
switch s {
|
||||
case ScopeOwn:
|
||||
return "Diňe öz maglumatlary"
|
||||
case ScopeBranch:
|
||||
return "Öz şahamçalary"
|
||||
case ScopeAll:
|
||||
return "Ähli şahamçalar"
|
||||
default:
|
||||
return string(s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s Scope) Valid() bool {
|
||||
return s == ScopeOwn || s == ScopeBranch || s == ScopeAll
|
||||
}
|
||||
|
||||
func (s Scope) rank() int {
|
||||
switch s {
|
||||
case ScopeBranch:
|
||||
return 1
|
||||
case ScopeAll:
|
||||
return 2
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Principal is the caller as rbac sees it, loaded once per request (cached
|
||||
// across requests, see Service.Load). Treat it as read-only.
|
||||
type Principal struct {
|
||||
UserID int64
|
||||
RoleID int64
|
||||
RoleCode string
|
||||
Scope Scope
|
||||
IsSuper bool
|
||||
Perms map[perm.Code]struct{}
|
||||
BranchIDs []int64
|
||||
}
|
||||
|
||||
func (p *Principal) Can(code perm.Code) bool {
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
if p.IsSuper {
|
||||
return true
|
||||
}
|
||||
_, ok := p.Perms[code]
|
||||
return ok
|
||||
}
|
||||
|
||||
// PermCodes lists the caller's effective permissions in catalog order.
|
||||
func (p *Principal) PermCodes() []perm.Code {
|
||||
out := []perm.Code{}
|
||||
for _, code := range perm.Codes() {
|
||||
if p.Can(code) {
|
||||
out = append(out, code)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RoleInfo is what the grant/edit rules need to know about a role.
|
||||
type RoleInfo struct {
|
||||
ID int64
|
||||
Code string
|
||||
Scope Scope
|
||||
IsSuper bool
|
||||
IsSystem bool
|
||||
Perms []perm.Code
|
||||
}
|
||||
|
||||
var (
|
||||
ErrSuperOnly = errors.New("only a superadmin can grant or change a superadmin role")
|
||||
ErrScopeTooWide = errors.New("role scope is wider than the caller's own scope")
|
||||
ErrPermissionHeld = errors.New("role holds a permission the caller does not have")
|
||||
ErrSystemRole = errors.New("system role scope cannot be changed")
|
||||
ErrUnknownPerm = errors.New("unknown permission code")
|
||||
ErrInvalidScope = errors.New("invalid scope")
|
||||
)
|
||||
|
||||
// CanGrant reports whether the caller may give target to a user - or, the
|
||||
// same question, manage a user who already holds target. A caller can only
|
||||
// hand out what they themselves hold: no wider scope, no permission they
|
||||
// lack, and superadmin only from a superadmin. Own-scope roles (clients)
|
||||
// skip the permission check: they only ever reach the holder's own records,
|
||||
// so a cards-only operator can still register a cards+loans client.
|
||||
func (p *Principal) CanGrant(target RoleInfo) error {
|
||||
if p == nil {
|
||||
return ErrSuperOnly
|
||||
}
|
||||
if p.IsSuper {
|
||||
return nil
|
||||
}
|
||||
if target.IsSuper {
|
||||
return ErrSuperOnly
|
||||
}
|
||||
if target.Scope.rank() > p.Scope.rank() {
|
||||
return ErrScopeTooWide
|
||||
}
|
||||
if target.Scope == ScopeOwn {
|
||||
return nil
|
||||
}
|
||||
for _, code := range target.Perms {
|
||||
if !p.Can(code) {
|
||||
return ErrPermissionHeld
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CanSaveRole checks a role create (existing == nil) or update. The caller
|
||||
// must be able to grant both the role as it is now and as it will be, so
|
||||
// they can neither widen a role past their own rights nor strip one that is
|
||||
// already out of their reach.
|
||||
func (p *Principal) CanSaveRole(existing *RoleInfo, next RoleInfo) error {
|
||||
if !next.Scope.Valid() {
|
||||
return ErrInvalidScope
|
||||
}
|
||||
for _, code := range next.Perms {
|
||||
if !perm.Valid(code) {
|
||||
return ErrUnknownPerm
|
||||
}
|
||||
}
|
||||
if existing != nil {
|
||||
if existing.IsSystem && next.Scope != existing.Scope {
|
||||
return ErrSystemRole
|
||||
}
|
||||
if err := p.CanGrant(*existing); err != nil {
|
||||
return err
|
||||
}
|
||||
next.IsSuper = existing.IsSuper
|
||||
}
|
||||
return p.CanGrant(next)
|
||||
}
|
||||
373
internal/identity/rbac/rbac_test.go
Normal file
373
internal/identity/rbac/rbac_test.go
Normal file
@@ -0,0 +1,373 @@
|
||||
package rbac
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"online-back/internal/identity/rbac/perm"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func principal(scope Scope, codes ...perm.Code) *Principal {
|
||||
p := &Principal{UserID: 7, RoleID: 70, Scope: scope, Perms: map[perm.Code]struct{}{}}
|
||||
for _, code := range codes {
|
||||
p.Perms[code] = struct{}{}
|
||||
}
|
||||
if scope == ScopeBranch {
|
||||
p.BranchIDs = []int64{3}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
type fakeAuthorizer struct {
|
||||
principals map[int64]*Principal
|
||||
visible bool
|
||||
loadErr error
|
||||
}
|
||||
|
||||
func (f *fakeAuthorizer) Load(_ context.Context, id int64) (*Principal, error) {
|
||||
return f.principals[id], f.loadErr
|
||||
}
|
||||
func (f *fakeAuthorizer) BranchIDs(context.Context, int64) ([]int64, error) { return nil, nil }
|
||||
func (f *fakeAuthorizer) UserVisibleInBranches(context.Context, int64, []int64) (bool, error) {
|
||||
return f.visible, nil
|
||||
}
|
||||
|
||||
// runPolicy sends one request through p's group middleware with caller
|
||||
// already in the context (as Guard would leave it).
|
||||
func runPolicy(t *testing.T, p Policy, caller *Principal, method, target, body string) (int, *http.Request) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(method, target, strings.NewReader(body))
|
||||
if caller != nil {
|
||||
c.Set(contextPrincipal, caller)
|
||||
}
|
||||
c.Set(contextService, &fakeAuthorizer{visible: false})
|
||||
p.handler()(c)
|
||||
if c.IsAborted() {
|
||||
return w.Code, c.Request
|
||||
}
|
||||
return http.StatusOK, c.Request
|
||||
}
|
||||
|
||||
func TestCan(t *testing.T) {
|
||||
p := principal(ScopeAll, perm.Loans)
|
||||
if !p.Can(perm.Loans) || p.Can(perm.Cards) {
|
||||
t.Fatal("Can should follow the permission set")
|
||||
}
|
||||
if !(&Principal{IsSuper: true}).Can(perm.Backups) {
|
||||
t.Fatal("superadmin holds every permission")
|
||||
}
|
||||
if (*Principal)(nil).Can(perm.Loans) {
|
||||
t.Fatal("nil principal holds nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermCodesFollowCatalogOrder(t *testing.T) {
|
||||
p := principal(ScopeAll, perm.Loans, perm.Dashboard, perm.Cards)
|
||||
got := p.PermCodes()
|
||||
want := []perm.Code{perm.Dashboard, perm.Cards, perm.Loans}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %v", got)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanGrant(t *testing.T) {
|
||||
admin := principal(ScopeAll, perm.Cards, perm.Loans, perm.Users)
|
||||
manager := principal(ScopeBranch, perm.Cards, perm.Users)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
caller *Principal
|
||||
target RoleInfo
|
||||
want error
|
||||
}{
|
||||
{"super grants anything", &Principal{IsSuper: true, Scope: ScopeAll}, RoleInfo{IsSuper: true, Scope: ScopeAll}, nil},
|
||||
{"admin cannot grant superadmin", admin, RoleInfo{IsSuper: true, Scope: ScopeAll}, ErrSuperOnly},
|
||||
{"admin grants loan head", admin, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Loans}}, nil},
|
||||
{"admin lacks backups", admin, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Backups}}, ErrPermissionHeld},
|
||||
{"manager cannot grant all scope", manager, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Cards}}, ErrScopeTooWide},
|
||||
{"manager grants card operator", manager, RoleInfo{Scope: ScopeBranch, Perms: []perm.Code{perm.Cards}}, nil},
|
||||
{"manager lacks loans", manager, RoleInfo{Scope: ScopeBranch, Perms: []perm.Code{perm.Loans}}, ErrPermissionHeld},
|
||||
{"own-scope role skips the permission check", manager, RoleInfo{Scope: ScopeOwn, Perms: []perm.Code{perm.Cards, perm.Loans}}, nil},
|
||||
{"nil caller", nil, RoleInfo{Scope: ScopeOwn}, ErrSuperOnly},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := tc.caller.CanGrant(tc.target); !errors.Is(got, tc.want) {
|
||||
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanSaveRole(t *testing.T) {
|
||||
admin := principal(ScopeAll, perm.Cards, perm.Loans, perm.Roles)
|
||||
super := &Principal{IsSuper: true, Scope: ScopeAll}
|
||||
|
||||
if err := admin.CanSaveRole(nil, RoleInfo{Scope: "global"}); !errors.Is(err, ErrInvalidScope) {
|
||||
t.Errorf("invalid scope: got %v", err)
|
||||
}
|
||||
if err := admin.CanSaveRole(nil, RoleInfo{Scope: ScopeAll, Perms: []perm.Code{"nope"}}); !errors.Is(err, ErrUnknownPerm) {
|
||||
t.Errorf("unknown perm: got %v", err)
|
||||
}
|
||||
system := &RoleInfo{Scope: ScopeOwn, IsSystem: true}
|
||||
if err := super.CanSaveRole(system, RoleInfo{Scope: ScopeBranch}); !errors.Is(err, ErrSystemRole) {
|
||||
t.Errorf("system role scope change: got %v", err)
|
||||
}
|
||||
if err := super.CanSaveRole(system, RoleInfo{Scope: ScopeOwn, Perms: []perm.Code{perm.Cards}}); err != nil {
|
||||
t.Errorf("system role perms may change: got %v", err)
|
||||
}
|
||||
superRole := &RoleInfo{Scope: ScopeAll, IsSuper: true, IsSystem: true}
|
||||
if err := admin.CanSaveRole(superRole, RoleInfo{Scope: ScopeAll}); !errors.Is(err, ErrSuperOnly) {
|
||||
t.Errorf("admin editing superadmin role: got %v", err)
|
||||
}
|
||||
// A role already out of reach cannot be stripped either.
|
||||
backups := &RoleInfo{Scope: ScopeAll, Perms: []perm.Code{perm.Backups}}
|
||||
if err := admin.CanSaveRole(backups, RoleInfo{Scope: ScopeAll}); !errors.Is(err, ErrPermissionHeld) {
|
||||
t.Errorf("admin editing role with backups: got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyMatrix(t *testing.T) {
|
||||
client := principal(ScopeOwn, perm.Cards, perm.Loans)
|
||||
operator := principal(ScopeBranch, perm.Cards)
|
||||
loanHead := principal(ScopeAll, perm.Loans)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
policy Policy
|
||||
caller *Principal
|
||||
method string
|
||||
want int
|
||||
}{
|
||||
{"client reads own cards", Require(perm.Cards), client, http.MethodGet, 200},
|
||||
{"operator lacks loans", Require(perm.Loans), operator, http.MethodGet, 403},
|
||||
{"loan head reads loans", Require(perm.Loans), loanHead, http.MethodGet, 200},
|
||||
{"loan head has no cards", Require(perm.Cards), loanHead, http.MethodGet, 403},
|
||||
{"client blocked from staff module", RequireStaff(perm.Cards), client, http.MethodGet, 403},
|
||||
{"operator on staff module", RequireStaff(perm.Cards), operator, http.MethodGet, 200},
|
||||
{"client reads catalog", Catalog(perm.Loans), client, http.MethodGet, 200},
|
||||
{"client cannot write catalog", Catalog(perm.Loans), client, http.MethodPost, 403},
|
||||
{"operator cannot write loans catalog", Catalog(perm.Loans), operator, http.MethodPost, 403},
|
||||
{"loan head writes loans catalog", Catalog(perm.Loans), loanHead, http.MethodPost, 200},
|
||||
{"staff read for operator", StaffRead(perm.PaymentSettings), operator, http.MethodGet, 200},
|
||||
{"staff read blocks client", StaffRead(perm.PaymentSettings), client, http.MethodGet, 403},
|
||||
{"staff write needs perm", StaffRead(perm.PaymentSettings), operator, http.MethodPut, 403},
|
||||
{"staff blocks client", Staff(), client, http.MethodGet, 403},
|
||||
{"authenticated lets client in", Authenticated(), client, http.MethodPut, 200},
|
||||
{"no principal", Authenticated(), nil, http.MethodGet, 403},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got, _ := runPolicy(t, tc.policy, tc.caller, tc.method, "/api/admin/x", ""); got != tc.want {
|
||||
t.Errorf("%s: got %d, want %d", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchScopeWithoutBranchesIsDenied(t *testing.T) {
|
||||
p := principal(ScopeBranch, perm.Cards)
|
||||
p.BranchIDs = nil
|
||||
if got, _ := runPolicy(t, Require(perm.Cards), p, http.MethodGet, "/api/admin/cards", ""); got != 403 {
|
||||
t.Fatalf("got %d, want 403", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnScopePinsQueryAndBody(t *testing.T) {
|
||||
client := principal(ScopeOwn, perm.Cards)
|
||||
|
||||
_, req := runPolicy(t, Require(perm.Cards), client, http.MethodGet, "/api/admin/card-orders?user_id=99", "")
|
||||
if req.URL.Query().Get("user_id") != "7" || req.URL.Query().Get("created_by") != "7" {
|
||||
t.Fatalf("list not pinned to caller: %s", req.URL.RawQuery)
|
||||
}
|
||||
|
||||
_, req = runPolicy(t, Require(perm.Cards), client, http.MethodPost, "/api/admin/card-orders", `{"userId":99,"branchId":1}`)
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"userId", "user_id", "createdBy", "created_by"} {
|
||||
if payload[key] != float64(7) {
|
||||
t.Fatalf("%s = %v, want 7", key, payload[key])
|
||||
}
|
||||
}
|
||||
if payload["branchId"] != float64(1) {
|
||||
t.Fatal("other fields must survive the rewrite")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBranchScopeWrites(t *testing.T) {
|
||||
operator := principal(ScopeBranch, perm.Cards)
|
||||
cases := []struct {
|
||||
name string
|
||||
method string
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
{"own branch", http.MethodPost, `{"branchId":3}`, 200},
|
||||
{"other branch", http.MethodPost, `{"branchId":4}`, 403},
|
||||
{"create for new customer", http.MethodPost, `{"branchId":3,"userId":50}`, 200},
|
||||
{"reassign to invisible user", http.MethodPut, `{"branchId":3,"userId":50}`, 403},
|
||||
{"no body", http.MethodPut, ``, 200},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got, _ := runPolicy(t, Require(perm.Cards), operator, tc.method, "/api/admin/card-orders/1", tc.body); got != tc.want {
|
||||
t.Errorf("%s: got %d, want %d", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryLookupAndVerify(t *testing.T) {
|
||||
routes.reset()
|
||||
defer routes.reset()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
engine := gin.New()
|
||||
admin := engine.Group("/api/admin")
|
||||
Group(admin, "/users", RequireStaff(perm.Users)).GET("/:id", func(*gin.Context) {})
|
||||
Group(admin, "/users/clients", Staff()).GET("", func(*gin.Context) {})
|
||||
Group(admin, "/login", Public()).POST("", func(*gin.Context) {})
|
||||
|
||||
if p, _ := routes.lookup("/api/admin/users/clients"); p.name != "staff" {
|
||||
t.Fatalf("longest prefix should win, got %s", p.name)
|
||||
}
|
||||
if p, _ := routes.lookup("/api/admin/users/:id"); p.name != "require-staff:users" {
|
||||
t.Fatalf("got %s", p.name)
|
||||
}
|
||||
if _, ok := routes.lookup("/api/admin/usersx"); ok {
|
||||
t.Fatal("prefix must match whole path segments")
|
||||
}
|
||||
if err := VerifyRoutes(engine.Routes(), "/api/admin"); err != nil {
|
||||
t.Fatalf("all routes declared: %v", err)
|
||||
}
|
||||
|
||||
admin.GET("/forgotten", func(*gin.Context) {})
|
||||
err := VerifyRoutes(engine.Routes(), "/api/admin")
|
||||
if err == nil || !strings.Contains(err.Error(), "GET /api/admin/forgotten") {
|
||||
t.Fatalf("undeclared route must be reported, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryRejectsConflictingPolicies(t *testing.T) {
|
||||
routes.reset()
|
||||
defer routes.reset()
|
||||
engine := gin.New()
|
||||
Group(engine.Group("/api/admin"), "/cards", Require(perm.Cards))
|
||||
Group(engine.Group("/api/admin"), "/cards", Require(perm.Cards)) // same policy twice is fine
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Fatal("expected panic for conflicting policy")
|
||||
}
|
||||
}()
|
||||
Group(engine.Group("/api/admin"), "/cards", Catalog(perm.Cards))
|
||||
}
|
||||
|
||||
func TestGuardEndToEnd(t *testing.T) {
|
||||
routes.reset()
|
||||
defer routes.reset()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
auth := &fakeAuthorizer{principals: map[int64]*Principal{7: principal(ScopeAll, perm.Loans)}}
|
||||
engine := gin.New()
|
||||
admin := engine.Group("/api/admin")
|
||||
// Stand-in for JwtTokenCheck: Guard reads the id from the context first.
|
||||
admin.Use(func(c *gin.Context) {
|
||||
if id := c.GetHeader("X-User"); id != "" {
|
||||
c.Set("id", id)
|
||||
}
|
||||
}, Guard(auth))
|
||||
ok := func(c *gin.Context) { c.Status(http.StatusOK) }
|
||||
admin.Group("/loan-orders", Require(perm.Loans).handler()).GET("", ok)
|
||||
routes.add("/api/admin/loan-orders", Require(perm.Loans))
|
||||
admin.Group("/cards", Require(perm.Cards).handler()).GET("", ok)
|
||||
routes.add("/api/admin/cards", Require(perm.Cards))
|
||||
admin.GET("/undeclared", ok)
|
||||
|
||||
do := func(path, user string) int {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, path, &bytes.Buffer{})
|
||||
if user != "" {
|
||||
req.Header.Set("X-User", user)
|
||||
}
|
||||
engine.ServeHTTP(w, req)
|
||||
return w.Code
|
||||
}
|
||||
if got := do("/api/admin/loan-orders", "7"); got != 200 {
|
||||
t.Errorf("loan head on loans: %d", got)
|
||||
}
|
||||
if got := do("/api/admin/cards", "7"); got != 403 {
|
||||
t.Errorf("loan head on cards: %d", got)
|
||||
}
|
||||
if got := do("/api/admin/loan-orders", "8"); got != 403 {
|
||||
t.Errorf("unknown user: %d", got)
|
||||
}
|
||||
if got := do("/api/admin/undeclared", "7"); got != 403 {
|
||||
t.Errorf("undeclared route must be denied: %d", got)
|
||||
}
|
||||
|
||||
auth.loadErr = errors.New("db down")
|
||||
if got := do("/api/admin/loan-orders", "7"); got != 500 {
|
||||
t.Errorf("load error: %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopeHelpers(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx := func(p *Principal) *gin.Context {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
c.Set(contextPrincipal, p)
|
||||
c.Set(contextService, &fakeAuthorizer{visible: true})
|
||||
return c
|
||||
}
|
||||
|
||||
all := ctx(principal(ScopeAll))
|
||||
if !HasAllScope(all) || !SkipRecordGuard(all) || BranchIDsFrom(all) != nil || !AllowsBranch(all, 99) {
|
||||
t.Error("all scope sees everything")
|
||||
}
|
||||
|
||||
branch := ctx(principal(ScopeBranch))
|
||||
if !HasBranchScope(branch) || SkipRecordGuard(branch) || AllowsBranch(branch, 99) || !AllowsBranch(branch, 3) {
|
||||
t.Error("branch scope is limited to its branches")
|
||||
}
|
||||
var ids []int64
|
||||
BindBranchIDs(branch, &ids)
|
||||
if len(ids) != 1 || ids[0] != 3 {
|
||||
t.Errorf("BindBranchIDs = %v", ids)
|
||||
}
|
||||
|
||||
own := ctx(principal(ScopeOwn))
|
||||
if !IsOwnScope(own) || SkipRecordGuard(own) {
|
||||
t.Error("own scope must be guarded")
|
||||
}
|
||||
mine, other := int64(7), int64(8)
|
||||
if !GuardOwned(own, &mine) || GuardOwned(ctx(principal(ScopeOwn)), &other) {
|
||||
t.Error("GuardOwned follows the owner id")
|
||||
}
|
||||
if id, ok := CurrentUserID(own); !ok || id != 7 {
|
||||
t.Errorf("CurrentUserID = %d, %v", id, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserInBranchSQLIncludesOrderTables(t *testing.T) {
|
||||
sql := UserInBranchSQL("u.id", 2)
|
||||
for _, table := range []string{"branch_user", "card_orders", "loan_orders", "card_pin_orders", "card_rekwizit_orders", "visa_master_payment_orders", "loan_paid_off_letters", "card_balances"} {
|
||||
if !strings.Contains(sql, table) {
|
||||
t.Errorf("UserInBranchSQL missing %s", table)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user