diff --git a/.DS_Store b/.DS_Store index 3883513..a6b506a 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/Screenshot 2026-09-30 at 16.08.20.png b/Screenshot 2026-09-30 at 16.08.20.png deleted file mode 100644 index acb17f5..0000000 Binary files a/Screenshot 2026-09-30 at 16.08.20.png and /dev/null differ diff --git a/db/migrations/20260702125108_init.down.sql b/db/migrations/20260702125108_init.down.sql index 75adccd..837f3f6 100644 --- a/db/migrations/20260702125108_init.down.sql +++ b/db/migrations/20260702125108_init.down.sql @@ -1,3 +1,4 @@ +DROP TABLE IF EXISTS payment_texts; DROP TABLE IF EXISTS rbac_version; DROP FUNCTION IF EXISTS rbac_bump_version() CASCADE; diff --git a/db/migrations/20260702125108_init.up.sql b/db/migrations/20260702125108_init.up.sql index ab5671e..139af9f 100644 --- a/db/migrations/20260702125108_init.up.sql +++ b/db/migrations/20260702125108_init.up.sql @@ -644,6 +644,30 @@ CREATE TABLE IF NOT EXISTS visa_master_payment_logs ( CREATE INDEX IF NOT EXISTS visa_master_payment_logs_order_id_idx ON visa_master_payment_logs (order_id); +-- 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. diff --git a/internal/analytics/db/postgresql.go b/internal/analytics/db/postgresql.go new file mode 100644 index 0000000..c785a1d --- /dev/null +++ b/internal/analytics/db/postgresql.go @@ -0,0 +1,909 @@ +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 >= $x AND < $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 = 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` + +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, `coalesce(nullif(trim(education), ''), 'unknown')`); err != nil { + return out, err + } + if out.MarriageStatus, err = r.loanApprovalBy(ctx, f, `coalesce(nullif(trim(marriage_status), ''), 'unknown')`); 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"}) + + for _, g := range out.AgeGroups { + out.Total += g.Count + } + return out, nil +} + +// loanApprovalBy groups loan orders in range by keyExpr with approved and +// rejected 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') + 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); 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 +} diff --git a/internal/analytics/dto.go b/internal/analytics/dto.go new file mode 100644 index 0000000..212beac --- /dev/null +++ b/internal/analytics/dto.go @@ -0,0 +1,212 @@ +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, 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"` + ApprovalRate *float64 `json:"approvalRate"` +} + +type CustomersDTO struct { + Total int64 `json:"total"` + 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"` +} diff --git a/internal/analytics/handler.go b/internal/analytics/handler.go new file mode 100644 index 0000000..5b4cb48 --- /dev/null +++ b/internal/analytics/handler.go @@ -0,0 +1,266 @@ +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 +} diff --git a/internal/analytics/storage.go b/internal/analytics/storage.go new file mode 100644 index 0000000..2d5d5d0 --- /dev/null +++ b/internal/analytics/storage.go @@ -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 +} diff --git a/internal/handlers/manager/manager.go b/internal/handlers/manager/manager.go index b81f086..3b0c623 100755 --- a/internal/handlers/manager/manager.go +++ b/internal/handlers/manager/manager.go @@ -5,6 +5,8 @@ import ( "net/http" "path/filepath" + "online-back/internal/analytics" + analyticsdb "online-back/internal/analytics/db" "online-back/internal/backup" backupdb "online-back/internal/backup/db" "online-back/internal/cards" @@ -79,6 +81,7 @@ func New(cfg *config.Config, client *pgxpool.Pool, logger *logging.Logger) *gin. payment.Register(adminGroup, client, logger, currencyRepo, paymentGatewayClient(cfg, logger), cfg.PublicBaseURL) currency.NewHandler(logger, currencyRepo).Register(adminGroup) dashboard.NewHandler(logger, dashboarddb.NewRepository(client, logger)).Register(adminGroup) + analytics.NewHandler(logger, analyticsdb.NewRepository(client, logger)).Register(adminGroup) backupDir := filepath.Join(cfg.PublicFilePath, "backups") backupSvc := backup.NewService(