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

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

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

View File

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

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

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

View File

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

View File

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