package analytics import ( "net/http" "strconv" "time" "online-back/internal/appresult" "online-back/internal/handlers" "online-back/internal/identity/rbac" "online-back/internal/identity/rbac/perm" "online-back/pkg/logging" "github.com/gin-gonic/gin" ) // Lives under the dashboard URL but is its own module; rbac picks the // longest registered prefix, so this group's policy applies here. const baseURL = "/dashboard/analytics" const ( dateLayout = "2006-01-02" maxRangeDays = 366 * 3 defaultOperatorLimit = 10 maxOperatorLimit = 50 ) type handler struct { logger *logging.Logger repository Repository } func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler { return &handler{logger: logger, repository: repository} } func (h *handler) Register(router *gin.RouterGroup) { group := rbac.Group(router, baseURL, rbac.RequireStaff(perm.Dashboard)) group.GET("/finance", h.finance) group.GET("/backlog", h.backlog) group.GET("/branches", h.branches) group.GET("/products", h.products) group.GET("/customers", h.customers) group.GET("/system", h.system) } // finance godoc // @Summary Dashboard analytics: finance // @Description Successful visa/master payouts (amount, bank/GBÜS/TVEB fees), gateway status breakdown and success rate, monthly payout totals, and the total loan amount requested. Payouts need the cards permission, the loan total the loans permission. // @Tags dashboard-analytics // @Produce json // @Security BearerAuth // @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year) // @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /dashboard/analytics/finance [get] func (h *handler) finance(c *gin.Context) { filter, ok := h.parseFilter(c) if !ok { return } result, err := h.repository.Finance(c.Request.Context(), filter) if err != nil { h.fail(c, "finance", err) return } if !rbac.Can(c, perm.Cards) { result.Payments = PaymentTotalsDTO{} result.Gateway = []CountDTO{} result.GatewaySuccessRate = nil result.Monthly = []FinanceMonthDTO{} } if !rbac.Can(c, perm.Loans) { result.LoanRequested = LoanRequestedDTO{} } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // backlog godoc // @Summary Dashboard analytics: backlog // @Description Open (unhandled) orders per order type aged under 1 day / 1-3 days / over 3 days, the oldest open order, and the average processing time of orders finished in range; plus exact visa/master payout timing from the payment log. Order types are limited to the modules the caller can open. // @Tags dashboard-analytics // @Produce json // @Security BearerAuth // @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year) // @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /dashboard/analytics/backlog [get] func (h *handler) backlog(c *gin.Context) { filter, ok := h.parseFilter(c) if !ok { return } result, err := h.repository.Backlog(c.Request.Context(), filter) if err != nil { h.fail(c, "backlog", err) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // branches godoc // @Summary Dashboard analytics: branches // @Description Per-branch leaderboard (orders per type, open/approved/rejected, approval rate, average processing hours) and order counts per region, for orders created in range. // @Tags dashboard-analytics // @Produce json // @Security BearerAuth // @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year) // @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /dashboard/analytics/branches [get] func (h *handler) branches(c *gin.Context) { filter, ok := h.parseFilter(c) if !ok { return } result, err := h.repository.Branches(c.Request.Context(), filter) if err != nil { h.fail(c, "branches", err) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // products godoc // @Summary Dashboard analytics: products // @Description Loan orders by source (web/mobile) and loan type, card orders by card type, and paid vs unpaid card orders, for orders created in range. // @Tags dashboard-analytics // @Produce json // @Security BearerAuth // @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year) // @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /dashboard/analytics/products [get] func (h *handler) products(c *gin.Context) { filter, ok := h.parseFilter(c) if !ok { return } result, err := h.repository.Products(c.Request.Context(), filter) if err != nil { h.fail(c, "products", err) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // customers godoc // @Summary Dashboard analytics: customers // @Description Loan applicants in range by age group, education, marriage status and number of guarantors, each with its approval rate. Needs the loans permission. // @Tags dashboard-analytics // @Produce json // @Security BearerAuth // @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year) // @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /dashboard/analytics/customers [get] func (h *handler) customers(c *gin.Context) { filter, ok := h.parseFilter(c) if !ok { return } result, err := h.repository.Customers(c.Request.Context(), filter) if err != nil { h.fail(c, "customers", err) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } // system godoc // @Summary Dashboard analytics: system // @Description Registration funnel (all-scope callers with the users permission), operator activity and error rate per module (activity-logs permission), order peak hours heatmap in Ashgabat time, and card balance check stats (cards permission). Widgets the caller cannot see are null or empty. // @Tags dashboard-analytics // @Produce json // @Security BearerAuth // @Param from query string false "Start date YYYY-MM-DD (inclusive)" default(Jan 1 of current year) // @Param to query string false "End date YYYY-MM-DD (inclusive)" default(today) // @Param operator_limit query int false "Number of operators to return" default(10) // @Success 200 {object} appresult.AppSuccess // @Failure 400 {object} appresult.AppError // @Failure 500 {object} appresult.AppError // @Router /dashboard/analytics/system [get] func (h *handler) system(c *gin.Context) { filter, ok := h.parseFilter(c) if !ok { return } opts := SystemOptions{ // Registrations are not tied to a branch, so branch-scope callers // would otherwise see bank-wide numbers. Registration: rbac.Can(c, perm.Users) && len(filter.BranchIds) == 0, Operators: rbac.Can(c, perm.ActivityLogs), CardBalances: rbac.Can(c, perm.Cards), OperatorLimit: defaultOperatorLimit, } if raw := c.Query("operator_limit"); raw != "" { limit, err := strconv.Atoi(raw) if err != nil || limit < 1 { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return } opts.OperatorLimit = min(limit, maxOperatorLimit) } result, err := h.repository.System(c.Request.Context(), filter, opts) if err != nil { h.fail(c, "system", err) return } c.JSON(http.StatusOK, appresult.SuccessWithData(result)) } func (h *handler) fail(c *gin.Context, widget string, err error) { h.logger.Errorf("dashboard analytics %s failed: %v", widget, err) c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer) } // parseFilter reads from/to (inclusive dates, default: this year so far), // the caller's branch scope, and the order types their permissions allow. // It writes the 400 itself and returns false on bad input. func (h *handler) parseFilter(c *gin.Context) (Filter, bool) { now := time.Now().UTC() today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC) from := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, time.UTC) to := today var err error if raw := c.Query("from"); raw != "" { if from, err = time.Parse(dateLayout, raw); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return Filter{}, false } } if raw := c.Query("to"); raw != "" { if to, err = time.Parse(dateLayout, raw); err != nil { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return Filter{}, false } } if to.Before(from) || to.Sub(from) > maxRangeDays*24*time.Hour { c.JSON(http.StatusBadRequest, appresult.ErrMissingParam) return Filter{}, false } filter := Filter{From: from, To: to.AddDate(0, 0, 1)} if rbac.Can(c, perm.Loans) { filter.Types = append(filter.Types, OrderLoan, OrderLoanLetter) } if rbac.Can(c, perm.Cards) { filter.Types = append(filter.Types, OrderCard, OrderCardPin, OrderCardRekwizit, OrderVisaMaster) } rbac.BindBranchIDs(c, &filter.BranchIds) return filter, true }