feat(admin): 模型管理 - 统一财务统计并支持已有分组选择

This commit is contained in:
Rou committed 2026-09-20 01:40:40 +08:00
1 parent b9d60f9807
commit 04cb438869
13 files changed
+522 -427

No files matched your search

+12 -7
View File
@@ -75,10 +75,11 @@ type AdminUserReference struct {
}
type AdminChannelReference struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Models []string `json:"models"`
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Models []string `json:"models"`
ModelDisplayNames []string `json:"modelDisplayNames"`
}
type AdminReferenceData struct {
@@ -194,15 +195,19 @@ func (s *Service) AdminReferences(actor *model.User) (*AdminReferenceData, error
result.Users = append(result.Users, AdminUserReference{ID: user.ID, Username: user.Username, DisplayName: user.DisplayName})
}
for _, channel := range channels {
items, itemErr := s.repo.ChannelModels(channel.ID, false)
items, itemErr := s.repo.ChannelModels(channel.ID, true)
if itemErr != nil {
return nil, itemErr
}
models := make([]string, 0, len(items))
displayNames := make([]string, 0, len(items))
for _, item := range items {
models = append(models, item.ModelKey)
if item.Enabled {
models = append(models, item.ModelKey)
}
displayNames = append(displayNames, firstNonEmpty(strings.TrimSpace(item.DisplayName), item.ModelKey))
}
result.Channels = append(result.Channels, AdminChannelReference{ID: channel.ID, Name: channel.Name, Enabled: channel.Enabled, Models: uniqueNonEmpty(models)})
result.Channels = append(result.Channels, AdminChannelReference{ID: channel.ID, Name: channel.Name, Enabled: channel.Enabled, Models: uniqueNonEmpty(models), ModelDisplayNames: uniqueNonEmpty(displayNames)})
}
return result, nil
}
+44 -57
View File
@@ -38,18 +38,16 @@ type AnalyticsOverview struct {
}
type AnalyticsKPI struct {
ActiveUsers int `json:"activeUsers"`
DAU int `json:"dau"`
WAU int `json:"wau"`
MAU int `json:"mau"`
GenerationTasks int `json:"generationTasks"`
UpstreamRequests int `json:"upstreamRequests"`
SuccessRate float64 `json:"successRate"`
P95DurationMs int64 `json:"p95DurationMs"`
CurrentQueuedTasks int64 `json:"currentQueuedTasks"`
EstimatedCostMicros int64 `json:"estimatedCostMicros"`
CostAvailable bool `json:"costAvailable"`
Currency string `json:"currency"`
ActiveUsers int `json:"activeUsers"`
DAU int `json:"dau"`
WAU int `json:"wau"`
MAU int `json:"mau"`
GenerationTasks int `json:"generationTasks"`
UpstreamRequests int `json:"upstreamRequests"`
SuccessRate float64 `json:"successRate"`
P95DurationMs int64 `json:"p95DurationMs"`
CurrentQueuedTasks int64 `json:"currentQueuedTasks"`
Finance AnalyticsFinance `json:"finance"`
}
type AnalyticsTrendPoint struct {
@@ -61,24 +59,22 @@ type AnalyticsTrendPoint struct {
}
type AnalyticsModelRow struct {
Model string `json:"model"`
Capability string `json:"capability"`
Tasks int `json:"tasks"`
Requests int `json:"requests"`
UniqueUsers int `json:"uniqueUsers"`
TaskSuccessRate float64 `json:"taskSuccessRate"`
RequestSuccessRate float64 `json:"requestSuccessRate"`
P50DurationMs int64 `json:"p50DurationMs"`
P95DurationMs int64 `json:"p95DurationMs"`
InputTokens int64 `json:"inputTokens"`
OutputTokens int64 `json:"outputTokens"`
CachedTokens int64 `json:"cachedTokens"`
UsageAvailable bool `json:"usageAvailable"`
MediaCount int `json:"mediaCount"`
VideoSeconds int `json:"videoSeconds"`
EstimatedCostMicros int64 `json:"estimatedCostMicros"`
CostAvailable bool `json:"costAvailable"`
Currency string `json:"currency"`
Model string `json:"model"`
Capability string `json:"capability"`
Tasks int `json:"tasks"`
Requests int `json:"requests"`
UniqueUsers int `json:"uniqueUsers"`
TaskSuccessRate float64 `json:"taskSuccessRate"`
RequestSuccessRate float64 `json:"requestSuccessRate"`
P50DurationMs int64 `json:"p50DurationMs"`
P95DurationMs int64 `json:"p95DurationMs"`
InputTokens int64 `json:"inputTokens"`
OutputTokens int64 `json:"outputTokens"`
CachedTokens int64 `json:"cachedTokens"`
UsageAvailable bool `json:"usageAvailable"`
MediaCount int `json:"mediaCount"`
VideoSeconds int `json:"videoSeconds"`
Finance AnalyticsFinance `json:"finance"`
}
type AnalyticsUserRow struct {
@@ -182,6 +178,11 @@ func (s *Service) AdminAnalytics(actor *model.User, query AnalyticsQuery) (*Anal
return nil, err
}
result := buildAnalyticsOverview(filter, tasks, rollingTasks, rollingLogs, logs, activities, users)
records, err := s.analyticsFinancialRecords(logs)
if err != nil {
return nil, err
}
applyAnalyticsFinance(result, records)
result.KPI.CurrentQueuedTasks = queued
return result, nil
}
@@ -448,14 +449,22 @@ func (s *Service) AdminAnalyticsCSV(actor *model.User, query AnalyticsQuery) ([]
if err != nil {
return nil, err
}
records, err := s.analyticsFinancialRecords(logs)
if err != nil {
return nil, err
}
var buffer bytes.Buffer
buffer.WriteString("\xEF\xBB\xBF")
writer := csv.NewWriter(&buffer)
_ = writer.Write([]string{"时间", "用户ID", "渠道ID", "任务ID", "能力", "请求阶段", "模型", "状态", "状态码", "耗时毫秒", "输入Token", "输出Token", "缓存Token", "媒体数量", "视频秒数", "估算费用(微单位)", "币种", "错误类型"})
_ = writer.Write([]string{"时间", "用户ID", "渠道ID", "任务ID", "能力", "请求阶段", "模型", "状态", "状态码", "耗时毫秒", "输入Token", "输出Token", "缓存Token", "媒体数量", "视频秒数", "收入(微积分)", "成本(微积分)", "利润(微积分)", "错误类型"})
for _, log := range logs {
cost := ""
if log.CostAvailable {
cost = strconv.FormatInt(log.EstimatedCostMicros, 10)
revenue, cost, profit := "", "", ""
if record, exists := records[log.ID]; exists {
revenue = strconv.FormatInt(record.Revenue, 10)
if record.Cost != nil {
cost = strconv.FormatInt(*record.Cost, 10)
profit = strconv.FormatInt(record.Revenue-*record.Cost, 10)
}
}
inputTokens, outputTokens, cachedTokens := "", "", ""
if log.UsageAvailable {
@@ -463,7 +472,7 @@ func (s *Service) AdminAnalyticsCSV(actor *model.User, query AnalyticsQuery) ([]
outputTokens = strconv.FormatInt(log.OutputTokens, 10)
cachedTokens = strconv.FormatInt(log.CachedTokens, 10)
}
_ = writer.Write([]string{log.CreatedAt.Format(time.RFC3339), log.UserID, log.ChannelID, log.TaskID, log.Capability, log.RequestKind, log.Model, string(log.Status), strconv.Itoa(log.StatusCode), strconv.FormatInt(log.DurationMs, 10), inputTokens, outputTokens, cachedTokens, strconv.Itoa(log.MediaCount), strconv.Itoa(log.VideoSeconds), cost, log.Currency, classifyAPICallError(log)})
_ = writer.Write([]string{log.CreatedAt.Format(time.RFC3339), log.UserID, log.ChannelID, log.TaskID, log.Capability, log.RequestKind, log.Model, string(log.Status), strconv.Itoa(log.StatusCode), strconv.FormatInt(log.DurationMs, 10), inputTokens, outputTokens, cachedTokens, strconv.Itoa(log.MediaCount), strconv.Itoa(log.VideoSeconds), revenue, cost, profit, classifyAPICallError(log)})
}
writer.Flush()
return buffer.Bytes(), writer.Error()
@@ -598,16 +607,9 @@ func buildAnalyticsOverview(filter repository.AnalyticsFilter, tasks []model.Tas
result.KPI.DAU = rollingActiveUsers(rollingActivities, rollingTasks, rollingLogs, filter.To.AddDate(0, 0, -1), filter.To)
result.KPI.WAU = rollingActiveUsers(rollingActivities, rollingTasks, rollingLogs, filter.To.AddDate(0, 0, -7), filter.To)
result.KPI.MAU = rollingActiveUsers(rollingActivities, rollingTasks, rollingLogs, filter.To.AddDate(0, 0, -30), filter.To)
currency := ""
for _, log := range logs {
durations = append(durations, log.DurationMs)
if log.CostAvailable {
result.KPI.CostAvailable = true
result.KPI.EstimatedCostMicros += log.EstimatedCostMicros
currency = mergeCurrency(currency, log.Currency)
}
}
result.KPI.Currency = currency
result.KPI.P95DurationMs = percentile(durations, 0.95)
result.Trend = buildAnalyticsTrend(filter, tasks, logs, activities)
result.Models = buildAnalyticsModels(tasks, logs)
@@ -724,11 +726,6 @@ func buildAnalyticsModels(tasks []model.Task, logs []model.ApiCallLog) []Analyti
}
item.row.MediaCount += log.MediaCount
item.row.VideoSeconds += log.VideoSeconds
if log.CostAvailable {
item.row.CostAvailable = true
item.row.EstimatedCostMicros += log.EstimatedCostMicros
item.row.Currency = mergeCurrency(item.row.Currency, log.Currency)
}
}
result := make([]AnalyticsModelRow, 0, len(items))
for _, item := range items {
@@ -917,16 +914,6 @@ func percentile(values []int64, quantile float64) int64 {
return items[index]
}
func mergeCurrency(current string, next string) string {
if next == "" {
return current
}
if current == "" || current == next {
return next
}
return "MIXED"
}
func capabilityFromTaskType(taskType string) string {
value := strings.ToLower(taskType)
for _, capability := range []string{"video", "image", "audio", "text"} {
+90
View File
@@ -0,0 +1,90 @@
package app
import "infinite-canvas/backend/internal/model"
type AnalyticsFinance struct {
SettledOrders int `json:"settledOrders"`
CostedOrders int `json:"costedOrders"`
RevenueMicrocredits int64 `json:"revenueMicrocredits"`
CostMicrocredits int64 `json:"costMicrocredits"`
ProfitMicrocredits *int64 `json:"profitMicrocredits"`
ProfitMargin *float64 `json:"profitMargin"`
}
type analyticsFinancialRecord struct {
Log model.ApiCallLog
Revenue int64
Cost *int64
}
// 一个订单的重试、轮询不能重复计入收入;只归属实际结算渠道。
// 历史订单使用下单价格快照,缺失成本时不反查当前价格。
func (s *Service) analyticsFinancialRecords(logs []model.ApiCallLog) (map[string]analyticsFinancialRecord, error) {
ids := make([]string, 0, len(logs))
for _, log := range logs {
if log.Billable && log.BillingOrderID != "" {
ids = append(ids, log.BillingOrderID)
}
}
orders, err := s.repo.BillingOrdersByIDs(uniqueNonEmpty(ids))
if err != nil {
return nil, err
}
byOrder := make(map[string]model.ApiCallLog)
for _, log := range logs {
order, exists := orders[log.BillingOrderID]
if !log.Billable || !exists || order.UserID != log.UserID || order.ChannelID != log.ChannelID || order.Status != model.BillingStatusSettled {
continue
}
switch log.RequestKind {
case "poll", "download", "upload", "workflow-schema", "cancel-query", "cancel":
continue
}
previous, exists := byOrder[order.ID]
if !exists || log.CreatedAt.Before(previous.CreatedAt) || (log.CreatedAt.Equal(previous.CreatedAt) && log.ID < previous.ID) {
byOrder[order.ID] = log
}
}
records := make(map[string]analyticsFinancialRecord, len(byOrder))
for id, log := range byOrder {
order := orders[id]
cost, err := billingCreditCost(order)
if err != nil {
return nil, err
}
records[log.ID] = analyticsFinancialRecord{Log: log, Revenue: order.ActualAmountMicrocredits, Cost: cost}
}
return records, nil
}
func (finance *AnalyticsFinance) add(record analyticsFinancialRecord) {
finance.SettledOrders++
finance.RevenueMicrocredits += record.Revenue
if record.Cost != nil {
finance.CostedOrders++
finance.CostMicrocredits += *record.Cost
}
finance.ProfitMicrocredits, finance.ProfitMargin = nil, nil
if finance.CostedOrders == finance.SettledOrders {
profit := finance.RevenueMicrocredits - finance.CostMicrocredits
finance.ProfitMicrocredits = &profit
if finance.RevenueMicrocredits > 0 {
margin := float64(profit) * 100 / float64(finance.RevenueMicrocredits)
finance.ProfitMargin = &margin
}
}
}
func applyAnalyticsFinance(overview *AnalyticsOverview, records map[string]analyticsFinancialRecord) {
rows := make(map[[2]string]*AnalyticsFinance, len(overview.Models))
for index := range overview.Models {
row := &overview.Models[index]
rows[[2]string{row.Model, row.Capability}] = &row.Finance
}
for _, record := range records {
overview.KPI.Finance.add(record)
if row := rows[[2]string{firstNonEmpty(record.Log.Model, "未识别"), record.Log.Capability}]; row != nil {
row.add(record)
}
}
}
@@ -0,0 +1,215 @@
package app
import (
"encoding/csv"
"strconv"
"strings"
"testing"
"time"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/repository"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestAnalyticsFinanceAggregatesKnownAndUnknownCosts(t *testing.T) {
cost := int64(300_000)
zero := int64(0)
for _, test := range []struct {
name string
records []analyticsFinancialRecord
costed int
revenue int64
cost int64
profit *int64
}{
{name: "no orders"},
{name: "explicit zero", records: []analyticsFinancialRecord{{Cost: &zero}}, costed: 1, profit: &zero},
{name: "break even", records: []analyticsFinancialRecord{{Revenue: 300_000, Cost: &cost}}, costed: 1, revenue: 300_000, cost: 300_000, profit: &zero},
{name: "partial cost last", records: []analyticsFinancialRecord{{Revenue: 900_000, Cost: &cost}, {Revenue: 400_000}}, costed: 1, revenue: 1_300_000, cost: 300_000},
{name: "partial cost first", records: []analyticsFinancialRecord{{Revenue: 400_000}, {Revenue: 900_000, Cost: &cost}}, costed: 1, revenue: 1_300_000, cost: 300_000},
} {
t.Run(test.name, func(t *testing.T) {
var finance AnalyticsFinance
for _, record := range test.records {
finance.add(record)
}
if finance.SettledOrders != len(test.records) || finance.CostedOrders != test.costed || finance.RevenueMicrocredits != test.revenue || finance.CostMicrocredits != test.cost {
t.Fatalf("finance = %+v", finance)
}
if test.profit == nil {
if finance.ProfitMicrocredits != nil || finance.ProfitMargin != nil {
t.Fatalf("unknown profit = %+v", finance)
}
return
}
if finance.ProfitMicrocredits == nil || *finance.ProfitMicrocredits != *test.profit {
t.Fatalf("profit = %+v", finance)
}
if test.revenue == 0 {
if finance.ProfitMargin != nil {
t.Fatalf("zero revenue margin = %v", *finance.ProfitMargin)
}
} else if finance.ProfitMargin == nil || *finance.ProfitMargin != float64(*test.profit)*100/float64(test.revenue) {
t.Fatalf("margin = %+v", finance)
}
})
}
}
func TestAdminAnalyticsFinanceUsesSettledSnapshotsAndDeduplicates(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file:"+newID()+"?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.BillingOrder{}, &model.ApiCallLog{}, &model.Task{}, &model.UserDailyActivity{}, &model.User{}); err != nil {
t.Fatal(err)
}
svc := &Service{repo: repository.New(db)}
admin := &model.User{ID: "admin", Role: model.UserRoleAdmin}
now := time.Now().UTC()
orders := []model.BillingOrder{
{ID: "paid", Status: model.BillingStatusSettled, ActualAmountMicrocredits: 900_000, BillingCostSnapshot: model.BillingCostSnapshot{CostBillingMode: "fixed_request", CostQuantity: 1, CostPricing: model.CreditCostPricing{Configured: true, UnitPriceMicrocredits: 300_000}}},
{ID: "free", Status: model.BillingStatusSettled, BillingCostSnapshot: model.BillingCostSnapshot{CostBillingMode: "fixed_request", CostQuantity: 1, CostPricing: model.CreditCostPricing{Configured: true}}},
{ID: "unknown", Status: model.BillingStatusSettled, ActualAmountMicrocredits: 400_000},
{ID: "reserved", Status: model.BillingStatusReserved, ReservedAmountMicrocredits: 1_000_000},
{ID: "refunded", Status: model.BillingStatusRefunded, ActualAmountMicrocredits: 800_000},
{ID: "loss", Status: model.BillingStatusSettled, ActualAmountMicrocredits: 100_000, BillingCostSnapshot: model.BillingCostSnapshot{CostBillingMode: "per_second", CostQuantity: 3, CostPricing: model.CreditCostPricing{Configured: true, UnitPriceMicrocredits: 100_000}}},
}
logs := make([]model.ApiCallLog, 0)
for index := range orders {
order := &orders[index]
order.UserID, order.ChannelID, order.IdempotencyKey = "user", "channel", order.ID
logs = append(logs, model.ApiCallLog{ID: order.ID, BillingOrderID: order.ID, UserID: "user", ChannelID: "channel", Model: order.ID, Capability: "text", Billable: true, RequestKind: "create", Status: model.ApiCallStatusSucceeded, CreatedAt: now})
}
for _, id := range []string{"retry", "poll", "download", "upload", "workflow-schema", "cancel-query", "cancel", "wrong-user", "old-channel"} {
item := logs[0]
item.ID = id
item.CreatedAt = now.Add(time.Second)
switch id {
case "poll", "download", "upload", "workflow-schema", "cancel-query", "cancel":
item.RequestKind = id
item.Model = "auxiliary"
item.CreatedAt = now.Add(-time.Second)
case "wrong-user":
item.UserID = "other"
case "old-channel":
item.ChannelID = "previous"
}
logs = append(logs, item)
}
if err := db.Create(&orders).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&logs).Error; err != nil {
t.Fatal(err)
}
query := AnalyticsQuery{From: now.Add(-time.Hour).Format(time.RFC3339), To: now.Add(time.Hour).Format(time.RFC3339)}
result, err := svc.AdminAnalytics(admin, query)
if err != nil {
t.Fatal(err)
}
finance := result.KPI.Finance
if finance.SettledOrders != 4 || finance.CostedOrders != 3 || finance.RevenueMicrocredits != 1_400_000 || finance.CostMicrocredits != 600_000 || finance.ProfitMicrocredits != nil || finance.ProfitMargin != nil {
t.Fatalf("partial finance = %+v", finance)
}
for _, row := range result.Models {
f := row.Finance
switch row.Model {
case "paid":
if f.SettledOrders != 1 || f.ProfitMicrocredits == nil || *f.ProfitMicrocredits != 600_000 || f.ProfitMargin == nil || *f.ProfitMargin < 66.6 || *f.ProfitMargin > 66.7 {
t.Fatalf("paid = %+v", f)
}
case "free":
if f.CostedOrders != 1 || f.ProfitMicrocredits == nil || *f.ProfitMicrocredits != 0 || f.ProfitMargin != nil {
t.Fatalf("free = %+v", f)
}
case "loss":
if f.ProfitMicrocredits == nil || *f.ProfitMicrocredits != -200_000 || f.ProfitMargin == nil || *f.ProfitMargin != -200 {
t.Fatalf("loss = %+v", f)
}
}
}
data, err := svc.AdminAnalyticsCSV(admin, query)
if err != nil {
t.Fatal(err)
}
rows, err := csv.NewReader(strings.NewReader(strings.TrimPrefix(string(data), "\xEF\xBB\xBF"))).ReadAll()
if err != nil {
t.Fatal(err)
}
var revenue, cost int64
for _, row := range rows[1:] {
if row[6] == "auxiliary" && (row[15] != "" || row[16] != "" || row[17] != "") {
t.Fatalf("auxiliary request must not carry order finances: %v", row)
}
for index, target := range map[int]*int64{15: &revenue, 16: &cost} {
if row[index] != "" {
value, err := strconv.ParseInt(row[index], 10, 64)
if err != nil {
t.Fatal(err)
}
*target += value
}
}
}
if revenue != finance.RevenueMicrocredits || cost != finance.CostMicrocredits {
t.Fatalf("CSV mismatch: revenue=%d cost=%d", revenue, cost)
}
query.Model = "paid"
filtered, err := svc.AdminAnalytics(admin, query)
if err != nil || filtered.KPI.Finance.SettledOrders != 1 || filtered.KPI.Finance.ProfitMicrocredits == nil || *filtered.KPI.Finance.ProfitMicrocredits != 600_000 {
t.Fatalf("model filter = %+v, %v", filtered, err)
}
query.ChannelID = "previous"
filtered, err = svc.AdminAnalytics(admin, query)
if err != nil || filtered.KPI.Finance.SettledOrders != 0 {
t.Fatalf("previous channel finance = %+v, %v", filtered, err)
}
query.Model, query.ChannelID = "auxiliary", ""
filtered, err = svc.AdminAnalytics(admin, query)
if err != nil || filtered.KPI.Finance.SettledOrders != 0 {
t.Fatalf("auxiliary request finance = %+v, %v", filtered, err)
}
if _, err := svc.AdminAnalytics(&model.User{Role: model.UserRoleUser}, query); err == nil {
t.Fatal("non-admin must not read costs")
}
}
func TestAdminReferencesIncludeExistingDisplayNameGroups(t *testing.T) {
svc, db := newChannelModelTestService(t)
if err := db.AutoMigrate(&model.User{}); err != nil {
t.Fatal(err)
}
channels := []model.ModelChannel{
{ID: "one", Scope: model.ChannelScopeSystem, Enabled: true},
{ID: "two", Scope: model.ChannelScopeSystem, Enabled: false},
}
if err := db.Create(&channels).Error; err != nil {
t.Fatal(err)
}
items := []model.ChannelModel{
{ID: "a", ChannelID: "one", ModelKey: "a", DisplayName: "Shared", Enabled: true},
{ID: "b", ChannelID: "one", ModelKey: "b", DisplayName: "Shared", Enabled: false},
{ID: "c", ChannelID: "two", ModelKey: "c", DisplayName: "Other", Enabled: false},
{ID: "d", ChannelID: "two", ModelKey: "d"},
}
if err := db.Create(&items).Error; err != nil {
t.Fatal(err)
}
result, err := svc.AdminReferences(&model.User{Role: model.UserRoleAdmin})
if err != nil {
t.Fatal(err)
}
groups := map[string]int{}
for _, channel := range result.Channels {
for _, name := range channel.ModelDisplayNames {
groups[name]++
}
}
if len(groups) != 3 || groups["Shared"] != 1 || groups["Other"] != 1 || groups["d"] != 1 {
t.Fatalf("groups = %#v", groups)
}
}