From 512ca52262d43df34cb9bccfccc17a965478bdc4 Mon Sep 17 00:00:00 2001 From: WangLX <519407855@qq.com> Date: Mon, 12 Oct 2026 17:42:30 +0800 Subject: [PATCH] fix: reconcile source currencies and retail token pricing --- .../controlplane/catalog/CatalogService.java | 16 +- ...e_source_currency_and_retail_discounts.sql | 44 +++++ .../catalog/CatalogServiceTest.java | 13 ++ docs/18-pricing-currency-and-discounts.md | 61 +++++++ prototype/src/components/CatalogAdmin.vue | 34 +++- prototype/src/services/catalog.ts | 1 + prototype/src/services/pricing.ts | 32 +++- prototype/tests/pricing.test.mjs | 23 ++- scripts/package-deployment.ps1 | 2 +- scripts/reconcile-pricing.py | 156 ++++++++++++++++++ scripts/test_pricing_migration.py | 57 +++++++ scripts/test_reconcile_pricing.py | 31 ++++ 12 files changed, 458 insertions(+), 12 deletions(-) create mode 100644 control-plane-java/src/main/resources/db/migration/V34__reconcile_source_currency_and_retail_discounts.sql create mode 100644 docs/18-pricing-currency-and-discounts.md create mode 100644 scripts/reconcile-pricing.py create mode 100644 scripts/test_pricing_migration.py create mode 100644 scripts/test_reconcile_pricing.py diff --git a/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java b/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java index cc3100e..fe7806c 100644 --- a/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java +++ b/control-plane-java/src/main/java/com/moyi/controlplane/catalog/CatalogService.java @@ -230,8 +230,22 @@ public class CatalogService { return findModel(id); } - private void validatePricing(Object input) { + static void validatePricing(Object input) { if (!(input instanceof Map prices)) return; + if (prices.get("listPriceUsd") != null && prices.get("listPriceCny") != null) + throw new ApiException("INVALID_PRICE", "标准价只能选择一种币种:人民币或美元"); + Object discount = prices.get("discount"); + if (discount != null) { + try { + var value = new java.math.BigDecimal(String.valueOf(discount)); + if (value.signum() < 0 || value.compareTo(java.math.BigDecimal.TEN) > 0) throw new NumberFormatException(); + } catch (NumberFormatException e) { throw new ApiException("INVALID_PRICE", "折扣须在 0–10 折之间,例如 5.5 表示 5.5 折"); } + } + if (prices.get("listPriceCny") != null && prices.get("exchangeRate") != null) { + try { + if (new java.math.BigDecimal(String.valueOf(prices.get("exchangeRate"))).compareTo(java.math.BigDecimal.ONE) != 0) throw new NumberFormatException(); + } catch (NumberFormatException e) { throw new ApiException("INVALID_PRICE", "人民币原价的换算系数必须为 1"); } + } for(String field: List.of("price","input","output","cachedInput")) { Object amount=prices.get(field); if(amount==null) continue; diff --git a/control-plane-java/src/main/resources/db/migration/V34__reconcile_source_currency_and_retail_discounts.sql b/control-plane-java/src/main/resources/db/migration/V34__reconcile_source_currency_and_retail_discounts.sql new file mode 100644 index 0000000..eafce78 --- /dev/null +++ b/control-plane-java/src/main/resources/db/migration/V34__reconcile_source_currency_and_retail_discounts.sql @@ -0,0 +1,44 @@ +-- Verified 2026-10-12: current source currency; purchase discount + 1 point. +-- Exact old JSON guard preserves later manual edits. Does not change enabled status, credentials or balances. +-- Dynamic, missing-source and extreme-increase rows are deliberately excluded. +WITH correction(provider_code, upstream_model, old_pricing, new_pricing) AS (VALUES + ('apipro', 'deepseek-v4-flash', '{"unit":"CNY / 1M tokens","input":0.66924,"output":1.33848,"discount":6.5,"cachedInput":0.13572,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.143,"output":0.286,"cachedInput":0.029},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":2.005848,"output":6.017076,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":0.2005848,"listPriceUsd":{"input":0.4286,"output":1.2856999999999206,"cachedInput":0.04286}}'::jsonb), + ('apipro', 'deepseek-v4-pro', '{"unit":"CNY / 1M tokens","input":8.0262,"output":16.04772,"discount":6.5,"cachedInput":0.66924,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":1.715,"output":3.429,"cachedInput":0.143},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":8.0262,"output":16.04772,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":0.66924,"listPriceUsd":{"input":1.715,"output":3.429000000000015,"cachedInput":0.14299999999957}}'::jsonb), + ('apipro', 'kimi-k3', '{"unit":"CNY / 1M tokens","input":13.371696,"output":66.857076,"discount":6.5,"cachedInput":1.337076,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":2.8572,"output":14.2857,"cachedInput":0.2857},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":13.371696,"output":66.857076,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":1.337076,"listPriceUsd":{"input":2.8572,"output":14.28570000000012,"cachedInput":0.2856999996}}'::jsonb), + ('apihub', 'kimi-k3', '{"unit":"CNY / 1M tokens","input":40.76352,"output":203.8176,"discount":2.8,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":20.22,"output":101.1},"discountLabel":"2.8折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":5.6,"output":28.0,"discount":2.8,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"2.8折","listPriceCny":{"input":20.0,"output":100.0}}'::jsonb), + ('tokenfoundryx', 'claude-fable-5-1', '{"unit":"CNY / 1M tokens","input":36,"output":180,"discount":5,"cachedInput":0.9,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":10,"output":50,"cachedInput":0.25},"discountLabel":"5.0折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":36.0,"output":180.0,"discount":5.0,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"5折","cachedInput":3.6,"listPriceUsd":{"input":10.0,"output":50.0,"cachedInput":1.0}}'::jsonb), + ('apipro', 'claude-opus-5', '{"unit":"CNY / 1M tokens","input":20.16,"output":100.8,"discount":5.6,"cachedInput":1.008,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":25,"cachedInput":0.25},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":20.16,"output":100.8,"discount":5.6,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"5.6折","cachedInput":2.016,"listPriceUsd":{"input":5.0,"output":25.0,"cachedInput":0.5}}'::jsonb), + ('apipro', 'deepseek-v3', '{"unit":"CNY / 1M tokens","input":1.34215848,"output":5.368428,"discount":6.5,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.286786,"output":1.1471},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.34215714,"output":5.36862857,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","listPriceUsd":{"input":0.286785714,"output":1.147142856}}'::jsonb), + ('apipro', 'deepseek-v3-0324', '{"unit":"CNY / 1M tokens","input":1.34215848,"output":5.368428,"discount":6.5,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.286786,"output":1.1471},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.34215714,"output":5.36862857,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","listPriceUsd":{"input":0.286785714,"output":1.147142856}}'::jsonb), + ('apipro', 'deepseek-v3.1', '{"unit":"CNY / 1M tokens","input":2.68431228,"output":8.052876,"discount":6.5,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.573571,"output":1.7207},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":2.68431428,"output":8.05294285,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","listPriceUsd":{"input":0.573571428,"output":1.720714284}}'::jsonb), + ('apipro', 'deepseek-v3.2', '{"unit":"CNY / 1M tokens","input":1.34215848,"output":2.01323772,"discount":6.5,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.286786,"output":0.430179},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.34215714,"output":2.01323571,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","listPriceUsd":{"input":0.286785714,"output":0.430178571}}'::jsonb), + ('apipro', 'deepseek-v4-flash-0731', '{"unit":"CNY / 1M tokens","input":0.66924,"output":1.33848,"discount":6.5,"cachedInput":0.13572,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.143,"output":0.286,"cachedInput":0.029},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":2.005848,"output":6.017076,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":0.2005848,"listPriceUsd":{"input":0.4286,"output":1.2856999999999206,"cachedInput":0.04286}}'::jsonb), + ('apipro', 'gemini-2.5-flash', '{"unit":"CNY / 1M tokens","input":1.2096,"output":10.08,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.3,"output":2.5},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.2096,"output":10.08,"discount":5.6,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"5.6折","listPriceUsd":{"input":0.3,"output":2.4999999999}}'::jsonb), + ('tokenfoundryx', 'gemini-2.5-flash-lite', '{"unit":"CNY / 1M tokens","input":540,"output":2160,"cachedInput":null,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":75,"output":300},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":189.0,"output":756.0,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"3.5折","discount":3.5,"listPriceUsd":{"input":75.0,"output":300.0}}'::jsonb), + ('tokenfoundryx', 'gemini-2.5-pro', '{"unit":"CNY / 1M tokens","input":540,"output":4320,"cachedInput":null,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":75,"output":600},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":3.15,"output":25.2,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"3.5折","discount":3.5,"cachedInput":0.315,"listPriceUsd":{"input":1.25,"output":10.0,"cachedInput":0.125}}'::jsonb), + ('apipro', 'gemini-3.5-flash-lite', '{"unit":"CNY / 1M tokens","input":1.2096,"output":10.08,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.3,"output":2.5},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.2096,"output":10.08,"discount":5.6,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"5.6折","listPriceUsd":{"input":0.3,"output":2.4999999999999}}'::jsonb), + ('tokenfoundryx', 'gemini-3.7-flash', '{"unit":"CNY / 1M tokens","input":5.4,"output":27,"cachedInput":0.54,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.75,"output":3.75,"cachedInput":0.075},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.89,"output":9.45,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"3.5折","discount":3.5,"cachedInput":0.189,"listPriceUsd":{"input":0.75,"output":3.75,"cachedInput":0.075}}'::jsonb), + ('tokenfoundryx', 'gemini-3.8-flash', '{"unit":"CNY / 1M tokens","input":5.4,"output":27,"cachedInput":0.54,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.75,"output":3.75,"cachedInput":0.075},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.89,"output":9.45,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"3.5折","discount":3.5,"cachedInput":0.189,"listPriceUsd":{"input":0.75,"output":3.75,"cachedInput":0.075}}'::jsonb), + ('apihub', 'glm-4.7', '{"unit":"CNY / 1M tokens","input":1.3392,"output":4.9104,"discount":3.1,"cachedInput":0.24552,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":0.6,"output":2.2,"cachedInput":0.11},"discountLabel":"3.1折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":0.62,"output":2.48,"discount":3.1,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3.1折","cachedInput":0.248,"listPriceCny":{"input":2.0,"output":8.0,"cachedInput":0.8}}'::jsonb), + ('apihub', 'glm-5', '{"unit":"CNY / 1M tokens","input":8.86104,"output":39.821112,"discount":3.1,"cachedInput":1.77444,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":3.97,"output":17.841,"cachedInput":0.795},"discountLabel":"3.1折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.24,"output":5.58,"discount":3.1,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3.1折","cachedInput":0.31,"listPriceCny":{"input":4.0,"output":18.0,"cachedInput":1.0}}'::jsonb), + ('apihub', 'glm-5.1', '{"unit":"CNY / 1M tokens","input":13.237992,"output":52.9542,"discount":3.1,"cachedInput":1.323576,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":5.931,"output":23.725,"cachedInput":0.593},"discountLabel":"3.1折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.86,"output":7.44,"discount":3.1,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3.1折","cachedInput":0.403,"listPriceCny":{"input":6.0,"output":24.0,"cachedInput":1.3}}'::jsonb), + ('apipro', 'glm-5.2', '{"unit":"CNY / 1M tokens","input":5.348304,"output":18.72,"discount":6.5,"cachedInput":1.337076,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":1.1428,"output":4,"cachedInput":0.2857},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":5.348304,"output":18.72,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":1.337076,"listPriceUsd":{"input":1.1428,"output":3.9999999999995,"cachedInput":0.2857}}'::jsonb), + ('apihub', 'glm-5.2', '{"unit":"CNY / 1M tokens","input":17.28,"output":60.56208,"discount":3,"cachedInput":4.32432,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":8,"output":28.038,"cachedInput":2.002},"discountLabel":"3.0折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":2.4,"output":8.4,"discount":3.0,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3折","cachedInput":0.705,"listPriceCny":{"input":8.0,"output":28.0,"cachedInput":2.35}}'::jsonb), + ('apipro', 'glm-5.3', '{"unit":"CNY / 1M tokens","input":5.348304,"output":18.72,"discount":6.5,"cachedInput":1.337076,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":1.1428,"output":4,"cachedInput":0.2857},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":5.348304,"output":18.72,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":1.337076,"listPriceUsd":{"input":1.1428,"output":3.9999999999995,"cachedInput":0.2857}}'::jsonb), + ('apihub', 'glm-5.3-flash', '{"unit":"CNY / 1M tokens","input":5.76,"output":20.16,"cachedInput":1.656,"priceSource":"ApiHub 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.8,"output":2.8,"cachedInput":0.23},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":0.24,"output":0.84,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3折","discount":3.0,"cachedInput":0.069,"listPriceCny":{"input":0.8,"output":2.8,"cachedInput":0.23}}'::jsonb), + ('tokenfoundryx', 'gpt-5.4', '{"unit":"CNY / 1M tokens","input":128.34,"output":770.04,"cachedInput":12.6,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":17.825,"output":106.95,"cachedInput":1.75},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":34.6518,"output":207.9108,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"2.7折","discount":2.7,"cachedInput":3.40200977,"listPriceUsd":{"input":17.825,"output":106.95,"cachedInput":1.750005025}}'::jsonb), + ('tokenfoundryx', 'gpt-5.4-mini', '{"unit":"CNY / 1M tokens","input":37.8,"output":226.8,"cachedInput":3.78,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5.25,"output":31.5,"cachedInput":0.525},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":10.206,"output":61.236,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"2.7折","discount":2.7,"cachedInput":1.0206,"listPriceUsd":{"input":5.25,"output":31.5,"cachedInput":0.525}}'::jsonb), + ('tokenfoundryx', 'gpt-5.5', '{"unit":"CNY / 1M tokens","input":36,"output":216,"cachedInput":3.6,"priceSource":"TokenFoundryX 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":5,"output":30,"cachedInput":0.5},"discountLabel":"未提供"}'::jsonb, '{"unit":"CNY / 1M tokens","input":9.72,"output":58.32,"priceSource":"TokenFoundryX 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"2.7折","discount":2.7,"cachedInput":0.972,"listPriceUsd":{"input":5.0,"output":30.0,"cachedInput":0.5}}'::jsonb), + ('apipro', 'grok-3-mini', '{"unit":"CNY / 1M tokens","input":1.2096,"output":2.016,"discount":5.6,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.3,"output":0.5},"discountLabel":"5.6折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.2096,"output":2.016,"discount":5.6,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"5.6折","listPriceUsd":{"input":0.3,"output":0.5000000000001}}'::jsonb), + ('apihub', 'kimi-k2.5', '{"unit":"CNY / 1M tokens","input":8.00352,"output":41.97312,"discount":2.8,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":3.97,"output":20.82},"discountLabel":"2.8折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.12,"output":5.88,"discount":2.8,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"2.8折","listPriceCny":{"input":4.0,"output":21.0}}'::jsonb), + ('apipro', 'kimi-k2.6', '{"unit":"CNY / 1M tokens","input":4.345848,"output":18.051228,"discount":6.5,"cachedInput":0.735228,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":0.9286,"output":3.8571,"cachedInput":0.1571},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":4.345848,"output":18.051228,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":0.735228,"listPriceUsd":{"input":0.9286,"output":3.857100000000277,"cachedInput":0.1570999999997104}}'::jsonb), + ('apihub', 'kimi-k2.6', '{"unit":"CNY / 1M tokens","input":12.989088,"output":53.95824,"discount":2.8,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":6.443,"output":26.765},"discountLabel":"2.8折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.82,"output":7.56,"discount":2.8,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"2.8折","cachedInput":0.308,"listPriceCny":{"input":6.5,"output":27.0,"cachedInput":1.1}}'::jsonb), + ('apihub', 'kimi-k2.7-code', '{"unit":"CNY / 1M tokens","input":18.236736,"output":75.757248,"discount":2.8,"cachedInput":3.64896,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":9.046,"output":37.578,"cachedInput":1.81},"discountLabel":"2.8折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":1.82,"output":7.56,"discount":2.8,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"2.8折","cachedInput":0.21560084,"listPriceCny":{"input":6.5,"output":27.0,"cachedInput":0.770003}}'::jsonb), + ('apihub', 'qwen3.6-plus', '{"unit":"CNY / 1M tokens","input":4.437216,"output":26.551872,"discount":3.1,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":1.988,"output":11.896},"discountLabel":"3.1折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":0.62,"output":14.88,"discount":3.1,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3.1折","cachedInput":0.062,"listPriceCny":{"input":2.0,"output":48.0,"cachedInput":0.2}}'::jsonb), + ('apihub', 'qwen3.7-max', '{"unit":"CNY / 1M tokens","input":26.587584,"output":79.76052,"discount":3.1,"cachedInput":2.660544,"priceSource":"芯化兰德报价_2026.09.09.xlsx","exchangeRate":7.2,"listPriceUsd":{"input":11.912,"output":35.735,"cachedInput":1.192},"discountLabel":"3.1折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":3.72,"output":11.16,"discount":3.1,"priceSource":"ApiHub 当前人民币原价 · 2026-10-12","exchangeRate":1.0,"discountLabel":"3.1折","cachedInput":0.744,"listPriceCny":{"input":12.0,"output":36.0,"cachedInput":2.4}}'::jsonb), + ('apipro', 'qwen3.8-max', '{"unit":"CNY / 1M tokens","input":8.022924,"output":24.068772,"discount":6.5,"cachedInput":1.002924,"priceSource":"APIPro 模型广场","exchangeRate":7.2,"listPriceUsd":{"input":1.7143,"output":5.1429,"cachedInput":0.2143},"discountLabel":"6.5折"}'::jsonb, '{"unit":"CNY / 1M tokens","input":8.022924,"output":24.068772,"discount":6.5,"priceSource":"APIPro 当前美元原价 · 2026-10-12","exchangeRate":7.2,"discountLabel":"6.5折","cachedInput":1.002924,"listPriceUsd":{"input":1.7143,"output":5.1429,"cachedInput":0.2143000000001658}}'::jsonb) +) +UPDATE model_catalog m SET pricing=c.new_pricing, updated_at=now() +FROM model_providers p, correction c +WHERE m.provider_id=p.id AND p.code=c.provider_code AND m.upstream_model=c.upstream_model +AND m.deleted_at IS NULL AND p.deleted_at IS NULL AND m.pricing=c.old_pricing; diff --git a/control-plane-java/src/test/java/com/moyi/controlplane/catalog/CatalogServiceTest.java b/control-plane-java/src/test/java/com/moyi/controlplane/catalog/CatalogServiceTest.java index 23c57d7..a192847 100644 --- a/control-plane-java/src/test/java/com/moyi/controlplane/catalog/CatalogServiceTest.java +++ b/control-plane-java/src/test/java/com/moyi/controlplane/catalog/CatalogServiceTest.java @@ -2,10 +2,23 @@ package com.moyi.controlplane.catalog; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import java.util.Map; +import com.moyi.controlplane.common.ApiException; import org.junit.jupiter.api.Test; class CatalogServiceTest { + @Test + void pricingRejectsAmbiguousCurrencyAndDiscountTypos() { + assertThrows(ApiException.class, () -> CatalogService.validatePricing(Map.of("listPriceCny", Map.of("input", 1), "listPriceUsd", Map.of("input", 1)))); + assertThrows(ApiException.class, () -> CatalogService.validatePricing(Map.of("discount", 55))); + assertThrows(ApiException.class, () -> CatalogService.validatePricing(Map.of("listPriceCny", Map.of("input", 1), "exchangeRate", 7.2))); + assertDoesNotThrow(() -> CatalogService.validatePricing(Map.of("listPriceCny", Map.of("input", 1), "exchangeRate", 1, "discount", 5.5))); + assertDoesNotThrow(() -> CatalogService.validatePricing(Map.of("listPriceUsd", Map.of("input", 1), "exchangeRate", 7.2, "discount", 5.6))); + assertDoesNotThrow(() -> CatalogService.validatePricing(Map.of("price", 1.44, "unit", "CNY / task"))); + } @Test void asyncReadinessMatchesImplementedAdapters() { assertTrue(CatalogService.asyncExecutorReady("provider-vast", "http", "3d")); diff --git a/docs/18-pricing-currency-and-discounts.md b/docs/18-pricing-currency-and-discounts.md new file mode 100644 index 0000000..e84080b --- /dev/null +++ b/docs/18-pricing-currency-and-discounts.md @@ -0,0 +1,61 @@ +# 定价币种与对外折扣(2026-10-12 核对) + +## 单位和规则 + +`1M tokens`、`1,000,000 tokens`、`一百万 Token` 是同一个计价单位。聊天结算仍按实际输入、输出和缓存命中用量除以 1,000,000,保留 8 位小数。 + +对外折数 = 采购折数 + 1。例如采购 4.6 折,对外 5.6 折,售价是原价的 0.56;这不是采购成本乘 1.1。此规则可由 V17 与原始报价表逐项对应确认。 + +| 渠道/范围 | 采购折数 | 对外折数 | +|---|---:|---:| +| APIPro Claude、Gemini、OpenAI、Grok | 4.6 | 5.6 | +| APIPro GLM、Kimi、MiniMax、Qwen、DeepSeek | 5.5 | 6.5 | +| APIPro Doubao | 9.0 | 10.0 | +| ApiHub / TokenFoundryX | 按用户提供报价表逐型号匹配 | 采购折数 + 1 | + +采购折扣来自用户 2026-10-12 确认;原始表《芯化兰德报价_2026.09.09.xlsx》明确标注 USD / 百万 tokens,不能把历史表的美元标签解释为人民币。当前 ApiHub 网站显示 CNY,TokenFoundryX / APIPro 显示 USD;本次按当前网站原价与币种计算,表格只作为逐型号采购折扣和历史原价的依据。实际 Key 分组结算仍须与渠道账单核对。 + +人民币原价:`原价 × 对外折数 / 10`。 + +美元原价:`原价 × 对外折数 / 10 × USD/CNY`。本次沿用已配置的 7.2,不将它声称为实时外汇汇率。 + +## 系统修复 + +- 原价分别保存为 `listPriceCny` / `listPriceUsd`,不能同时存在。人民币原价的 `exchangeRate` 为 1。 +- 管理端可以选择原价币种、填入对外折数,明确点击换算后才更新人民币售价草稿,保存后生效。 +- 计算使用整数定点乘法及 HALF_UP 八位小数,避免浮点乘法累积误差。 +- 后端拒绝同时存在两种原价币种、55 折等明显无效折扣和人民币原价再使用 7.2 的配置。 +- 修改分组时保留已有任务标准价、固定任务费等未编辑的价格元数据。 +- 扣费时仍直接使用 `input` / `output` / `cachedInput`,不会再次乘折扣或汇率。正在进行的调用继续使用预留时的价格快照。 +- 新增 V34,保留既有 Flyway 迁移,不修改历史 V17/V22/V23。 + +## 修正范围与保留项 + +原用户价格清单覆盖 206 条 Token 路由、2 条 Tripo 任务。V34 准备修正 35 条 Token 路由,包含金额、缓存价及原价精度/币种元数据。107 条与本轮规则一致,64 条仍保留现价待核。配置就绪不代表已经逐模型付费实测。 + +例:ApiHub GLM-5.3-flash 原价 CNY 0.8/2.8,采购 2 折、对外 3 折,售价为 CNY 0.24/0.84;TokenFoundryX Gemini 2.5 Pro 原价 USD 1.25/10,采购 2.5 折、对外 3.5 折,售价为 CNY 3.15/25.2。 + +以下不自动推断或涨价: + +- 渠道当前目录未找到同名模型,或者没有用户确认的采购折扣。 +- 动态上下文/时段等计费表达式:本次没有为其新增动态结算引擎。现有固定售价不等于覆盖上游所有档位。 +- APIPro `gemini-2.5-flash-preview-09-2025` 当前公开倍率推导的输出价比历史价高 100 倍以上,须核实渠道配置。 +- Tripo 任务类型、纹理和额外参数费用:本次不调整原来的 1.44 元任务价。 + +TokenFoundryX `gemini-2.5-flash-lite` 当前网页仍显示 USD 75/300,远高于旧表 USD 0.1/0.4。此次补齐 3.5 折对外折扣后的值为 CNY 189/756,不能据此认定渠道原价合理。 + +## 来源与复算 + +- MOYI: +- ApiHub 登录后模型广场: +- TokenFoundryX:、 +- APIPro: +- 用户原报价表及本轮确认的 APIPro 折扣。 + +`scripts/reconcile-pricing.py` 读取已保存的来源快照,用 Decimal 复算,并生成修价对照和迁移。脚本不访问网络、不连接数据库、不执行渠道计费表达式。不得将它当作无审核实时同步器。输出迁移匹配渠道、模型和完整旧价格 JSON,管理员在核对后另改过的价格会被保留,且不更改启用状态、凭据、余额或历史订单。 + +本地回归:`scripts/test_reconcile_pricing.py`;隔离 PostgreSQL 迁移验证:`scripts/test_pricing_migration.py --sources <快照目录> --postgres-bin <本机 PostgreSQL bin>`。 + +## 发布验证 + +按 docs/11-server-test-deployment.md 创建独立发布目录并备份数据库,保留现有环境配置、证书和密钥。发布后重新读取 `/api/models`,逐条比较 V34 目标价格及币种,检查被旧值保护条件跳过的记录。未成功部署并核对前,修订版 Excel 只能标为待上线稿。 diff --git a/prototype/src/components/CatalogAdmin.vue b/prototype/src/components/CatalogAdmin.vue index e2f5804..8f90b5b 100644 --- a/prototype/src/components/CatalogAdmin.vue +++ b/prototype/src/components/CatalogAdmin.vue @@ -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, 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() 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 - - + + + + + + + 1M Token=1,000,000 Token=一百万 Token。人民币原价不乘汇率;美元原价仅换算一次。采购 4.6 折加 1 个折扣点,对外填 5.6。 输入、输出价格是实际扣费值,单位为 CNY / 1M tokens。折扣只用于向用户展示,不会替代人民币售价;留空表示不展示折扣。 diff --git a/prototype/src/services/catalog.ts b/prototype/src/services/catalog.ts index 512865a..152b71f 100644 --- a/prototype/src/services/catalog.ts +++ b/prototype/src/services/catalog.ts @@ -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 diff --git a/prototype/src/services/pricing.ts b/prototype/src/services/pricing.ts index 84ce451..a5d8748 100644 --- a/prototype/src/services/pricing.ts +++ b/prototype/src/services/pricing.ts @@ -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) { 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 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 diff --git a/prototype/tests/pricing.test.mjs b/prototype/tests/pricing.test.mjs index 1cc737c..ed3f6ea 100644 --- a/prototype/tests/pricing.test.mjs +++ b/prototype/tests/pricing.test.mjs @@ -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 } }, diff --git a/scripts/package-deployment.ps1 b/scripts/package-deployment.ps1 index 49c995d..fb8a9f0 100644 --- a/scripts/package-deployment.ps1 +++ b/scripts/package-deployment.ps1 @@ -30,7 +30,7 @@ New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null $staging = Join-Path $artifactRoot ('moyi-test-' + $releaseId) New-Item -ItemType Directory -Path $staging | Out-Null # Copy tracked deployment files only, never .env, certificates or .git. -$tracked = @(git ls-files infra/moyi scripts/live-gateway-smoke.py docs/11-server-test-deployment.md docs/13-model-groups-registration-credit.md docs/14-lifecycle-usage-credit-adjustments.md docs/15-relay-onboarding.md docs/16-streaming-chat-billing.md docs/17-catalog-and-key-selection.md) +$tracked = @(git ls-files infra/moyi scripts/live-gateway-smoke.py docs/11-server-test-deployment.md docs/13-model-groups-registration-credit.md docs/14-lifecycle-usage-credit-adjustments.md docs/15-relay-onboarding.md docs/16-streaming-chat-billing.md docs/17-catalog-and-key-selection.md docs/18-pricing-currency-and-discounts.md) foreach ($relative in $tracked) { if ($relative -match '(^|/)(\.env\.cloud|\.deploy-mode|certs)(/|$)') { throw 'Sensitive path in release allowlist.' } $destination = Join-Path $staging $relative diff --git a/scripts/reconcile-pricing.py b/scripts/reconcile-pricing.py new file mode 100644 index 0000000..3934b8b --- /dev/null +++ b/scripts/reconcile-pricing.py @@ -0,0 +1,156 @@ +"""Build a reviewable, guarded pricing migration from explicit source snapshots. + +No network access, database writes or execution of supplier pricing expressions. +The old and new price JSON must match before a migration can update a route. +""" +import argparse +import copy +import json +import re +from decimal import Decimal, ROUND_HALF_UP +from pathlib import Path + +D = lambda x: Decimal(str(x)) +API_DISCOUNT = {'claude': '4.6', 'gemini': '4.6', 'gpt': '4.6', 'chatgpt': '4.6', 'codex': '4.6', 'grok': '4.6', 'glm': '5.5', 'kimi': '5.5', 'minimax': '5.5', 'qwen': '5.5', 'deepseek': '5.5', 'doubao': '9'} + +def retail_price(prices, currency, purchase_discount, exchange_rate='7.2'): + if currency not in ('USD', 'CNY'): + raise ValueError('Source currency must be explicit USD or CNY') + if not D(0) <= D(purchase_discount) <= D(9): + raise ValueError('Purchase discount plus one must be within 0-10') + fx = D(1) if currency == 'CNY' else D(exchange_rate) + if not D(0) < fx <= D(1000): + raise ValueError('Invalid exchange rate') + discount = D(purchase_discount) + D(1) + result = {'unit':'CNY / 1M tokens', 'discount':float(discount), 'discountLabel':f'{discount.normalize()}折', 'exchangeRate':float(fx)} + listed = {} + for field in ('input', 'output', 'cachedInput'): + value = prices.get(field) + if value is None: + if field != 'cachedInput': + raise ValueError('Both input and output list rates are required') + continue + value = D(value) + if not value.is_finite() or value < 0: + raise ValueError('Invalid source price') + amount = (value * fx * discount / 10).quantize(D('0.00000001'), rounding=ROUND_HALF_UP) + if amount > 1000000: + raise ValueError('Retail rate exceeds the billing limit') + listed[field] = float(value) + result[field] = float(amount) + result['listPriceUsd' if currency == 'USD' else 'listPriceCny'] = listed + return result + +def normalize_model(value): + # Only punctuation normalization supported by explicit matching quote rows. + return value.lower().replace('.', '-') + +def source_rate(item): + if item.get('billing_mode') == 'tiered_expr': + expr = item.get('billing_expr', '') + # A single literal tier is a fixed rate. Never eval provider expressions. + match = re.fullmatch(r'tier\("[^"]+",\s*([^()]+)\)', expr) + if not match: + return None + fields = dict(re.findall(r'\b(p|c|cr)\s*\*\s*([0-9.]+)', match[1])) + if not {'p','c'}.issubset(fields): + return None + return {'input':fields['p'], 'output':fields['c'], 'cachedInput':fields.get('cr')} + if item.get('quota_type') != 0: + return None + base = D(item['model_ratio']) * 2 + return {'input':base, 'output':base*D(item['completion_ratio']), 'cachedInput':base*D(item['cache_ratio']) if item.get('cache_ratio') is not None else None} + +def build(directory): + read = lambda name: json.loads((directory/name).read_text(encoding='utf-8')) + catalog = read('catalog-audit-source.json') + ready = {r['id'] for r in read('ready-audit.json')} + quote = {normalize_model(r[0]):r for r in read('supplier-quote-source.json')['报价单'][3:] if r[0]} + source = {p:{r['model_name']:r for r in read(p+'-pricing-recheck.json')['data']} for p in ('apipro','tokenfoundryx')} + hubs = {} + for file in ('apihub-page1.txt','apihub-page2.txt'): + for block in re.split(r'\d+ heading ', (directory/file).read_text(encoding='utf-8'))[1:]: + name=block.split(', Value:')[0] + line=next((line for line in block.splitlines() if 'text 输入 ¥' in line), None) + if not line or '动态计费' in block: + continue + nums=re.findall(r'¥([\d.]+)',line) + if len(nums) >= 4: + hubs[name]={'input':nums[1],'output':nums[3],'cachedInput':nums[5] if len(nums)>5 else None} + rows=[] + for row in catalog: + p=row['provider'];model=row['model'];old=row.get('pricing') or {} + if old.get('unit') != 'CNY / 1M tokens': + continue + result={**row,'ready':row['id'] in ready,'oldPricing':old,'newPricing':copy.deepcopy(old),'purchaseDiscount':None,'state':'保留现价','reason':'','sourceCurrency':None} + q=quote.get(normalize_model(model)) + discount=None;rate=None;currency=None + if p=='apipro': + family=next((family for family in API_DISCOUNT if re.match(re.escape(family)+r'(?:[-.\d]|$)',model.lower())),None) + discount=API_DISCOUNT.get(family) + if model.startswith('text-embedding-'): discount='4.6' + if re.match(r'^o[134](?:-|$)',model): discount='4.6' + item=source[p].get(model) + result['source']='https://api.apipro.ai/api/pricing' + if item: rate=source_rate(item) + currency='USD' + if not item: result['reason']='当前渠道目录未匹配同名模型,保留现价,待确认映射。' + elif rate is None: result['reason']='上游含动态/阶梯或非 Token 规则,保留平台固定现价,完整条件待复核。';result['billingExpr']=item.get('billing_expr','') + elif p in ('apihub','tokenfoundryx'): + if q: discount=q[6].replace('折','');result['quoteModel']=q[0];result['quoteList']={'input':q[3],'output':q[4],'cachedInput':q[5]} + if p=='apihub': rate=hubs.get(model);currency='CNY';result['source']='https://apihub.chem-cloud.cn/pricing' + else: + item=source[p].get(model) + rate=source_rate(item) if item else None;currency='USD';result['source']='https://www.tokenfoundryx.com/api/pricing' + if not rate: result['reason']='当前原价未核实或为动态计费,保留现价。' + else: result['reason']='不在本次三个中转渠道折扣范围。' + result['purchaseDiscount']=float(discount) if discount is not None else None + result['sourceCurrency']=currency + if discount is None: result['reason']+=' 未找到用户确认的该模型采购折扣,不按相近模型猜测。' + if rate is not None and discount is not None: + computed=retail_price(rate,currency,discount) + oldout=D(old.get('output',0)) + if oldout>0 and D(computed['output'])/oldout >= 100: + result['reason']='当前渠道输出原价比历史值高至少 100 倍,疑似渠道异常配置;不自动涨价。' + result['candidatePricing']=computed + else: + new=copy.deepcopy(old) + for key in ('listPriceUsd','listPriceCny','cachedInput'): + new.pop(key,None) + new.update(computed) + new['priceSource']=('ApiHub 当前人民币原价' if p=='apihub' else ('APIPro' if p=='apipro' else 'TokenFoundryX')+' 当前美元原价')+' · 2026-10-12' + result['newPricing']=new + fields=('input','output','cachedInput','discount','exchangeRate','listPriceUsd','listPriceCny') + changed=any(old.get(k)!=new.get(k) for k in fields) + result['state']='修正' if changed else '一致' + result['reason']='按渠道当前原价与币种,采购折扣加 1 个折扣点;美元按 7.2 换算一次。' + if q and p=='tokenfoundryx' and q[3] and D(rate['input'])/D(q[3]) >= 10: + result['reason']+=' 渠道当前原价明显高于历史报价表,已按当前网页计算,需向渠道复核异常高原价。' + rows.append(result) + return rows + +def migration(rows): + changed=[r for r in rows if r['state']=='修正'] + def sql(value): return "'"+json.dumps(value,ensure_ascii=False,separators=(',',':')).replace("'","''")+"'::jsonb" + values=[] + for r in changed: + values.append(" ('"+r['provider'].replace("'","''")+"', '"+r['model'].replace("'","''")+"', "+sql(r['oldPricing'])+", "+sql(r['newPricing'])+")") + return ("-- Verified 2026-10-12: current source currency; purchase discount + 1 point.\n" + "-- Exact old JSON guard preserves later manual edits. Does not change enabled status, credentials or balances.\n" + "-- Dynamic, missing-source and extreme-increase rows are deliberately excluded.\n" + "WITH correction(provider_code, upstream_model, old_pricing, new_pricing) AS (VALUES\n"+',\n'.join(values)+"\n)\n" + "UPDATE model_catalog m SET pricing=c.new_pricing, updated_at=now()\n" + "FROM model_providers p, correction c\n" + "WHERE m.provider_id=p.id AND p.code=c.provider_code AND m.upstream_model=c.upstream_model\n" + "AND m.deleted_at IS NULL AND p.deleted_at IS NULL AND m.pricing=c.old_pricing;\n") + +if __name__=='__main__': + parser=argparse.ArgumentParser() + parser.add_argument('--sources',type=Path,required=True) + parser.add_argument('--migration',type=Path,required=True) + args=parser.parse_args() + rows=build(args.sources) + (args.sources/'pricing-corrections.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2),encoding='utf-8') + args.migration.write_text(migration(rows),encoding='utf-8') + from collections import Counter + print(json.dumps({'all':dict(Counter(r['state'] for r in rows)),'ready':dict(Counter(r['state'] for r in rows if r['ready']))},ensure_ascii=False)) diff --git a/scripts/test_pricing_migration.py b/scripts/test_pricing_migration.py new file mode 100644 index 0000000..9b125dc --- /dev/null +++ b/scripts/test_pricing_migration.py @@ -0,0 +1,57 @@ +"""Exercise the pricing correction against an isolated local PostgreSQL cluster.""" +import argparse +import json +import socket +import subprocess +import tempfile +from pathlib import Path + +parser=argparse.ArgumentParser() +parser.add_argument('--sources',type=Path,required=True) +parser.add_argument('--postgres-bin',type=Path,required=True) +args=parser.parse_args() +repo=Path(__file__).resolve().parent.parent +folder=Path(tempfile.mkdtemp(prefix='pricing-migration-',dir=repo/'.tools')) +bin=args.postgres_bin +with socket.socket() as sock: + sock.bind(('127.0.0.1',0));port=sock.getsockname()[1] +def run(command): + # PostgreSQL's Windows child can inherit stdout pipes and keep communicate() + # waiting after pg_ctl exits. A file avoids inheriting a pipe reader. + with tempfile.TemporaryFile(mode='w+b') as output: + subprocess.run([str(x) for x in command],check=True,stdout=output,stderr=output,timeout=90) + output.seek(0) + return output.read().decode('utf-8',errors='replace') +def sql_literal(value): + return "'"+value.replace("'","''")+"'" +def sql_json(value): + return sql_literal(json.dumps(value,ensure_ascii=False,separators=(',',':')))+'::jsonb' +rows=json.loads((args.sources/'pricing-corrections.json').read_text(encoding='utf8')) +changed=[r for r in rows if r['state']=='修正'] +sql=['CREATE TABLE model_providers(id text PRIMARY KEY,code text,deleted_at timestamptz);', + 'CREATE TABLE model_catalog(id text PRIMARY KEY,provider_id text,upstream_model text,pricing jsonb,status text,deleted_at timestamptz,updated_at timestamptz);'] +for provider in sorted({r['provider'] for r in rows}): + sql.append(f'INSERT INTO model_providers VALUES ({sql_literal(provider)},{sql_literal(provider)},NULL);') +for row in rows: + sql.append('INSERT INTO model_catalog VALUES ('+','.join([sql_literal(row['id']),sql_literal(row['provider']),sql_literal(row['model']),sql_json(row['oldPricing']),sql_literal(row['status']),'NULL','now()'])+');') +sample=changed[0] +sql.append('INSERT INTO model_catalog SELECT \'manual-edit\',provider_id,upstream_model,\'{"input":123,"unit":"CNY / 1M tokens"}\'::jsonb,\'disabled\',NULL,now() FROM model_catalog WHERE id='+sql_literal(sample['id'])+';') +sql.append('CREATE TEMP TABLE before_rows AS SELECT * FROM model_catalog;') +migration=(repo/'control-plane-java/src/main/resources/db/migration/V34__reconcile_source_currency_and_retail_discounts.sql').read_text(encoding='utf8') +sql.append(migration) +for row in rows: + expected=row['newPricing'] if row['state']=='修正' else row['oldPricing'] + sql.append('DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM model_catalog WHERE id='+sql_literal(row['id'])+' AND pricing='+sql_json(expected)+') THEN RAISE EXCEPTION \'Incorrect migrated price\'; END IF; END $$;') +sql.append("DO $$ BEGIN IF EXISTS (SELECT 1 FROM model_catalog m JOIN before_rows b USING(id) WHERE m.status<>b.status) OR NOT EXISTS (SELECT 1 FROM model_catalog WHERE id='manual-edit' AND pricing->>'input'='123') THEN RAISE EXCEPTION 'Manual edit or status was changed'; END IF; END $$;") +sql.append('CREATE TEMP TABLE first_pass AS SELECT * FROM model_catalog;') +sql.append(migration) +sql.append("DO $$ BEGIN IF EXISTS (SELECT 1 FROM model_catalog m JOIN first_pass f USING(id) WHERE m.pricing IS DISTINCT FROM f.pricing OR m.updated_at IS DISTINCT FROM f.updated_at) THEN RAISE EXCEPTION 'Not idempotent'; END IF; END $$;") +sql.append("SELECT 'Pricing migration verified' AS result;") +script=folder/'verify.sql';script.write_text('\n'.join(sql),encoding='utf8') +run([bin/'initdb.exe','-D',folder/'data','-U','pricing_test','-A','trust','--encoding=UTF8','--locale=C']) +try: + run([bin/'pg_ctl.exe','-D',folder/'data','-l',folder/'postgres.log','-o',f'-p {port} -h 127.0.0.1','-w','start']) + out=run([bin/'psql.exe','-h','127.0.0.1','-p',str(port),'-U','pricing_test','-d','postgres','-v','ON_ERROR_STOP=1','-f',script]) + print(f'PASS: {len(changed)} corrections; {len(rows)} prices checked; manual-edit guard, status preservation and idempotence verified.') +finally: + run([bin/'pg_ctl.exe','-D',folder/'data','-w','stop','-m','fast']) diff --git a/scripts/test_reconcile_pricing.py b/scripts/test_reconcile_pricing.py new file mode 100644 index 0000000..dd738f3 --- /dev/null +++ b/scripts/test_reconcile_pricing.py @@ -0,0 +1,31 @@ +import unittest +from importlib.util import spec_from_file_location, module_from_spec +from pathlib import Path + +spec=spec_from_file_location('pricing',Path(__file__).with_name('reconcile-pricing.py')) +p=module_from_spec(spec) +spec.loader.exec_module(p) + +class PricingTests(unittest.TestCase): + def test_cny_no_fx_and_plus_one(self): + r=p.retail_price({'input':'.8','output':'2.8','cachedInput':'.23'},'CNY','2') + self.assertEqual((r['input'],r['output'],r['cachedInput'],r['discount'],r['exchangeRate']),(.24,.84,.069,3,1)) + self.assertNotIn('listPriceUsd',r) + def test_usd_and_zero(self): + r=p.retail_price({'input':'1.25','output':'10','cachedInput':'0'},'USD','2.5') + self.assertEqual((r['input'],r['output'],r['cachedInput']),(3.15,25.2,0)) + self.assertEqual(p.retail_price({'input':1,'output':2},'USD',9)['discount'],10) + def test_half_up(self): + self.assertEqual(p.retail_price({'input':'.00000001','output':0},'CNY',4)['input'],.00000001) + def test_reject_ambiguous(self): + for currency,discount in [('RMB',2),('USD',55)]: + with self.assertRaises(ValueError):p.retail_price({'input':1,'output':1},currency,discount) + def test_dynamic_not_evaluated(self): + self.assertIsNone(p.source_rate({'billing_mode':'tiered_expr','billing_expr':'len < 10 ? tier("x",p*1+c*2) : tier("y",p*2+c*4)'})) + self.assertEqual(p.source_rate({'billing_mode':'tiered_expr','billing_expr':'tier("standard", p * 10 + c * 50 + cr * 1 + cc * 12.5)'}),{'input':'10','output':'50','cachedInput':'1'}) + def test_migration_guard(self): + sql=p.migration([{'state':'修正','provider':'x','model':'a','oldPricing':{'input':1},'newPricing':{'input':2}}]) + self.assertIn('m.pricing=c.old_pricing',sql) + self.assertNotIn('status=',sql) + +if __name__=='__main__':unittest.main()