/* 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 */ import { Trans } from 'react-i18next'; import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { Banner, Button, DatePicker, Input, InputNumber, Modal, Popconfirm, Radio, RadioGroup, Select, Space, Table, Tag, Tooltip, Typography, } from '@/components/ui'; import { IconRefresh, IconSearch } from '@/components/ui/icons'; import { useTranslation } from 'react-i18next'; import i18next from 'i18next'; import { API, showError, showSuccess, showWarning, computeDiscountRatio, formatDiscountLabel, tierPriceOf, } from '../../../helpers'; const { Text } = Typography; // ============================================================================ // 模型成本价(按渠道维护) // ---------------------------------------------------------------------------- // 成本价只有「按渠道」这一个有业务意义的维度——同一个模型走不同上游,进价本就不同。 // 计费侧的四级查找(channel→tag→group→global)保持不变,本页只维护渠道级; // 历史遗留的非渠道级配置由后端计数回传,在页面顶部显式告警(看不见但仍在生效)。 // // 交互约定(踩过的坑,改动前务必读): // 1. 列表一行 = 一个模型,输入/输出/按次等单价在行内直接改。原实现一行 = 模型×单位, // gpt-4o 占两行、改一个模型要开两次弹窗,且看不到官方价与折扣,无从判断贵贱。 // 2. 「已配置/未配置」筛选走**快照**分类,不随每次按键重算——否则在「未配置」下刚 // 敲第一个字符该行就被过滤掉,输出价永远填不了(原厂价页同款坑)。 // 3. 非法输入(0/负数/非数字)保留在输入框里并标红,绝不静默丢弃。 // 4. 保存走版本化写入(截断旧区间 + 新开一版),历史账单仍按旧成本可复算。 // 5. 清空输入 = 删除当前生效版本,需显式确认,不与「改价」混在一起静默执行。 // ============================================================================ const UYUAN_PER_YUAN = 1000000; const CHANNEL_STORAGE_KEY = 'model_cost_last_channel'; // 计量单位展示元数据(label = 列内短标签,suffix = 输入框后缀)。 // token 形态的四个类目与收入侧计费公式逐项对应(service/quota.go): // fresh 输入 / 缓存读取 / 缓存创建 / 输出——四项都要有成本价,未填时后端按 // 「输入价 × 缓存倍率」推算兜底,但推算做不到按渠道真实进价对账,仍应显式填写。 const UNIT_META = { input_1m: { label: '输入', suffix: '/1M', official: 'input' }, output_1m: { label: '输出', suffix: '/1M', official: 'output' }, // 缓存两项的参照价:原厂页填了缓存牌价就用它(officialCache), // 没填才按厂商倍率从官方输入价折算(official) cached_input_1m: { label: '缓存读取', suffix: '/1M', official: 'input', officialCache: 'cache_read', }, cache_creation_1m: { label: '缓存创建', suffix: '/1M', official: 'input', officialCache: 'cache_creation', }, per_call: { label: '按次', suffix: '/次', official: 'per_call' }, // 分档两项的参照价按档位取:原厂页对按秒/按分辨率模型逐档登记牌价 //(tiered=true 表示 official 指向的是 { 档位键: 价 } 映射而非标量) per_second: { label: '按秒', suffix: '/秒', official: 'per_second', tiered: true, }, per_image: { label: '按张', suffix: '/张', official: 'per_image', tiered: true, }, }; // 复合键分隔符:模型名 / 单位 / 档位都可能含 - _ . 等常见字符,用不可见分隔符才不会撞键 const SEP = String.fromCharCode(0); const slotKeyOf = (unit, tier) => `${unit}${SEP}${tier || ''}`; const parseSlotKey = (k) => { const i = k.indexOf(SEP); return i < 0 ? { unit: k, tier: '' } : { unit: k.slice(0, i), tier: k.slice(i + 1) }; }; const fieldKeyOf = (modelName, slotKey) => `${modelName}${SEP}${slotKey}`; // fieldKey = 模型名 + SEP + 槽位键(槽位键内部还有一个 SEP),故按首个分隔符切 const parseFieldKey = (fk) => { const i = fk.indexOf(SEP); return { modelName: fk.slice(0, i), slotKey: fk.slice(i + 1) }; }; const isPositive = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0; // 微元 → 元展示:去掉无意义尾零(0.600000 → 0.6),但保留 0.000001 这类小额 const formatYuan = (uYuan) => (uYuan / UYUAN_PER_YUAN).toFixed(6).replace(/\.?0+$/, '') || '0'; const tsToDate = (ts) => (ts ? new Date(ts * 1000) : null); const fmtTs = (ts) => (ts ? new Date(ts * 1000).toLocaleString() : ''); const FILL_FILLED = 'filled'; const FILL_PARTIAL = 'partial'; const FILL_EMPTY = 'empty'; export default function ModelCostSettings() { const { t } = useTranslation(); const [channels, setChannels] = useState([]); const [channelsLoading, setChannelsLoading] = useState(false); const [channelId, setChannelId] = useState(''); const [scopeModels, setScopeModels] = useState([]); const [official, setOfficial] = useState({}); const [legacyCount, setLegacyCount] = useState(0); const [costRows, setCostRows] = useState([]); const [loading, setLoading] = useState(false); const [loaded, setLoaded] = useState(false); // 生效判定基准时刻:随每次载入固定,不随渲染漂移(否则同一份数据不同渲染可能判出不同的生效版本) const [nowTs, setNowTs] = useState(() => Math.floor(Date.now() / 1000)); // 行内编辑态:edits 存合法值(number = 改价,null = 清空即删除当前版本) const [edits, setEdits] = useState({}); const [drafts, setDrafts] = useState({}); // 非法输入原样回显 const [errors, setErrors] = useState({}); const [saving, setSaving] = useState(false); const [effectiveFrom, setEffectiveFrom] = useState(null); // null = 立即生效 const [search, setSearch] = useState(''); const [fillFilter, setFillFilter] = useState('all'); const [snapshotTick, setSnapshotTick] = useState(0); const [selectedRowKeys, setSelectedRowKeys] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [pageSize, setPageSize] = useState(10); const [discountVisible, setDiscountVisible] = useState(false); const [discount, setDiscount] = useState(0.2); const [discountMode, setDiscountMode] = useState('only_missing'); const [discountTarget, setDiscountTarget] = useState('filtered'); const [discountRunning, setDiscountRunning] = useState(false); const [historyModel, setHistoryModel] = useState(null); const [uncoveredTotal, setUncoveredTotal] = useState(0); const [uncoveredItems, setUncoveredItems] = useState([]); const [uncoveredVisible, setUncoveredVisible] = useState(false); const [advanced, setAdvanced] = useState(null); // 高级编辑(生效区间/备注) const [advancedSaving, setAdvancedSaving] = useState(false); // -------------------------------------------------------------------------- // 数据加载 // -------------------------------------------------------------------------- // 后端 GetPageQuery 将 page_size 硬截为 100:必须翻页拉全,否则 >100 渠道时下拉静默缺项 const loadChannels = useCallback(async () => { setChannelsLoading(true); try { const all = []; for (let p = 1; p <= 20; p++) { const res = await API.get( `/api/channel/?p=${p}&page_size=100&id_sort=true`, { skipErrorHandler: true }, ); if (!res.data.success) break; const items = res.data.data?.items || []; all.push(...items); const total = res.data.data?.total ?? 0; if (items.length === 0 || all.length >= total) break; } setChannels(all); setChannelId((prev) => { if (prev) return prev; const remembered = localStorage.getItem(CHANNEL_STORAGE_KEY); if (remembered && all.some((c) => String(c.id) === remembered)) { return remembered; } // 默认落在第一个启用渠道上:进页面即可用,不必先做一次无意义的选择 const first = all.find((c) => c.status === 1) || all[0]; return first ? String(first.id) : ''; }); } catch (e) { showError(t('加载渠道列表失败')); } finally { setChannelsLoading(false); } }, [t]); const load = useCallback(async () => { if (!channelId) { setScopeModels([]); setCostRows([]); setLoaded(false); return; } setLoading(true); try { const params = { scope: 'channel', scope_key: channelId }; // skipErrorHandler:全局拦截器对网络/HTTP 错误直接 showError(error)(英文原文), // 不跳过会与这里的中文提示双弹 const [sm, rows] = await Promise.all([ API.get('/api/commission/costs/scope_models', { params, skipErrorHandler: true, }), API.get('/api/commission/costs/', { params, skipErrorHandler: true }), ]); if (!sm.data.success) { showError(sm.data.message || t('加载渠道模型清单失败')); return; } if (!rows.data.success) { showError(rows.data.message || t('加载成本配置失败')); return; } setScopeModels(sm.data.data?.models || []); setOfficial(sm.data.data?.official || {}); setLegacyCount(sm.data.data?.legacy_non_channel || 0); setCostRows(rows.data.data || []); setNowTs(Math.floor(Date.now() / 1000)); setEdits({}); setDrafts({}); setErrors({}); setSelectedRowKeys([]); setSnapshotTick((v) => v + 1); setLoaded(true); } catch (e) { showError(t('加载成本配置失败,请重试')); } finally { setLoading(false); } }, [channelId, t]); const loadUncovered = useCallback(async () => { try { const res = await API.get('/api/commission/costs/uncovered', { params: { limit: 200 }, skipErrorHandler: true, }); if (res.data.success) { setUncoveredTotal(res.data.data.total || 0); setUncoveredItems(res.data.data.items || []); } } catch (e) { // 未覆盖清单仅作提示,失败不影响主流程 } }, []); useEffect(() => { loadChannels(); loadUncovered(); }, [loadChannels, loadUncovered]); useEffect(() => { load(); }, [load]); useEffect(() => { if (channelId) localStorage.setItem(CHANNEL_STORAGE_KEY, channelId); }, [channelId]); // 有未保存修改时离开页面给出浏览器级确认 const dirtyKeys = useMemo(() => Object.keys(edits), [edits]); useEffect(() => { if (dirtyKeys.length === 0) return undefined; const handler = (e) => { e.preventDefault(); e.returnValue = ''; }; window.addEventListener('beforeunload', handler); return () => window.removeEventListener('beforeunload', handler); }, [dirtyKeys.length]); // -------------------------------------------------------------------------- // 视图模型:一行 = 一个模型 // -------------------------------------------------------------------------- const channelOptions = useMemo( () => channels.map((c) => ({ value: String(c.id), label: `#${c.id} ${c.name}${c.status === 1 ? '' : t('(已禁用)')}`, })), [channels, t], ); const rows = useMemo(() => { const byModel = new Map(); const ensure = (name, base) => { let e = byModel.get(name); if (!e) { e = { model_name: name, platform_names: [], channel_names: [], enabled_channels: 0, declared: [], // slotMeta: slotKey -> { derivedRatio }。缓存槽位带厂商倍率, // 用于展示「未配置时会按什么价记账」并把官方输入牌价折算成缓存参照价 slotMeta: new Map(), orphan: true, // 先按「渠道已不提供」标记,命中清单时翻转 history: new Map(), ...base, }; byModel.set(name, e); } return e; }; scopeModels.forEach((m) => { const e = ensure(m.model_name, {}); e.platform_names = m.platform_names || []; e.channel_names = m.channel_names || []; e.enabled_channels = m.enabled_channels || 0; e.declared = (m.units || []).map((u) => slotKeyOf(u.unit, u.tier_key)); (m.units || []).forEach((u) => { e.slotMeta.set(slotKeyOf(u.unit, u.tier_key), { derivedRatio: u.derived_ratio || 0, }); }); e.orphan = false; }); // 已有成本行:渠道不再提供的模型也要显示(否则配置看不见、删不掉,却仍在四级查找里生效) costRows.forEach((r) => { const e = ensure(r.model_name, {}); const k = slotKeyOf(r.unit, r.tier_key); if (!e.history.has(k)) e.history.set(k, []); e.history.get(k).push(r); }); const out = []; byModel.forEach((e) => { // 槽位 = 清单声明的单位 ∪ 已有配置出现过的单位(手工加的 cached_input_1m 等不能漏) const slots = Array.from(new Set([...e.declared, ...e.history.keys()])); slots.sort((a, b) => { const order = Object.keys(UNIT_META); const pa = parseSlotKey(a); const pb = parseSlotKey(b); const d = order.indexOf(pa.unit) - order.indexOf(pb.unit); return d !== 0 ? d : pa.tier.localeCompare(pb.tier); }); const effective = new Map(); e.history.forEach((list, k) => { list.sort((a, b) => b.effective_from - a.effective_from); const hit = list.find( (r) => r.effective_from <= nowTs && (r.effective_to === 0 || nowTs < r.effective_to), ); if (hit) effective.set(k, hit); }); // 官方牌价:上游真名优先,其次平台售卖名(映射渠道下两者不同) let op = official[e.model_name]; if (!op) { for (const p of e.platform_names) { if (official[p]) { op = official[p]; break; } } } out.push({ ...e, slots, effective, official: op || null }); }); out.sort((a, b) => a.model_name.localeCompare(b.model_name)); return out; }, [scopeModels, costRows, official, nowTs]); const rowByModel = useMemo(() => { const m = new Map(); rows.forEach((r) => m.set(r.model_name, r)); return m; }, [rows]); // 某槽位的当前值(草稿 > 编辑 > 已保存) const slotValue = useCallback( (row, slotKey) => { const fk = fieldKeyOf(row.model_name, slotKey); if (drafts[fk] !== undefined) return drafts[fk]; if (fk in edits) { return edits[fk] === null ? '' : edits[fk]; } const cur = row.effective.get(slotKey); return cur ? cur.cost_uyuan_per_unit / UYUAN_PER_YUAN : ''; }, [drafts, edits], ); // 实时填写状态(计数与行内标记用)。只按【必填】槽位判定:缓存读取/创建留空会由后端 // 按倍率派生,把它们算进缺口会让所有支持缓存的模型永远停在「部分配置」,这个状态也就 // 失去了指示意义。 const liveStateOf = useCallback( (row) => { const required = row.slots; if (required.length === 0) return FILL_EMPTY; let filled = 0; required.forEach((k) => { if (isPositive(slotValue(row, k))) filled += 1; }); if (filled === 0) return FILL_EMPTY; return filled === required.length ? FILL_FILLED : FILL_PARTIAL; }, [slotValue], ); // 分类快照(列表过滤口径):故意不依赖编辑态。跟着按键实时重算会让正在编辑的 // 那一行立刻被过滤掉——这正是「在未配置页输一个值就跳走」的成因。 const snapshot = useMemo(() => { const map = {}; rows.forEach((r) => { map[r.model_name] = liveStateOf(r); }); return map; // eslint-disable-next-line react-hooks/exhaustive-deps }, [rows, fillFilter, snapshotTick]); const counts = useMemo(() => { const c = { total: rows.length, filled: 0, partial: 0, empty: 0 }; rows.forEach((r) => { const s = liveStateOf(r); if (s === FILL_FILLED) c.filled += 1; else if (s === FILL_PARTIAL) c.partial += 1; else c.empty += 1; }); return c; }, [rows, liveStateOf]); const staleCount = useMemo(() => { if (fillFilter === 'all') return 0; return rows.filter((r) => snapshot[r.model_name] !== liveStateOf(r)).length; }, [rows, snapshot, liveStateOf, fillFilter]); const orphanRows = useMemo(() => rows.filter((r) => r.orphan), [rows]); const filteredRows = useMemo(() => { let result = rows; const kw = search.trim().toLowerCase(); if (kw) { result = result.filter( (r) => r.model_name.toLowerCase().includes(kw) || (r.platform_names || []).some((p) => p.toLowerCase().includes(kw)), ); } if (fillFilter !== 'all') { const want = fillFilter === 'filled' ? FILL_FILLED : fillFilter === 'partial' ? FILL_PARTIAL : FILL_EMPTY; result = result.filter((r) => snapshot[r.model_name] === want); } return result; }, [rows, search, fillFilter, snapshot]); useEffect(() => { setCurrentPage(1); }, [search, fillFilter, channelId]); // 数据缩减后钳制当前页,避免停留在越界空页 useEffect(() => { const maxPage = Math.max(1, Math.ceil(filteredRows.length / pageSize)); if (currentPage > maxPage) setCurrentPage(maxPage); }, [filteredRows.length, pageSize, currentPage]); // 选中集始终收敛到可见行:筛选把已选行藏起来后,批量操作不得误伤看不见的行 useEffect(() => { setSelectedRowKeys((prev) => { const next = prev.filter((n) => filteredRows.some((r) => r.model_name === n), ); return next.length === prev.length ? prev : next; }); }, [filteredRows]); // -------------------------------------------------------------------------- // 编辑 // -------------------------------------------------------------------------- const updateSlot = (row, slotKey, value) => { const fk = fieldKeyOf(row.model_name, slotKey); const cur = row.effective.get(slotKey); const savedYuan = cur ? cur.cost_uyuan_per_unit / UYUAN_PER_YUAN : null; const isEmpty = value === '' || value === null || value === undefined; const num = isEmpty ? null : Number(value); const valid = !isEmpty && Number.isFinite(num) && num > 0; // 非法值原样保留在输入框(受控组件下抹掉 = 用户白输),并给出行内错误 setDrafts((prev) => { const next = { ...prev }; if (isEmpty || valid) delete next[fk]; else next[fk] = value; return next; }); setErrors((prev) => { const next = { ...prev }; if (isEmpty || valid) delete next[fk]; else if (!Number.isFinite(num)) next[fk] = t('请输入数字'); else next[fk] = t('成本单价必须大于 0'); return next; }); setEdits((prev) => { const next = { ...prev }; if (isEmpty) { // 清空:有已保存版本 → 标记删除;本就没有 → 回到无改动 if (cur) next[fk] = null; else delete next[fk]; } else if (valid) { if (savedYuan !== null && Math.abs(savedYuan - num) < 1e-12) { delete next[fk]; // 改回原值 = 没改 } else { next[fk] = num; } } else { delete next[fk]; // 非法值不进提交集,仅停留在 drafts + errors } return next; }); }; const clearModel = (row) => { row.slots.forEach((k) => updateSlot(row, k, '')); }; const resetEdits = () => { setEdits({}); setDrafts({}); setErrors({}); setSnapshotTick((v) => v + 1); }; // 切渠道会整份重载,行内未保存的改价会被无声丢弃——切之前必须问一句 const switchChannel = (id) => { const next = id || ''; if (next === channelId) return; if (Object.keys(edits).length === 0) { setChannelId(next); return; } Modal.confirm({ title: t('切换渠道将丢弃未保存的修改'), content: t('当前有 {{count}} 项成本价改动尚未保存,切换渠道后将丢失。', { count: Object.keys(edits).length, }), okText: t('放弃修改并切换'), cancelText: t('留在当前渠道'), onOk: () => setChannelId(next), }); }; // 待提交拆分:改价走版本化 apply,清空走删除 const pending = useMemo(() => { const items = []; const deleteIds = []; Object.entries(edits).forEach(([fk, v]) => { const { modelName, slotKey } = parseFieldKey(fk); const row = rowByModel.get(modelName); if (!row) return; const { unit, tier } = parseSlotKey(slotKey); if (v === null) { const cur = row.effective.get(slotKey); if (cur) deleteIds.push(cur.id); return; } items.push({ model_name: modelName, unit, tier_key: tier, cost_uyuan_per_unit: Math.round(v * UYUAN_PER_YUAN), note: '', }); }); return { items, deleteIds }; }, [edits, rowByModel]); const errorCount = Object.keys(errors).length; const dirty = pending.items.length > 0 || pending.deleteIds.length > 0; const doSave = async () => { if (errorCount > 0) { showError(t('存在非法输入,请先修正标红的价格')); return; } if (!dirty) { showWarning(t('你似乎并没有修改什么')); return; } // 微元取整后仍须为正:0.0000001 这类值 round 后为 0,后端会拒收 const zero = pending.items.find((i) => i.cost_uyuan_per_unit <= 0); if (zero) { showError( t('{{model}} 的单价过小(不足 0.000001 元),无法保存', { model: zero.model_name, }), ); return; } const from = effectiveFrom ? Math.floor(new Date(effectiveFrom).getTime() / 1000) : 0; setSaving(true); try { let ok = true; if (pending.items.length > 0) { const res = await API.post( '/api/commission/costs/apply', { scope: 'channel', scope_key: channelId, effective_from: from, mode: 'new_version', items: pending.items, }, { skipErrorHandler: true }, ); const d = res.data?.data || {}; if (res.data?.success) { showSuccess( t( '已保存:新增 {{created}} 条,改价 {{updated}} 条,归档旧版本 {{closed}} 条', { created: d.created || 0, updated: d.updated || 0, closed: d.closed || 0, }, ), ); } else { ok = false; const fails = d.failures || []; showError( t('{{value}}{{value2}}', { value: res.data?.message || t('部分保存失败'), value2: fails.length ? ': ' + fails.slice(0, 3).join('; ') : '', }), ); } } if (pending.deleteIds.length > 0) { const res = await API.post( '/api/commission/costs/batch_delete', { ids: pending.deleteIds }, { skipErrorHandler: true }, ); if (res.data?.success) { showSuccess( t('已删除 {{count}} 条成本配置', { count: res.data.data?.deleted ?? pending.deleteIds.length, }), ); } else { ok = false; showError(res.data?.message || t('删除失败')); } } await load(); if (ok) await loadUncovered(); } catch (e) { showError(t('保存失败,请重试')); await load(); } finally { setSaving(false); } }; const onSave = () => { if (pending.deleteIds.length === 0) { doSave(); return; } // 清空 = 删除生效中的成本配置,删掉后这些消耗会退回「官方牌价 × 兜底折扣」预估, // 与改价的后果完全不同,必须显式确认 Modal.confirm({ title: t('确认保存?其中包含删除操作'), content: t( '有 {{del}} 项单价被清空,保存后对应的成本配置将被删除;这些模型的消耗将退回「官方牌价 × 兜底折扣」预估并在账单标记。另有 {{upd}} 项调价。', { del: pending.deleteIds.length, upd: pending.items.length }, ), okText: t('确认保存'), cancelText: t('取消'), onOk: doSave, }); }; // -------------------------------------------------------------------------- // 批量折扣 // -------------------------------------------------------------------------- const discountTargets = useMemo( () => discountTarget === 'selected' ? rows.filter((r) => selectedRowKeys.includes(r.model_name)) : filteredRows, [discountTarget, rows, selectedRowKeys, filteredRows], ); // 缺官方牌价的模型算不出折扣价,必须在弹窗里先说清楚会漏掉多少 const discountMissing = useMemo( () => discountTargets.filter((r) => !r.official).length, [discountTargets], ); const runDiscount = async () => { const d = discount === '' ? NaN : Number(discount); if (!Number.isFinite(d) || d <= 0 || d > 1) { showError(t('折扣必须在 (0,1] 区间')); return; } if (discountTargets.length === 0) { showError(t('没有可应用的模型')); return; } if (dirty) { showError(t('请先保存或撤销行内的未保存修改,再执行批量折扣')); return; } const from = effectiveFrom ? Math.floor(new Date(effectiveFrom).getTime() / 1000) : 0; setDiscountRunning(true); try { const res = await API.post( '/api/commission/costs/generate', { scope: 'channel', scope_key: channelId, discount: d, effective_from: from, mode: discountMode, model_names: discountTargets.map((r) => r.model_name), }, { skipErrorHandler: true }, ); if (res.data?.success) { const r = res.data.data || {}; showSuccess( t( '已应用:新增 {{created}} 条,改价 {{updated}} 条,归档旧版本 {{closed}} 条,跳过 {{skipped}} 条', { created: r.created || 0, updated: r.updated || 0, closed: r.closed || 0, skipped: r.skipped || 0, }, ), ); if ((r.missing_official || []).length > 0) { showWarning( t('有 {{count}} 个模型未填官方牌价,已跳过:{{names}}', { count: r.missing_official.length, names: r.missing_official.slice(0, 5).join('、'), }), ); } // 写库失败必须显式呈现:不报的话表现为「绿色成功 + 那几档静默没有成本价」, // 之后只能靠毛利异常反查(后端同时把失败数写进了管理审计) if ((r.failures || []).length > 0) { showError( t('有 {{count}} 条成本价写入失败:{{names}}', { count: r.failures.length, names: r.failures.slice(0, 3).join(';'), }), ); } setDiscountVisible(false); await load(); await loadUncovered(); } else { showError(res.data?.message || t('批量应用失败')); } } catch (e) { showError(t('批量应用失败,请重试')); } finally { setDiscountRunning(false); } }; // -------------------------------------------------------------------------- // 单条高级编辑 / 删除 // -------------------------------------------------------------------------- const submitAdvanced = async () => { const a = advanced; const yuanNum = a.yuan === '' ? NaN : Number(a.yuan); const uyuan = Number.isFinite(yuanNum) ? Math.round(yuanNum * UYUAN_PER_YUAN) : 0; if (uyuan <= 0) { showError(t('请填写大于 0 的成本单价')); return; } if (!a.effective_from) { showError(t('请选择生效时间')); return; } const from = Math.floor(new Date(a.effective_from).getTime() / 1000); const to = a.effective_to ? Math.floor(new Date(a.effective_to).getTime() / 1000) : 0; if (to !== 0 && to <= from) { showError(t('失效时间必须晚于生效时间')); return; } setAdvancedSaving(true); try { // 整行回传(保留 created_at / created_by 等原字段),仅覆盖界面上可改的字段 const res = await API.put( '/api/commission/costs/', [ { ...a.base, cost_uyuan_per_unit: uyuan, effective_from: from, effective_to: to, note: (a.note || '').trim(), }, ], { skipErrorHandler: true }, ); if (res.data?.success) { showSuccess(t('保存成功')); setAdvanced(null); await load(); } else { const fails = res.data?.data?.failures || []; showError( t('{{value}}{{value2}}', { value: res.data?.message || t('保存失败'), value2: fails.length ? ': ' + fails.join('; ') : '', }), ); } } catch (e) { showError(t('保存失败,请重试')); } finally { setAdvancedSaving(false); } }; const deleteRow = async (id) => { try { const res = await API.delete(`/api/commission/costs/${id}`, { skipErrorHandler: true, }); if (res.data?.success) { showSuccess(t('已删除')); await load(); } else showError(res.data?.message || t('删除失败')); } catch (e) { showError(t('删除失败,请重试')); } }; // -------------------------------------------------------------------------- // 渲染片段 // -------------------------------------------------------------------------- // 该槽位的官方参照价。缓存读/写没有独立牌价——各厂商就是按输入价的倍数定价的, // 所以参照价 = 官方输入价 × 缓存倍率。不乘倍率会把「缓存创建按 1.25× 收费」误算成 // 相对输入价的 125%,折扣列于是显示「高于官方价」,一整列红着毫无参考价值。 const officialOfSlot = (row, slotKey) => { if (!row.official) return undefined; const { unit, tier } = parseSlotKey(slotKey); const meta = UNIT_META[unit]; if (!meta || !meta.official) return undefined; // 分档类:逐档取牌价(档位键大小写不敏感,与收入侧同口径) if (meta.tiered) return tierPriceOf(row.official, meta.official, tier); // 缓存类:原厂页显式填了缓存牌价就直接用;没填才按厂商倍率从输入价折算 if (meta.officialCache && isPositive(row.official[meta.officialCache])) { return row.official[meta.officialCache]; } const v = row.official[meta.official]; if (!isPositive(v)) return undefined; const ratio = row.slotMeta.get(slotKey)?.derivedRatio; return ratio > 0 ? v * ratio : v; }; const renderOfficial = (row) => { if (!row.official) { return ( {t('未填官方价')} ); } const { input, output, per_call: perCall } = row.official; // 缓存类的官方参照价按倍率派生展示,与右侧「相对官方价」列的口径保持一致 const cacheRefs = row.slots .map((k) => { const meta = UNIT_META[parseSlotKey(k).unit]; if (!meta?.officialCache) return null; const explicit = row.official[meta.officialCache]; if (isPositive(explicit)) { return { key: k, label: t(meta.label), price: explicit, ratio: 0 }; } const m = row.slotMeta.get(k); if (!(m?.derivedRatio > 0) || !isPositive(input)) return null; return { key: k, label: t(meta.label), ratio: m.derivedRatio, price: Number((input * m.derivedRatio).toFixed(6)), }; }) .filter(Boolean); // 分档类(按秒/按分辨率):逐档展示原厂牌价,与左侧逐档成本输入框一一对齐 const tierRefs = row.slots .map((k) => { const { unit, tier } = parseSlotKey(k); const meta = UNIT_META[unit]; if (!meta?.tiered) return null; const price = tierPriceOf(row.official, meta.official, tier); if (!isPositive(price)) return null; return { key: k, tier, price, suffix: meta.suffix }; }) .filter(Boolean); // 官方价条目存在、却没有一项与当前计费形态匹配(典型成因:档位被下线、 // 模型改过计费方式)。不点名的话这一列渲染成空白,管理员分不清"没填"与 // "填了但不匹配",只能去原厂价页逐个翻。 if ( !isPositive(input) && !isPositive(output) && !isPositive(perCall) && tierRefs.length === 0 && cacheRefs.length === 0 ) { return ( {t('官方价不匹配')} ); } return (
{isPositive(input) && (
{t('输入')} ¥{input} / 1M
)} {isPositive(output) && (
{t('输出')} ¥{output} / 1M
)} {isPositive(perCall) && (
¥{perCall} / {t('次')}
)} {tierRefs.map((r) => (
{r.tier} ¥{r.price} {t(r.suffix)}
))} {cacheRefs.map((r) => (
{r.label} ¥{r.price} / 1M({r.ratio} {I18N_TECHNICAL_TEXT.MULTIPLIER_CLOSE_CJK}
))}
); }; const renderCostEditor = (row) => { if (row.slots.length === 0) { return ( {t('该模型无需配置成本单位')} ); } return ( {row.slots.map((k) => { const { unit, tier } = parseSlotKey(k); const meta = UNIT_META[unit] || { label: unit, suffix: '' }; const fk = fieldKeyOf(row.model_name, k); const err = errors[fk]; const marked = edits[fk] === null; const declared = row.declared.includes(k); const slotMeta = row.slotMeta.get(k); // 缓存槽位(有厂商倍率的槽位)未填时后端会推算,把推算结果直接算给用户看, // 否则「不填会按什么价记账」全靠猜。这两项仍然是必填——目标是扣费的每一项 // 都有显式成本价,推算只是不至于算成 0 的兜底。 const isCache = slotMeta?.derivedRatio > 0; const derivedFrom = isCache ? slotValue(row, slotKeyOf('input_1m', '')) : null; const derivedValue = isCache && isPositive(derivedFrom) ? derivedFrom * slotMeta.derivedRatio : null; return (
} value={slotValue(row, k)} step={0.01} hideButtons validateStatus={err ? 'error' : 'default'} style={{ width: 210 }} placeholder={t('成本单价')} onChange={(v) => updateSlot(row, k, v)} /> {err && (
{err}
)} {isCache && !isPositive(slotValue(row, k)) && !err && (
{derivedValue !== null ? t('未填 → 暂按 {{ratio}}× 推算 ¥{{price}}/1M', { ratio: slotMeta.derivedRatio, price: Number(derivedValue.toFixed(6)), }) : t('未填 → 暂按输入价 × {{ratio}}× 推算', { ratio: slotMeta.derivedRatio, })}
)} {marked && (
{t('保存后将删除该单价')}
)} {/* orphan 行的 declared 恒空,逐个单位再标一次「额外单位」纯属噪音—— 行头的「渠道已不提供」已经把话说完了 */} {!declared && !marked && !row.orphan && (
{t('额外单位')}
)}
); })}
); }; const renderDiscountCol = (row) => { if (row.slots.length === 0) return -; const lines = row.slots .map((k) => { const off = officialOfSlot(row, k); const cost = slotValue(row, k); if (!isPositive(cost)) return null; const meta = UNIT_META[parseSlotKey(k).unit] || {}; const label = t(meta.label || parseSlotKey(k).unit); if (off === undefined) { return (
{label}{' '} {t('无官方价')}
); } const ratio = computeDiscountRatio(cost, off); return (
{label}{' '} {ratio === null ? ( {t('高于官方价')} ) : ( {formatDiscountLabel(ratio, i18next.language)} )}
); }) .filter(Boolean); if (lines.length === 0) return -; return
{lines}
; }; const renderFillTag = (row) => { const s = liveStateOf(row); if (s === FILL_FILLED) { return ( {t('已配置')} ); } if (s === FILL_PARTIAL) { return ( {t('部分配置')} ); } return ( {t('未配置')} ); }; const historyCount = (row) => { let n = 0; row.history.forEach((list) => { n += list.length; }); return n; }; const columns = [ { title: t('模型(上游名)'), dataIndex: 'model_name', sorter: (a, b) => a.model_name.localeCompare(b.model_name), render: (text, row) => (
{text}
{row.orphan && ( {t('渠道已不提供')} )} {!row.orphan && row.enabled_channels === 0 && ( {t('渠道已禁用')} )} {row.platform_names .filter((p) => p !== row.model_name) .map((p) => ( {p} ))}
), }, { title: ( {t('官方牌价')} ), dataIndex: 'official', width: 170, render: (_, row) => renderOfficial(row), }, { title: t('成本单价(¥,不含税)'), dataIndex: 'cost', width: 260, render: (_, row) => renderCostEditor(row), }, { title: ( {t('相对官方价')} ), dataIndex: 'discount', width: 150, render: (_, row) => renderDiscountCol(row), }, { title: t('状态'), dataIndex: 'state', width: 110, render: (_, row) => renderFillTag(row), }, { title: t('操作'), dataIndex: 'op', width: 160, render: (_, row) => ( ), }, ]; const historyRow = historyModel ? rowByModel.get(historyModel) : null; const historyList = useMemo(() => { if (!historyRow) return []; const out = []; historyRow.history.forEach((list, k) => { const { unit, tier } = parseSlotKey(k); list.forEach((r) => out.push({ ...r, _unit: unit, _tier: tier })); }); out.sort( (a, b) => a._unit.localeCompare(b._unit) || b.effective_from - a.effective_from, ); return out; }, [historyRow]); const selectedChannel = channels.find((c) => String(c.id) === channelId); const emptyText = !channelId ? t('请先在上方选择一个渠道') : rows.length === 0 ? t('该渠道未配置任何模型,请先在渠道编辑页填写模型列表') : t('没有符合当前搜索与筛选条件的模型'); return (
{legacyCount > 0 && ( )} {orphanRows.length > 0 && ( r.model_name) .join('、'), }, )} /> )} {/* 渠道选择:本页的主轴,独占一行以免被工具条挤成一个不起眼的下拉 */}
{t('渠道')} } placeholder={t('搜索模型名')} value={search} onChange={setSearch} showClear style={{ width: 200 }} /> { setFillFilter(e.target.value); setSnapshotTick((v) => v + 1); }} > {t('全部')} ({counts.total}) {t('已配置')} ({counts.filled}) {t('部分配置')} ({counts.partial}) {t('未配置')} ({counts.empty}) {errorCount > 0 && ( {t('{{count}} 处非法输入', { count: errorCount })} )} {dirty && errorCount === 0 && ( {t('{{count}} 项未保存', { count: pending.items.length + pending.deleteIds.length, })} )} {uncoveredTotal > 0 && ( )} {/* errorCount 也要放行:只剩非法输入时 dirty 为 false, 不给撤销入口的话满屏标红既存不下也清不掉,只能逐个手动删 */} {(dirty || errorCount > 0) && ( )}
{/* 生效时间:默认立即。留在工具条里,避免用户在弹窗里改完、行内保存时却不生效 */}
{t('生效时间')} setEffectiveFrom(d || null)} showClear placeholder={t('立即生效')} style={{ width: 200 }} /> {t( '保存与批量定价都以该时刻生效:此前的消耗仍按旧成本记账,旧版本自动归档留痕。', )}
{fillFilter !== 'all' && (
{t( '筛选结果按进入筛选时的状态固定,编辑中的行不会突然消失;上方计数为实时值。', )} {staleCount > 0 && ( )}
)} setSelectedRowKeys(keys || []), }} pagination={{ currentPage, pageSize, total: filteredRows.length, showSizeChanger: true, pageSizeOpts: [10, 20, 50, 100], onPageChange: setCurrentPage, onPageSizeChange: (size) => { setPageSize(size); setCurrentPage(1); }, }} empty={emptyText} /> {/* ---------------------------------------------------------------- */} setDiscountVisible(false)} width={560} >
{t('折扣(相对官方牌价)')}
{Number.isFinite(Number(discount)) && Number(discount) > 0 ? t('即官方价的 {{label}}', { label: formatDiscountLabel( Number(discount), i18next.language, ) || t('原价'), }) : t('例:0.2 表示按官方价 2 折作为成本')}
{t('应用范围')} setDiscountTarget(e.target.value)} > {t('当前列表全部模型')}({filteredRows.length}) {t('已勾选的模型')}({selectedRowKeys.length})
{t('对已有成本价的模型')} setDiscountMode(e.target.value)} > {t('跳过(仅补缺失)')} {t('覆盖(新开一版价格)')}
{discountMissing > 0 && ( {t( '其中 {{count}} 个模型未填官方牌价,算不出折扣价,将被跳过——请先到「模型原厂价格」补齐。', { count: discountMissing }, )} )} {t('生效时间:{{time}}(在页面工具条上调整)', { time: effectiveFrom ? new Date(effectiveFrom).toLocaleString() : t('立即'), })}
{/* ---------------------------------------------------------------- */} setHistoryModel(null)} width={860} >
( {t((UNIT_META[r._unit] || {}).label || r._unit)} {r._tier ? ` · ${r._tier}` : ''} ), }, { title: t('成本单价(¥)'), render: (_, r) => ( {formatYuan(r.cost_uyuan_per_unit)} ), }, { title: t('生效区间'), render: (_, r) => { const live = r.effective_from <= nowTs && (r.effective_to === 0 || nowTs < r.effective_to); return (
{fmtTs(r.effective_from)} ~{' '} {r.effective_to ? fmtTs(r.effective_to) : t('长期')} {live && ( {t('生效中')} )}
); }, }, { title: t('备注'), dataIndex: 'note', render: (v) => v || '—' }, { title: t('操作'), render: (_, r) => ( deleteRow(r.id)} > ), }, ]} dataSource={historyList} rowKey='id' pagination={false} empty={t('该模型暂无成本价版本')} /> {/* ---------------------------------------------------------------- */} setAdvanced(null)} width={460} > {advanced && ( {advanced.base.model_name} ·{' '} {t( (UNIT_META[advanced.base.unit] || {}).label || advanced.base.unit, )} {advanced.base.tier_key ? ` · ${advanced.base.tier_key}` : ''}
{t('成本单价(¥,不含税)')} setAdvanced((p) => ({ ...p, yuan: v }))} min={0} max={1000000} hideButtons style={{ width: '100%' }} />
{t('生效时间')} setAdvanced((p) => ({ ...p, effective_from: d })) } style={{ width: '100%' }} />
setAdvanced((p) => ({ ...p, effective_to: d || null })) } showClear style={{ width: '100%' }} />
{t('备注')} setAdvanced((p) => ({ ...p, note: v }))} maxLength={255} style={{ width: '100%' }} />
)}
{/* ---------------------------------------------------------------- */} setUncoveredVisible(false)} width={780} >
`#${r.channel_id} ${r.channel_name}`, }, { title: t('模型(上游名)'), dataIndex: 'model_name' }, { title: t('计量单位'), dataIndex: 'unit', render: (u) => t((UNIT_META[u] || {}).label || u), }, { title: t('档位'), dataIndex: 'tier_key', render: (v) => v || '—', }, { title: t('操作'), render: (_, r) => ( ), }, ]} dataSource={uncoveredItems} rowKey={(r) => `${r.channel_id}-${r.model_name}-${r.unit}-${r.tier_key}` } pagination={{ pageSize: 10 }} /> {t( '这些组合的消耗将按「官方牌价 × 兜底折扣」预估成本,并在账单标记「含预估成本」。点「去配置」会切到对应渠道并定位到该模型。', )} ); }