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>
394 lines
12 KiB
Go
394 lines
12 KiB
Go
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()
|
|
}
|