feat(admin): per-user finance panel — balances, benefits, risk, ledger
CI / changes (pull_request) Successful in 4s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 28s
CI / ui (pull_request) Has been skipped
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m46s
CI / changes (pull_request) Successful in 4s
CI / unit (pull_request) Successful in 11s
CI / integration (pull_request) Successful in 28s
CI / ui (pull_request) Has been skipped
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m46s
The /_gm user card gains a Finance panel: an account's chip balances per funding segment, benefits per origin (hints, no-ads until/forever), the recorded refund risk (abuse flag + floor-0 loss), and the append-only ledger history newest-first. Backed by a new payments.AccountStatement read straight from the materialized tables + the ledger (uncached — an admin, rare view). Folds the agreed admin / reports / catalog plan into PLAN.md (the PR stack: this panel, then the catalog editor, admin grant, refund + ledger export) and moves the tournament-entry storage design to the tournament stage.
This commit is contained in:
@@ -63,6 +63,28 @@
|
||||
<div><button type="submit">{{if .Suspension.Blocked}}Re-block{{else}}Block{{end}}</button></div>
|
||||
</form>
|
||||
</section>
|
||||
<section class="panel"><h2>Finance</h2>
|
||||
{{if .Finance.Present}}
|
||||
{{if or .Finance.Segments .Finance.Benefits .Finance.Abuse .Finance.Loss}}
|
||||
<ul class="kv">
|
||||
{{range .Finance.Segments}}<li><b>Chips ({{.Source}})</b> {{.Chips}}</li>{{end}}
|
||||
{{range .Finance.Benefits}}<li><b>Benefits ({{.Origin}})</b> {{.Hints}} hints{{if .Forever}} · no-ads forever{{else if .AdsUntil}} · no-ads until {{.AdsUntil}} (UTC){{end}}</li>{{end}}
|
||||
{{if or .Finance.Abuse .Finance.Loss}}<li><b>Refund risk</b> <span class="warn">{{if .Finance.Abuse}}abuse-flagged{{end}}{{if .Finance.Loss}} · loss {{.Finance.Loss}} chips{{end}}</span></li>{{end}}
|
||||
</ul>
|
||||
{{else}}<p class="note">no balances or benefits</p>{{end}}
|
||||
<h3>Ledger</h3>
|
||||
{{if .Finance.Ledger}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Time</th><th>Kind</th><th>Source</th><th>Origin</th><th>Chips</th><th>Order</th><th>Provider</th><th>Detail</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Finance.Ledger}}
|
||||
<tr><td>{{.At}}</td><td>{{.Kind}}</td><td>{{.Source}}</td><td>{{.Origin}}</td><td>{{.ChipsDelta}}</td><td>{{if .Order}}<code>{{.Order}}</code>{{end}}</td><td>{{.Provider}}</td><td>{{if .Snapshot}}<code>{{.Snapshot}}</code>{{end}}</td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}<p class="note">no ledger entries</p>{{end}}
|
||||
{{else}}<p class="note">payments not enabled</p>{{end}}
|
||||
</section>
|
||||
<section class="panel"><h2>Roles</h2>
|
||||
{{$id := .ID}}
|
||||
{{if .Roles}}
|
||||
|
||||
@@ -195,6 +195,52 @@ type UserDetailView struct {
|
||||
Blocks []RelationRow
|
||||
BlockedBy []RelationRow
|
||||
Friends []RelationRow
|
||||
// Finance is the account's payments picture (balances, benefits, refund risk, ledger). Present
|
||||
// is false when the payments domain is unwired.
|
||||
Finance FinanceView
|
||||
}
|
||||
|
||||
// FinanceView is the account's payments picture on the user card: chip balances per funding
|
||||
// segment, benefits per origin, the recorded refund risk, and the append-only ledger history
|
||||
// (newest first). Present is false when the payments domain is unwired.
|
||||
type FinanceView struct {
|
||||
Present bool
|
||||
Segments []SegmentRow
|
||||
Benefits []BenefitRow
|
||||
// Abuse is the refund abuse flag; Loss is the unrecoverable chip loss from floor-0 refunds.
|
||||
Abuse bool
|
||||
Loss int
|
||||
Ledger []LedgerRow
|
||||
}
|
||||
|
||||
// SegmentRow is one funding segment's chip balance.
|
||||
type SegmentRow struct {
|
||||
Source string
|
||||
Chips int
|
||||
}
|
||||
|
||||
// BenefitRow is one origin's benefit: the hint wallet, the ad-free expiry (pre-formatted, empty
|
||||
// when none) and the lifetime ad-free flag.
|
||||
type BenefitRow struct {
|
||||
Origin string
|
||||
Hints int
|
||||
AdsUntil string
|
||||
Forever bool
|
||||
}
|
||||
|
||||
// LedgerRow is one append-only ledger entry: its kind, funding source / benefit origin, signed chip
|
||||
// delta, the product / order / provider it references (empty when none), the raw snapshot JSON and
|
||||
// the pre-formatted time.
|
||||
type LedgerRow struct {
|
||||
Kind string
|
||||
Source string
|
||||
Origin string
|
||||
ChipsDelta int
|
||||
Product string
|
||||
Order string
|
||||
Provider string
|
||||
Snapshot string
|
||||
At string
|
||||
}
|
||||
|
||||
// RelationRow is one cross-linked account in the user card's blocks / blocked-by / friends
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//go:build integration
|
||||
|
||||
package inttest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/payments"
|
||||
)
|
||||
|
||||
// TestAccountStatement checks the admin financial statement: a funded pack shows as a chip segment
|
||||
// + a fund ledger row, an admin grant as a benefit + an admin_grant row, the ledger is newest-first,
|
||||
// and a clean account carries no refund risk.
|
||||
func TestAccountStatement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newPaymentsService()
|
||||
acc := uuid.New()
|
||||
|
||||
// A funded pack: 100 chips to the direct segment + a fund ledger row.
|
||||
prod := seedPackProduct(t, 100, methodPrice{method: "direct", currency: "RUB", amount: 14900})
|
||||
res, err := svc.CreateOrder(ctx, acc, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
|
||||
if err != nil {
|
||||
t.Fatalf("create order: %v", err)
|
||||
}
|
||||
paid, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
|
||||
if _, err := svc.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), paid); err != nil {
|
||||
t.Fatalf("fund: %v", err)
|
||||
}
|
||||
// An admin grant: 5 hints to the direct origin + an admin_grant ledger row.
|
||||
if err := svc.Grant(ctx, acc, payments.SourceDirect, 5, 0, false); err != nil {
|
||||
t.Fatalf("grant: %v", err)
|
||||
}
|
||||
|
||||
stmt, err := svc.AccountStatement(ctx, acc)
|
||||
if err != nil {
|
||||
t.Fatalf("statement: %v", err)
|
||||
}
|
||||
|
||||
if len(stmt.Segments) != 1 || stmt.Segments[0].Source != payments.SourceDirect || stmt.Segments[0].Chips != 100 {
|
||||
t.Fatalf("segments = %+v, want 100 chips on direct", stmt.Segments)
|
||||
}
|
||||
if len(stmt.Benefits) != 1 || stmt.Benefits[0].Origin != payments.SourceDirect || stmt.Benefits[0].Hints != 5 {
|
||||
t.Fatalf("benefits = %+v, want 5 hints on direct", stmt.Benefits)
|
||||
}
|
||||
if len(stmt.Ledger) != 2 {
|
||||
t.Fatalf("ledger rows = %d, want 2 (fund + admin_grant)", len(stmt.Ledger))
|
||||
}
|
||||
// Newest-first ordering (the grant is the later write).
|
||||
if stmt.Ledger[0].CreatedAt.Before(stmt.Ledger[1].CreatedAt) {
|
||||
t.Error("ledger is not newest-first")
|
||||
}
|
||||
kinds := map[string]int{}
|
||||
for _, e := range stmt.Ledger {
|
||||
kinds[e.Kind]++
|
||||
if e.Kind == "fund" && e.ChipsDelta != 100 {
|
||||
t.Errorf("fund chips delta = %d, want 100", e.ChipsDelta)
|
||||
}
|
||||
}
|
||||
if kinds["fund"] != 1 || kinds["admin_grant"] != 1 {
|
||||
t.Fatalf("ledger kinds = %v, want one fund + one admin_grant", kinds)
|
||||
}
|
||||
if stmt.Risk.Present {
|
||||
t.Errorf("risk = %+v, want none for a clean account", stmt.Risk)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConsoleFinancePanel checks the user card renders the finance panel: a funded pack + an admin
|
||||
// grant surface as the segment balance, the benefit and the ledger rows.
|
||||
func TestConsoleFinancePanel(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
srv, _, pay := bannerServer(t)
|
||||
id := provisionAccount(t)
|
||||
|
||||
prod := seedPackProduct(t, 100, methodPrice{method: "direct", currency: "RUB", amount: 14900})
|
||||
res, err := pay.CreateOrder(ctx, id, payments.NewContext("direct", "web"), []payments.Source{payments.SourceDirect}, prod, "robokassa")
|
||||
if err != nil {
|
||||
t.Fatalf("create order: %v", err)
|
||||
}
|
||||
paid, _ := payments.MoneyFromMinor(14900, payments.CurrencyRUB)
|
||||
if _, err := pay.Fund(ctx, res.OrderID, "robokassa", res.OrderID.String(), paid); err != nil {
|
||||
t.Fatalf("fund: %v", err)
|
||||
}
|
||||
if err := pay.Grant(ctx, id, payments.SourceDirect, 5, 0, false); err != nil {
|
||||
t.Fatalf("grant: %v", err)
|
||||
}
|
||||
|
||||
code, body := consoleDo(srv.Handler(), http.MethodGet, "http://admin.test/_gm/users/"+id.String(), "", "")
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("user card = %d, want 200", code)
|
||||
}
|
||||
for _, want := range []string{"Finance", "Chips (direct)", "Benefits (direct)", "5 hints", "admin_grant", "fund"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("finance panel missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Statement is an account's full financial picture for the admin console: chip balances per funding
|
||||
// segment, benefits per origin, the recorded refund risk, and the append-only ledger history
|
||||
// (newest first). Read straight from the materialized tables + the ledger, uncached — an admin-only,
|
||||
// rare view, not a hot path.
|
||||
type Statement struct {
|
||||
Segments []SegmentChips
|
||||
Benefits []OriginBenefit
|
||||
Risk RiskInfo
|
||||
Ledger []LedgerEntry
|
||||
}
|
||||
|
||||
// SegmentChips is one funding segment's chip balance.
|
||||
type SegmentChips struct {
|
||||
Source Source
|
||||
Chips int
|
||||
}
|
||||
|
||||
// OriginBenefit is one origin's benefit state: the hint wallet, the ad-free term (zero AdsPaidUntil
|
||||
// when none) and the lifetime ad-free flag.
|
||||
type OriginBenefit struct {
|
||||
Origin Source
|
||||
Hints int
|
||||
AdsPaidUntil time.Time
|
||||
AdsForever bool
|
||||
}
|
||||
|
||||
// RiskInfo is the account's recorded refund risk: whether it is abuse-flagged and the unrecoverable
|
||||
// chip loss accumulated by floor-0 refunds. Present is false when the account has no risk row.
|
||||
type RiskInfo struct {
|
||||
Present bool
|
||||
Abuse bool
|
||||
LossChips int
|
||||
}
|
||||
|
||||
// LedgerEntry is one append-only ledger row projected for the report. The string ids are empty when
|
||||
// the column is NULL; Snapshot is the raw purchase/refund JSON (empty when none).
|
||||
type LedgerEntry struct {
|
||||
Kind string
|
||||
Source string
|
||||
Origin string
|
||||
ChipsDelta int
|
||||
ProductID string
|
||||
OrderID string
|
||||
Provider string
|
||||
ProviderPaymentID string
|
||||
Snapshot string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// AccountStatement assembles the account's financial picture (segments, benefits, risk, full ledger
|
||||
// history) for the admin console, straight from the materialized tables and the ledger (uncached).
|
||||
func (s *Service) AccountStatement(ctx context.Context, accountID uuid.UUID) (Statement, error) {
|
||||
return s.store.accountStatement(ctx, accountID)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package payments
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-jet/jet/v2/postgres"
|
||||
"github.com/go-jet/jet/v2/qrm"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/postgres/jet/payments/model"
|
||||
"scrabble/backend/internal/postgres/jet/payments/table"
|
||||
)
|
||||
|
||||
// statementOrder is the fixed segment/origin ordering the report renders, so the panel is stable
|
||||
// (the balance/benefit maps iterate randomly).
|
||||
var statementOrder = []Source{SourceDirect, SourceVK, SourceTelegram}
|
||||
|
||||
// accountStatement reads the account's balances, benefits, refund risk and full ledger history for
|
||||
// the admin report. Uncached and outside any transaction — an operator view, not a hot path.
|
||||
func (s *Store) accountStatement(ctx context.Context, accountID uuid.UUID) (Statement, error) {
|
||||
st, err := s.loadState(ctx, accountID)
|
||||
if err != nil {
|
||||
return Statement{}, err
|
||||
}
|
||||
var out Statement
|
||||
for _, src := range statementOrder {
|
||||
if chips, ok := st.chips[src]; ok {
|
||||
out.Segments = append(out.Segments, SegmentChips{Source: src, Chips: chips})
|
||||
}
|
||||
if b, ok := st.benefits[src]; ok {
|
||||
out.Benefits = append(out.Benefits, OriginBenefit{
|
||||
Origin: src, Hints: b.hints, AdsPaidUntil: derefTime(b.adsPaidUntil), AdsForever: b.adsForever,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var risk model.AccountRisk
|
||||
err = postgres.SELECT(table.AccountRisk.AllColumns).
|
||||
FROM(table.AccountRisk).
|
||||
WHERE(table.AccountRisk.AccountID.EQ(postgres.UUID(accountID))).
|
||||
LIMIT(1).
|
||||
QueryContext(ctx, s.db, &risk)
|
||||
switch {
|
||||
case err == nil:
|
||||
out.Risk = RiskInfo{Present: true, Abuse: risk.Abuse, LossChips: int(risk.LossChips)}
|
||||
case errors.Is(err, qrm.ErrNoRows):
|
||||
// no risk row — a clean account
|
||||
default:
|
||||
return Statement{}, fmt.Errorf("payments: load risk %s: %w", accountID, err)
|
||||
}
|
||||
|
||||
var rows []model.Ledger
|
||||
if err := postgres.SELECT(table.Ledger.AllColumns).
|
||||
FROM(table.Ledger).
|
||||
WHERE(table.Ledger.AccountID.EQ(postgres.UUID(accountID))).
|
||||
ORDER_BY(table.Ledger.CreatedAt.DESC()).
|
||||
QueryContext(ctx, s.db, &rows); err != nil {
|
||||
return Statement{}, fmt.Errorf("payments: load ledger %s: %w", accountID, err)
|
||||
}
|
||||
for _, r := range rows {
|
||||
out.Ledger = append(out.Ledger, LedgerEntry{
|
||||
Kind: r.Kind,
|
||||
Source: derefStr(r.Source),
|
||||
Origin: derefStr(r.Origin),
|
||||
ChipsDelta: int(r.ChipsDelta),
|
||||
ProductID: derefUUID(r.ProductID),
|
||||
OrderID: derefUUID(r.OrderID),
|
||||
Provider: derefStr(r.Provider),
|
||||
ProviderPaymentID: derefStr(r.ProviderPaymentID),
|
||||
Snapshot: derefStr(r.Snapshot),
|
||||
CreatedAt: r.CreatedAt,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// derefStr returns the pointed-to string, or "" when the pointer is nil (a NULL column).
|
||||
func derefStr(p *string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return *p
|
||||
}
|
||||
|
||||
// derefUUID renders the pointed-to UUID as a string, or "" when the pointer is nil.
|
||||
func derefUUID(p *uuid.UUID) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return p.String()
|
||||
}
|
||||
|
||||
// derefTime returns the pointed-to time, or the zero time when the pointer is nil (a NULL column).
|
||||
func derefTime(p *time.Time) time.Time {
|
||||
if p == nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return *p
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"scrabble/backend/internal/dictadmin"
|
||||
"scrabble/backend/internal/engine"
|
||||
"scrabble/backend/internal/game"
|
||||
"scrabble/backend/internal/payments"
|
||||
"scrabble/backend/internal/ratewatch"
|
||||
"scrabble/backend/internal/robot"
|
||||
"scrabble/backend/internal/social"
|
||||
@@ -436,9 +437,40 @@ func (s *Server) consoleUserDetail(c *gin.Context) {
|
||||
view.Friends = relationRows(rels)
|
||||
}
|
||||
}
|
||||
if s.payments != nil {
|
||||
if stmt, err := s.payments.AccountStatement(ctx, id); err == nil {
|
||||
view.Finance = financeView(stmt)
|
||||
} else {
|
||||
s.log.Warn("console: account statement failed", zap.String("account", id.String()), zap.Error(err))
|
||||
}
|
||||
}
|
||||
s.renderConsole(c, "user_detail", "users", acc.DisplayName, view)
|
||||
}
|
||||
|
||||
// financeView projects an account's payments statement into the user-card finance panel, with the
|
||||
// benefit expiry and ledger times pre-formatted for the logic-free template.
|
||||
func financeView(stmt payments.Statement) adminconsole.FinanceView {
|
||||
fv := adminconsole.FinanceView{Present: true, Abuse: stmt.Risk.Abuse, Loss: stmt.Risk.LossChips}
|
||||
for _, sg := range stmt.Segments {
|
||||
fv.Segments = append(fv.Segments, adminconsole.SegmentRow{Source: string(sg.Source), Chips: sg.Chips})
|
||||
}
|
||||
for _, b := range stmt.Benefits {
|
||||
row := adminconsole.BenefitRow{Origin: string(b.Origin), Hints: b.Hints, Forever: b.AdsForever}
|
||||
if !b.AdsPaidUntil.IsZero() {
|
||||
row.AdsUntil = fmtTime(b.AdsPaidUntil)
|
||||
}
|
||||
fv.Benefits = append(fv.Benefits, row)
|
||||
}
|
||||
for _, e := range stmt.Ledger {
|
||||
fv.Ledger = append(fv.Ledger, adminconsole.LedgerRow{
|
||||
Kind: e.Kind, Source: e.Source, Origin: e.Origin, ChipsDelta: e.ChipsDelta,
|
||||
Product: e.ProductID, Order: e.OrderID, Provider: e.Provider, Snapshot: e.Snapshot,
|
||||
At: fmtTime(e.CreatedAt),
|
||||
})
|
||||
}
|
||||
return fv
|
||||
}
|
||||
|
||||
// relationRows maps the social graph entries to the cross-linked, date-formatted rows the
|
||||
// user card renders.
|
||||
func relationRows(rels []social.AdminRelation) []adminconsole.RelationRow {
|
||||
|
||||
Reference in New Issue
Block a user