Compare commits
94
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fbbcd5ffa | ||
|
|
41ae56240a | ||
|
|
11e1fa4972 | ||
|
|
742e078090 | ||
|
|
570d4c6d20 | ||
|
|
d7e5d1f989 | ||
|
|
78e1976e53 | ||
|
|
f1337706f0 | ||
|
|
72a5ac52b0 | ||
|
|
c6540a658b | ||
|
|
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 | ||
|
|
514b9ca5fc | ||
|
|
5e3c46da83 | ||
|
|
704606b3f5 | ||
|
|
5f6ddc5217 | ||
|
|
1987d4f596 | ||
|
|
51283ffa14 | ||
|
|
18012fcec0 | ||
|
|
ba53b5b5c2 | ||
|
|
30bcfefc1e | ||
|
|
3636e1ca53 | ||
|
|
585ba63bc2 | ||
|
|
7e3a5cebcc | ||
|
|
6705c4ce91 | ||
|
|
c29c72fd92 | ||
|
|
d6555e1133 | ||
|
|
be3dc28e68 | ||
|
|
77bc4025d3 | ||
|
|
1337175e5d |
No files matched your search
@@ -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
|
||||||
@@ -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' }}
|
||||||
+11
@@ -1,5 +1,7 @@
|
|||||||
# Binaries
|
# Binaries
|
||||||
online-back
|
online-back
|
||||||
|
myapp
|
||||||
|
app
|
||||||
*.exe
|
*.exe
|
||||||
*.exe~
|
*.exe~
|
||||||
*.dll
|
*.dll
|
||||||
@@ -21,6 +23,7 @@ coverage.html
|
|||||||
!.env.example
|
!.env.example
|
||||||
config.local.yaml
|
config.local.yaml
|
||||||
config.yaml
|
config.yaml
|
||||||
|
!config.example.yaml
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs/
|
logs/
|
||||||
@@ -29,6 +32,8 @@ logs/
|
|||||||
# Uploaded files (keep directory structure)
|
# Uploaded files (keep directory structure)
|
||||||
public/images/*
|
public/images/*
|
||||||
!public/images/.gitkeep
|
!public/images/.gitkeep
|
||||||
|
public/backups/*
|
||||||
|
!public/backups/.gitkeep
|
||||||
|
|
||||||
# IDE & editors
|
# IDE & editors
|
||||||
.idea/
|
.idea/
|
||||||
@@ -52,6 +57,9 @@ Desktop.ini
|
|||||||
docker-compose.override.yaml
|
docker-compose.override.yaml
|
||||||
docker-compose.override.yml
|
docker-compose.override.yml
|
||||||
|
|
||||||
|
# Local MinIO Ubuntu package (do not commit)
|
||||||
|
deployment/minio.deb
|
||||||
|
|
||||||
# Temporary files
|
# Temporary files
|
||||||
tmp/
|
tmp/
|
||||||
temp/
|
temp/
|
||||||
@@ -69,3 +77,6 @@ bank_db_schema.drawio
|
|||||||
# Debug
|
# Debug
|
||||||
__debug_bin
|
__debug_bin
|
||||||
debug
|
debug
|
||||||
|
|
||||||
|
# Docker image bundles (make docker-bundle)
|
||||||
|
dist/
|
||||||
+25
-16
@@ -1,30 +1,39 @@
|
|||||||
#!/bin/ash
|
# Offline build: nothing in this file touches the network.
|
||||||
# Specifies a parent image
|
# - 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
|
FROM golang:1.26.4-alpine AS builder
|
||||||
|
|
||||||
# Creates an app directory to hold your app’s source code
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
# Installs Go dependencies
|
ENV CGO_ENABLED=0 \
|
||||||
COPY go.mod ./
|
GOOS=linux \
|
||||||
COPY go.sum ./
|
GOARCH=amd64 \
|
||||||
RUN go mod download
|
GOFLAGS=-mod=vendor \
|
||||||
|
GOPROXY=off
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Builds your app with optional configuration
|
RUN go build -trimpath -ldflags="-s -w" -o myapp ./app.go
|
||||||
RUN GOARCH=amd64 GOOS=linux go build -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/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
|
EXPOSE 5050
|
||||||
#ENTRYPOINT ["/app/myapp"]
|
|
||||||
CMD ["/app/myapp"]
|
|
||||||
|
|
||||||
|
|
||||||
|
# Replaces the postgres docker-entrypoint.sh inherited from the base image.
|
||||||
|
ENTRYPOINT ["/app/myapp"]
|
||||||
@@ -8,12 +8,58 @@ create-migration:
|
|||||||
|
|
||||||
# --- for Macos
|
# --- for Macos
|
||||||
migrate:
|
migrate:
|
||||||
migrate -database 'postgres://bank_admin:bank@#23#@_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up
|
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up
|
||||||
migrate-rollback:
|
migrate-rollback:
|
||||||
migrate -database 'postgres://bank_admin:bank@#23#@_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||||
|
seed:
|
||||||
|
docker exec -i main-db psql -U bank_admin -d bank_db -f - < db/seed.sql
|
||||||
|
|
||||||
# ---- for linux
|
# ---- for linux
|
||||||
# migrate:
|
# migrate:
|
||||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
# migrate -database 'postgresql://bank_admin:bank%40%2323%23%40_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
||||||
# migrate-rollback:
|
# migrate-rollback:
|
||||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
|
# 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
|
||||||
@@ -56,14 +56,21 @@ Additional Swagger endpoints (categories, settings) are documented but not yet i
|
|||||||
├── config.yaml # Runtime configuration
|
├── config.yaml # Runtime configuration
|
||||||
├── docker-compose.yaml # Local development stack
|
├── docker-compose.yaml # Local development stack
|
||||||
├── db/migrations/ # SQL migrations
|
├── db/migrations/ # SQL migrations
|
||||||
|
├── db/seed.sql # Consolidated, idempotent seed data
|
||||||
├── docs/ # Generated Swagger docs
|
├── docs/ # Generated Swagger docs
|
||||||
├── internal/
|
├── internal/
|
||||||
│ ├── admin/auth/ # Admin auth handlers & repository
|
|
||||||
│ ├── appresult/ # Response helpers & JWT middleware
|
│ ├── appresult/ # Response helpers & JWT middleware
|
||||||
│ ├── config/ # Config loader
|
│ ├── 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/
|
└── pkg/
|
||||||
├── client/postgresql/ # PostgreSQL connection pool
|
├── client/postgresql/ # PostgreSQL connection pool
|
||||||
|
├── repository/genericrepo/ # Shared List/GetByID/Delete repository helper
|
||||||
├── logging/ # Structured logging
|
├── logging/ # Structured logging
|
||||||
└── utils/ # JWT & file utilities
|
└── utils/ # JWT & file utilities
|
||||||
```
|
```
|
||||||
@@ -110,7 +117,7 @@ The API will be available at `http://localhost:5050`.
|
|||||||
|
|
||||||
1. Start PostgreSQL (or use `docker compose up main-db -d`).
|
1. Start PostgreSQL (or use `docker compose up main-db -d`).
|
||||||
|
|
||||||
2. Update `config.yaml` — set `storage.host` to `localhost` and match your database credentials.
|
2. Copy `config.example.yaml` to `config.yaml`, set `storage.host` to `localhost`, and fill in your database credentials and a JWT secret.
|
||||||
|
|
||||||
3. Apply migrations:
|
3. Apply migrations:
|
||||||
|
|
||||||
@@ -130,26 +137,6 @@ The API will be available at `http://localhost:5050`.
|
|||||||
go run app.go
|
go run app.go
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Settings are loaded from `config.yaml`:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
is_debug: true
|
|
||||||
listen:
|
|
||||||
port: 5050
|
|
||||||
jwt_key: <your-jwt-secret>
|
|
||||||
storage:
|
|
||||||
host: main-db # use localhost when running outside Docker
|
|
||||||
port: 5432
|
|
||||||
database: bank_db
|
|
||||||
username: bank_admin
|
|
||||||
password: <password>
|
|
||||||
pg_pool_max_conn: 10
|
|
||||||
public_file_path: ./public
|
|
||||||
app_version: 0.0.1
|
|
||||||
```
|
|
||||||
|
|
||||||
> **Note:** Replace default credentials before deploying to production.
|
> **Note:** Replace default credentials before deploying to production.
|
||||||
|
|
||||||
|
|
||||||
@@ -166,7 +153,7 @@ Authorization: <accessToken>
|
|||||||
|
|
||||||
### Swagger
|
### Swagger
|
||||||
|
|
||||||
Interactive API docs: [http://localhost:5050/swagger/index.html](http://localhost:5050/swagger/index.html)
|
Interactive API docs: [http://localhost:5005/swagger/index.html](http://localhost:5005/swagger/index.html)
|
||||||
|
|
||||||
## Database migrations
|
## Database migrations
|
||||||
|
|
||||||
@@ -185,6 +172,23 @@ make migrate-rollback
|
|||||||
|
|
||||||
Migration files live in `db/migrations/`.
|
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
|
## Development
|
||||||
|
|
||||||
### Run tests
|
### Run tests
|
||||||
|
|||||||
+1
-1
@@ -235,7 +235,7 @@ Admin users for the back-office panel.
|
|||||||
| avatar | varchar(250) | |
|
| avatar | varchar(250) | |
|
||||||
| social_media | json | |
|
| social_media | json | |
|
||||||
| light_mode | integer | Default `1` |
|
| light_mode | integer | Default `1` |
|
||||||
| role | varchar(250) | Default `'user'` |
|
| role_id | bigint | FK → roles.id, NOT NULL |
|
||||||
| status | boolean | Default `true` |
|
| status | boolean | Default `true` |
|
||||||
| created_at | timestamp UTC | |
|
| created_at | timestamp UTC | |
|
||||||
| updated_at | timestamp UTC | |
|
| updated_at | timestamp UTC | |
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"online-back/docs"
|
"online-back/docs"
|
||||||
"online-back/internal/config"
|
"online-back/internal/config"
|
||||||
@@ -9,19 +12,18 @@ import (
|
|||||||
"online-back/pkg/client/postgresql"
|
"online-back/pkg/client/postgresql"
|
||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/jackc/pgx/v4/pgxpool"
|
"github.com/jackc/pgx/v4/pgxpool"
|
||||||
swaggerFiles "github.com/swaggo/files"
|
swaggerFiles "github.com/swaggo/files"
|
||||||
ginSwagger "github.com/swaggo/gin-swagger"
|
ginSwagger "github.com/swaggo/gin-swagger"
|
||||||
|
"github.com/swaggo/swag"
|
||||||
)
|
)
|
||||||
|
|
||||||
// @title Service APIs
|
// @title Service APIs
|
||||||
// @version 1.0
|
// @version 1.0
|
||||||
// @description Online payment system admin API.
|
// @description Online payment system admin API. Localized fields ({en, ru, tm} objects) come back as a plain string in the language of the `lang` query parameter: tm, ru or en (default tm), falling back to tm, ru, en when that translation is empty. lang=all returns the full {en, ru, tm} objects (for edit forms); any other value is 400.
|
||||||
// @host localhost:5050
|
// @host localhost:5005
|
||||||
// @BasePath /api/admin
|
// @BasePath /api/admin
|
||||||
// @securityDefinitions.apikey BearerAuth
|
|
||||||
// @in header
|
|
||||||
// @name Authorization
|
|
||||||
// @schemes http
|
// @schemes http
|
||||||
// @tag.name auth
|
// @tag.name auth
|
||||||
// @tag.description Authentication
|
// @tag.description Authentication
|
||||||
@@ -37,21 +39,47 @@ import (
|
|||||||
// @tag.description Loan types
|
// @tag.description Loan types
|
||||||
// @tag.name loan-document
|
// @tag.name loan-document
|
||||||
// @tag.description Loan required documents
|
// @tag.description Loan required documents
|
||||||
|
// @tag.name loans-repayment
|
||||||
|
// @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-orders
|
||||||
|
// @tag.description Visa/Master and Sber student-transfer orders: list, view, create, edit, delete
|
||||||
|
// @tag.name visa-master-order-actions
|
||||||
|
// @tag.description Visa/Master we Sber sargytlarynyň amallary (Ammallar): kim, haçan, näme goşdy, üýtgetdi ýa-da pozdy. Ulanylyş tertibi: 1) GET /visa-master-payment-orders/{id}/actions - sargydyň amallary; 2) GET /visa-master-payment-orders/{id}/actions/{actionId} - bir amalyň öňki we täze bahalary
|
||||||
|
// @tag.name visa-master-payment
|
||||||
|
// @tag.description Paying a Visa/Master or Sber order through GBÜS (HALKBANK): quote, pay, status re-check, bank callback
|
||||||
|
// @tag.name payment-history
|
||||||
|
// @tag.description Visa/Master we Sber töleg synanyşyklarynyň taryhy. Ulanylyş tertibi: 1) GET /payment-history - ähli tölegler; 2) GET /payment-history/{id} - bir sargydyň tölegleri; 3) GET /payment-history/payments/{id} - bir tölegiň jikme-jikligi; 4) GET /payment-history/{id}/gateway - sargydyň tölegleri GBÜS jogaplary bilen; 5) GET /payment-history/{id}/logs - sargydyň ädimme-ädim töleg loglary
|
||||||
|
// @tag.name backups
|
||||||
|
// @tag.description Database SQL backups
|
||||||
|
// @tag.name currencies
|
||||||
|
// @tag.description Currency exchange rates
|
||||||
|
//
|
||||||
|
// Security definitions go last: swag reads every line after one as its
|
||||||
|
// attributes, so anything declared below it (tags, schemes) is dropped.
|
||||||
|
// @securityDefinitions.apikey BearerAuth
|
||||||
|
// @in header
|
||||||
|
// @name Authorization
|
||||||
func main() {
|
func main() {
|
||||||
docs.SwaggerInfo.Title = "Service APIs"
|
|
||||||
docs.SwaggerInfo.Version = "1.0"
|
|
||||||
docs.SwaggerInfo.Description = "Online payment system admin API."
|
|
||||||
docs.SwaggerInfo.Host = "localhost:5050"
|
|
||||||
docs.SwaggerInfo.BasePath = "/api/admin"
|
|
||||||
docs.SwaggerInfo.Schemes = []string{"http"}
|
|
||||||
|
|
||||||
cfg := config.GetConfig()
|
cfg := config.GetConfig()
|
||||||
logger := logging.GetLogger()
|
logger := logging.GetLogger()
|
||||||
|
|
||||||
|
docs.SwaggerInfo.Title = "Service APIs"
|
||||||
|
docs.SwaggerInfo.Version = "1.0"
|
||||||
|
docs.SwaggerInfo.Description = "Online payment system admin API. Localized fields ({en, ru, tm} objects) come back as a plain string in the language of the `lang` query parameter: tm, ru or en (default tm), falling back to tm, ru, en when that translation is empty. lang=all returns the full {en, ru, tm} objects (for edit forms); any other value is 400."
|
||||||
|
docs.SwaggerInfo.Host = "localhost:" + cfg.Listen.Port
|
||||||
|
docs.SwaggerInfo.BasePath = "/api/admin"
|
||||||
|
docs.SwaggerInfo.Schemes = []string{"http"}
|
||||||
|
|
||||||
pool := mustConnectPostgresql(cfg, logger)
|
pool := mustConnectPostgresql(cfg, logger)
|
||||||
router := handlermanager.New(cfg, pool, logger)
|
router := handlermanager.New(cfg, pool, logger)
|
||||||
|
|
||||||
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
router.GET("/swagger/*any", swaggerHandler())
|
||||||
|
|
||||||
addr := cfg.Listen.BindIP + ":" + cfg.Listen.Port
|
addr := cfg.Listen.BindIP + ":" + cfg.Listen.Port
|
||||||
logger.Infof("starting server on %s", addr)
|
logger.Infof("starting server on %s", addr)
|
||||||
@@ -60,6 +88,51 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// swaggerHandler serves the Swagger UI, but answers doc.json itself so the
|
||||||
|
// spec can describe the address the browser actually used. Behind a reverse
|
||||||
|
// proxy that strips a path prefix, the baked-in host and basePath would point
|
||||||
|
// "Try it out" at the app's own listen address instead of the public URL.
|
||||||
|
func swaggerHandler() gin.HandlerFunc {
|
||||||
|
ui := ginSwagger.WrapHandler(swaggerFiles.Handler)
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if strings.HasSuffix(c.Param("any"), "/doc.json") {
|
||||||
|
serveSwaggerSpec(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ui(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveSwaggerSpec(c *gin.Context) {
|
||||||
|
doc, err := swag.ReadDoc()
|
||||||
|
if err != nil {
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var spec map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(doc), &spec); err != nil {
|
||||||
|
c.Status(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
scheme := "http"
|
||||||
|
if proto := c.GetHeader("X-Forwarded-Proto"); proto != "" {
|
||||||
|
scheme = proto
|
||||||
|
} else if c.Request.TLS != nil {
|
||||||
|
scheme = "https"
|
||||||
|
}
|
||||||
|
|
||||||
|
basePath, _ := spec["basePath"].(string)
|
||||||
|
prefix := strings.TrimSuffix(c.GetHeader("X-Forwarded-Prefix"), "/")
|
||||||
|
|
||||||
|
spec["schemes"] = []string{scheme}
|
||||||
|
spec["host"] = c.Request.Host
|
||||||
|
spec["basePath"] = prefix + basePath
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, spec)
|
||||||
|
}
|
||||||
|
|
||||||
func mustConnectPostgresql(cfg *config.Config, logger *logging.Logger) *pgxpool.Pool {
|
func mustConnectPostgresql(cfg *config.Config, logger *logging.Logger) *pgxpool.Pool {
|
||||||
pool, err := postgresql.NewClient(context.Background(), 3, cfg.Storage)
|
pool, err := postgresql.NewClient(context.Background(), 3, cfg.Storage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
is_debug: true
|
||||||
|
listen:
|
||||||
|
type: port
|
||||||
|
bind_ip: 0.0.0.0
|
||||||
|
port: 5050
|
||||||
|
jwt_key: <your-jwt-secret>
|
||||||
|
storage:
|
||||||
|
host: main-db # use localhost when running the app on the host
|
||||||
|
port: 5432 # use 5424 when host is localhost (docker-compose)
|
||||||
|
database: bank_db
|
||||||
|
username: bank_admin
|
||||||
|
password: <your-db-password>
|
||||||
|
pg_pool_max_conn: 10
|
||||||
|
minio:
|
||||||
|
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_base_url: https://your-api-domain.example # used to build the GBÜS payment callback (returnUrl)
|
||||||
-16
@@ -1,16 +0,0 @@
|
|||||||
is_debug: true
|
|
||||||
listen:
|
|
||||||
type: port
|
|
||||||
port: 5050
|
|
||||||
jwt_key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX@VCJ9.yueyJzdWIiOiIyNTEyNzMiLCJpYXQiOjE1MTYy#MzkwMjJ9.o_LoJm03CaE6!0dugdR8sjIuFgPxGT7I2W8NvugFqHRY
|
|
||||||
storage:
|
|
||||||
# host: localhost
|
|
||||||
host: main-db
|
|
||||||
# port: 5424
|
|
||||||
port: 5432
|
|
||||||
database: bank_db
|
|
||||||
username: bank_admin
|
|
||||||
password: bank@#23#@_password
|
|
||||||
pg_pool_max_conn: 10
|
|
||||||
app_version: 0.0.1
|
|
||||||
public_file_path: ./public
|
|
||||||
@@ -1,8 +1,83 @@
|
|||||||
DROP TABLE IF EXISTS roles;
|
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_order_actions;
|
||||||
|
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;
|
||||||
|
DROP TABLE IF EXISTS card_pin_orders;
|
||||||
|
DROP TABLE IF EXISTS card_orders;
|
||||||
|
DROP TABLE IF EXISTS cards;
|
||||||
DROP TABLE IF EXISTS loan_order_required_docs;
|
DROP TABLE IF EXISTS loan_order_required_docs;
|
||||||
DROP TABLE IF EXISTS loan_types;
|
DROP TABLE IF EXISTS loan_types;
|
||||||
DROP TABLE IF EXISTS card_states;
|
DROP TABLE IF EXISTS card_states;
|
||||||
DROP TABLE IF EXISTS card_types;
|
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 branches;
|
||||||
|
|
||||||
DROP TABLE IF EXISTS provinces;
|
DROP TABLE IF EXISTS provinces;
|
||||||
|
|
||||||
|
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 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,46 +1,115 @@
|
|||||||
CREATE TABLE IF NOT EXISTS users (
|
-- RBAC: permission = modul (bir permission her modul üçin), rol = permission-lar + scope
|
||||||
"id" bigserial primary key,
|
-- (own | branch | all). Her ulanyjynyň bir roly bar (users.role_id).
|
||||||
"email" character varying(250) NOT NULL DEFAULT '',
|
CREATE TABLE IF NOT EXISTS roles (
|
||||||
"name" character varying(250) NOT NULL DEFAULT '',
|
id bigserial PRIMARY KEY,
|
||||||
"password" character varying(250) NOT NULL DEFAULT '',
|
code character varying(255) NOT NULL DEFAULT '',
|
||||||
"first_name" character varying(250) NOT NULL DEFAULT '',
|
name character varying(255) NOT NULL,
|
||||||
"last_name" character varying(250) NOT NULL DEFAULT '',
|
scope character varying(16) NOT NULL,
|
||||||
"username" character varying(250) NOT NULL DEFAULT '',
|
is_super boolean NOT NULL DEFAULT false,
|
||||||
"phone" character varying(250) NOT NULL DEFAULT '',
|
is_system boolean NOT NULL DEFAULT false,
|
||||||
"light_mode" integer DEFAULT 1 NOT NULL,
|
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
"role" character varying(250) NOT NULL DEFAULT 'user',
|
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
"active" boolean NOT NULL DEFAULT true,
|
deleted_at TIMESTAMPTZ,
|
||||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
CONSTRAINT roles_scope_check CHECK (scope IN ('own', 'branch', 'all'))
|
||||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
);
|
||||||
);
|
|
||||||
|
|
||||||
insert into users(
|
CREATE UNIQUE INDEX IF NOT EXISTS roles_code_uq ON roles (code) WHERE deleted_at IS NULL;
|
||||||
phone, password, name, email, role
|
|
||||||
) values (
|
-- Katalog kodda (internal/identity/rbac/perm); app başlanda şu sanawy sinhronlaýar.
|
||||||
'61531216',
|
CREATE TABLE IF NOT EXISTS permissions (
|
||||||
'$2a$12$8ZbKmoSwna4CASQptM2/SubwvsBUR1YhABULd.2/QJB.13Wi2v55m',
|
code character varying(64) PRIMARY KEY,
|
||||||
'Admin',
|
name character varying(255) NOT NULL DEFAULT ''
|
||||||
'admin@admin.com',
|
);
|
||||||
'admin'
|
|
||||||
);
|
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 '',
|
||||||
|
password character varying(250) NOT NULL DEFAULT '',
|
||||||
|
name character varying(255) NOT NULL DEFAULT '',
|
||||||
|
first_name character varying(255) NOT NULL DEFAULT '',
|
||||||
|
last_name character varying(255) NOT NULL DEFAULT '',
|
||||||
|
username character varying(250) NOT NULL DEFAULT '',
|
||||||
|
phone character varying(250) NOT NULL DEFAULT '',
|
||||||
|
avatar character varying(250) NOT NULL DEFAULT '',
|
||||||
|
social_media json NOT NULL DEFAULT '{}'::json,
|
||||||
|
light_mode integer NOT NULL DEFAULT 1,
|
||||||
|
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,
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username
|
||||||
|
ON users (LOWER(username))
|
||||||
|
WHERE username <> '' AND deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone
|
||||||
|
ON users (phone)
|
||||||
|
WHERE phone <> '' AND deleted_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS registration_verifications (
|
||||||
|
id bigserial PRIMARY KEY,
|
||||||
|
name character varying(255) NOT NULL DEFAULT '',
|
||||||
|
username character varying(250) NOT NULL DEFAULT '',
|
||||||
|
phone character varying(250) NOT NULL UNIQUE,
|
||||||
|
password character varying(250) NOT NULL DEFAULT '',
|
||||||
|
code_hash character varying(250) NOT NULL DEFAULT '',
|
||||||
|
attempts integer NOT NULL DEFAULT 0,
|
||||||
|
expires_at TIMESTAMP 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 provinces (
|
CREATE TABLE IF NOT EXISTS provinces (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
name json NOT NULL DEFAULT '{}'::json,
|
name json NOT NULL DEFAULT '{}'::json,
|
||||||
region json NOT NULL DEFAULT '{}'::json,
|
region json NOT NULL DEFAULT '{}'::json,
|
||||||
active boolean NOT NULL DEFAULT true,
|
active boolean NOT NULL DEFAULT true,
|
||||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS branches (
|
CREATE TABLE IF NOT EXISTS branches (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
unique_code character varying(255) UNIQUE,
|
unique_code character varying(255),
|
||||||
name json NOT NULL DEFAULT '{}'::json,
|
name json NOT NULL DEFAULT '{}'::json,
|
||||||
address json NOT NULL DEFAULT '{}'::json,
|
address json NOT NULL DEFAULT '{}'::json,
|
||||||
region character varying(2) NOT NULL DEFAULT '',
|
region character varying(20) NOT NULL DEFAULT '',
|
||||||
province_id bigint REFERENCES provinces(id) ON DELETE SET NULL,
|
province_id bigint,
|
||||||
phone_numbers json NOT NULL DEFAULT '[]'::json,
|
phone_numbers character varying(255) NOT NULL DEFAULT '',
|
||||||
billing_username character varying(255) NOT NULL DEFAULT '',
|
billing_username character varying(255) NOT NULL DEFAULT '',
|
||||||
billing_password character varying(255) NOT NULL DEFAULT '',
|
billing_password character varying(255) NOT NULL DEFAULT '',
|
||||||
billing_swift_username character varying(255) NOT NULL DEFAULT '',
|
billing_swift_username character varying(255) NOT NULL DEFAULT '',
|
||||||
@@ -50,18 +119,42 @@ CREATE TABLE IF NOT EXISTS branches (
|
|||||||
billing_sber_username character varying(255) NOT NULL DEFAULT '',
|
billing_sber_username character varying(255) NOT NULL DEFAULT '',
|
||||||
billing_sber_password character varying(255) NOT NULL DEFAULT '',
|
billing_sber_password character varying(255) NOT NULL DEFAULT '',
|
||||||
active boolean NOT NULL DEFAULT true,
|
active boolean NOT NULL DEFAULT true,
|
||||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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 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,
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 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 (
|
CREATE TABLE IF NOT EXISTS card_types (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
name json NOT NULL DEFAULT '{}'::json,
|
name json NOT NULL DEFAULT '{}'::json,
|
||||||
price character varying(255) NOT NULL DEFAULT '',
|
price character varying(255) NOT NULL DEFAULT '',
|
||||||
notes character varying(255) NOT NULL DEFAULT '',
|
notes character varying(255) NOT NULL DEFAULT '',
|
||||||
active boolean NOT NULL DEFAULT true,
|
active boolean NOT NULL DEFAULT true,
|
||||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS card_states (
|
CREATE TABLE IF NOT EXISTS card_states (
|
||||||
@@ -71,7 +164,8 @@ CREATE TABLE IF NOT EXISTS card_states (
|
|||||||
notes character varying(255) NOT NULL DEFAULT '',
|
notes character varying(255) NOT NULL DEFAULT '',
|
||||||
active boolean NOT NULL DEFAULT true,
|
active boolean NOT NULL DEFAULT true,
|
||||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS loan_types (
|
CREATE TABLE IF NOT EXISTS loan_types (
|
||||||
@@ -82,7 +176,8 @@ CREATE TABLE IF NOT EXISTS loan_types (
|
|||||||
notes json NOT NULL DEFAULT '{}'::json,
|
notes json NOT NULL DEFAULT '{}'::json,
|
||||||
active boolean NOT NULL DEFAULT true,
|
active boolean NOT NULL DEFAULT true,
|
||||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
||||||
@@ -91,23 +186,594 @@ CREATE TABLE IF NOT EXISTS loan_order_required_docs (
|
|||||||
value text NOT NULL DEFAULT '',
|
value text NOT NULL DEFAULT '',
|
||||||
active boolean NOT NULL DEFAULT true,
|
active boolean NOT NULL DEFAULT true,
|
||||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS roles (
|
CREATE TABLE IF NOT EXISTS cards (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
code character varying(255) NOT NULL DEFAULT '',
|
user_id bigint,
|
||||||
name character varying(255) NOT NULL,
|
number character varying(250) NOT NULL,
|
||||||
guard_name character varying(255) NOT NULL,
|
name character varying(250) NOT NULL,
|
||||||
|
month character varying(250) NOT NULL,
|
||||||
|
year character varying(250),
|
||||||
|
type character varying(250),
|
||||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
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)
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS permissions (
|
CREATE TABLE IF NOT EXISTS card_orders (
|
||||||
id bigserial PRIMARY KEY,
|
id bigserial PRIMARY KEY,
|
||||||
code character varying(255) NOT NULL DEFAULT '',
|
unique_id character varying(255),
|
||||||
name character varying(255) NOT NULL,
|
card_state_id bigint NOT NULL,
|
||||||
guard_name character varying(255) NOT NULL,
|
card_type_id bigint 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,
|
||||||
|
old_surname character varying(255),
|
||||||
|
citizenship character varying(255) NOT NULL,
|
||||||
|
passport_serie character varying(255) NOT NULL,
|
||||||
|
passport_id character varying(255) NOT NULL,
|
||||||
|
passport_given_at date NOT NULL,
|
||||||
|
passport_given_by character varying(255) NOT NULL,
|
||||||
|
born_place character varying(255) NOT NULL,
|
||||||
|
job_location character varying(255),
|
||||||
|
passport_address character varying(255),
|
||||||
|
real_address character varying(255),
|
||||||
|
phone character varying(255),
|
||||||
|
phone_additional character varying(255),
|
||||||
|
status character varying(255) DEFAULT 'pending'::character varying,
|
||||||
|
passport_one text NOT NULL,
|
||||||
|
passport_two text NOT NULL,
|
||||||
|
passport_three text NOT NULL,
|
||||||
|
passport_four text NOT NULL,
|
||||||
|
notes text,
|
||||||
|
user_id bigint,
|
||||||
|
paid boolean NOT NULL DEFAULT false,
|
||||||
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 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
|
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
|
||||||
|
FOREIGN KEY (card_type_id) REFERENCES card_types(id),
|
||||||
|
CONSTRAINT card_orders_branch_id_fkey
|
||||||
|
FOREIGN KEY (branch_id) REFERENCES branches(id),
|
||||||
|
CONSTRAINT card_orders_user_id_fkey
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS card_pin_orders (
|
||||||
|
id bigserial PRIMARY KEY,
|
||||||
|
unique_id character varying(255),
|
||||||
|
user_id bigint,
|
||||||
|
card_type_id bigint NOT NULL,
|
||||||
|
card_number character varying(255),
|
||||||
|
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,
|
||||||
|
phone character varying(255),
|
||||||
|
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(250),
|
||||||
|
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
|
||||||
|
FOREIGN KEY (branch_id) REFERENCES branches(id),
|
||||||
|
CONSTRAINT card_pin_orders_user_id_fkey
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
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(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),
|
||||||
|
passport_address character varying(255) NOT NULL,
|
||||||
|
real_address character varying(255) NOT NULL,
|
||||||
|
passport_serie character varying(255) NOT NULL,
|
||||||
|
passport_id character varying(255) NOT NULL,
|
||||||
|
passport_given_at date NOT NULL,
|
||||||
|
passport_given_by character varying(255) NOT NULL,
|
||||||
|
born_place character varying(255) NOT NULL,
|
||||||
|
born_at date NOT NULL,
|
||||||
|
email character varying(255),
|
||||||
|
phone character varying(255) NOT NULL,
|
||||||
|
phone_additional character varying(255),
|
||||||
|
phone_home character varying(255),
|
||||||
|
work_region character varying(255),
|
||||||
|
work_province_id bigint,
|
||||||
|
work_company character varying(255),
|
||||||
|
work_company_accountant_number character varying(255),
|
||||||
|
work_started_at date,
|
||||||
|
work_salary character varying(255),
|
||||||
|
work_position character varying(255),
|
||||||
|
education character varying(255) NOT NULL,
|
||||||
|
marriage_status 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,
|
||||||
|
loan_amount character varying(255),
|
||||||
|
card_number character varying(255),
|
||||||
|
card_name character varying(255),
|
||||||
|
card_month character varying(255),
|
||||||
|
card_year character varying(255),
|
||||||
|
guarantor_name character varying(255),
|
||||||
|
guarantor_surname character varying(255),
|
||||||
|
guarantor_patronic_name character varying(255),
|
||||||
|
guarantor_passport_serie character varying(255),
|
||||||
|
guarantor_passport_id character varying(255),
|
||||||
|
guarantor_card_number character varying(255),
|
||||||
|
guarantor_card_name character varying(255),
|
||||||
|
guarantor_card_month character varying(255),
|
||||||
|
guarantor_card_year character varying(255),
|
||||||
|
guarantor_note character varying(255),
|
||||||
|
guarantor_2_name character varying(255),
|
||||||
|
guarantor_2_surname character varying(255),
|
||||||
|
guarantor_2_patronic_name character varying(255),
|
||||||
|
guarantor_2_passport_serie character varying(255),
|
||||||
|
guarantor_2_passport_id character varying(255),
|
||||||
|
guarantor_2_card_number character varying(255),
|
||||||
|
guarantor_2_card_name character varying(255),
|
||||||
|
guarantor_2_card_month character varying(255),
|
||||||
|
guarantor_2_card_year character varying(255),
|
||||||
|
guarantor_2_note character varying(255),
|
||||||
|
loan_card_number character varying(255),
|
||||||
|
loan_card_name character varying(255),
|
||||||
|
loan_card_month character varying(255),
|
||||||
|
loan_card_year character varying(255),
|
||||||
|
loan_order_required_doc_id bigint,
|
||||||
|
status character varying(255),
|
||||||
|
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,
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS loans (
|
||||||
|
id bigserial PRIMARY KEY,
|
||||||
|
user_id bigint NOT NULL,
|
||||||
|
passport_serie character varying(255) NOT NULL,
|
||||||
|
passport_id character varying(255) NOT NULL,
|
||||||
|
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)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS loan_paid_off_letters (
|
||||||
|
id bigserial PRIMARY KEY,
|
||||||
|
unique_id character varying(255),
|
||||||
|
region character varying(255) NOT NULL,
|
||||||
|
branch_id bigint NOT NULL,
|
||||||
|
user_id bigint,
|
||||||
|
customer_name character varying(255) NOT NULL,
|
||||||
|
customer_surname character varying(255) NOT NULL,
|
||||||
|
customer_patronic_name character varying(255),
|
||||||
|
born_at date,
|
||||||
|
phone character varying(255) NOT NULL,
|
||||||
|
passport_serie character varying(255) NOT NULL,
|
||||||
|
passport_id character varying(255) NOT NULL,
|
||||||
|
status character varying(255),
|
||||||
|
notes text,
|
||||||
|
loan_contract_number character varying(255),
|
||||||
|
loan_contract_date date,
|
||||||
|
loan_amount character varying(255),
|
||||||
|
loan_reason character varying(255),
|
||||||
|
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)
|
||||||
|
);
|
||||||
|
|
||||||
|
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,
|
||||||
|
method character varying(10) NOT NULL DEFAULT '',
|
||||||
|
path character varying(255) NOT NULL DEFAULT '',
|
||||||
|
module character varying(100) NOT NULL DEFAULT '',
|
||||||
|
action character varying(50) NOT NULL DEFAULT '',
|
||||||
|
status_code integer NOT NULL DEFAULT 0,
|
||||||
|
request_body jsonb,
|
||||||
|
ip character varying(50) NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
|
CONSTRAINT activity_logs_user_id_fkey
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
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);
|
||||||
|
-- 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;
|
||||||
|
|
||||||
|
-- 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);
|
||||||
|
-- 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);
|
||||||
|
|
||||||
|
-- Every create/update/delete of a visa/master or sber order, for the
|
||||||
|
-- order page's "Ammallar" table: who did it, whether it went through, and
|
||||||
|
-- for an update only the columns that changed - original holds their
|
||||||
|
-- values before, changes after. A create has no original and a delete no
|
||||||
|
-- changes. Failed actions are kept too, with exception set and changes
|
||||||
|
-- holding what was attempted. created_by is null when no user started it
|
||||||
|
-- (the GBÜS callback finalizing a payment).
|
||||||
|
CREATE TABLE IF NOT EXISTS visa_master_order_actions (
|
||||||
|
id bigserial PRIMARY KEY,
|
||||||
|
order_id bigint NOT NULL,
|
||||||
|
name character varying(20) NOT NULL,
|
||||||
|
status character varying(20) NOT NULL,
|
||||||
|
original jsonb,
|
||||||
|
changes jsonb,
|
||||||
|
exception text,
|
||||||
|
created_by bigint,
|
||||||
|
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||||
|
CONSTRAINT visa_master_order_actions_order_id_fkey
|
||||||
|
FOREIGN KEY (order_id) REFERENCES visa_master_payment_orders(id),
|
||||||
|
CONSTRAINT visa_master_order_actions_created_by_fkey
|
||||||
|
FOREIGN KEY (created_by) REFERENCES users(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS visa_master_order_actions_order_id_idx
|
||||||
|
ON visa_master_order_actions (order_id, id DESC);
|
||||||
|
|
||||||
|
-- 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();
|
||||||
+947
@@ -0,0 +1,947 @@
|
|||||||
|
-- Dev / staging mock data. Re-runnable: wipes app tables then reloads.
|
||||||
|
-- Usage: make seed
|
||||||
|
-- or: PGPASSWORD='bank@#23#@_password' psql -h localhost -p 5424 -U bank_admin -d bank_db -f db/seed.sql
|
||||||
|
-- Login (password = test1234):
|
||||||
|
-- superadmin@bank.tm / +993 61 92 92 48 (is_super: ähli permission awtomatik)
|
||||||
|
-- admin@bank.tm (scope=all, roles we backups-dan başga ähli)
|
||||||
|
-- manager@bank.tm (scope=branch: cards, loans, users, dashboard)
|
||||||
|
-- operator@bank.tm (scope=branch: cards)
|
||||||
|
-- loanop@bank.tm (scope=branch: loans)
|
||||||
|
-- bothop@bank.tm (scope=branch: cards + loans)
|
||||||
|
-- loanhead@bank.tm (scope=all: loans — ähli filiallaryň karz bölümi)
|
||||||
|
-- currency@bank.tm (scope=all: diňe walýuta)
|
||||||
|
-- serdar@bank.tm … leyla@bank.tm (role=user, scope=own)
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
TRUNCATE TABLE
|
||||||
|
activity_logs,
|
||||||
|
backups,
|
||||||
|
currencies,
|
||||||
|
visa_master_payment_logs,
|
||||||
|
visa_master_order_payments,
|
||||||
|
visa_master_payment_orders,
|
||||||
|
loan_paid_off_letters,
|
||||||
|
loans,
|
||||||
|
loan_orders,
|
||||||
|
card_rekwizit_orders,
|
||||||
|
card_pin_orders,
|
||||||
|
card_orders,
|
||||||
|
card_balances,
|
||||||
|
cards,
|
||||||
|
loan_order_required_docs,
|
||||||
|
loan_types,
|
||||||
|
card_states,
|
||||||
|
card_types,
|
||||||
|
branch_user,
|
||||||
|
branches,
|
||||||
|
provinces,
|
||||||
|
role_permissions,
|
||||||
|
roles,
|
||||||
|
registration_verifications,
|
||||||
|
users
|
||||||
|
RESTART IDENTITY CASCADE;
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Roles & permissions. Permission katalogy (permissions tablisasy) app
|
||||||
|
-- tarapyndan başlanda sinhronlanýar (rbac/perm); bu ýerde diňe rollar.
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO roles (code, name, scope, is_super, is_system) VALUES
|
||||||
|
('user', 'User', 'own', false, true),
|
||||||
|
('operator', 'Operator', 'branch', false, false),
|
||||||
|
('loan_operator', 'Loan Operator', 'branch', false, false),
|
||||||
|
('full_operator', 'Full Operator (cards + loans)','branch', false, false),
|
||||||
|
('admin', 'Admin', 'all', false, false),
|
||||||
|
('superadmin', 'Superadmin', 'all', true, true),
|
||||||
|
('manager', 'Branch Manager', 'branch', false, false),
|
||||||
|
('loan_head', 'Karz bölüminiň başlygy', 'all', false, false),
|
||||||
|
('currency_maintainer', 'Walyuta kursy operator', 'all', false, false);
|
||||||
|
|
||||||
|
INSERT INTO role_permissions (role_id, permission_code)
|
||||||
|
SELECT r.id, x.code
|
||||||
|
FROM (VALUES
|
||||||
|
('user', 'cards'),
|
||||||
|
('user', 'loans'),
|
||||||
|
('operator', 'cards'),
|
||||||
|
('operator', 'dashboard'),
|
||||||
|
('loan_operator', 'loans'),
|
||||||
|
('loan_operator', 'dashboard'),
|
||||||
|
('full_operator', 'cards'),
|
||||||
|
('full_operator', 'loans'),
|
||||||
|
('full_operator', 'dashboard'),
|
||||||
|
('admin', 'dashboard'),
|
||||||
|
('admin', 'cards'),
|
||||||
|
('admin', 'loans'),
|
||||||
|
('admin', 'users'),
|
||||||
|
('admin', 'branches'),
|
||||||
|
('admin', 'provinces'),
|
||||||
|
('admin', 'currencies'),
|
||||||
|
('admin', 'payment-settings'),
|
||||||
|
('admin', 'activity-logs'),
|
||||||
|
('manager', 'cards'),
|
||||||
|
('manager', 'loans'),
|
||||||
|
('manager', 'users'),
|
||||||
|
('manager', 'dashboard'),
|
||||||
|
('loan_head', 'loans'),
|
||||||
|
('loan_head', 'dashboard'),
|
||||||
|
('currency_maintainer', 'currencies')
|
||||||
|
) AS x(role, code)
|
||||||
|
JOIN roles r ON r.code = x.role;
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Users (14): superadmin, admin, manager, operator,
|
||||||
|
-- 1 branch-assigned user (serdar), 5 users (gulnar…leyla),
|
||||||
|
-- 1 currency maintainer, 1 loan operator, 1 cards+loans operator,
|
||||||
|
-- 1 head of loans (all branches).
|
||||||
|
-- Password = test1234 for all. Phone unique (idx_users_phone).
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO users (email, password, name, first_name, last_name, username, phone, role_id, active) VALUES
|
||||||
|
(
|
||||||
|
'superadmin@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Super Admin', 'Myrat', 'Nazarow', 'superadmin',
|
||||||
|
'+993 61 92 92 48', (SELECT id FROM roles WHERE code = 'superadmin'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'admin@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Admin', 'Nurmuhammet', 'Allanow', 'admin',
|
||||||
|
'+993 61 92 92 41', (SELECT id FROM roles WHERE code = 'admin'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'manager@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Branch Manager', 'Mergen', 'Berdiyew', 'manager',
|
||||||
|
'+993 61 92 92 42', (SELECT id FROM roles WHERE code = 'manager'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'operator@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Operator', 'Aygul', 'Hojayeva', 'operator',
|
||||||
|
'+993 61 92 92 43', (SELECT id FROM roles WHERE code = 'operator'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'serdar@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Serdar Myradow', 'Serdar', 'Myradow', 'serdar',
|
||||||
|
'+993 61 92 92 44', (SELECT id FROM roles WHERE code = 'user'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'gulnar@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Gulnar Orazowa', 'Gulnar', 'Orazowa', 'gulnar',
|
||||||
|
'+993 61 92 92 45', (SELECT id FROM roles WHERE code = 'user'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'dovran@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Dovran Annayew', 'Dovran', 'Annayew', 'dovran',
|
||||||
|
'+993 61 92 92 46', (SELECT id FROM roles WHERE code = 'user'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'maya@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Maya Halylowa', 'Maya', 'Halylowa', 'maya',
|
||||||
|
'+993 61 92 92 47', (SELECT id FROM roles WHERE code = 'user'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'kerim@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Kerim Atayew', 'Kerim', 'Atayew', 'kerim',
|
||||||
|
'+993 61 92 92 49', (SELECT id FROM roles WHERE code = 'user'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'leyla@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Leyla Gurbanowa', 'Leyla', 'Gurbanowa', 'leyla',
|
||||||
|
'+993 61 92 92 40', (SELECT id FROM roles WHERE code = 'user'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'currency@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Walýuta operator', 'Berdi', 'Hojayew', 'currency',
|
||||||
|
'+993 61 92 92 38', (SELECT id FROM roles WHERE code = 'currency_maintainer'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'loanop@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Loan Operator', 'Jeren', 'Atayeva', 'loanop',
|
||||||
|
'+993 61 92 92 37', (SELECT id FROM roles WHERE code = 'loan_operator'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'bothop@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Full Operator', 'Batyr', 'Myradow', 'bothop',
|
||||||
|
'+993 61 92 92 36', (SELECT id FROM roles WHERE code = 'full_operator'), true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'loanhead@bank.tm',
|
||||||
|
'$2a$12$.9KVj6x7wxUMdPcBJ6UpweYbzW4Mka0d2mQj7O20YHXpBKlb3ypdC',
|
||||||
|
'Loan Head', 'Aman', 'Orazow', 'loanhead',
|
||||||
|
'+993 61 92 92 35', (SELECT id FROM roles WHERE code = 'loan_head'), true
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Provinces — name = etrap, region = welaýat (admin location list)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO provinces (name, region, active) VALUES
|
||||||
|
('{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json, '{"en":"Ashgabat","ru":"Ашхабад","tm":"Aşgabat"}'::json, true),
|
||||||
|
('{"en":"Ak bugday","ru":"Ак бугдай","tm":"Ak bugdaý"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Babadayhan","ru":"Бабадайхан","tm":"Babadaýhan"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Baherden","ru":"Бахерден","tm":"Bäherden"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Gokdepe","ru":"Гокдепе","tm":"Gökdepe"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Kaka","ru":"Кака","tm":"Kaka"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Sarahs","ru":"Серахс","tm":"Sarahs"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Tejen","ru":"Теджен","tm":"Tejen"}'::json, '{"en":"Ahal","ru":"Ахал","tm":"Ahal"}'::json, true),
|
||||||
|
('{"en":"Balkanabat","ru":"Балканабад","tm":"Balkanabat"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Bereket","ru":"Берекет","tm":"Bereket"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Esenguly","ru":"Эсенгулы","tm":"Esenguly"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Etrek","ru":"Этрек","tm":"Etrek"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Garabogaz","ru":"Гарабогаз","tm":"Garabogaz"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Gyzylarbat","ru":"Кызыларбат","tm":"Gyzylarbat"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Hazar","ru":"Хазар","tm":"Hazar"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Magtymguly","ru":"Махтумкули","tm":"Magtymguly"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Turkmenbashy","ru":"Туркменбашы","tm":"Türkmenbaşy"}'::json, '{"en":"Balkan","ru":"Балкан","tm":"Balkan"}'::json, true),
|
||||||
|
('{"en":"Akdepe","ru":"Акдепе","tm":"Akdepe"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Boldumsaz","ru":"Болдумсаз","tm":"Boldumsaz"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Gorogly","ru":"Гёроглы","tm":"Görogly"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Gubadag","ru":"Губадаг","tm":"Gubadag"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Gurbansoltan Eje","ru":"Гурбансолтан эдже","tm":"Gurbansoltan eje ad."}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Koneurgench","ru":"Кёнеургенч","tm":"Köneürgenç"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Ruhubelent","ru":"Рухубелент","tm":"Ruhubelent"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"S. Turkmenbashy","ru":"С. Туркменбашы","tm":"S. Türkmenbaşy ad."}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Shawat","ru":"Шават","tm":"Şawat"}'::json, '{"en":"Dashoguz","ru":"Дашогуз","tm":"Daşoguz"}'::json, true),
|
||||||
|
('{"en":"Charjew","ru":"Чарджев","tm":"Çärjew"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Danew","ru":"Данев","tm":"Dänew"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Darganata","ru":"Дарганата","tm":"Darganata"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Dowletli","ru":"Довлетли","tm":"Döwletli"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Farap","ru":"Фарап","tm":"Farap"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Garabekewul","ru":"Гарабекевюль","tm":"Garabekewül"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Halach","ru":"Халач","tm":"Halaç"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Hojambaz","ru":"Ходжамбаз","tm":"Hojambaz"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Kerki","ru":"Керки","tm":"Kerki"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Koytendag","ru":"Койтендаг","tm":"Köýtendag"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Magdanly","ru":"Магданлы","tm":"Magdanly"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Sayat","ru":"Саят","tm":"Saýat"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Seydi","ru":"Сейди","tm":"Seýdi"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Turkmenabat","ru":"Туркменабад","tm":"Türkmenabat"}'::json, '{"en":"Lebap","ru":"Лебап","tm":"Lebap"}'::json, true),
|
||||||
|
('{"en":"Bayramaly","ru":"Байрамали","tm":"Baýramaly"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Garagum","ru":"Гарагум","tm":"Garagum"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Murgap","ru":"Мургап","tm":"Murgap"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Oguzhan","ru":"Огузхан","tm":"Oguzhan"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Sakarchage","ru":"Сакарчаге","tm":"Sakarçäge"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Serhetabat","ru":"Серхетабад","tm":"Serhetabat"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Tagtabazar","ru":"Тагтабазар","tm":"Tagtabazar"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Turkmengala","ru":"Туркменгала","tm":"Türkmengala"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Vekilbazar","ru":"Векильбазар","tm":"Wekilbazar"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true),
|
||||||
|
('{"en":"Yoloten","ru":"Ёлётен","tm":"Ýolöten"}'::json, '{"en":"Mary","ru":"Мары","tm":"Mary"}'::json, true);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Branches — 8 named mock şahamça first (ids 1–8 for order FKs),
|
||||||
|
-- then one şahamça per remaining etrap.
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO branches (
|
||||||
|
unique_code, name, address, region, province_id, phone_numbers,
|
||||||
|
billing_username, billing_password,
|
||||||
|
billing_visa_master_username, billing_visa_master_password,
|
||||||
|
billing_sber_username, billing_sber_password, active
|
||||||
|
)
|
||||||
|
SELECT v.unique_code, v.name::json, v.address::json, v.region, p.id, '+993 61 92 92 48', v.billing_username, 'billing_pass',
|
||||||
|
replace(v.billing_username, 'billing_', 'vm_'), 'vm_pass',
|
||||||
|
replace(v.billing_username, 'billing_', 'sber_'), 'sber_pass', v.active
|
||||||
|
FROM (VALUES
|
||||||
|
('AGB-01', '{"en":"Ashgabat Central Branch","ru":"Центральный филиал Ашхабад","tm":"Aşgabat Merkezi şahamça"}', '{"en":"Archabil Ave 1","ru":"пр. Арчабиль 1","tm":"Arçabil şaýoly 1"}', 'AG', 'Aşgabat', 'billing_agb', true),
|
||||||
|
('AGB-02', '{"en":"Ashgabat Kopetdag Branch","ru":"Филиал Копетдаг","tm":"Köpetdag şahamçasy"}', '{"en":"Turkmenbashy Ave 45","ru":"пр. Туркменбаши 45","tm":"Türkmenbaşy şaýoly 45"}', 'AG', 'Aşgabat', 'billing_agb2', true),
|
||||||
|
('AHL-01', '{"en":"Ahal Branch","ru":"Ахалский филиал","tm":"Ahal şahamçasy"}', '{"en":"Ak bugday, Main St 10","ru":"Ак бугдай, ул. Главная 10","tm":"Ak bugdaý, Baş köçe 10"}', 'AH', 'Ak bugdaý', 'billing_ahl', true),
|
||||||
|
('BLK-01', '{"en":"Balkanabat Branch","ru":"Филиал Балканабад","tm":"Balkanabat şahamçasy"}', '{"en":"Garaşsyzlyk St 7","ru":"ул. Гарашсызлык 7","tm":"Garaşsyzlyk köçesi 7"}', 'BL', 'Balkanabat', 'billing_blk', true),
|
||||||
|
('DSZ-01', '{"en":"Dashoguz Branch","ru":"Филиал Дашогуз","tm":"Daşoguz şahamçasy"}', '{"en":"Galkynyş St 3","ru":"ул. Галкыныш 3","tm":"Galkynyş köçesi 3"}', 'DZ', 'Daşoguz', 'billing_dsz', true),
|
||||||
|
('LBP-01', '{"en":"Turkmenabat Branch","ru":"Филиал Туркменабад","tm":"Türkmenabat şahamçasy"}', '{"en":"Magtymguly Ave 12","ru":"пр. Махтумкули 12","tm":"Magtymguly şaýoly 12"}', 'LB', 'Türkmenabat', 'billing_lbp', true),
|
||||||
|
('MRY-01', '{"en":"Mary Branch","ru":"Марыйский филиал","tm":"Mary şahamçasy"}', '{"en":"Mollanepes St 8","ru":"ул. Молланепес 8","tm":"Mollanepes köçesi 8"}', 'MR', 'Mary', 'billing_mry', true),
|
||||||
|
('MRY-02', '{"en":"Bayramaly Branch (inactive)","ru":"Филиал Байрамали (неактивен)","tm":"Baýramaly şahamçasy (işjeň däl)"}', '{"en":"Bayramaly, Central 1","ru":"Байрамали, Центральная 1","tm":"Baýramaly, Merkezi 1"}', 'MR', 'Baýramaly', 'billing_mry2', false)
|
||||||
|
) AS v(unique_code, name, address, region, province_tm, billing_username, active)
|
||||||
|
JOIN provinces p ON p.name->>'tm' = v.province_tm;
|
||||||
|
|
||||||
|
INSERT INTO branches (unique_code, name, address, region, province_id, phone_numbers, active)
|
||||||
|
SELECT
|
||||||
|
s.region_code || '-' || s.name_slug,
|
||||||
|
json_build_object(
|
||||||
|
'en', (s.name->>'en') || ' branch',
|
||||||
|
'ru', (s.name->>'ru') || ' филиал',
|
||||||
|
'tm', (s.name->>'tm') || ' şahamçasy'
|
||||||
|
),
|
||||||
|
json_build_object('en', s.name->>'en', 'ru', s.name->>'ru', 'tm', s.name->>'tm'),
|
||||||
|
s.region_code,
|
||||||
|
s.id,
|
||||||
|
'+993 61 92 92 48',
|
||||||
|
true
|
||||||
|
FROM (
|
||||||
|
SELECT
|
||||||
|
p.id,
|
||||||
|
p.name,
|
||||||
|
CASE p.region->>'tm'
|
||||||
|
WHEN 'Aşgabat' THEN 'AG'
|
||||||
|
WHEN 'Ahal' THEN 'AH'
|
||||||
|
WHEN 'Balkan' THEN 'BL'
|
||||||
|
WHEN 'Daşoguz' THEN 'DZ'
|
||||||
|
WHEN 'Lebap' THEN 'LB'
|
||||||
|
WHEN 'Mary' THEN 'MR'
|
||||||
|
ELSE 'XX'
|
||||||
|
END AS region_code,
|
||||||
|
trim(both '-' FROM upper(regexp_replace(
|
||||||
|
translate(p.name->>'tm', 'ÄäÇçŇňÖöŞşÜüÝý', 'AaCcNnOoSsUuYy'),
|
||||||
|
'[^A-Za-z0-9]+', '-', 'g'
|
||||||
|
))) AS name_slug
|
||||||
|
FROM provinces p
|
||||||
|
WHERE p.active
|
||||||
|
) s
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM branches b
|
||||||
|
WHERE b.unique_code = s.region_code || '-' || s.name_slug
|
||||||
|
OR b.province_id = s.id
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO branch_user (branch_id, user_id) VALUES
|
||||||
|
(1, 1),
|
||||||
|
(1, 2),
|
||||||
|
(1, 3),
|
||||||
|
(7, 4),
|
||||||
|
(2, 5),
|
||||||
|
(1, 11),
|
||||||
|
(7, 12),
|
||||||
|
(7, 13);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Card types (Kart görnüşleri) & card states (çykarma sebäpleri)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO card_types (name, price, notes, active) VALUES
|
||||||
|
('{"en":"Altyn Asyr","ru":"Алтын Асыр","tm":"Altyn Asyr"}'::json, '32', '', true),
|
||||||
|
('{"en":"Family","ru":"Семейная","tm":"Maşgala"}'::json, '32', '', true),
|
||||||
|
('{"en":"Deposit","ru":"Депозитная","tm":"Goýum"}'::json, '32', '', true),
|
||||||
|
('{"en":"Pension","ru":"Пенсионная","tm":"Pensiýa"}'::json, '32', '', true),
|
||||||
|
('{"en":"Entrepreneur","ru":"Предпринимательская","tm":"Telekeçi"}'::json, '32', '', true),
|
||||||
|
('{"en":"Credit","ru":"Кредитная","tm":"Karz"}'::json, '32', '', false),
|
||||||
|
('{"en":"Overdraft","ru":"Овердрафт","tm":"Owerdraft"}'::json, '32', '', true);
|
||||||
|
|
||||||
|
INSERT INTO card_states (name, price, notes, active) VALUES
|
||||||
|
('{"en":"New","ru":"Новая","tm":"Täze"}'::json, '32', '', true),
|
||||||
|
('{"en":"Broken / damaged","ru":"Сломанная / повреждённая","tm":"Döwülen/Zaýalanan"}'::json, '32', '', true),
|
||||||
|
('{"en":"Usage period expired","ru":"Истёк срок использования","tm":"Ulanylyş möhleti geçen"}'::json, '32', '', true),
|
||||||
|
('{"en":"Surname change","ru":"Смена фамилии","tm":"Familiýasy üýtgeýär"}'::json, '32', '', true),
|
||||||
|
('{"en":"Lost","ru":"Утеряна","tm":"Ýiten"}'::json, '37.75', '', true),
|
||||||
|
('{"en":"PIN envelope (blocked)","ru":"PIN-конверт (заблокирован)","tm":"Pin bukja (bloklanan)"}'::json, '3.02', '', false),
|
||||||
|
('{"en":"Requisites","ru":"Реквизиты","tm":"Rekwizit"}'::json, '2.30', '', false);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Loan types (Karz görnüşleri) & required docs
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO loan_types (name, tax, maturity, notes, active) VALUES
|
||||||
|
('{"en":"Youth / newlyweds loan","ru":"Кредит для молодожёнов","tm":"Ýaş çatynjalara"}'::json, 1.00, '30', '{}'::json, true),
|
||||||
|
('{"en":"Consumer loan secured by guarantor","ru":"Потребительский кредит под поручительство","tm":"Üpjünçiligine zamunlyk bolan sarp ediş karzy"}'::json, 1.00, '30', '{}'::json, true),
|
||||||
|
('{"en":"Small loans","ru":"Кредиты малого объёма","tm":"Kiçi göwrümli karzlar"}'::json, 1.00, '30', '{}'::json, true),
|
||||||
|
('{"en":"Consumer loan secured by collateral","ru":"Потребительский кредит под залог имущества","tm":"Üpjünçiligine girew emlägi bolan sarp ediş karzy"}'::json, 1.00, '30', '{}'::json, true),
|
||||||
|
('{"en":"Student loan","ru":"Студенческий кредит","tm":"Talyp karzy"}'::json, 1.00, '30', '{"en":"Note","ru":"Примечание","tm":"Bellik"}'::json, true);
|
||||||
|
|
||||||
|
INSERT INTO loan_order_required_docs (name, value, active) VALUES
|
||||||
|
('Passport copy', 'passport', true),
|
||||||
|
('Income certificate', 'income', true),
|
||||||
|
('Employment letter', 'employment', true),
|
||||||
|
('Property documents', 'property', true),
|
||||||
|
('Guarantor passport', 'guarantor_passport', true),
|
||||||
|
('Old checklist (inactive)', 'legacy', false);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Cards belonging to users
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO cards (user_id, number, name, month, year, type) VALUES
|
||||||
|
(5, '4169740012345678', 'SERDAR MYRADOW', '12', '28', '1'),
|
||||||
|
(6, '4169740087654321', 'GULNAR ORAZOWA', '06', '27', '1'),
|
||||||
|
(8, '5536910011223344', 'MAYA HALYLOWA', '03', '29', '3'),
|
||||||
|
(7, '9860010055667788', 'DOVRAN ANNAYEW', '09', '26', '4'),
|
||||||
|
(9, '4169740011112222', 'KERIM ATAYEW', '08', '28', '1'),
|
||||||
|
(10, '5536910055556666', 'LEYLA GURBANOWA', '11', '29', '3');
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Card orders
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO card_orders (
|
||||||
|
unique_id, card_state_id, card_type_id, region, branch_id,
|
||||||
|
customer_name, customer_surname, customer_patronic_name, born_at,
|
||||||
|
citizenship, passport_serie, passport_id, passport_given_at, passport_given_by,
|
||||||
|
born_place, job_location, passport_address, real_address, phone, phone_additional,
|
||||||
|
status, passport_one, passport_two, passport_three, passport_four,
|
||||||
|
notes, user_id, paid
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'CO-2026-0001', 1, 1, 'AG', 1,
|
||||||
|
'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12',
|
||||||
|
'TM', 'I-AG', '123456', '2015-03-20', 'Ashgabat City Police',
|
||||||
|
'Ashgabat', 'Bank employee', 'Ashgabat, 10ýyl Abadanlyk 5', 'Ashgabat, 10ýyl Abadanlyk 5',
|
||||||
|
'+993 61 92 92 48', '+993 61 92 92 48',
|
||||||
|
'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||||
|
'First Visa Classic order', 5, false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CO-2026-0002', 2, 2, 'AG', 1,
|
||||||
|
'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03',
|
||||||
|
'TM', 'I-AG', '654321', '2014-08-11', 'Ashgabat City Police',
|
||||||
|
'Ashgabat', 'Teacher', 'Ashgabat, Andalyp 12', 'Ashgabat, Andalyp 12',
|
||||||
|
'+993 61 92 92 48', NULL,
|
||||||
|
'approved', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||||
|
'Lost card reissue — Gold', 6, true
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CO-2026-0003', 1, 4, 'MR', 7,
|
||||||
|
'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25',
|
||||||
|
'TM', 'I-MR', '112233', '2018-06-01', 'Mary Police',
|
||||||
|
'Mary', 'Farmer', 'Mary, Garaşsyzlyk 3', 'Mary, Garaşsyzlyk 3',
|
||||||
|
'+993 61 92 92 48', NULL,
|
||||||
|
'rejected', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||||
|
'Incomplete documents', 7, false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CO-2026-0004', 3, 3, 'BL', 4,
|
||||||
|
'Maya', 'Halylowa', 'Saparowna', '1992-07-19',
|
||||||
|
'TM', 'I-BL', '445566', '2016-02-14', 'Balkanabat Police',
|
||||||
|
'Balkanabat', 'Nurse', 'Balkanabat, Magtymguly 9', 'Balkanabat, Magtymguly 9',
|
||||||
|
'+993 61 92 92 48', NULL,
|
||||||
|
'pending', 'pass1.jpg', 'pass2.jpg', 'pass3.jpg', 'pass4.jpg',
|
||||||
|
'Damaged MasterCard', 8, false
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Card PIN orders
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO card_pin_orders (
|
||||||
|
unique_id, user_id, card_type_id, card_number, region, branch_id,
|
||||||
|
customer_name, customer_surname, customer_patronic_name, born_at, phone,
|
||||||
|
passport_serie, passport_id,
|
||||||
|
passport_one, passport_two, passport_three, passport_four,
|
||||||
|
status, notes
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'CPO-2026-0001', 5, 1, '4169740012345678', 'AG', 1,
|
||||||
|
'Serdar', 'Myradow', 'Gurbanowicz', '1990-05-12', '+993 61 92 92 48',
|
||||||
|
'I-AG', '123456',
|
||||||
|
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||||
|
'pending', 'PIN reset request'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CPO-2026-0002', 7, 4, '9860010055667788', 'MR', 7,
|
||||||
|
'Dovran', 'Annayew', 'Hojamyradowiç', '1995-01-25', '+993 61 92 92 48',
|
||||||
|
'I-MR', '112233',
|
||||||
|
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||||
|
'completed', 'PIN issued'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CPO-2026-0003', NULL, 2, '4169740099990000', 'AH', 3,
|
||||||
|
'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48',
|
||||||
|
'I-AH', '334455',
|
||||||
|
'pin1.jpg', 'pin2.jpg', 'pin3.jpg', 'pin4.jpg',
|
||||||
|
'rejected', 'Passport mismatch'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Card rekwizit orders
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO card_rekwizit_orders (
|
||||||
|
unique_id, user_id, card_type_id, card_number, card_month, card_year,
|
||||||
|
region, branch_id,
|
||||||
|
customer_name, customer_surname, customer_patronic_name, born_at, phone,
|
||||||
|
passport_serie, passport_id,
|
||||||
|
passport_one, passport_two, passport_three, passport_four,
|
||||||
|
status, notes
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'CRO-2026-0001', 6, 1, '4169740088776655', '08', '2028',
|
||||||
|
'AG', 1,
|
||||||
|
'Gulnar', 'Orazowa', 'Batyrowna', '1988-11-03', '+993 61 92 92 48',
|
||||||
|
'I-AG', '654321',
|
||||||
|
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
|
||||||
|
'pending', 'Card details request'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CRO-2026-0002', 8, 3, '9860010011223344', '11', '2027',
|
||||||
|
'BL', 4,
|
||||||
|
'Maya', 'Halylowa', 'Saparowna', '1992-07-19', '+993 61 92 92 48',
|
||||||
|
'I-BL', '445566',
|
||||||
|
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
|
||||||
|
'approved', 'Details issued'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'CRO-2026-0003', NULL, 2, '4169740077001122', '01', '2030',
|
||||||
|
'AH', 3,
|
||||||
|
'Leyla', 'Garayeva', 'Meredowna', '1993-04-08', '+993 61 92 92 48',
|
||||||
|
'I-AH', '778899',
|
||||||
|
'rek1.jpg', 'rek2.jpg', 'rek3.jpg', 'rek4.jpg',
|
||||||
|
'rejected', 'Expired card'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Loan orders
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO loan_orders (
|
||||||
|
unique_id, source, user_id, loan_type, region, branch_id,
|
||||||
|
customer_name, customer_surname, customer_patronic_name,
|
||||||
|
passport_address, real_address, passport_serie, passport_id,
|
||||||
|
passport_given_at, passport_given_by, born_place, born_at,
|
||||||
|
email, phone, phone_additional, phone_home,
|
||||||
|
work_region, work_province_id, work_company, work_company_accountant_number,
|
||||||
|
work_started_at, work_salary, work_position,
|
||||||
|
education, marriage_status,
|
||||||
|
passport_one, passport_two, passport_three, passport_four,
|
||||||
|
loan_amount, card_number, card_name, card_month, card_year,
|
||||||
|
guarantor_name, guarantor_surname, guarantor_patronic_name,
|
||||||
|
guarantor_passport_serie, guarantor_passport_id,
|
||||||
|
guarantor_card_number, guarantor_card_name, guarantor_card_month, guarantor_card_year,
|
||||||
|
guarantor_note,
|
||||||
|
loan_order_required_doc_id, status, satisfiable, notes
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'0001', 'mobile', 9, 1, 'AG', 1,
|
||||||
|
'Kerim', 'Atayew', 'Begliýewiç',
|
||||||
|
'Ashgabat, Bitaraplyk 20', 'Ashgabat, Bitaraplyk 20', 'I-AG', '101010',
|
||||||
|
'2017-01-15', 'Ashgabat City Police', 'Ashgabat', '1989-03-21',
|
||||||
|
'kerim@bank.tm', '+993 61 92 92 48', NULL, '+993 61 92 92 48',
|
||||||
|
'AG', 1, 'Türkmen Poçta', 'ACC-1001',
|
||||||
|
'2019-05-01', '4500', 'Specialist',
|
||||||
|
'higher', 'married',
|
||||||
|
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||||
|
'20000', '4169740011112222', 'KERIM ATAYEW', '08', '28',
|
||||||
|
'Myrat', 'Atayew', 'Begliýewiç',
|
||||||
|
'I-AG', '202020',
|
||||||
|
'4169740033334444', 'MYRAT ATAYEW', '08', '27',
|
||||||
|
'Brother',
|
||||||
|
1, 'pending', 'yes', 'Consumer loan application'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'0002', 'mobile', 10, 3, 'AG', 2,
|
||||||
|
'Leyla', 'Gurbanowa', 'Saparowna',
|
||||||
|
'Ashgabat, Andalyp 8', 'Ashgabat, Andalyp 8', 'I-AG', '303030',
|
||||||
|
'2016-09-10', 'Ashgabat City Police', 'Ashgabat', '1994-08-02',
|
||||||
|
'leyla@bank.tm', '+993 61 92 92 48', '+993 61 92 92 48', NULL,
|
||||||
|
'AG', 1, 'Altyn Asyr', 'ACC-2002',
|
||||||
|
'2020-02-15', '3800', 'Accountant',
|
||||||
|
'higher', 'single',
|
||||||
|
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||||
|
'80000', '5536910055556666', 'LEYLA GURBANOWA', '11', '29',
|
||||||
|
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
|
||||||
|
2, 'approved', 'yes', 'Auto loan approved'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'0003', 'mobile', 7, 2, 'MR', 7,
|
||||||
|
'Dovran', 'Annayew', 'Hojamyradowiç',
|
||||||
|
'Mary, Galkynyş 15', 'Mary, Galkynyş 15', 'I-MR', '112233',
|
||||||
|
'2012-04-22', 'Mary Police', 'Mary', '1995-01-25',
|
||||||
|
'dovran@bank.tm', '+993 61 92 92 48', NULL, NULL,
|
||||||
|
'MR', (SELECT id FROM provinces WHERE name->>'tm' = 'Mary'), 'Mary Textile', 'ACC-3003',
|
||||||
|
'2015-01-10', '5200', 'Engineer',
|
||||||
|
'higher', 'married',
|
||||||
|
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||||
|
'250000', NULL, NULL, NULL, NULL,
|
||||||
|
'Hatyja', 'Jumaýewa', 'Berdiýewna',
|
||||||
|
'I-MR', '505050',
|
||||||
|
'9860010077778888', 'HATYJA JUMAYEWA', '01', '28',
|
||||||
|
'Spouse',
|
||||||
|
4, 'review', 'pending', 'Mortgage under review'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'0004', 'mobile', NULL, 4, 'LB', 6,
|
||||||
|
'Oguljenan', 'Çaryýewa', 'Myradowna',
|
||||||
|
'Turkmenabat, Magtymguly 2', 'Turkmenabat, Magtymguly 2', 'I-LB', '606060',
|
||||||
|
'2019-11-05', 'Turkmenabat Police', 'Turkmenabat', '1996-12-12',
|
||||||
|
'ogul@mail.tm', '+993 61 92 92 48', NULL, NULL,
|
||||||
|
'LB', (SELECT id FROM provinces WHERE name->>'tm' = 'Türkmenabat'), 'Self-employed', NULL,
|
||||||
|
'2021-03-01', '6000', 'Entrepreneur',
|
||||||
|
'secondary', 'single',
|
||||||
|
'lo1.jpg', 'lo2.jpg', 'lo3.jpg', 'lo4.jpg',
|
||||||
|
'50000', '4169740099998888', 'OGULJENAN CARYYEWA', '04', '27',
|
||||||
|
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
|
||||||
|
3, 'rejected', 'no', 'Insufficient income proof'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Loans (repayment accounts)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO loans (user_id, passport_serie, passport_id, account_number) VALUES
|
||||||
|
(9, 'I-AG', '101010', 'ACC-LOAN-10001'),
|
||||||
|
(10, 'I-AG', '303030', 'ACC-LOAN-10002'),
|
||||||
|
(7, 'I-MR', '112233', 'ACC-LOAN-10003'),
|
||||||
|
(5, 'I-AG', '123456', 'ACC-LOAN-10004'),
|
||||||
|
(6, 'I-AG', '654321', 'ACC-LOAN-10005');
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Loan paid-off letters
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO loan_paid_off_letters (
|
||||||
|
unique_id, region, branch_id, user_id,
|
||||||
|
customer_name, customer_surname, customer_patronic_name, born_at, phone,
|
||||||
|
passport_serie, passport_id, status, notes,
|
||||||
|
loan_contract_number, loan_contract_date, loan_amount, loan_reason, loan_file
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'LPL-2026-0001', 'AG', 1, 9,
|
||||||
|
'Kerim', 'Atayew', 'Begliýewiç', '1989-03-21', '+993 61 92 92 48',
|
||||||
|
'I-AG', '101010', 'pending', 'Waiting for branch confirmation',
|
||||||
|
'CTR-2024-1001', '2024-01-15', '15000', 'Consumer loan closed', 'letter1.pdf'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'LPL-2026-0002', 'AG', 2, 10,
|
||||||
|
'Leyla', 'Gurbanowa', 'Saparowna', '1994-08-02', '+993 61 92 92 48',
|
||||||
|
'I-AG', '303030', 'approved', 'Paid off confirmed',
|
||||||
|
'CTR-2023-2202', '2023-06-01', '8000', 'Early repayment', 'letter2.pdf'
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'LPL-2026-0003', 'AG', 1, NULL,
|
||||||
|
'Batyr', 'Saparow', 'Orazowicz', '1991-12-01', '+993 61 92 92 48',
|
||||||
|
'I-AH', '334455', 'rejected', 'Outstanding balance remains',
|
||||||
|
'CTR-2025-3303', '2025-02-10', '20000', 'Requested too early', NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Visa / Master payment orders (type = student)
|
||||||
|
-- documents JSON keys match the admin upload slots (student + sender).
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO visa_master_payment_orders (
|
||||||
|
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,
|
||||||
|
paid, amount_usd
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'VMP-2026-0001', 'student', 'Serdar', 'Myradow', '+993 61 92 92 48', 'serdar@bank.tm',
|
||||||
|
'AG', 1, 5, 'Aşgabat, Parahat 7',
|
||||||
|
'{"fullName":"Myradow Serdar Orazowiç","passportSerie":"I-AG","passportNumber":"123456","depositAccount":"23202984200012345678"}'::json,
|
||||||
|
'[{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["visa-card-1.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-1.pdf"],
|
||||||
|
"student_ticket_copy":["ticket-1.pdf"],
|
||||||
|
"student_internal_passport":["student-internal-1.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-1.pdf"],
|
||||||
|
"student_visa_page":["student-visa-page-1.pdf"],
|
||||||
|
"student_stamp_page":["student-stamp-1.pdf"],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-1.pdf"],
|
||||||
|
"sender_foreign_passport":["sender-foreign-1.pdf"],
|
||||||
|
"sender_stamp_page":["sender-stamp-1.pdf"],
|
||||||
|
"kinship_documents":["kinship-1.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'pending', 'Garaşylýar',
|
||||||
|
'Myradow Serdar Orazowiç', 'I-AG', '123456', '23202984200012345678',
|
||||||
|
'Orazowa Gulnar Myradowna', 'I-AG', '654321', NULL,
|
||||||
|
false, NULL
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'VMP-2026-0002', 'student', 'Kerim', 'Atayew', '+993 61 92 92 48', NULL,
|
||||||
|
'AG', 2, 9, 'Aşgabat, 10 ýyl Abadançylyk',
|
||||||
|
'{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-AG","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json,
|
||||||
|
'[{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AG","passportNumber":"303030"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["visa-card-2.pdf"],
|
||||||
|
"student_enrollment_certificate":[],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-2.pdf"],
|
||||||
|
"student_foreign_passport":[],
|
||||||
|
"student_visa_page":[],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-2.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":["sender-stamp-2.pdf"],
|
||||||
|
"kinship_documents":[],
|
||||||
|
"first_passport_series_info":["old-passport-series-2.pdf"],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'approved', NULL,
|
||||||
|
'Atayew Kerim Begliýewiç', 'I-AG', '101010', '23202984200010101011',
|
||||||
|
'Gurbanowa Leyla Saparowna', 'I-AG', '303030', NULL,
|
||||||
|
true, 150.00
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Sber payment orders (type = sber). Ids 3–8; aşakdaky töleg/loglar
|
||||||
|
-- order_id 4, 5, 6-a salgylanýar.
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO visa_master_payment_orders (
|
||||||
|
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,
|
||||||
|
paid, amount_usd
|
||||||
|
) VALUES
|
||||||
|
(
|
||||||
|
'VMP-2026-0003', 'sber', 'Batyr', 'Saparow', '+993 61 92 92 48', NULL,
|
||||||
|
'AG', 1, 5, 'Aşgabat, Bitarap Türkmenistan 12',
|
||||||
|
'{"fullName":"Saparow Batyr Annaýewiç","passportSerie":"I-AG","passportNumber":"202020","depositAccount":"23202984200020202022"}'::json,
|
||||||
|
'[{"fullName":"Saparowa Aýna Batyrowna","passportSerie":"I-AG","passportNumber":"404040"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["sber-card-3.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-3.pdf"],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-3.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-3.pdf"],
|
||||||
|
"student_visa_page":[],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-3.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":[],
|
||||||
|
"kinship_documents":["kinship-3.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'pending', 'Sber tölegi garaşylýar',
|
||||||
|
'Saparow Batyr Annaýewiç', 'I-AG', '202020', '23202984200020202022',
|
||||||
|
'Saparowa Aýna Batyrowna', 'I-AG', '404040', NULL,
|
||||||
|
false, 200.00
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'VMP-2026-0004', 'sber', 'Aýna', 'Orazowa', '+993 61 92 92 48', 'gulnar@bank.tm',
|
||||||
|
'AG', 1, 6, 'Aşgabat, Andalyp 21',
|
||||||
|
'{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321","depositAccount":"23202984200065432100"}'::json,
|
||||||
|
'[{"fullName":"Orazowa Aýna Serdarowna","passportSerie":"I-AG","passportNumber":"505050"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["sber-card-4.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-4.pdf"],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-4.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-4.pdf"],
|
||||||
|
"student_visa_page":["student-visa-page-4.pdf"],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-4.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":[],
|
||||||
|
"kinship_documents":["kinship-4.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'approved', 'Sber tölegi geçirildi',
|
||||||
|
'Orazowa Gulnar Myradowna', 'I-AG', '654321', '23202984200065432100',
|
||||||
|
'Orazowa Aýna Serdarowna', 'I-AG', '505050', NULL,
|
||||||
|
true, 250.00
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'VMP-2026-0005', 'sber', 'Merdan', 'Hojaýew', '+993 61 92 92 48', 'dovran@bank.tm',
|
||||||
|
'AG', 2, 7, 'Aşgabat, Garaşsyzlyk 55',
|
||||||
|
'{"fullName":"Hojaýew Döwran Amanowiç","passportSerie":"I-AG","passportNumber":"606060","depositAccount":"23202984200060606066"}'::json,
|
||||||
|
'[{"fullName":"Hojaýew Merdan Döwranowiç","passportSerie":"I-AG","passportNumber":"707070"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["sber-card-5.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-5.pdf"],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-5.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-5.pdf"],
|
||||||
|
"student_visa_page":["student-visa-page-5.pdf"],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-5.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":[],
|
||||||
|
"kinship_documents":["kinship-5.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'approved', 'Töleg şowsuz, gaýtadan synanyşyň',
|
||||||
|
'Hojaýew Döwran Amanowiç', 'I-AG', '606060', '23202984200060606066',
|
||||||
|
'Hojaýew Merdan Döwranowiç', 'I-AG', '707070', NULL,
|
||||||
|
false, 200.00
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'VMP-2026-0006', 'sber', 'Leýli', 'Nurýewa', '+993 61 92 92 48', 'maya@bank.tm',
|
||||||
|
'AG', 1, 8, 'Aşgabat, Oguzhan 3',
|
||||||
|
'{"fullName":"Nurýewa Maýa Batyrowna","passportSerie":"I-AG","passportNumber":"808080","depositAccount":"23202984200080808088"}'::json,
|
||||||
|
'[{"fullName":"Nurýewa Leýli Myratowna","passportSerie":"I-AG","passportNumber":"909090"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["sber-card-6.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-6.pdf"],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-6.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-6.pdf"],
|
||||||
|
"student_visa_page":["student-visa-page-6.pdf"],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-6.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":[],
|
||||||
|
"kinship_documents":["kinship-6.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'approved', 'GBÜS tassyklamasy garaşylýar',
|
||||||
|
'Nurýewa Maýa Batyrowna', 'I-AG', '808080', '23202984200080808088',
|
||||||
|
'Nurýewa Leýli Myratowna', 'I-AG', '909090', NULL,
|
||||||
|
false, 150.00
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'VMP-2026-0007', 'sber', 'Rahman', 'Gurbanow', '+993 61 92 92 48', 'leyla@bank.tm',
|
||||||
|
'AH', 3, 10, 'Ak bugdaý, Täze ýol 4',
|
||||||
|
'{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AH","passportNumber":"303030","depositAccount":"23202984200030303033"}'::json,
|
||||||
|
'[{"fullName":"Gurbanow Rahman Kakajanowiç","passportSerie":"I-AH","passportNumber":"111222"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["sber-card-7.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-7.pdf"],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-7.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-7.pdf"],
|
||||||
|
"student_visa_page":["student-visa-page-7.pdf"],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-7.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":[],
|
||||||
|
"kinship_documents":["kinship-7.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'rejected', 'Okuw güwänamasy ýok',
|
||||||
|
'Gurbanowa Leyla Saparowna', 'I-AH', '303030', '23202984200030303033',
|
||||||
|
'Gurbanow Rahman Kakajanowiç', 'I-AH', '111222', NULL,
|
||||||
|
false, NULL
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'VMP-2026-0008', 'sber', 'Myrat', 'Atayew', '+993 61 92 92 48', 'kerim@bank.tm',
|
||||||
|
'MR', 7, 9, 'Mary, Magtymguly 18',
|
||||||
|
'{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-MR","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json,
|
||||||
|
'[{"fullName":"Atayew Myrat Kerimowiç","passportSerie":"I-MR","passportNumber":"121212"}]'::json,
|
||||||
|
'{
|
||||||
|
"student_visa_card_details":["sber-card-8.pdf"],
|
||||||
|
"student_enrollment_certificate":["enrollment-8.pdf"],
|
||||||
|
"student_ticket_copy":[],
|
||||||
|
"student_internal_passport":["student-internal-8.pdf"],
|
||||||
|
"student_foreign_passport":["student-foreign-8.pdf"],
|
||||||
|
"student_visa_page":["student-visa-page-8.pdf"],
|
||||||
|
"student_stamp_page":[],
|
||||||
|
"student_enrollment_clarification":[],
|
||||||
|
"sender_internal_passport":["sender-internal-8.pdf"],
|
||||||
|
"sender_foreign_passport":[],
|
||||||
|
"sender_stamp_page":[],
|
||||||
|
"kinship_documents":["kinship-8.pdf"],
|
||||||
|
"first_passport_series_info":[],
|
||||||
|
"police_passport_series_info":[]
|
||||||
|
}'::json,
|
||||||
|
'pending', 'Sber: resminamalar barlanýar',
|
||||||
|
'Atayew Kerim Begliýewiç', 'I-MR', '101010', '23202984200010101011',
|
||||||
|
'Atayew Myrat Kerimowiç', 'I-MR', '121212', NULL,
|
||||||
|
false, NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Sber payout attempts (visa_master_order_payments) & step logs.
|
||||||
|
-- Kurs: USD→TMT 3.5175, RUB→TMT 0.047504; sber_bank_fee_tmt = 100,
|
||||||
|
-- tveb_fee_usd = 18 (= 63.32 TMT). Sber üçin gbus_fee_tmt NULL.
|
||||||
|
-- Order ids: 4 = paid (2 aý), 5 = failed, 6 = pending (GBÜS garaşylýar).
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO visa_master_order_payments (
|
||||||
|
order_id, user_id, payment_period, exchange_rate_usd, exchange_rate_rub, amount_tmt,
|
||||||
|
bank_fee_tmt, gbus_fee_tmt, tveb_fee_usd, tveb_fee_tmt, total_amount_tmt,
|
||||||
|
gateway_status, gateway_reference, gateway_response, created_by, order_number, created_at, updated_at
|
||||||
|
) VALUES
|
||||||
|
(4, 6, '2026-08-01', 3.5175, 0.047504, 879.38, 100, NULL, 18, 63.32, 1042.70,
|
||||||
|
'paid', 'a1b2c3d4-0004-4001-8001-000000000001', '{"orderStatus":2,"actionCode":0,"actionCodeDescription":"Request processed successfully"}'::jsonb,
|
||||||
|
3, '150826101512', '2026-08-15 05:15:12', '2026-08-15 05:17:40'),
|
||||||
|
(4, 6, '2026-09-01', 3.5175, 0.047504, 879.38, 100, NULL, 18, 63.32, 1042.70,
|
||||||
|
'paid', 'a1b2c3d4-0004-4001-8001-000000000002', '{"orderStatus":2,"actionCode":0,"actionCodeDescription":"Request processed successfully"}'::jsonb,
|
||||||
|
3, '120926112030', '2026-09-12 06:20:30', '2026-09-12 06:22:05'),
|
||||||
|
(5, 7, '2026-09-01', 3.5175, 0.047504, 700.00, 100, NULL, 18, 63.32, 863.32,
|
||||||
|
'failed', 'a1b2c3d4-0005-4001-8001-000000000003', '{"orderStatus":6,"actionCode":-2007,"actionCodeDescription":"Decline. Payment time limit"}'::jsonb,
|
||||||
|
3, '250926143011', '2026-09-25 09:30:11', '2026-09-25 09:50:11'),
|
||||||
|
(6, 8, '2026-09-01', 3.5175, 0.047504, 527.63, 100, NULL, 18, 63.32, 690.95,
|
||||||
|
'pending', 'a1b2c3d4-0006-4001-8001-000000000004', '{"errorCode":"0","orderId":"a1b2c3d4-0006-4001-8001-000000000004"}'::jsonb,
|
||||||
|
3, '300926154500', '2026-09-30 10:45:00', '2026-09-30 10:45:01');
|
||||||
|
|
||||||
|
INSERT INTO visa_master_payment_logs (order_id, step, detail, created_by, created_at) VALUES
|
||||||
|
(4, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":879.38,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-12 06:20:28'),
|
||||||
|
(4, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":1042.70}'::jsonb, 3, '2026-09-12 06:20:29'),
|
||||||
|
(4, 'callback_received', '{"gatewayStatus":"pending"}'::jsonb, NULL, '2026-09-12 06:22:04'),
|
||||||
|
(4, 'payment_finalized', '{"paid":true,"gatewayStatus":"paid"}'::jsonb, NULL, '2026-09-12 06:22:05'),
|
||||||
|
(5, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":700.00,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-25 09:30:09'),
|
||||||
|
(5, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":863.32}'::jsonb, 3, '2026-09-25 09:30:10'),
|
||||||
|
(5, 'status_check_response', '{"success":true,"paid":false,"orderStatus":6,"actionCode":-2007}'::jsonb, 3, '2026-09-25 09:50:10'),
|
||||||
|
(5, 'payment_finalized', '{"paid":false,"gatewayStatus":"failed"}'::jsonb, 3, '2026-09-25 09:50:11'),
|
||||||
|
(6, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":527.63,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-30 10:44:59'),
|
||||||
|
(6, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":690.95}'::jsonb, 3, '2026-09-30 10:45:00');
|
||||||
|
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Currency rates (Walýuta kursy)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO currencies (currency_from, currency_to, value, created_by, updated_by) VALUES
|
||||||
|
('EUR', 'TMT', 3.812, 2, 2),
|
||||||
|
('USD', 'TMT', 3.5175, 2, 2),
|
||||||
|
('EUR', 'RUB', 80.23, 2, 1),
|
||||||
|
('USD', 'RUB', 74.0455, 2, 2),
|
||||||
|
('RUB', 'TMT', 0.047504, 2, 2),
|
||||||
|
('USD', 'USD', 250, 1, 1),
|
||||||
|
('GBP', 'TMT', 4.45, 2, 2),
|
||||||
|
('CNY', 'TMT', 0.485, 2, 3);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Activity logs
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
INSERT INTO activity_logs (user_id, method, path, module, action, status_code, request_body, ip) VALUES
|
||||||
|
(1, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"superadmin@bank.tm"}'::jsonb, '127.0.0.1'),
|
||||||
|
(2, 'POST', '/api/admin/login', 'auth', 'login', 200, '{"email":"admin@bank.tm"}'::jsonb, '10.0.0.5'),
|
||||||
|
(2, 'GET', '/api/admin/users', 'users', 'list', 200, NULL, '10.0.0.5'),
|
||||||
|
(1, 'POST', '/api/admin/provinces', 'provinces', 'create', 200, '{"name":{"tm":"Aşgabat"}}'::jsonb, '127.0.0.1'),
|
||||||
|
(3, 'GET', '/api/admin/card-orders', 'card-orders', 'list', 200, NULL, '10.0.0.12'),
|
||||||
|
(3, 'PUT', '/api/admin/card-orders/2', 'card-orders', 'update', 200, '{"status":"approved"}'::jsonb, '10.0.0.12'),
|
||||||
|
(4, 'GET', '/api/admin/loan-orders', 'loan-orders', 'list', 200, NULL, '10.0.0.20'),
|
||||||
|
(4, 'POST', '/api/admin/loan-orders', 'loan-orders', 'create', 400, '{"loanAmount":"0"}'::jsonb, '10.0.0.20'),
|
||||||
|
(1, 'DELETE', '/api/admin/roles/99', 'roles', 'delete', 404, NULL, '127.0.0.1'),
|
||||||
|
(3, 'GET', '/api/admin/branches', 'branches', 'list', 200, NULL, '10.0.0.12'),
|
||||||
|
(2, 'PUT', '/api/admin/profile', 'auth', 'update', 200, '{"firstName":"Nurmuhammet"}'::jsonb, '10.0.0.5'),
|
||||||
|
(5, 'GET', '/api/admin/cards', 'cards', 'list', 200, NULL, '10.0.0.30');
|
||||||
|
|
||||||
|
-- TRUNCATE ... CASCADE payment_settings-i hem arassalaýar (users FK); ýeke setiri gaýtadan goý.
|
||||||
|
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;
|
||||||
|
|
||||||
|
-- payment_texts hem şeýle (users FK); klient kodlary gaýtadan goý.
|
||||||
|
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":"","ru":"","en":""}'::jsonb)
|
||||||
|
ON CONFLICT (code) DO NOTHING;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
-- Quick counts
|
||||||
|
SELECT 'users' AS table_name, count(*) FROM users
|
||||||
|
UNION ALL SELECT 'roles', count(*) FROM roles
|
||||||
|
UNION ALL SELECT 'role_permissions', count(*) FROM role_permissions
|
||||||
|
UNION ALL SELECT 'branch_user', count(*) FROM branch_user
|
||||||
|
UNION ALL SELECT 'permissions', count(*) FROM permissions
|
||||||
|
UNION ALL SELECT 'provinces', count(*) FROM provinces
|
||||||
|
UNION ALL SELECT 'branches', count(*) FROM branches
|
||||||
|
UNION ALL SELECT 'card_types', count(*) FROM card_types
|
||||||
|
UNION ALL SELECT 'card_states', count(*) FROM card_states
|
||||||
|
UNION ALL SELECT 'loan_types', count(*) FROM loan_types
|
||||||
|
UNION ALL SELECT 'loan_order_required_docs', count(*) FROM loan_order_required_docs
|
||||||
|
UNION ALL SELECT 'cards', count(*) FROM cards
|
||||||
|
UNION ALL SELECT 'card_orders', count(*) FROM card_orders
|
||||||
|
UNION ALL SELECT 'card_pin_orders', count(*) FROM card_pin_orders
|
||||||
|
UNION ALL SELECT 'card_rekwizit_orders', count(*) FROM card_rekwizit_orders
|
||||||
|
UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders
|
||||||
|
UNION ALL SELECT 'loans', count(*) FROM loans
|
||||||
|
UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters
|
||||||
|
UNION ALL SELECT 'visa_master_payment_orders', count(*) FROM visa_master_payment_orders
|
||||||
|
UNION ALL SELECT 'visa_master_order_payments', count(*) FROM visa_master_order_payments
|
||||||
|
UNION ALL SELECT 'visa_master_payment_logs', count(*) FROM visa_master_payment_logs
|
||||||
|
UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications
|
||||||
|
UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs
|
||||||
|
UNION ALL SELECT 'backups', count(*) FROM backups
|
||||||
|
UNION ALL SELECT 'currencies', count(*) FROM currencies
|
||||||
|
ORDER BY 1;
|
||||||
|
|
||||||
Executable
+40
@@ -0,0 +1,40 @@
|
|||||||
|
# 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
|
||||||
|
|
||||||
|
VOLUME /storage
|
||||||
|
|
||||||
|
ENV MINIO_VOLUMES="/storage"
|
||||||
|
EXPOSE 9000
|
||||||
|
EXPOSE 9093
|
||||||
|
|
||||||
|
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
|
||||||
Executable
+74
@@ -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
|
||||||
@@ -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=
|
||||||
+49
-18
@@ -1,7 +1,6 @@
|
|||||||
version: '3.4'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
main-db:
|
main-db:
|
||||||
|
# Keep in sync with the runtime stage in Dockerfile: pg_dump must match this major version.
|
||||||
image: postgres:14.1-alpine
|
image: postgres:14.1-alpine
|
||||||
container_name: "main-db"
|
container_name: "main-db"
|
||||||
restart: always
|
restart: always
|
||||||
@@ -13,28 +12,60 @@ services:
|
|||||||
- '5424:5432'
|
- '5424:5432'
|
||||||
volumes:
|
volumes:
|
||||||
- main-db-storage:/var/lib/postgresql/data
|
- 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:
|
networks:
|
||||||
- myNetwork
|
- myNetwork
|
||||||
|
|
||||||
main-server:
|
main-server:
|
||||||
image: main-app
|
image: main-app:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
container_name: "main-app"
|
container_name: "main-app"
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
ports:
|
environment:
|
||||||
- "5050:5050"
|
- TZ=Asia/Ashgabat
|
||||||
volumes:
|
ports:
|
||||||
- ./public:/app/public
|
- "5050:5050"
|
||||||
depends_on:
|
volumes:
|
||||||
- main-db
|
# Inside this network the config must point at main-db:5432 and main-minio:9000.
|
||||||
networks:
|
- ./config.yaml:/app/config.yaml:ro
|
||||||
- myNetwork
|
- ./public:/app/public
|
||||||
|
- ./logs:/app/logs
|
||||||
|
depends_on:
|
||||||
|
main-db:
|
||||||
|
condition: service_healthy
|
||||||
|
main-minio:
|
||||||
|
condition: service_started
|
||||||
|
networks:
|
||||||
|
- myNetwork
|
||||||
|
|
||||||
|
main-minio:
|
||||||
|
image: main-minio:latest
|
||||||
|
container_name: "main-minio"
|
||||||
|
build:
|
||||||
|
context: ./deployment
|
||||||
|
dockerfile: Dockerfile.minio
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
- MINIO_ROOT_USER=TX3H1H6XTS288QW07S8Z
|
||||||
|
- MINIO_ROOT_PASSWORD=FWWspiI4n4LMknnxYCmzFTCY1ObkGiuaU9SNwOCU
|
||||||
|
ports:
|
||||||
|
- '127.0.0.1:9003:9000'
|
||||||
|
- '127.0.0.1:9093:9093'
|
||||||
|
volumes:
|
||||||
|
- main-minio-storage:/storage
|
||||||
|
networks:
|
||||||
|
- myNetwork
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
main-db-storage:
|
main-db-storage:
|
||||||
|
main-minio-storage:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
myNetwork:
|
myNetwork:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
|
|
||||||
+10258
-216
File diff suppressed because it is too large.
Load diff
+10260
-215
File diff suppressed because it is too large.
Load diff
+7325
-249
File diff suppressed because it is too large.
Load diff
@@ -10,10 +10,31 @@ var swaggerTagOrder = []struct {
|
|||||||
{Name: "auth", Description: "Authentication"},
|
{Name: "auth", Description: "Authentication"},
|
||||||
{Name: "province", Description: "Provinces"},
|
{Name: "province", Description: "Provinces"},
|
||||||
{Name: "branches", Description: "Branches"},
|
{Name: "branches", Description: "Branches"},
|
||||||
|
{Name: "branch-users", Description: "Branch users"},
|
||||||
|
{Name: "user", Description: "Users"},
|
||||||
|
{Name: "role", Description: "Roles"},
|
||||||
|
{Name: "permission", Description: "Permissions"},
|
||||||
{Name: "payment-card", Description: "Payment cards"},
|
{Name: "payment-card", Description: "Payment cards"},
|
||||||
{Name: "reason-card", Description: "Reason 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-type", Description: "Loan types"},
|
||||||
{Name: "loan-document", Description: "Loan required documents"},
|
{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() {
|
||||||
|
applySwaggerTagOrder()
|
||||||
}
|
}
|
||||||
|
|
||||||
func applySwaggerTagOrder() {
|
func applySwaggerTagOrder() {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ require (
|
|||||||
github.com/ilyakaznacheev/cleanenv v1.5.0
|
github.com/ilyakaznacheev/cleanenv v1.5.0
|
||||||
github.com/jackc/pgconn v1.14.3
|
github.com/jackc/pgconn v1.14.3
|
||||||
github.com/jackc/pgx/v4 v4.18.3
|
github.com/jackc/pgx/v4 v4.18.3
|
||||||
|
github.com/minio/minio-go/v7 v7.2.1
|
||||||
github.com/sirupsen/logrus v1.9.4
|
github.com/sirupsen/logrus v1.9.4
|
||||||
github.com/swaggo/files v1.0.1
|
github.com/swaggo/files v1.0.1
|
||||||
github.com/swaggo/gin-swagger v1.6.1
|
github.com/swaggo/gin-swagger v1.6.1
|
||||||
@@ -24,7 +25,9 @@ require (
|
|||||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||||
github.com/bytedance/sonic v1.15.0 // indirect
|
github.com/bytedance/sonic v1.15.0 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||||
@@ -36,6 +39,7 @@ require (
|
|||||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||||
github.com/goccy/go-json v0.10.5 // indirect
|
github.com/goccy/go-json v0.10.5 // indirect
|
||||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||||
github.com/jackc/pgio v1.0.0 // indirect
|
github.com/jackc/pgio v1.0.0 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
@@ -46,20 +50,28 @@ require (
|
|||||||
github.com/joho/godotenv v1.5.1 // indirect
|
github.com/joho/godotenv v1.5.1 // indirect
|
||||||
github.com/josharian/intern v1.0.0 // indirect
|
github.com/josharian/intern v1.0.0 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
github.com/klauspost/compress v1.18.6 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
|
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/lib/pq v1.12.3 // indirect
|
github.com/lib/pq v1.12.3 // indirect
|
||||||
github.com/mailru/easyjson v0.7.6 // indirect
|
github.com/mailru/easyjson v0.7.6 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||||
|
github.com/minio/md5-simd v1.1.2 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
|
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
|
||||||
|
github.com/philhofer/fwd v1.2.0 // indirect
|
||||||
github.com/quic-go/qpack v0.6.0 // indirect
|
github.com/quic-go/qpack v0.6.0 // indirect
|
||||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
github.com/rs/xid v1.6.0 // indirect
|
||||||
|
github.com/tinylib/msgp v1.6.1 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||||
|
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||||
golang.org/x/arch v0.23.0 // indirect
|
golang.org/x/arch v0.23.0 // indirect
|
||||||
golang.org/x/mod v0.36.0 // indirect
|
golang.org/x/mod v0.36.0 // indirect
|
||||||
golang.org/x/net v0.56.0 // indirect
|
golang.org/x/net v0.56.0 // indirect
|
||||||
@@ -68,6 +80,7 @@ require (
|
|||||||
golang.org/x/text v0.38.0 // indirect
|
golang.org/x/text v0.38.0 // indirect
|
||||||
golang.org/x/tools v0.45.0 // indirect
|
golang.org/x/tools v0.45.0 // indirect
|
||||||
google.golang.org/protobuf v1.36.10 // indirect
|
google.golang.org/protobuf v1.36.10 // indirect
|
||||||
|
gopkg.in/ini.v1 v1.67.2 // indirect
|
||||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
|
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uS
|
|||||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||||
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
|
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
|
||||||
@@ -26,6 +28,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
|
github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
|
||||||
@@ -69,6 +73,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
|||||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
|
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
|
||||||
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
|
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
|
||||||
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
|
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
|
||||||
@@ -127,8 +133,13 @@ github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFF
|
|||||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
|
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||||
|
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||||
|
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||||
|
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
@@ -158,6 +169,12 @@ github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hd
|
|||||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||||
|
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||||
|
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||||
|
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||||
|
github.com/minio/minio-go/v7 v7.2.1 h1:PfBfwvKB/MmqyN8Vb1G9voWisaM9OrLv+WwOvMwS9Dw=
|
||||||
|
github.com/minio/minio-go/v7 v7.2.1/go.mod h1:EU9hENAStx/xXduNdrGO5e4X5vk19NtgB+RIPjZO8o0=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
@@ -166,6 +183,8 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY
|
|||||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||||
github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=
|
github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=
|
||||||
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||||
|
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
@@ -178,6 +197,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR
|
|||||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||||
|
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||||
|
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||||
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
|
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
|
||||||
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
|
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
|
||||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||||
@@ -212,11 +233,17 @@ github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs
|
|||||||
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||||
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||||
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||||
|
github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=
|
||||||
|
github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||||
|
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||||
|
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||||
|
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||||
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
||||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||||
@@ -233,6 +260,8 @@ go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9E
|
|||||||
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||||
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
|
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
|
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
|
||||||
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
@@ -325,6 +354,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN
|
|||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s=
|
gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s=
|
||||||
|
gopkg.in/ini.v1 v1.67.2 h1:JtOSMb9OuaCZKr7h5D/h6iii14sK0hLbplTc6frx4Ss=
|
||||||
|
gopkg.in/ini.v1 v1.67.2/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
@@ -1,52 +0,0 @@
|
|||||||
package db
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"online-back/internal/admin/auth"
|
|
||||||
"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) auth.Repository {
|
|
||||||
return &repository{
|
|
||||||
client: client,
|
|
||||||
logger: logger,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
loginQuery = `SELECT id, password FROM users WHERE email = $1`
|
|
||||||
userByIDQuery = `SELECT id, password FROM users WHERE id = $1`
|
|
||||||
profileQuery = `SELECT id, fullname, phone_number, avatar, created_at
|
|
||||||
FROM users WHERE id = $1`
|
|
||||||
)
|
|
||||||
|
|
||||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.UserCredentials, error) {
|
|
||||||
var result auth.UserCredentials
|
|
||||||
err := r.client.QueryRow(ctx, loginQuery, dto.Email).Scan(&result.Id, &result.Password)
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) GetUserByID(ctx context.Context, id int) (auth.UserCredentials, error) {
|
|
||||||
var result auth.UserCredentials
|
|
||||||
err := r.client.QueryRow(ctx, userByIDQuery, id).Scan(&result.Id, &result.Password)
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
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.FullName,
|
|
||||||
&profile.PhoneNumber,
|
|
||||||
&profile.Avatar,
|
|
||||||
&profile.CreatedAt,
|
|
||||||
)
|
|
||||||
return profile, err
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type LoginDTO struct {
|
|
||||||
Email string `json:"email" binding:"required"`
|
|
||||||
Password string `json:"password" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type RefreshTokenDTO struct {
|
|
||||||
RefreshToken string `json:"refreshToken" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserProfileDTO struct {
|
|
||||||
Id int `json:"id"`
|
|
||||||
FullName string `json:"fullName"`
|
|
||||||
PhoneNumber string `json:"phoneNumber"`
|
|
||||||
Avatar string `json:"avatar"`
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserCredentials struct {
|
|
||||||
Id int
|
|
||||||
Password string
|
|
||||||
}
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"online-back/internal/appresult"
|
|
||||||
"online-back/internal/handlers"
|
|
||||||
"online-back/pkg/logging"
|
|
||||||
"online-back/pkg/utils"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
loginURL = "/login"
|
|
||||||
tokenURL = "/token"
|
|
||||||
profileURL = "/profile"
|
|
||||||
)
|
|
||||||
|
|
||||||
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) {
|
|
||||||
router.POST(loginURL, h.login)
|
|
||||||
router.POST(tokenURL, h.refreshToken)
|
|
||||||
|
|
||||||
protected := router.Group("", appresult.JwtTokenCheck())
|
|
||||||
protected.GET(profileURL, h.getProfile)
|
|
||||||
}
|
|
||||||
|
|
||||||
// login godoc
|
|
||||||
// @Summary Login
|
|
||||||
// @Description Authenticates a user by email and password
|
|
||||||
// @Tags auth
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body LoginDTO true "Login payload"
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 401 {object} appresult.AppError
|
|
||||||
// @Router /login [post]
|
|
||||||
func (h *handler) login(c *gin.Context) {
|
|
||||||
var dto LoginDTO
|
|
||||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := h.repository.Login(c.Request.Context(), dto)
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Errorf("login lookup failed: %v", err)
|
|
||||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(dto.Password)); err != nil {
|
|
||||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tokenPair, err := utils.GenerateTokenPair(user.Id)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
|
|
||||||
}
|
|
||||||
|
|
||||||
// refreshToken godoc
|
|
||||||
// @Summary Refresh tokens
|
|
||||||
// @Description Issues a new access and refresh token pair
|
|
||||||
// @Tags auth
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body RefreshTokenDTO true "Refresh token payload"
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 401 {object} appresult.AppError
|
|
||||||
// @Router /token [post]
|
|
||||||
func (h *handler) refreshToken(c *gin.Context) {
|
|
||||||
var dto RefreshTokenDTO
|
|
||||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := utils.ParseRefreshToken(dto.RefreshToken)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
id, ok := utils.ClaimID(claims)
|
|
||||||
if !ok {
|
|
||||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := h.repository.GetUserByID(c.Request.Context(), id)
|
|
||||||
if err != nil || user.Id != id {
|
|
||||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tokenPair, err := utils.GenerateTokenPair(id)
|
|
||||||
if err != nil {
|
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData(tokenPair))
|
|
||||||
}
|
|
||||||
|
|
||||||
// getProfile godoc
|
|
||||||
// @Summary Get profile
|
|
||||||
// @Description Returns the authenticated user's profile
|
|
||||||
// @Tags auth
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 401 {object} appresult.AppError
|
|
||||||
// @Failure 404 {object} appresult.AppError
|
|
||||||
// @Router /profile [get]
|
|
||||||
func (h *handler) getProfile(c *gin.Context) {
|
|
||||||
userID, ok := currentUserID(c)
|
|
||||||
if !ok {
|
|
||||||
c.JSON(http.StatusUnauthorized, appresult.ErrUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
profile, err := h.repository.GetProfile(c.Request.Context(), userID)
|
|
||||||
if err != nil {
|
|
||||||
h.logger.Errorf("get profile failed: %v", err)
|
|
||||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData(profile))
|
|
||||||
}
|
|
||||||
|
|
||||||
func currentUserID(c *gin.Context) (int, bool) {
|
|
||||||
rawID, exists := c.Get("id")
|
|
||||||
if !exists {
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch id := rawID.(type) {
|
|
||||||
case int:
|
|
||||||
return id, id > 0
|
|
||||||
case string:
|
|
||||||
parsed, err := strconv.Atoi(id)
|
|
||||||
return parsed, err == nil && parsed > 0
|
|
||||||
default:
|
|
||||||
return 0, false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import "context"
|
|
||||||
|
|
||||||
type Repository interface {
|
|
||||||
Login(ctx context.Context, dto LoginDTO) (UserCredentials, error)
|
|
||||||
GetUserByID(ctx context.Context, id int) (UserCredentials, error)
|
|
||||||
GetProfile(ctx context.Context, id int) (UserProfileDTO, error)
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package branches
|
|
||||||
|
|
||||||
type LocalizedText struct {
|
|
||||||
En string `json:"en"`
|
|
||||||
Ru string `json:"ru"`
|
|
||||||
Tm string `json:"tm"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type BranchDTO struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
UniqueCode string `json:"uniqueCode"`
|
|
||||||
Name LocalizedText `json:"name"`
|
|
||||||
Address LocalizedText `json:"address"`
|
|
||||||
Region string `json:"region"`
|
|
||||||
ProvinceId *int64 `json:"provinceId"`
|
|
||||||
ProvinceName LocalizedText `json:"provinceName"`
|
|
||||||
PhoneNumbers []string `json:"phoneNumbers"`
|
|
||||||
BillingUsername string `json:"billingUsername"`
|
|
||||||
BillingPassword string `json:"billingPassword"`
|
|
||||||
BillingSberUsername string `json:"billingSberUsername"`
|
|
||||||
BillingSberPassword string `json:"billingSberPassword"`
|
|
||||||
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
|
|
||||||
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
|
|
||||||
BillingSwiftUsername string `json:"billingSwiftUsername"`
|
|
||||||
BillingSwiftPassword string `json:"billingSwiftPassword"`
|
|
||||||
Active bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreateBranchDTO struct {
|
|
||||||
UniqueCode string `json:"uniqueCode"`
|
|
||||||
Name LocalizedText `json:"name" binding:"required"`
|
|
||||||
Address LocalizedText `json:"address" binding:"required"`
|
|
||||||
Region string `json:"region" binding:"required"`
|
|
||||||
ProvinceId *int64 `json:"provinceId"`
|
|
||||||
PhoneNumbers []string `json:"phoneNumbers"`
|
|
||||||
BillingUsername string `json:"billingUsername"`
|
|
||||||
BillingPassword string `json:"billingPassword"`
|
|
||||||
BillingSberUsername string `json:"billingSberUsername"`
|
|
||||||
BillingSberPassword string `json:"billingSberPassword"`
|
|
||||||
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
|
|
||||||
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
|
|
||||||
BillingSwiftUsername string `json:"billingSwiftUsername"`
|
|
||||||
BillingSwiftPassword string `json:"billingSwiftPassword"`
|
|
||||||
Active *bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateBranchDTO struct {
|
|
||||||
UniqueCode string `json:"uniqueCode"`
|
|
||||||
Name LocalizedText `json:"name" binding:"required"`
|
|
||||||
Address LocalizedText `json:"address" binding:"required"`
|
|
||||||
Region string `json:"region" binding:"required"`
|
|
||||||
ProvinceId *int64 `json:"provinceId"`
|
|
||||||
PhoneNumbers []string `json:"phoneNumbers"`
|
|
||||||
BillingUsername string `json:"billingUsername"`
|
|
||||||
BillingPassword string `json:"billingPassword"`
|
|
||||||
BillingSberUsername string `json:"billingSberUsername"`
|
|
||||||
BillingSberPassword string `json:"billingSberPassword"`
|
|
||||||
BillingVisaMasterUsername string `json:"billingVisaMasterUsername"`
|
|
||||||
BillingVisaMasterPassword string `json:"billingVisaMasterPassword"`
|
|
||||||
BillingSwiftUsername string `json:"billingSwiftUsername"`
|
|
||||||
BillingSwiftPassword string `json:"billingSwiftPassword"`
|
|
||||||
Active bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListFilter struct {
|
|
||||||
ProvinceID *int64
|
|
||||||
ProvinceName string
|
|
||||||
BranchName string
|
|
||||||
UniqueCode string
|
|
||||||
Page int
|
|
||||||
Limit int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListBranchDTO struct {
|
|
||||||
Count int64 `json:"count"`
|
|
||||||
Branches []BranchDTO `json:"branches"`
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package paymentcard
|
|
||||||
|
|
||||||
type LocalizedText struct {
|
|
||||||
En string `json:"en"`
|
|
||||||
Ru string `json:"ru"`
|
|
||||||
Tm string `json:"tm"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PaymentCardDTO struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Price string `json:"price"`
|
|
||||||
Title 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"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdatePaymentCardDTO struct {
|
|
||||||
Price string `json:"price" binding:"required"`
|
|
||||||
Title LocalizedText `json:"title" binding:"required"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
Active bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdatePaymentCardActiveDTO struct {
|
|
||||||
Active bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListFilter struct {
|
|
||||||
CardName string
|
|
||||||
Active *bool
|
|
||||||
Page int
|
|
||||||
Limit int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListPaymentCardDTO struct {
|
|
||||||
Count int64 `json:"count"`
|
|
||||||
PaymentCards []PaymentCardDTO `json:"paymentCards"`
|
|
||||||
}
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
package db
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"online-back/internal/admin/permission"
|
|
||||||
"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) permission.Repository {
|
|
||||||
return &repository{client: client, 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) {
|
|
||||||
fromClause, whereClause, args := buildListQuery(filter)
|
|
||||||
|
|
||||||
var count int64
|
|
||||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
|
||||||
return permission.ListPermissionDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := (filter.Page - 1) * filter.Limit
|
|
||||||
limitPlaceholder := len(args) + 1
|
|
||||||
offsetPlaceholder := len(args) + 2
|
|
||||||
listQuery := fmt.Sprintf(
|
|
||||||
`SELECT %s%s%s ORDER BY p.id LIMIT $%d OFFSET $%d`,
|
|
||||||
permissionColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
||||||
)
|
|
||||||
|
|
||||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
||||||
if err != nil {
|
|
||||||
return permission.ListPermissionDTO{}, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var items []permission.PermissionDTO
|
|
||||||
for rows.Next() {
|
|
||||||
item, err := scanPermission(rows)
|
|
||||||
if err != nil {
|
|
||||||
return permission.ListPermissionDTO{}, err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return permission.ListPermissionDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return permission.ListPermissionDTO{Count: count, Permissions: items}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildListQuery(filter permission.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
|
||||||
fromClause = ` FROM permissions p`
|
|
||||||
|
|
||||||
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 fromClause, "", args
|
|
||||||
}
|
|
||||||
|
|
||||||
return fromClause, " 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) {
|
|
||||||
query := fmt.Sprintf(`SELECT %s FROM permissions p WHERE p.id = $1`, permissionColumns)
|
|
||||||
item, err := scanPermission(r.client.QueryRow(ctx, query, id))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return permission.PermissionDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
tag, err := r.client.Exec(ctx, `DELETE FROM permissions 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 scanPermission(row scannable) (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,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,129 +0,0 @@
|
|||||||
package db
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"online-back/internal/admin/province"
|
|
||||||
"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) province.Repository {
|
|
||||||
return &repository{client: client, logger: logger}
|
|
||||||
}
|
|
||||||
|
|
||||||
const provinceSelectColumns = `id, name, region, active`
|
|
||||||
|
|
||||||
func (r *repository) List(ctx context.Context) ([]province.ProvinceDTO, error) {
|
|
||||||
rows, err := r.client.Query(ctx, `SELECT `+provinceSelectColumns+` FROM provinces ORDER BY id`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var items []province.ProvinceDTO
|
|
||||||
for rows.Next() {
|
|
||||||
item, err := scanProvince(rows)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
|
|
||||||
return items, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) GetByID(ctx context.Context, id int64) (province.ProvinceDTO, error) {
|
|
||||||
row := r.client.QueryRow(ctx, `SELECT `+provinceSelectColumns+` FROM provinces WHERE id = $1`, id)
|
|
||||||
item, err := scanProvince(row)
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO) (province.ProvinceDTO, error) {
|
|
||||||
name, region, err := marshalProvinceJSON(dto.Name, dto.Region)
|
|
||||||
if err != nil {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
active := true
|
|
||||||
if dto.Active != nil {
|
|
||||||
active = *dto.Active
|
|
||||||
}
|
|
||||||
|
|
||||||
row := r.client.QueryRow(ctx,
|
|
||||||
`INSERT INTO provinces (name, region, active) VALUES ($1, $2, $3) RETURNING `+provinceSelectColumns,
|
|
||||||
name, region, active,
|
|
||||||
)
|
|
||||||
return scanProvince(row)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Update(ctx context.Context, id int64, dto province.UpdateProvinceDTO) (province.ProvinceDTO, error) {
|
|
||||||
name, region, err := marshalProvinceJSON(dto.Name, dto.Region)
|
|
||||||
if err != nil {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
row := r.client.QueryRow(ctx,
|
|
||||||
`UPDATE provinces SET name = $1, region = $2, active = $3 WHERE id = $4 RETURNING `+provinceSelectColumns,
|
|
||||||
name, region, dto.Active, id,
|
|
||||||
)
|
|
||||||
item, err := scanProvince(row)
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
||||||
tag, err := r.client.Exec(ctx, `DELETE FROM provinces WHERE id = $1`, id)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if tag.RowsAffected() == 0 {
|
|
||||||
return pgx.ErrNoRows
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, error) {
|
|
||||||
nameJSON, err := json.Marshal(name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
regionJSON, err := json.Marshal(region)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
return nameJSON, regionJSON, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type scannable interface {
|
|
||||||
Scan(dest ...interface{}) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanProvince(row scannable) (province.ProvinceDTO, error) {
|
|
||||||
var item province.ProvinceDTO
|
|
||||||
var nameJSON, regionJSON []byte
|
|
||||||
if err := row.Scan(&item.Id, &nameJSON, ®ionJSON, &item.Active); err != nil {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(nameJSON, &item.Name); err != nil {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(regionJSON, &item.Region); err != nil {
|
|
||||||
return province.ProvinceDTO{}, err
|
|
||||||
}
|
|
||||||
return item, nil
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package reasonscard
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type LocalizedText struct {
|
|
||||||
En string `json:"en"`
|
|
||||||
Ru string `json:"ru"`
|
|
||||||
Tm string `json:"tm"`
|
|
||||||
}
|
|
||||||
|
|
||||||
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"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreateReasonCardDTO struct {
|
|
||||||
Title 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"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListFilter struct {
|
|
||||||
ReasonName string
|
|
||||||
Page int
|
|
||||||
Limit int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListReasonCardDTO struct {
|
|
||||||
Count int64 `json:"count"`
|
|
||||||
ReasonCards []ReasonCardDTO `json:"reasonCards"`
|
|
||||||
}
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
package db
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"online-back/internal/admin/role"
|
|
||||||
"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) role.Repository {
|
|
||||||
return &repository{client: client, logger: logger}
|
|
||||||
}
|
|
||||||
|
|
||||||
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
|
|
||||||
|
|
||||||
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
|
|
||||||
|
|
||||||
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
|
|
||||||
fromClause, whereClause, args := buildListQuery(filter)
|
|
||||||
|
|
||||||
var count int64
|
|
||||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
|
||||||
return role.ListRoleDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := (filter.Page - 1) * filter.Limit
|
|
||||||
limitPlaceholder := len(args) + 1
|
|
||||||
offsetPlaceholder := len(args) + 2
|
|
||||||
listQuery := fmt.Sprintf(
|
|
||||||
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
|
||||||
roleColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
||||||
)
|
|
||||||
|
|
||||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
||||||
if err != nil {
|
|
||||||
return role.ListRoleDTO{}, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var items []role.RoleDTO
|
|
||||||
for rows.Next() {
|
|
||||||
item, err := scanRole(rows)
|
|
||||||
if err != nil {
|
|
||||||
return role.ListRoleDTO{}, err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return role.ListRoleDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return role.ListRoleDTO{Count: count, Roles: items}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildListQuery(filter role.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
|
||||||
fromClause = ` FROM roles r`
|
|
||||||
|
|
||||||
var conditions []string
|
|
||||||
if filter.RoleName != "" {
|
|
||||||
args = append(args, likePattern(filter.RoleName))
|
|
||||||
n := len(args)
|
|
||||||
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(conditions) == 0 {
|
|
||||||
return fromClause, "", args
|
|
||||||
}
|
|
||||||
|
|
||||||
return fromClause, " 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) (role.RoleDTO, error) {
|
|
||||||
query := fmt.Sprintf(`SELECT %s FROM roles r WHERE r.id = $1`, roleColumns)
|
|
||||||
item, err := scanRole(r.client.QueryRow(ctx, query, id))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return role.RoleDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
|
|
||||||
query := fmt.Sprintf(`
|
|
||||||
INSERT INTO roles (code, name, guard_name)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING %s`, roleReturningColumns)
|
|
||||||
|
|
||||||
return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) {
|
|
||||||
query := fmt.Sprintf(`
|
|
||||||
UPDATE roles SET
|
|
||||||
code = $1, name = $2, guard_name = $3,
|
|
||||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
||||||
WHERE id = $4
|
|
||||||
RETURNING %s`, roleReturningColumns)
|
|
||||||
|
|
||||||
item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return role.RoleDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
||||||
tag, err := r.client.Exec(ctx, `DELETE FROM roles 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 scanRole(row scannable) (role.RoleDTO, error) {
|
|
||||||
var item role.RoleDTO
|
|
||||||
if err := row.Scan(
|
|
||||||
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
|
|
||||||
); err != nil {
|
|
||||||
return role.RoleDTO{}, err
|
|
||||||
}
|
|
||||||
return item, nil
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package role
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type RoleDTO 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 CreateRoleDTO struct {
|
|
||||||
Code string `json:"code" binding:"required"`
|
|
||||||
Name string `json:"name" binding:"required"`
|
|
||||||
GuardName string `json:"guardName" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateRoleDTO struct {
|
|
||||||
Code string `json:"code" binding:"required"`
|
|
||||||
Name string `json:"name" binding:"required"`
|
|
||||||
GuardName string `json:"guardName" binding:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListFilter struct {
|
|
||||||
RoleName string
|
|
||||||
Page int
|
|
||||||
Limit int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListRoleDTO struct {
|
|
||||||
Count int64 `json:"count"`
|
|
||||||
Roles []RoleDTO `json:"roles"`
|
|
||||||
}
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
package db
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"online-back/internal/admin/user"
|
|
||||||
"online-back/pkg/client/postgresql"
|
|
||||||
"online-back/pkg/logging"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v4"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type repository struct {
|
|
||||||
client postgresql.Client
|
|
||||||
logger *logging.Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRepository(client postgresql.Client, logger *logging.Logger) user.Repository {
|
|
||||||
return &repository{client: client, logger: logger}
|
|
||||||
}
|
|
||||||
|
|
||||||
const userColumns = `u.id, u.email, u.fullname, u.username, u.phone_number, u.avatar, u.social_media, u.light_mode, u.role, u.active, u.created_at, u.updated_at`
|
|
||||||
|
|
||||||
const userReturningColumns = `id, email, fullname, username, phone_number, avatar, social_media, light_mode, role, active, created_at, updated_at`
|
|
||||||
|
|
||||||
func (r *repository) List(ctx context.Context, filter user.ListFilter) (user.ListUserDTO, error) {
|
|
||||||
fromClause, whereClause, args := buildListQuery(filter)
|
|
||||||
|
|
||||||
var count int64
|
|
||||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
|
||||||
return user.ListUserDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := (filter.Page - 1) * filter.Limit
|
|
||||||
limitPlaceholder := len(args) + 1
|
|
||||||
offsetPlaceholder := len(args) + 2
|
|
||||||
listQuery := fmt.Sprintf(
|
|
||||||
`SELECT %s%s%s ORDER BY u.id LIMIT $%d OFFSET $%d`,
|
|
||||||
userColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
||||||
)
|
|
||||||
|
|
||||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
||||||
if err != nil {
|
|
||||||
return user.ListUserDTO{}, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var items []user.UserDTO
|
|
||||||
for rows.Next() {
|
|
||||||
item, err := scanUser(rows)
|
|
||||||
if err != nil {
|
|
||||||
return user.ListUserDTO{}, err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return user.ListUserDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return user.ListUserDTO{Count: count, Users: items}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildListQuery(filter user.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
|
||||||
fromClause = ` FROM users u`
|
|
||||||
|
|
||||||
var conditions []string
|
|
||||||
if filter.Username != "" {
|
|
||||||
args = append(args, likePattern(filter.Username))
|
|
||||||
n := len(args)
|
|
||||||
conditions = append(conditions, fmt.Sprintf(`u.username ILIKE $%d`, n))
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(conditions) == 0 {
|
|
||||||
return fromClause, "", args
|
|
||||||
}
|
|
||||||
|
|
||||||
return fromClause, " 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) (user.UserDTO, error) {
|
|
||||||
query := fmt.Sprintf(`SELECT %s FROM users u WHERE u.id = $1`, userColumns)
|
|
||||||
item, err := scanUser(r.client.QueryRow(ctx, query, id))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Create(ctx context.Context, dto user.CreateUserDTO) (user.UserDTO, error) {
|
|
||||||
socialMedia, err := json.Marshal(dto.SocialMedia)
|
|
||||||
if err != nil {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(dto.Password), bcrypt.DefaultCost)
|
|
||||||
if err != nil {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
active := true
|
|
||||||
if dto.Active != nil {
|
|
||||||
active = *dto.Active
|
|
||||||
}
|
|
||||||
|
|
||||||
query := fmt.Sprintf(`
|
|
||||||
INSERT INTO users (email, password, fullname, username, phone_number, avatar, social_media, light_mode, role, active)
|
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
||||||
RETURNING %s`, userReturningColumns)
|
|
||||||
|
|
||||||
return scanUser(r.client.QueryRow(ctx, query,
|
|
||||||
dto.Email, hashedPassword, dto.Fullname, dto.Username, dto.PhoneNumber, dto.Avatar, socialMedia, dto.LightMode, dto.Role, active,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Update(ctx context.Context, id int64, dto user.UpdateUserDTO) (user.UserDTO, error) {
|
|
||||||
socialMedia, err := json.Marshal(dto.SocialMedia)
|
|
||||||
if err != nil {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
query := fmt.Sprintf(`
|
|
||||||
UPDATE users SET
|
|
||||||
email = $1, fullname = $2, username = $3, phone_number = $4, avatar = $5,
|
|
||||||
social_media = $6, light_mode = $7, role = $8, active = $9,
|
|
||||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
|
||||||
WHERE id = $10
|
|
||||||
RETURNING %s`, userReturningColumns)
|
|
||||||
|
|
||||||
item, err := scanUser(r.client.QueryRow(ctx, query,
|
|
||||||
dto.Email, dto.Fullname, dto.Username, dto.PhoneNumber, dto.Avatar, socialMedia, dto.LightMode, dto.Role, dto.Active, id,
|
|
||||||
))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
|
||||||
tag, err := r.client.Exec(ctx, `DELETE FROM users 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 scanUser(row scannable) (user.UserDTO, error) {
|
|
||||||
var item user.UserDTO
|
|
||||||
var socialMedia []byte
|
|
||||||
if err := row.Scan(
|
|
||||||
&item.Id, &item.Email, &item.Fullname, &item.Username, &item.PhoneNumber, &item.Avatar,
|
|
||||||
&socialMedia, &item.LightMode, &item.Role, &item.Active, &item.CreatedAt, &item.UpdatedAt,
|
|
||||||
); err != nil {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(socialMedia, &item.SocialMedia); err != nil {
|
|
||||||
return user.UserDTO{}, err
|
|
||||||
}
|
|
||||||
return item, nil
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type SocialMedia struct {
|
|
||||||
Facebook string `json:"facebook"`
|
|
||||||
Instagram string `json:"instagram"`
|
|
||||||
Telegram string `json:"telegram"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserDTO struct {
|
|
||||||
Id int64 `json:"id"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Fullname string `json:"fullname"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
PhoneNumber string `json:"phoneNumber"`
|
|
||||||
Avatar string `json:"avatar"`
|
|
||||||
SocialMedia SocialMedia `json:"socialMedia"`
|
|
||||||
LightMode int `json:"lightMode"`
|
|
||||||
Role string `json:"role"`
|
|
||||||
Active bool `json:"active"`
|
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
|
||||||
UpdatedAt time.Time `json:"updatedAt"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type CreateUserDTO struct {
|
|
||||||
Email string `json:"email" binding:"required"`
|
|
||||||
Password string `json:"password" binding:"required"`
|
|
||||||
Fullname string `json:"fullname" binding:"required"`
|
|
||||||
Username string `json:"username" binding:"required"`
|
|
||||||
PhoneNumber string `json:"phoneNumber"`
|
|
||||||
Avatar string `json:"avatar"`
|
|
||||||
SocialMedia SocialMedia `json:"socialMedia"`
|
|
||||||
LightMode int `json:"lightMode"`
|
|
||||||
Role string `json:"role"`
|
|
||||||
Active *bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UpdateUserDTO struct {
|
|
||||||
Email string `json:"email" binding:"required"`
|
|
||||||
Fullname string `json:"fullname" binding:"required"`
|
|
||||||
Username string `json:"username" binding:"required"`
|
|
||||||
PhoneNumber string `json:"phoneNumber"`
|
|
||||||
Avatar string `json:"avatar"`
|
|
||||||
SocialMedia SocialMedia `json:"socialMedia"`
|
|
||||||
LightMode int `json:"lightMode"`
|
|
||||||
Role string `json:"role"`
|
|
||||||
Active bool `json:"active"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListFilter struct {
|
|
||||||
Username string
|
|
||||||
Page int
|
|
||||||
Limit int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ListUserDTO struct {
|
|
||||||
Count int64 `json:"count"`
|
|
||||||
Users []UserDTO `json:"users"`
|
|
||||||
}
|
|
||||||
@@ -1,242 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
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 = "/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.GET("/:id", h.getByID)
|
|
||||||
group.POST("", h.create)
|
|
||||||
group.PUT("/:id", h.update)
|
|
||||||
group.DELETE("/:id", h.delete)
|
|
||||||
}
|
|
||||||
|
|
||||||
// list godoc
|
|
||||||
// @Summary List users
|
|
||||||
// @Description Returns paginated users with optional filters
|
|
||||||
// @Tags user
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param username query string false "Filter by username"
|
|
||||||
// @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 /users [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 users failed: %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
|
||||||
}
|
|
||||||
|
|
||||||
// getByID godoc
|
|
||||||
// @Summary Get user by ID
|
|
||||||
// @Description Returns a single user
|
|
||||||
// @Tags user
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param id path int true "User ID"
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 404 {object} appresult.AppError
|
|
||||||
// @Failure 500 {object} appresult.AppError
|
|
||||||
// @Router /users/{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 user failed: %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
|
||||||
}
|
|
||||||
|
|
||||||
// create godoc
|
|
||||||
// @Summary Create user
|
|
||||||
// @Description Creates a new user
|
|
||||||
// @Tags user
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param body body CreateUserDTO true "User payload"
|
|
||||||
// @Success 201 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 500 {object} appresult.AppError
|
|
||||||
// @Router /users [post]
|
|
||||||
func (h *handler) create(c *gin.Context) {
|
|
||||||
var dto CreateUserDTO
|
|
||||||
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 user failed: %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
|
||||||
}
|
|
||||||
|
|
||||||
// update godoc
|
|
||||||
// @Summary Update user
|
|
||||||
// @Description Updates an existing user
|
|
||||||
// @Tags user
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param id path int true "User ID"
|
|
||||||
// @Param body body UpdateUserDTO true "User payload"
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 404 {object} appresult.AppError
|
|
||||||
// @Failure 500 {object} appresult.AppError
|
|
||||||
// @Router /users/{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 UpdateUserDTO
|
|
||||||
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 user failed: %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
|
||||||
}
|
|
||||||
|
|
||||||
// delete godoc
|
|
||||||
// @Summary Delete user
|
|
||||||
// @Description Deletes a user
|
|
||||||
// @Tags user
|
|
||||||
// @Produce json
|
|
||||||
// @Security BearerAuth
|
|
||||||
// @Param id path int true "User ID"
|
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
|
||||||
// @Failure 400 {object} appresult.AppError
|
|
||||||
// @Failure 404 {object} appresult.AppError
|
|
||||||
// @Failure 500 {object} appresult.AppError
|
|
||||||
// @Router /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 user failed: %v", err)
|
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData("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
|
|
||||||
}
|
|
||||||
|
|
||||||
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("username")); raw != "" {
|
|
||||||
filter.Username = raw
|
|
||||||
}
|
|
||||||
|
|
||||||
return filter, true
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import "context"
|
|
||||||
|
|
||||||
type Repository interface {
|
|
||||||
List(ctx context.Context, filter ListFilter) (ListUserDTO, error)
|
|
||||||
GetByID(ctx context.Context, id int64) (UserDTO, error)
|
|
||||||
Create(ctx context.Context, dto CreateUserDTO) (UserDTO, error)
|
|
||||||
Update(ctx context.Context, id int64, dto UpdateUserDTO) (UserDTO, error)
|
|
||||||
Delete(ctx context.Context, id int64) error
|
|
||||||
}
|
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -3,11 +3,20 @@ package appresult
|
|||||||
import "encoding/json"
|
import "encoding/json"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrMissingParam = NewAppError(nil, "Required parameter is missing or invalid.", "SE-00001")
|
ErrMissingParam = NewAppError(nil, "Required parameter is missing or invalid.", "SE-00001")
|
||||||
ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002")
|
ErrUnauthorized = NewAppError(nil, "Invalid credentials or unauthorized access.", "SE-00002")
|
||||||
ErrNotFound = NewAppError(nil, "The requested resource was not found.", "SE-00003")
|
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")
|
ErrInternalServer = NewAppError(nil, "An internal server error occurred. Please try again later.", "SE-00004")
|
||||||
ErrNotAcceptable = NewAppError(nil, "The request could not be processed.", "SE-00007")
|
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 {
|
type AppError struct {
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package appresult
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultLang is the language localized fields collapse to when the caller
|
||||||
|
// passes no ?lang=.
|
||||||
|
const DefaultLang = "tm"
|
||||||
|
|
||||||
|
// LangAll keeps every localized field as its full {en, ru, tm} object - what
|
||||||
|
// admin edit forms need to fill all three inputs.
|
||||||
|
const LangAll = "all"
|
||||||
|
|
||||||
|
// langFallback is the order empty translations are filled from.
|
||||||
|
var langFallback = []string{"tm", "ru", "en"}
|
||||||
|
|
||||||
|
// Localize collapses every {"en", "ru", "tm"} object (shared.LocalizedText)
|
||||||
|
// in a JSON response into the plain string for ?lang= (tm, ru or en;
|
||||||
|
// default tm), so clients only download the language they show. ?lang=all
|
||||||
|
// leaves responses untouched. It rewrites the encoded body rather than the
|
||||||
|
// DTOs, so every module gets it without knowing about it; non-JSON
|
||||||
|
// responses (files, images) are streamed through as-is.
|
||||||
|
func Localize() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
lang := strings.ToLower(strings.TrimSpace(c.Query("lang")))
|
||||||
|
switch lang {
|
||||||
|
case "":
|
||||||
|
lang = DefaultLang
|
||||||
|
case "tm", "ru", "en":
|
||||||
|
case LangAll:
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
c.AbortWithStatusJSON(http.StatusBadRequest, ErrMissingParam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w := &localizeWriter{ResponseWriter: c.Writer}
|
||||||
|
c.Writer = w
|
||||||
|
c.Next()
|
||||||
|
c.Writer = w.ResponseWriter
|
||||||
|
w.flush(lang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// localizeWriter buffers JSON bodies until the handler is done, so they can
|
||||||
|
// be rewritten as a whole; anything else goes straight to the client.
|
||||||
|
type localizeWriter struct {
|
||||||
|
gin.ResponseWriter
|
||||||
|
decided bool
|
||||||
|
buffer bool
|
||||||
|
body bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *localizeWriter) Write(data []byte) (int, error) {
|
||||||
|
if !w.decided {
|
||||||
|
w.decided = true
|
||||||
|
w.buffer = strings.HasPrefix(w.Header().Get("Content-Type"), "application/json")
|
||||||
|
}
|
||||||
|
if !w.buffer {
|
||||||
|
return w.ResponseWriter.Write(data)
|
||||||
|
}
|
||||||
|
return w.body.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *localizeWriter) WriteString(s string) (int, error) {
|
||||||
|
return w.Write([]byte(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *localizeWriter) flush(lang string) {
|
||||||
|
if w.body.Len() == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := localizeJSON(w.body.Bytes(), lang)
|
||||||
|
if err != nil {
|
||||||
|
out = w.body.Bytes()
|
||||||
|
}
|
||||||
|
w.ResponseWriter.Write(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// localizeJSON re-encodes data token by token - keeping key order and
|
||||||
|
// number precision - with localized objects replaced by their lang string.
|
||||||
|
func localizeJSON(data []byte, lang string) ([]byte, error) {
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(data))
|
||||||
|
dec.UseNumber()
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := localizeValue(dec, &out, lang); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func localizeValue(dec *json.Decoder, out *bytes.Buffer, lang string) error {
|
||||||
|
tok, err := dec.Token()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch t := tok.(type) {
|
||||||
|
case json.Delim:
|
||||||
|
if t == '[' {
|
||||||
|
return localizeArray(dec, out, lang)
|
||||||
|
}
|
||||||
|
return localizeObject(dec, out, lang)
|
||||||
|
case string:
|
||||||
|
return writeString(out, t)
|
||||||
|
case json.Number:
|
||||||
|
out.WriteString(t.String())
|
||||||
|
case bool:
|
||||||
|
if t {
|
||||||
|
out.WriteString("true")
|
||||||
|
} else {
|
||||||
|
out.WriteString("false")
|
||||||
|
}
|
||||||
|
case nil:
|
||||||
|
out.WriteString("null")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func localizeArray(dec *json.Decoder, out *bytes.Buffer, lang string) error {
|
||||||
|
out.WriteByte('[')
|
||||||
|
for i := 0; dec.More(); i++ {
|
||||||
|
if i > 0 {
|
||||||
|
out.WriteByte(',')
|
||||||
|
}
|
||||||
|
if err := localizeValue(dec, out, lang); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := dec.Token(); err != nil { // ']'
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteByte(']')
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type jsonField struct {
|
||||||
|
key string
|
||||||
|
value []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func localizeObject(dec *json.Decoder, out *bytes.Buffer, lang string) error {
|
||||||
|
var fields []jsonField
|
||||||
|
for dec.More() {
|
||||||
|
keyTok, err := dec.Token()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var value bytes.Buffer
|
||||||
|
if err := localizeValue(dec, &value, lang); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fields = append(fields, jsonField{key: keyTok.(string), value: value.Bytes()})
|
||||||
|
}
|
||||||
|
if _, err := dec.Token(); err != nil { // '}'
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if text, ok := pickLocalized(fields, lang); ok {
|
||||||
|
return writeString(out, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
out.WriteByte('{')
|
||||||
|
for i, f := range fields {
|
||||||
|
if i > 0 {
|
||||||
|
out.WriteByte(',')
|
||||||
|
}
|
||||||
|
if err := writeString(out, f.key); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteByte(':')
|
||||||
|
out.Write(f.value)
|
||||||
|
}
|
||||||
|
out.WriteByte('}')
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pickLocalized reports whether fields is exactly a {en, ru, tm} object of
|
||||||
|
// strings/nulls and, if so, returns lang's text - falling back through
|
||||||
|
// langFallback when it's empty.
|
||||||
|
func pickLocalized(fields []jsonField, lang string) (string, bool) {
|
||||||
|
if len(fields) != 3 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
texts := make(map[string]string, 3)
|
||||||
|
for _, f := range fields {
|
||||||
|
if f.key != "en" && f.key != "ru" && f.key != "tm" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
if _, dup := texts[f.key]; dup {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
var text *string
|
||||||
|
if err := json.Unmarshal(f.value, &text); err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
texts[f.key] = ""
|
||||||
|
if text != nil {
|
||||||
|
texts[f.key] = *text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if text := texts[lang]; text != "" {
|
||||||
|
return text, true
|
||||||
|
}
|
||||||
|
for _, l := range langFallback {
|
||||||
|
if text := texts[l]; text != "" {
|
||||||
|
return text, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeString encodes s the way gin's c.JSON does (json.Marshal, HTML
|
||||||
|
// escaped), so rewritten bodies match untouched ones byte for byte.
|
||||||
|
func writeString(out *bytes.Buffer, s string) error {
|
||||||
|
encoded, err := json.Marshal(s)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.Write(encoded)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package appresult
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func serve(t *testing.T, query string, handler gin.HandlerFunc) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
router := gin.New()
|
||||||
|
router.Use(Localize())
|
||||||
|
router.GET("/x", handler)
|
||||||
|
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/x"+query, nil))
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonHandler(body string) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
c.Data(http.StatusOK, "application/json; charset=utf-8", []byte(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const branchBody = `{"id":1,"name":{"en":"Branch","ru":"Филиал","tm":"Şahamça"}}`
|
||||||
|
|
||||||
|
func TestLocalizeLanguages(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
query string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"", `{"id":1,"name":"Şahamça"}`},
|
||||||
|
{"?lang=tm", `{"id":1,"name":"Şahamça"}`},
|
||||||
|
{"?lang=ru", `{"id":1,"name":"Филиал"}`},
|
||||||
|
{"?lang=EN", `{"id":1,"name":"Branch"}`},
|
||||||
|
{"?lang=all", branchBody},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
rec := serve(t, tt.query, jsonHandler(branchBody))
|
||||||
|
if rec.Code != http.StatusOK || rec.Body.String() != tt.want {
|
||||||
|
t.Errorf("%q: got %d %s, want %s", tt.query, rec.Code, rec.Body.String(), tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalizeRejectsUnknownLang(t *testing.T) {
|
||||||
|
called := false
|
||||||
|
rec := serve(t, "?lang=xx", func(c *gin.Context) { called = true })
|
||||||
|
if rec.Code != http.StatusBadRequest || called {
|
||||||
|
t.Fatalf("got %d (handler called: %v), want 400 without calling the handler", rec.Code, called)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalizeFallback(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
body string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{`{"tm":"","ru":"Филиал","en":"Branch"}`, `"Филиал"`},
|
||||||
|
{`{"tm":null,"ru":"","en":"Branch"}`, `"Branch"`},
|
||||||
|
{`{"tm":"","ru":"","en":""}`, `""`},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := serve(t, "", jsonHandler(tt.body)).Body.String(); got != tt.want {
|
||||||
|
t.Errorf("%s: got %s, want %s", tt.body, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalizeKeepsStructure(t *testing.T) {
|
||||||
|
body := `{"z":9007199254740993,"a":[{"b":{"en":"E","ru":"R","tm":"T"},"f":1.10}],` +
|
||||||
|
`"extra":{"en":"E","ru":"R","tm":"T","id":2},"partial":{"en":"E","ru":"R"},` +
|
||||||
|
`"nested":{"en":{"x":1},"ru":"R","tm":"T"},"ok":true,"none":null,"html":"<a&b>"}`
|
||||||
|
want := `{"z":9007199254740993,"a":[{"b":"T","f":1.10}],` +
|
||||||
|
`"extra":{"en":"E","ru":"R","tm":"T","id":2},"partial":{"en":"E","ru":"R"},` +
|
||||||
|
`"nested":{"en":{"x":1},"ru":"R","tm":"T"},"ok":true,"none":null,"html":` + "\"\\u003ca\\u0026b\\u003e\"}"
|
||||||
|
if got := serve(t, "", jsonHandler(body)).Body.String(); got != want {
|
||||||
|
t.Fatalf("got %s\nwant %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalizeMatchesGinJSON(t *testing.T) {
|
||||||
|
rec := serve(t, "?lang=ru", func(c *gin.Context) {
|
||||||
|
c.JSON(http.StatusCreated, SuccessWithData(map[string]interface{}{
|
||||||
|
"name": map[string]string{"en": "Branch", "ru": "Филиал", "tm": "Şahamça"},
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
want := `{"status":true,"message":"Request completed successfully.","code":"SS-10000","data":{"name":"Филиал"}}`
|
||||||
|
if rec.Code != http.StatusCreated || rec.Body.String() != want {
|
||||||
|
t.Fatalf("got %d %s, want 201 %s", rec.Code, rec.Body.String(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLocalizeSkipsNonJSON(t *testing.T) {
|
||||||
|
body := `{"en":"E","ru":"R","tm":"T"}`
|
||||||
|
rec := serve(t, "", func(c *gin.Context) {
|
||||||
|
c.Data(http.StatusOK, "text/plain", []byte(body))
|
||||||
|
})
|
||||||
|
if rec.Body.String() != body {
|
||||||
|
t.Fatalf("got %s, want body untouched", rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
type repository struct {
|
||||||
|
client postgresql.Client
|
||||||
|
generic *genericrepo.Repository[cardorder.CardOrderDTO]
|
||||||
|
logger *logging.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(client postgresql.Client, logger *logging.Logger) cardorder.Repository {
|
||||||
|
return &repository{
|
||||||
|
client: client,
|
||||||
|
generic: genericrepo.New(client, "card_orders", cardOrderColumnsSQL, scanCardOrder),
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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",
|
||||||
|
"passport_serie", "passport_id", "passport_given_at", "passport_given_by", "born_place",
|
||||||
|
"job_location", "passport_address", "real_address", "phone", "phone_additional",
|
||||||
|
"status", "passport_one", "passport_two", "passport_three", "passport_four", "notes", "user_id", "paid",
|
||||||
|
}
|
||||||
|
|
||||||
|
var cardOrderColumns = append(append([]string{"id"}, cardOrderWritableColumns...), "created_at", "updated_at")
|
||||||
|
|
||||||
|
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"
|
||||||
|
return &pending
|
||||||
|
}
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolvePaid(paid *bool) bool {
|
||||||
|
if paid == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return *paid
|
||||||
|
}
|
||||||
|
|
||||||
|
func createArgs(dto cardorder.CreateCardOrderDTO) []interface{} {
|
||||||
|
return []interface{}{
|
||||||
|
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, shared.OptionalInt64(dto.UserId), resolvePaid(dto.Paid),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateArgs(dto cardorder.UpdateCardOrderDTO) []interface{} {
|
||||||
|
return []interface{}{
|
||||||
|
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, shared.OptionalInt64(dto.UserId), dto.Paid,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) List(ctx context.Context, filter cardorder.ListFilter) (cardorder.ListCardOrderDTO, error) {
|
||||||
|
whereClause, args := buildListQuery(filter)
|
||||||
|
|
||||||
|
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{}) {
|
||||||
|
conditions := []string{"co.deleted_at IS NULL"}
|
||||||
|
|
||||||
|
if filter.Status != nil {
|
||||||
|
args = append(args, *filter.Status)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("co.status = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
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("co.branch_id = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if filter.UserId != nil {
|
||||||
|
args = append(args, *filter.UserId)
|
||||||
|
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("co.card_state_id = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if filter.CardTypeId != nil {
|
||||||
|
args = append(args, *filter.CardTypeId)
|
||||||
|
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("co.region = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) GetByID(ctx context.Context, id int64) (cardorder.CardOrderDTO, error) {
|
||||||
|
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) {
|
||||||
|
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_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 scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Update(ctx context.Context, id int64, dto cardorder.UpdateCardOrderDTO) (cardorder.CardOrderDTO, error) {
|
||||||
|
args := updateArgs(dto)
|
||||||
|
|
||||||
|
assignments := make([]string, len(cardOrderWritableColumns))
|
||||||
|
for i, column := range cardOrderWritableColumns {
|
||||||
|
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||||
|
}
|
||||||
|
args = append(args, id)
|
||||||
|
|
||||||
|
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 := scanCardOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||||
|
if err != nil {
|
||||||
|
return cardorder.CardOrderDTO{}, err
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||||
|
return r.generic.Delete(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package cardorder
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"online-back/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CardOrderDTO struct {
|
||||||
|
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 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 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
|
||||||
|
Region string
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
package cardorder
|
||||||
|
|
||||||
|
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-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 orders
|
||||||
|
// @Description Returns paginated card orders with optional filters
|
||||||
|
// @Tags card-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_state_id query int false "Filter by card state 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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-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 orders failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
// getByID godoc
|
||||||
|
// @Summary Get card order by ID
|
||||||
|
// @Description Returns a single card order
|
||||||
|
// @Tags card-orders
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Card order ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-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 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 order
|
||||||
|
// @Description Creates a new card order
|
||||||
|
// @Tags card-orders
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param body body CreateCardOrderDTO true "Card order payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 201 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-orders [post]
|
||||||
|
func (h *handler) create(c *gin.Context) {
|
||||||
|
var dto CreateCardOrderDTO
|
||||||
|
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||||
|
h.logger.Errorf("create card order bind failed: %v", err)
|
||||||
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Errorf("create card order failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
// update godoc
|
||||||
|
// @Summary Update card order
|
||||||
|
// @Description Updates an existing card order
|
||||||
|
// @Tags card-orders
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Card order ID"
|
||||||
|
// @Param body body UpdateCardOrderDTO true "Card order payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-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 UpdateCardOrderDTO
|
||||||
|
if err := c.ShouldBindBodyWithJSON(&dto); err != nil {
|
||||||
|
h.logger.Errorf("update card order bind failed: %v", err)
|
||||||
|
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 order failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete godoc
|
||||||
|
// @Summary Delete card order
|
||||||
|
// @Description Deletes a card order
|
||||||
|
// @Tags card-orders
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Card order ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-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 order failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData("card 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_state_id", "cardStateId"); !ok {
|
||||||
|
return ListFilter{}, false
|
||||||
|
} else if id != nil {
|
||||||
|
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 := 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package cardorder
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type Repository interface {
|
||||||
|
List(ctx context.Context, filter ListFilter) (ListCardOrderDTO, error)
|
||||||
|
GetByID(ctx context.Context, id int64) (CardOrderDTO, error)
|
||||||
|
Create(ctx context.Context, dto CreateCardOrderDTO) (CardOrderDTO, error)
|
||||||
|
Update(ctx context.Context, id int64, dto UpdateCardOrderDTO) (CardOrderDTO, error)
|
||||||
|
Delete(ctx context.Context, id int64) error
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
type repository struct {
|
||||||
|
client postgresql.Client
|
||||||
|
generic *genericrepo.Repository[cardpinorders.CardPinOrderDTO]
|
||||||
|
logger *logging.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(client postgresql.Client, logger *logging.Logger) cardpinorders.Repository {
|
||||||
|
return &repository{
|
||||||
|
client: client,
|
||||||
|
generic: genericrepo.New(client, "card_pin_orders", cardPinOrderColumnsSQL, scanCardPinOrder),
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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",
|
||||||
|
"passport_serie", "passport_id", "passport_one", "passport_two", "passport_three", "passport_four",
|
||||||
|
"status", "notes",
|
||||||
|
}
|
||||||
|
|
||||||
|
var cardPinOrderColumns = append(append([]string{"id"}, cardPinOrderWritableColumns...), "created_at", "updated_at")
|
||||||
|
|
||||||
|
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, 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateArgs(dto cardpinorders.UpdateCardPinOrderDTO) []interface{} {
|
||||||
|
return []interface{}{
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) List(ctx context.Context, filter cardpinorders.ListFilter) (cardpinorders.ListCardPinOrderDTO, error) {
|
||||||
|
whereClause, args := buildListQuery(filter)
|
||||||
|
|
||||||
|
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{}) {
|
||||||
|
conditions := []string{"cpo.deleted_at IS NULL"}
|
||||||
|
|
||||||
|
if filter.Status != nil {
|
||||||
|
args = append(args, *filter.Status)
|
||||||
|
conditions = append(conditions, fmt.Sprintf("cpo.status = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
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("cpo.branch_id = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if filter.UserId != nil {
|
||||||
|
args = append(args, *filter.UserId)
|
||||||
|
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("cpo.card_type_id = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if filter.Region != "" {
|
||||||
|
args = append(args, filter.Region)
|
||||||
|
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) {
|
||||||
|
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) {
|
||||||
|
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_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 scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Update(ctx context.Context, id int64, dto cardpinorders.UpdateCardPinOrderDTO) (cardpinorders.CardPinOrderDTO, error) {
|
||||||
|
args := updateArgs(dto)
|
||||||
|
|
||||||
|
assignments := make([]string, len(cardPinOrderWritableColumns))
|
||||||
|
for i, column := range cardPinOrderWritableColumns {
|
||||||
|
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||||
|
}
|
||||||
|
args = append(args, id)
|
||||||
|
|
||||||
|
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 := scanCardPinOrderWithJoins(r.client.QueryRow(ctx, query, args...))
|
||||||
|
if err != nil {
|
||||||
|
return cardpinorders.CardPinOrderDTO{}, err
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||||
|
return r.generic.Delete(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
package cardpinorders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"online-back/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CardPinOrderDTO 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"`
|
||||||
|
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 *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 *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
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
package cardpinorders
|
||||||
|
|
||||||
|
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-pin-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 pin orders
|
||||||
|
// @Description Returns paginated card pin orders with optional filters
|
||||||
|
// @Tags card-pin-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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-pin-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 pin orders failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
// getByID godoc
|
||||||
|
// @Summary Get card pin order by ID
|
||||||
|
// @Description Returns a single card pin order
|
||||||
|
// @Tags card-pin-orders
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Card pin order ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-pin-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 pin 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 pin order
|
||||||
|
// @Description Creates a new card pin order
|
||||||
|
// @Tags card-pin-orders
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param body body CreateCardPinOrderDTO true "Card pin order payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 201 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-pin-orders [post]
|
||||||
|
func (h *handler) create(c *gin.Context) {
|
||||||
|
var dto CreateCardPinOrderDTO
|
||||||
|
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 pin order failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
// update godoc
|
||||||
|
// @Summary Update card pin order
|
||||||
|
// @Description Updates an existing card pin order
|
||||||
|
// @Tags card-pin-orders
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Card pin order ID"
|
||||||
|
// @Param body body UpdateCardPinOrderDTO true "Card pin order payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-pin-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 UpdateCardPinOrderDTO
|
||||||
|
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 pin order failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete godoc
|
||||||
|
// @Summary Delete card pin order
|
||||||
|
// @Description Deletes a card pin order
|
||||||
|
// @Tags card-pin-orders
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Card pin order ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /card-pin-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 pin order failed: %v", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData("card pin 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package cardpinorders
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type Repository interface {
|
||||||
|
List(ctx context.Context, filter ListFilter) (ListCardPinOrderDTO, error)
|
||||||
|
GetByID(ctx context.Context, id int64) (CardPinOrderDTO, error)
|
||||||
|
Create(ctx context.Context, dto CreateCardPinOrderDTO) (CardPinOrderDTO, error)
|
||||||
|
Update(ctx context.Context, id int64, dto UpdateCardPinOrderDTO) (CardPinOrderDTO, error)
|
||||||
|
Delete(ctx context.Context, id int64) error
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
type repository struct {
|
||||||
|
client postgresql.Client
|
||||||
|
generic *genericrepo.Repository[cards.CardDTO]
|
||||||
|
logger *logging.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(client postgresql.Client, logger *logging.Logger) cards.Repository {
|
||||||
|
return &repository{
|
||||||
|
client: client,
|
||||||
|
generic: genericrepo.New(client, "cards", cardColumnsSQL, scanCard),
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// cardWritableColumns lists every cards column except id, created_at and
|
||||||
|
// updated_at, in the exact order CreateCardDTO/UpdateCardDTO fields are read.
|
||||||
|
var cardWritableColumns = []string{
|
||||||
|
"user_id", "number", "name", "month", "year", "type",
|
||||||
|
}
|
||||||
|
|
||||||
|
var cardColumns = append(append([]string{"id"}, cardWritableColumns...), "created_at", "updated_at")
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateArgs(dto cards.UpdateCardDTO) []interface{} {
|
||||||
|
return []interface{}{
|
||||||
|
dto.UserId, dto.Number, dto.Name, dto.Month, dto.Year, dto.Type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) List(ctx context.Context, filter cards.ListFilter) (cards.ListCardDTO, error) {
|
||||||
|
whereClause, args := buildListQuery(filter)
|
||||||
|
|
||||||
|
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{}) {
|
||||||
|
conditions := []string{"c.deleted_at IS NULL"}
|
||||||
|
|
||||||
|
if filter.UserId != nil {
|
||||||
|
args = append(args, *filter.UserId)
|
||||||
|
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("c.type = $%d", len(args)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) GetByID(ctx context.Context, id int64) (cards.CardDTO, error) {
|
||||||
|
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) {
|
||||||
|
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 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 scanCardWithUser(r.client.QueryRow(ctx, query, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Update(ctx context.Context, id int64, dto cards.UpdateCardDTO) (cards.CardDTO, error) {
|
||||||
|
args := updateArgs(dto)
|
||||||
|
|
||||||
|
assignments := make([]string, len(cardWritableColumns))
|
||||||
|
for i, column := range cardWritableColumns {
|
||||||
|
assignments[i] = fmt.Sprintf("%s = $%d", column, i+1)
|
||||||
|
}
|
||||||
|
args = append(args, id)
|
||||||
|
|
||||||
|
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 := scanCardWithUser(r.client.QueryRow(ctx, query, args...))
|
||||||
|
if err != nil {
|
||||||
|
return cards.CardDTO{}, err
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||||
|
return r.generic.Delete(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
dest := []interface{}{
|
||||||
|
&item.Id, &item.UserId, &item.Number, &item.Name, &item.Month, &item.Year, &item.Type,
|
||||||
|
&item.CreatedAt, &item.UpdatedAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package cards
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"online-back/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CardDTO struct {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
UserId *int64 `json:"-"`
|
||||||
|
User *shared.UserInfo `json:"user,omitempty"`
|
||||||
|
Number string `json:"number"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Month string `json:"month"`
|
||||||
|
Year *string `json:"year"`
|
||||||
|
Type *string `json:"-"`
|
||||||
|
CardType *shared.NamedInfo `json:"cardType,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateCardDTO struct {
|
||||||
|
UserId *int64 `json:"userId"`
|
||||||
|
Number string `json:"number" binding:"required"`
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
Month string `json:"month" binding:"required"`
|
||||||
|
Year *string `json:"year"`
|
||||||
|
Type *string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateCardDTO struct {
|
||||||
|
UserId *int64 `json:"userId"`
|
||||||
|
Number string `json:"number" binding:"required"`
|
||||||
|
Name string `json:"name" binding:"required"`
|
||||||
|
Month string `json:"month" binding:"required"`
|
||||||
|
Year *string `json:"year"`
|
||||||
|
Type *string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListFilter struct {
|
||||||
|
UserId *int64
|
||||||
|
BranchIds []int64
|
||||||
|
Type *string
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListCardDTO struct {
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
Cards []CardDTO `json:"cards"`
|
||||||
|
}
|
||||||
@@ -1,20 +1,21 @@
|
|||||||
package permission
|
package cards
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"online-back/internal/appresult"
|
"online-back/internal/appresult"
|
||||||
"online-back/internal/handlers"
|
"online-back/internal/handlers"
|
||||||
|
"online-back/internal/identity/rbac"
|
||||||
|
"online-back/internal/identity/rbac/perm"
|
||||||
|
"online-back/internal/shared"
|
||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/jackc/pgx/v4"
|
"github.com/jackc/pgx/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
const baseURL = "/permissions"
|
const baseURL = "/cards"
|
||||||
|
|
||||||
type handler struct {
|
type handler struct {
|
||||||
logger *logging.Logger
|
logger *logging.Logger
|
||||||
@@ -26,7 +27,7 @@ func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *handler) Register(router *gin.RouterGroup) {
|
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("", h.list)
|
||||||
group.GET("/:id", h.getByID)
|
group.GET("/:id", h.getByID)
|
||||||
group.POST("", h.create)
|
group.POST("", h.create)
|
||||||
@@ -35,18 +36,20 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// list godoc
|
// list godoc
|
||||||
// @Summary List permissions
|
// @Summary List cards
|
||||||
// @Description Returns paginated permissions with optional filters
|
// @Description Returns paginated cards with optional filters
|
||||||
// @Tags permission
|
// @Tags cards
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param permission_name query string false "Filter by name"
|
// @Param user_id query int false "Filter by user ID"
|
||||||
|
// @Param type query string false "Filter by card type"
|
||||||
// @Param page query int false "Page number" default(1)
|
// @Param page query int false "Page number" default(1)
|
||||||
// @Param limit query int false "Items per page" default(10)
|
// @Param limit query int false "Items per page" default(10)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /permissions [get]
|
// @Router /cards [get]
|
||||||
func (h *handler) list(c *gin.Context) {
|
func (h *handler) list(c *gin.Context) {
|
||||||
filter, ok := parseListFilter(c)
|
filter, ok := parseListFilter(c)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -56,7 +59,7 @@ func (h *handler) list(c *gin.Context) {
|
|||||||
|
|
||||||
result, err := h.repository.List(c.Request.Context(), filter)
|
result, err := h.repository.List(c.Request.Context(), filter)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Errorf("list permissions failed: %v", err)
|
h.logger.Errorf("list cards failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -65,19 +68,20 @@ func (h *handler) list(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getByID godoc
|
// getByID godoc
|
||||||
// @Summary Get permission by ID
|
// @Summary Get card by ID
|
||||||
// @Description Returns a single permission
|
// @Description Returns a single card
|
||||||
// @Tags permission
|
// @Tags cards
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Permission ID"
|
// @Param id path int true "Card ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /permissions/{id} [get]
|
// @Router /cards/{id} [get]
|
||||||
func (h *handler) getByID(c *gin.Context) {
|
func (h *handler) getByID(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -89,28 +93,39 @@ func (h *handler) getByID(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Errorf("get permission failed: %v", err)
|
h.logger.Errorf("get card failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
return
|
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))
|
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||||
}
|
}
|
||||||
|
|
||||||
// create godoc
|
// create godoc
|
||||||
// @Summary Create permission
|
// @Summary Create card
|
||||||
// @Description Creates a new permission
|
// @Description Creates a new card
|
||||||
// @Tags permission
|
// @Tags cards
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param body body CreatePermissionDTO true "Permission payload"
|
// @Param body body CreateCardDTO true "Card payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 201 {object} appresult.AppSuccess
|
// @Success 201 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /permissions [post]
|
// @Router /cards [post]
|
||||||
func (h *handler) create(c *gin.Context) {
|
func (h *handler) create(c *gin.Context) {
|
||||||
var dto CreatePermissionDTO
|
var dto CreateCardDTO
|
||||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -118,7 +133,7 @@ func (h *handler) create(c *gin.Context) {
|
|||||||
|
|
||||||
item, err := h.repository.Create(c.Request.Context(), dto)
|
item, err := h.repository.Create(c.Request.Context(), dto)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Errorf("create permission failed: %v", err)
|
h.logger.Errorf("create card failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -127,27 +142,32 @@ func (h *handler) create(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// update godoc
|
// update godoc
|
||||||
// @Summary Update permission
|
// @Summary Update card
|
||||||
// @Description Updates an existing permission
|
// @Description Updates an existing card
|
||||||
// @Tags permission
|
// @Tags cards
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Permission ID"
|
// @Param id path int true "Card ID"
|
||||||
// @Param body body UpdatePermissionDTO true "Permission payload"
|
// @Param body body UpdateCardDTO true "Card payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /permissions/{id} [put]
|
// @Router /cards/{id} [put]
|
||||||
func (h *handler) update(c *gin.Context) {
|
func (h *handler) update(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var dto UpdatePermissionDTO
|
if !h.guardCardByID(c, id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var dto UpdateCardDTO
|
||||||
if err := c.ShouldBindJSON(&dto); err != nil {
|
if err := c.ShouldBindJSON(&dto); err != nil {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -159,7 +179,7 @@ func (h *handler) update(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logger.Errorf("update permission failed: %v", err)
|
h.logger.Errorf("update card failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -168,75 +188,78 @@ func (h *handler) update(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// delete godoc
|
// delete godoc
|
||||||
// @Summary Delete permission
|
// @Summary Delete card
|
||||||
// @Description Deletes a permission
|
// @Description Deletes a card
|
||||||
// @Tags permission
|
// @Tags cards
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Permission ID"
|
// @Param id path int true "Card ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /permissions/{id} [delete]
|
// @Router /cards/{id} [delete]
|
||||||
func (h *handler) delete(c *gin.Context) {
|
func (h *handler) delete(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !h.guardCardByID(c, id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||||
return
|
return
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
h.logger.Errorf("delete permission failed: %v", err)
|
h.logger.Errorf("delete card failed: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, appresult.SuccessWithData("permission removed"))
|
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) {
|
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||||
filter := ListFilter{
|
page, limit, ok := shared.ParsePageLimit(c)
|
||||||
Page: defaultPage,
|
if !ok {
|
||||||
Limit: defaultLimit,
|
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("page"); raw != "" {
|
if raw := shared.QueryValue(c, "type"); raw != "" {
|
||||||
page, err := strconv.Atoi(raw)
|
filter.Type = &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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
rbac.BindBranchIDs(c, &filter.BranchIds)
|
||||||
return filter, true
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package cards
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type Repository interface {
|
||||||
|
List(ctx context.Context, filter ListFilter) (ListCardDTO, error)
|
||||||
|
GetByID(ctx context.Context, id int64) (CardDTO, error)
|
||||||
|
Create(ctx context.Context, dto CreateCardDTO) (CardDTO, error)
|
||||||
|
Update(ctx context.Context, id int64, dto UpdateCardDTO) (CardDTO, error)
|
||||||
|
Delete(ctx context.Context, id int64) error
|
||||||
|
}
|
||||||
+23
-67
@@ -7,20 +7,27 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"online-back/internal/admin/paymentcard"
|
"online-back/internal/cards/paymentcard"
|
||||||
|
"online-back/internal/shared"
|
||||||
"online-back/pkg/client/postgresql"
|
"online-back/pkg/client/postgresql"
|
||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
|
"online-back/pkg/repository/genericrepo"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v4"
|
"github.com/jackc/pgx/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
type repository struct {
|
type repository struct {
|
||||||
client postgresql.Client
|
client postgresql.Client
|
||||||
logger *logging.Logger
|
generic *genericrepo.Repository[paymentcard.PaymentCardDTO]
|
||||||
|
logger *logging.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard.Repository {
|
func NewRepository(client postgresql.Client, logger *logging.Logger) paymentcard.Repository {
|
||||||
return &repository{client: client, logger: logger}
|
return &repository{
|
||||||
|
client: client,
|
||||||
|
generic: genericrepo.New(client, "card_types c", cardColumns, scanPaymentCard),
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
|
const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
|
||||||
@@ -28,49 +35,21 @@ const cardColumns = `c.id, c.price, c.name, c.notes, c.active`
|
|||||||
const cardReturningColumns = `id, price, name, notes, active`
|
const cardReturningColumns = `id, price, name, notes, active`
|
||||||
|
|
||||||
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) {
|
func (r *repository) List(ctx context.Context, filter paymentcard.ListFilter) (paymentcard.ListPaymentCardDTO, error) {
|
||||||
fromClause, whereClause, args := buildListQuery(filter)
|
whereClause, args := buildListQuery(filter)
|
||||||
|
|
||||||
var count int64
|
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
|
||||||
return paymentcard.ListPaymentCardDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := (filter.Page - 1) * filter.Limit
|
|
||||||
limitPlaceholder := len(args) + 1
|
|
||||||
offsetPlaceholder := len(args) + 2
|
|
||||||
listQuery := fmt.Sprintf(
|
|
||||||
`SELECT %s%s%s ORDER BY c.id LIMIT $%d OFFSET $%d`,
|
|
||||||
cardColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
||||||
)
|
|
||||||
|
|
||||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return paymentcard.ListPaymentCardDTO{}, err
|
return paymentcard.ListPaymentCardDTO{}, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var items []paymentcard.PaymentCardDTO
|
|
||||||
for rows.Next() {
|
|
||||||
item, err := scanPaymentCard(rows)
|
|
||||||
if err != nil {
|
|
||||||
return paymentcard.ListPaymentCardDTO{}, err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return paymentcard.ListPaymentCardDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil
|
return paymentcard.ListPaymentCardDTO{Count: count, PaymentCards: items}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
func buildListQuery(filter paymentcard.ListFilter) (whereClause string, args []interface{}) {
|
||||||
fromClause = ` FROM card_types c`
|
|
||||||
|
|
||||||
var conditions []string
|
var conditions []string
|
||||||
|
|
||||||
if filter.CardName != "" {
|
if filter.CardName != "" {
|
||||||
args = append(args, likePattern(filter.CardName))
|
args = append(args, shared.LikePattern(filter.CardName))
|
||||||
n := len(args)
|
n := len(args)
|
||||||
conditions = append(conditions, fmt.Sprintf(`(
|
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
|
c.name->>'en' ILIKE $%[1]d OR c.name->>'ru' ILIKE $%[1]d OR c.name->>'tm' ILIKE $%[1]d
|
||||||
@@ -83,26 +62,14 @@ func buildListQuery(filter paymentcard.ListFilter) (fromClause, whereClause stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(conditions) == 0 {
|
if len(conditions) == 0 {
|
||||||
return fromClause, "", args
|
return "", args
|
||||||
}
|
}
|
||||||
|
|
||||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), 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) (paymentcard.PaymentCardDTO, error) {
|
func (r *repository) GetByID(ctx context.Context, id int64) (paymentcard.PaymentCardDTO, error) {
|
||||||
query := fmt.Sprintf(`SELECT %s FROM card_types c WHERE c.id = $1`, cardColumns)
|
return r.generic.GetByID(ctx, id)
|
||||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, id))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return paymentcard.PaymentCardDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
|
func (r *repository) Create(ctx context.Context, dto paymentcard.CreatePaymentCardDTO) (paymentcard.PaymentCardDTO, error) {
|
||||||
@@ -133,7 +100,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto paymentcard.Updat
|
|||||||
query := fmt.Sprintf(`
|
query := fmt.Sprintf(`
|
||||||
UPDATE card_types SET
|
UPDATE card_types SET
|
||||||
price = $1, name = $2, notes = $3, active = $4
|
price = $1, name = $2, notes = $3, active = $4
|
||||||
WHERE id = $5
|
WHERE id = $5 AND deleted_at IS NULL
|
||||||
RETURNING %s`, cardReturningColumns)
|
RETURNING %s`, cardReturningColumns)
|
||||||
|
|
||||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||||
@@ -146,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) {
|
func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (paymentcard.PaymentCardDTO, error) {
|
||||||
query := fmt.Sprintf(`
|
query := fmt.Sprintf(`
|
||||||
UPDATE card_types SET active = $1
|
UPDATE card_types SET active = $1
|
||||||
WHERE id = $2
|
WHERE id = $2 AND deleted_at IS NULL
|
||||||
RETURNING %s`, cardReturningColumns)
|
RETURNING %s`, cardReturningColumns)
|
||||||
|
|
||||||
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
|
item, err := scanPaymentCard(r.client.QueryRow(ctx, query, active, id))
|
||||||
@@ -157,25 +124,14 @@ func (r *repository) UpdateActive(ctx context.Context, id int64, active bool) (p
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||||
tag, err := r.client.Exec(ctx, `DELETE FROM card_types WHERE id = $1`, id)
|
return r.generic.Delete(ctx, id)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if tag.RowsAffected() == 0 {
|
|
||||||
return pgx.ErrNoRows
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func marshalName(title paymentcard.LocalizedText) ([]byte, error) {
|
func marshalName(title shared.LocalizedText) ([]byte, error) {
|
||||||
return json.Marshal(title)
|
return json.Marshal(title)
|
||||||
}
|
}
|
||||||
|
|
||||||
type scannable interface {
|
func scanPaymentCard(row genericrepo.Scanner) (paymentcard.PaymentCardDTO, error) {
|
||||||
Scan(dest ...interface{}) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanPaymentCard(row scannable) (paymentcard.PaymentCardDTO, error) {
|
|
||||||
var item paymentcard.PaymentCardDTO
|
var item paymentcard.PaymentCardDTO
|
||||||
var nameJSON []byte
|
var nameJSON []byte
|
||||||
|
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package paymentcard
|
||||||
|
|
||||||
|
import "online-back/internal/shared"
|
||||||
|
|
||||||
|
type PaymentCardDTO struct {
|
||||||
|
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 shared.LocalizedText `json:"title" binding:"required"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
Active *bool `json:"active"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdatePaymentCardDTO struct {
|
||||||
|
Price string `json:"price" binding:"required"`
|
||||||
|
Title shared.LocalizedText `json:"title" binding:"required"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdatePaymentCardActiveDTO struct {
|
||||||
|
Active bool `json:"active"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListFilter struct {
|
||||||
|
CardName string
|
||||||
|
Active *bool
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListPaymentCardDTO struct {
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
PaymentCards []PaymentCardDTO `json:"paymentCards"`
|
||||||
|
}
|
||||||
@@ -4,10 +4,12 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"online-back/internal/appresult"
|
"online-back/internal/appresult"
|
||||||
"online-back/internal/handlers"
|
"online-back/internal/handlers"
|
||||||
|
"online-back/internal/identity/rbac"
|
||||||
|
"online-back/internal/identity/rbac/perm"
|
||||||
|
"online-back/internal/shared"
|
||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"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) {
|
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("", h.list)
|
||||||
group.GET("/:id", h.getByID)
|
group.GET("/:id", h.getByID)
|
||||||
group.POST("", h.create)
|
group.POST("", h.create)
|
||||||
@@ -45,6 +47,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
|||||||
// @Param active query bool false "Filter by active"
|
// @Param active query bool false "Filter by active"
|
||||||
// @Param page query int false "Page number" default(1)
|
// @Param page query int false "Page number" default(1)
|
||||||
// @Param limit query int false "Items per page" default(10)
|
// @Param limit query int false "Items per page" default(10)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
@@ -73,13 +76,14 @@ func (h *handler) list(c *gin.Context) {
|
|||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Payment card ID"
|
// @Param id path int true "Payment card ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /payment-cards/{id} [get]
|
// @Router /payment-cards/{id} [get]
|
||||||
func (h *handler) getByID(c *gin.Context) {
|
func (h *handler) getByID(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -107,6 +111,7 @@ func (h *handler) getByID(c *gin.Context) {
|
|||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param body body CreatePaymentCardDTO true "Payment card payload"
|
// @Param body body CreatePaymentCardDTO true "Payment card payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 201 {object} appresult.AppSuccess
|
// @Success 201 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
@@ -137,13 +142,14 @@ func (h *handler) create(c *gin.Context) {
|
|||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Payment card ID"
|
// @Param id path int true "Payment card ID"
|
||||||
// @Param body body UpdatePaymentCardDTO true "Payment card payload"
|
// @Param body body UpdatePaymentCardDTO true "Payment card payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /payment-cards/{id} [put]
|
// @Router /payment-cards/{id} [put]
|
||||||
func (h *handler) update(c *gin.Context) {
|
func (h *handler) update(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -178,13 +184,14 @@ func (h *handler) update(c *gin.Context) {
|
|||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Payment card ID"
|
// @Param id path int true "Payment card ID"
|
||||||
// @Param body body UpdatePaymentCardActiveDTO true "Active payload"
|
// @Param body body UpdatePaymentCardActiveDTO true "Active payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /payment-cards/{id}/active [put]
|
// @Router /payment-cards/{id}/active [put]
|
||||||
func (h *handler) updateActive(c *gin.Context) {
|
func (h *handler) updateActive(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -217,13 +224,14 @@ func (h *handler) updateActive(c *gin.Context) {
|
|||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Payment card ID"
|
// @Param id path int true "Payment card ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /payment-cards/{id} [delete]
|
// @Router /payment-cards/{id} [delete]
|
||||||
func (h *handler) delete(c *gin.Context) {
|
func (h *handler) delete(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -241,47 +249,18 @@ func (h *handler) delete(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, appresult.SuccessWithData("payment card removed"))
|
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) {
|
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||||
filter := ListFilter{
|
page, limit, ok := shared.ParsePageLimit(c)
|
||||||
Page: defaultPage,
|
if !ok {
|
||||||
Limit: defaultLimit,
|
return ListFilter{}, false
|
||||||
}
|
}
|
||||||
|
filter := ListFilter{Page: page, Limit: limit}
|
||||||
|
|
||||||
if raw := c.Query("page"); raw != "" {
|
if raw := shared.QueryValue(c, "card_name", "cardName"); 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 != "" {
|
|
||||||
filter.CardName = raw
|
filter.CardName = raw
|
||||||
}
|
}
|
||||||
|
|
||||||
if raw := c.Query("active"); raw != "" {
|
if raw := shared.QueryValue(c, "active"); raw != "" {
|
||||||
active, err := strconv.ParseBool(raw)
|
active, err := strconv.ParseBool(raw)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ListFilter{}, false
|
return ListFilter{}, false
|
||||||
File renamed without changes.
+22
-66
@@ -7,20 +7,27 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"online-back/internal/admin/reasonscard"
|
"online-back/internal/cards/reasonscard"
|
||||||
|
"online-back/internal/shared"
|
||||||
"online-back/pkg/client/postgresql"
|
"online-back/pkg/client/postgresql"
|
||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
|
"online-back/pkg/repository/genericrepo"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v4"
|
"github.com/jackc/pgx/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
type repository struct {
|
type repository struct {
|
||||||
client postgresql.Client
|
client postgresql.Client
|
||||||
logger *logging.Logger
|
generic *genericrepo.Repository[reasonscard.ReasonCardDTO]
|
||||||
|
logger *logging.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard.Repository {
|
func NewRepository(client postgresql.Client, logger *logging.Logger) reasonscard.Repository {
|
||||||
return &repository{client: client, logger: logger}
|
return &repository{
|
||||||
|
client: client,
|
||||||
|
generic: genericrepo.New(client, "card_states r", reasonColumns, scanReasonCard),
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r.updated_at`
|
const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r.updated_at`
|
||||||
@@ -28,48 +35,20 @@ const reasonColumns = `r.id, r.price, r.name, r.notes, r.active, r.created_at, r
|
|||||||
const reasonReturningColumns = `id, price, name, notes, active, created_at, updated_at`
|
const reasonReturningColumns = `id, price, name, notes, active, created_at, updated_at`
|
||||||
|
|
||||||
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) {
|
func (r *repository) List(ctx context.Context, filter reasonscard.ListFilter) (reasonscard.ListReasonCardDTO, error) {
|
||||||
fromClause, whereClause, args := buildListQuery(filter)
|
whereClause, args := buildListQuery(filter)
|
||||||
|
|
||||||
var count int64
|
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) `+fromClause+whereClause, args...).Scan(&count); err != nil {
|
|
||||||
return reasonscard.ListReasonCardDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := (filter.Page - 1) * filter.Limit
|
|
||||||
limitPlaceholder := len(args) + 1
|
|
||||||
offsetPlaceholder := len(args) + 2
|
|
||||||
listQuery := fmt.Sprintf(
|
|
||||||
`SELECT %s%s%s ORDER BY r.id LIMIT $%d OFFSET $%d`,
|
|
||||||
reasonColumns, fromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
|
||||||
)
|
|
||||||
|
|
||||||
rows, err := r.client.Query(ctx, listQuery, append(args, filter.Limit, offset)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return reasonscard.ListReasonCardDTO{}, err
|
return reasonscard.ListReasonCardDTO{}, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var items []reasonscard.ReasonCardDTO
|
|
||||||
for rows.Next() {
|
|
||||||
item, err := scanReasonCard(rows)
|
|
||||||
if err != nil {
|
|
||||||
return reasonscard.ListReasonCardDTO{}, err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return reasonscard.ListReasonCardDTO{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil
|
return reasonscard.ListReasonCardDTO{Count: count, ReasonCards: items}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause string, args []interface{}) {
|
func buildListQuery(filter reasonscard.ListFilter) (whereClause string, args []interface{}) {
|
||||||
fromClause = ` FROM card_states r`
|
|
||||||
|
|
||||||
var conditions []string
|
var conditions []string
|
||||||
if filter.ReasonName != "" {
|
if filter.ReasonName != "" {
|
||||||
args = append(args, likePattern(filter.ReasonName))
|
args = append(args, shared.LikePattern(filter.ReasonName))
|
||||||
n := len(args)
|
n := len(args)
|
||||||
conditions = append(conditions, fmt.Sprintf(`(
|
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
|
r.name->>'en' ILIKE $%[1]d OR r.name->>'ru' ILIKE $%[1]d OR r.name->>'tm' ILIKE $%[1]d
|
||||||
@@ -77,26 +56,14 @@ func buildListQuery(filter reasonscard.ListFilter) (fromClause, whereClause stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(conditions) == 0 {
|
if len(conditions) == 0 {
|
||||||
return fromClause, "", args
|
return "", args
|
||||||
}
|
}
|
||||||
|
|
||||||
return fromClause, " WHERE " + strings.Join(conditions, " AND "), 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) (reasonscard.ReasonCardDTO, error) {
|
func (r *repository) GetByID(ctx context.Context, id int64) (reasonscard.ReasonCardDTO, error) {
|
||||||
query := fmt.Sprintf(`SELECT %s FROM card_states r WHERE r.id = $1`, reasonColumns)
|
return r.generic.GetByID(ctx, id)
|
||||||
item, err := scanReasonCard(r.client.QueryRow(ctx, query, id))
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return reasonscard.ReasonCardDTO{}, err
|
|
||||||
}
|
|
||||||
return item, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
|
func (r *repository) Create(ctx context.Context, dto reasonscard.CreateReasonCardDTO) (reasonscard.ReasonCardDTO, error) {
|
||||||
@@ -128,7 +95,7 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
|
|||||||
UPDATE card_states SET
|
UPDATE card_states SET
|
||||||
price = $1, name = $2, notes = $3, active = $4,
|
price = $1, name = $2, notes = $3, active = $4,
|
||||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||||
WHERE id = $5
|
WHERE id = $5 AND deleted_at IS NULL
|
||||||
RETURNING %s`, reasonReturningColumns)
|
RETURNING %s`, reasonReturningColumns)
|
||||||
|
|
||||||
item, err := scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
item, err := scanReasonCard(r.client.QueryRow(ctx, query, dto.Price, name, dto.Notes, dto.Active, id))
|
||||||
@@ -139,25 +106,14 @@ func (r *repository) Update(ctx context.Context, id int64, dto reasonscard.Updat
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||||
tag, err := r.client.Exec(ctx, `DELETE FROM card_states WHERE id = $1`, id)
|
return r.generic.Delete(ctx, id)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if tag.RowsAffected() == 0 {
|
|
||||||
return pgx.ErrNoRows
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func marshalName(title reasonscard.LocalizedText) ([]byte, error) {
|
func marshalName(title shared.LocalizedText) ([]byte, error) {
|
||||||
return json.Marshal(title)
|
return json.Marshal(title)
|
||||||
}
|
}
|
||||||
|
|
||||||
type scannable interface {
|
func scanReasonCard(row genericrepo.Scanner) (reasonscard.ReasonCardDTO, error) {
|
||||||
Scan(dest ...interface{}) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanReasonCard(row scannable) (reasonscard.ReasonCardDTO, error) {
|
|
||||||
var item reasonscard.ReasonCardDTO
|
var item reasonscard.ReasonCardDTO
|
||||||
var nameJSON []byte
|
var nameJSON []byte
|
||||||
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package reasonscard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"online-back/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ReasonCardDTO struct {
|
||||||
|
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 shared.LocalizedText `json:"title" binding:"required"`
|
||||||
|
Price string `json:"price" binding:"required"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
Active *bool `json:"active"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateReasonCardDTO struct {
|
||||||
|
Title shared.LocalizedText `json:"title" binding:"required"`
|
||||||
|
Price string `json:"price" binding:"required"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
Active bool `json:"active"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListFilter struct {
|
||||||
|
ReasonName string
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListReasonCardDTO struct {
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
ReasonCards []ReasonCardDTO `json:"reasonCards"`
|
||||||
|
}
|
||||||
@@ -3,11 +3,12 @@ package reasonscard
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"online-back/internal/appresult"
|
"online-back/internal/appresult"
|
||||||
"online-back/internal/handlers"
|
"online-back/internal/handlers"
|
||||||
|
"online-back/internal/identity/rbac"
|
||||||
|
"online-back/internal/identity/rbac/perm"
|
||||||
|
"online-back/internal/shared"
|
||||||
"online-back/pkg/logging"
|
"online-back/pkg/logging"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"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) {
|
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("", h.list)
|
||||||
group.GET("/:id", h.getByID)
|
group.GET("/:id", h.getByID)
|
||||||
group.POST("", h.create)
|
group.POST("", h.create)
|
||||||
@@ -43,6 +44,7 @@ func (h *handler) Register(router *gin.RouterGroup) {
|
|||||||
// @Param reason_name query string false "Filter by title (en, ru, tm)"
|
// @Param reason_name query string false "Filter by title (en, ru, tm)"
|
||||||
// @Param page query int false "Page number" default(1)
|
// @Param page query int false "Page number" default(1)
|
||||||
// @Param limit query int false "Items per page" default(10)
|
// @Param limit query int false "Items per page" default(10)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
@@ -71,13 +73,14 @@ func (h *handler) list(c *gin.Context) {
|
|||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Reason card ID"
|
// @Param id path int true "Reason card ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /reasons-cards/{id} [get]
|
// @Router /reasons-cards/{id} [get]
|
||||||
func (h *handler) getByID(c *gin.Context) {
|
func (h *handler) getByID(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -105,6 +108,7 @@ func (h *handler) getByID(c *gin.Context) {
|
|||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param body body CreateReasonCardDTO true "Reason card payload"
|
// @Param body body CreateReasonCardDTO true "Reason card payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 201 {object} appresult.AppSuccess
|
// @Success 201 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
@@ -135,13 +139,14 @@ func (h *handler) create(c *gin.Context) {
|
|||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Reason card ID"
|
// @Param id path int true "Reason card ID"
|
||||||
// @Param body body UpdateReasonCardDTO true "Reason card payload"
|
// @Param body body UpdateReasonCardDTO true "Reason card payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /reasons-cards/{id} [put]
|
// @Router /reasons-cards/{id} [put]
|
||||||
func (h *handler) update(c *gin.Context) {
|
func (h *handler) update(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -174,13 +179,14 @@ func (h *handler) update(c *gin.Context) {
|
|||||||
// @Produce json
|
// @Produce json
|
||||||
// @Security BearerAuth
|
// @Security BearerAuth
|
||||||
// @Param id path int true "Reason card ID"
|
// @Param id path int true "Reason card ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
// @Success 200 {object} appresult.AppSuccess
|
// @Success 200 {object} appresult.AppSuccess
|
||||||
// @Failure 400 {object} appresult.AppError
|
// @Failure 400 {object} appresult.AppError
|
||||||
// @Failure 404 {object} appresult.AppError
|
// @Failure 404 {object} appresult.AppError
|
||||||
// @Failure 500 {object} appresult.AppError
|
// @Failure 500 {object} appresult.AppError
|
||||||
// @Router /reasons-cards/{id} [delete]
|
// @Router /reasons-cards/{id} [delete]
|
||||||
func (h *handler) delete(c *gin.Context) {
|
func (h *handler) delete(c *gin.Context) {
|
||||||
id, ok := parseID(c.Param("id"))
|
id, ok := shared.ParseID(c.Param("id"))
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
return
|
return
|
||||||
@@ -198,43 +204,14 @@ func (h *handler) delete(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, appresult.SuccessWithData("reason card removed"))
|
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) {
|
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||||
filter := ListFilter{
|
page, limit, ok := shared.ParsePageLimit(c)
|
||||||
Page: defaultPage,
|
if !ok {
|
||||||
Limit: defaultLimit,
|
return ListFilter{}, false
|
||||||
}
|
}
|
||||||
|
filter := ListFilter{Page: page, Limit: limit}
|
||||||
|
|
||||||
if raw := c.Query("page"); raw != "" {
|
if raw := shared.QueryValue(c, "reason_name", "reasonName"); 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 != "" {
|
|
||||||
filter.ReasonName = raw
|
filter.ReasonName = raw
|
||||||
}
|
}
|
||||||
|
|
||||||
File renamed without changes.
@@ -0,0 +1,52 @@
|
|||||||
|
// 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/cards/visamasteractions"
|
||||||
|
visamasteractionsdb "online-back/internal/cards/visamasteractions/db"
|
||||||
|
"online-back/internal/handlers"
|
||||||
|
"online-back/pkg/client/postgresql"
|
||||||
|
"online-back/pkg/logging"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Register wires every cards module's handler onto router.
|
||||||
|
func Register(router *gin.RouterGroup, client postgresql.Client, logger *logging.Logger) {
|
||||||
|
for _, h := range Handlers(client, logger) {
|
||||||
|
h.Register(router)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Handlers(client postgresql.Client, logger *logging.Logger) []handlers.Handler {
|
||||||
|
return []handlers.Handler{
|
||||||
|
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)),
|
||||||
|
visamasteractions.NewHandler(logger, visamasteractionsdb.NewRepository(client, logger)),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,483 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"online-back/internal/cards/visamaster"
|
||||||
|
"online-back/internal/cards/visamasteractions"
|
||||||
|
actionsdb "online-back/internal/cards/visamasteractions/db"
|
||||||
|
"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,
|
||||||
|
)
|
||||||
|
|
||||||
|
// A failed create has no order to attach an action to, so only the
|
||||||
|
// successful one is recorded - in the same transaction as the insert.
|
||||||
|
tx, err := r.client.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
item, err := scanOrder(tx.QueryRow(ctx, query, args...))
|
||||||
|
if err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := actionsdb.Snapshot(ctx, tx, item.Id)
|
||||||
|
if err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
if err := actionsdb.Insert(ctx, tx, visamasteractions.CreateOrderActionDTO{
|
||||||
|
OrderId: item.Id, Name: visamasteractions.NameCreate, Status: visamasteractions.StatusFinished,
|
||||||
|
Changes: created, CreatedBy: dto.CreatedBy,
|
||||||
|
}); err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
tx, err := r.client.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
before, err := actionsdb.Snapshot(ctx, tx, id)
|
||||||
|
if err != nil {
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// fail rolls the update back and records it as failed, with the
|
||||||
|
// values it attempted.
|
||||||
|
fail := func(err error) (visamaster.VisaMasterPaymentOrderDTO, error) {
|
||||||
|
tx.Rollback(ctx)
|
||||||
|
original, changes := r.attemptedChanges(before, args)
|
||||||
|
r.recordFailure(ctx, id, visamasteractions.NameUpdate, dto.UpdatedBy, original, changes, err)
|
||||||
|
return visamaster.VisaMasterPaymentOrderDTO{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
item, err := scanOrder(tx.QueryRow(ctx, query, args...))
|
||||||
|
if err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
after, err := actionsdb.Snapshot(ctx, tx, id)
|
||||||
|
if err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
// An update that changed nothing (the form saved as-is) is not an action.
|
||||||
|
if original, changes := visamasteractions.Diff(before, after); changes != nil {
|
||||||
|
if err := actionsdb.Insert(ctx, tx, visamasteractions.CreateOrderActionDTO{
|
||||||
|
OrderId: id, Name: visamasteractions.NameUpdate, Status: visamasteractions.StatusFinished,
|
||||||
|
Original: original, Changes: changes, CreatedBy: dto.UpdatedBy,
|
||||||
|
}); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) Delete(ctx context.Context, id int64, deletedBy *int64) error {
|
||||||
|
tx, err := r.client.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
before, err := actionsdb.Snapshot(ctx, tx, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
fail := func(err error) error {
|
||||||
|
tx.Rollback(ctx)
|
||||||
|
r.recordFailure(ctx, id, visamasteractions.NameDelete, deletedBy, before, nil, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same soft delete as genericrepo.Delete, inside the transaction.
|
||||||
|
if _, err := tx.Exec(ctx, `UPDATE visa_master_payment_orders SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
if err := actionsdb.Insert(ctx, tx, visamasteractions.CreateOrderActionDTO{
|
||||||
|
OrderId: id, Name: visamasteractions.NameDelete, Status: visamasteractions.StatusFinished,
|
||||||
|
Original: before, CreatedBy: deletedBy,
|
||||||
|
}); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// attemptedChanges is what a failed update tried to change: the writable
|
||||||
|
// columns whose attempted value (args, in orderWritableColumns order)
|
||||||
|
// differs from before.
|
||||||
|
func (r *repository) attemptedChanges(before map[string]interface{}, args []interface{}) (original, changes map[string]interface{}) {
|
||||||
|
values := make(map[string]interface{}, len(orderWritableColumns))
|
||||||
|
current := make(map[string]interface{}, len(orderWritableColumns))
|
||||||
|
for i, column := range orderWritableColumns {
|
||||||
|
value := args[i]
|
||||||
|
// jsonArg's bytes are JSON, not a byte string to base64-encode.
|
||||||
|
if raw, ok := value.([]byte); ok {
|
||||||
|
value = json.RawMessage(raw)
|
||||||
|
}
|
||||||
|
values[column] = value
|
||||||
|
current[column] = before[column]
|
||||||
|
}
|
||||||
|
attempted, err := visamasteractions.Normalize(values)
|
||||||
|
if err != nil {
|
||||||
|
// Unencodable (e.g. invalid JSON in senderDatas): record the failure
|
||||||
|
// without the attempted values rather than not at all.
|
||||||
|
r.logger.Errorf("visa master order action: encode attempted values failed: %v", err)
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return visamasteractions.Diff(current, attempted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// recordFailure records a failed action through the plain client, after
|
||||||
|
// its transaction rolled back. Best-effort: a write failure here is
|
||||||
|
// logged, not propagated over the action's own error.
|
||||||
|
func (r *repository) recordFailure(ctx context.Context, orderID int64, name string, createdBy *int64, original, changes map[string]interface{}, cause error) {
|
||||||
|
exception := cause.Error()
|
||||||
|
// Detached from cancellation: a client dropping the request must not
|
||||||
|
// cost us the record of what it tried.
|
||||||
|
if err := actionsdb.Insert(context.WithoutCancel(ctx), r.client, visamasteractions.CreateOrderActionDTO{
|
||||||
|
OrderId: orderID, Name: name, Status: visamasteractions.StatusFailed,
|
||||||
|
Original: original, Changes: changes, Exception: &exception, CreatedBy: createdBy,
|
||||||
|
}); err != nil {
|
||||||
|
r.logger.Errorf("record failed visa master order action (order %d, %s) failed: %v", orderID, name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
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"`
|
||||||
|
// CreatedBy is the caller, recorded on the order's create action.
|
||||||
|
CreatedBy *int64 `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
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"`
|
||||||
|
// UpdatedBy is the caller, recorded on the order's update action.
|
||||||
|
UpdatedBy *int64 `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
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"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
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-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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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-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)
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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-orders
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Visa/master payment order ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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-orders
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param body body CreateVisaMasterPaymentOrderDTO true "Visa/master payment order payload"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
}
|
||||||
|
if userID, ok := rbac.CurrentUserID(c); ok {
|
||||||
|
dto.CreatedBy = &userID
|
||||||
|
}
|
||||||
|
|
||||||
|
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-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"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
}
|
||||||
|
if userID, ok := rbac.CurrentUserID(c); ok {
|
||||||
|
dto.UpdatedBy = &userID
|
||||||
|
}
|
||||||
|
|
||||||
|
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-orders
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Visa/master payment order ID"
|
||||||
|
// @Param lang query string false "Language of localized fields; all returns the full {en, ru, tm} objects" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @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
|
||||||
|
}
|
||||||
|
|
||||||
|
var deletedBy *int64
|
||||||
|
if userID, ok := rbac.CurrentUserID(c); ok {
|
||||||
|
deletedBy = &userID
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.repository.Delete(c.Request.Context(), id, deletedBy); 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
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 soft-deletes the order; deletedBy is the caller, recorded on
|
||||||
|
// its delete action.
|
||||||
|
Delete(ctx context.Context, id int64, deletedBy *int64) error
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"online-back/internal/cards/visamasteractions"
|
||||||
|
"online-back/internal/shared"
|
||||||
|
"online-back/pkg/client/postgresql"
|
||||||
|
"online-back/pkg/logging"
|
||||||
|
|
||||||
|
"github.com/jackc/pgconn"
|
||||||
|
"github.com/jackc/pgx/v4"
|
||||||
|
)
|
||||||
|
|
||||||
|
type repository struct {
|
||||||
|
client postgresql.Client
|
||||||
|
logger *logging.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(client postgresql.Client, logger *logging.Logger) visamasteractions.Repository {
|
||||||
|
return &repository{client: client, logger: logger}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Querier is satisfied by both postgresql.Client and pgx.Tx, so the order
|
||||||
|
// repositories can snapshot and record inside the transaction that changes
|
||||||
|
// the order - an action is on record exactly when its change is.
|
||||||
|
type Querier interface {
|
||||||
|
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
|
||||||
|
Exec(ctx context.Context, sql string, args ...interface{}) (pgconn.CommandTag, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot locks orderID's row (FOR UPDATE) and returns its columns as
|
||||||
|
// recorded on an action - everything but id and the timestamps, which
|
||||||
|
// change on every write. pgx.ErrNoRows if the order doesn't exist or is
|
||||||
|
// deleted.
|
||||||
|
func Snapshot(ctx context.Context, q Querier, orderID int64) (map[string]interface{}, error) {
|
||||||
|
var raw []byte
|
||||||
|
err := q.QueryRow(ctx,
|
||||||
|
`SELECT to_jsonb(o) - 'id' - 'created_at' - 'updated_at' - 'deleted_at'
|
||||||
|
FROM visa_master_payment_orders o WHERE o.id = $1 AND o.deleted_at IS NULL FOR UPDATE`,
|
||||||
|
orderID,
|
||||||
|
).Scan(&raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var row map[string]interface{}
|
||||||
|
if err := json.Unmarshal(raw, &row); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return row, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert records one action. A failed action must be recorded through the
|
||||||
|
// plain client after its transaction rolled back, or it is rolled back too.
|
||||||
|
func Insert(ctx context.Context, q Querier, dto visamasteractions.CreateOrderActionDTO) error {
|
||||||
|
original, err := jsonOrNull(dto.Original)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
changes, err := jsonOrNull(dto.Changes)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = q.Exec(ctx,
|
||||||
|
`INSERT INTO visa_master_order_actions (order_id, name, status, original, changes, exception, created_by)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||||
|
dto.OrderId, dto.Name, dto.Status, original, changes, dto.Exception, dto.CreatedBy,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonOrNull(values map[string]interface{}) ([]byte, error) {
|
||||||
|
if values == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return json.Marshal(values)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) OwnerInfo(ctx context.Context, orderID int64) (*int64, int64, error) {
|
||||||
|
var userID *int64
|
||||||
|
var branchID int64
|
||||||
|
err := r.client.QueryRow(ctx,
|
||||||
|
`SELECT user_id, branch_id FROM visa_master_payment_orders WHERE id = $1`, orderID,
|
||||||
|
).Scan(&userID, &branchID)
|
||||||
|
return userID, branchID, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const actionSelectColumns = `a.id, a.order_id, a.name, a.status, o.unique_id, o.type,
|
||||||
|
a.created_by, ` + shared.UserDisplaySQL + `, a.created_at`
|
||||||
|
|
||||||
|
const actionFromClause = ` FROM visa_master_order_actions a
|
||||||
|
JOIN visa_master_payment_orders o ON o.id = a.order_id
|
||||||
|
LEFT JOIN users u ON u.id = a.created_by`
|
||||||
|
|
||||||
|
func (r *repository) List(ctx context.Context, filter visamasteractions.ListFilter) (visamasteractions.ListOrderActionDTO, error) {
|
||||||
|
result := visamasteractions.ListOrderActionDTO{Actions: []visamasteractions.OrderActionDTO{}}
|
||||||
|
|
||||||
|
if err := r.client.QueryRow(ctx,
|
||||||
|
`SELECT COUNT(*) FROM visa_master_order_actions WHERE order_id = $1`, filter.OrderId,
|
||||||
|
).Scan(&result.Count); err != nil {
|
||||||
|
return visamasteractions.ListOrderActionDTO{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := r.client.Query(ctx,
|
||||||
|
`SELECT `+actionSelectColumns+actionFromClause+` WHERE a.order_id = $1 ORDER BY a.id DESC LIMIT $2 OFFSET $3`,
|
||||||
|
filter.OrderId, filter.Limit, (filter.Page-1)*filter.Limit,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return visamasteractions.ListOrderActionDTO{}, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
item, err := scanAction(rows)
|
||||||
|
if err != nil {
|
||||||
|
return visamasteractions.ListOrderActionDTO{}, err
|
||||||
|
}
|
||||||
|
result.Actions = append(result.Actions, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return visamasteractions.ListOrderActionDTO{}, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *repository) GetByID(ctx context.Context, orderID, actionID int64) (visamasteractions.OrderActionDetailDTO, error) {
|
||||||
|
var detail visamasteractions.OrderActionDetailDTO
|
||||||
|
var original, changes []byte
|
||||||
|
row := r.client.QueryRow(ctx,
|
||||||
|
`SELECT `+actionSelectColumns+`, a.original, a.changes, a.exception`+actionFromClause+` WHERE a.id = $1 AND a.order_id = $2`,
|
||||||
|
actionID, orderID,
|
||||||
|
)
|
||||||
|
item, err := scanAction(row, &original, &changes, &detail.Exception)
|
||||||
|
if err != nil {
|
||||||
|
return visamasteractions.OrderActionDetailDTO{}, err
|
||||||
|
}
|
||||||
|
detail.OrderActionDTO = item
|
||||||
|
detail.Original = rawOrNull(original)
|
||||||
|
detail.Changes = rawOrNull(changes)
|
||||||
|
return detail, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scanAction reads actionSelectColumns, followed by any extra columns into
|
||||||
|
// extra.
|
||||||
|
func scanAction(row pgx.Row, extra ...interface{}) (visamasteractions.OrderActionDTO, error) {
|
||||||
|
var item visamasteractions.OrderActionDTO
|
||||||
|
dest := append([]interface{}{
|
||||||
|
&item.Id, &item.OrderId, &item.Name, &item.Status, &item.Target.UniqueId, &item.Target.Type,
|
||||||
|
&item.CreatedById, &item.CreatedByName, &item.CreatedAt,
|
||||||
|
}, extra...)
|
||||||
|
if err := row.Scan(dest...); err != nil {
|
||||||
|
return visamasteractions.OrderActionDTO{}, err
|
||||||
|
}
|
||||||
|
item.NameLabel = visamasteractions.NameLabel(item.Name)
|
||||||
|
item.Target.Id = item.OrderId
|
||||||
|
item.Target.Label = visamasteractions.TargetLabel(item.Target.Type)
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func rawOrNull(raw []byte) json.RawMessage {
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return json.RawMessage("null")
|
||||||
|
}
|
||||||
|
return json.RawMessage(raw)
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package visamasteractions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Normalize round-trips values through JSON, so Go values (pointers, raw
|
||||||
|
// JSON bytes, float64s) compare equal to the same values read back from a
|
||||||
|
// jsonb snapshot of the row.
|
||||||
|
func Normalize(values map[string]interface{}) (map[string]interface{}, error) {
|
||||||
|
if values == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var normalized map[string]interface{}
|
||||||
|
if err := json.Unmarshal(data, &normalized); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return normalized, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diff keeps only the columns whose value differs between before and
|
||||||
|
// after: original gets their before values and changes their after
|
||||||
|
// values. A column missing on one side counts as null there. Both are nil
|
||||||
|
// when nothing changed.
|
||||||
|
func Diff(before, after map[string]interface{}) (original, changes map[string]interface{}) {
|
||||||
|
for key, value := range after {
|
||||||
|
if old, ok := before[key]; ok && reflect.DeepEqual(old, value) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if original == nil {
|
||||||
|
original, changes = map[string]interface{}{}, map[string]interface{}{}
|
||||||
|
}
|
||||||
|
original[key] = before[key]
|
||||||
|
changes[key] = value
|
||||||
|
}
|
||||||
|
for key, old := range before {
|
||||||
|
if _, ok := after[key]; ok || old == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if original == nil {
|
||||||
|
original, changes = map[string]interface{}{}, map[string]interface{}{}
|
||||||
|
}
|
||||||
|
original[key] = old
|
||||||
|
changes[key] = nil
|
||||||
|
}
|
||||||
|
return original, changes
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package visamasteractions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDiffKeepsOnlyChangedColumns(t *testing.T) {
|
||||||
|
before := map[string]interface{}{"status": "pending", "paid": false, "amount_usd": 250.0, "notes": nil}
|
||||||
|
after := map[string]interface{}{"status": "completed", "paid": false, "amount_usd": 250.0, "notes": nil}
|
||||||
|
|
||||||
|
original, changes := Diff(before, after)
|
||||||
|
|
||||||
|
if !reflect.DeepEqual(original, map[string]interface{}{"status": "pending"}) {
|
||||||
|
t.Errorf("original = %v, want only status: pending", original)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(changes, map[string]interface{}{"status": "completed"}) {
|
||||||
|
t.Errorf("changes = %v, want only status: completed", changes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiffNothingChanged(t *testing.T) {
|
||||||
|
row := map[string]interface{}{"status": "pending", "sender_datas": map[string]interface{}{"a": 1.0}}
|
||||||
|
if original, changes := Diff(row, row); original != nil || changes != nil {
|
||||||
|
t.Errorf("Diff of equal rows = %v, %v, want nil, nil", original, changes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiffMissingColumnCountsAsNull(t *testing.T) {
|
||||||
|
before := map[string]interface{}{"status": "pending", "notes": "old"}
|
||||||
|
after := map[string]interface{}{"status": "pending", "email": "a@b.tm"}
|
||||||
|
|
||||||
|
original, changes := Diff(before, after)
|
||||||
|
|
||||||
|
if !reflect.DeepEqual(original, map[string]interface{}{"notes": "old", "email": nil}) {
|
||||||
|
t.Errorf("original = %v", original)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(changes, map[string]interface{}{"notes": nil, "email": "a@b.tm"}) {
|
||||||
|
t.Errorf("changes = %v", changes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeMatchesJSONBSnapshot(t *testing.T) {
|
||||||
|
status := "pending"
|
||||||
|
attempted, err := Normalize(map[string]interface{}{
|
||||||
|
"status": &status,
|
||||||
|
"amount_usd": 250.0,
|
||||||
|
"sender_datas": json.RawMessage(`{"a": 1}`),
|
||||||
|
"notes": (*string)(nil),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var snapshot map[string]interface{}
|
||||||
|
if err := json.Unmarshal([]byte(`{"status": "pending", "amount_usd": 250, "sender_datas": {"a": 1}, "notes": null}`), &snapshot); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if original, changes := Diff(snapshot, attempted); original != nil || changes != nil {
|
||||||
|
t.Errorf("normalized values differ from the snapshot: %v -> %v", original, changes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package visamasteractions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"online-back/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Action names, as the "Ammallar" table's Amalyň ady column shows them.
|
||||||
|
const (
|
||||||
|
NameCreate = "create"
|
||||||
|
NameUpdate = "update"
|
||||||
|
NameDelete = "delete"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Action statuses: finished once the change is committed, failed (with
|
||||||
|
// Exception) when it was attempted but rolled back.
|
||||||
|
const (
|
||||||
|
StatusFinished = "finished"
|
||||||
|
StatusFailed = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// orderTypeSber is the type value of Sber orders, matched case-insensitively
|
||||||
|
// like visamaster and visamasterpay do.
|
||||||
|
const orderTypeSber = "sber"
|
||||||
|
|
||||||
|
var nameLabels = map[string]shared.LocalizedText{
|
||||||
|
NameCreate: {Tm: "Goşmak", Ru: "Создание", En: "Create"},
|
||||||
|
NameUpdate: {Tm: "Üýtgetmek", Ru: "Изменение", En: "Update"},
|
||||||
|
NameDelete: {Tm: "Pozmak", Ru: "Удаление", En: "Delete"},
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
sberTargetLabel = shared.LocalizedText{Tm: "Sber töleg (talyplar üçin)", Ru: "Оплата Sber (для студентов)", En: "Sber payment (for students)"}
|
||||||
|
visaMasterTargetLabel = shared.LocalizedText{Tm: "Visa/Master töleg (talyplar üçin)", Ru: "Оплата Visa/Master (для студентов)", En: "Visa/Master payment (for students)"}
|
||||||
|
)
|
||||||
|
|
||||||
|
// NameLabel is the display name of an action name; unknown names fall
|
||||||
|
// back to the name itself.
|
||||||
|
func NameLabel(name string) shared.LocalizedText {
|
||||||
|
if label, ok := nameLabels[name]; ok {
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
return shared.LocalizedText{Tm: name, Ru: name, En: name}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TargetLabel is the display name of the order an action was done to,
|
||||||
|
// by the order's (current) type.
|
||||||
|
func TargetLabel(orderType *string) shared.LocalizedText {
|
||||||
|
if orderType != nil && strings.EqualFold(strings.TrimSpace(*orderType), orderTypeSber) {
|
||||||
|
return sberTargetLabel
|
||||||
|
}
|
||||||
|
return visaMasterTargetLabel
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrderActionTargetDTO is the order an action was done to - Amalyň
|
||||||
|
// nyşany (targedi), e.g. "TB6312-14083 (Sber töleg (talyplar üçin))".
|
||||||
|
type OrderActionTargetDTO struct {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
UniqueId *string `json:"uniqueId"`
|
||||||
|
Type *string `json:"type"`
|
||||||
|
Label shared.LocalizedText `json:"label"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrderActionDTO is one row of an order's "Ammallar" table. CreatedById is
|
||||||
|
// null (and CreatedByName empty) when no user started the action - the
|
||||||
|
// GBÜS callback finalizing a payment.
|
||||||
|
type OrderActionDTO struct {
|
||||||
|
Id int64 `json:"id"`
|
||||||
|
OrderId int64 `json:"orderId"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
NameLabel shared.LocalizedText `json:"nameLabel"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Target OrderActionTargetDTO `json:"target"`
|
||||||
|
CreatedById *int64 `json:"createdById"`
|
||||||
|
CreatedByName string `json:"createdByName"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrderActionDetailDTO is a single action with what it changed - the list
|
||||||
|
// leaves these out so pages stay small. Original holds the changed
|
||||||
|
// columns' values before the action and Changes their values after (or,
|
||||||
|
// for a failed action, the values it attempted); either is null when
|
||||||
|
// there's nothing on that side (Original for a create, Changes for a
|
||||||
|
// delete).
|
||||||
|
type OrderActionDetailDTO struct {
|
||||||
|
OrderActionDTO
|
||||||
|
Original json.RawMessage `json:"original" swaggertype:"object"`
|
||||||
|
Changes json.RawMessage `json:"changes" swaggertype:"object"`
|
||||||
|
Exception *string `json:"exception"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListOrderActionDTO struct {
|
||||||
|
Count int64 `json:"count"`
|
||||||
|
Actions []OrderActionDTO `json:"actions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateOrderActionDTO is one action to record, written by the
|
||||||
|
// repositories that change orders (cards/visamaster, payment/visamasterpay)
|
||||||
|
// - never through the API.
|
||||||
|
type CreateOrderActionDTO struct {
|
||||||
|
OrderId int64
|
||||||
|
Name string
|
||||||
|
Status string
|
||||||
|
Original map[string]interface{}
|
||||||
|
Changes map[string]interface{}
|
||||||
|
Exception *string
|
||||||
|
CreatedBy *int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListFilter struct {
|
||||||
|
OrderId int64
|
||||||
|
Page int
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package visamasteractions
|
||||||
|
|
||||||
|
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 = "/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}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register only wires read endpoints: actions are recorded by the
|
||||||
|
// repositories that change orders, never through the API. The group is
|
||||||
|
// its own /:id/actions prefix because rbac allows one policy per prefix
|
||||||
|
// and cards/visamaster already declares require:cards for baseURL.
|
||||||
|
func (h *handler) Register(router *gin.RouterGroup) {
|
||||||
|
group := rbac.Group(router, baseURL+"/:id/actions", rbac.RequireStaff(perm.Cards))
|
||||||
|
group.GET("", h.list)
|
||||||
|
group.GET("/:actionId", h.get)
|
||||||
|
}
|
||||||
|
|
||||||
|
// list godoc
|
||||||
|
// @Summary Sargydyň amallary (Ammallar)
|
||||||
|
// @Description Bir Visa/Master ýa-da Sber sargydynyň ähli amallaryny gaýtarýar: goşmak, üýtgetmek, pozmak (name/nameLabel), kim tarapyndan (createdByName), haýsy sargyt (target: uniqueId we label, mysal üçin "Sber töleg (talyplar üçin)"), statusy (finished ýa-da failed) we senesi. Tertip: iň täzesi birinji. Bellik: näme üýtgändigi (original/changes) we ýalňyşlyk (exception) /visa-master-payment-orders/{id}/actions/{actionId} salgysynda; töleg tamamlananda sargydyň status/paid üýtgemegi hem şu ýere ýazylýar, GBÜS callback-dan gelse createdById null.
|
||||||
|
// @Tags visa-master-order-actions
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Sargyt ID-si"
|
||||||
|
// @Param page query int false "Sahypa belgisi" default(1)
|
||||||
|
// @Param limit query int false "Bir sahypadaky ýazgy sany" default(10)
|
||||||
|
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} ListOrderActionDTO
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 403 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /visa-master-payment-orders/{id}/actions [get]
|
||||||
|
func (h *handler) list(c *gin.Context) {
|
||||||
|
orderID, ok := shared.ParseID(c.Param("id"))
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, limit, ok := shared.ParsePageLimit(c)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !h.guardOrder(c, orderID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := h.repository.List(c.Request.Context(), ListFilter{OrderId: orderID, Page: page, Limit: limit})
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Errorf("list visa master order actions failed (order %d): %v", orderID, err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
// get godoc
|
||||||
|
// @Summary Sargydyň bir amaly
|
||||||
|
// @Description Sargydyň bir amalyny näme üýtgändigi bilen gaýtarýar: original - üýtgän meýdanlaryň öňki bahalary (Asyl), changes - täze bahalary (Üýtgeşmeler), exception - şowsuz amalyň ýalňyşlygy. Tertip: ýeke ýazgy. Bellik: goşmakda original null we changes ähli meýdanlar, pozmakda original ähli meýdanlar we changes null; şowsuz amalda changes synanyşylan bahalar.
|
||||||
|
// @Tags visa-master-order-actions
|
||||||
|
// @Produce json
|
||||||
|
// @Security BearerAuth
|
||||||
|
// @Param id path int true "Sargyt ID-si"
|
||||||
|
// @Param actionId path int true "Amalyň ID-si"
|
||||||
|
// @Param lang query string false "Lokallaşdyrylan meýdanlaryň dili; all - doly {en, ru, tm} obýektleri" Enums(tm, ru, en, all) default(tm)
|
||||||
|
// @Success 200 {object} OrderActionDetailDTO
|
||||||
|
// @Failure 400 {object} appresult.AppError
|
||||||
|
// @Failure 403 {object} appresult.AppError
|
||||||
|
// @Failure 404 {object} appresult.AppError
|
||||||
|
// @Failure 500 {object} appresult.AppError
|
||||||
|
// @Router /visa-master-payment-orders/{id}/actions/{actionId} [get]
|
||||||
|
func (h *handler) get(c *gin.Context) {
|
||||||
|
orderID, ok := shared.ParseID(c.Param("id"))
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actionID, ok := shared.ParseID(c.Param("actionId"))
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !h.guardOrder(c, orderID) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
item, err := h.repository.GetByID(c.Request.Context(), orderID, actionID)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Errorf("get visa master order action failed (order %d, action %d): %v", orderID, actionID, err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *handler) guardOrder(c *gin.Context, orderID int64) bool {
|
||||||
|
if rbac.SkipRecordGuard(c) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
userID, branchID, err := h.repository.OwnerInfo(c.Request.Context(), orderID)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
h.logger.Errorf("visa master order actions owner lookup failed (order %d): %v", orderID, err)
|
||||||
|
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return rbac.GuardOrder(c, userID, branchID)
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package visamasteractions
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type Repository interface {
|
||||||
|
// OwnerInfo returns the order's owner/branch so the handler can run
|
||||||
|
// rbac.GuardOrder without importing cards/visamaster. Deleted orders
|
||||||
|
// are included: their actions stay readable.
|
||||||
|
OwnerInfo(ctx context.Context, orderID int64) (userID *int64, branchID int64, err error)
|
||||||
|
List(ctx context.Context, filter ListFilter) (ListOrderActionDTO, error)
|
||||||
|
// GetByID returns orderID's action actionID - pgx.ErrNoRows if it
|
||||||
|
// belongs to another order.
|
||||||
|
GetByID(ctx context.Context, orderID, actionID int64) (OrderActionDetailDTO, error)
|
||||||
|
}
|
||||||
@@ -16,7 +16,9 @@ type Config struct {
|
|||||||
Port string `yaml:"port" env-default:"8080"`
|
Port string `yaml:"port" env-default:"8080"`
|
||||||
} `yaml:"listen"`
|
} `yaml:"listen"`
|
||||||
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
||||||
|
PublicBaseURL string `yaml:"public_base_url" env-required:"true"`
|
||||||
Storage StorageConfig `yaml:"storage"`
|
Storage StorageConfig `yaml:"storage"`
|
||||||
|
Minio MinioConfig `yaml:"minio"`
|
||||||
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
||||||
AppVersion string `yaml:"app_version" env-required:"true"`
|
AppVersion string `yaml:"app_version" env-required:"true"`
|
||||||
}
|
}
|
||||||
@@ -30,6 +32,14 @@ type StorageConfig struct {
|
|||||||
Password string `yaml:"password"`
|
Password string `yaml:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type MinioConfig struct {
|
||||||
|
Endpoint string `yaml:"endpoint" env-required:"true"`
|
||||||
|
AccessKey string `yaml:"access_key" env-required:"true"`
|
||||||
|
SecretKey string `yaml:"secret_key" env-required:"true"`
|
||||||
|
Bucket string `yaml:"bucket" env-required:"true"`
|
||||||
|
UseSSL bool `yaml:"use_ssl" env-default:"false"`
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
instance *Config
|
instance *Config
|
||||||
once sync.Once
|
once sync.Once
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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"`
|
||||||
|
}
|
||||||
Loaded 100 of 581 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user