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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions .github/scripts/upstream-channel-entities-screenshot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'};
Expand All @@ -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=`<!doctype html><html lang="zh"><meta charset="utf-8"><div id="app"></div><script type="module">
const html=`<!doctype html><html lang="zh"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><div id="app"></div><script type="module">
import 'virtual:entity-fixture';import {createApp} from 'vue';import {createPinia} from 'pinia';import {createRouter,createWebHistory,RouterView} from 'vue-router';import {createI18n} from 'vue-i18n';import {useAuthStore} from '/src/stores/auth.ts';
import Profit from '/src/views/admin/ProfitOperationsView.vue';import Channels from '/src/views/admin/UpstreamChannelsView.vue';const Accounts=()=>import('/src/views/admin/AccountsView.vue');import zh from '/src/i18n/locales/zh/index.ts';import '/src/style.css';
const pinia=createPinia();const router=createRouter({history:createWebHistory(),routes:[{path:'/admin/profit-operations',component:Profit},{path:'/admin/upstream-channels',component:Channels},{path:'/admin/accounts',component:Accounts}]});
import Config from '/src/views/admin/ChannelConfigView.vue';import Profit from '/src/views/admin/ProfitOperationsView.vue';import Channels from '/src/views/admin/UpstreamChannelsView.vue';const Accounts=()=>import('/src/views/admin/AccountsView.vue');import zh from '/src/i18n/locales/zh/index.ts';import '/src/style.css';
const pinia=createPinia();const router=createRouter({history:createWebHistory(),routes:[{path:'/admin/channel-config',component:Config},{path:'/admin/profit-operations',component:Profit},{path:'/admin/upstream-channels',component:Channels},{path:'/admin/accounts',component:Accounts}]});
const app=createApp(RouterView);app.use(pinia);const auth=useAuthStore();auth.user={id:1,email:'synthetic@test.invalid',role:'admin',status:'active',balance:0,concurrency:1};app.use(router).use(createI18n({legacy:false,locale:'zh',messages:{zh}})).mount('#app');</script></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()})
Expand Down Expand Up @@ -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()}
2 changes: 1 addition & 1 deletion .github/workflows/profit-operations.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions backend/internal/handler/admin/channel_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions backend/internal/handler/admin/mature_providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
38 changes: 36 additions & 2 deletions backend/internal/handler/admin/profit_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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) {
Expand All @@ -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})
}
Loading
Loading