Compare commits
4
Commits
v1.2.0
...
dev/novalink
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b4262f9e2 | ||
|
|
199cbc0e32 | ||
|
|
b71ac7aa88 | ||
|
|
9b8f0584e6 |
No files matched your search
@@ -31,6 +31,12 @@ services:
|
||||
- REDIS_CONN_STRING=redis://redis
|
||||
- TZ=Asia/Shanghai
|
||||
- BATCH_UPDATE_ENABLED=true
|
||||
# 上游监控凭据加密:首次配置运行 openssl rand -base64 32 生成密钥,再取消下一行注释并替换占位值。
|
||||
# Upstream credential encryption: generate with openssl rand -base64 32, then uncomment and replace the placeholder.
|
||||
# - UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
|
||||
# 修改后执行 / Apply with: docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api
|
||||
# 单纯重启不会更新环境变量。密钥独立备份,所有节点使用同一持久密钥;已有凭据时沿用原密钥。
|
||||
# A restart does not reload environment changes. Back up the key separately; reuse the same persistent key on all nodes and for existing credentials.
|
||||
# Local HTTP dev mode: keep Secure=false and leave TRUSTED_URL unset. This disables the refresh/logout OriginGuard so the :5173 -> :3000 dev proxy works.
|
||||
- SESSION_COOKIE_SECURE=false
|
||||
# For HTTPS only: set Secure=true and list every exact trusted HTTPS browser Origin. This does not configure relay CORS.
|
||||
|
||||
@@ -40,6 +40,12 @@ services:
|
||||
# - STREAMING_TIMEOUT=300 # 流模式无响应超时时间,单位秒,默认120秒,如果出现空补全可以尝试改为更大值 (Streaming timeout in seconds, default is 120s. Increase if experiencing empty completions)
|
||||
# - RELAY_IDLE_CONN_TIMEOUT=90 # Relay HTTP 客户端空闲连接超时时间,单位秒,默认跟随 Go 标准库,设置为0表示不限制 (Relay HTTP client idle keep-alive timeout in seconds, defaults to Go standard library; set 0 to disable)
|
||||
# - SESSION_SECRET=random_string # 多机部署时设置,必须修改这个随机字符串!! (multi-node deployment, set this to a random string!!!!!!!)
|
||||
# 上游监控凭据加密:首次配置运行 openssl rand -base64 32 生成密钥,再取消下一行注释并替换占位值。
|
||||
# Upstream credential encryption: generate with openssl rand -base64 32, then uncomment and replace the placeholder.
|
||||
# - UPSTREAM_MONITOR_KEY=base64_encoded_32_random_bytes
|
||||
# 修改后执行 / Apply with: docker compose up -d --no-deps --force-recreate new-api
|
||||
# 单纯重启不会更新环境变量。密钥独立备份,所有节点使用同一持久密钥;已有凭据时沿用原密钥。
|
||||
# A restart does not reload environment changes. Back up the key separately; reuse the same persistent key on all nodes and for existing credentials.
|
||||
# - SESSION_COOKIE_SECURE=true # true:启用 Secure Refresh Cookie 和严格 refresh/logout OriginGuard;false/未配置:关闭 OriginGuard,仅用于本地 HTTP (true: Secure cookie + strict refresh/logout OriginGuard; false/unset: guard disabled for local HTTP only)
|
||||
# - SESSION_COOKIE_TRUSTED_URL=https://example.com,https://admin.example.com # Secure=true 时必填的精确 HTTPS Origin;不是 relay CORS 白名单,不支持通配符/路径 (Required exact HTTPS origins when Secure=true; not a relay CORS allowlist, no wildcard/path)
|
||||
# - TRUSTED_PROXIES=172.20.0.0/16 # 未配置时信任回环/RFC1918/fc00::/7 并告警,none 为严格模式,显式列表替代默认值 (Unset trusts loopback/RFC 1918/fc00::/7 with a warning; none trusts no proxies; an explicit list replaces defaults)
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { act, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createInstance } from 'i18next'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { BindingsPanel } from '../components/bindings-panel'
|
||||
import en from '@/i18n/locales/en.json'
|
||||
import fr from '@/i18n/locales/fr.json'
|
||||
import zh from '@/i18n/locales/zh.json'
|
||||
|
||||
import { BindingDialog, BindingsPanel } from '../components/bindings-panel'
|
||||
import type { MonitorAccount, MonitorSnapshot, MonitorState } from '../types'
|
||||
|
||||
const account: MonitorAccount = {
|
||||
@@ -148,7 +154,9 @@ describe('cost binding selectors', () => {
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2)
|
||||
await user.type(group, 'shop-a')
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'shop-a (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Local model' }))
|
||||
expect(screen.getAllByRole('option')).toHaveLength(3)
|
||||
@@ -177,6 +185,192 @@ describe('cost binding selectors', () => {
|
||||
)
|
||||
})
|
||||
|
||||
test('group options and selected labels show full captured ratios, preserve zero and keep missing ratios unknown', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
const latest = input.snapshots.find((item) => item.id === 'newest')
|
||||
if (!latest) throw new Error('Missing confirmed snapshot')
|
||||
latest.data.groups = [
|
||||
{
|
||||
name: 'shop-a',
|
||||
display_name: 'Shared display name',
|
||||
ratio: 0.085123456789,
|
||||
},
|
||||
{ name: 'shop-b', display_name: 'Shared display name', ratio: 0 },
|
||||
{ name: 'unknown', ratio: null },
|
||||
]
|
||||
render(<BindingsPanel state={input} onSave={vi.fn()} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Add binding' }))
|
||||
const group = screen.getByRole('combobox', { name: 'Upstream group' })
|
||||
await user.click(group)
|
||||
const precise =
|
||||
'shop-a (Shared display name) · Upstream ratio 0.085123456789'
|
||||
expect(screen.getByRole('option', { name: precise })).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-b (Shared display name) · Upstream ratio 0',
|
||||
})
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('option', { name: 'unknown · Upstream ratio Unknown' })
|
||||
).toBeVisible()
|
||||
await user.click(screen.getByRole('option', { name: precise }))
|
||||
expect(group).toHaveValue(precise)
|
||||
})
|
||||
|
||||
test('selected group ratio labels follow interface language changes without replacing the saved group code', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
const latest = input.snapshots.find((item) => item.id === 'newest')
|
||||
if (!latest) throw new Error('Missing confirmed snapshot')
|
||||
latest.data.groups[0].ratio = 0.085123456789
|
||||
input.config.bindings = [
|
||||
{
|
||||
id: 'binding',
|
||||
channel_id: 1,
|
||||
account_id: 'bee',
|
||||
upstream_group: 'shop-a',
|
||||
local_model: '',
|
||||
upstream_model: '',
|
||||
},
|
||||
]
|
||||
const translations = createInstance()
|
||||
await translations.init({
|
||||
lng: 'en',
|
||||
fallbackLng: 'en',
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
resources: { en, fr, zhCN: zh },
|
||||
})
|
||||
const onSave = vi.fn().mockResolvedValue(undefined)
|
||||
render(
|
||||
<I18nextProvider i18n={translations}>
|
||||
<BindingsPanel state={input} onSave={onSave} />
|
||||
</I18nextProvider>
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
const group = screen.getByRole('combobox', { name: 'Upstream group' })
|
||||
expect(group).toHaveValue(
|
||||
'shop-a (Shared display name) · Upstream ratio 0.085123456789'
|
||||
)
|
||||
await act(() => translations.changeLanguage('fr'))
|
||||
expect(group).toHaveValue(
|
||||
'shop-a (Shared display name) · Coefficient fournisseur 0,085123456789'
|
||||
)
|
||||
await act(() => translations.changeLanguage('zhCN'))
|
||||
expect(group).toHaveValue(
|
||||
'shop-a (Shared display name) · 上游倍率 0.085123456789'
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: '保存' }))
|
||||
await waitFor(() =>
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bindings: [expect.objectContaining({ upstream_group: 'shop-a' })],
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
test('channel search filters names, preserves selection on no match and saves the selected numeric ID', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
input.channels[1].name = '美团 LongChat'
|
||||
input.config.bindings = [
|
||||
{
|
||||
id: 'binding',
|
||||
channel_id: 1,
|
||||
account_id: 'bee',
|
||||
upstream_group: 'shop-a',
|
||||
local_model: 'local-gpt',
|
||||
upstream_model: 'gpt-upstream',
|
||||
},
|
||||
]
|
||||
const onSave = vi.fn().mockResolvedValue(undefined)
|
||||
render(<BindingsPanel state={input} onSave={onSave} />)
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
const channel = screen.getByRole('combobox', { name: 'Channel' })
|
||||
expect(channel).toHaveValue('OpenAI')
|
||||
await user.click(channel)
|
||||
await user.type(channel, 'no-matching-channel')
|
||||
expect(screen.getByText('No results found')).toBeVisible()
|
||||
expect(screen.queryByRole('option')).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(channel).toHaveValue('OpenAI')
|
||||
await user.click(channel)
|
||||
await user.type(channel, 'LONGchat')
|
||||
expect(screen.getAllByRole('option')).toHaveLength(1)
|
||||
expect(screen.getByRole('option', { name: '美团 LongChat' })).toBeVisible()
|
||||
await user.keyboard('{ArrowDown}{Enter}')
|
||||
expect(channel).toHaveValue('美团 LongChat')
|
||||
await user.click(screen.getByRole('combobox', { name: 'Local model' }))
|
||||
expect(
|
||||
screen.getByRole('option', { name: 'All channel models' })
|
||||
).toHaveAttribute('aria-selected', 'true')
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'local-gpt' })
|
||||
).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(
|
||||
screen.getByRole('combobox', { name: 'Upstream model' })
|
||||
).toHaveValue('Channel mapping')
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bindings: [
|
||||
expect.objectContaining({
|
||||
channel_id: 2,
|
||||
upstream_group: 'shop-a',
|
||||
local_model: '',
|
||||
upstream_model: '',
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
test('a channel moved out of the quick-binding group after refresh cannot be saved', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
const onSave = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const view = render(
|
||||
<BindingDialog
|
||||
localGroup='default'
|
||||
state={input}
|
||||
onSave={onSave}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
const save = screen.getByRole('button', { name: 'Save' })
|
||||
expect(save).toBeEnabled()
|
||||
view.rerender(
|
||||
<BindingDialog
|
||||
localGroup='default'
|
||||
state={{
|
||||
...input,
|
||||
channels: input.channels.map((channel) => ({
|
||||
...channel,
|
||||
group: 'another-group',
|
||||
})),
|
||||
}}
|
||||
onSave={onSave}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)
|
||||
expect(save).toBeDisabled()
|
||||
await user.click(save)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('clears incompatible selections when switching account, channel or model scope', async () => {
|
||||
const user = userEvent.setup()
|
||||
const input = state()
|
||||
@@ -215,7 +409,9 @@ describe('cost binding selectors', () => {
|
||||
await user.click(group)
|
||||
expect(screen.getAllByRole('option')).toHaveLength(1)
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'other-code (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'other-code (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
await user.click(upstream)
|
||||
expect(screen.getByRole('option', { name: 'other-model' })).toBeVisible()
|
||||
@@ -233,7 +429,9 @@ describe('cost binding selectors', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Add binding' }))
|
||||
await user.click(screen.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'shop-a (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
await user.click(screen.getByRole('combobox', { name: 'Local model' }))
|
||||
await user.click(screen.getByRole('option', { name: 'local-gpt' }))
|
||||
@@ -322,7 +520,9 @@ describe('cost binding selectors', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Add binding' }))
|
||||
await user.click(screen.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'shop-a (Shared display name)' })
|
||||
screen.getByRole('option', {
|
||||
name: 'shop-a (Shared display name) · Upstream ratio 1',
|
||||
})
|
||||
)
|
||||
const models = screen.getByRole('combobox', { name: 'Local model' })
|
||||
await user.click(models)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { act, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createInstance } from 'i18next'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import en from '@/i18n/locales/en.json'
|
||||
import fr from '@/i18n/locales/fr.json'
|
||||
import ja from '@/i18n/locales/ja.json'
|
||||
import ru from '@/i18n/locales/ru.json'
|
||||
import viLocale from '@/i18n/locales/vi.json'
|
||||
import zhTW from '@/i18n/locales/zh-TW.json'
|
||||
import zh from '@/i18n/locales/zh.json'
|
||||
|
||||
import { EncryptionKeyNotice } from '../components/encryption-key-notice'
|
||||
|
||||
const resources = { en, zhCN: zh, zhTW, fr, ru, ja, vi: viLocale }
|
||||
|
||||
describe('upstream credential key setup', () => {
|
||||
test('a missing or invalid key shows expandable configuration steps with copyable commands and no preset secret', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clipboard = vi.spyOn(navigator.clipboard, 'writeText')
|
||||
render(<EncryptionKeyNotice ready={false} />)
|
||||
const alert = screen.getByRole('alert')
|
||||
expect(alert).toHaveTextContent('Credential encryption is not configured')
|
||||
const summary = within(alert).getByText(
|
||||
'How to configure the encryption key'
|
||||
)
|
||||
const details = summary.closest('details')
|
||||
expect(details).not.toHaveAttribute('open')
|
||||
await user.click(summary)
|
||||
expect(details).toHaveAttribute('open')
|
||||
const steps = within(alert).getByRole('list')
|
||||
expect(within(steps).getAllByRole('listitem')).toHaveLength(3)
|
||||
expect(steps).toHaveTextContent('docker-compose.yml')
|
||||
expect(steps).toHaveTextContent('docker-compose.dev.yml')
|
||||
expect(steps).toHaveTextContent('- UPSTREAM_MONITOR_KEY=<BASE64_KEY>')
|
||||
expect(alert).toHaveTextContent('restore the original key')
|
||||
expect(alert).toHaveTextContent('working directory')
|
||||
const commands = [
|
||||
'openssl rand -base64 32',
|
||||
'docker compose up -d --no-deps --force-recreate new-api',
|
||||
'docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api',
|
||||
]
|
||||
const copy = within(alert).getAllByRole('button', {
|
||||
name: 'Copy to clipboard',
|
||||
})
|
||||
expect(copy).toHaveLength(commands.length)
|
||||
for (const [index, command] of commands.entries()) {
|
||||
expect(alert).toHaveTextContent(command)
|
||||
await user.click(copy[index])
|
||||
expect(clipboard).toHaveBeenLastCalledWith(command)
|
||||
}
|
||||
expect(alert.textContent).not.toMatch(/[A-Za-z0-9+/]{43}=/)
|
||||
})
|
||||
|
||||
test('a valid key removes the warning and setup steps after state refresh', () => {
|
||||
const view = render(<EncryptionKeyNotice ready={false} />)
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument()
|
||||
view.rerender(<EncryptionKeyNotice ready />)
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByText('How to configure the encryption key')
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('setup instructions follow all seven interface languages while commands stay exact', async () => {
|
||||
const translations = createInstance()
|
||||
await translations.init({
|
||||
lng: 'en',
|
||||
fallbackLng: 'en',
|
||||
keySeparator: false,
|
||||
nsSeparator: false,
|
||||
resources,
|
||||
})
|
||||
render(
|
||||
<I18nextProvider i18n={translations}>
|
||||
<EncryptionKeyNotice ready={false} />
|
||||
</I18nextProvider>
|
||||
)
|
||||
for (const [language, resource] of Object.entries(resources)) {
|
||||
await act(() => translations.changeLanguage(language))
|
||||
const alert = screen.getByRole('alert')
|
||||
const key = 'How to configure the encryption key'
|
||||
expect(within(alert).getByText(resource.translation[key])).toBeVisible()
|
||||
expect(alert).toHaveTextContent('openssl rand -base64 32')
|
||||
expect(alert).toHaveTextContent('- UPSTREAM_MONITOR_KEY=<BASE64_KEY>')
|
||||
expect(alert).toHaveTextContent(
|
||||
'docker compose up -d --no-deps --force-recreate new-api'
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -486,6 +486,7 @@ describe('profit comparisons', () => {
|
||||
name: 'Channel cost bindings',
|
||||
})
|
||||
expect(drawer).toHaveAttribute('data-side', 'right')
|
||||
expect(drawer).toHaveClass('w-full', 'sm:w-[90vw]', 'sm:max-w-7xl')
|
||||
expect(bindings).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(
|
||||
within(drawer).getByRole('button', { name: 'Add binding' })
|
||||
@@ -501,6 +502,165 @@ describe('profit comparisons', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('quick binding opens the shared dialog with only exact local-group channels and saves without dropping existing bindings', async () => {
|
||||
const user = userEvent.setup()
|
||||
const state = stateWithRows([
|
||||
baseRow,
|
||||
{ ...baseRow, local_group: 'premium' },
|
||||
{ ...baseRow, local_group: 'no-channels' },
|
||||
])
|
||||
state.channels = [
|
||||
{ id: 1, name: 'Standard channel', group: 'standard', models: 'model-a' },
|
||||
{
|
||||
id: 2,
|
||||
name: 'Shared channel',
|
||||
group: 'standard, premium',
|
||||
models: 'shared-model',
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'Premium channel',
|
||||
group: 'premium',
|
||||
models: 'premium-model',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: 'Wrong group',
|
||||
group: 'premium-plus',
|
||||
models: 'wrong-model',
|
||||
},
|
||||
]
|
||||
state.config.accounts = [
|
||||
{
|
||||
id: 'account-a',
|
||||
site_id: 'site-a',
|
||||
name: 'Account A',
|
||||
username: 'operator',
|
||||
external_id: '42',
|
||||
has_password: true,
|
||||
device_id: '',
|
||||
flow_id: '',
|
||||
interval_minutes: 0,
|
||||
enabled: true,
|
||||
purchase_factor: 1,
|
||||
fee_rate: 0,
|
||||
fee_bearer: 'self',
|
||||
},
|
||||
]
|
||||
const existing = {
|
||||
id: 'existing',
|
||||
channel_id: 1,
|
||||
account_id: 'account-a',
|
||||
upstream_group: 'base',
|
||||
local_model: 'model-a',
|
||||
upstream_model: 'source-a',
|
||||
}
|
||||
state.config.bindings = [existing]
|
||||
state.snapshots = [
|
||||
{
|
||||
id: 'capture',
|
||||
job_id: 'job',
|
||||
account_id: 'account-a',
|
||||
confirmed: true,
|
||||
complete: true,
|
||||
created_at: 1,
|
||||
data: {
|
||||
account_id: '42',
|
||||
balances: [],
|
||||
models: [],
|
||||
groups: [{ name: 'base', ratio: 0.5 }],
|
||||
topups: [],
|
||||
warnings: [],
|
||||
},
|
||||
},
|
||||
]
|
||||
const get = vi
|
||||
.spyOn(api, 'get')
|
||||
.mockResolvedValue({ data: { success: true, data: state } })
|
||||
const put = vi
|
||||
.spyOn(api, 'put')
|
||||
.mockResolvedValue({ data: { success: true } })
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
|
||||
})
|
||||
const view = render(
|
||||
<QueryClientProvider client={client}>
|
||||
<UpstreamMonitor />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
try {
|
||||
const quick = await screen.findByRole('button', {
|
||||
name: 'Bind channels in premium',
|
||||
})
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Bind channels in no-channels' })
|
||||
).toBeDisabled()
|
||||
const local = within(screen.getByRole('region', { name: 'Local groups' }))
|
||||
expect(
|
||||
local.getByRole('button', { name: /^standard/, pressed: true })
|
||||
).toBeVisible()
|
||||
quick.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
const dialog = within(
|
||||
await screen.findByRole('dialog', { name: 'Channel cost binding' })
|
||||
)
|
||||
expect(dialog.getByText('Channels in local group premium')).toBeVisible()
|
||||
const channel = dialog.getByRole('combobox', { name: 'Channel' })
|
||||
expect(channel).toHaveValue('Shared channel')
|
||||
await user.click(channel)
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2)
|
||||
expect(
|
||||
screen.getByRole('option', { name: 'Shared channel' })
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'Standard channel' })
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('option', { name: 'Wrong group' })
|
||||
).not.toBeInTheDocument()
|
||||
await user.type(channel, 'premium')
|
||||
await user.click(screen.getByRole('option', { name: 'Premium channel' }))
|
||||
await user.click(dialog.getByRole('combobox', { name: 'Upstream group' }))
|
||||
await user.click(
|
||||
screen.getByRole('option', { name: 'base · Upstream ratio 0.5' })
|
||||
)
|
||||
await user.click(dialog.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(put).toHaveBeenCalledWith(
|
||||
'/api/upstream_monitor/config',
|
||||
expect.objectContaining({
|
||||
bindings: [
|
||||
existing,
|
||||
expect.objectContaining({
|
||||
channel_id: 3,
|
||||
account_id: 'account-a',
|
||||
upstream_group: 'base',
|
||||
local_model: '',
|
||||
upstream_model: '',
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'Channel cost binding' })
|
||||
).not.toBeInTheDocument()
|
||||
)
|
||||
expect(
|
||||
local.getByRole('button', { name: /^standard/, pressed: true })
|
||||
).toBeVisible()
|
||||
expect(state.config.bindings).toEqual([existing])
|
||||
expect(
|
||||
get.mock.calls.filter(([url]) => url === '/api/upstream_monitor/state')
|
||||
.length
|
||||
).toBeGreaterThan(1)
|
||||
} finally {
|
||||
view.unmount()
|
||||
client.clear()
|
||||
}
|
||||
})
|
||||
|
||||
test('details show the matched tier, unit prices, and the same trial values in JSON', async () => {
|
||||
const user = userEvent.setup()
|
||||
const row = {
|
||||
@@ -892,7 +1052,7 @@ describe('profit comparisons', () => {
|
||||
upstreamKey: '',
|
||||
})
|
||||
})
|
||||
test('switching local groups updates selected upstream and models with keyboard access', async () => {
|
||||
test('group headers count distinct list entries and update upstream counts when switching local groups', async () => {
|
||||
const user = userEvent.setup()
|
||||
const second = {
|
||||
...baseRow,
|
||||
@@ -901,27 +1061,55 @@ describe('profit comparisons', () => {
|
||||
site_name: 'Site B',
|
||||
local_model: 'model-b',
|
||||
}
|
||||
render(
|
||||
const view = render(
|
||||
<ProfitPanel
|
||||
state={stateWithRows([baseRow, second])}
|
||||
state={stateWithRows([
|
||||
baseRow,
|
||||
{ ...baseRow, channel_id: 2, local_model: 'another-model' },
|
||||
{ ...baseRow, account_id: 'another-account', site_name: 'Site C' },
|
||||
second,
|
||||
])}
|
||||
onSnapshot={vi.fn()}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('model-a')).toBeInTheDocument()
|
||||
const local = screen.getByRole('region', { name: 'Local groups' })
|
||||
const upstream = screen.getByRole('region', { name: 'Upstream groups' })
|
||||
expect(
|
||||
within(within(local).getByRole('heading')).getByText('2')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(within(upstream).getByRole('heading')).getByText('2')
|
||||
).toBeVisible()
|
||||
expect(within(local).getAllByRole('button')).toHaveLength(2)
|
||||
expect(within(upstream).getAllByRole('button')).toHaveLength(2)
|
||||
const premium = within(local).getByRole('button', { name: /premium/ })
|
||||
premium.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
expect(premium).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getByText('model-b')).toBeInTheDocument()
|
||||
expect(screen.queryByText('model-a')).not.toBeInTheDocument()
|
||||
const upstream = screen.getByRole('region', { name: 'Upstream groups' })
|
||||
expect(
|
||||
within(upstream).getByRole('button', { pressed: true })
|
||||
).toHaveTextContent('Site B')
|
||||
expect(
|
||||
within(within(local).getByRole('heading')).getByText('2')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(within(upstream).getByRole('heading')).getByText('1')
|
||||
).toBeVisible()
|
||||
expect(screen.getByTestId('profit-columns')).toHaveClass(
|
||||
'lg:grid-cols-[20fr_20fr_60fr]'
|
||||
)
|
||||
view.rerender(
|
||||
<ProfitPanel state={stateWithRows([second])} onSnapshot={vi.fn()} />
|
||||
)
|
||||
expect(
|
||||
within(within(local).getByRole('heading')).getByText('1')
|
||||
).toBeVisible()
|
||||
expect(
|
||||
within(within(upstream).getByRole('heading')).getByText('1')
|
||||
).toBeVisible()
|
||||
})
|
||||
test('profit list omits repeated account names, channel names and the comparable badge', () => {
|
||||
const state = stateWithRows([baseRow])
|
||||
@@ -1260,6 +1448,61 @@ describe('profit comparisons', () => {
|
||||
expect(within(accounts).getByRole('table')).toBeVisible()
|
||||
})
|
||||
|
||||
test('upstream account balances retain captured fractional precision, signs and unknown values', () => {
|
||||
const state = stateWithRows([])
|
||||
state.config.accounts = [
|
||||
{
|
||||
id: 'account',
|
||||
site_id: 'site',
|
||||
name: 'Precision account',
|
||||
username: 'operator',
|
||||
external_id: '42',
|
||||
has_password: false,
|
||||
device_id: '',
|
||||
flow_id: '',
|
||||
interval_minutes: 0,
|
||||
enabled: true,
|
||||
purchase_factor: 1,
|
||||
fee_rate: 0,
|
||||
fee_bearer: 'self',
|
||||
},
|
||||
]
|
||||
state.snapshots = [
|
||||
{
|
||||
id: 'snapshot',
|
||||
job_id: 'job',
|
||||
account_id: 'account',
|
||||
confirmed: true,
|
||||
complete: true,
|
||||
created_at: 100,
|
||||
data: {
|
||||
account_id: '42',
|
||||
groups: [],
|
||||
models: [],
|
||||
topups: [],
|
||||
warnings: [],
|
||||
balances: [
|
||||
{ kind: 'wallet', amount: 4.000123456, currency: 'USD' },
|
||||
{ kind: 'available', amount: -0.00022783, currency: 'CNY' },
|
||||
{ kind: 'tiny', amount: 8.5123456789e-14, currency: 'JPY' },
|
||||
{ kind: 'zero', amount: 0, currency: 'USD' },
|
||||
{ kind: 'unknown', amount: null, currency: 'USD' },
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
render(<SitesPanel state={state} onSave={vi.fn()} onRun={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('wallet: 4.000123456 USD')).toBeVisible()
|
||||
expect(screen.getByText('available: -0.00022783 CNY')).toBeVisible()
|
||||
expect(
|
||||
screen.getByText('tiny: 0.000000000000085123456789 JPY')
|
||||
).toBeVisible()
|
||||
expect(screen.getByText('zero: 0 USD')).toBeVisible()
|
||||
expect(screen.getByText('unknown: — USD')).toBeVisible()
|
||||
})
|
||||
|
||||
test.each([false, true])(
|
||||
'all models with estimates=%s shows labeled unconnected inventory without changing scenario totals',
|
||||
async (estimated) => {
|
||||
|
||||
@@ -17,7 +17,12 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form'
|
||||
import { parseModelsList } from '@/features/channels/lib/channel-utils'
|
||||
import {
|
||||
parseGroupsList,
|
||||
parseModelsList,
|
||||
} from '@/features/channels/lib/channel-utils'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
import { formatNumber } from '@/lib/format'
|
||||
import { handleServerError } from '@/lib/handle-server-error'
|
||||
|
||||
import { bindingSchema, newMonitorID } from '../lib/config'
|
||||
@@ -35,18 +40,27 @@ function includeSavedOption(
|
||||
: options
|
||||
}
|
||||
|
||||
function BindingDialog(props: {
|
||||
export function BindingDialog(props: {
|
||||
binding?: MonitorBinding
|
||||
localGroup?: string
|
||||
state: MonitorState
|
||||
onSave: SaveMonitorConfig
|
||||
onClose: () => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
|
||||
const binding = props.binding
|
||||
const localGroup = props.localGroup
|
||||
const channels =
|
||||
localGroup === undefined
|
||||
? props.state.channels
|
||||
: props.state.channels.filter((channel) =>
|
||||
parseGroupsList(channel.group).includes(localGroup)
|
||||
)
|
||||
const form = useForm<z.infer<typeof bindingSchema>>({
|
||||
resolver: zodResolver(bindingSchema),
|
||||
defaultValues: {
|
||||
channel_id: binding?.channel_id ?? props.state.channels[0]?.id ?? 0,
|
||||
channel_id: binding?.channel_id ?? channels[0]?.id ?? 0,
|
||||
account_id:
|
||||
binding?.account_id ?? props.state.config.accounts[0]?.id ?? '',
|
||||
upstream_group: binding?.upstream_group ?? '',
|
||||
@@ -60,11 +74,19 @@ function BindingDialog(props: {
|
||||
const localModels = form.watch('local_models')
|
||||
const localModel = localModels.length === 1 ? localModels[0] : undefined
|
||||
const snapshot = latestMonitorSnapshots(props.state.snapshots).get(accountID)
|
||||
const channel = props.state.channels.find((item) => item.id === channelID)
|
||||
const channel = channels.find((item) => item.id === channelID)
|
||||
const groupOptions = includeSavedOption(
|
||||
(snapshot?.data.groups ?? []).map((item) => ({
|
||||
value: item.name,
|
||||
label: monitorGroupLabel(item.name, item.display_name),
|
||||
label: `${monitorGroupLabel(item.name, item.display_name)} · ${t(
|
||||
'Upstream ratio {{ratio}}',
|
||||
{
|
||||
ratio:
|
||||
item.ratio === null
|
||||
? t('Unknown')
|
||||
: formatNumber(item.ratio, locale, { fullPrecision: true }),
|
||||
}
|
||||
)}`,
|
||||
})),
|
||||
binding?.account_id === accountID ? binding.upstream_group : undefined
|
||||
)
|
||||
@@ -93,6 +115,13 @@ function BindingDialog(props: {
|
||||
const clearUpstreamModel = () =>
|
||||
form.setValue('upstream_model', '', { shouldDirty: true })
|
||||
const submit = async (values: z.infer<typeof bindingSchema>) => {
|
||||
if (
|
||||
props.localGroup !== undefined &&
|
||||
!channels.some((channel) => channel.id === values.channel_id)
|
||||
) {
|
||||
form.setError('channel_id', { message: t('Select an option') })
|
||||
return
|
||||
}
|
||||
const { local_models, ...scope } = values
|
||||
const existing = props.state.config.bindings.filter(
|
||||
(item) => item.id !== binding?.id
|
||||
@@ -146,6 +175,11 @@ function BindingDialog(props: {
|
||||
if (!open) props.onClose()
|
||||
}}
|
||||
title={t('Channel cost binding')}
|
||||
description={
|
||||
props.localGroup === undefined
|
||||
? undefined
|
||||
: t('Channels in local group {{group}}', { group: props.localGroup })
|
||||
}
|
||||
footer={
|
||||
<>
|
||||
<Button variant='outline' onClick={props.onClose}>
|
||||
@@ -155,7 +189,10 @@ function BindingDialog(props: {
|
||||
type='submit'
|
||||
form='monitor-binding-form'
|
||||
disabled={
|
||||
form.formState.isSubmitting || !group || !localModels.length
|
||||
form.formState.isSubmitting ||
|
||||
!group ||
|
||||
!localModels.length ||
|
||||
(props.localGroup !== undefined && !channel)
|
||||
}
|
||||
>
|
||||
{t('Save')}
|
||||
@@ -173,11 +210,12 @@ function BindingDialog(props: {
|
||||
control={form.control}
|
||||
name='channel_id'
|
||||
label={t('Channel')}
|
||||
searchable
|
||||
onValueChange={() => {
|
||||
form.setValue('local_models', [''], { shouldDirty: true })
|
||||
clearUpstreamModel()
|
||||
}}
|
||||
options={props.state.channels.map((channel) => ({
|
||||
options={channels.map((channel) => ({
|
||||
value: String(channel.id),
|
||||
label: channel.name,
|
||||
}))}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { CopyButton } from '@/components/copy-button'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
|
||||
export function EncryptionKeyNotice(props: { ready: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
if (props.ready) return null
|
||||
|
||||
const generateCommand = 'openssl rand -base64 32'
|
||||
const recreateCommand =
|
||||
'docker compose up -d --no-deps --force-recreate new-api'
|
||||
const recreateDevCommand =
|
||||
'docker compose -f docker-compose.dev.yml up -d --no-deps --force-recreate new-api'
|
||||
|
||||
return (
|
||||
<Alert
|
||||
variant='destructive'
|
||||
className='max-h-[50%] shrink-0 overflow-y-auto'
|
||||
>
|
||||
<AlertTitle>{t('Credential encryption is not configured')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t(
|
||||
'An administrator must configure the upstream monitor encryption key before saving credentials or running tasks.'
|
||||
)}
|
||||
<details className='text-foreground mt-2 min-w-0'>
|
||||
<summary className='focus-visible:ring-ring cursor-pointer rounded-sm font-medium focus-visible:ring-2 focus-visible:outline-none'>
|
||||
{t('How to configure the encryption key')}
|
||||
</summary>
|
||||
<ol className='mt-3 list-decimal space-y-3 pl-5'>
|
||||
<li>
|
||||
{t(
|
||||
'For first-time setup, generate a random 32-byte Base64 key on the server:'
|
||||
)}
|
||||
<div className='bg-muted mt-1 flex min-w-0 items-start gap-2 rounded-md p-2'>
|
||||
<code className='min-w-0 flex-1 self-center break-all'>
|
||||
{generateCommand}
|
||||
</code>
|
||||
<CopyButton value={generateCommand} className='size-7' />
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:'
|
||||
)}
|
||||
<code className='bg-muted mt-1 block rounded-md p-2 break-all'>
|
||||
{'- UPSTREAM_MONITOR_KEY=<BASE64_KEY>'}
|
||||
</code>
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:'
|
||||
)}
|
||||
<div className='bg-muted mt-1 flex min-w-0 items-start gap-2 rounded-md p-2'>
|
||||
<code className='min-w-0 flex-1 self-center break-all'>
|
||||
{recreateCommand}
|
||||
</code>
|
||||
<CopyButton value={recreateCommand} className='size-7' />
|
||||
</div>
|
||||
<div className='mt-2'>
|
||||
{t('For docker-compose.dev.yml, use:')}
|
||||
</div>
|
||||
<div className='bg-muted mt-1 flex min-w-0 items-start gap-2 rounded-md p-2'>
|
||||
<code className='min-w-0 flex-1 self-center break-all'>
|
||||
{recreateDevCommand}
|
||||
</code>
|
||||
<CopyButton value={recreateDevCommand} className='size-7' />
|
||||
</div>
|
||||
<div className='mt-2'>
|
||||
{t(
|
||||
'Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.'
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<div className='mt-3'>
|
||||
{t(
|
||||
'For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.'
|
||||
)}
|
||||
</div>
|
||||
<div className='mt-3'>
|
||||
{t(
|
||||
'Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.'
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Link2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
@@ -9,9 +10,16 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { parseGroupsList } from '@/features/channels/lib/channel-utils'
|
||||
import { toIntlLocale } from '@/i18n/languages'
|
||||
import { formatLocalCurrencyAmount } from '@/lib/currency'
|
||||
import { formatNumber, formatTimestamp } from '@/lib/format'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
import { monitorGroupLabel } from '../lib/groups'
|
||||
import { latestMonitorSnapshots } from '../lib/jobs'
|
||||
@@ -38,6 +46,7 @@ export const profitColumnsClassName =
|
||||
export function ProfitPanel(props: {
|
||||
state: MonitorState
|
||||
onSnapshot: (id: string) => void
|
||||
onBind?: (group: string) => void
|
||||
}) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
|
||||
@@ -194,39 +203,73 @@ export function ProfitPanel(props: {
|
||||
className='flex min-h-0 min-w-0 flex-col rounded-xl border'
|
||||
aria-label={t('Local groups')}
|
||||
>
|
||||
<h3 className='shrink-0 border-b px-3 py-2 text-sm font-medium'>
|
||||
{t('Local groups')}
|
||||
<h3 className='flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2 text-sm font-medium'>
|
||||
<span>{t('Local groups')}</span>
|
||||
<Badge variant='secondary' className='tabular-nums'>
|
||||
{formatNumber(localGroups.length, locale)}
|
||||
</Badge>
|
||||
</h3>
|
||||
<div className='max-h-72 min-h-0 space-y-1 overflow-y-auto overscroll-contain p-2 lg:max-h-none lg:flex-1'>
|
||||
{localGroups.map((group) => (
|
||||
<Button
|
||||
<div
|
||||
key={group}
|
||||
variant={
|
||||
selection.localGroup === group ? 'secondary' : 'ghost'
|
||||
}
|
||||
className='h-auto w-full justify-start px-3 py-2 text-left whitespace-normal'
|
||||
aria-pressed={selection.localGroup === group}
|
||||
onClick={() => {
|
||||
setLocalGroup(group)
|
||||
setUpstreamKey('')
|
||||
}}
|
||||
className={cn(
|
||||
'flex min-w-0 items-center rounded-md',
|
||||
selection.localGroup === group && 'bg-secondary'
|
||||
)}
|
||||
>
|
||||
<span className='min-w-0'>
|
||||
<span className='block break-all'>{group}</span>
|
||||
<span className='text-muted-foreground block text-xs'>
|
||||
{t('Ratio {{ratio}} · {{count}} routes', {
|
||||
ratio: formatNumber(
|
||||
rows.find((row) => row.local_group === group)
|
||||
?.local_ratio,
|
||||
locale,
|
||||
{ fullPrecision: true }
|
||||
),
|
||||
count: rows.filter((row) => row.local_group === group)
|
||||
.length,
|
||||
})}
|
||||
<Button
|
||||
variant='ghost'
|
||||
className='h-auto min-w-0 flex-1 justify-start px-3 py-2 text-left whitespace-normal'
|
||||
aria-pressed={selection.localGroup === group}
|
||||
onClick={() => {
|
||||
setLocalGroup(group)
|
||||
setUpstreamKey('')
|
||||
}}
|
||||
>
|
||||
<span className='min-w-0'>
|
||||
<span className='block break-all'>{group}</span>
|
||||
<span className='text-muted-foreground block text-xs'>
|
||||
{t('Ratio {{ratio}} · {{count}} routes', {
|
||||
ratio: formatNumber(
|
||||
rows.find((row) => row.local_group === group)
|
||||
?.local_ratio,
|
||||
locale,
|
||||
{ fullPrecision: true }
|
||||
),
|
||||
count: rows.filter((row) => row.local_group === group)
|
||||
.length,
|
||||
})}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
</Button>
|
||||
{props.onBind && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon-sm'
|
||||
className='mr-1 shrink-0'
|
||||
aria-label={t('Bind channels in {{group}}', {
|
||||
group,
|
||||
})}
|
||||
disabled={
|
||||
!props.state.config.accounts.length ||
|
||||
!props.state.channels.some((channel) =>
|
||||
parseGroupsList(channel.group).includes(group)
|
||||
)
|
||||
}
|
||||
onClick={() => props.onBind?.(group)}
|
||||
>
|
||||
<Link2 className='size-4' />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{t('Bind')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
@@ -234,8 +277,11 @@ export function ProfitPanel(props: {
|
||||
className='flex min-h-0 min-w-0 flex-col rounded-xl border'
|
||||
aria-label={t('Upstream groups')}
|
||||
>
|
||||
<h3 className='shrink-0 border-b px-3 py-2 text-sm font-medium'>
|
||||
{t('Upstream groups')}
|
||||
<h3 className='flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2 text-sm font-medium'>
|
||||
<span>{t('Upstream groups')}</span>
|
||||
<Badge variant='secondary' className='tabular-nums'>
|
||||
{formatNumber(upstreams.length, locale)}
|
||||
</Badge>
|
||||
</h3>
|
||||
<div className='max-h-72 min-h-0 space-y-1 overflow-y-auto overscroll-contain p-2 lg:max-h-none lg:flex-1'>
|
||||
{upstreams.map(([key, row]) => {
|
||||
|
||||
@@ -203,6 +203,7 @@ export function SitesPanel(props: {
|
||||
locale,
|
||||
showSymbol: false,
|
||||
abbreviate: false,
|
||||
fullPrecision: true,
|
||||
})}{' '}
|
||||
{balance.currency}
|
||||
</p>
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
import { ErrorState } from '@/components/error-state'
|
||||
import { SectionPageLayout } from '@/components/layout'
|
||||
import { LoadingState } from '@/components/loading-state'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Sheet,
|
||||
@@ -24,8 +23,9 @@ import {
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
|
||||
import { getMonitorState, monitorQueryKey, saveMonitorConfig } from './api'
|
||||
import { BindingsPanel } from './components/bindings-panel'
|
||||
import { BindingDialog, BindingsPanel } from './components/bindings-panel'
|
||||
import { DevicesPanel } from './components/devices-panel'
|
||||
import { EncryptionKeyNotice } from './components/encryption-key-notice'
|
||||
import { FlowsPanel } from './components/flows-panel'
|
||||
import { JobDetail } from './components/job-detail'
|
||||
import { JobsPanel } from './components/jobs-panel'
|
||||
@@ -41,6 +41,7 @@ export function UpstreamMonitor() {
|
||||
const { t } = useTranslation()
|
||||
const client = useQueryClient()
|
||||
const [tab, setTab] = useState('profit')
|
||||
const [bindingGroup, setBindingGroup] = useState<string | null>(null)
|
||||
const [run, setRun] = useState<MonitorAccount | null>(null)
|
||||
const [configure, setConfigure] = useState<{ flow?: MonitorFlow } | null>(
|
||||
null
|
||||
@@ -81,7 +82,9 @@ export function UpstreamMonitor() {
|
||||
{t('Channel cost bindings')}
|
||||
</SheetTrigger>
|
||||
<SheetContent
|
||||
className={sideDrawerContentClassName('sm:w-4/5 sm:max-w-5xl')}
|
||||
className={sideDrawerContentClassName(
|
||||
'sm:w-[90vw] sm:max-w-7xl'
|
||||
)}
|
||||
>
|
||||
<SheetHeader
|
||||
className={sideDrawerHeaderClassName('pr-12 sm:pr-12')}
|
||||
@@ -105,18 +108,7 @@ export function UpstreamMonitor() {
|
||||
)}
|
||||
{state && (
|
||||
<div className='flex h-full min-h-0 flex-col gap-3'>
|
||||
{!state.key_ready && (
|
||||
<Alert variant='destructive'>
|
||||
<AlertTitle>
|
||||
{t('Credential encryption is not configured')}
|
||||
</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t(
|
||||
'An administrator must configure the upstream monitor encryption key before saving credentials or running tasks.'
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<EncryptionKeyNotice ready={state.key_ready} />
|
||||
<Tabs
|
||||
value={tab}
|
||||
onValueChange={setTab}
|
||||
@@ -149,7 +141,11 @@ export function UpstreamMonitor() {
|
||||
value='profit'
|
||||
className='min-h-0 flex-1 overflow-y-auto pt-2 lg:overflow-hidden'
|
||||
>
|
||||
<ProfitPanel state={state} onSnapshot={setSnapshotID} />
|
||||
<ProfitPanel
|
||||
state={state}
|
||||
onSnapshot={setSnapshotID}
|
||||
onBind={setBindingGroup}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value='sites'
|
||||
@@ -199,6 +195,14 @@ export function UpstreamMonitor() {
|
||||
)}
|
||||
</SectionPageLayout.Content>
|
||||
</SectionPageLayout>
|
||||
{bindingGroup !== null && state && (
|
||||
<BindingDialog
|
||||
localGroup={bindingGroup}
|
||||
state={state}
|
||||
onSave={save}
|
||||
onClose={() => setBindingGroup(null)}
|
||||
/>
|
||||
)}
|
||||
{run && state && (
|
||||
<RunDialog
|
||||
account={run}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Bind channels in {{group}}",
|
||||
"Channels in local group {{group}}": "Channels in local group {{group}}",
|
||||
"How to configure the encryption key": "How to configure the encryption key",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "For first-time setup, generate a random 32-byte Base64 key on the server:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:",
|
||||
"For docker-compose.dev.yml, use:": "For docker-compose.dev.yml, use:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.",
|
||||
"Select at most 500 estimate mappings.": "Select at most 500 estimate mappings.",
|
||||
"Select each upstream model and group only once.": "Select each upstream model and group only once.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Lier les canaux du groupe {{group}}",
|
||||
"Channels in local group {{group}}": "Canaux du groupe local {{group}}",
|
||||
"How to configure the encryption key": "Comment configurer la clé de chiffrement",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "Lors de la première configuration, générez sur le serveur une clé aléatoire de 32 octets encodée en Base64 :",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "Dans docker-compose.yml ou docker-compose.dev.yml, repérez la section environment du service new-api. Décommentez UPSTREAM_MONITOR_KEY et remplacez la valeur d’exemple par la clé générée :",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Recréez le conteneur backend pour appliquer la variable d’environnement ; redémarrer le conteneur existant ne charge pas les modifications :",
|
||||
"For docker-compose.dev.yml, use:": "Pour docker-compose.dev.yml, utilisez :",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Remplacez new-api dans ces commandes si votre service backend porte un autre nom. Actualisez cette page après le démarrage du backend.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "Pour un déploiement par exécutable, définissez UPSTREAM_MONITOR_KEY dans l’environnement du backend ou dans le fichier .env de son répertoire de travail, puis redémarrez le backend.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Sauvegardez la clé séparément de la base de données et utilisez la même clé sur tous les nœuds backend. Si des identifiants sont déjà enregistrés, restaurez la clé d’origine au lieu d’en générer une nouvelle.",
|
||||
"Select at most 500 estimate mappings.": "Sélectionnez au maximum 500 correspondances d’estimation.",
|
||||
"Select each upstream model and group only once.": "Sélectionnez chaque combinaison de modèle et groupe amont une seule fois.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Utilisez des noms exacts non vides respectant les limites UTF-8, sans espaces de début ou de fin ni caractères de contrôle.",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "{{group}} のチャネルを紐付け",
|
||||
"Channels in local group {{group}}": "ローカルグループ {{group}} のチャネル",
|
||||
"How to configure the encryption key": "暗号化キーの設定方法",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "初回設定時は、サーバー上で32バイトのランダムなキーをBase64形式で生成してください:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "docker-compose.yml または docker-compose.dev.yml で、new-api サービスの environment セクションを探してください。UPSTREAM_MONITOR_KEY のコメントを解除し、プレースホルダーを生成したキーに置き換えてください:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "環境変数を適用するには、バックエンドのコンテナを再作成してください。既存コンテナの再起動では変更は読み込まれません:",
|
||||
"For docker-compose.dev.yml, use:": "docker-compose.dev.yml を使用する場合:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "バックエンドのサービス名が異なる場合は、これらのコマンド内の new-api を置き換えてください。バックエンドの起動後、このページを再読み込みしてください。",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "実行ファイルを直接起動する構成では、バックエンドの環境変数または作業ディレクトリの .env ファイルに UPSTREAM_MONITOR_KEY を設定し、バックエンドを再起動してください。",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "キーはデータベースとは別にバックアップし、すべてのバックエンドノードで同じキーを使用してください。認証情報が保存済みの場合は、新しいキーを生成せず、元のキーを復元してください。",
|
||||
"Select at most 500 estimate mappings.": "推定マッピングは500件以下で選択してください。",
|
||||
"Select each upstream model and group only once.": "上流モデルとグループの組み合わせは1回だけ選択してください。",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "UTF-8の上限内で空でない正確なモデル名とグループ名を使用し、前後の空白や制御文字を含めないでください。",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Привязать каналы группы {{group}}",
|
||||
"Channels in local group {{group}}": "Каналы локальной группы {{group}}",
|
||||
"How to configure the encryption key": "Как настроить ключ шифрования",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "При первоначальной настройке сгенерируйте на сервере случайный 32-байтовый ключ в кодировке Base64:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "В docker-compose.yml или docker-compose.dev.yml найдите раздел environment сервиса new-api. Раскомментируйте UPSTREAM_MONITOR_KEY и замените значение-заглушку сгенерированным ключом:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Пересоздайте контейнер бэкенда, чтобы применить переменную окружения; перезапуск существующего контейнера не загружает изменения:",
|
||||
"For docker-compose.dev.yml, use:": "Для docker-compose.dev.yml используйте:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Замените new-api в этих командах, если сервис бэкенда называется иначе. Обновите эту страницу после запуска бэкенда.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "При запуске исполняемого файла напрямую задайте UPSTREAM_MONITOR_KEY в окружении бэкенда или в файле .env в его рабочем каталоге, затем перезапустите бэкенд.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Храните резервную копию ключа отдельно от базы данных и используйте один и тот же ключ на всех узлах бэкенда. Если учётные данные уже сохранены, восстановите исходный ключ вместо создания нового.",
|
||||
"Select at most 500 estimate mappings.": "Выберите не более 500 сопоставлений для оценки.",
|
||||
"Select each upstream model and group only once.": "Каждую пару модели и группы поставщика выбирайте только один раз.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Используйте точные непустые имена моделей и групп в пределах UTF-8, без пробелов по краям и управляющих символов.",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "Liên kết các kênh trong {{group}}",
|
||||
"Channels in local group {{group}}": "Các kênh thuộc nhóm cục bộ {{group}}",
|
||||
"How to configure the encryption key": "Cách cấu hình khóa mã hóa",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "Khi thiết lập lần đầu, hãy tạo khóa ngẫu nhiên 32 byte được mã hóa Base64 trên máy chủ:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "Trong docker-compose.yml hoặc docker-compose.dev.yml, tìm mục environment của dịch vụ new-api. Bỏ dấu chú thích của UPSTREAM_MONITOR_KEY và thay giá trị giữ chỗ bằng khóa vừa tạo:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "Tạo lại container backend để áp dụng biến môi trường; khởi động lại container hiện có sẽ không nạp các thay đổi:",
|
||||
"For docker-compose.dev.yml, use:": "Với docker-compose.dev.yml, dùng:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "Thay new-api trong các lệnh này nếu dịch vụ backend của bạn có tên khác. Làm mới trang này sau khi backend khởi động.",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "Khi triển khai bằng cách chạy trực tiếp tệp thực thi, hãy đặt UPSTREAM_MONITOR_KEY trong môi trường backend hoặc tệp .env ở thư mục làm việc của backend, rồi khởi động lại backend.",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "Sao lưu khóa riêng biệt với cơ sở dữ liệu và dùng cùng một khóa trên mọi nút backend. Nếu đã lưu thông tin xác thực, hãy khôi phục khóa gốc thay vì tạo khóa thay thế.",
|
||||
"Select at most 500 estimate mappings.": "Chọn tối đa 500 ánh xạ ước tính.",
|
||||
"Select each upstream model and group only once.": "Chỉ chọn mỗi cặp mô hình và nhóm thượng nguồn một lần.",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "Dùng tên mô hình và nhóm chính xác, không rỗng, trong giới hạn UTF-8, không có khoảng trắng đầu cuối hoặc ký tự điều khiển.",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "綁定 {{group}} 下的渠道",
|
||||
"Channels in local group {{group}}": "本站群組:{{group}}",
|
||||
"How to configure the encryption key": "如何設定加密金鑰",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "首次設定時,請在伺服器上產生一個以 Base64 編碼的 32 位元組隨機金鑰:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "在 docker-compose.yml 或 docker-compose.dev.yml 中找到 new-api 服務的 environment 設定區段。取消 UPSTREAM_MONITOR_KEY 的註解,並將預留值替換為產生的金鑰:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "請重新建立後端容器以套用環境變數;重新啟動現有容器不會載入這些變更:",
|
||||
"For docker-compose.dev.yml, use:": "使用 docker-compose.dev.yml 時,請執行:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "若後端服務名稱不同,請替換這些命令中的 new-api。後端啟動後,請重新整理此頁面。",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "直接執行可執行檔部署時,請在後端環境變數或其工作目錄中的 .env 檔案內設定 UPSTREAM_MONITOR_KEY,然後重新啟動後端。",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "請將金鑰與資料庫分開備份,並在所有後端節點上使用相同金鑰。若已儲存憑證,請還原原本金鑰,勿產生新金鑰取代。",
|
||||
"Select at most 500 estimate mappings.": "最多選擇 500 條估算對應。",
|
||||
"Select each upstream model and group only once.": "每個上游模型和群組組合只能選擇一次。",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "請使用非空且符合 UTF-8 位元組限制的精確模型名和群組名,不得包含首尾空格或控制字元。",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"translation": {
|
||||
"Bind channels in {{group}}": "绑定 {{group}} 下的渠道",
|
||||
"Channels in local group {{group}}": "本站分组:{{group}}",
|
||||
"How to configure the encryption key": "如何配置加密密钥",
|
||||
"For first-time setup, generate a random 32-byte Base64 key on the server:": "首次配置时,请在服务器上生成一个以 Base64 编码的 32 字节随机密钥:",
|
||||
"In docker-compose.yml or docker-compose.dev.yml, find the new-api service environment section. Uncomment UPSTREAM_MONITOR_KEY and replace the placeholder with the generated key:": "在 docker-compose.yml 或 docker-compose.dev.yml 中找到 new-api 服务的 environment 配置段。取消 UPSTREAM_MONITOR_KEY 的注释,并将占位值替换为生成的密钥:",
|
||||
"Recreate the backend container to apply the environment variable; restarting the existing container does not load changes:": "请重新创建后端容器以应用环境变量;重启现有容器不会加载这些更改:",
|
||||
"For docker-compose.dev.yml, use:": "使用 docker-compose.dev.yml 时,请执行:",
|
||||
"Replace new-api in these commands if your backend service has a different name. Refresh this page after the backend starts.": "若后端服务名称不同,请替换这些命令中的 new-api。后端启动后,请刷新此页面。",
|
||||
"For a direct executable deployment, set UPSTREAM_MONITOR_KEY in the backend environment or in .env in its working directory, then restart the backend.": "直接运行可执行文件部署时,请在后端环境变量或其工作目录中的 .env 文件内设置 UPSTREAM_MONITOR_KEY,然后重启后端。",
|
||||
"Keep the key backed up separately from the database and use the same key on every backend node. If credentials are already saved, restore the original key instead of generating a replacement.": "请将密钥与数据库分开备份,并在所有后端节点上使用同一密钥。若已保存凭据,请恢复原密钥,不要生成新密钥替换。",
|
||||
"Select at most 500 estimate mappings.": "最多选择 500 条估算映射。",
|
||||
"Select each upstream model and group only once.": "每个上游模型和分组组合只能选择一次。",
|
||||
"Use exact non-empty model and group names within the supported UTF-8 limits, without surrounding spaces or control characters.": "请使用非空且符合 UTF-8 字节限制的精确模型名和分组名,不得包含首尾空格或控制字符。",
|
||||
|
||||
Reference in new issue
Block a user