Files
online-backend/internal/dashboard/handler.go
GuwandykA f1337706f0
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
swagger: document the ?lang= query parameter on every admin endpoint
appresult.Localize applies to all /api/admin routes, so each handler's
godoc now declares lang (tm, ru, en, all; default tm) and Swagger UI
offers it as a dropdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:08:32 +05:00

152 lines
4.5 KiB
Go

package dashboard
import (
"net/http"
"strconv"
"time"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/pkg/logging"
"online-back/pkg/sysstats"
"github.com/gin-gonic/gin"
)
const baseURL = "/dashboard"
const (
defaultRecentLimit = 10
maxRecentLimit = 50
)
type handler struct {
logger *logging.Logger
repository Repository
// diskPaths are the mount points reported by /server-stats.
diskPaths []string
}
func NewHandler(logger *logging.Logger, repository Repository, diskPaths []string) handlers.Handler {
return &handler{logger: logger, repository: repository, diskPaths: diskPaths}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard))
group.GET("/overview", h.overview)
group.GET("/server-stats", h.serverStats)
}
// overview godoc
// @Summary Dashboard overview
// @Description Returns the KPI cards, loan/card trend, loan status breakdown, weekly order counts, and recent activity feed for the admin dashboard
// @Tags dashboard
// @Produce json
// @Security BearerAuth
// @Param year query int false "Year for the monthly trend chart" default(current year)
// @Param recent_limit query int false "Number of recent activity items to return" default(10)
// @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/overview [get]
func (h *handler) overview(c *gin.Context) {
filter, ok := parseOverviewFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.Overview(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("dashboard overview failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
redactByPermission(&result, rbac.Can(c, perm.Cards), rbac.Can(c, perm.Loans))
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// serverStats godoc
// @Summary Server statistics
// @Description Returns host CPU, RAM and disk usage plus the API process's own memory and uptime. CPU usage is sampled over ~250ms; host fields are null when the OS cannot report them.
// @Tags dashboard
// @Produce json
// @Security BearerAuth
// @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{data=sysstats.Stats}
// @Failure 500 {object} appresult.AppError
// @Router /dashboard/server-stats [get]
func (h *handler) serverStats(c *gin.Context) {
stats, err := sysstats.Collect(c.Request.Context(), h.diskPaths)
if err != nil {
h.logger.Errorf("dashboard server stats failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(stats))
}
func parseOverviewFilter(c *gin.Context) (OverviewFilter, bool) {
filter := OverviewFilter{
Year: time.Now().Year(),
RecentLimit: defaultRecentLimit,
}
if raw := c.Query("year"); raw != "" {
year, err := strconv.Atoi(raw)
if err != nil || year < 2000 || year > 2100 {
return OverviewFilter{}, false
}
filter.Year = year
}
if raw := c.Query("recent_limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 {
return OverviewFilter{}, false
}
if limit > maxRecentLimit {
limit = maxRecentLimit
}
filter.RecentLimit = limit
}
rbac.BindBranchIDs(c, &filter.BranchIds)
return filter, true
}
// redactByPermission blanks the widgets of modules the caller cannot open, so
// e.g. a head of loans sees every branch's loan numbers but no card numbers.
func redactByPermission(o *OverviewDTO, cards, loans bool) {
if !cards {
o.Stats.ActiveCards = StatMetricDTO{}
o.Stats.OnlinePayments = StatMetricDTO{}
}
if !loans {
o.Stats.LoanOrders = StatMetricDTO{}
o.LoanStatus = []LoanStatusShareDTO{}
o.RecentActivity = []RecentActivityDTO{}
}
for i := range o.Trend.Points {
if !cards {
o.Trend.Points[i].Cards = 0
}
if !loans {
o.Trend.Points[i].Loans = 0
}
}
for i := range o.WeeklyOrders {
if !cards {
o.WeeklyOrders[i].Cards = 0
}
if !loans {
o.WeeklyOrders[i].Loans = 0
}
}
}