From 8331cb3de5ee933658744d99c945b37da0c9f8f7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Thu, 19 Nov 2026 18:00:45 +0800 Subject: [PATCH 1/9] =?UTF-8?q?feat:=20=E7=BB=9F=E4=B8=80=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E9=85=8D=E7=BD=AE=E5=B9=B6=E5=88=86=E7=A6=BB=E9=92=B1?= =?UTF-8?q?=E5=8C=85=E6=88=90=E6=9C=AC=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../upstream-channel-entities-screenshot.mjs | 24 ++- .github/workflows/profit-operations.yml | 2 +- .../internal/handler/admin/channel_handler.go | 1 + .../handler/admin/profit_operations.go | 11 +- .../handler/admin/profit_operations_cache.go | 197 ++++++++++++++++++ .../admin/profit_operations_cache_test.go | 67 ++++++ .../handler/admin/provider_profit_links.go | 1 + .../internal/repository/profit_operations.go | 10 +- ...provider_profit_charge_integration_test.go | 1 + .../repository/provider_profit_links.go | 14 +- ...provider_profit_report_integration_test.go | 31 +++ .../repository/provider_spend_snapshot.go | 2 +- .../internal/service/provider_profit_links.go | 11 +- .../internal/service/upstream_operations.go | 27 +-- .../388_provider_profit_cost_mode.sql | 4 + docs/channel-config/README.md | 11 + frontend/src/api/admin/profitOperations.ts | 9 +- .../admin/operations/MatureProvidersPanel.vue | 4 +- .../admin/operations/ProfitAnalytics.vue | 31 ++- .../admin/operations/ProfitProviders.vue | 17 +- .../admin/operations/SmartOpsNav.vue | 2 +- .../admin/operations/UpstreamAnalytics.vue | 7 +- .../operations/UpstreamChannelManager.vue | 4 +- .../operations/__tests__/SmartOpsNav.spec.ts | 8 +- frontend/src/components/layout/AppSidebar.vue | 4 +- frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/i18n/locales/en/channelConfig.ts | 7 + frontend/src/i18n/locales/en/index.ts | 2 + frontend/src/i18n/locales/zh/channelConfig.ts | 7 + frontend/src/i18n/locales/zh/index.ts | 2 + frontend/src/router/index.ts | 9 +- frontend/src/views/admin/AccountOpsView.vue | 29 ++- .../src/views/admin/ChannelConfigView.vue | 74 +++++++ .../admin/__tests__/ChannelConfigView.spec.ts | 31 +++ .../src/views/admin/channelConfigScope.ts | 9 + 35 files changed, 600 insertions(+), 71 deletions(-) create mode 100644 backend/internal/handler/admin/profit_operations_cache.go create mode 100644 backend/internal/handler/admin/profit_operations_cache_test.go create mode 100644 backend/migrations/388_provider_profit_cost_mode.sql create mode 100644 docs/channel-config/README.md create mode 100644 frontend/src/i18n/locales/en/channelConfig.ts create mode 100644 frontend/src/i18n/locales/zh/channelConfig.ts create mode 100644 frontend/src/views/admin/ChannelConfigView.vue create mode 100644 frontend/src/views/admin/__tests__/ChannelConfigView.spec.ts create mode 100644 frontend/src/views/admin/channelConfigScope.ts diff --git a/.github/scripts/upstream-channel-entities-screenshot.mjs b/.github/scripts/upstream-channel-entities-screenshot.mjs index e186da3f07bb..91d4f5ea7043 100644 --- a/.github/scripts/upstream-channel-entities-screenshot.mjs +++ b/.github/scripts/upstream-channel-entities-screenshot.mjs @@ -44,7 +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:[]}}}; - }else if(url.includes('management-capabilities'))data={web_search_enabled:false,account_quota_notify_enabled:false}; + }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'}; @@ -59,11 +63,11 @@ 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 +111,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/profit_operations.go b/backend/internal/handler/admin/profit_operations.go index dfbf8cf25ae9..9f3ddb171db0 100644 --- a/backend/internal/handler/admin/profit_operations.go +++ b/backend/internal/handler/admin/profit_operations.go @@ -33,9 +33,16 @@ 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) + query := f + query.CollectProfitRows = collect + return h.channelService.ProfitOperations(ctx, query) + }) if err != nil { status, reason, message := http.StatusInternalServerError, "PROFIT_OPERATIONS_QUERY_FAILED", "Upstream operations query failed; retry" if errors.Is(err, context.DeadlineExceeded) { 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..f8cfb7d01c7d --- /dev/null +++ b/backend/internal/handler/admin/profit_operations_cache.go @@ -0,0 +1,197 @@ +package admin + +import ( + "context" + "encoding/json" + "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 + 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.CollectProfitRows = false + key.From = key.From.UTC() + key.Until = key.Until.UTC() + c.mu.Lock() + 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 + } + 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 := r.Val.([]byte) + if raw == nil { + 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 + out.Scope.CollectProfitRows = false + 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/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/repository/profit_operations.go b/backend/internal/repository/profit_operations.go index 6488a76f3cb8..9e37aced7fb6 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 f.CollectProfitRows { + 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/provider_profit_charge_integration_test.go b/backend/internal/repository/provider_profit_charge_integration_test.go index f0fb033eaa43..7d53944cfc03 100644 --- a/backend/internal/repository/provider_profit_charge_integration_test.go +++ b/backend/internal/repository/provider_profit_charge_integration_test.go @@ -29,6 +29,7 @@ func newProfitChargeFixture(t *testing.T) *profitChargeFixture { db, _ := UpstreamChannelsTestDatabase(t) f := &profitChargeFixture{t: t, db: db, r: &channelRepository{db: db}} f.pid = f.provider() + f.exec(`UPDATE provider_profit_links SET cost_mode='wallet',revision=revision+1 WHERE provider_id=$1`, f.pid) f.channel = f.id(`SELECT channel_id FROM provider_profit_links WHERE provider_id=$1`, f.pid) var err error f.epoch, err = f.r.ProviderProfitIdentityFrom(context.Background(), f.pid) 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..4c70c59cead6 100644 --- a/backend/internal/repository/provider_profit_report_integration_test.go +++ b/backend/internal/repository/provider_profit_report_integration_test.go @@ -463,3 +463,34 @@ func TestProviderProfitLegacyIncomeUnchangedByFirstLink(t *testing.T) { check() } } + +func TestProviderProfitNamingPreservesEstimateUntilWalletOptIn(t *testing.T) { + f := newProfitChargeFixture(t) + // A new URL/name record defaults to estimates, even without credentials. + pid := f.provider() + 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) + 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/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/internal/service/upstream_operations.go b/backend/internal/service/upstream_operations.go index 8456e719ea6f..e382112e41aa 100644 --- a/backend/internal/service/upstream_operations.go +++ b/backend/internal/service/upstream_operations.go @@ -16,19 +16,20 @@ import ( var ErrUpstreamOperationsValidation = infraerrors.BadRequest("UPSTREAM_OPERATIONS_VALIDATION", "运维查询参数无效:请检查时间范围、分页、模型口径及安全上游网址") type UpstreamOperationsFilter struct { - From time.Time `json:"from"` - Until time.Time `json:"until"` - Upstream string `json:"upstream"` - ChannelID int64 `json:"channel_id,omitempty"` - AccountID int64 `json:"account_id"` - GroupID int64 `json:"group_id"` - Model string `json:"model"` - ModelScope string `json:"model_scope"` - Dimension string `json:"dimension"` - Sort string `json:"sort"` - Direction string `json:"direction"` - Page int `json:"page"` - PageSize int `json:"page_size"` + CollectProfitRows bool `json:"-"` + From time.Time `json:"from"` + Until time.Time `json:"until"` + Upstream string `json:"upstream"` + ChannelID int64 `json:"channel_id,omitempty"` + AccountID int64 `json:"account_id"` + GroupID int64 `json:"group_id"` + Model string `json:"model"` + ModelScope string `json:"model_scope"` + Dimension string `json:"dimension"` + Sort string `json:"sort"` + Direction string `json:"direction"` + Page int `json:"page"` + PageSize int `json:"page_size"` } type UpstreamOperationsSnapshot struct { diff --git a/backend/migrations/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..294ca5dac5f8 --- /dev/null +++ b/docs/channel-config/README.md @@ -0,0 +1,11 @@ +# 渠道配置 + +`/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 数据,不访问生产或发送收费请求。 diff --git a/frontend/src/api/admin/profitOperations.ts b/frontend/src/api/admin/profitOperations.ts index c16b3f5f6df1..228df9975dae 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 } diff --git a/frontend/src/components/admin/operations/MatureProvidersPanel.vue b/frontend/src/components/admin/operations/MatureProvidersPanel.vue index d1f408cacb6f..c65bf8511683 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) { diff --git a/frontend/src/components/admin/operations/ProfitAnalytics.vue b/frontend/src/components/admin/operations/ProfitAnalytics.vue index 551a2ae55809..542e977b98ff 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..b922a401541f 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..9b88d5a2359b --- /dev/null +++ b/frontend/src/i18n/locales/en/channelConfig.ts @@ -0,0 +1,7 @@ +export default { + 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..84fd54ffeb37 --- /dev/null +++ b/frontend/src/i18n/locales/zh/channelConfig.ts @@ -0,0 +1,7 @@ +export default { + 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..1ad66165027e 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..254f80d9173e --- /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..37ef8a1f6572 --- /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:'