diff --git a/.github/scripts/upstream-channel-entities-screenshot.mjs b/.github/scripts/upstream-channel-entities-screenshot.mjs index 62e09dd151b3..6368df965606 100644 --- a/.github/scripts/upstream-channel-entities-screenshot.mjs +++ b/.github/scripts/upstream-channel-entities-screenshot.mjs @@ -44,6 +44,11 @@ apiClient.defaults.adapter=async config=>{ const drilled=params.dimension==='account'||params.dimension==='model'||Number(params.account_id)>0||Number(params.group_id)>0||String(params.model||'')!==''; const metrics={requests:2,standard_charge:20,request_income:8,supplier_requests:2,bill_requests:0,estimated_requests:0,upstream_cost:drilled?null:(yesterday?4:5),gross_profit:drilled?null:(yesterday?4:3),gross_margin:drilled?null:(yesterday?0.5:0.375),cost_covered_requests:2,unknown_cost_requests:0,unknown_upstream_requests:0,cost_source:drilled?'wallet_not_split':(yesterday?'wallet_window':'wallet_today'),wallet_basis:yesterday?'wallet_window':'wallet_today',wallet_currency:'USD'}; data={scope:params,queried_at:now,currency:'USD',usage:{summary:metrics,wallet_synced_at:now,rows:[{...metrics,key:drilled?'41':'channel:7',name:drilled?'合成账号 41':channel.name,provider_id:1,provider_site_type:'sub2api',channel_id:7,channel_code:channel.code,channel_remark:channel.remark,assignment:'explicit'}],total:1,catalog:[{key:'channel:7',name:channel.name,accounts:2,channel_id:7,channel_code:channel.code,channel_remark:channel.remark,assignment:'explicit'}],catalog_total:1,members:[],member_total:0,accounts:[],capacity:{accounts:2,schedulable:2,configured_concurrency:6}},quality:{status:'ready',data:{summary:{},rows:[]}},errors:{status:'ready',data:{rows:[]}}}; + if (params.basis === 'account_usage' && sessionStorage.getItem('account-usage-fixture')) { + data.usage.basis='account_usage'; + for (const m of [data.usage.summary,...data.usage.rows]) Object.assign(m,{cost_source:'account_usage',upstream_cost:2,gross_profit:6,gross_margin:.75}); + delete data.usage.wallet_synced_at; + } }else if(url==='/admin/profit-operations/channel-accounts')data={account_ids:[41,42]}; else if(url==='/admin/account-ops/config')data={config:{enabled:false,recipient:'',balance_low:false,weekly_quota:false,cooldown_minutes:30,groups:[],webhooks:[],balance_thresholds:[],quota_thresholds:[]},encryption_key_configured:true}; else if(url==='/admin/account-ops/threshold-accounts')data={items:[...Array.from({length:15},(_,i)=>({account_id:i+1,account_name:'示例成员 '+(i+1),type:'apikey',platform:'openai',provider_id:1,group_id:'manual-demo-wallet',group_mode:'manual',unit:'USD',balance:420,balance_status:'ok',received_at:now,usage_windows:[]})),{account_id:42,account_name:'示例官方账号',platform:'openai',type:'oauth',usage_windows:[],unit:'%',balance:null,balance_status:'unsupported',received_at:null}]}; @@ -112,8 +117,11 @@ try{ // Render the same real edit/bulk dialogs through table actions where exposed. await page.getByRole('button',{name:'编辑',exact:true}).first().click();await page.getByTestId('open-channel-bindings').click();await page.getByTestId('upstream-channel-select').waitFor();await page.getByTestId('upstream-channel-select').selectOption('0');await page.getByTestId('confirm-channel-binding').check();await page.getByTestId('save-channel-binding').click();await page.getByText('已保存并从服务器读回确认',{exact:true}).waitFor();await page.screenshot({path:path.join(output,'entity-account-edit-bindings.png'),fullPage:true});await page.keyboard.press('Escape') await page.locator('table input[type="checkbox"]').first().check();await page.getByRole('button',{name:'批量编辑',exact:false}).first().click();await page.getByTestId('open-channel-bindings').click();await page.getByTestId('upstream-channel-select').focus();await page.getByTestId('upstream-channel-select').selectOption('7');await page.getByTestId('confirm-channel-binding').check();await page.getByTestId('save-channel-binding').click();await page.getByText('已保存并从服务器读回确认',{exact:true}).waitFor();await page.screenshot({path:path.join(output,'entity-account-bulk-bindings.png'),fullPage:true}) + await page.evaluate(()=>sessionStorage.setItem('account-usage-fixture','1')) await page.goto('http://127.0.0.1:4185/admin/channel-config',{waitUntil:'networkidle'}) await page.getByTestId('profit-summary').waitFor() + await page.getByTestId('profit-summary').locator('[data-field="gross_margin"]').filter({hasText:'75.00%'}).waitFor() + await page.getByTestId('profit-summary').getByText('账号计费',{exact:true}).waitFor() await page.screenshot({path:path.join(output,'channel-config-profit.png'),fullPage:true}) const reportCalls=await page.evaluate(()=>globalThis.__entityFixture.calls.filter(c=>c.url==='/admin/profit-operations/snapshot').length) const management=page.getByTestId('config-panel-channels') diff --git a/.github/workflows/upstream-channel-operations.yml b/.github/workflows/upstream-channel-operations.yml index 69b81f6432cf..7f86919ea66e 100644 --- a/.github/workflows/upstream-channel-operations.yml +++ b/.github/workflows/upstream-channel-operations.yml @@ -51,8 +51,10 @@ jobs: s=s[:s.index(begin)]+current[current.index(begin):current.index(end)]+s[s.index(end):] if '"strconv"' not in s: s=s.replace('import (\n', 'import (\n "strconv"\n', 1) - if '`json:"channel_id,omitempty"`' not in s: - s=s.replace('Upstream string `json:"upstream"`', 'Upstream string `json:"upstream"`\n ChannelID int64 `json:"channel_id,omitempty"`') + dto='type UpstreamOperationsFilter struct {' + def dto_end(source): + return source.index('\n}', source.index(dto))+2 + s=s[:s.index(dto)]+current[current.index(dto):dto_end(current)]+s[dto_end(s):] s=re.sub(r'\n// OperationsCostMultiplier distinguishes.*?\n}\s*$', '\n', s, flags=re.S) assert '`json:"channel_id,omitempty"`' in s assert 'func OperationsCostMultiplier' not in s diff --git a/backend/internal/handler/admin/profit_operations.go b/backend/internal/handler/admin/profit_operations.go index 9df893d5921b..e6d8a0706cac 100644 --- a/backend/internal/handler/admin/profit_operations.go +++ b/backend/internal/handler/admin/profit_operations.go @@ -27,6 +27,7 @@ func (h *ChannelHandler) ProfitOperations(c *gin.Context) { return } f := service.UpstreamOperationsFilter{From: from, Until: until, Upstream: c.Query("upstream"), ChannelID: channel, AccountID: account, GroupID: group, Model: c.Query("model"), ModelScope: c.DefaultQuery("model_scope", "public"), Dimension: c.DefaultQuery("dimension", "upstream"), Sort: c.DefaultQuery("sort", "requests"), Direction: c.DefaultQuery("direction", "desc"), Page: int(page), PageSize: int(size)} + f.AccountUsage = c.Query("basis") == "account_usage" if err := service.NormalizeProfitOperationsFilter(&f); err != nil { response.ErrorFrom(c, err) return @@ -39,7 +40,9 @@ func (h *ChannelHandler) ProfitOperations(c *gin.Context) { } started := time.Now() out, err := h.profitReports.read(c.Request.Context(), f, func(ctx context.Context, collect bool) (*service.ProfitOperationsSnapshot, error) { - h.refreshBoundProviderSpend(ctx, f.From, f.Until, force) + if !f.AccountUsage { + h.refreshBoundProviderSpend(ctx, f.From, f.Until, force) + } if collect { ctx = service.WithProfitRowCollection(ctx) } @@ -47,6 +50,10 @@ func (h *ChannelHandler) ProfitOperations(c *gin.Context) { }) if err != nil { status, reason, message := http.StatusInternalServerError, "PROFIT_OPERATIONS_QUERY_FAILED", "Upstream operations query failed; retry" + if errors.Is(err, service.ErrAccountUsageBuilding) { + response.ErrorFrom(c, err) + return + } if errors.Is(err, context.DeadlineExceeded) { status, reason, message = http.StatusGatewayTimeout, "PROFIT_OPERATIONS_TIMEOUT", "Profit operations query timed out; retry later" } diff --git a/backend/internal/repository/account_usage_financial.go b/backend/internal/repository/account_usage_financial.go new file mode 100644 index 000000000000..7b3b31ce562c --- /dev/null +++ b/backend/internal/repository/account_usage_financial.go @@ -0,0 +1,81 @@ +package repository + +import ( + "context" + "database/sql" + "errors" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// Rebuild a closed slice under a fresh READ COMMITTED snapshot after the +// writer barrier. Replacing it also handles deleted or re-attributed usage. +func (r *dashboardAggregationRepository) RefreshAccountUsageFinancial(ctx context.Context) (bool, error) { + db, ok := r.sql.(*sql.DB) + if !ok { + return false, nil + } + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return false, err + } + defer func() { _ = tx.Rollback() }() + var bucket time.Time + err = tx.QueryRowContext(ctx, `SELECT bucket FROM account_usage_financial_pending + WHERE bucket < account_usage_bucket(now()) ORDER BY bucket DESC LIMIT 1`).Scan(&bucket) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + var acquired bool + err = tx.QueryRowContext(ctx, `SELECT pg_try_advisory_xact_lock(825393,(extract(epoch FROM $1::timestamptz)/300)::integer)`, bucket).Scan(&acquired) + if err != nil || !acquired { + return false, err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM account_usage_financial_rollups WHERE bucket=$1`, bucket); err != nil { + return false, err + } + _, err = tx.ExecContext(ctx, `INSERT INTO account_usage_financial_rollups + SELECT $1::timestamptz,account_id,group_id,model,public_model,upstream_model, + count(*),COALESCE(sum(tokens),0),COALESCE(sum(standard_charge),0),COALESCE(sum(user_charge),0), + COALESCE(sum(account_charge),0),sum(duration_sum),sum(duration_count) + FROM account_usage_financial_events WHERE created_at >= $1 AND created_at < $1::timestamptz+interval '5 minutes' + GROUP BY account_id,group_id,model,public_model,upstream_model`, bucket) + if err != nil { + return false, err + } + if _, err = tx.ExecContext(ctx, `DELETE FROM account_usage_financial_pending WHERE bucket=$1`, bucket); err != nil { + return false, err + } + return true, tx.Commit() +} + +// Full five-minute buckets use saved statistics. Only partial boundaries and +// the most recent five to ten minutes can read events. All three ranges are +// disjoint even for a window shorter than one bucket. +const accountUsageWindow = `WITH bounds AS ( + SELECT LEAST($2::timestamptz, CASE WHEN $1=account_usage_bucket($1) THEN $1 ELSE account_usage_bucket($1)+interval '5 minutes' END) AS lo, + GREATEST($1::timestamptz,LEAST(account_usage_bucket($2),account_usage_bucket(now())-interval '5 minutes')) AS hi +), facts AS ( + SELECT bucket AS at,account_id,group_id,model,public_model,upstream_model,requests,tokens,standard_charge,user_charge,account_charge,duration_sum,duration_count + FROM account_usage_financial_rollups,bounds WHERE bucket>=lo AND bucket=$1 AND created_at=GREATEST(lo,hi) AND created_at<$2 AND ($3::bigint=0 OR account_id=$3) +)` + +func accountUsageReady(ctx context.Context, tx *sql.Tx, from, until time.Time) error { + var pending bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM account_usage_financial_pending + WHERE bucket >= $1 AND bucket < LEAST(account_usage_bucket($2),account_usage_bucket(now())-interval '5 minutes'))`, from, until).Scan(&pending) + if err == nil && pending { + return service.ErrAccountUsageBuilding + } + return err +} diff --git a/backend/internal/repository/dashboard_aggregation_group_usage_test.go b/backend/internal/repository/dashboard_aggregation_group_usage_test.go index c77e0923e8b6..94d0ec7b0b41 100644 --- a/backend/internal/repository/dashboard_aggregation_group_usage_test.go +++ b/backend/internal/repository/dashboard_aggregation_group_usage_test.go @@ -543,6 +543,7 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedInvalidatesRet WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(nil)) mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202604"`). WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(`INSERT INTO account_usage_financial_pending`).WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() // 6 月分区含保留下界之后的记录:删除后按其中最早时刻失效。 mock.ExpectBegin() @@ -554,6 +555,7 @@ func TestDashboardAggregationRepositoryCleanupUsageLogsPartitionedInvalidatesRet WillReturnRows(sqlmock.NewRows([]string{"min"}).AddRow(retainedInJunePartition)) mock.ExpectExec(`DROP TABLE IF EXISTS "usage_logs_202606"`). WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec(`INSERT INTO account_usage_financial_pending`).WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectExec(groupRollupInvalidateSQL). WithArgs(retainedInJunePartition, "UTC"). WillReturnResult(sqlmock.NewResult(0, 0)) diff --git a/backend/internal/repository/dashboard_aggregation_repo.go b/backend/internal/repository/dashboard_aggregation_repo.go index 1adad1277906..cb9db7fa4ca4 100644 --- a/backend/internal/repository/dashboard_aggregation_repo.go +++ b/backend/internal/repository/dashboard_aggregation_repo.go @@ -610,6 +610,17 @@ func (r *dashboardAggregationRepository) dropUsageLogsPartition(ctx context.Cont if _, err := q.ExecContext(ctx, fmt.Sprintf("DROP TABLE IF EXISTS %s", pq.QuoteIdentifier(name))); err != nil { return err } + // Dropping a partition bypasses row DELETE triggers. Rebuild any + // published slices from that month after the partition disappears. + month, err := time.Parse("200601", strings.TrimPrefix(name, "usage_logs_")) + if err != nil { + return err + } + if _, err := q.ExecContext(ctx, `INSERT INTO account_usage_financial_pending + SELECT DISTINCT bucket FROM account_usage_financial_rollups WHERE bucket >= $1 AND bucket < $2 + ON CONFLICT DO NOTHING`, month, month.AddDate(0, 1, 0)); err != nil { + return err + } if earliestRetained.Valid { return invalidateGroupUsageRollupsAt(ctx, q, earliestRetained.Time, r.timezoneLocation().String()) } diff --git a/backend/internal/repository/profit_operations.go b/backend/internal/repository/profit_operations.go index 537ec80b3a97..d4f2ed83cdc5 100644 --- a/backend/internal/repository/profit_operations.go +++ b/backend/internal/repository/profit_operations.go @@ -342,6 +342,9 @@ func (r *channelRepository) ReadProfitOperations(ctx context.Context, f service. return nil, err } defer func() { _ = tx.Rollback() }() + if f.AccountUsage { + return readAccountUsageProfit(ctx, tx, f) + } raw, err := profitOperationsAccounts(ctx, tx, f) if err != nil { return nil, err diff --git a/backend/internal/repository/profit_operations_account_usage.go b/backend/internal/repository/profit_operations_account_usage.go new file mode 100644 index 000000000000..3872b5794f24 --- /dev/null +++ b/backend/internal/repository/profit_operations_account_usage.go @@ -0,0 +1,61 @@ +package repository + +import ( + "context" + "database/sql" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +func readAccountUsageProfit(ctx context.Context, tx *sql.Tx, f service.UpstreamOperationsFilter) (*service.ProfitOperationsSnapshot, error) { + if err := accountUsageReady(ctx, tx, f.From, f.Until); err != nil { + return nil, err + } + raw, err := profitOperationsAccounts(ctx, tx, f) + if err != nil { + return nil, err + } + size, offset := f.PageSize, (f.Page-1)*f.PageSize + if service.CollectProfitRows(ctx) { + size, offset = 10001, 0 + } + // sort and direction are allowlisted by NormalizeProfitOperationsFilter. + q := accountUsageWindow + `, cfg AS ( + SELECT * FROM jsonb_to_recordset($4::jsonb) AS c(id bigint,name text,key text,channel_id bigint,channel_name text,channel_code text, + channel_remark text,assignment text,schedulable boolean,concurrency integer,status text,deleted boolean) +), scoped AS ( + SELECT f.*,COALESCE(c.key,'unknown:account_missing') AS upstream_key,c.name AS account_name,c.channel_id,c.channel_name,c.channel_code, + c.channel_remark,c.assignment,CASE $5 WHEN 'public' THEN public_model WHEN 'recorded' THEN model ELSE COALESCE(upstream_model,'(unknown upstream model)') END AS model_key + FROM facts f LEFT JOIN cfg c ON c.id=f.account_id + WHERE ($6::bigint=0 OR f.group_id=$6) AND ($7::bigint=0 OR c.channel_id=$7) AND ($8='' OR COALESCE(c.key,'unknown:account_missing')=$8) + AND ($9='' OR CASE $5 WHEN 'public' THEN public_model WHEN 'recorded' THEN model ELSE upstream_model END=$9) +), named AS ( + SELECT *, CASE $10 WHEN 'upstream' THEN upstream_key WHEN 'account' THEN account_id::text ELSE model_key END AS key, + CASE $10 WHEN 'upstream' THEN COALESCE(NULLIF(channel_name,''),upstream_key) + WHEN 'account' THEN COALESCE(account_name,'Deleted account')||' #'||account_id::text ELSE model_key END AS name FROM scoped +), totals AS ( + SELECT grouping(key) AS is_total,key,max(name) AS name,COALESCE(sum(requests),0) AS requests, + COALESCE(sum(standard_charge),0) AS standard_charge,COALESCE(sum(user_charge),0) AS request_income,COALESCE(sum(account_charge),0) AS upstream_cost, + COALESCE(sum(user_charge),0)-COALESCE(sum(account_charge),0) AS gross_profit,(sum(user_charge)-COALESCE(sum(account_charge),0))/NULLIF(sum(user_charge),0) AS gross_margin, + 'account_usage'::text AS cost_source,CASE WHEN $10='upstream' THEN max(channel_id) END AS channel_id, + max(channel_code) AS channel_code,max(channel_remark) AS channel_remark,max(assignment) AS assignment + FROM named GROUP BY GROUPING SETS ((key),()) +), members AS ( + SELECT * FROM cfg c WHERE NOT deleted AND ($7::bigint=0 OR channel_id=$7) AND ($8='' OR key=$8) + AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6)) +), catalog AS (SELECT key,max(channel_id) AS channel_id,COALESCE(NULLIF(max(channel_name),''),key) AS name,count(*) AS accounts FROM members GROUP BY key) + SELECT jsonb_build_object('basis','account_usage','summary',(SELECT to_jsonb(t)-'is_total' FROM totals t WHERE is_total=1), + 'total',(SELECT count(*) FROM totals WHERE is_total=0), + 'rows',COALESCE((SELECT jsonb_agg(to_jsonb(t)-'is_total' ORDER BY ` + f.Sort + ` ` + f.Direction + ` NULLS LAST,key) FROM ( + SELECT * FROM totals WHERE is_total=0 ORDER BY ` + f.Sort + ` ` + f.Direction + ` NULLS LAST,key LIMIT $11 OFFSET $12)t),'[]'), + 'catalog_total',(SELECT count(*) FROM catalog),'catalog',COALESCE((SELECT jsonb_agg(to_jsonb(c) ORDER BY key) FROM (SELECT * FROM catalog ORDER BY key LIMIT $11 OFFSET $12)c),'[]'), + 'member_total',(SELECT count(*) FROM members),'members',COALESCE((SELECT jsonb_agg(to_jsonb(m) ORDER BY id) FROM (SELECT id,name FROM members ORDER BY id LIMIT $11 OFFSET $12)m),'[]'), + 'accounts','[]'::jsonb,'account_details_limit',0)` + out := &service.ProfitOperationsSnapshot{UpstreamOperationsSnapshot: service.UpstreamOperationsSnapshot{ + Scope: f, QueriedAt: time.Now().UTC(), Attribution: "current_account_channel", + Quality: service.ChannelOperationsSection{Status: "not_requested"}, Errors: service.ChannelOperationsSection{Status: "not_requested"}, + }, Currency: "USD"} + err = tx.QueryRowContext(ctx, q, f.From, f.Until, f.AccountID, string(raw), f.ModelScope, f.GroupID, f.ChannelID, f.Upstream, f.Model, f.Dimension, size, offset).Scan(&out.Usage) + return out, err +} diff --git a/backend/internal/repository/profit_operations_account_usage_integration_test.go b/backend/internal/repository/profit_operations_account_usage_integration_test.go new file mode 100644 index 000000000000..bb6653a52090 --- /dev/null +++ b/backend/internal/repository/profit_operations_account_usage_integration_test.go @@ -0,0 +1,70 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestProfitOperationsAccountUsageRollup(t *testing.T) { + f := newChannelOperationsFixture(t) + ctx := context.Background() + from := time.Now().UTC().Truncate(5 * time.Minute).Add(-20 * time.Minute) + filter := service.UpstreamOperationsFilter{From: from, Until: from.Add(5 * time.Minute), AccountID: f.account, AccountUsage: true, + Dimension: "account", ModelScope: "public", Sort: "requests", Direction: "desc", Page: 1, PageSize: 20} + _, err := integrationDB.Exec(`INSERT INTO usage_logs(user_id,api_key_id,account_id,request_id,model,total_cost,actual_cost,account_stats_cost,account_rate_multiplier,created_at) + VALUES($1,$2,$3,'financial-rollup','fixture',50,10,4,0.5,$4)`, f.user, f.key, f.account, from.Add(time.Minute)) + require.NoError(t, err) + _, err = f.repo.ReadProfitOperations(ctx, filter) + require.ErrorIs(t, err, service.ErrAccountUsageBuilding) + worker := newDashboardAggregationRepositoryWithSQL(integrationDB) + check := func(requests int, income, cost, profit float64) { + t.Helper() + for i := 0; i < 10; i++ { + var pending bool + require.NoError(t, integrationDB.QueryRow("SELECT EXISTS(SELECT 1 FROM account_usage_financial_pending WHERE bucket=$1)", from).Scan(&pending)) + if !pending { + break + } + _, err := worker.RefreshAccountUsageFinancial(ctx) + require.NoError(t, err) + } + report, err := f.repo.ReadProfitOperations(ctx, filter) + require.NoError(t, err) + var result struct { + Summary struct { + Requests int + Income float64 `json:"request_income"` + Cost float64 `json:"upstream_cost"` + Profit float64 `json:"gross_profit"` + } + } + require.NoError(t, json.Unmarshal(report.Usage, &result)) + require.Equal(t, requests, result.Summary.Requests) + require.Equal(t, income, result.Summary.Income) + require.Equal(t, cost, result.Summary.Cost) + require.Equal(t, profit, result.Summary.Profit) + } + check(1, 10, 2, 8) + // Late corrections invalidate the published slice. A partial range on + // either edge still uses the same persisted prices and half-open bounds. + _, err = integrationDB.Exec("UPDATE usage_logs SET actual_cost=9 WHERE account_id=$1 AND request_id='financial-rollup'", f.account) + require.NoError(t, err) + check(1, 9, 2, 7) + filter.From = from.Add(time.Minute) + filter.Until = from.Add(2 * time.Minute) + check(1, 9, 2, 7) + filter.From = from + filter.Until = from.Add(time.Minute) + check(0, 0, 0, 0) + filter.Until = from.Add(5 * time.Minute) + _, err = integrationDB.Exec("DELETE FROM usage_logs WHERE account_id=$1 AND request_id='financial-rollup'", f.account) + require.NoError(t, err) + check(0, 0, 0, 0) +} diff --git a/backend/internal/repository/upstream_operations.go b/backend/internal/repository/upstream_operations.go index 9f8acb5a82cc..a33f485e2b5d 100644 --- a/backend/internal/repository/upstream_operations.go +++ b/backend/internal/repository/upstream_operations.go @@ -34,7 +34,7 @@ func operationsAccounts(ctx context.Context, tx *sql.Tx, f service.UpstreamOpera jsonb_build_object('base_url',a.credentials->'base_url','api_base_urls',a.credentials->'api_base_urls','account_mode',a.credentials->'account_mode','api_protocol',a.credentials->'api_protocol','provider_profile',a.credentials->'provider_profile','client_id',a.credentials->'client_id','auth_mode',a.credentials->'auth_mode','openai_auth_mode',a.credentials->'openai_auth_mode'), jsonb_build_object('custom_base_url_enabled',a.extra->'custom_base_url_enabled','custom_base_url',a.extra->'custom_base_url','openai_siwc',a.extra->'openai_siwc','openai_prism_browser',a.extra->'openai_prism_browser','openai_excel_bps',a.extra->'openai_excel_bps'), a.updated_at,a.deleted_at IS NOT NULL,a.parent_account_id,a.schedulable,a.concurrency,a.status - FROM accounts a WHERE ($3::bigint=0 OR a.id=$3) AND (a.deleted_at IS NULL OR EXISTS(SELECT 1 FROM usage_logs u WHERE u.account_id=a.id AND u.created_at >= $1 AND u.created_at < $2))`, f.From, f.Until, f.AccountID) + FROM accounts a WHERE ($3::bigint=0 OR a.id=$3) AND ($4::bool OR a.deleted_at IS NULL OR EXISTS(SELECT 1 FROM usage_logs u WHERE u.account_id=a.id AND u.created_at >= $1 AND u.created_at < $2))`, f.From, f.Until, f.AccountID, f.AccountUsage) if err != nil { return nil, err } diff --git a/backend/internal/repository/usage_log_repo_stats.go b/backend/internal/repository/usage_log_repo_stats.go index 7ec9ea639175..5c2c0dec97c8 100644 --- a/backend/internal/repository/usage_log_repo_stats.go +++ b/backend/internal/repository/usage_log_repo_stats.go @@ -3,6 +3,7 @@ package repository import ( "context" "database/sql" + "errors" "fmt" "os" "sort" @@ -921,14 +922,36 @@ func (r *usageLogRepository) GetAccountUsageStats(ctx context.Context, accountID COALESCE(SUM(input_tokens + output_tokens + cache_creation_tokens + cache_read_tokens), 0) as tokens, COALESCE(SUM(total_cost), 0) as cost, COALESCE(SUM(COALESCE(account_stats_cost, total_cost) * COALESCE(account_rate_multiplier, 1)), 0) as actual_cost, - COALESCE(SUM(actual_cost), 0) as user_cost + COALESCE(SUM(actual_cost), 0) as user_cost,COALESCE(sum(duration_ms),0),count(duration_ms) FROM usage_logs WHERE account_id = $1 AND created_at >= $2 AND created_at < $3 GROUP BY date ORDER BY date ASC ` - rows, err := r.sql.QueryContext(ctx, query, accountID, startTime, endTime) + reader := r.sql + args := []any{accountID, startTime, endTime} + var tx *sql.Tx + if r.db != nil { + tx, err = r.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + err = accountUsageReady(ctx, tx, startTime, endTime) + if err == nil { + query = accountUsageWindow + ` SELECT TO_CHAR(at,'YYYY-MM-DD') AS date,sum(requests),sum(tokens),sum(standard_charge),sum(account_charge),sum(user_charge),sum(duration_sum),sum(duration_count) + FROM facts GROUP BY date ORDER BY date` + reader = tx + args = []any{startTime, endTime, accountID} + } else if !errors.Is(err, service.ErrAccountUsageBuilding) { + return nil, err + } else { + // The existing single-account dialog remains available during backfill. + _ = tx.Rollback() + } + } + rows, err := reader.QueryContext(ctx, query, args...) if err != nil { return nil, err } @@ -941,6 +964,8 @@ func (r *usageLogRepository) GetAccountUsageStats(ctx context.Context, accountID } }() + var durationSum float64 + var durationCount int64 history := make([]AccountUsageHistory, 0) for rows.Next() { var date string @@ -949,9 +974,13 @@ func (r *usageLogRepository) GetAccountUsageStats(ctx context.Context, accountID var cost float64 var actualCost float64 var userCost float64 - if err = rows.Scan(&date, &requests, &tokens, &cost, &actualCost, &userCost); err != nil { + var dayDuration float64 + var daySamples int64 + if err = rows.Scan(&date, &requests, &tokens, &cost, &actualCost, &userCost, &dayDuration, &daySamples); err != nil { return nil, err } + durationSum += dayDuration + durationCount += daySamples t, _ := time.Parse("2006-01-02", date) history = append(history, AccountUsageHistory{ Date: date, @@ -992,10 +1021,12 @@ func (r *usageLogRepository) GetAccountUsageStats(ctx context.Context, accountID actualDaysUsed = 1 } - avgQuery := "SELECT COALESCE(AVG(duration_ms), 0) as avg_duration_ms FROM usage_logs WHERE account_id = $1 AND created_at >= $2 AND created_at < $3" var avgDuration float64 - if err := scanSingleRow(ctx, r.sql, avgQuery, []any{accountID, startTime, endTime}, &avgDuration); err != nil { - return nil, err + if durationCount > 0 { + avgDuration = durationSum / float64(durationCount) + } + if tx != nil { + _ = tx.Rollback() } summary := AccountUsageSummary{ diff --git a/backend/internal/service/dashboard_aggregation_service.go b/backend/internal/service/dashboard_aggregation_service.go index c1c2f5255fdd..786d469d3b18 100644 --- a/backend/internal/service/dashboard_aggregation_service.go +++ b/backend/internal/service/dashboard_aggregation_service.go @@ -97,6 +97,23 @@ func (s *DashboardAggregationService) Start() { if s == nil || s.repo == nil || s.timingWheel == nil { return } + if worker, ok := s.repo.(interface { + RefreshAccountUsageFinancial(context.Context) (bool, error) + }); ok { + s.timingWheel.ScheduleRecurring("account:financial-rollups", time.Minute, func() { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + for ctx.Err() == nil { + more, err := worker.RefreshAccountUsageFinancial(ctx) + if err != nil && ctx.Err() == nil { + slog.Warn("account usage rollup failed", "error", err) + } + if err != nil || !more { + return + } + } + }) + } if !s.cfg.Enabled { logger.LegacyPrintf("service.dashboard_aggregation", "[DashboardAggregation] 聚合作业已禁用") // Explicit runtime retention remains available without dashboard aggregation. diff --git a/backend/internal/service/profit_operations.go b/backend/internal/service/profit_operations.go index 76a098d8ffc8..e45b13bb55b2 100644 --- a/backend/internal/service/profit_operations.go +++ b/backend/internal/service/profit_operations.go @@ -32,6 +32,8 @@ const ProfitWalletTodaySkew = 5 * time.Minute // [from, until). A manual refresh ignores it. const ProfitSpendFreshness = 2 * time.Minute +var ErrAccountUsageBuilding = infraerrors.ServiceUnavailable("ACCOUNT_USAGE_BUILDING", "Account usage statistics are being aggregated") + const profitOperationsQueryTimeout = 5 * time.Minute type ProfitOperationsSnapshot struct { @@ -70,6 +72,16 @@ func NormalizeProfitOperationsFilter(f *UpstreamOperationsFilter) error { } f.ChannelID, f.Upstream = id, "" } + if f.AccountUsage { + switch f.Sort { + case "estimated_cost": + f.Sort = "upstream_cost" + case "estimated_profit": + f.Sort = "gross_profit" + case "margin": + f.Sort = "gross_margin" + } + } return ValidateProfitOperationsFilter(*f) } diff --git a/backend/internal/service/upstream_operations.go b/backend/internal/service/upstream_operations.go index 8456e719ea6f..7178e3638d48 100644 --- a/backend/internal/service/upstream_operations.go +++ b/backend/internal/service/upstream_operations.go @@ -16,19 +16,20 @@ import ( var ErrUpstreamOperationsValidation = infraerrors.BadRequest("UPSTREAM_OPERATIONS_VALIDATION", "运维查询参数无效:请检查时间范围、分页、模型口径及安全上游网址") type UpstreamOperationsFilter struct { - From time.Time `json:"from"` - Until time.Time `json:"until"` - Upstream string `json:"upstream"` - ChannelID int64 `json:"channel_id,omitempty"` - AccountID int64 `json:"account_id"` - GroupID int64 `json:"group_id"` - Model string `json:"model"` - ModelScope string `json:"model_scope"` - Dimension string `json:"dimension"` - Sort string `json:"sort"` - Direction string `json:"direction"` - Page int `json:"page"` - PageSize int `json:"page_size"` + AccountUsage bool `json:"account_usage,omitempty"` + From time.Time `json:"from"` + Until time.Time `json:"until"` + Upstream string `json:"upstream"` + ChannelID int64 `json:"channel_id,omitempty"` + AccountID int64 `json:"account_id"` + GroupID int64 `json:"group_id"` + Model string `json:"model"` + ModelScope string `json:"model_scope"` + Dimension string `json:"dimension"` + Sort string `json:"sort"` + Direction string `json:"direction"` + Page int `json:"page"` + PageSize int `json:"page_size"` } type UpstreamOperationsSnapshot struct { diff --git a/backend/migrations/393_account_usage_financial_rollups.sql b/backend/migrations/393_account_usage_financial_rollups.sql new file mode 100644 index 000000000000..7e740be3863f --- /dev/null +++ b/backend/migrations/393_account_usage_financial_rollups.sql @@ -0,0 +1,69 @@ +-- The row shape is shared by the account usage dialog and the profit report. +-- Index time first for reports and account first for the account dialog. +CREATE TABLE account_usage_financial_rollups ( + bucket timestamptz NOT NULL, + account_id bigint NOT NULL, + group_id bigint, + model text NOT NULL, + public_model text NOT NULL, + upstream_model text, + requests bigint NOT NULL, + tokens numeric NOT NULL, + standard_charge numeric NOT NULL, + user_charge numeric NOT NULL, + account_charge numeric NOT NULL, + duration_sum numeric NOT NULL, + duration_count bigint NOT NULL +); +CREATE INDEX account_usage_financial_time ON account_usage_financial_rollups(bucket); +CREATE INDEX account_usage_financial_account ON account_usage_financial_rollups(account_id,bucket); + +CREATE TABLE account_usage_financial_pending (bucket timestamptz PRIMARY KEY); + +CREATE FUNCTION account_usage_bucket(timestamptz) RETURNS timestamptz +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT to_timestamp(floor(extract(epoch FROM $1) / 300)::bigint * 300) +$$; + +-- Transition tables coalesce a batch into one notification per time slice. +-- A shared writer lock pairs with the worker's exclusive lock. A late writer +-- either commits before the worker reads or queues the slice again afterwards. +CREATE FUNCTION queue_account_usage_financial() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + b timestamptz; + source text; +BEGIN + IF TG_OP = 'INSERT' THEN + source := 'SELECT account_usage_bucket(created_at) FROM added'; + ELSIF TG_OP = 'DELETE' THEN + source := 'SELECT account_usage_bucket(created_at) FROM removed'; + ELSE + source := 'SELECT account_usage_bucket(created_at) FROM added UNION ALL SELECT account_usage_bucket(created_at) FROM removed'; + END IF; + FOR b IN EXECUTE 'SELECT DISTINCT * FROM (' || source || ') bins ORDER BY 1' LOOP + PERFORM pg_advisory_xact_lock_shared(825393, (extract(epoch FROM b)/300)::integer); + INSERT INTO account_usage_financial_pending VALUES(b) ON CONFLICT DO NOTHING; + END LOOP; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_usage_financial_insert AFTER INSERT ON usage_logs +REFERENCING NEW TABLE AS added FOR EACH STATEMENT EXECUTE FUNCTION queue_account_usage_financial(); +CREATE TRIGGER account_usage_financial_update AFTER UPDATE ON usage_logs +REFERENCING OLD TABLE AS removed NEW TABLE AS added FOR EACH STATEMENT EXECUTE FUNCTION queue_account_usage_financial(); +CREATE TRIGGER account_usage_financial_delete AFTER DELETE ON usage_logs +REFERENCING OLD TABLE AS removed FOR EACH STATEMENT EXECUTE FUNCTION queue_account_usage_financial(); + +-- The migration seeds work using the time index. Each worker transaction reads +-- just one five-minute slice, including on the first installation. +INSERT INTO account_usage_financial_pending +SELECT generate_series(account_usage_bucket((SELECT min(created_at) FROM usage_logs)), + account_usage_bucket(now()),interval '5 minutes') ON CONFLICT DO NOTHING; + +CREATE VIEW account_usage_financial_events AS +SELECT created_at, account_id, group_id, model, COALESCE(NULLIF(requested_model,''),model) AS public_model, upstream_model, + 1::bigint AS requests,(input_tokens::bigint+output_tokens+cache_creation_tokens+cache_read_tokens)::numeric AS tokens, + total_cost AS standard_charge,actual_cost AS user_charge, + COALESCE(account_stats_cost,total_cost)*COALESCE(account_rate_multiplier,1) AS account_charge, + COALESCE(duration_ms,0)::numeric AS duration_sum,(duration_ms IS NOT NULL)::int AS duration_count +FROM usage_logs; diff --git a/docs/profit-operations.md b/docs/profit-operations.md index fbae403d5ac3..4a3e53afae67 100644 --- a/docs/profit-operations.md +++ b/docs/profit-operations.md @@ -1,6 +1,16 @@ # 利润运营与独立上游渠道归属 -利润运维页 `/admin/profit-operations` 按渠道显示本站请求的收入、成本、毛利润和毛利率。在「服务商管理」添加供应商后,无须再手建同名渠道;原有手工渠道仍可用。筛选和下钻使用渠道内部 ID,不按显示名称识别。 +## 按账号使用统计分析利润 + +利润页以每个账号「使用统计」的用户扣费为收入,以同页的账号计费为成本,按账号当前所属渠道加总。毛利润等于用户扣费减账号计费,毛利率为总毛利润除以总用户扣费。账号改绑渠道后,所选时段的账号小计会随当前归属展示。订阅请求沿用账号统计的用量计价值。 + +金额来自写入用量时保存的价格。后台每次更新五分钟的账号、请求分组和模型小计。首次升级按最近时段优先补齐历史,延迟写入、修改、删除会重新登记对应时段。完整历史时段使用已发布小计,精确时间边界和最近不足十分钟的用量按相同公式读取。窗口内有待补历史时,利润页提示稍后刷新。账号弹窗的模型与端点明细使用原有单账号查询。 + +## 钱包成本报表 API + +以下为既有钱包报表的口径。管理 API 调用方可以继续使用原快照接口,利润页面使用 `basis=account_usage`。 + +钱包报表接口 按渠道显示本站请求的收入、成本、毛利润和毛利率。在「服务商管理」添加供应商后,无须再手建同名渠道;原有手工渠道仍可用。筛选和下钻使用渠道内部 ID,不按显示名称识别。 例如周一开始手填 A 的网址和 Key、周五才登记 A:重新查询含周一的时段,原网址行里没有其他明确归属的请求会归入 A,不需要重新导入 Key,也不会在两行重复计数。这是报表分组,不改账号路由和历史用量。没有逐笔历史网址时,用原网址行的当前有效配置来认领。明确绑到**另一个**渠道的账号仍归该渠道。手动把渠道解成空(`channel_id` 为空)之后,若网址仍只对应一个服务商,请求回到该服务商,不再单独留下「未绑定 · URL 自动归类」行。两个服务商共用同一个站点键时不自动合并。只有唯一的 HTTPS 站点根地址或其 `/v1` API 地址参与认领,不把其他租户路径、动态或无法确定的地址并成同一站。`unknown:oauth_dynamic_endpoint`(页面上可能显示为未知上游)没有稳定网址,只按供应商导入、`provider_binding` 或已有渠道绑定归类;没有任何这种关联时才留在未知行。 @@ -10,20 +20,20 @@ ## 财务口径 -- **已绑定供应商:**打开利润页会先按**所选窗口**刷新每个已关联服务商的钱包消费,再用与该窗口起止时间相同的快照计算成本。快照存在 `provider_spend_snapshots`(`provider_id`、`window_from`、`window_until`、`amount`、`currency`、`observed_at`、`source`)。同一窗口约 2 分钟内已成功读过的快照会复用;页面上的「刷新此时段上游消费」会忽略这 2 分钟。失败时保留该窗口上一次成功的金额;若从未成功,成本不可用,并显示错误和时间。这个数字可能包含不是本站产生的支出,仍然整笔使用,不按本站请求拆开,也不再用逐笔上游账单。只有 USD 才与本站请求收费相减。 +- **已绑定供应商:**读取钱包报表会先按**所选窗口**刷新每个已关联服务商的钱包消费,再用与该窗口起止时间相同的快照计算成本。快照存在 `provider_spend_snapshots`(`provider_id`、`window_from`、`window_until`、`amount`、`currency`、`observed_at`、`source`)。同一窗口约 2 分钟内已成功读过的快照会复用;页面上的「刷新此时段上游消费」会忽略这 2 分钟。失败时保留该窗口上一次成功的金额;若从未成功,成本不可用,并显示错误和时间。这个数字可能包含不是本站产生的支出,仍然整笔使用,不按本站请求拆开,也不再用逐笔上游账单。只有 USD 才与本站请求收费相减。 - **今天和其他时段:**北京时间当天的窗口(从当天 0 点开始,结束于当前时刻附近约 5 分钟内,或直到次日 0 点)会同时更新渠道运维的「今日消费」(`mature_providers.metrics.today_spend`)。昨天、上周和自定义区间只写入对应窗口的快照,**不会**覆盖「今日消费」。没有窗口快照时,利润报表只在当天窗口回退到仍有效的「今日消费」。New API 请求 `/api/log/self/stat?type=2&start_timestamp=&end_timestamp=`,时间就是所选窗口。Sub2API 的当天仍请求 `/api/v1/usage/dashboard/stats`,优先 `today_actual_cost`,否则 `today_cost`,币种记为 USD。其他时段请求 `/api/v1/usage/dashboard/snapshot-v2?start_date=&end_date=&timezone=Asia/Shanghai`,汇总返回里的 `actual_cost`(优先趋势,否则模型),不用标价 `cost` / `total_cost`。该日期接口按北京时间的整天计算;窗口若不是整天,读到的是覆盖这些日期的日历日合计。较旧的 Sub2API 站点如果没有 `snapshot-v2`,该时段成本不可用,并保留已有快照。查询接口不接受比现在晚超过 1 分钟的结束时间。 - **下钻:**按账号或模型比较,或筛选账号、分组、模型时,不把钱包总额按比例分到每一行。钱包成本留在渠道合计;这些子集的上游成本显示不可用。 - **未绑定供应商:**包括只有手工渠道 ID、没有对应窗口钱包读数的渠道。估算成本 = 保存的 `usage_logs.total_cost` × 当前账号成本倍率 `extra.cost_multiplier`;未设置倍率时用 0.1。显式零倍率与缺少有效倍率不是一回事。上游刷新失败不会挡住这些估算行。 - **两种渠道:**请求收入取本站已保存的 `usage_logs.actual_cost`,订阅计价不等于现金收入。毛利润 = 收入 − 成本,毛利率 = 毛利润 ÷ 收入。明确的零价按零算,收入为零时不显示百分比。跨渠道合计先按各自口径计成本,再按总收入算毛利率,不平均每行百分比。同一窗口里,已绑定渠道用各自的钱包快照,未绑定渠道用倍率估算,再相加。 -打开利润页会为当前窗口刷新(或复用刚读过的)钱包快照,然后计算毛利润;页面显示最近一次成功读取的时间。打开渠道运维会自动刷新一次已保存登录态的服务商,更新卡片上的「今日消费」。两条路径都走渠道运维原来的探测会话,不会比那次探测更频繁地更换令牌,也不会把令牌或密文写进日志。页面不再提供「同步上游账单」。旧的逐笔同步代码可以留在仓库里,但不再决定本报表的成本。遇到 HTTP 429 时沿用利润同步的退避,不把不完整的读数写成新金额。 +读取钱包报表会为当前窗口刷新(或复用刚读过的)钱包快照,然后计算毛利润;页面显示最近一次成功读取的时间。打开渠道运维会自动刷新一次已保存登录态的服务商,更新卡片上的「今日消费」。两条路径都走渠道运维原来的探测会话,不会比那次探测更频繁地更换令牌,也不会把令牌或密文写进日志。页面不再提供「同步上游账单」。旧的逐笔同步代码可以留在仓库里,但不再决定本报表的成本。遇到 HTTP 429 时沿用利润同步的退避,不把不完整的读数写成新金额。 ## 服务商对账与隔离试用 仅在测试实例上从源码构建此分支;使用独立的 PostgreSQL、缓存、模拟上游及虚构 Key,不要指向生产服务。先保留测试库副本,再按项目正常启动流程应用迁移 383–387;回退测试环境请恢复副本,不要手工删除业务表。打开利润页或渠道运维会按上面的规则向已保存的服务商读取钱包,不会逐笔拉取 `/api/v1/usage`。离线用例通过模拟 HTTP 传输提供上游响应;管理页面的实际连接仍要求受控的公网 HTTPS 测试站,不能用 localhost,也不要为试用关闭地址校验。 1. 给手填网址和 Key 的测试账号记两笔虚构请求,再在服务商管理添加同网址的 A。选择含这两笔请求的日期,确认两笔只出现在 A 下;不更动账号,也不等下一笔请求。 -2. 打开利润页并选择北京时间当天。A 的上游成本等于刚读到的当天钱包消费,即使另有逐笔账单或共享钱包里的其他支出。把窗口换成昨天或其他区间时,使用该区间自己的快照;没有快照时成本不可用,不能把今天的数字填进去。今天的「今日消费」也不会被昨天的金额覆盖。 +2. 读取钱包报表并选择北京时间当天。A 的上游成本等于刚读到的当天钱包消费,即使另有逐笔账单或共享钱包里的其他支出。把窗口换成昨天或其他区间时,使用该区间自己的快照;没有快照时成本不可用,不能把今天的数字填进去。今天的「今日消费」也不会被昨天的金额覆盖。 3. 登记日期不是查询起点。没有逐笔请求标识的历史请求仍可归到 A,但不会因此生成一笔虚构的逐笔成本。按账号或模型下钻时,渠道合计仍是整笔窗口消费,每一行不显示分摊金额。手动解除 A 的渠道绑定后,只要网址仍然只属于 A,这些请求回到 A,而不是单独的未绑定网址行。 验收例:本站两笔收入合计 100,当天钱包消费为 60 USD。即使上游用量明细是 32 和 13、另有余额实扣,主表也应为 **成本 60、毛利润 40、毛利率 40%**。同一钱包不会按两笔请求各计一次。另一个未绑定供应商的手工渠道仍按倍率估算;和 A 加总时,成本是 60 加上该渠道的估算。钱包消费为 0 时成本是 0,而不是不可用。昨天若有匹配的 15 USD 快照,则该窗口成本是 15,而不是 60。 diff --git a/docs/screenshots/channel-config/account-usage-profit.png b/docs/screenshots/channel-config/account-usage-profit.png new file mode 100644 index 000000000000..dbc211b5e9c0 Binary files /dev/null and b/docs/screenshots/channel-config/account-usage-profit.png differ diff --git a/frontend/src/api/admin/profitOperations.ts b/frontend/src/api/admin/profitOperations.ts index b59f5bfe3c02..bf6a221a73d9 100644 --- a/frontend/src/api/admin/profitOperations.ts +++ b/frontend/src/api/admin/profitOperations.ts @@ -17,7 +17,7 @@ export interface ProfitMetrics { unknown_standard_requests: number; unknown_income_requests: number; unmetered_zero_records: number; cost_covered_requests: number; unknown_cost_requests: number; unknown_upstream_requests: number saved_multiplier_requests: number; default_multiplier_requests: number; saved_stats_base_requests: number; standard_base_fallback_requests: number subscription_requests: number; deleted_account_requests: number; samples: number; unknown_samples: number - cost_source?: 'estimate' | 'wallet_today' | 'wallet_window' | 'wallet_unavailable' | 'wallet_not_split' | 'wallet_currency' | 'mixed' + cost_source?: 'account_usage' | 'estimate' | 'wallet_today' | 'wallet_window' | 'wallet_unavailable' | 'wallet_not_split' | 'wallet_currency' | 'mixed' wallet_basis?: 'wallet_today' | 'wallet_window' wallet_currency?: string | null wallet_observed_at?: string | null @@ -30,13 +30,13 @@ export interface OperationsRow extends ProfitMetrics { key: string; name: string export interface AccountBasis { id: number; name: string; key: string; attribution: string; updated_at: string; deleted: boolean; multiplier: number | null; cost_basis: string } export interface OperationsSnapshot { scope: OperationsQuery; queried_at: string; attribution: string; currency: string - usage: { summary: ProfitMetrics; rows: OperationsRow[]; total: number; wallet_synced_at?: string | null; accounts: AccountBasis[]; members: AccountBasis[]; member_total: number; capacity: { accounts: number; schedulable: number; configured_concurrency: number }; account_details_limit: number; catalog: Array<{key: string; name: string; accounts: number; channel_id?: number; channel_code?: string; channel_remark?: string; assignment?: string}>; catalog_total: number; historical_upstream_snapshot_requests: number; historical_cost_multiplier_snapshot_requests: number; cost_formula: string; income_source: string; standard_source: string } + usage: { basis?: 'account_usage'; summary: ProfitMetrics; rows: OperationsRow[]; total: number; wallet_synced_at?: string | null; accounts: AccountBasis[]; members: AccountBasis[]; member_total: number; capacity: { accounts: number; schedulable: number; configured_concurrency: number }; account_details_limit: number; catalog: Array<{key: string; name: string; accounts: number; channel_id?: number; channel_code?: string; channel_remark?: string; assignment?: string}>; catalog_total: number; historical_upstream_snapshot_requests: number; historical_cost_multiplier_snapshot_requests: number; cost_formula: string; income_source: string; standard_source: string } quality: Section; errors: Section } export async function readProfitOperations( params: OperationsQuery, signal?: AbortSignal, refreshSpend = false, refreshReport = false): Promise { // Full-range accounting may take minutes; leave time for the server's five-minute budget and response. // refresh_spend bypasses the short same-window cache. It does not sync per-request bills. - return (await apiClient.get('/admin/profit-operations/snapshot', { params: { ...params, ...(refreshReport ? { refresh_report: 1 } : {}), ...(refreshSpend ? { refresh_spend: 1 } : {}) }, signal, timeout: 330_000 })).data + return (await apiClient.get('/admin/profit-operations/snapshot', { params: { ...params, ...(refreshSpend ? {} : { basis: 'account_usage' }), ...(refreshReport ? { refresh_report: 1 } : {}), ...(refreshSpend ? { refresh_spend: 1 } : {}) }, signal, timeout: 330_000 })).data } export interface ProfitProvider extends Pick { cost_mode?: 'estimate' | 'wallet' diff --git a/frontend/src/components/admin/operations/ProfitAnalytics.vue b/frontend/src/components/admin/operations/ProfitAnalytics.vue index 9b5e2d410e49..2932a97f8f6d 100644 --- a/frontend/src/components/admin/operations/ProfitAnalytics.vue +++ b/frontend/src/components/admin/operations/ProfitAnalytics.vue @@ -1,11 +1,11 @@