/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ // ============================================================================ // 模型原厂(官方)价格 · 折扣计算纯函数 // ---------------------------------------------------------------------------- // 官方价由管理员在 系统设置-倍率设置-模型原厂价格 维护,单位 ¥(平台按人民币兑 // 美元 1:1 口径,与站内计价基准 model_ratio×2 同量纲)。折扣只做前端展示, // 不参与任何计费。折扣率一律用「实付/官方」的数值比计算,绝不从格式化字符串反推。 // 保持纯 JS(无 JSX/无副作用)以便 node --test 直测。 // ============================================================================ const DISCOUNT_EPSILON = 0.995; // 比值 ≥ 该阈值视为无折扣(避免 9.9 折之类的噪声标签) const isPositiveFinite = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0; /** * 单价折扣比:实付 / 官方。任一值非法或实付不低于官方(含加价)→ null(不展示)。 */ export const computeDiscountRatio = (actualPrice, officialPrice) => { if (!isPositiveFinite(actualPrice) || !isPositiveFinite(officialPrice)) { return null; } const ratio = actualPrice / officialPrice; if (ratio >= DISCOUNT_EPSILON) return null; return ratio; }; /** * 从多个方向的折扣比中挑选卡片徽标使用的「代表折扣」。 * 取有效值中的最大比值(= 折扣最保守的方向),避免「输入 2.5 折、输出 5 折」 * 时徽标夸大宣传;任一方向为 null(无折扣/加价)→ 整体不出徽标,防止误导。 */ export const pickBadgeDiscount = (ratios) => { const list = Array.isArray(ratios) ? ratios : [ratios]; const valid = list.filter((r) => r !== null && r !== undefined); if (valid.length === 0 || valid.length !== list.length) return null; return Math.max(...valid); }; /** * 折扣文案:中文用「X 折」(如 0.25 → "2.5折"),其他语言用 "-75%"。 * @param {number} ratio 实付/官方 比值 (0,1) * @param {string} language i18next 当前语言 */ export const formatDiscountLabel = (ratio, language = 'zh') => { if (!isPositiveFinite(ratio) || ratio >= 1) return ''; if (String(language).toLowerCase().startsWith('zh')) { // 保留 1 位小数并去掉尾零:0.25→2.5折,0.5→5折,0.08→0.8折 const zhe = Math.round(ratio * 100) / 10; return `${zhe}折`; } return `-${Math.round((1 - ratio) * 100)}%`; }; /** * 组装某模型在指定分组倍率下的官方价对比信息(数值层,不做货币格式化)。 * @param {object} record 模型定价记录(/api/pricing data 条目) * @param {object|undefined} official { input, output, per_call },单位 ¥(1:1 兑美元口径),/1M tokens 或 /次 * @param {number} usedGroupRatio 实际使用的分组倍率(已含等级折扣) * @returns {null | { * officialInput?: number, officialOutput?: number, officialPerCall?: number, * discountInput?: number|null, discountOutput?: number|null, discountPerCall?: number|null, * badgeDiscount: number|null, * }} */ export const buildOfficialComparison = (record, official, usedGroupRatio) => { if (!record || !official) return null; if (!isPositiveFinite(usedGroupRatio)) return null; if (record.quota_type === 0) { const hasInput = isPositiveFinite(official.input); const hasOutput = isPositiveFinite(official.output); if (!hasInput && !hasOutput) return null; const actualInput = record.model_ratio * 2 * usedGroupRatio; const actualOutput = record.model_ratio * (record.completion_ratio ?? 1) * 2 * usedGroupRatio; const discountInput = hasInput ? computeDiscountRatio(actualInput, official.input) : undefined; const discountOutput = hasOutput ? computeDiscountRatio(actualOutput, official.output) : undefined; return { officialInput: hasInput ? official.input : undefined, officialOutput: hasOutput ? official.output : undefined, discountInput, discountOutput, badgeDiscount: pickBadgeDiscount( [discountInput, discountOutput].filter((d) => d !== undefined), ), }; } if (record.quota_type === 1) { if (!isPositiveFinite(official.per_call)) return null; const actual = parseFloat(record.model_price) * usedGroupRatio; const discountPerCall = computeDiscountRatio(actual, official.per_call); return { officialPerCall: official.per_call, discountPerCall, badgeDiscount: discountPerCall, }; } // quota_type 2/3(按秒、按分辨率分档):官方价按档位登记(见 tierPricingOf), // 只服务成本核算与毛利,不上市场页——市场页的分组价表按档位横排,再叠一行 // 逐档原价会把表挤爆,且分档模型的折扣本就要逐档看,一个整体徽标只会误导。 return null; }; // ============================================================================ // 分档计费(视频按秒 / 图片按分辨率) // ---------------------------------------------------------------------------- // 分档模型的每个档位单价互不相干(720p 与 1080p 可差数倍),官方价必须逐档登记: // 一个"整模型均价"在高档位必然算亏、低档位虚高,毛利与分佣都会失真。 // 档位键与收入侧规范键同源(大小写不敏感,比较前一律归一)。 // ============================================================================ export const normalizeTierKey = (key) => String(key ?? '') .trim() .toLowerCase(); /** * 该记录的分档计价元信息;非分档计费返回 null。 * @returns {null | { field: 'per_second'|'per_image', unit: string, * tiers: Array<{key: string, label: string, basePrice: number}> }} */ export const tierPricingOf = (record) => { if (!record) return null; // 档位键为空的条目一律剔除:牌价按档位键存,空键在后端 normalizeTierMap 被拒、 // 在前端 canonical 里被丢弃——若照样渲染输入框,用户填的值会静默消失且提示 // 「你似乎并没有修改什么」。收入侧本身允许空 key(parseVideoPricing 无校验)。 const mapTiers = (tiers, priceField) => (tiers || []) .filter((t) => normalizeTierKey(t?.key) !== '') .map((t) => ({ key: t.key, label: t.label || t.key, basePrice: Number(t[priceField]), })); if (record.quota_type === 2) { return { field: 'per_second', unit: '秒', tiers: mapTiers(record.video_second_pricing?.tiers, 'price_per_second'), }; } if (record.quota_type === 3) { return { field: 'per_image', unit: '张', tiers: mapTiers( record.image_resolution_pricing?.tiers, 'price_per_image', ), }; } return null; }; /** 归一化取档位官方价;未填/非法 → undefined */ export const tierPriceOf = (entry, field, tierKey) => { const map = entry?.[field]; if (!map || typeof map !== 'object') return undefined; const want = normalizeTierKey(tierKey); const found = Object.keys(map).find((k) => normalizeTierKey(k) === want); if (found === undefined) return undefined; const v = map[found]; return isPositiveFinite(v) ? v : undefined; }; /** * 分档模型的逐档折扣对照(管理端预览用;市场页不展示,理由见 buildOfficialComparison)。 * @returns {null | Array<{key,label,basePrice,official?:number,discount?:number|null}>} */ export const buildTierComparison = (record, official) => { const pricing = tierPricingOf(record); if (!pricing) return null; return pricing.tiers.map((tier) => { const officialPrice = tierPriceOf(official, pricing.field, tier.key); return { ...tier, official: officialPrice, discount: officialPrice === undefined ? undefined : computeDiscountRatio(tier.basePrice, officialPrice), }; }); }; // ============================================================================ // 管理端维护辅助(系统设置-倍率设置-模型原厂价格) // ---------------------------------------------------------------------------- // 填写完整度判定 / 稳定序列化 / 导入校验。保持纯函数以便 node --test 直测。 // ============================================================================ export const OFFICIAL_FILL_NA = 'na'; // 无可填字段的计费类型(未知形态 / 分档模型没有任何档位) export const OFFICIAL_FILL_EMPTY = 'empty'; export const OFFICIAL_FILL_PARTIAL = 'partial'; export const OFFICIAL_FILL_FILLED = 'filled'; /** * 官方价字段的固定顺序(序列化与遍历口径统一,避免键序影响比较)。 * cache_read / cache_creation 不参与市场页折扣展示,只服务成本核算: * 收入侧对缓存读取与缓存创建单独计价,成本侧要「扣费的每一项都有成本价」, * 就必须有对应的原厂参照价。 */ const OFFICIAL_SCALAR_FIELDS = [ 'input', 'output', 'per_call', 'cache_read', 'cache_creation', ]; /** 分档字段:值是 { 档位键: ¥单价 } 映射,不是标量(校验/序列化都要区别对待) */ export const OFFICIAL_TIER_FIELDS = ['per_second', 'per_image']; const OFFICIAL_FIELDS = [...OFFICIAL_SCALAR_FIELDS, ...OFFICIAL_TIER_FIELDS]; export const isOfficialTierField = (field) => OFFICIAL_TIER_FIELDS.includes(field); const isTierField = isOfficialTierField; /** 该字段是否填了有效值(标量 = 正数;分档 = 至少一个档位是正数) */ const hasFieldValue = (entry, field) => { const v = entry?.[field]; if (!isTierField(field)) return isPositiveFinite(v); if (!v || typeof v !== 'object') return false; return Object.values(v).some((p) => isPositiveFinite(p)); }; /** 各计费类型下真正用得上的字段(其余字段填了也不生效) */ const applicableFields = (quotaType) => { // per_image 对按量计费模型同样生效:Responses 内嵌出图是「token 费 + 出图调用费」 // 相加,成本侧 CalcDirectCost 也是把 imageCost 加到 token 段上(不是二选一)。 // 漏了它会把一条正在记账的基准标成「配置不生效」,诱导管理员删掉。 if (quotaType === 0) return ['input', 'output', 'cache_read', 'cache_creation', 'per_image']; if (quotaType === 1) return ['per_call']; if (quotaType === 2) return ['per_second']; if (quotaType === 3) return ['per_image']; return []; }; /** * 某模型官方价的填写完整度。 * 按量计费(quota_type=0)必须输入价 + 输出价都填才算「已填写」:市场页的折扣 * 徽标走 pickBadgeDiscount(任一方向缺失即不出徽标),只填一侧其实不生效—— * 若把它计入已填写,管理员会误以为该模型已经配好。 * * 缓存两项按 need 传入时才纳入判定:只有收入侧确实按缓存计费的模型才需要它们, * 给所有模型都要求会让绝大多数模型永远停在「部分填写」,状态也就失去指示意义。 * * 分档计费(按秒 / 按分辨率)以 need.tierKeys 为必填集:收入侧逐档定价,成本侧 * 也逐档记账,缺一档就是那一档的毛利算不出来,必须显示「部分填写」点名。 * 该模型没有任何档位(分档配置被清空)时无字段可填,返回 NA。 * @param {{needCacheRead?: boolean, needCacheCreation?: boolean, tierKeys?: string[]}} [need] */ export const officialFillState = (quotaType, entry, need) => { const e = entry || {}; if (quotaType === 0) { const required = ['input', 'output']; if (need?.needCacheRead) required.push('cache_read'); if (need?.needCacheCreation) required.push('cache_creation'); const filled = required.filter((f) => isPositiveFinite(e[f])).length; if (filled === required.length) return OFFICIAL_FILL_FILLED; if (filled > 0) return OFFICIAL_FILL_PARTIAL; return OFFICIAL_FILL_EMPTY; } if (quotaType === 1) { return isPositiveFinite(e.per_call) ? OFFICIAL_FILL_FILLED : OFFICIAL_FILL_EMPTY; } if (quotaType === 2 || quotaType === 3) { const field = quotaType === 2 ? 'per_second' : 'per_image'; const tiers = need?.tierKeys || []; if (tiers.length === 0) return OFFICIAL_FILL_NA; const filled = tiers.filter( (k) => tierPriceOf(e, field, k) !== undefined, ).length; if (filled === tiers.length) return OFFICIAL_FILL_FILLED; if (filled > 0) return OFFICIAL_FILL_PARTIAL; return OFFICIAL_FILL_EMPTY; } return OFFICIAL_FILL_NA; }; /** * 该条目在当前计费类型下是否**完全不生效**(填了值,但没有一个字段用得上)。 * 典型成因:模型事后改了计费方式(按量↔按次)、改成按秒分档、导入时字段填错。 * 这类条目在页面上「看起来没填」,却会被原样保存、永远不产生折扣——必须显式标出, * 否则管理员会以为配好了。 * * 判定看的是「有没有任何一个**适用**字段有值」,不能拿 officialFillState 的 * EMPTY 来代替:按量计费模型只填了缓存价时 fillState 仍是 EMPTY(缓存不算必填), * 但那个值成本侧照用不误,标成「配置不生效」是误报。 */ export const isOfficialEntryInert = (quotaType, entry) => { const e = entry || {}; if (!OFFICIAL_FIELDS.some((f) => hasFieldValue(e, f))) return false; return !applicableFields(quotaType).some((f) => hasFieldValue(e, f)); }; /** * 稳定序列化:模型名按字典序、字段按固定序、丢弃非正数与空条目。 * 「是否有未保存修改」必须用它比较——直接 JSON.stringify 对键序敏感, * 「清空某字段后又填回同一个值」会让条目被删除再追加到末尾,键序变化, * 于是页面永远挂着「有未保存的修改」。 */ export const canonicalOfficialPriceJSON = (map) => { const src = map && typeof map === 'object' ? map : {}; const out = {}; Object.keys(src) .sort() .forEach((model) => { const entry = src[model]; if (!entry || typeof entry !== 'object') return; const kept = {}; OFFICIAL_FIELDS.forEach((field) => { if (!isTierField(field)) { if (isPositiveFinite(entry[field])) kept[field] = entry[field]; return; } // 分档字段:档位键归一 + 按字典序落盘,序列化结果才与键序无关; // 归一后同键取字典序靠前的原键,避免「1080p / 1080P」两写法互相覆盖出抖动 const rawTiers = entry[field]; if ( !rawTiers || typeof rawTiers !== 'object' || Array.isArray(rawTiers) ) return; const normalized = {}; Object.keys(rawTiers) .sort() // 同一归一键有多种写法时取字典序靠前的那个,结果才确定 .forEach((rawKey) => { const key = normalizeTierKey(rawKey); if (!key || normalized[key] !== undefined) return; if (isPositiveFinite(rawTiers[rawKey])) normalized[key] = rawTiers[rawKey]; }); const keys = Object.keys(normalized).sort(); if (keys.length === 0) return; // 按归一键字典序重建:JSON.stringify 依插入序输出,归一前排序不足以定序 kept[field] = keys.reduce((acc, k) => { acc[k] = normalized[k]; return acc; }, {}); }); if (Object.keys(kept).length > 0) out[model] = kept; }); return JSON.stringify(out); }; /** * 导入校验:把任意 JSON 收敛成合法的 * model -> {input?,output?,per_call?,cache_read?,cache_creation?,per_second?,per_image?} 映射 *(per_second / per_image 的值是 { 档位键: ¥单价 })。 * 校验口径与后端 ValidateOfficialPriceJSONString 一致(必须是 > 0 的有限数、 * 不允许空条目),未知字段视为错误而非静默丢弃——拼错 per_call 会导致整条配置 * 看似导入成功却完全不生效。 * @returns {{ value: object, errors: string[] }} */ export const sanitizeOfficialPriceMap = (raw) => { const errors = []; const value = {}; if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { return { value, errors: [ '顶层必须是 { 模型名: { input, output, per_call, cache_read, cache_creation, per_second: {档位: 价}, per_image: {档位: 价} } } 结构', ], }; } Object.keys(raw).forEach((model) => { const name = String(model).trim(); if (!name) { errors.push('存在空模型名'); return; } const entry = raw[model]; if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { errors.push(`${name}: 价格必须是对象`); return; } const unknown = Object.keys(entry).filter( (k) => !OFFICIAL_FIELDS.includes(k), ); if (unknown.length > 0) { errors.push(`${name}: 不认识的字段 ${unknown.join('、')}`); return; } const kept = {}; let fieldFailed = false; OFFICIAL_FIELDS.forEach((field) => { const v = entry[field]; if (v === undefined || v === null || v === '') return; if (isTierField(field)) { // 分档字段是 { 档位键: 价格 } 映射;写成标量说明量纲搞错了,必须报错 if (typeof v !== 'object' || Array.isArray(v)) { errors.push(`${name}.${field}: 必须是 { 档位键: 价格 } 结构`); fieldFailed = true; return; } const tiers = {}; Object.keys(v).forEach((rawKey) => { const key = normalizeTierKey(rawKey); if (!key) { errors.push(`${name}.${field}: 存在空档位键`); fieldFailed = true; return; } // 归一后重键:只差大小写的两档会互相覆盖,静默丢掉一档的牌价 if (tiers[key] !== undefined) { errors.push( `${name}.${field}: 档位键 ${key} 重复(档位键大小写不敏感)`, ); fieldFailed = true; return; } const tv = Number(v[rawKey]); if (!isPositiveFinite(tv)) { errors.push(`${name}.${field}.${rawKey}: 必须是大于 0 的数值`); fieldFailed = true; return; } tiers[key] = tv; }); if (Object.keys(tiers).length > 0) kept[field] = tiers; return; } const n = Number(v); if (!isPositiveFinite(n)) { errors.push(`${name}.${field}: 必须是大于 0 的数值`); fieldFailed = true; return; } kept[field] = n; }); if (Object.keys(kept).length === 0) { // 已按字段报过错就不再叠一条「未填写任何字段」,否则同一处问题报两遍 if (!fieldFailed) errors.push(`${name}: 未填写任何官方价字段`); return; } value[name] = kept; }); return { value, errors }; };