- {filteredModels.length === 0 ? (
+ {filteredModels.length === 0 && removedModels.length === 0 ? (
@@ -369,6 +406,14 @@ const ModelSelectModal = ({
{renderModelsByCategory(existingModelsByCategory, 'existing')}
)}
+ {activeTab === 'removed' && removedModels.length > 0 && (
+
+ {renderModelsByCategory(
+ categorizeModels(removedModels),
+ 'removed',
+ )}
+
+ )}
)}
@@ -382,7 +427,11 @@ const ModelSelectModal = ({
{(() => {
const currentModels =
- activeTab === 'new' ? newModels : existingModels;
+ activeTab === 'new'
+ ? newModels
+ : activeTab === 'removed'
+ ? removedModels
+ : existingModels;
const currentSelected = currentModels.filter((model) =>
checkedList.includes(model),
).length;
diff --git a/web/classic/src/components/table/model-pricing/modal/components/DynamicPricingBreakdown.jsx b/web/classic/src/components/table/model-pricing/modal/components/DynamicPricingBreakdown.jsx
index fd2be3f35f..23d1712a1b 100644
--- a/web/classic/src/components/table/model-pricing/modal/components/DynamicPricingBreakdown.jsx
+++ b/web/classic/src/components/table/model-pricing/modal/components/DynamicPricingBreakdown.jsx
@@ -20,8 +20,8 @@ For commercial licensing, please contact support@quantumnous.com
import React from 'react';
import { Avatar, Tag, Table, Typography } from '@douyinfe/semi-ui';
import { IconPriceTag } from '@douyinfe/semi-icons';
-import { parseTiersFromExpr } from '../../../../../helpers';
-import { BILLING_VARS } from '../../../../../constants';
+import { parseTiersFromExpr, getCurrencyConfig } from '../../../../../helpers';
+import { BILLING_PRICING_VARS } from '../../../../../constants';
import {
splitBillingExprAndRequestRules,
tryParseRequestRuleExpr,
@@ -36,8 +36,6 @@ import {
const { Text } = Typography;
-const PRICE_SUFFIX = '$/1M tokens';
-
const VAR_LABELS = { p: '输入', c: '输出' };
const OP_LABELS = { '<': '<', '<=': '≤', '>': '>', '>=': '≥' };
const TIME_FUNC_LABELS = { hour: '小时', minute: '分钟', weekday: '星期', month: '月份', day: '日期' };
@@ -89,6 +87,7 @@ function describeGroup(group, t) {
}
export default function DynamicPricingBreakdown({ billingExpr, t }) {
+ const { symbol, rate } = getCurrencyConfig();
const { billingExpr: baseExpr, requestRuleExpr: ruleExpr } =
splitBillingExprAndRequestRules(billingExpr || '');
@@ -114,7 +113,7 @@ export default function DynamicPricingBreakdown({ billingExpr, t }) {
);
}
- const priceFields = BILLING_VARS.map((v) => [v.field, v.shortLabel]);
+ const priceFields = BILLING_PRICING_VARS.map((v) => [v.field, v.shortLabel]);
const tierColumns = [
{
@@ -132,9 +131,9 @@ export default function DynamicPricingBreakdown({ billingExpr, t }) {
...priceFields
.filter(([field]) => hasTiers && tiers.some((tier) => tier[field] > 0))
.map(([field, label]) => ({
- title: `${t(label)} (${PRICE_SUFFIX})`,
+ title: `${t(label)} (${symbol}/1M tokens)`,
dataIndex: field,
- render: (v) => v > 0 ? ${v.toFixed(4)} : '-',
+ render: (v) => v > 0 ? {`${symbol}${(v * rate).toFixed(4)}`} : '-',
})),
];
diff --git a/web/classic/src/components/table/users/UsersColumnDefs.jsx b/web/classic/src/components/table/users/UsersColumnDefs.jsx
index dc3e6f3413..2e0d171ae4 100644
--- a/web/classic/src/components/table/users/UsersColumnDefs.jsx
+++ b/web/classic/src/components/table/users/UsersColumnDefs.jsx
@@ -29,7 +29,14 @@ import {
Dropdown,
} from '@douyinfe/semi-ui';
import { IconMore } from '@douyinfe/semi-icons';
-import { renderGroup, renderNumber, renderQuota } from '../../../helpers';
+import {
+ renderGroup,
+ renderNumber,
+ renderQuota,
+ timestamp2string,
+} from '../../../helpers';
+
+const renderTimestamp = (text) => (text ? timestamp2string(text) : '-');
/**
* Render user role
@@ -350,6 +357,16 @@ export const getUsersColumns = ({
dataIndex: 'invite',
render: (text, record, index) => renderInviteInfo(text, record, t),
},
+ {
+ title: t('创建时间'),
+ dataIndex: 'created_at',
+ render: renderTimestamp,
+ },
+ {
+ title: t('最后登录'),
+ dataIndex: 'last_login_at',
+ render: renderTimestamp,
+ },
{
title: '',
dataIndex: 'operate',
diff --git a/web/classic/src/constants/billing.constants.js b/web/classic/src/constants/billing.constants.js
index 79ef32866d..28114808bd 100644
--- a/web/classic/src/constants/billing.constants.js
+++ b/web/classic/src/constants/billing.constants.js
@@ -13,6 +13,7 @@
export const BILLING_VARS = [
{ key: 'p', field: 'inputPrice', tierField: 'input_unit_cost', label: '输入价格', shortLabel: '输入', side: 'input', isBase: true },
{ key: 'c', field: 'outputPrice', tierField: 'output_unit_cost', label: '补全价格', shortLabel: '补全', side: 'output', isBase: true },
+ { key: 'len', field: null, tierField: null, label: '输入长度', shortLabel: '长度', side: 'condition', isConditionOnly: true },
{ key: 'cr', field: 'cacheReadPrice', tierField: 'cache_read_unit_cost', label: '缓存读取价格', shortLabel: '缓存读', side: 'input', group: 'cache' },
{ key: 'cc', field: 'cacheCreatePrice', tierField: 'cache_create_unit_cost', label: '缓存创建价格', shortLabel: '缓存创建', side: 'input', group: 'cache' },
{ key: 'cc1h', field: 'cacheCreate1hPrice', tierField: 'cache_create_1h_unit_cost', label: '1h缓存创建价格', shortLabel: '1h缓存创建', side: 'input', group: 'cache' },
@@ -24,18 +25,20 @@ export const BILLING_VARS = [
export const BILLING_VAR_KEYS = BILLING_VARS.map((v) => v.key);
-export const BILLING_EXTRA_VARS = BILLING_VARS.filter((v) => !v.isBase);
+export const BILLING_PRICING_VARS = BILLING_VARS.filter((v) => !v.isConditionOnly);
+
+export const BILLING_EXTRA_VARS = BILLING_VARS.filter((v) => !v.isBase && !v.isConditionOnly);
export const BILLING_VAR_KEY_TO_FIELD = Object.fromEntries(
- BILLING_VARS.map((v) => [v.key, v.field]),
+ BILLING_PRICING_VARS.map((v) => [v.key, v.field]),
);
export const BILLING_VAR_FIELD_TO_LABEL = Object.fromEntries(
- BILLING_VARS.map((v) => [v.field, v.label]),
+ BILLING_PRICING_VARS.map((v) => [v.field, v.label]),
);
export const BILLING_VAR_FIELD_TO_SHORT_LABEL = Object.fromEntries(
- BILLING_VARS.map((v) => [v.field, v.shortLabel]),
+ BILLING_PRICING_VARS.map((v) => [v.field, v.shortLabel]),
);
export const BILLING_CACHE_VAR_MAP = BILLING_EXTRA_VARS.map((v) => ({
@@ -44,6 +47,10 @@ export const BILLING_CACHE_VAR_MAP = BILLING_EXTRA_VARS.map((v) => ({
}));
export const BILLING_VAR_REGEX = new RegExp(
- `\\b(${BILLING_VAR_KEYS.join('|')})\\s*\\*\\s*([\\d.eE+-]+)`,
+ `\\b(${BILLING_PRICING_VARS.map((v) => v.key).join('|')})\\s*\\*\\s*([\\d.eE+-]+)`,
'g',
);
+
+export const BILLING_CONDITION_VARS = BILLING_VARS.filter(
+ (v) => v.isBase || v.isConditionOnly,
+).map((v) => v.key);
diff --git a/web/classic/src/constants/common.constant.js b/web/classic/src/constants/common.constant.js
index 8737f7299e..316356631d 100644
--- a/web/classic/src/constants/common.constant.js
+++ b/web/classic/src/constants/common.constant.js
@@ -19,7 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
export const ITEMS_PER_PAGE = 10; // this value must keep same as the one defined in backend!
-export const DEFAULT_ENDPOINT = '/api/ratio_config';
+export const DEFAULT_ENDPOINT = '/api/pricing';
export const TABLE_COMPACT_MODES_KEY = 'table_compact_modes';
diff --git a/web/classic/src/helpers/render.jsx b/web/classic/src/helpers/render.jsx
index d7ba654648..f5ce1f0391 100644
--- a/web/classic/src/helpers/render.jsx
+++ b/web/classic/src/helpers/render.jsx
@@ -22,7 +22,7 @@ import { Modal, Tag, Typography, Avatar } from '@douyinfe/semi-ui';
import { copy, showSuccess } from './utils';
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
import {
- BILLING_VARS,
+ BILLING_PRICING_VARS,
BILLING_VAR_KEY_TO_FIELD,
BILLING_VAR_REGEX,
} from '../constants';
@@ -2246,7 +2246,7 @@ export function parseTiersFromExpr(exprStr) {
if (!exprStr) return [];
try {
const { body } = stripExprVersion(exprStr);
- const condGroup = `((?:(?:p|c)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)(?:\\s*&&\\s*(?:p|c)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)*)`;
+ const condGroup = `((?:(?:p|c|len)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)(?:\\s*&&\\s*(?:p|c|len)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)*)`;
const tierRe = new RegExp(`(?:${condGroup}\\s*\\?\\s*)?tier\\("([^"]*)",\\s*([^)]+)\\)`, 'g');
const tiers = [];
let m;
@@ -2255,7 +2255,7 @@ export function parseTiersFromExpr(exprStr) {
const conditions = [];
if (condStr) {
for (const cp of condStr.split(/\s*&&\s*/)) {
- const cm = cp.trim().match(/^(p|c)\s*(<|<=|>|>=)\s*([\d.eE+]+)$/);
+ const cm = cp.trim().match(/^(p|c|len)\s*(<|<=|>|>=)\s*([\d.eE+]+)$/);
if (cm) conditions.push({ var: cm[1], op: cm[2], value: Number(cm[3]) });
}
}
@@ -2293,7 +2293,7 @@ export function renderTieredModelPrice(opts) {
const { symbol, rate } = getCurrencyConfig();
const gr = groupRatio || 1;
- const priceLines = BILLING_VARS.map((v) => [v.field, v.label]);
+ const priceLines = BILLING_PRICING_VARS.map((v) => [v.field, v.label]);
const lines = [
buildBillingText('命中档位:{{tier}}', { tier: matchedTier || tier.label }),
@@ -2334,7 +2334,7 @@ export function renderTieredModelPriceSimple(opts) {
];
if (tier && isPriceDisplayMode(displayMode)) {
- const priceSegments = BILLING_VARS.map((v) => [v.field, v.shortLabel]);
+ const priceSegments = BILLING_PRICING_VARS.map((v) => [v.field, v.shortLabel]);
for (const [field, label] of priceSegments) {
if (tier[field] > 0) {
segments.push({
diff --git a/web/classic/src/helpers/utils.jsx b/web/classic/src/helpers/utils.jsx
index f73df714b0..7c7e63c737 100644
--- a/web/classic/src/helpers/utils.jsx
+++ b/web/classic/src/helpers/utils.jsx
@@ -18,7 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import { Toast, Pagination } from '@douyinfe/semi-ui';
-import { toastConstants, BILLING_VARS, BILLING_VAR_REGEX } from '../constants';
+import { toastConstants, BILLING_PRICING_VARS, BILLING_VAR_REGEX } from '../constants';
import React from 'react';
import { toast } from 'react-toastify';
import {
@@ -900,6 +900,20 @@ export const getModelPriceItems = (
export const formatDynamicPriceSummary = (billingExpr, t, groupRatio = 1) => {
if (!billingExpr) return {t('动态计费')};
+ const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
+ let symbol = '$';
+ let rate = 1;
+ try {
+ const s = JSON.parse(localStorage.getItem('status') || '{}');
+ if (quotaDisplayType === 'CNY') {
+ symbol = '¥';
+ rate = s?.usd_exchange_rate || 7;
+ } else if (quotaDisplayType === 'CUSTOM') {
+ symbol = s?.custom_currency_symbol || '¤';
+ rate = s?.custom_currency_exchange_rate || 1;
+ }
+ } catch (e) {}
+
const gr = groupRatio || 1;
const exprBody = billingExpr.replace(/^v\d+:/, '');
const tierMatches = exprBody.match(/tier\(/g) || [];
@@ -913,7 +927,7 @@ export const formatDynamicPriceSummary = (billingExpr, t, groupRatio = 1) => {
}
const hasCoeffs = 'p' in varCoeffs || 'c' in varCoeffs;
- const varLabels = BILLING_VARS.map((v) => [v.key, v.label]);
+ const varLabels = BILLING_PRICING_VARS.map((v) => [v.key, v.label]);
const hasTimeCondition = /\b(?:hour|minute|weekday|month|day)\(/.test(exprBody);
const hasRequestCondition = /\b(?:param|header)\(/.test(exprBody);
@@ -933,7 +947,7 @@ export const formatDynamicPriceSummary = (billingExpr, t, groupRatio = 1) => {
{varLabels.map(([key, label]) =>
key in varCoeffs ? (
- {t(label)} ${(varCoeffs[key] * gr).toFixed(4)}{unitSuffix}
+ {`${t(label)} ${symbol}${(varCoeffs[key] * gr * rate).toFixed(4)}${unitSuffix}`}
) : null,
)}
diff --git a/web/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx b/web/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx
index 20ea45e9eb..20b0bdf318 100644
--- a/web/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx
+++ b/web/classic/src/pages/Setting/Ratio/UpstreamRatioSync.jsx
@@ -29,17 +29,14 @@ import {
Tooltip,
Select,
Modal,
+ Spin,
} from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
-import {
- RefreshCcw,
- CheckSquare,
- AlertTriangle,
- CheckCircle,
-} from 'lucide-react';
+import { RefreshCcw, CheckSquare, AlertTriangle } from 'lucide-react';
import {
API,
showError,
+ showInfo,
showSuccess,
showWarning,
stringToColor,
@@ -63,7 +60,7 @@ const MODELS_DEV_PRESET_NAME = 'models.dev 价格预设';
const MODELS_DEV_PRESET_BASE_URL = 'https://models.dev';
const MODELS_DEV_PRESET_ENDPOINT = 'https://models.dev/api.json';
-function ConflictConfirmModal({ t, visible, items, onOk, onCancel }) {
+function ConflictConfirmModal({ t, visible, items, loading, onOk, onCancel }) {
const isMobile = useIsMobile();
const columns = [
{ title: t('渠道'), dataIndex: 'channel' },
@@ -84,7 +81,10 @@ function ConflictConfirmModal({ t, visible, items, onOk, onCancel }) {
@@ -103,6 +103,7 @@ export default function UpstreamRatioSync(props) {
const [modalVisible, setModalVisible] = useState(false);
const [loading, setLoading] = useState(false);
const [syncLoading, setSyncLoading] = useState(false);
+ const [confirmLoading, setConfirmLoading] = useState(false);
const isMobile = useIsMobile();
// 渠道选择相关
@@ -251,7 +252,7 @@ export default function UpstreamRatioSync(props) {
setHasSynced(true);
if (Object.keys(differences).length === 0) {
- showSuccess(t('未找到差异化倍率,无需同步'));
+ showSuccess(t('未找到差异化价格,无需同步'));
}
} catch (e) {
showError(t('请求后端接口失败:') + e.message);
@@ -260,32 +261,165 @@ export default function UpstreamRatioSync(props) {
}
};
+ const ratioSyncFields = [
+ 'model_ratio',
+ 'completion_ratio',
+ 'cache_ratio',
+ 'create_cache_ratio',
+ 'image_ratio',
+ 'audio_ratio',
+ 'audio_completion_ratio',
+ ];
+
+ const numericSyncFields = new Set([...ratioSyncFields, 'model_price']);
+ const syncFieldOrder = [
+ ...ratioSyncFields,
+ 'model_price',
+ 'billing_mode',
+ 'billing_expr',
+ ];
+
+ function getSyncFieldLabel(ratioType) {
+ const typeMap = {
+ model_ratio: t('模型倍率'),
+ completion_ratio: t('补全倍率'),
+ cache_ratio: t('缓存倍率'),
+ create_cache_ratio: t('缓存创建倍率'),
+ image_ratio: t('图片倍率'),
+ audio_ratio: t('音频倍率'),
+ audio_completion_ratio: t('音频补全倍率'),
+ model_price: t('固定价格'),
+ billing_mode: t('计费模式'),
+ billing_expr: t('表达式计费'),
+ };
+ return typeMap[ratioType] || ratioType;
+ }
+
+ function getOrderedRatioTypes(ratioTypes) {
+ const keys = Object.keys(ratioTypes || {});
+ const ordered = [
+ ...syncFieldOrder.filter((field) => keys.includes(field)),
+ ...keys.filter((field) => !syncFieldOrder.includes(field)),
+ ];
+ return ratioTypeFilter
+ ? ordered.filter((field) => field === ratioTypeFilter)
+ : ordered;
+ }
+
+ function deleteResolutionField(newRes, model, ratioType) {
+ if (!newRes[model]) return;
+ delete newRes[model][ratioType];
+ if (ratioType === 'billing_expr') {
+ delete newRes[model].billing_mode;
+ }
+ if (ratioType === 'billing_mode') {
+ delete newRes[model].billing_expr;
+ }
+ if (Object.keys(newRes[model]).length === 0) {
+ delete newRes[model];
+ }
+ }
+
function getBillingCategory(ratioType) {
- return ratioType === 'model_price' ? 'price' : 'ratio';
+ if (ratioType === 'model_price') return 'price';
+ if (ratioType === 'billing_mode' || ratioType === 'billing_expr') {
+ return 'tiered';
+ }
+ return 'ratio';
+ }
+
+ function optionKeyBySyncField(ratioType) {
+ const explicit = {
+ billing_mode: 'billing_setting.billing_mode',
+ billing_expr: 'billing_setting.billing_expr',
+ };
+ if (explicit[ratioType]) return explicit[ratioType];
+ return ratioType
+ .split('_')
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join('');
+ }
+
+ function getUpstreamValue(model, ratioType, sourceName) {
+ return differences[model]?.[ratioType]?.upstreams?.[sourceName];
+ }
+
+ function isSelectableUpstreamValue(value) {
+ return value !== null && value !== undefined && value !== 'same';
+ }
+
+ function getPreferredSyncField(model, ratioType, sourceName) {
+ const exprValue = getUpstreamValue(model, 'billing_expr', sourceName);
+ if (ratioType !== 'billing_expr' && isSelectableUpstreamValue(exprValue)) {
+ return 'billing_expr';
+ }
+ return ratioType;
+ }
+
+ function shouldShowSyncField(model, ratioType, sourceName) {
+ if (!sourceName) return true;
+ return getPreferredSyncField(model, ratioType, sourceName) === ratioType;
}
const selectValue = useCallback(
- (model, ratioType, value) => {
+ (model, ratioType, value, sourceName) => {
+ const preferredRatioType = sourceName
+ ? getPreferredSyncField(model, ratioType, sourceName)
+ : ratioType;
+ const preferredValue =
+ preferredRatioType === ratioType
+ ? value
+ : getUpstreamValue(model, preferredRatioType, sourceName);
+ ratioType = preferredRatioType;
+ value = preferredValue;
+
const category = getBillingCategory(ratioType);
setResolutions((prev) => {
const newModelRes = { ...(prev[model] || {}) };
Object.keys(newModelRes).forEach((rt) => {
- if (getBillingCategory(rt) !== category) {
+ if (
+ category !== 'tiered' &&
+ getBillingCategory(rt) !== 'tiered' &&
+ getBillingCategory(rt) !== category
+ ) {
delete newModelRes[rt];
}
});
newModelRes[ratioType] = value;
+ if (category === 'tiered' && sourceName) {
+ const modeValue =
+ differences[model]?.billing_mode?.upstreams?.[sourceName];
+ const exprValue =
+ differences[model]?.billing_expr?.upstreams?.[sourceName];
+ if (
+ modeValue !== undefined &&
+ modeValue !== null &&
+ modeValue !== 'same'
+ ) {
+ newModelRes.billing_mode = modeValue;
+ } else if (ratioType === 'billing_expr') {
+ newModelRes.billing_mode = 'tiered_expr';
+ }
+ if (
+ exprValue !== undefined &&
+ exprValue !== null &&
+ exprValue !== 'same'
+ ) {
+ newModelRes.billing_expr = exprValue;
+ }
+ }
+
return {
...prev,
[model]: newModelRes,
};
});
},
- [setResolutions],
+ [setResolutions, differences],
);
const applySync = async () => {
@@ -293,7 +427,19 @@ export default function UpstreamRatioSync(props) {
ModelRatio: JSON.parse(props.options.ModelRatio || '{}'),
CompletionRatio: JSON.parse(props.options.CompletionRatio || '{}'),
CacheRatio: JSON.parse(props.options.CacheRatio || '{}'),
+ CreateCacheRatio: JSON.parse(props.options.CreateCacheRatio || '{}'),
+ ImageRatio: JSON.parse(props.options.ImageRatio || '{}'),
+ AudioRatio: JSON.parse(props.options.AudioRatio || '{}'),
+ AudioCompletionRatio: JSON.parse(
+ props.options.AudioCompletionRatio || '{}',
+ ),
ModelPrice: JSON.parse(props.options.ModelPrice || '{}'),
+ 'billing_setting.billing_mode': JSON.parse(
+ props.options['billing_setting.billing_mode'] || '{}',
+ ),
+ 'billing_setting.billing_expr': JSON.parse(
+ props.options['billing_setting.billing_expr'] || '{}',
+ ),
};
const conflicts = [];
@@ -303,7 +449,11 @@ export default function UpstreamRatioSync(props) {
if (
currentRatios.ModelRatio[model] !== undefined ||
currentRatios.CompletionRatio[model] !== undefined ||
- currentRatios.CacheRatio[model] !== undefined
+ currentRatios.CacheRatio[model] !== undefined ||
+ currentRatios.CreateCacheRatio[model] !== undefined ||
+ currentRatios.ImageRatio[model] !== undefined ||
+ currentRatios.AudioRatio[model] !== undefined ||
+ currentRatios.AudioCompletionRatio[model] !== undefined
)
return 'ratio';
return null;
@@ -320,9 +470,14 @@ export default function UpstreamRatioSync(props) {
Object.entries(resolutions).forEach(([model, ratios]) => {
const localCat = getLocalBillingCategory(model);
- const newCat = 'model_price' in ratios ? 'price' : 'ratio';
+ const newCat =
+ 'model_price' in ratios
+ ? 'price'
+ : ratioSyncFields.some((rt) => rt in ratios)
+ ? 'ratio'
+ : 'tiered';
- if (localCat && localCat !== newCat) {
+ if (localCat && newCat !== 'tiered' && localCat !== newCat) {
const currentDesc =
localCat === 'price'
? `${t('固定价格')} : ${currentRatios.ModelPrice[model]}`
@@ -366,33 +521,50 @@ export default function UpstreamRatioSync(props) {
ModelRatio: { ...currentRatios.ModelRatio },
CompletionRatio: { ...currentRatios.CompletionRatio },
CacheRatio: { ...currentRatios.CacheRatio },
+ CreateCacheRatio: { ...currentRatios.CreateCacheRatio },
+ ImageRatio: { ...currentRatios.ImageRatio },
+ AudioRatio: { ...currentRatios.AudioRatio },
+ AudioCompletionRatio: { ...currentRatios.AudioCompletionRatio },
ModelPrice: { ...currentRatios.ModelPrice },
+ 'billing_setting.billing_mode': {
+ ...currentRatios['billing_setting.billing_mode'],
+ },
+ 'billing_setting.billing_expr': {
+ ...currentRatios['billing_setting.billing_expr'],
+ },
};
Object.entries(resolutions).forEach(([model, ratios]) => {
const selectedTypes = Object.keys(ratios);
const hasPrice = selectedTypes.includes('model_price');
- const hasRatio = selectedTypes.some((rt) => rt !== 'model_price');
+ const hasRatio = selectedTypes.some((rt) =>
+ ratioSyncFields.includes(rt),
+ );
if (hasPrice) {
delete finalRatios.ModelRatio[model];
delete finalRatios.CompletionRatio[model];
delete finalRatios.CacheRatio[model];
+ delete finalRatios.CreateCacheRatio[model];
+ delete finalRatios.ImageRatio[model];
+ delete finalRatios.AudioRatio[model];
+ delete finalRatios.AudioCompletionRatio[model];
}
if (hasRatio) {
delete finalRatios.ModelPrice[model];
}
Object.entries(ratios).forEach(([ratioType, value]) => {
- const optionKey = ratioType
- .split('_')
- .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
- .join('');
- finalRatios[optionKey][model] = parseFloat(value);
+ const optionKey = optionKeyBySyncField(ratioType);
+ finalRatios[optionKey][model] = numericSyncFields.has(ratioType)
+ ? parseFloat(value)
+ : value;
});
});
setLoading(true);
+ showInfo(t('正在同步价格,请稍候'));
+ let success = false;
try {
const updates = Object.entries(finalRatios).map(([key, value]) =>
API.put('/api/option/', {
@@ -426,6 +598,7 @@ export default function UpstreamRatioSync(props) {
});
setResolutions({});
+ success = true;
} else {
showError(t('部分保存失败'));
}
@@ -434,6 +607,7 @@ export default function UpstreamRatioSync(props) {
} finally {
setLoading(false);
}
+ return success;
},
[resolutions, props.options, props.refresh],
);
@@ -451,6 +625,7 @@ export default function UpstreamRatioSync(props) {
}
className='w-full md:w-auto mt-2'
+ disabled={loading || syncLoading || confirmLoading}
onClick={() => {
setModalVisible(true);
if (allChannels.length === 0) {
@@ -469,7 +644,10 @@ export default function UpstreamRatioSync(props) {
icon={}
type='secondary'
onClick={applySync}
- disabled={!hasSelections}
+ loading={loading || confirmLoading}
+ disabled={
+ !hasSelections || loading || syncLoading || confirmLoading
+ }
className='w-full md:w-auto mt-2'
>
{t('应用同步')}
@@ -484,14 +662,16 @@ export default function UpstreamRatioSync(props) {
value={searchKeyword}
onChange={setSearchKeyword}
className='w-full sm:w-64'
+ disabled={loading || syncLoading || confirmLoading}
showClear
/>
@@ -510,31 +701,17 @@ export default function UpstreamRatioSync(props) {
const renderDifferenceTable = () => {
const dataSource = useMemo(() => {
- const tmp = [];
-
- Object.entries(differences).forEach(([model, ratioTypes]) => {
+ return Object.entries(differences).map(([model, ratioTypes]) => {
const hasPrice = 'model_price' in ratioTypes;
- const hasOtherRatio = [
- 'model_ratio',
- 'completion_ratio',
- 'cache_ratio',
- ].some((rt) => rt in ratioTypes);
- const billingConflict = hasPrice && hasOtherRatio;
+ const hasOtherRatio = ratioSyncFields.some((rt) => rt in ratioTypes);
- Object.entries(ratioTypes).forEach(([ratioType, diff]) => {
- tmp.push({
- key: `${model}_${ratioType}`,
- model,
- ratioType,
- current: diff.current,
- upstreams: diff.upstreams,
- confidence: diff.confidence || {},
- billingConflict,
- });
- });
+ return {
+ key: model,
+ model,
+ ratioTypes,
+ billingConflict: hasPrice && hasOtherRatio,
+ };
});
-
- return tmp;
}, [differences]);
const filteredDataSource = useMemo(() => {
@@ -548,7 +725,7 @@ export default function UpstreamRatioSync(props) {
item.model.toLowerCase().includes(searchKeyword.toLowerCase().trim());
const matchesRatioType =
- !ratioTypeFilter || item.ratioType === ratioTypeFilter;
+ !ratioTypeFilter || ratioTypeFilter in item.ratioTypes;
return matchesKeyword && matchesRatioType;
});
@@ -557,12 +734,162 @@ export default function UpstreamRatioSync(props) {
const upstreamNames = useMemo(() => {
const set = new Set();
filteredDataSource.forEach((row) => {
- Object.keys(row.upstreams || {}).forEach((name) => set.add(name));
+ getOrderedRatioTypes(row.ratioTypes).forEach((ratioType) => {
+ Object.keys(row.ratioTypes[ratioType]?.upstreams || {}).forEach(
+ (name) => set.add(name),
+ );
+ });
});
return Array.from(set);
- }, [filteredDataSource]);
+ }, [filteredDataSource, ratioTypeFilter]);
+
+ const renderValueTag = (value, color = 'default') => {
+ if (value === null || value === undefined) {
+ return (
+
+ {t('未设置')}
+
+ );
+ }
+
+ const text = String(value);
+ return (
+
+
+
+ {text}
+
+
+
+ );
+ };
+
+ const renderCurrentFields = (record) => {
+ const fields = getOrderedRatioTypes(record.ratioTypes);
+ return (
+
+ {fields.map((ratioType) => (
+
+
+ {getSyncFieldLabel(ratioType)}
+
+ {renderValueTag(record.ratioTypes[ratioType]?.current, 'blue')}
+
+ ))}
+
+ );
+ };
+
+ const renderUpstreamField = (record, ratioType, upName) => {
+ const diff = record.ratioTypes[ratioType] || {};
+ const upstreamVal = diff.upstreams?.[upName];
+ const isConfident = diff.confidence?.[upName] !== false;
+ const isPreferredField =
+ getPreferredSyncField(record.model, ratioType, upName) === ratioType;
+
+ if (upstreamVal === null || upstreamVal === undefined) {
+ return renderValueTag(undefined);
+ }
+
+ if (upstreamVal === 'same') {
+ return (
+
+ {t('与本地相同')}
+
+ );
+ }
+
+ const text = String(upstreamVal);
+ const isSelected =
+ isPreferredField &&
+ resolutions[record.model]?.[ratioType] === upstreamVal;
+ const valueNode = isPreferredField ? (
+ {
+ const isChecked = e.target.checked;
+ if (isChecked) {
+ selectValue(record.model, ratioType, upstreamVal, upName);
+ } else {
+ setResolutions((prev) => {
+ const newRes = { ...prev };
+ deleteResolutionField(newRes, record.model, ratioType);
+ return newRes;
+ });
+ }
+ }}
+ >
+
+
+ {text}
+
+
+
+ ) : (
+
+
+
+ {text}
+
+
+
+ );
+
+ return (
+
+ {valueNode}
+ {!isConfident && (
+
+
+
+ )}
+
+ );
+ };
+
+ const renderUpstreamFields = (record, upName) => {
+ const fields = getOrderedRatioTypes(record.ratioTypes).filter(
+ (ratioType) => shouldShowSyncField(record.model, ratioType, upName),
+ );
+ return (
+
+ {fields.map((ratioType) => (
+
+
+ {getSyncFieldLabel(ratioType)}
+
+
+ {renderUpstreamField(record, ratioType, upName)}
+
+
+ ))}
+
+ );
+ };
if (filteredDataSource.length === 0) {
+ if (syncLoading) {
+ return (
+
+
+
+ {t('正在同步上游价格,请稍候')}
+
+
+ );
+ }
+
return (
}
@@ -574,7 +901,7 @@ export default function UpstreamRatioSync(props) {
? t('未找到匹配的模型')
: Object.keys(differences).length === 0
? hasSynced
- ? t('暂无差异化倍率显示')
+ ? t('暂无差异化价格显示')
: t('请先选择同步渠道')
: t('请先选择同步渠道')
}
@@ -588,95 +915,24 @@ export default function UpstreamRatioSync(props) {
title: t('模型'),
dataIndex: 'model',
fixed: 'left',
- },
- {
- title: t('倍率类型'),
- dataIndex: 'ratioType',
- render: (text, record) => {
- const typeMap = {
- model_ratio: t('模型倍率'),
- completion_ratio: t('补全倍率'),
- cache_ratio: t('缓存倍率'),
- model_price: t('固定价格'),
- };
- const baseTag = (
-
- {typeMap[text] || text}
-
- );
- if (record?.billingConflict) {
- return (
-
- );
- }
- return baseTag;
- },
- },
- {
- title: t('置信度'),
- dataIndex: 'confidence',
- render: (_, record) => {
- const allConfident = Object.values(record.confidence || {}).every(
- (v) => v !== false,
- );
-
- if (allConfident) {
- return (
-
- }
- >
- {t('可信')}
-
-
- );
- } else {
- const untrustedSources = Object.entries(record.confidence || {})
- .filter(([_, isConfident]) => isConfident === false)
- .map(([name]) => name)
- .join(', ');
-
- return (
+ render: (text, record) => (
+
+
{text}
+ {record.billingConflict && (
- }
- >
- {t('谨慎')}
-
+
- );
- }
- },
+ )}
+
+ ),
},
{
- title: t('当前值'),
+ title: t('当前价格'),
dataIndex: 'current',
- render: (text) => (
-
- {text !== null && text !== undefined ? String(text) : t('未设置')}
-
- ),
+ render: (_, record) => renderCurrentFields(record),
},
...upstreamNames.map((upName) => {
const channelStats = (() => {
@@ -684,19 +940,20 @@ export default function UpstreamRatioSync(props) {
let selectedCount = 0;
filteredDataSource.forEach((row) => {
- const upstreamVal = row.upstreams?.[upName];
- if (
- upstreamVal !== null &&
- upstreamVal !== undefined &&
- upstreamVal !== 'same'
- ) {
- selectableCount++;
- const isSelected =
- resolutions[row.model]?.[row.ratioType] === upstreamVal;
- if (isSelected) {
- selectedCount++;
+ getOrderedRatioTypes(row.ratioTypes).forEach((ratioType) => {
+ const upstreamVal =
+ row.ratioTypes[ratioType]?.upstreams?.[upName];
+ if (
+ getPreferredSyncField(row.model, ratioType, upName) ===
+ ratioType &&
+ isSelectableUpstreamValue(upstreamVal)
+ ) {
+ selectableCount++;
+ if (resolutions[row.model]?.[ratioType] === upstreamVal) {
+ selectedCount++;
+ }
}
- }
+ });
});
return {
@@ -713,25 +970,29 @@ export default function UpstreamRatioSync(props) {
const handleBulkSelect = (checked) => {
if (checked) {
filteredDataSource.forEach((row) => {
- const upstreamVal = row.upstreams?.[upName];
- if (
- upstreamVal !== null &&
- upstreamVal !== undefined &&
- upstreamVal !== 'same'
- ) {
- selectValue(row.model, row.ratioType, upstreamVal);
- }
+ getOrderedRatioTypes(row.ratioTypes).forEach((ratioType) => {
+ const upstreamVal =
+ row.ratioTypes[ratioType]?.upstreams?.[upName];
+ if (
+ getPreferredSyncField(row.model, ratioType, upName) ===
+ ratioType &&
+ isSelectableUpstreamValue(upstreamVal)
+ ) {
+ selectValue(row.model, ratioType, upstreamVal, upName);
+ }
+ });
});
} else {
setResolutions((prev) => {
const newRes = { ...prev };
filteredDataSource.forEach((row) => {
- if (newRes[row.model]) {
- delete newRes[row.model][row.ratioType];
- if (Object.keys(newRes[row.model]).length === 0) {
- delete newRes[row.model];
+ getOrderedRatioTypes(row.ratioTypes).forEach((ratioType) => {
+ if (
+ row.ratioTypes[ratioType]?.upstreams?.[upName] !== undefined
+ ) {
+ deleteResolutionField(newRes, row.model, ratioType);
}
- }
+ });
});
return newRes;
});
@@ -743,6 +1004,7 @@ export default function UpstreamRatioSync(props) {
handleBulkSelect(e.target.checked)}
>
{upName}
@@ -751,64 +1013,7 @@ export default function UpstreamRatioSync(props) {
{upName}
),
dataIndex: upName,
- render: (_, record) => {
- const upstreamVal = record.upstreams?.[upName];
- const isConfident = record.confidence?.[upName] !== false;
-
- if (upstreamVal === null || upstreamVal === undefined) {
- return (
-
- {t('未设置')}
-
- );
- }
-
- if (upstreamVal === 'same') {
- return (
-
- {t('与本地相同')}
-
- );
- }
-
- const isSelected =
- resolutions[record.model]?.[record.ratioType] === upstreamVal;
-
- return (
-
-
{
- const isChecked = e.target.checked;
- if (isChecked) {
- selectValue(record.model, record.ratioType, upstreamVal);
- } else {
- setResolutions((prev) => {
- const newRes = { ...prev };
- if (newRes[record.model]) {
- delete newRes[record.model][record.ratioType];
- if (Object.keys(newRes[record.model]).length === 0) {
- delete newRes[record.model];
- }
- }
- return newRes;
- });
- }
- }}
- >
- {String(upstreamVal)}
-
- {!isConfident && (
-
-
-
- )}
-
- );
- },
+ render: (_, record) => renderUpstreamFields(record, upName),
};
}),
];
@@ -874,15 +1079,37 @@ export default function UpstreamRatioSync(props) {
t={t}
visible={confirmVisible}
items={conflictItems}
+ loading={confirmLoading}
onOk={async () => {
- setConfirmVisible(false);
+ setConfirmLoading(true);
const curRatios = {
ModelRatio: JSON.parse(props.options.ModelRatio || '{}'),
CompletionRatio: JSON.parse(props.options.CompletionRatio || '{}'),
CacheRatio: JSON.parse(props.options.CacheRatio || '{}'),
+ CreateCacheRatio: JSON.parse(
+ props.options.CreateCacheRatio || '{}',
+ ),
+ ImageRatio: JSON.parse(props.options.ImageRatio || '{}'),
+ AudioRatio: JSON.parse(props.options.AudioRatio || '{}'),
+ AudioCompletionRatio: JSON.parse(
+ props.options.AudioCompletionRatio || '{}',
+ ),
ModelPrice: JSON.parse(props.options.ModelPrice || '{}'),
+ 'billing_setting.billing_mode': JSON.parse(
+ props.options['billing_setting.billing_mode'] || '{}',
+ ),
+ 'billing_setting.billing_expr': JSON.parse(
+ props.options['billing_setting.billing_expr'] || '{}',
+ ),
};
- await performSync(curRatios);
+ try {
+ const success = await performSync(curRatios);
+ if (success) {
+ setConfirmVisible(false);
+ }
+ } finally {
+ setConfirmLoading(false);
+ }
}}
onCancel={() => setConfirmVisible(false)}
/>
diff --git a/web/classic/src/pages/Setting/Ratio/components/TieredPricingEditor.jsx b/web/classic/src/pages/Setting/Ratio/components/TieredPricingEditor.jsx
index ec06a3409c..4ad94f736c 100644
--- a/web/classic/src/pages/Setting/Ratio/components/TieredPricingEditor.jsx
+++ b/web/classic/src/pages/Setting/Ratio/components/TieredPricingEditor.jsx
@@ -31,9 +31,10 @@ import {
TextArea,
Typography,
} from '@douyinfe/semi-ui';
-import { IconDelete, IconPlus } from '@douyinfe/semi-icons';
+import { IconCopy, IconDelete, IconPlus } from '@douyinfe/semi-icons';
import { renderQuota } from '../../../../helpers/render';
-import { BILLING_EXTRA_VARS, BILLING_CACHE_VAR_MAP } from '../../../../constants';
+import { copy, showSuccess } from '../../../../helpers';
+import { BILLING_EXTRA_VARS, BILLING_CACHE_VAR_MAP, BILLING_CONDITION_VARS } from '../../../../constants';
import {
createEmptyCondition,
createEmptyTimeCondition,
@@ -70,6 +71,7 @@ function priceToUnitCost(price) {
const OPS = ['<', '<=', '>', '>='];
const VAR_OPTIONS = [
+ { value: 'len', label: 'len (长度)' },
{ value: 'p', label: 'p (输入)' },
{ value: 'c', label: 'c (输出)' },
];
@@ -224,7 +226,7 @@ function tryParseVisualConfig(exprStr) {
}
// Multi-tier: cond1 ? tier(body) : cond2 ? tier(body) : tier(body)
- const condGroup = `((?:(?:p|c)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)(?:\\s*&&\\s*(?:p|c)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)*)`;
+ const condGroup = `((?:(?:p|c|len)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)(?:\\s*&&\\s*(?:p|c|len)\\s*(?:<|<=|>|>=)\\s*[\\d.eE+]+)*)`;
const tierRe = new RegExp(
`(?:${condGroup}\\s*\\?\\s*)?tier\\("([^"]*)",\\s*${bodyPat}\\)`,
'g',
@@ -237,7 +239,7 @@ function tryParseVisualConfig(exprStr) {
if (condStr) {
const condParts = condStr.split(/\s*&&\s*/);
for (const cp of condParts) {
- const cm = cp.trim().match(/^(p|c)\s*(<|<=|>|>=)\s*([\d.eE+]+)$/);
+ const cm = cp.trim().match(/^(p|c|len)\s*(<|<=|>|>=)\s*([\d.eE+]+)$/);
if (cm) {
conditions.push({ var: cm[1], op: cm[2], value: Number(cm[3]) });
}
@@ -283,7 +285,7 @@ function ConditionRow({ cond, onChange, onRemove, t }) {
}}>