Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/scripts/upstream-channel-entities-screenshot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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}]};
Expand Down Expand Up @@ -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')
Expand Down
6 changes: 4 additions & 2 deletions .github/workflows/upstream-channel-operations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion backend/internal/handler/admin/profit_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,14 +40,20 @@ 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)
}
return h.channelService.ProfitOperations(ctx, f)
})
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"
}
Expand Down
81 changes: 81 additions & 0 deletions backend/internal/repository/account_usage_financial.go
Original file line number Diff line number Diff line change
@@ -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<hi AND ($3::bigint=0 OR account_id=$3)
UNION ALL
SELECT created_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_events,bounds WHERE created_at>=$1 AND created_at<lo AND ($3::bigint=0 OR account_id=$3)
UNION ALL
SELECT created_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_events,bounds WHERE 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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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))
Expand Down
11 changes: 11 additions & 0 deletions backend/internal/repository/dashboard_aggregation_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
Expand Down
3 changes: 3 additions & 0 deletions backend/internal/repository/profit_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 61 additions & 0 deletions backend/internal/repository/profit_operations_account_usage.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading