diff --git a/.github/scripts/upstream-channel-entities-screenshot.mjs b/.github/scripts/upstream-channel-entities-screenshot.mjs index e186da3f07bb..4584edeba500 100644 --- a/.github/scripts/upstream-channel-entities-screenshot.mjs +++ b/.github/scripts/upstream-channel-entities-screenshot.mjs @@ -44,7 +44,12 @@ 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:[]}}}; - }else if(url.includes('management-capabilities'))data={web_search_enabled:false,account_quota_notify_enabled:false}; + }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:[]}; + else if(url==='/admin/account-ops/groups')data={groups:[]}; + else if(url==='/admin/account-ops/alerts')data={items:[],has_more:false}; + else if(url.includes('management-capabilities'))data={web_search_enabled:false,account_quota_notify_enabled:false}; else if(url.includes('credential-encryption'))data={configured:true,source:'server_config'}; else if(url.includes('check-mixed-channel'))data={has_risk:false}; else if(url.includes('/settings'))data={run_mode:'simple',site_name:'Synthetic upstream channels'}; @@ -57,13 +62,13 @@ apiClient.defaults.adapter=async config=>{ }; ` const shell=`import {h} from 'vue';export default {setup(_,ctx){return()=>h('main',{class:'mx-auto max-w-7xl p-4'},ctx.slots.default?.())}}` -const html=`
` process.chdir(frontend) -const server=await createServer({root:frontend,configFile:false,plugins:[vue(),{name:'entity-offline',resolveId(id){if(id.startsWith('virtual:entity-'))return '\0'+id},load(id){if(id==='\0virtual:entity-fixture')return fixture;if(id==='\0virtual:entity-shell')return shell},configureServer(vite){vite.middlewares.use((req,res,next)=>{if(['/admin/profit-operations','/admin/upstream-channels','/admin/accounts'].includes(req.url?.split('?')[0])){res.setHeader('Content-Type','text/html');void vite.transformIndexHtml(req.url,html).then(v=>res.end(v));return}next()})}}],resolve:{alias:[{find:'@/components/layout/AppLayout.vue',replacement:'virtual:entity-shell'},{find:'@',replacement:path.join(frontend,'src')}]},css:{postcss:{plugins:[tailwind({config:path.join(frontend,'tailwind.config.js')}),autoprefixer()]}},server:{host:'127.0.0.1',port:4185,strictPort:true},optimizeDeps:{noDiscovery:true,include:['vue','vue-i18n','pinia','vue-router','axios','@vueuse/core','@tanstack/vue-virtual','chart.js','vue-chartjs','dompurify','qrcode','driver.js']}}) +const server=await createServer({root:frontend,configFile:false,plugins:[vue(),{name:'entity-offline',resolveId(id){if(id.startsWith('virtual:entity-'))return '\0'+id},load(id){if(id==='\0virtual:entity-fixture')return fixture;if(id==='\0virtual:entity-shell')return shell},configureServer(vite){vite.middlewares.use((req,res,next)=>{if(['/admin/channel-config','/admin/profit-operations','/admin/upstream-channels','/admin/accounts'].includes(req.url?.split('?')[0])){res.setHeader('Content-Type','text/html');void vite.transformIndexHtml(req.url,html).then(v=>res.end(v));return}next()})}}],resolve:{alias:[{find:'@/components/layout/AppLayout.vue',replacement:'virtual:entity-shell'},{find:'@',replacement:path.join(frontend,'src')}]},css:{postcss:{plugins:[tailwind({config:path.join(frontend,'tailwind.config.js')}),autoprefixer()]}},server:{host:'127.0.0.1',port:4185,strictPort:true},optimizeDeps:{noDiscovery:true,include:['vue','vue-i18n','pinia','vue-router','axios','@vueuse/core','@tanstack/vue-virtual','chart.js','vue-chartjs','dompurify','qrcode','driver.js']}}) await server.listen();const browser=await chromium.launch({headless:true}) const page=await browser.newPage({viewport:{width:1440,height:1100}}),errors=[],network=[] page.on('pageerror',e=>errors.push(e.message));await page.route('**/*',r=>{const url=new URL(r.request().url());if(url.pathname.startsWith('/api/')||url.hostname!=='127.0.0.1'){network.push(r.request().url());return r.abort()}return r.continue()}) @@ -107,6 +112,18 @@ 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.goto('http://127.0.0.1:4185/admin/channel-config',{waitUntil:'networkidle'}) + await page.getByTestId('new-upstream-channel').waitFor() + if(await page.evaluate(()=>globalThis.__entityFixture.calls.some(c=>c.url==='/admin/profit-operations/snapshot')))throw new Error('configuration triggered profit aggregation') + await page.screenshot({path:path.join(output,'channel-config-management.png'),fullPage:true}) + await page.getByTestId('config-panel-profit').locator('summary').first().click();await page.getByTestId('profit-summary').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) + await page.getByTestId('config-panel-accounts').locator('summary').first().click();await page.getByTestId('account-ops-tab-settings').waitFor() + if(await page.evaluate(()=>globalThis.__entityFixture.calls.filter(c=>c.url==='/admin/profit-operations/snapshot').length)!==reportCalls)throw new Error('account panel recomputed profit') + await page.screenshot({path:path.join(output,'channel-config-accounts.png'),fullPage:true}) + await page.setViewportSize({width:390,height:844});await page.evaluate(()=>document.documentElement.classList.add('dark')) + await page.screenshot({path:path.join(output,'channel-config-mobile-dark.png'),fullPage:true}) if(errors.length||network.length)throw new Error(JSON.stringify({errors,network})) await fs.writeFile(path.join(output,'entity-verification.json'),JSON.stringify({commit:execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim(),actualViews:['ProfitOperationsView','UpstreamChannelsView','AccountsView'],synthetic:true,liveApiCalls:0,paidRequests:0,browserErrors:errors,calls:await page.evaluate(()=>globalThis.__entityFixture.calls)},null,2)) }catch(error){await page.screenshot({path:path.join(output,'entity-failure.png'),fullPage:true});await fs.writeFile(path.join(output,'entity-failure.txt'),String(error)+'\n'+JSON.stringify({errors,network})+'\n'+await page.locator('body').innerText());throw error}finally{await browser.close();await server.close()} diff --git a/.github/workflows/profit-operations.yml b/.github/workflows/profit-operations.yml index feb858f2b935..bd8160276c55 100644 --- a/.github/workflows/profit-operations.yml +++ b/.github/workflows/profit-operations.yml @@ -77,7 +77,7 @@ jobs: cache: pnpm cache-dependency-path: frontend/pnpm-lock.yaml - run: pnpm --dir frontend install --frozen-lockfile - - run: pnpm exec vitest run src/views/admin/__tests__/ProfitOperationsView.spec.ts src/views/admin/__tests__/ProviderProfit.spec.ts src/components/admin/operations/__tests__/SmartOpsNav.spec.ts src/components/layout/__tests__/AppSidebar.spec.ts --maxWorkers=1 --minWorkers=1 --no-file-parallelism + - run: pnpm exec vitest run src/views/admin/__tests__/ChannelConfigView.spec.ts src/views/admin/__tests__/ProfitOperationsView.spec.ts src/views/admin/__tests__/ProviderProfit.spec.ts src/components/admin/operations/__tests__/SmartOpsNav.spec.ts src/components/layout/__tests__/AppSidebar.spec.ts --maxWorkers=1 --minWorkers=1 --no-file-parallelism working-directory: frontend - name: Calendar presets in local timezones working-directory: frontend diff --git a/backend/internal/handler/admin/channel_handler.go b/backend/internal/handler/admin/channel_handler.go index 9a6818ae649d..f7b28005876b 100644 --- a/backend/internal/handler/admin/channel_handler.go +++ b/backend/internal/handler/admin/channel_handler.go @@ -20,6 +20,7 @@ import ( // ChannelHandler handles admin channel management type ChannelHandler struct { profitJobs providerProfitJobs + profitReports profitReportCache providerCancel context.CancelFunc providerWG sync.WaitGroup providerEncryptor service.SecretEncryptor diff --git a/backend/internal/handler/admin/mature_providers.go b/backend/internal/handler/admin/mature_providers.go index 09fcb9bb3dc3..a961501126a8 100644 --- a/backend/internal/handler/admin/mature_providers.go +++ b/backend/internal/handler/admin/mature_providers.go @@ -119,9 +119,11 @@ func (h *ChannelHandler) MutateMatureProvider(c *gin.Context) { return } if out == nil { + h.profitReports.clear() response.Success(c, gin.H{"deleted": id}) return } middleware.SetAuditExtra(c, map[string]any{"provider_id": out.ID, "revision": out.Revision}) + h.profitReports.clear() response.Success(c, out) } diff --git a/backend/internal/handler/admin/profit_operations.go b/backend/internal/handler/admin/profit_operations.go index dfbf8cf25ae9..9df893d5921b 100644 --- a/backend/internal/handler/admin/profit_operations.go +++ b/backend/internal/handler/admin/profit_operations.go @@ -14,6 +14,7 @@ import ( // UpstreamOperations is shared by two independent, read-only admin endpoints. func (h *ChannelHandler) ProfitOperations(c *gin.Context) { + c.Header("Cache-Control", "no-store") account, e1 := operationsInt(c, "account_id", 0) group, e2 := operationsInt(c, "group_id", 0) channel, e7 := operationsInt(c, "channel_id", 0) @@ -33,9 +34,17 @@ func (h *ChannelHandler) ProfitOperations(c *gin.Context) { // Refresh (or reuse) each linked provider's wallet for this window before // the report subtracts it. A probe failure does not hide unbound estimates. force := c.Query("refresh_spend") == "1" || c.Query("refresh_spend") == "true" - h.refreshBoundProviderSpend(c.Request.Context(), f.From, f.Until, force) + if force || c.Query("refresh_report") == "1" { + h.profitReports.clear() + } started := time.Now() - out, err := h.channelService.ProfitOperations(c.Request.Context(), f) + 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 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, context.DeadlineExceeded) { @@ -49,3 +58,28 @@ func (h *ChannelHandler) ProfitOperations(c *gin.Context) { } response.Success(c, out) } + +func (h *ChannelHandler) ProfitChannelAccountIDs(c *gin.Context) { + id, err := operationsInt(c, "channel_id", 0) + if err != nil || id <= 0 { + response.ErrorFrom(c, service.ErrUpstreamOperationsValidation) + return + } + repo, ok := h.upstreamChannelRepo(c) + if !ok { + return + } + reader, ok := repo.(interface { + ProfitChannelAccountIDs(context.Context, int64) ([]int64, error) + }) + if !ok { + response.ErrorFrom(c, service.ErrProviderProfitLinkUnavailable) + return + } + ids, err := reader.ProfitChannelAccountIDs(c.Request.Context(), id) + if err != nil { + response.Error(c, http.StatusInternalServerError, "Unable to read channel accounts") + return + } + response.Success(c, gin.H{"account_ids": ids}) +} diff --git a/backend/internal/handler/admin/profit_operations_cache.go b/backend/internal/handler/admin/profit_operations_cache.go new file mode 100644 index 000000000000..dbc99ea4f41a --- /dev/null +++ b/backend/internal/handler/admin/profit_operations_cache.go @@ -0,0 +1,216 @@ +package admin + +import ( + "context" + "encoding/json" + "errors" + "math/big" + "sort" + "strings" + "sync" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "golang.org/x/sync/singleflight" +) + +// Cache only aggregated admin reports, never usage rows or credentials. The +// original observation time remains visible. Eight entries, each <= 4 MiB. +type profitReportCache struct { + mu sync.Mutex + generation uint64 + slots chan struct{} + entries map[service.UpstreamOperationsFilter]profitReportEntry + flight singleflight.Group +} +type profitReportEntry struct { + raw []byte + expires time.Time +} + +func (c *profitReportCache) clear() { + c.mu.Lock() + defer c.mu.Unlock() + c.generation++ + c.entries = nil +} +func (c *profitReportCache) read(ctx context.Context, f service.UpstreamOperationsFilter, load func(context.Context, bool) (*service.ProfitOperationsSnapshot, error)) (*service.ProfitOperationsSnapshot, error) { + key := f + key.Page = 1 + key.PageSize = 20 + key.Sort = "requests" + key.Direction = "desc" + key.From = key.From.UTC() + key.Until = key.Until.UTC() + c.mu.Lock() + if c.slots == nil { + c.slots = make(chan struct{}, 2) + } + slots := c.slots + generation := c.generation + entry, ok := c.entries[key] + c.mu.Unlock() + if ok && time.Now().Before(entry.expires) { + return pageProfitReport(entry.raw, f) + } + encoded, _ := json.Marshal(struct { + Filter service.UpstreamOperationsFilter + Generation uint64 + }{key, generation}) + result := c.flight.DoChan(string(encoded), func() (any, error) { + // A leader's cancellation also cancels its query; failures are never cached. + c.mu.Lock() + entry, ok := c.entries[key] + c.mu.Unlock() + if ok && time.Now().Before(entry.expires) { + return entry.raw, nil + } + select { + case slots <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-slots }() + report, err := load(ctx, true) + if err != nil { + return nil, err + } + raw, err := json.Marshal(report) + if err != nil { + return nil, err + } + if len(raw) > 4<<20 || !profitReportFits(report) { + return []byte(nil), nil + } + c.mu.Lock() + defer c.mu.Unlock() + if generation == c.generation { + if c.entries == nil { + c.entries = make(map[service.UpstreamOperationsFilter]profitReportEntry) + } + if len(c.entries) >= 8 { + var oldest service.UpstreamOperationsFilter + var expires time.Time + for k, v := range c.entries { + if expires.IsZero() || v.expires.Before(expires) { + oldest = k + expires = v.expires + } + } + delete(c.entries, oldest) + } + c.entries[key] = profitReportEntry{raw: raw, expires: time.Now().Add(2 * time.Minute)} + } + return raw, nil + }) + select { + case <-ctx.Done(): + return nil, ctx.Err() + case r := <-result: + if r.Err != nil { + return nil, r.Err + } + raw, ok := r.Val.([]byte) + if !ok { + return nil, errors.New("invalid profit report cache result") + } + if raw == nil { + select { + case slots <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-slots }() + return load(ctx, false) + } + return pageProfitReport(raw, f) + } +} +func profitReportFits(r *service.ProfitOperationsSnapshot) bool { + var usage map[string]json.RawMessage + if json.Unmarshal(r.Usage, &usage) != nil { + return false + } + for _, key := range []string{"total", "member_total", "catalog_total"} { + var n int + if len(usage[key]) > 0 && (json.Unmarshal(usage[key], &n) != nil || n > 10000) { + return false + } + } + if r.Quality.Status == "ready" { + var q struct{ Total int } + if json.Unmarshal(r.Quality.Data, &q) != nil || q.Total > 10000 { + return false + } + } + return true +} +func pageProfitReport(raw []byte, f service.UpstreamOperationsFilter) (*service.ProfitOperationsSnapshot, error) { + var out service.ProfitOperationsSnapshot + if err := json.Unmarshal(raw, &out); err != nil { + return nil, err + } + out.Scope = f + var usage map[string]json.RawMessage + if err := json.Unmarshal(out.Usage, &usage); err != nil { + return nil, err + } + for _, field := range []string{"rows", "members", "catalog"} { + if len(usage[field]) == 0 { + continue + } + var rows []map[string]json.RawMessage + if err := json.Unmarshal(usage[field], &rows); err != nil { + return nil, err + } + if field == "rows" { + sort.SliceStable(rows, func(i, j int) bool { + a, b := rows[i][f.Sort], rows[j][f.Sort] + an, bn := len(a) == 0 || string(a) == "null", len(b) == 0 || string(b) == "null" + if an != bn { + return !an + } + cmp := 0 + if !an { + if f.Sort == "name" { + var x, y string + _ = json.Unmarshal(a, &x) + _ = json.Unmarshal(b, &y) + cmp = strings.Compare(x, y) + } else { + x, xok := new(big.Rat).SetString(string(a)) + y, yok := new(big.Rat).SetString(string(b)) + if xok && yok { + cmp = x.Cmp(y) + } + } + } + if cmp == 0 { + return strings.Compare(string(rows[i]["key"]), string(rows[j]["key"])) < 0 + } + if f.Direction == "desc" { + return cmp > 0 + } + return cmp < 0 + }) + } + start := min((f.Page-1)*f.PageSize, len(rows)) + end := min(start+f.PageSize, len(rows)) + usage[field], _ = json.Marshal(rows[start:end]) + } + out.Usage, _ = json.Marshal(usage) + if out.Quality.Status == "ready" { + var quality map[string]json.RawMessage + if err := json.Unmarshal(out.Quality.Data, &quality); err != nil { + return nil, err + } + var rows []json.RawMessage + if err := json.Unmarshal(quality["rows"], &rows); err != nil { + return nil, err + } + start := min((f.Page-1)*f.PageSize, len(rows)) + quality["rows"], _ = json.Marshal(rows[start:min(start+f.PageSize, len(rows))]) + out.Quality.Data, _ = json.Marshal(quality) + } + return &out, nil +} diff --git a/backend/internal/handler/admin/profit_operations_cache_test.go b/backend/internal/handler/admin/profit_operations_cache_test.go new file mode 100644 index 000000000000..7706d80fc7f6 --- /dev/null +++ b/backend/internal/handler/admin/profit_operations_cache_test.go @@ -0,0 +1,67 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "testing" + "time" +) + +func TestProfitOperationsCachePagesSortAndInvalidation(t *testing.T) { + var cache profitReportCache + calls := 0 + f := service.UpstreamOperationsFilter{From: time.Now().Add(-time.Hour), Until: time.Now(), Dimension: "upstream", Sort: "upstream_cost", Direction: "asc", Page: 1, PageSize: 1} + load := func(_ context.Context, collect bool) (*service.ProfitOperationsSnapshot, error) { + calls++ + require.True(t, collect) + return &service.ProfitOperationsSnapshot{UpstreamOperationsSnapshot: service.UpstreamOperationsSnapshot{Scope: f, QueriedAt: f.Until, Usage: json.RawMessage(`{"summary":{"requests":1000000,"request_income":123},"rows":[{"key":"missing","upstream_cost":null},{"key":"two","upstream_cost":2},{"key":"one","upstream_cost":1}],"total":3,"members":[],"member_total":0,"catalog":[],"catalog_total":0}`)}}, nil + } + first, err := cache.read(context.Background(), f, load) + require.NoError(t, err) + require.Contains(t, string(first.Usage), `"key":"one"`) + f.Page = 2 + second, err := cache.read(context.Background(), f, load) + require.NoError(t, err) + require.Contains(t, string(second.Usage), `"key":"two"`) + require.Equal(t, first.QueriedAt, second.QueriedAt) + f.Page = 1 + f.Direction = "desc" + third, err := cache.read(context.Background(), f, load) + require.NoError(t, err) + require.Contains(t, string(third.Usage), `"key":"two"`) + require.Equal(t, 1, calls) + f.Page = 3 + last, err := cache.read(context.Background(), f, load) + require.NoError(t, err) + require.Contains(t, string(last.Usage), `"key":"missing"`) + cache.clear() + _, err = cache.read(context.Background(), f, load) + require.NoError(t, err) + require.Equal(t, 2, calls) + f.AccountID = 4 + _, err = cache.read(context.Background(), f, load) + require.NoError(t, err) + require.Equal(t, 3, calls) +} +func TestProfitOperationsCacheDoesNotCacheOversizedReports(t *testing.T) { + var cache profitReportCache + calls := 0 + f := service.UpstreamOperationsFilter{Page: 1, PageSize: 20} + load := func(_ context.Context, collect bool) (*service.ProfitOperationsSnapshot, error) { + calls++ + raw := `{"total":10001}` + if !collect { + raw = `{"total":10001,"rows":[]}` + } + return &service.ProfitOperationsSnapshot{UpstreamOperationsSnapshot: service.UpstreamOperationsSnapshot{Usage: json.RawMessage(raw)}}, nil + } + for i := 0; i < 2; i++ { + _, err := cache.read(context.Background(), f, load) + require.NoError(t, err) + } + require.Equal(t, 4, calls) +} diff --git a/backend/internal/handler/admin/profit_operations_test.go b/backend/internal/handler/admin/profit_operations_test.go index 9ffdcc127e73..35aae35435da 100644 --- a/backend/internal/handler/admin/profit_operations_test.go +++ b/backend/internal/handler/admin/profit_operations_test.go @@ -40,7 +40,7 @@ func TestProfitOperationsHTTPIndependentScopesAndSafeFailure(t *testing.T) { h := NewChannelHandler(service.NewChannelService(repo, nil, nil, nil, nil), nil, nil) r := gin.New() r.GET("/upstream", h.ProfitOperations) - path := "/upstream?from=2026-10-01T00:00:00Z&until=2026-10-02T00:00:00Z&account_id=42&dimension=model&model_scope=upstream&sort=estimated_profit&direction=asc" + path := "/upstream?refresh_report=1&from=2026-10-01T00:00:00Z&until=2026-10-02T00:00:00Z&account_id=42&dimension=model&model_scope=upstream&sort=estimated_profit&direction=asc" w := httptest.NewRecorder() r.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) require.Equal(t, 200, w.Code) diff --git a/backend/internal/handler/admin/provider_profit_links.go b/backend/internal/handler/admin/provider_profit_links.go index dfadc5d7c24b..efc7d4ff5922 100644 --- a/backend/internal/handler/admin/provider_profit_links.go +++ b/backend/internal/handler/admin/provider_profit_links.go @@ -68,5 +68,6 @@ func (h *ChannelHandler) SetProviderProfitLink(c *gin.Context) { providerProfitLinkError(c, err) return } + h.profitReports.clear() response.Success(c, out) } diff --git a/backend/internal/handler/admin/provider_profit_links_test.go b/backend/internal/handler/admin/provider_profit_links_test.go index d155d51e0395..37bad22e1540 100644 --- a/backend/internal/handler/admin/provider_profit_links_test.go +++ b/backend/internal/handler/admin/provider_profit_links_test.go @@ -32,7 +32,7 @@ func (s *providerProfitLinkStub) SetProviderProfitLink(_ context.Context, id int return &s.item, nil } func TestProviderProfitLinkHandlerContract(t *testing.T) { - s := &providerProfitLinkStub{item: service.ProviderProfitLink{ProviderID: 7, ProviderName: "Fixture", SiteType: "newapi", ChannelID: 19, ChannelName: "Fixture channel", Revision: 3, Status: "disconnected"}} + s := &providerProfitLinkStub{item: service.ProviderProfitLink{CostMode: "estimate", ProviderID: 7, ProviderName: "Fixture", SiteType: "newapi", ChannelID: 19, ChannelName: "Fixture channel", Revision: 3, Status: "disconnected"}} h := NewChannelHandler(service.NewChannelService(s, nil, nil, nil, nil), nil, nil) r := gin.New() r.GET("/providers", h.ListProviderProfitLinks) @@ -48,11 +48,11 @@ func TestProviderProfitLinkHandlerContract(t *testing.T) { w := call("GET", "/providers?page=1&page_size=10", "") require.Equal(t, 200, w.Code) require.Equal(t, "no-store", w.Header().Get("Cache-Control")) - require.JSONEq(t, `{"code":0,"message":"success","data":{"items":[{"provider_id":7,"provider_name":"Fixture","site_type":"newapi","channel_id":19,"channel_name":"Fixture channel","revision":3,"observed_at":null,"status":"disconnected","metrics":{"today_spend":null,"total_spend":null,"currency":""}}],"total":1,"page":1,"page_size":10}}`, w.Body.String()) + require.JSONEq(t, `{"code":0,"message":"success","data":{"items":[{"cost_mode":"estimate","provider_id":7,"provider_name":"Fixture","site_type":"newapi","channel_id":19,"channel_name":"Fixture channel","revision":3,"observed_at":null,"status":"disconnected","metrics":{"today_spend":null,"total_spend":null,"currency":""}}],"total":1,"page":1,"page_size":10}}`, w.Body.String()) for _, path := range []string{"/providers?page=0", "/providers?page_size=101", "/providers?page=1.5"} { require.Equal(t, 400, call("GET", path, "").Code) } - for _, body := range []string{`{}`, `{"channel_id":5,"revision":3}`, `{"channel_id":0,"revision":3,"confirm":true}`, `{"channel_id":5,"revision":0,"confirm":true}`, `{"channel_id":5,"revision":3,"confirm":true,"unexpected":42}`, `{"channel_id":5,"revision":3,"confirm":true}{}`} { + for _, body := range []string{`{"channel_id":5,"revision":3,"confirm":true,"cost_mode":"invalid"}`, `{}`, `{"channel_id":5,"revision":3}`, `{"channel_id":0,"revision":3,"confirm":true}`, `{"channel_id":5,"revision":0,"confirm":true}`, `{"channel_id":5,"revision":3,"confirm":true,"unexpected":42}`, `{"channel_id":5,"revision":3,"confirm":true}{}`} { require.Equal(t, 400, call("PUT", "/providers/7", body).Code) } require.Zero(t, s.writes) diff --git a/backend/internal/handler/admin/upstream_channels.go b/backend/internal/handler/admin/upstream_channels.go index cde5acec24ab..71c37100ee27 100644 --- a/backend/internal/handler/admin/upstream_channels.go +++ b/backend/internal/handler/admin/upstream_channels.go @@ -92,10 +92,12 @@ func (h *ChannelHandler) MutateUpstreamChannel(c *gin.Context) { return } if out == nil { + h.profitReports.clear() response.Success(c, gin.H{"deleted": id}) return } middleware.SetAuditExtra(c, map[string]any{"target_channel_id": out.ID, "config_version": out.Revision}) + h.profitReports.clear() response.Success(c, out) } func (h *ChannelHandler) ReadUpstreamChannelBindings(c *gin.Context) { @@ -141,6 +143,7 @@ func (h *ChannelHandler) BindUpstreamChannelAccounts(c *gin.Context) { upstreamChannelError(c, e) return } + h.profitReports.clear() response.Success(c, gin.H{"items": out}) } func (h *ChannelHandler) UpstreamChannelMembers(c *gin.Context) { diff --git a/backend/internal/repository/profit_operations.go b/backend/internal/repository/profit_operations.go index 6488a76f3cb8..b7d4943f670a 100644 --- a/backend/internal/repository/profit_operations.go +++ b/backend/internal/repository/profit_operations.go @@ -190,7 +190,7 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS u.account_stats_cost,u.input_tokens,u.output_tokens,u.cache_read_tokens,u.cache_creation_tokens,u.duration_ms,u.billing_type,u.created_at,u.queue_timing,u.queue_wait_ms, COALESCE('channel:'||owner.channel_id::text,c.url_key,'unknown:account_missing') AS upstream_key, CASE WHEN e.channel_id IS NOT NULL OR h.channel_id IS NOT NULL THEN 'historical_channel' WHEN legacy.channel_id IS NOT NULL THEN 'legacy_channel_estimate' WHEN owner.channel_id IS NOT NULL THEN 'provider_url' ELSE COALESCE(c.url_attribution,'account_missing') END AS attribution, - c.name AS account_name,c.updated_at AS config_updated_at,c.deleted,c.multiplier,owner.channel_id AS explicit_channel_id,ch.name AS channel_name,ch.code AS channel_code,ch.remark AS channel_remark,ch.revision AS channel_revision,pl.provider_id,p.site_type AS provider_site_type, + c.name AS account_name,c.updated_at AS config_updated_at,c.deleted,c.multiplier,owner.channel_id AS explicit_channel_id,ch.name AS channel_name,ch.code AS channel_code,ch.remark AS channel_remark,ch.revision AS channel_revision,p.id AS provider_id,p.site_type AS provider_site_type, CASE WHEN snap.amount IS NOT NULL THEN snap.amount WHEN $18::bool AND jsonb_typeof(p.metrics->'today_spend')='number' AND p.observed_at>=$12::timestamptz AND p.observed_at<$13::timestamptz THEN (p.metrics->>'today_spend')::numeric END AS wallet_spend, CASE WHEN snap.amount IS NOT NULL AND snap.currency IN ('USD','CNY','quota_units') THEN snap.currency @@ -219,7 +219,7 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS END) AS channel_id) owner LEFT JOIN upstream_channels ch ON ch.id=owner.channel_id LEFT JOIN provider_profit_links pl ON pl.channel_id=owner.channel_id - LEFT JOIN mature_providers p ON p.id=pl.provider_id + LEFT JOIN mature_providers p ON p.id=pl.provider_id AND pl.cost_mode='wallet' LEFT JOIN provider_spend_snapshots snap ON snap.provider_id=p.id AND snap.window_from=$1 AND snap.window_until=$2 WHERE u.created_at >= $1 AND u.created_at < $2 AND ($5::bigint=0 OR u.account_id=$5) AND ($6::bigint=0 OR u.group_id=$6) AND ($7='' OR CASE $8 WHEN 'public' THEN COALESCE(NULLIF(u.requested_model,''),u.model) WHEN 'recorded' THEN u.model WHEN 'upstream' THEN u.upstream_model END=$7) @@ -302,7 +302,11 @@ func (r *channelRepository) ReadProfitOperations(ctx context.Context, f service. if err != nil { return nil, err } - args := []any{f.From, f.Until, string(raw), f.Upstream, f.AccountID, f.GroupID, f.Model, f.ModelScope, f.PageSize, (f.Page - 1) * f.PageSize, f.ChannelID} + size, offset := f.PageSize, (f.Page-1)*f.PageSize + if service.CollectProfitRows(ctx) { + size, offset = 10001, 0 + } + args := []any{f.From, f.Until, string(raw), f.Upstream, f.AccountID, f.GroupID, f.Model, f.ModelScope, size, offset, f.ChannelID} dimension, name := `upstream_key`, `COALESCE(NULLIF(max(channel_name),''),upstream_key)` channelFields := `,COALESCE(max(explicit_channel_id),0) AS channel_id,max(provider_id) AS provider_id,max(provider_site_type) AS provider_site_type,max(channel_code) AS channel_code,max(channel_remark) AS channel_remark,max(channel_revision) AS channel_revision,COALESCE(max(assignment),'unbound_unknown') AS assignment` switch f.Dimension { diff --git a/backend/internal/repository/profit_operations_cache_integration_test.go b/backend/internal/repository/profit_operations_cache_integration_test.go new file mode 100644 index 000000000000..9d8fe5d45265 --- /dev/null +++ b/backend/internal/repository/profit_operations_cache_integration_test.go @@ -0,0 +1,88 @@ +//go:build integration + +package repository_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http/httptest" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Reproducible isolated SQL comparison. Timings are observations, not pass/fail +// latency thresholds or a claim about the production million-request window. +func TestProfitOperationsCachedWindowTiming(t *testing.T) { + db, _ := repository.UpstreamChannelsTestDatabase(t) + id := func(query string, args ...any) int64 { + t.Helper() + var v int64 + require.NoError(t, db.QueryRow(query, args...).Scan(&v)) + return v + } + user := id(`INSERT INTO users(email,password_hash,balance) VALUES('cache@test.invalid','synthetic',0) RETURNING id`) + key := id(`INSERT INTO api_keys(user_id,key,name) VALUES($1,'cache-fixture','fixture') RETURNING id`, user) + a := id(`INSERT INTO accounts(name,platform,type,credentials) VALUES('alpha','openai','apikey','{"base_url":"https://fixture.invalid"}') RETURNING id`) + b := id(`INSERT INTO accounts(name,platform,type,credentials) VALUES('beta','openai','apikey','{"base_url":"https://fixture.invalid"}') RETURNING id`) + until := time.Now().UTC().Truncate(time.Second) + from := until.Add(-time.Hour) + _, err := db.Exec(`INSERT INTO usage_logs(user_id,api_key_id,account_id,request_id,model,total_cost,actual_cost,created_at) + SELECT $1,$2,CASE WHEN n%2=0 THEN $3::bigint ELSE $4::bigint END,'cache-'||n,'fixture-model',10,4,$5::timestamptz FROM generate_series(1,10000)n`, user, key, a, b, from.Add(time.Minute)) + require.NoError(t, err) + svc := service.NewChannelService(repository.NewChannelRepository(db), nil, nil, nil, nil) + f := service.UpstreamOperationsFilter{From: from, Until: until, Dimension: "account", ModelScope: "public", Sort: "requests", Direction: "desc", Page: 1, PageSize: 1} + var baseline []time.Duration + for i := 0; i < 3; i++ { + f.Page = 1 + i%2 + if i == 2 { + f.Sort = "name" + } + at := time.Now() + _, err := svc.ProfitOperations(context.Background(), f) + require.NoError(t, err) + baseline = append(baseline, time.Since(at)) + } + handler := admin.NewChannelHandler(svc, nil, nil) + r := gin.New() + r.GET("/snapshot", handler.ProfitOperations) + var cached []time.Duration + var observed time.Time + var summary json.RawMessage + for i := 0; i < 4; i++ { + sort := "requests" + if i >= 2 { + sort = "name" + } + target := fmt.Sprintf("/snapshot?from=%s&until=%s&dimension=account&sort=%s&page=%d&page_size=1", from.Format(time.RFC3339), until.Format(time.RFC3339), sort, 1+i%2) + w := httptest.NewRecorder() + at := time.Now() + r.ServeHTTP(w, httptest.NewRequest("GET", target, nil)) + cached = append(cached, time.Since(at)) + require.Equal(t, 200, w.Code, w.Body.String()) + var envelope struct { + Data service.ProfitOperationsSnapshot + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &envelope)) + var usage struct { + Summary json.RawMessage + Rows []json.RawMessage + } + require.NoError(t, json.Unmarshal(envelope.Data.Usage, &usage)) + require.Len(t, usage.Rows, 1) + if i == 0 { + observed = envelope.Data.QueriedAt + summary = usage.Summary + } else { + require.Equal(t, observed, envelope.Data.QueriedAt) + require.JSONEq(t, string(summary), string(usage.Summary)) + } + } + t.Logf("synthetic PostgreSQL rows=10000 timezone=UTC window=[%s,%s) uncached(first,page,sort)=%v cached(first,page,sort,repeat)=%v", from.Format(time.RFC3339), until.Format(time.RFC3339), baseline, cached) +} diff --git a/backend/internal/repository/profit_operations_provider_urls.go b/backend/internal/repository/profit_operations_provider_urls.go index 121368447781..0520a43f4e7e 100644 --- a/backend/internal/repository/profit_operations_provider_urls.go +++ b/backend/internal/repository/profit_operations_provider_urls.go @@ -3,6 +3,8 @@ package repository import ( "context" "database/sql" + "encoding/json" + "time" "github.com/Wei-Shaw/sub2api/internal/service" ) @@ -42,3 +44,37 @@ func profitURLDirectory(ctx context.Context, tx *sql.Tx) (map[string]profitURLPr } return directory, rows.Err() } + +// ProfitChannelAccountIDs uses the same current ownership projection as the +// report, without aggregating usage or requesting a provider wallet. +func (r *channelRepository) ProfitChannelAccountIDs(ctx context.Context, channel int64) ([]int64, error) { + ctx, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + tx, err := r.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + raw, err := profitOperationsAccounts(ctx, tx, service.UpstreamOperationsFilter{}) + if err != nil { + return nil, err + } + var accounts []struct { + ID int64 `json:"id"` + ChannelID int64 `json:"channel_id"` + Deleted bool `json:"deleted"` + } + if err = json.Unmarshal(raw, &accounts); err != nil { + return nil, err + } + ids := make([]int64, 0) + for _, account := range accounts { + if !account.Deleted && account.ChannelID == channel { + ids = append(ids, account.ID) + } + } + if err = tx.Commit(); err != nil { + return nil, err + } + return ids, nil +} diff --git a/backend/internal/repository/provider_profit_charge_integration_test.go b/backend/internal/repository/provider_profit_charge_integration_test.go index f0fb033eaa43..f4ccb314a0fb 100644 --- a/backend/internal/repository/provider_profit_charge_integration_test.go +++ b/backend/internal/repository/provider_profit_charge_integration_test.go @@ -50,7 +50,9 @@ func (f *profitChargeFixture) exec(q string, args ...any) { require.NoError(f.t, err) } func (f *profitChargeFixture) provider() int64 { - return f.id(`INSERT INTO mature_providers(name,site_type,base_url) VALUES('fixture','sub2api',$1) RETURNING id`, profitChargeBase) + pid := f.id(`INSERT INTO mature_providers(name,site_type,base_url) VALUES('fixture','sub2api',$1) RETURNING id`, profitChargeBase) + f.exec(`UPDATE provider_profit_links SET cost_mode='wallet',revision=revision+1 WHERE provider_id=$1`, pid) + return pid } func (f *profitChargeFixture) imported(provider, key int64) int64 { return f.id(`INSERT INTO accounts(name,type,platform,extra,credentials) VALUES('fixture','apikey','openai',jsonb_build_object('provider_binding',jsonb_build_object('provider_id',$1::bigint,'key_id',$2::text,'provider_revision',(SELECT revision FROM mature_providers WHERE id=$1))),jsonb_build_object('base_url',(SELECT rtrim(base_url,'/') FROM mature_providers WHERE id=$1),'api_key','fixture-only')) RETURNING id`, provider, fmt.Sprint(key)) diff --git a/backend/internal/repository/provider_profit_links.go b/backend/internal/repository/provider_profit_links.go index 127c941423bb..657187a4df89 100644 --- a/backend/internal/repository/provider_profit_links.go +++ b/backend/internal/repository/provider_profit_links.go @@ -13,7 +13,7 @@ import ( // Select individual public fields; never select raw metrics, dashboard account, // observations' errors, URL, key provenance, or encrypted credentials. -const providerProfitLinkSelect = `SELECT p.id,p.name,p.site_type,c.id,c.name,l.revision,p.observed_at,p.status, +const providerProfitLinkSelect = `SELECT l.cost_mode,p.id,p.name,p.site_type,c.id,c.name,l.revision,p.observed_at,p.status, CASE WHEN jsonb_typeof(p.metrics->'today_spend')='number' THEN p.metrics->>'today_spend' END, CASE WHEN jsonb_typeof(p.metrics->'total_spend')='number' THEN p.metrics->>'total_spend' END, CASE WHEN p.metrics->>'currency' IN ('USD','CNY','quota_units') THEN p.metrics->>'currency' ELSE '' END @@ -21,7 +21,7 @@ const providerProfitLinkSelect = `SELECT p.id,p.name,p.site_type,c.id,c.name,l.r func scanProviderProfitLink(row interface{ Scan(...any) error }) (*service.ProviderProfitLink, error) { var v service.ProviderProfitLink - err := row.Scan(&v.ProviderID, &v.ProviderName, &v.SiteType, &v.ChannelID, &v.ChannelName, &v.Revision, &v.ObservedAt, &v.Status, &v.Metrics.TodaySpend, &v.Metrics.TotalSpend, &v.Metrics.Currency) + err := row.Scan(&v.CostMode, &v.ProviderID, &v.ProviderName, &v.SiteType, &v.ChannelID, &v.ChannelName, &v.Revision, &v.ObservedAt, &v.Status, &v.Metrics.TodaySpend, &v.Metrics.TotalSpend, &v.Metrics.Currency) if errors.Is(err, sql.ErrNoRows) { return nil, service.ErrProviderProfitLinkNotFound } @@ -89,7 +89,8 @@ func (r *channelRepository) SetProviderProfitLink(ctx context.Context, id int64, var out *service.ProviderProfitLink err := r.runInTx(ctx, func(tx *sql.Tx) error { var channel, revision int64 - err := tx.QueryRowContext(ctx, `SELECT channel_id,revision FROM provider_profit_links WHERE provider_id=$1 FOR UPDATE`, id).Scan(&channel, &revision) + var costMode string + err := tx.QueryRowContext(ctx, `SELECT channel_id,revision,cost_mode FROM provider_profit_links WHERE provider_id=$1 FOR UPDATE`, id).Scan(&channel, &revision, &costMode) if errors.Is(err, sql.ErrNoRows) { return service.ErrProviderProfitLinkNotFound } @@ -99,8 +100,11 @@ func (r *channelRepository) SetProviderProfitLink(ctx context.Context, id int64, if m.Revision != revision { return service.ErrProviderProfitLinkConflict } - if m.ChannelID != channel { - _, err = tx.ExecContext(ctx, `UPDATE provider_profit_links SET channel_id=$2,revision=revision+1 WHERE provider_id=$1`, id, m.ChannelID) + if m.CostMode != nil { + costMode = *m.CostMode + } + if m.ChannelID != channel || m.CostMode != nil { + _, err = tx.ExecContext(ctx, `UPDATE provider_profit_links SET channel_id=$2,cost_mode=$3,revision=revision+1 WHERE provider_id=$1`, id, m.ChannelID, costMode) if isUniqueViolation(err) { return service.ErrProviderProfitLinkConflict } diff --git a/backend/internal/repository/provider_profit_report_integration_test.go b/backend/internal/repository/provider_profit_report_integration_test.go index 1701cc78dd7f..aece571f0315 100644 --- a/backend/internal/repository/provider_profit_report_integration_test.go +++ b/backend/internal/repository/provider_profit_report_integration_test.go @@ -85,7 +85,7 @@ func TestProviderProfitReportPartialThenSettledWithSharedWallet(t *testing.T) { check("40", "40", "60", 2) mainMetrics("2", "45", "null", "null", "null") newChannel := f.id(`INSERT INTO upstream_channels(name,code) VALUES('New location','new-location') RETURNING id`) - _, err := f.r.SetProviderProfitLink(context.Background(), f.pid, service.ProviderProfitLinkMutation{Revision: 1, ChannelID: newChannel, Confirm: true}) + _, err := f.r.SetProviderProfitLink(context.Background(), f.pid, service.ProviderProfitLinkMutation{Revision: f.id(`SELECT revision FROM provider_profit_links WHERE provider_id=$1`, f.pid), ChannelID: newChannel, Confirm: true}) require.NoError(t, err) f.counts(w, 2, 0, a, b, external) check("40", "40", "60", 2) @@ -153,6 +153,7 @@ func TestProviderProfitReportRegisterSiteAfterUsage(t *testing.T) { check(rows[api], map[string]string{"requests": "1", "upstream_cost": "6", "supplier_requests": "0"}) check(s, map[string]string{"requests": "2", "request_income": "100", "upstream_cost": "12"}) pid := f.id(`INSERT INTO mature_providers(name,site_type,base_url) VALUES('Later supplier','sub2api',$1) RETURNING id`, site) + f.exec(`UPDATE provider_profit_links SET cost_mode='wallet',revision=revision+1 WHERE provider_id=$1`, pid) channel := f.id(`SELECT channel_id FROM provider_profit_links WHERE provider_id=$1`, pid) key := fmt.Sprintf("channel:%d", channel) s, rows = read() @@ -457,9 +458,43 @@ func TestProviderProfitLegacyIncomeUnchangedByFirstLink(t *testing.T) { require.JSONEq(t, "null", string(s["reconciled_cost"])) } check() - for rev, dest := range []int64{channel, f.channel} { - _, err := f.r.SetProviderProfitLink(context.Background(), f.pid, service.ProviderProfitLinkMutation{Revision: int64(rev + 1), ChannelID: dest, Confirm: true}) + for _, dest := range []int64{channel, f.channel} { + _, err := f.r.SetProviderProfitLink(context.Background(), f.pid, service.ProviderProfitLinkMutation{Revision: f.id(`SELECT revision FROM provider_profit_links WHERE provider_id=$1`, f.pid), ChannelID: dest, Confirm: true}) require.NoError(t, err) check() } } + +func TestProviderProfitNamingPreservesEstimateUntilWalletOptIn(t *testing.T) { + f := newProfitChargeFixture(t) + // A new URL/name record defaults to estimates, even without credentials. + pid := f.id(`INSERT INTO mature_providers(name,site_type,base_url) VALUES('new estimate','sub2api','https://estimate.invalid') RETURNING id`) + var mode string + require.NoError(t, f.db.QueryRow(`SELECT cost_mode FROM provider_profit_links WHERE provider_id=$1`, pid).Scan(&mode)) + require.Equal(t, "estimate", mode) + f.exec(`UPDATE provider_profit_links SET cost_mode='estimate',revision=revision+1 WHERE provider_id=$1`, f.pid) + at := f.now() + w := service.ProviderProfitWindow{From: at, Until: at.Add(time.Microsecond)} + f.usageWithIncome(f.account, "estimate-mode", at, 25) + before := f.report(f.channel, w) + f.exec(`UPDATE mature_providers SET name='Renamed only' WHERE id=$1`, f.pid) + f.exec(`UPDATE upstream_channels SET name='Renamed classification' WHERE id=$1`, f.channel) + after := f.report(f.channel, w) + ids, err := f.r.ProfitChannelAccountIDs(context.Background(), f.channel) + require.NoError(t, err) + require.Contains(t, ids, f.account) + for _, key := range []string{"requests", "request_income", "upstream_cost", "gross_profit", "cost_source"} { + require.JSONEq(t, string(before[key]), string(after[key])) + } + require.JSONEq(t, `"estimate"`, string(after["cost_source"])) + var revision int64 + require.NoError(t, f.db.QueryRow(`SELECT revision FROM provider_profit_links WHERE provider_id=$1`, f.pid).Scan(&revision)) + wallet := "wallet" + _, err = f.r.SetProviderProfitLink(context.Background(), f.pid, service.ProviderProfitLinkMutation{ChannelID: f.channel, Revision: revision, Confirm: true, CostMode: &wallet}) + require.NoError(t, err) + missing := f.report(f.channel, w) + require.JSONEq(t, `"wallet_unavailable"`, string(missing["cost_source"])) + require.JSONEq(t, `null`, string(missing["upstream_cost"])) + require.JSONEq(t, string(before["requests"]), string(missing["requests"])) + require.JSONEq(t, string(before["request_income"]), string(missing["request_income"])) +} diff --git a/backend/internal/repository/provider_spend_snapshot.go b/backend/internal/repository/provider_spend_snapshot.go index 82a2605e0bc1..f45edd7501b1 100644 --- a/backend/internal/repository/provider_spend_snapshot.go +++ b/backend/internal/repository/provider_spend_snapshot.go @@ -10,7 +10,7 @@ import ( func (r *channelRepository) ListProviderSpendTargets(ctx context.Context) ([]service.ProviderSpendTarget, error) { rows, err := r.db.QueryContext(ctx, `SELECT p.id, p.revision FROM mature_providers p JOIN provider_profit_links l ON l.provider_id=p.id - WHERE p.credential_cipher<>'' + WHERE p.credential_cipher<>'' AND l.cost_mode='wallet' ORDER BY p.id`) if err != nil { return nil, err diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index 9aaba3406418..19ed650097a1 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -1092,6 +1092,7 @@ func registerChannelRoutes(admin *gin.RouterGroup, h *handler.Handlers) { admin.GET("/upstream-channels/:id/members", h.Admin.Channel.UpstreamChannelMembers) admin.GET("/upstream-channel-bindings", h.Admin.Channel.ReadUpstreamChannelBindings) admin.PUT("/upstream-channel-bindings", h.Admin.Channel.BindUpstreamChannelAccounts) + admin.GET("/profit-operations/channel-accounts", h.Admin.Channel.ProfitChannelAccountIDs) admin.GET("/profit-operations/snapshot", h.Admin.Channel.ProfitOperations) admin.GET("/profit-operations/providers", h.Admin.Channel.ListProviderProfitLinks) admin.PUT("/providers/:id/profit-channel", h.Admin.Channel.SetProviderProfitLink) diff --git a/backend/internal/service/profit_operations.go b/backend/internal/service/profit_operations.go index f562ce4bbbc0..76a098d8ffc8 100644 --- a/backend/internal/service/profit_operations.go +++ b/backend/internal/service/profit_operations.go @@ -11,6 +11,17 @@ import ( infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" ) +// Internal collection hint for bounded report caching; never accepted from HTTP. +type profitCollectionKey struct{} + +func WithProfitRowCollection(ctx context.Context) context.Context { + return context.WithValue(ctx, profitCollectionKey{}, true) +} +func CollectProfitRows(ctx context.Context) bool { + value, _ := ctx.Value(profitCollectionKey{}).(bool) + return value +} + // ProfitWalletTodaySkew is how far the profit window's end may sit behind // "now" and still count as today's consumption snapshot. The today preset // sends the browser's current time, which is slightly earlier than the server. diff --git a/backend/internal/service/provider_profit_links.go b/backend/internal/service/provider_profit_links.go index 85da9b7a323f..8d22afa713d8 100644 --- a/backend/internal/service/provider_profit_links.go +++ b/backend/internal/service/provider_profit_links.go @@ -18,6 +18,7 @@ var ( // This projection deliberately excludes connection details, credentials and raw // observations. Null spend is unknown; it is not a zero or verified event cost. type ProviderProfitLink struct { + CostMode string `json:"cost_mode"` ProviderID int64 `json:"provider_id"` ProviderName string `json:"provider_name"` SiteType string `json:"site_type"` @@ -43,12 +44,16 @@ type ProviderProfitLinkPage struct { } type ProviderProfitLinkMutation struct { - ChannelID int64 `json:"channel_id"` - Revision int64 `json:"revision"` - Confirm bool `json:"confirm"` + CostMode *string `json:"cost_mode,omitempty"` + ChannelID int64 `json:"channel_id"` + Revision int64 `json:"revision"` + Confirm bool `json:"confirm"` } func (m ProviderProfitLinkMutation) Validate(providerID int64) error { + if m.CostMode != nil && *m.CostMode != "estimate" && *m.CostMode != "wallet" { + return ErrProviderProfitLinkValidation + } if providerID <= 0 || m.ChannelID <= 0 || m.Revision <= 0 || m.Revision == math.MaxInt64 || !m.Confirm { return ErrProviderProfitLinkValidation } diff --git a/backend/migrations/388_provider_profit_cost_mode.sql b/backend/migrations/388_provider_profit_cost_mode.sql new file mode 100644 index 000000000000..1f332c8b10d0 --- /dev/null +++ b/backend/migrations/388_provider_profit_cost_mode.sql @@ -0,0 +1,4 @@ +-- Existing links keep their accounting basis. Naming a new upstream never opts into a wallet. +ALTER TABLE provider_profit_links ADD COLUMN cost_mode text NOT NULL DEFAULT 'wallet' + CHECK (cost_mode IN ('estimate', 'wallet')); +ALTER TABLE provider_profit_links ALTER COLUMN cost_mode SET DEFAULT 'estimate'; diff --git a/docs/channel-config/README.md b/docs/channel-config/README.md new file mode 100644 index 000000000000..1134360fedbc --- /dev/null +++ b/docs/channel-config/README.md @@ -0,0 +1,15 @@ +# 渠道配置 + +`/admin/channel-config` 统一渠道管理、利润运维和账号运维。面板首次展开才挂载,利润面板折叠后保留结果与筛选;账号面板折叠时停止定时读取。旧 `/admin/channel-operations`、`/admin/upstream-channels`、`/admin/profit-operations`、`/admin/account-ops` 跳转到对应面板,保留 query 和 hash,继续要求管理员权限。 + +名称 / URL / 账号归属与模型定价、供应商连接、利润成本来源分别配置。从渠道成员入口选择当前渠道,或在顶部输入渠道 ID;利润下钻的渠道和账号继续用于账号规则筛选。运营分组、通知渠道、OAuth 和独立账号规则保留原配置,并不按域名合并。 + +新增供应商默认“倍率估算”。迁移前已有供应商保留“钱包消费”;名称或账号归属编辑不修改该选择。在供应商连接面板单独切换成本来源时,以 revision 做并发检查。钱包读数缺失仍是 null / 不可用,展示查询窗口、读取时间和失败原因,不回填零。不修改用量或扣费流水、采购倍率。回滚旧二进制会忽略 cost_mode 并重新按原钱包逻辑统计,应先评估口径变化;新增列可以保留。 + +利润首次读取仍进行完整窗口聚合。之后相同筛选与维度下的分页、排序复用两分钟内的汇总,显示原 queried_at。各进程最多保留 8 份、每份 4 MiB,超过 10,000 个维度/成员/质量记录时退回原分页查询;不会缓存请求正文。每进程最多两个利润聚合任务,并发相同窗口合并计算,失败不缓存,取消会取消发起者的查询。刷新统计清除本进程缓存;刷新钱包同时重新探测。成本模式保存清除本进程缓存,其他节点最多保留两分钟旧结果。配置编辑提示刷新,未宣称第一遍百万行聚合已加速。 + +验证由 PR CI 执行:`TestProfitOperationsCachePagesSortAndInvalidation` 对同一窗口首次、翻页、倒序、缺失金额排序进行对照,前三次读取只调用聚合一次;这是合成聚合调用次数证据,不是生产延迟基准。`TestProviderProfitNamingPreservesEstimateUntilWalletOptIn` 在非空 PostgreSQL 用量窗口验证命名不改变请求数/收入/成本来源,选择钱包且没有读数时成本为 null。浏览器截图使用实际 Vue 组件与合成 API 数据,不访问生产或发送收费请求。 + +`TestProfitOperationsCachedWindowTiming` 在隔离 PostgreSQL 中生成 10,000 条合成用量,记录不复用时的首次/分页/排序和复用时的首次/分页/排序/重复耗时,核对窗口、汇总及查询时间。记录在 PR CI 日志;不设置不稳定的绝对耗时断言,不将其外推为生产百万行性能。 + +2026-11-19,CI head `97cec13fe29667eef5b842baa6ea2fe80e3f79fb` 的隔离 PostgreSQL 实测:UTC 窗口 `[2026-11-19T09:25:31Z,2026-11-19T10:25:31Z)`,10,000 条合成记录。不复用的首次/分页/排序为 198.37 / 183.95 / 186.45 ms;复用的首次/分页/排序/重复读取为 189.22 / 0.312 / 0.245 / 0.301 ms。窗口汇总一致。来源:[CI 日志](https://github.com/ranxi2001/sub2api/actions/runs/44504393963/job/135492082737)。该 job 的两个旧修订号断言失败,性能及新成本模式用例自身通过;修订号修正仍以最终 head CI 为准。此为单次合成环境观测。 diff --git a/docs/screenshots/channel-config/README.md b/docs/screenshots/channel-config/README.md new file mode 100644 index 000000000000..bd3a89b116b8 --- /dev/null +++ b/docs/screenshots/channel-config/README.md @@ -0,0 +1,13 @@ +# 渠道配置截图 + +2026-11-19,通过 Windows Chrome CDP 渲染实际 Vue 组件。数据来自 `.github/scripts/upstream-channel-entities-screenshot.mjs` 的合成 Axios adapter,未访问生产或真实供应商。AppLayout 使用简单预览容器,因此截图不证明生产侧栏、管理员认证或后端接口已验收。 + +- `before-profit.png`:生产基线 `5a51997112d0f93c8ec06747748680a9d7e8e4a7` 的原利润页,旧智能运维导航中三个入口独立。 +- `management.png`:新统一入口默认展开渠道管理,利润和账号运维尚未挂载。 +- `profit.png`:展开利润面板,保留原汇总、时间筛选和渠道/账号/模型下钻。 +- `accounts.png`:再展开账号面板,展示账号规则和通知渠道;空账号列表是合成数据场景。 +- `mobile-dark.png`:390px 宽度、深色主题,保留账号面板;页面 `scrollWidth=390`,表格在自身容器横向滚动。 + +浏览器回读:默认进入利润 API 调用 0 次,展开利润后 1 次,展开账号后仍为 1 次;利润汇总/表格、账号规则 DOM 均存在,最后回读无页面 `role=alert`。这仅验证面板加载互不触发利润请求;数据库缓存正确性和耗时由 PostgreSQL CI 用例验证。 + +截图源代码是本目录提交中的实现,截图未后期合成或贴字。原利润页使用单独基线 worktree 和相同合成数据渲染。 diff --git a/docs/screenshots/channel-config/accounts.png b/docs/screenshots/channel-config/accounts.png new file mode 100644 index 000000000000..98b77da1d076 Binary files /dev/null and b/docs/screenshots/channel-config/accounts.png differ diff --git a/docs/screenshots/channel-config/before-profit.png b/docs/screenshots/channel-config/before-profit.png new file mode 100644 index 000000000000..b550d36fc361 Binary files /dev/null and b/docs/screenshots/channel-config/before-profit.png differ diff --git a/docs/screenshots/channel-config/evidence.json b/docs/screenshots/channel-config/evidence.json new file mode 100644 index 000000000000..7cc9b8156200 --- /dev/null +++ b/docs/screenshots/channel-config/evidence.json @@ -0,0 +1,14 @@ +{ + "date": "2026-11-19", + "browser": "Chrome/157.0.8103.79", + "baseline": "5a51997112d0f93c8ec06747748680a9d7e8e4a7", + "rendering": "actual Vue components; synthetic Axios adapter; simplified AppLayout", + "production_requests": 0, + "paid_requests": 0, + "profit_api_calls": {"initial_configuration": 0, "profit_expanded": 1, "accounts_expanded": 1}, + "profit_summary_present": true, + "profit_table_rows": 1, + "account_rules_present": true, + "visible_alerts": [], + "responsive_dark": {"viewport_width": 390, "document_scroll_width": 390} +} diff --git a/docs/screenshots/channel-config/management.png b/docs/screenshots/channel-config/management.png new file mode 100644 index 000000000000..20072d514c73 Binary files /dev/null and b/docs/screenshots/channel-config/management.png differ diff --git a/docs/screenshots/channel-config/mobile-dark.png b/docs/screenshots/channel-config/mobile-dark.png new file mode 100644 index 000000000000..23fe2923962b Binary files /dev/null and b/docs/screenshots/channel-config/mobile-dark.png differ diff --git a/docs/screenshots/channel-config/profit.png b/docs/screenshots/channel-config/profit.png new file mode 100644 index 000000000000..d9d4edc3b722 Binary files /dev/null and b/docs/screenshots/channel-config/profit.png differ diff --git a/frontend/src/api/admin/profitOperations.ts b/frontend/src/api/admin/profitOperations.ts index c16b3f5f6df1..b59f5bfe3c02 100644 --- a/frontend/src/api/admin/profitOperations.ts +++ b/frontend/src/api/admin/profitOperations.ts @@ -33,12 +33,13 @@ export interface OperationsSnapshot { 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): Promise { +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, ...(refreshSpend ? { refresh_spend: 1 } : {}) }, signal, timeout: 330_000 })).data + return (await apiClient.get('/admin/profit-operations/snapshot', { params: { ...params, ...(refreshReport ? { refresh_report: 1 } : {}), ...(refreshSpend ? { refresh_spend: 1 } : {}) }, signal, timeout: 330_000 })).data } export interface ProfitProvider extends Pick { + cost_mode?: 'estimate' | 'wallet' provider_id: number provider_name: string channel_id: number | null @@ -49,8 +50,8 @@ export interface ProfitProviderPage { items: ProfitProvider[]; total: number; pa export async function listProfitProviders(page: number, signal?: AbortSignal) { return (await apiClient.get('/admin/profit-operations/providers', { params: { page, page_size: 20 }, signal })).data } -export async function linkProfitChannel(providerId: number, channelId: number, revision: number) { - await apiClient.put(`/admin/providers/${providerId}/profit-channel`, { channel_id: channelId, revision, confirm: true }) +export async function linkProfitChannel(providerId: number, channelId: number, revision: number, costMode?: 'estimate' | 'wallet') { + await apiClient.put(`/admin/providers/${providerId}/profit-channel`, { channel_id: channelId, revision, confirm: true, ...(costMode ? { cost_mode: costMode } : {}) }) } export type ProfitDates = Pick export interface ProfitSyncStatus { status: 'running' | 'succeeded' | 'failed'; matched?: number; unmatched?: number; reason?: string } @@ -63,3 +64,7 @@ export async function readProfitSync(providerId: number, jobId: string, signal: export async function readExplicitChannelProfitOperations(query: OperationsQuery, channelId: number, signal?: AbortSignal): Promise { return readProfitOperations({ ...query, upstream: '', channel_id: channelId }, signal) } + +export async function readProfitChannelAccountIDs(channelId: number) { + return (await apiClient.get<{account_ids:number[]}>('/admin/profit-operations/channel-accounts', {params:{channel_id:channelId}})).data.account_ids +} diff --git a/frontend/src/components/admin/operations/MatureProvidersPanel.vue b/frontend/src/components/admin/operations/MatureProvidersPanel.vue index d1f408cacb6f..0f321f7aae90 100644 --- a/frontend/src/components/admin/operations/MatureProvidersPanel.vue +++ b/frontend/src/components/admin/operations/MatureProvidersPanel.vue @@ -81,6 +81,8 @@ import { useAuthStore } from '@/stores/auth' import NewFeatureBadge from '@/components/common/NewFeatureBadge.vue' import { NEW_FEATURE_NOTICES } from '@/constants/newFeatureNotices' import { listProviders, saveProvider, refreshProvider, deleteProvider, type MatureProvider, type ProviderInput } from '@/api/admin/matureProviders' +const props = defineProps<{ passive?: boolean }>() +const emit = defineEmits<{ changed: [] }>() const { t } = useI18n(), auth = useAuthStore() const providers = ref([]), total = ref(0), page = ref(1), pageSize = 20 const query = ref(''), status = ref(''), loading = ref(false), error = ref(''), busy = ref(null) @@ -98,7 +100,7 @@ function amount(p: MatureProvider, field: typeof metrics[number]) { function lowBalance(p: MatureProvider) { return p.status === 'connected' && !p.suppress_low_balance_alert && p.low_balance_threshold != null && p.metrics.balance != null && p.metrics.balance < p.low_balance_threshold } function message(e: unknown) { return t((e as { status?: number })?.status === 409 ? 'matureProviders.conflict' : 'matureProviders.failed') } async function refreshVisible(items: MatureProvider[], current: number) { - if (formOpen.value || current !== generation) return + if (props.passive || formOpen.value || current !== generation) return const pending = items.filter(p => p.has_credential && !refreshed.has(p.id)) if (!pending.length) return for (const provider of pending) { @@ -131,7 +133,7 @@ async function save() { const input = { ...draft.value, cost_multiplier: cost.value === '' ? null : Number(cost.value), low_balance_threshold: threshold.value === '' ? null : Number(threshold.value) } if (credential.value) { if (input.auth_mode === 'password') input.password = credential.value; else input.access_token = credential.value } if (refreshToken.value && input.auth_mode === 'token' && input.site_type === 'sub2api') input.refresh_token = refreshToken.value - try { await saveProvider(editID.value, input); formOpen.value = false; credential.value = ''; refreshToken.value = ''; await load() } + try { await saveProvider(editID.value, input); formOpen.value = false; credential.value = ''; refreshToken.value = ''; await load(); emit('changed') } catch (e) { error.value = message(e) } finally { saving.value = false } } @@ -143,7 +145,7 @@ async function refresh(p: MatureProvider) { async function remove() { if (!deleting.value || busy.value !== null) return busy.value = deleting.value.id; error.value = '' - try { await deleteProvider(deleting.value); deleting.value = null; await load() } catch (e) { error.value = message(e); deleting.value = null } finally { busy.value = null } + try { await deleteProvider(deleting.value); deleting.value = null; await load(); emit('changed') } catch (e) { error.value = message(e); deleting.value = null } finally { busy.value = null } } onMounted(load) onBeforeUnmount(() => { alive = false; generation++; controller?.abort(); credential.value = ''; refreshToken.value = '' }) diff --git a/frontend/src/components/admin/operations/ProfitAnalytics.vue b/frontend/src/components/admin/operations/ProfitAnalytics.vue index 551a2ae55809..4061fdc1c71f 100644 --- a/frontend/src/components/admin/operations/ProfitAnalytics.vue +++ b/frontend/src/components/admin/operations/ProfitAnalytics.vue @@ -1,9 +1,9 @@ - + diff --git a/frontend/src/components/admin/operations/ProfitProviders.vue b/frontend/src/components/admin/operations/ProfitProviders.vue index 0c57ed8ba286..cc87359eab08 100644 --- a/frontend/src/components/admin/operations/ProfitProviders.vue +++ b/frontend/src/components/admin/operations/ProfitProviders.vue @@ -7,6 +7,10 @@

{{ t('profitOps.providersEmpty') }}

{{ p.provider_name }} #{{ p.provider_id }} → {{ channelName(p) }}
+ +

{{ t('channelConfig.costHelp') }}

@@ -23,7 +27,7 @@ diff --git a/frontend/src/components/admin/operations/SmartOpsNav.vue b/frontend/src/components/admin/operations/SmartOpsNav.vue index 2b4413bbe13c..e096d887890a 100644 --- a/frontend/src/components/admin/operations/SmartOpsNav.vue +++ b/frontend/src/components/admin/operations/SmartOpsNav.vue @@ -18,5 +18,5 @@ const { t } = useI18n(), route = useRoute(), adminSettingsStore = useAdminSettin const authStore = useAuthStore() interface SmartOpsNavItem { path: string; label: string; noticeId?: string } // Keep the order in sync with the 智能运维 group in AppSidebar.vue. -const items = computed((): SmartOpsNavItem[] => [{ path: '/admin/lottery', label: 'lottery.adminTitle' }, { path: '/admin/auto-config', label: 'autoConfig.title', noticeId: NEW_FEATURE_NOTICES.oauthInitialModelSelection }, { path: '/admin/priority-scheduling', label: 'priorityScheduling.title' }, ...(authStore.isAdmin ? [{ path: '/admin/qqbot/overview', label: 'qqbot.title', noticeId: NEW_FEATURE_NOTICES.qqCommunity }] : []), { path: '/admin/channel-operations', label: 'channelOps.title', noticeId: NEW_FEATURE_NOTICES.matureProviders }, { path: '/admin/profit-operations', label: 'profitOps.title', noticeId: NEW_FEATURE_NOTICES.providerProfit }, { path: '/admin/account-quality', label: 'qualityOps.title', noticeId: NEW_FEATURE_NOTICES.qualityRetestRest }, { path: '/admin/controlled-experiments', label: 'controlledExperiments.title' }, { path: '/admin/account-ops', label: 'accountOps.title' }, { path: '/admin/token-guard-v2', label: 'tokenGuardV2.title' }, { path: '/admin/pelican-tests', label: 'pelicanTests.title' }, { path: '/admin/group-cache-tests', label: 'admin.groupCacheTest.title' }, ...(adminSettingsStore.requestCaptureEnabled ? [{ path: '/admin/request-captures', label: 'admin.requestCapture.title' }] : []), ...(authStore.isAdmin ? [{ path: '/admin/ai-ops', label: 'aiOps.title', noticeId: NEW_FEATURE_NOTICES.aiOpsCodex }] : [])]) +const items = computed((): SmartOpsNavItem[] => [{ path: '/admin/lottery', label: 'lottery.adminTitle' }, { path: '/admin/auto-config', label: 'autoConfig.title', noticeId: NEW_FEATURE_NOTICES.oauthInitialModelSelection }, { path: '/admin/priority-scheduling', label: 'priorityScheduling.title' }, ...(authStore.isAdmin ? [{ path: '/admin/qqbot/overview', label: 'qqbot.title', noticeId: NEW_FEATURE_NOTICES.qqCommunity }] : []), { path: '/admin/channel-config', label: 'channelConfig.title', noticeId: NEW_FEATURE_NOTICES.channelConfig }, { path: '/admin/account-quality', label: 'qualityOps.title', noticeId: NEW_FEATURE_NOTICES.qualityRetestRest }, { path: '/admin/controlled-experiments', label: 'controlledExperiments.title' }, { path: '/admin/token-guard-v2', label: 'tokenGuardV2.title' }, { path: '/admin/pelican-tests', label: 'pelicanTests.title' }, { path: '/admin/group-cache-tests', label: 'admin.groupCacheTest.title' }, ...(adminSettingsStore.requestCaptureEnabled ? [{ path: '/admin/request-captures', label: 'admin.requestCapture.title' }] : []), ...(authStore.isAdmin ? [{ path: '/admin/ai-ops', label: 'aiOps.title', noticeId: NEW_FEATURE_NOTICES.aiOpsCodex }] : [])]) diff --git a/frontend/src/components/admin/operations/UpstreamAnalytics.vue b/frontend/src/components/admin/operations/UpstreamAnalytics.vue index c7b8792283b7..ffcb6228725b 100644 --- a/frontend/src/components/admin/operations/UpstreamAnalytics.vue +++ b/frontend/src/components/admin/operations/UpstreamAnalytics.vue @@ -1,8 +1,8 @@
- + diff --git a/frontend/src/components/admin/operations/__tests__/SmartOpsNav.spec.ts b/frontend/src/components/admin/operations/__tests__/SmartOpsNav.spec.ts index 2e9a38c8eda6..62bbe7c30e5a 100644 --- a/frontend/src/components/admin/operations/__tests__/SmartOpsNav.spec.ts +++ b/frontend/src/components/admin/operations/__tests__/SmartOpsNav.spec.ts @@ -12,7 +12,7 @@ import { NEW_FEATURE_NOTICES } from '@/constants/newFeatureNotices' import type { User } from '@/types' const smartOpsPaths = ['/admin/lottery', '/admin/auto-config', '/admin/priority-scheduling', - '/admin/qqbot/overview', '/admin/channel-operations', '/admin/profit-operations', '/admin/account-quality', '/admin/controlled-experiments', '/admin/account-ops', '/admin/token-guard-v2', '/admin/pelican-tests', '/admin/group-cache-tests'] + '/admin/qqbot/overview', '/admin/channel-config', '/admin/account-quality', '/admin/controlled-experiments', '/admin/token-guard-v2', '/admin/pelican-tests', '/admin/group-cache-tests'] async function mountAt(path: string) { const router = createRouter({ @@ -99,9 +99,9 @@ describe('SmartOpsNav', () => { }) it('uses the provider reconciliation notice on the existing profit entry', async () => { - const wrapper = await mountAt('/admin/profit-operations') - await wrapper.get('a[href="/admin/profit-operations"] + [data-testid="new-feature-badge"]').trigger('click') - expect(useNewFeatureNoticeStore().isDismissed(41, NEW_FEATURE_NOTICES.providerProfit)).toBe(true) + const wrapper = await mountAt('/admin/channel-config') + await wrapper.get('a[href="/admin/channel-config"] + [data-testid="new-feature-badge"]').trigger('click') + expect(useNewFeatureNoticeStore().isDismissed(41, NEW_FEATURE_NOTICES.channelConfig)).toBe(true) wrapper.unmount() }) diff --git a/frontend/src/components/layout/AppSidebar.vue b/frontend/src/components/layout/AppSidebar.vue index 59fd8720923f..695f3b63a308 100644 --- a/frontend/src/components/layout/AppSidebar.vue +++ b/frontend/src/components/layout/AppSidebar.vue @@ -887,11 +887,9 @@ const adminNavItems = computed((): NavItem[] => { { path: '/admin/auto-config', label: t('autoConfig.title'), icon: AccountOpsIcon, noticeId: NEW_FEATURE_NOTICES.oauthInitialModelSelection }, { path: '/admin/priority-scheduling', label: t('priorityScheduling.title'), icon: AccountOpsIcon }, { path: '/admin/qqbot/overview', label: t('qqbot.title'), icon: AccountOpsIcon, noticeId: NEW_FEATURE_NOTICES.qqCommunity }, - { path: '/admin/channel-operations', label: t('channelOps.title'), icon: ChannelIcon, noticeId: NEW_FEATURE_NOTICES.matureProviders }, - { path: '/admin/profit-operations', label: t('profitOps.title'), icon: PriceTagIcon, noticeId: NEW_FEATURE_NOTICES.providerProfit }, + { path: '/admin/channel-config', label: t('channelConfig.title'), icon: PriceTagIcon, noticeId: NEW_FEATURE_NOTICES.channelConfig }, { path: '/admin/account-quality', label: t('qualityOps.title'), icon: QualityOpsIcon, noticeId: NEW_FEATURE_NOTICES.qualityRetestRest }, { path: '/admin/controlled-experiments', label: t('controlledExperiments.title'), icon: QualityOpsIcon }, - { path: '/admin/account-ops', label: t('accountOps.title'), icon: AccountOpsIcon }, { path: '/admin/token-guard-v2', label: t('tokenGuardV2.title'), icon: CredentialOpsIcon }, { path: '/admin/pelican-tests', label: t('pelicanTests.title'), icon: PelicanTestsIcon }, { path: '/admin/group-cache-tests', label: t('admin.groupCacheTest.title'), icon: QualityOpsIcon }, diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 0d9128abb0cf..9d953f488636 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -4,6 +4,7 @@ * browser; use a new ID to announce the feature again in a later release. */ export const NEW_FEATURE_NOTICES = { + channelConfig: 'channel-configuration-20261119', imageUsageBilling: 'image-usage-minimum-charge-20261119', newAPICostConversion: 'new-api-cost-conversion-20261119', accountOpsBalanceNotification: 'account-ops-per-account-balance-notification-20261119', diff --git a/frontend/src/i18n/locales/en/channelConfig.ts b/frontend/src/i18n/locales/en/channelConfig.ts new file mode 100644 index 000000000000..8226f16ad0aa --- /dev/null +++ b/frontend/src/i18n/locales/en/channelConfig.ts @@ -0,0 +1,8 @@ +export default { + channels:'Channel management', observations:'Requests and latency', + title:'Channel configuration', description:'Manage ownership, profit and account alerts by channel. Panels load independently and retain filters and drilldown state.', + currentChannel:'Current channel ID (0 for all)', identityHelp:'Names, URLs and account membership classify upstreams. Model pricing is separate. Changing ownership does not enable wallet costs; a shared domain does not imply a shared wallet or alert scope.', + connections:'Provider connections and cost sources', costMode:'Profit cost source', estimate:'Multiplier estimate', wallet:'Wallet consumption', + costHelp:'Changes are saved on selection. Wallet consumption uses the report window; missing readings remain unavailable. Renaming or linking preserves this choice.', + stale:'Configuration changed. Loaded profit results retain their observation time; use Refresh statistics. Pagination and sorting reuse the same window aggregate for up to two minutes.' +} diff --git a/frontend/src/i18n/locales/en/index.ts b/frontend/src/i18n/locales/en/index.ts index 3e70478b8b37..99a9498f7bc9 100644 --- a/frontend/src/i18n/locales/en/index.ts +++ b/frontend/src/i18n/locales/en/index.ts @@ -9,6 +9,7 @@ import lottery from './lottery' import accountTestTiming from './accountTestTiming' import openaiAuth from './openaiAuth' import upstreamEntities from './upstreamEntities' +import channelConfig from './channelConfig' import profitOps from './profitOps' import upstreamOps from './upstreamOps' import channelOps from './channelOps' @@ -65,6 +66,7 @@ export default { qualityOps, channelOps, upstreamOps, + channelConfig, profitOps, controlledExperiments, accountOps, diff --git a/frontend/src/i18n/locales/zh/channelConfig.ts b/frontend/src/i18n/locales/zh/channelConfig.ts new file mode 100644 index 000000000000..597b1b4156b7 --- /dev/null +++ b/frontend/src/i18n/locales/zh/channelConfig.ts @@ -0,0 +1,8 @@ +export default { + channels:'渠道管理', observations:'请求与延迟观测', + title:'渠道配置', description:'按渠道管理上游归属、利润和账号告警。各面板独立加载,保留筛选和下钻状态。', + currentChannel:'当前渠道 ID(0 为全部)', identityHelp:'名称、URL 和账号归属用于分类;模型与定价单独配置。修改归属不会自动启用钱包成本,同域名也不代表共享钱包或告警。', + connections:'供应商连接与成本来源', costMode:'利润成本来源', estimate:'倍率估算', wallet:'钱包消费', + costHelp:'选择后保存生效。钱包消费按统计窗口读取,缺少读数显示不可用;不会以零或估算代替。仅修改名称或关联保留此选择。', + stale:'配置已变更。已加载的利润结果保留原查询时间;请在利润面板点击刷新统计。相同窗口的分页和排序最多复用两分钟内的汇总。' +} diff --git a/frontend/src/i18n/locales/zh/index.ts b/frontend/src/i18n/locales/zh/index.ts index 3e70478b8b37..99a9498f7bc9 100644 --- a/frontend/src/i18n/locales/zh/index.ts +++ b/frontend/src/i18n/locales/zh/index.ts @@ -9,6 +9,7 @@ import lottery from './lottery' import accountTestTiming from './accountTestTiming' import openaiAuth from './openaiAuth' import upstreamEntities from './upstreamEntities' +import channelConfig from './channelConfig' import profitOps from './profitOps' import upstreamOps from './upstreamOps' import channelOps from './channelOps' @@ -65,6 +66,7 @@ export default { qualityOps, channelOps, upstreamOps, + channelConfig, profitOps, controlledExperiments, accountOps, diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 8d0cd8e3325a..3977cf58fc33 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -599,15 +599,16 @@ const routes: RouteRecordRaw[] = [ { path: '/admin/qqbot/runtime', redirect: '/admin/qqbot/records' }, { path: '/admin/qqbot/checkin', redirect: { path: '/admin/qqbot/activities', query: { tab: 'checkin' } } }, { path: '/admin/qqbot/lottery', redirect: { path: '/admin/qqbot/activities', query: { tab: 'lottery' } } }, - { path: '/admin/channel-operations', name: 'AdminChannelOperations', component: () => import('@/views/admin/UpstreamChannelOperationsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, titleKey: 'channelOps.title', descriptionKey: 'channelOps.description' } }, - { path: '/admin/upstream-channels', name: 'AdminUpstreamChannels', component: () => import('@/views/admin/UpstreamChannelsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, titleKey: 'upstreamEntities.title', descriptionKey: 'upstreamEntities.history' } }, - { path: '/admin/profit-operations', name: 'AdminProfitOperations', component: () => import('@/views/admin/ProfitOperationsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, titleKey: 'profitOps.title', descriptionKey: 'profitOps.description' } }, + { path: '/admin/channel-config', name: 'AdminChannelConfig', component: () => import('@/views/admin/ChannelConfigView.vue'), meta: { requiresAuth: true, requiresAdmin: true, titleKey: 'channelConfig.title' } }, + { path: '/admin/channel-operations', redirect: to => ({ path: '/admin/channel-config', query: { ...to.query, panel: 'channels' }, hash: to.hash }), meta: { requiresAuth: true, requiresAdmin: true } }, + { path: '/admin/upstream-channels', redirect: to => ({ path: '/admin/channel-config', query: { ...to.query, panel: 'channels' }, hash: to.hash }), meta: { requiresAuth: true, requiresAdmin: true } }, + { path: '/admin/profit-operations', redirect: to => ({ path: '/admin/channel-config', query: { ...to.query, panel: 'profit' }, hash: to.hash }), meta: { requiresAuth: true, requiresAdmin: true } }, { path: '/admin/smart-ops', redirect: '/admin/account-quality', meta: { requiresAuth: true, requiresAdmin: true } }, { path: '/admin/ai-ops', name: 'AdminAIOps', component: () => import('@/views/admin/AIOpsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, title: 'AI operations', titleKey: 'aiOps.title', descriptionKey: 'aiOps.description' } }, { path: '/admin/controlled-experiments', name: 'AdminControlledExperiments', component: () => import('@/views/admin/ControlledExperimentsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, title: 'Controlled experiments', titleKey: 'controlledExperiments.title', descriptionKey: 'controlledExperiments.description' } }, { path: '/admin/pelican-tests', name: 'AdminPelicanTests', component: () => import('@/views/admin/PelicanTestsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, title: 'Pelican Showcase', titleKey: 'pelicanTests.title', descriptionKey: 'pelicanTests.description' } }, { path: '/admin/token-guard-v2', name: 'AdminTokenGuardV2', component: () => import('@/views/admin/ops/TokenGuardV2View.vue'), meta: { requiresAuth: true, requiresAdmin: true, title: 'Credential Operations', titleKey: 'tokenGuardV2.title', descriptionKey: 'tokenGuardV2.description' } }, - { path: '/admin/account-ops', name: 'AdminAccountOps', component: () => import('@/views/admin/AccountOpsView.vue'), meta: { requiresAuth: true, requiresAdmin: true, title: 'Account operations', titleKey: 'accountOps.title', descriptionKey: 'accountOps.description' } }, + { path: '/admin/account-ops', redirect: to => ({ path: '/admin/channel-config', query: { ...to.query, panel: 'accounts' }, hash: to.hash }), meta: { requiresAuth: true, requiresAdmin: true } }, { path: '/admin/account-quality', name: 'AdminAccountQuality', diff --git a/frontend/src/views/admin/AccountOpsView.vue b/frontend/src/views/admin/AccountOpsView.vue index eccf7458eaba..679b0a22c265 100644 --- a/frontend/src/views/admin/AccountOpsView.vue +++ b/frontend/src/views/admin/AccountOpsView.vue @@ -1,7 +1,7 @@ - + diff --git a/frontend/src/views/admin/ChannelConfigView.vue b/frontend/src/views/admin/ChannelConfigView.vue new file mode 100644 index 000000000000..1ced0dd1375f --- /dev/null +++ b/frontend/src/views/admin/ChannelConfigView.vue @@ -0,0 +1,74 @@ + + + diff --git a/frontend/src/views/admin/__tests__/ChannelConfigView.spec.ts b/frontend/src/views/admin/__tests__/ChannelConfigView.spec.ts new file mode 100644 index 000000000000..e67df661356f --- /dev/null +++ b/frontend/src/views/admin/__tests__/ChannelConfigView.spec.ts @@ -0,0 +1,31 @@ +import { mount, flushPromises } from '@vue/test-utils' +import { createRouter, createMemoryHistory } from 'vue-router' +import { describe, it, expect, vi } from 'vitest' +import ChannelConfig from '../ChannelConfigView.vue' +import { profitScopeFromQuery } from '../channelConfigScope' +vi.mock('vue-i18n',()=>({useI18n:()=>({t:(key:string)=>key})})) +vi.mock('@/stores/auth',()=>({useAuthStore:()=>({user:{id:1}})})) +vi.mock('@/components/layout/AppLayout.vue',()=>({default:{template:'
'}})) +vi.mock('@/components/admin/operations/SmartOpsNav.vue',()=>({default:{template:'