fix: reconcile source currencies and retail token pricing
This commit is contained in:
1 parent
ea9069e332
commit
512ca52262
12 files changed
+458
-12
No files matched your search
@@ -5,6 +5,7 @@ import { catalogClient, type CatalogProvider, type CatalogModel, type LogicalMod
|
||||
import UiModal from './UiModal.vue'
|
||||
import ListPagination from './ListPagination.vue'
|
||||
import { usePagination } from '../composables/usePagination'
|
||||
import { calculateTokenRetailPricing } from '../services/pricing'
|
||||
|
||||
const props = defineProps<{ section: 'models' | 'channels' }>()
|
||||
const emit = defineEmits<{ notify: [message: string] }>()
|
||||
@@ -30,6 +31,8 @@ async function remove() {
|
||||
const channel = reactive({ code: '', name: '', protocol: 'openai-compatible' as CatalogProvider['protocol'], sourceType: 'relay' as CatalogProvider['sourceType'], baseUrl: '', credentialType: 'api-key' as NonNullable<CatalogProvider['credentialType']>, credentialSecret: '', description: '', status: 'active' as CatalogProvider['status'] })
|
||||
const model = reactive({ publicName: '', modelKey: '', vendorName: '', type: 'text' as LogicalModel['type'], mode: 'sync' as LogicalModel['mode'], description: '', inputTypes: 'text', outputTypes: 'text', status: 'active' as LogicalModel['status'] })
|
||||
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', cachedInput: '', unit: 'CNY / 1M tokens', discount: '', discountLabel: '', exchangeRate: '', priceSource: '', listPriceInput: '', listPriceOutput: '', listPriceCachedInput: '', priority: '100', maxConcurrency: '0', status: 'active' as CatalogModel['status'] })
|
||||
const listCurrency = ref<'USD' | 'CNY'>('USD')
|
||||
const originalPricing = ref<CatalogModel['pricing']>()
|
||||
const shownModels = computed(() => models.value.filter(item => `${item.publicName} ${item.vendorName || ''} ${item.modelKey || ''}`.toLowerCase().includes(query.value.toLowerCase())))
|
||||
const shownChannels = computed(() => channels.value.filter(item => `${item.name} ${item.code}`.toLowerCase().includes(query.value.toLowerCase())))
|
||||
const { page: modelPage, pageSize: modelPageSize, pagedItems: pagedModels } = usePagination(shownModels)
|
||||
@@ -64,9 +67,29 @@ function editModel(item?: LogicalModel) {
|
||||
}
|
||||
function editGroup(parent: LogicalModel, item?: CatalogModel) {
|
||||
editingId.value = item?.id
|
||||
originalPricing.value = item?.pricing
|
||||
listCurrency.value = item?.pricing?.listPriceCny ? 'CNY' : 'USD'
|
||||
Object.assign(group, { logicalModelId: parent.id, providerId: item?.providerId || '', sourceLabel: item?.sourceLabel || '', upstreamModel: item?.upstreamModel || '', input: item?.pricing?.input?.toString() || '', output: item?.pricing?.output?.toString() || '', cachedInput: item?.pricing?.cachedInput?.toString() || '', unit: item?.pricing?.unit || 'CNY / 1M tokens', discount: item?.pricing?.discount?.toString() || '', discountLabel: item?.pricing?.discountLabel || '', exchangeRate: item?.pricing?.exchangeRate?.toString() || '', priceSource: item?.pricing?.priceSource || '', listPriceInput: item?.pricing?.listPriceUsd?.input?.toString() || '', listPriceOutput: item?.pricing?.listPriceUsd?.output?.toString() || '', listPriceCachedInput: item?.pricing?.listPriceUsd?.cachedInput?.toString() || '', priority: String(item?.priority ?? 100), maxConcurrency: String(item?.maxConcurrency ?? 0), status: item?.status || 'active' })
|
||||
const list = item?.pricing?.listPriceCny || item?.pricing?.listPriceUsd
|
||||
group.listPriceInput = list?.input?.toString() ?? ''
|
||||
group.listPriceOutput = list?.output?.toString() ?? ''
|
||||
group.listPriceCachedInput = list?.cachedInput?.toString() ?? ''
|
||||
editor.value = 'group'
|
||||
}
|
||||
function calculateRetail() {
|
||||
try {
|
||||
if (group.unit !== 'CNY / 1M tokens') throw new Error('自动换算仅支持每百万 Token 价格')
|
||||
if (group.listPriceInput === '' || group.listPriceOutput === '' || group.discount === '') throw new Error('请填写标准输入价、标准输出价和对外折扣')
|
||||
const price = calculateTokenRetailPricing(listCurrency.value, {input:Number(group.listPriceInput),output:Number(group.listPriceOutput),cachedInput:group.listPriceCachedInput === '' ? undefined : Number(group.listPriceCachedInput)}, Number(group.discount), group.exchangeRate === '' ? undefined : Number(group.exchangeRate))
|
||||
Object.assign(group, {input:String(price.input),output:String(price.output),cachedInput:price.cachedInput === undefined ? '' : String(price.cachedInput),discountLabel:price.discountLabel,exchangeRate:String(price.exchangeRate)})
|
||||
emit('notify', '已换算人民币售价,请保存使其生效')
|
||||
} catch (e) { emit('notify', e instanceof Error ? e.message : '换算失败') }
|
||||
}
|
||||
|
||||
function groupPricing(): CatalogModel['pricing'] {
|
||||
const list = group.listPriceInput === '' && group.listPriceOutput === '' && group.listPriceCachedInput === '' ? undefined : {input:group.listPriceInput === '' ? undefined : Number(group.listPriceInput),output:group.listPriceOutput === '' ? undefined : Number(group.listPriceOutput),cachedInput:group.listPriceCachedInput === '' ? undefined : Number(group.listPriceCachedInput)}
|
||||
return {...originalPricing.value,input:group.input === '' ? undefined : Number(group.input),output:group.output === '' ? undefined : Number(group.output),cachedInput:group.cachedInput === '' ? undefined : Number(group.cachedInput),unit:group.unit,discount:group.discount === '' ? undefined : Number(group.discount),discountLabel:group.discountLabel.trim() || undefined,exchangeRate:listCurrency.value === 'CNY' && list ? 1 : group.exchangeRate === '' ? undefined : Number(group.exchangeRate),priceSource:group.priceSource.trim() || undefined,listPriceUsd:listCurrency.value === 'USD' ? list : undefined,listPriceCny:listCurrency.value === 'CNY' ? list : undefined}
|
||||
}
|
||||
async function save() {
|
||||
if (saving.value) return
|
||||
saving.value = true
|
||||
@@ -81,7 +104,7 @@ async function save() {
|
||||
await catalogClient.saveDefinition(editingId.value, { ...model, inputTypes: model.inputTypes.split(',').map(s => s.trim()).filter(Boolean), outputTypes: model.outputTypes.split(',').map(s => s.trim()).filter(Boolean) })
|
||||
} else {
|
||||
if (!group.providerId || !group.sourceLabel.trim() || !group.upstreamModel.trim()) throw new Error('请选择渠道并填写分组名称、上游模型标识')
|
||||
await catalogClient.saveGroup(editingId.value, { logicalModelId: group.logicalModelId, providerId: group.providerId, sourceLabel: group.sourceLabel, upstreamModel: group.upstreamModel, status: group.status, priority: Number(group.priority), maxConcurrency: Number(group.maxConcurrency), pricing: { input: group.input === '' ? undefined : Number(group.input), output: group.output === '' ? undefined : Number(group.output), cachedInput: group.cachedInput === '' ? undefined : Number(group.cachedInput), unit: group.unit, discount: group.discount === '' ? undefined : Number(group.discount), discountLabel: group.discountLabel.trim() || undefined, exchangeRate: group.exchangeRate === '' ? undefined : Number(group.exchangeRate), priceSource: group.priceSource.trim() || undefined, listPriceUsd: group.listPriceInput === '' && group.listPriceOutput === '' && group.listPriceCachedInput === '' ? undefined : { input: group.listPriceInput === '' ? undefined : Number(group.listPriceInput), output: group.listPriceOutput === '' ? undefined : Number(group.listPriceOutput), cachedInput: group.listPriceCachedInput === '' ? undefined : Number(group.listPriceCachedInput) } } })
|
||||
await catalogClient.saveGroup(editingId.value, { logicalModelId: group.logicalModelId, providerId: group.providerId, sourceLabel: group.sourceLabel, upstreamModel: group.upstreamModel, status: group.status, priority: Number(group.priority), maxConcurrency: Number(group.maxConcurrency), pricing: groupPricing() })
|
||||
}
|
||||
editor.value = ''
|
||||
await refresh()
|
||||
@@ -152,8 +175,13 @@ async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider
|
||||
<div class="modal-form-grid"><label><span class="form-label">输入价格</span><input v-model="group.input" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">输出价格</span><input v-model="group.output" class="text-input" type="number" min="0" step="any" /></label></div>
|
||||
<label class="form-label">缓存命中输入价格(留空按普通输入价格)<input v-model="group.cachedInput" class="text-input" type="number" min="0" step="any" /></label>
|
||||
<label class="form-label" for="group-unit">价格单位</label><input id="group-unit" v-model="group.unit" class="text-input" required />
|
||||
<div class="modal-form-grid"><label><span class="form-label">标准输入价(USD / 1M)</span><input v-model="group.listPriceInput" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">标准输出价(USD / 1M)</span><input v-model="group.listPriceOutput" class="text-input" type="number" min="0" step="any" /></label></div>
|
||||
<label class="form-label">标准缓存输入价(USD / 1M,可选)<input v-model="group.listPriceCachedInput" class="text-input" type="number" min="0" step="any" /></label>
|
||||
<label class="form-label" for="list-currency">渠道标准价币种</label><select id="list-currency" v-model="listCurrency" class="text-input"><option value="CNY">人民币 CNY</option><option value="USD">美元 USD</option></select>
|
||||
<div class="modal-form-grid"><label><span class="form-label">标准输入价({{ listCurrency }} / 百万 Token)</span><input v-model="group.listPriceInput" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">标准输出价({{ listCurrency }} / 百万 Token)</span><input v-model="group.listPriceOutput" class="text-input" type="number" min="0" step="any" /></label></div>
|
||||
<label class="form-label">标准缓存输入价({{ listCurrency }} / 百万 Token,可选)<input v-model="group.listPriceCachedInput" class="text-input" type="number" min="0" step="any" /></label>
|
||||
<label class="form-label">对外折扣数值<input v-model="group.discount" class="text-input" type="number" min="0" max="10" step="0.1" placeholder="例如:5.6 表示 5.6 折" /></label>
|
||||
<label v-if="listCurrency === 'USD'" class="form-label">美元兑人民币汇率<input v-model="group.exchangeRate" class="text-input" type="number" min="0.00000001" step="any" /></label>
|
||||
<button v-if="group.unit === 'CNY / 1M tokens'" type="button" class="button secondary" @click="calculateRetail">按标准价和对外折扣换算售价</button>
|
||||
<small>1M Token=1,000,000 Token=一百万 Token。人民币原价不乘汇率;美元原价仅换算一次。采购 4.6 折加 1 个折扣点,对外填 5.6。</small>
|
||||
<label class="form-label" for="group-discount">对外折扣(仅展示)</label><input id="group-discount" v-model="group.discountLabel" class="text-input" maxlength="24" placeholder="例如:5.6折" /><small>输入、输出价格是实际扣费值,单位为 CNY / 1M tokens。折扣只用于向用户展示,不会替代人民币售价;留空表示不展示折扣。</small>
|
||||
<div class="modal-form-grid"><label><span class="form-label">优先级</span><input v-model="group.priority" class="text-input" type="number" min="0" step="1" required /></label><label><span class="form-label">MOYI 分组并发上限</span><input v-model="group.maxConcurrency" class="text-input" type="number" min="0" step="1" required /><small>填 0 表示不设置平台分组上限,直接测量渠道方的真实并发;只有渠道明确给出共享上限时才填写正整数。</small></label></div>
|
||||
</template>
|
||||
|
||||
@@ -44,6 +44,7 @@ export interface CatalogModel {
|
||||
upstreamCredits?: number
|
||||
standardPrice?: { price?: number; unit?: string; credits?: number; priceSource?: string }
|
||||
listPriceUsd?: { input?: number; output?: number; cachedInput?: number }
|
||||
listPriceCny?: { input?: number; output?: number; cachedInput?: number }
|
||||
}
|
||||
pricingConfigured?: boolean
|
||||
billingReady?: boolean
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface DisplayPricing {
|
||||
upstreamCredits?: number
|
||||
standardPrice?: { price?: number; unit?: string; credits?: number; priceSource?: string }
|
||||
listPriceUsd?: { input?: number; output?: number; cachedInput?: number }
|
||||
listPriceCny?: { input?: number; output?: number; cachedInput?: number }
|
||||
}
|
||||
|
||||
function numberLabel(value: number | undefined, currency = '¥') {
|
||||
@@ -51,8 +52,11 @@ export function standardPriceLabel(pricing?: DisplayPricing) {
|
||||
if (!pricing) return '标准价未提供'
|
||||
const fixed = pricing.standardPrice ? fixedStandardPriceLabel(pricing.standardPrice) : undefined
|
||||
if (fixed) return fixed
|
||||
if (pricing.listPriceCny) {
|
||||
return `${numberLabel(pricing.listPriceCny.input)} 输入 / ${numberLabel(pricing.listPriceCny.output)} 输出 · CNY / 1M(一百万 Token)`
|
||||
}
|
||||
if (pricing.listPriceUsd) {
|
||||
return `${formatUsd(pricing.listPriceUsd.input)} 输入 / ${formatUsd(pricing.listPriceUsd.output)} 输出 · USD / 1M`
|
||||
return `${formatUsd(pricing.listPriceUsd.input)} 输入 / ${formatUsd(pricing.listPriceUsd.output)} 输出 · USD / 1M(一百万 Token)`
|
||||
}
|
||||
const credits = pricing.upstreamCredits ?? pricing.standardPrice?.credits
|
||||
if (credits !== undefined && Number.isFinite(credits)) {
|
||||
@@ -64,10 +68,10 @@ export function standardPriceLabel(pricing?: DisplayPricing) {
|
||||
/** A logical model can have several routes. Do not present one route's list price as universal when they differ. */
|
||||
export function modelStandardPriceLabel(pricings: Array<DisplayPricing | undefined>) {
|
||||
const values = pricings.filter((pricing): pricing is DisplayPricing => !!pricing)
|
||||
const listed = values.filter((pricing) => !!pricing.listPriceUsd || !!pricing.standardPrice)
|
||||
const listed = values.filter((pricing) => !!pricing.listPriceUsd || !!pricing.listPriceCny || !!pricing.standardPrice)
|
||||
if (listed.length > 0 && listed.length < values.length) return '部分分组标准价见详情'
|
||||
if (listed.length > 1) {
|
||||
const keys = new Set(listed.map((pricing) => JSON.stringify({ listPriceUsd: pricing.listPriceUsd, standardPrice: pricing.standardPrice })))
|
||||
const keys = new Set(listed.map((pricing) => JSON.stringify({ listPriceUsd: pricing.listPriceUsd, listPriceCny: pricing.listPriceCny, standardPrice: pricing.standardPrice })))
|
||||
if (keys.size > 1) return '各分组标准价见详情'
|
||||
}
|
||||
return standardPriceLabel(listed[0] || values[0])
|
||||
@@ -76,12 +80,32 @@ export function modelStandardPriceLabel(pricings: Array<DisplayPricing | undefin
|
||||
export function platformPriceLabel(pricing?: DisplayPricing) {
|
||||
if (!pricing) return '价格待配置'
|
||||
if (isTokenUnit(pricing.unit)) {
|
||||
return `${numberLabel(pricing.input)} 输入 / ${numberLabel(pricing.output)} 输出 · ${pricing.unit || 'CNY / 1M tokens'}`
|
||||
const unit = pricing.unit === 'CNY / 1M tokens' ? '人民币 / 1M(一百万 Token)' : pricing.unit || '人民币 / 1M(一百万 Token)'
|
||||
return `${numberLabel(pricing.input)} 输入 / ${numberLabel(pricing.output)} 输出 · ${unit}`
|
||||
}
|
||||
const price = pricing.price ?? pricing.input
|
||||
return price === undefined ? `计费单位:${unitLabel(pricing.unit)}` : `平台售价 ${numberLabel(price)} / ${unitSuffix(pricing)}`
|
||||
}
|
||||
|
||||
/** Explicit admin action. Settlement still uses saved CNY rates, never applies a second discount. */
|
||||
export function calculateTokenRetailPricing(currency: 'CNY' | 'USD', list: { input: number; output: number; cachedInput?: number }, discount: number, exchangeRate?: number) {
|
||||
if (currency !== 'CNY' && currency !== 'USD') throw new Error('请选择人民币或美元原价')
|
||||
if (!Number.isFinite(discount) || discount < 0 || discount > 10) throw new Error('对外折扣须在 0–10 折之间')
|
||||
const fx = currency === 'CNY' ? 1 : exchangeRate
|
||||
if (fx === undefined || !Number.isFinite(fx) || fx <= 0 || fx > 1000) throw new Error('美元原价需要有效的人民币汇率')
|
||||
const scale = 100000000n
|
||||
const scaled = (value: number) => BigInt(value.toFixed(8).replace('.', ''))
|
||||
const amount = (value: number) => {
|
||||
if (!Number.isFinite(value) || value < 0 || value > 1000000) throw new Error('原价须在 0–100 万之间')
|
||||
// Integer arithmetic with HALF_UP rounding to the same eight places as ChatMeter.
|
||||
const divisor = scale * scale * 10n
|
||||
const price = Number((scaled(value) * scaled(discount) * scaled(fx) + divisor / 2n) / divisor) / Number(scale)
|
||||
if (price > 1000000) throw new Error('人民币售价不能超过 100 万')
|
||||
return price
|
||||
}
|
||||
return { input: amount(list.input), output: amount(list.output), cachedInput: list.cachedInput === undefined ? undefined : amount(list.cachedInput), unit: 'CNY / 1M tokens', discount, discountLabel: `${discount}折`, exchangeRate: fx }
|
||||
}
|
||||
|
||||
export function groupDiscountLabel(pricing?: DisplayPricing, configured = true) {
|
||||
if (!configured || !pricing) return '价格待配置'
|
||||
if (pricing.discountLabel && pricing.discountLabel !== '标准价') return pricing.discountLabel
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { groupDiscountLabel, modelStandardPriceLabel, platformPriceLabel, standardPriceLabel } from '../src/services/pricing.ts'
|
||||
import { calculateTokenRetailPricing, groupDiscountLabel, modelStandardPriceLabel, platformPriceLabel, standardPriceLabel } from '../src/services/pricing.ts'
|
||||
|
||||
test('fixed-unit pricing shows platform task price without inventing a standard price or discount', () => {
|
||||
const tripo = { price: 1.44, unit: 'CNY / task', upstreamCredits: 20, exchangeRate: 7.2, priceSource: 'Tripo 官方', standardPrice: { price: 0.2, unit: 'USD / task', credits: 20 } }
|
||||
@@ -18,11 +18,28 @@ test('official standard price source is displayed, while a standard-price marker
|
||||
|
||||
test('token pricing retains explicit source list price and discount', () => {
|
||||
const pricing = { input: 1.2, output: 4.8, unit: 'CNY / 1M tokens', discount: 6.5, discountLabel: '6.5折', listPriceUsd: { input: 1, output: 4 } }
|
||||
assert.equal(standardPriceLabel(pricing), '$1 输入 / $4 输出 · USD / 1M')
|
||||
assert.equal(platformPriceLabel(pricing), '¥1.2 输入 / ¥4.8 输出 · CNY / 1M tokens')
|
||||
assert.equal(standardPriceLabel(pricing), '$1 输入 / $4 输出 · USD / 1M(一百万 Token)')
|
||||
assert.equal(platformPriceLabel(pricing), '¥1.2 输入 / ¥4.8 输出 · 人民币 / 1M(一百万 Token)')
|
||||
assert.equal(groupDiscountLabel(pricing), '6.5折')
|
||||
})
|
||||
|
||||
test('CNY source keeps its currency and never multiplies the USD exchange rate', () => {
|
||||
const result = calculateTokenRetailPricing('CNY', {input: 0.8, output: 2.8, cachedInput: 0.23}, 3, 7.2)
|
||||
assert.deepEqual([result.input, result.output, result.cachedInput, result.exchangeRate], [0.24, 0.84, 0.069, 1])
|
||||
assert.equal(standardPriceLabel({listPriceCny:{input:0.8,output:2.8}}), '¥0.8 输入 / ¥2.8 输出 · CNY / 1M(一百万 Token)')
|
||||
assert.equal(modelStandardPriceLabel([{listPriceUsd:{input:1,output:4}},{listPriceCny:{input:1,output:4}}]), '各分组标准价见详情')
|
||||
})
|
||||
|
||||
test('retail discount is in tenths; USD conversion and eight-place rounding happen once', () => {
|
||||
const result = calculateTokenRetailPricing('USD', {input:1.25, output:10, cachedInput:0.125}, 3.5, 7.2)
|
||||
assert.deepEqual([result.input,result.output,result.cachedInput],[3.15,25.2,0.315])
|
||||
assert.equal(calculateTokenRetailPricing('CNY',{input:0.00000001,output:0},5).input,0.00000001)
|
||||
assert.equal(calculateTokenRetailPricing('CNY',{input:0,output:0,cachedInput:0},10).cachedInput,0)
|
||||
assert.throws(()=>calculateTokenRetailPricing('USD',{input:1,output:1},5),/汇率/)
|
||||
assert.throws(()=>calculateTokenRetailPricing('CNY',{input:1,output:1},55),/折扣/)
|
||||
assert.throws(()=>calculateTokenRetailPricing('CNY',{input:NaN,output:1},5),/原价/)
|
||||
})
|
||||
|
||||
test('different route list prices are not presented as one universal model price', () => {
|
||||
assert.equal(modelStandardPriceLabel([
|
||||
{ unit: 'CNY / 1M tokens', listPriceUsd: { input: 1, output: 4 } },
|
||||
|
||||
Reference in new issue
Block a user