Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

275 строки
10 KiB

  1. export const BILLING_UNITS = {
  2. perCall: 'per_call',
  3. per1MTokens: 'per_1m_tokens',
  4. };
  5. export const PRECONSUME_STRATEGIES = {
  6. exact: 'exact',
  7. minimum: 'minimum',
  8. };
  9. export const FALLBACKS = {
  10. reject: 'reject',
  11. max: 'max',
  12. default: 'default',
  13. };
  14. export const ROW_SOURCES = {
  15. manual: 'manual',
  16. generated: 'generated',
  17. };
  18. const RESERVED_KEYS = new Set([
  19. 'price',
  20. 'source',
  21. '__fallback__',
  22. 'price_formula',
  23. 'pricing_mode',
  24. 'fallback_strategy',
  25. 'schema_version',
  26. 'scope',
  27. 'billing_unit',
  28. 'preconsume_strategy',
  29. ]);
  30. export const createDefaultConfig = () => ({
  31. schema_version: 1,
  32. scope: 'model',
  33. billing_unit: BILLING_UNITS.perCall,
  34. preconsume_strategy: PRECONSUME_STRATEGIES.exact,
  35. dimensions: [
  36. {
  37. key: 'resolution',
  38. source: 'request.resolution',
  39. type: 'string',
  40. default: null,
  41. },
  42. ],
  43. table: [
  44. {
  45. resolution: '*',
  46. price: 0.1,
  47. source: ROW_SOURCES.manual,
  48. },
  49. ],
  50. fallback: {
  51. strategy: FALLBACKS.reject,
  52. },
  53. });
  54. export const validatePricingConfig = (config) => {
  55. const errors = [];
  56. if (!config || typeof config !== 'object') {
  57. return { ok: false, errors: ['config must be an object'] };
  58. }
  59. if (config.schema_version !== 1) errors.push('schema_version must be 1');
  60. if (config.scope !== 'model') errors.push('scope must be model');
  61. const billingUnit = config.billing_unit || BILLING_UNITS.perCall;
  62. const preconsume = config.preconsume_strategy || PRECONSUME_STRATEGIES.exact;
  63. if (!Object.values(BILLING_UNITS).includes(billingUnit)) errors.push('billing_unit is invalid');
  64. if (!Object.values(PRECONSUME_STRATEGIES).includes(preconsume)) errors.push('preconsume_strategy is invalid');
  65. if (billingUnit === BILLING_UNITS.perCall && preconsume !== PRECONSUME_STRATEGIES.exact) {
  66. errors.push('per_call requires exact preconsume_strategy');
  67. }
  68. if (billingUnit === BILLING_UNITS.per1MTokens && preconsume !== PRECONSUME_STRATEGIES.minimum) {
  69. errors.push('per_1m_tokens requires minimum preconsume_strategy');
  70. }
  71. if (!Array.isArray(config.dimensions) || config.dimensions.length === 0) errors.push('dimensions must not be empty');
  72. if (!Array.isArray(config.table) || config.table.length === 0) errors.push('table must not be empty');
  73. const dimensionKeys = new Set();
  74. for (const dim of config.dimensions || []) {
  75. if (!/^[a-z][a-z0-9_]{0,31}$/.test(dim.key || '')) errors.push(`dimension key "${dim.key || ''}" is invalid`);
  76. if (RESERVED_KEYS.has(dim.key)) errors.push(`dimension key "${dim.key}" is reserved`);
  77. if (dimensionKeys.has(dim.key)) errors.push(`dimension key "${dim.key}" is duplicated`);
  78. dimensionKeys.add(dim.key);
  79. if (!['string', 'number', 'boolean'].includes(dim.type)) errors.push(`dimension "${dim.key}" type is invalid`);
  80. if (dim.optional && (dim.default === null || dim.default === undefined)) {
  81. errors.push(`optional dimension "${dim.key}" requires a default value`);
  82. }
  83. if (!dim.optional && dim.default !== null && dim.default !== undefined) {
  84. errors.push(`required dimension "${dim.key}" must use null default`);
  85. }
  86. if (dim.optional && dim.default !== null && dim.default !== undefined && !valueMatchesType(dim.default, dim.type)) {
  87. errors.push(`dimension "${dim.key}" default does not match type`);
  88. }
  89. }
  90. const rowSignatures = new Set();
  91. const rowPatterns = [];
  92. for (const [index, row] of (config.table || []).entries()) {
  93. for (const key of Object.keys(row || {})) {
  94. if (!dimensionKeys.has(key) && key !== 'price' && key !== 'source') errors.push(`row ${index + 1} contains extra field "${key}"`);
  95. }
  96. for (const dim of config.dimensions || []) {
  97. if (!(dim.key in row)) {
  98. errors.push(`row ${index + 1} missing "${dim.key}"`);
  99. continue;
  100. }
  101. if (row[dim.key] !== '*' && !valueMatchesType(row[dim.key], dim.type)) {
  102. errors.push(`row ${index + 1} value for "${dim.key}" does not match type`);
  103. }
  104. }
  105. const price = Number(row.price);
  106. if (Number.isNaN(price) || price < 0) errors.push(`row ${index + 1} price must be >= 0`);
  107. if (!Object.values(ROW_SOURCES).includes(row.source)) errors.push(`row ${index + 1} source must be manual or generated`);
  108. const signature = (config.dimensions || []).map((dim) => String(row[dim.key])).join('\u0001');
  109. if (rowSignatures.has(signature)) errors.push(`row ${index + 1} duplicates another row`);
  110. rowSignatures.add(signature);
  111. rowPatterns.push({
  112. index,
  113. values: (config.dimensions || []).map((dim) => row[dim.key]),
  114. wildcards: (config.dimensions || []).filter((dim) => row[dim.key] === '*').length,
  115. });
  116. }
  117. for (let i = 0; i < rowPatterns.length; i += 1) {
  118. for (let j = i + 1; j < rowPatterns.length; j += 1) {
  119. if (rowPatterns[i].wildcards !== rowPatterns[j].wildcards) continue;
  120. if (patternsOverlap(rowPatterns[i].values, rowPatterns[j].values)) {
  121. errors.push(`rows ${rowPatterns[i].index + 1} and ${rowPatterns[j].index + 1} are ambiguous`);
  122. }
  123. }
  124. }
  125. const strategy = config.fallback?.strategy;
  126. if (!Object.values(FALLBACKS).includes(strategy)) errors.push('fallback.strategy is invalid');
  127. if (strategy === FALLBACKS.default && (config.fallback.default_price === undefined || Number(config.fallback.default_price) < 0)) {
  128. errors.push('fallback.default_price must be >= 0');
  129. }
  130. return { ok: errors.length === 0, errors };
  131. };
  132. export const generateRowsFromRatios = ({ dimensions, basePrice, ratios }) => {
  133. const dims = dimensions || [];
  134. if (dims.length === 0) return [];
  135. const build = (index, prefix, price) => {
  136. if (index >= dims.length) return [{ ...prefix, price: Number(Number(price).toFixed(6)), source: ROW_SOURCES.generated }];
  137. const dim = dims[index];
  138. const dimRatios = ratios?.[dim.key] || {};
  139. return Object.entries(dimRatios).flatMap(([value, ratio]) =>
  140. build(index + 1, { ...prefix, [dim.key]: parseDimensionValue(value, dim.type) }, price * Number(ratio || 1)),
  141. );
  142. };
  143. return build(0, {}, Number(basePrice || 0));
  144. };
  145. export const mergeGeneratedRows = ({ existingRows, generatedRows, strategy }) => {
  146. if (strategy === 'replace_all') return [...(generatedRows || [])];
  147. const manualRows = (existingRows || []).filter((row) => row.source === ROW_SOURCES.manual);
  148. return [...manualRows, ...(generatedRows || [])];
  149. };
  150. export const importPricingCsv = (text, dimensions) => {
  151. const lines = String(text || '').trim().split(/\r?\n/).filter(Boolean);
  152. if (lines.length === 0) return { rows: [], errors: [] };
  153. const headers = parseCsvLine(lines[0]);
  154. const errors = [];
  155. const rows = lines.slice(1).map((line, index) => {
  156. const cells = parseCsvLine(line);
  157. const row = {};
  158. headers.forEach((header, i) => {
  159. row[header] = cells[i] ?? '';
  160. });
  161. for (const dim of dimensions || []) row[dim.key] = row[dim.key] === '*' ? '*' : parseDimensionValue(row[dim.key], dim.type);
  162. row.price = Number(row.price);
  163. row.source = row.source || ROW_SOURCES.manual;
  164. if (Number.isNaN(row.price)) errors.push(`line ${index + 2} has invalid price`);
  165. return row;
  166. });
  167. return { rows, errors };
  168. };
  169. export const exportPricingCsv = (rows, dimensions) => {
  170. const headers = [...(dimensions || []).map((dim) => dim.key), 'price', 'source'];
  171. const body = (rows || []).map((row) => headers.map((header) => escapeCsvValue(row[header] ?? '')).join(','));
  172. return [headers.join(','), ...body].join('\n');
  173. };
  174. export const previewLookup = (config, requestValues) => {
  175. const validation = validatePricingConfig(config);
  176. if (!validation.ok) return { mode: 'invalid', error: validation.errors.join('\n') };
  177. const matches = [];
  178. for (const row of config.table || []) {
  179. let wildcards = 0;
  180. let matched = true;
  181. for (const dim of config.dimensions || []) {
  182. const expected = row[dim.key];
  183. if (expected === '*') {
  184. wildcards += 1;
  185. continue;
  186. }
  187. if (String(expected) !== String(requestValues?.[dim.key])) {
  188. matched = false;
  189. break;
  190. }
  191. }
  192. if (matched) matches.push({ row, wildcards });
  193. }
  194. matches.sort((a, b) => a.wildcards - b.wildcards);
  195. if (matches.length > 1 && matches[0].wildcards === matches[1].wildcards) return { mode: 'reject', error: 'ambiguous matching rows' };
  196. if (matches.length > 0) {
  197. const best = matches[0];
  198. return {
  199. mode: 'matched',
  200. row: best.row,
  201. price: Number(best.row.price),
  202. snapshot: buildSnapshot(config, requestValues, Number(best.row.price), 'matched'),
  203. };
  204. }
  205. if (config.fallback.strategy === FALLBACKS.reject) return { mode: 'reject', error: 'no pricing row matched' };
  206. if (config.fallback.strategy === FALLBACKS.max) {
  207. const price = Math.max(...config.table.map((row) => Number(row.price || 0)));
  208. return { mode: 'fallback_max', price, snapshot: buildSnapshot(config, requestValues, price, 'fallback_max', FALLBACKS.max) };
  209. }
  210. const price = Number(config.fallback.default_price || 0);
  211. return { mode: 'fallback_default', price, snapshot: buildSnapshot(config, requestValues, price, 'fallback_default', FALLBACKS.default) };
  212. };
  213. export const parseDimensionValue = (value, type) => {
  214. if (value === '*') return value;
  215. if (type === 'number') return Number(value);
  216. if (type === 'boolean') return value === true || value === 'true';
  217. return value;
  218. };
  219. const valueMatchesType = (value, type) => {
  220. if (type === 'number') return typeof value === 'number' && !Number.isNaN(value);
  221. if (type === 'boolean') return typeof value === 'boolean';
  222. return typeof value === 'string';
  223. };
  224. const patternsOverlap = (left, right) =>
  225. left.every((leftValue, index) => leftValue === '*' || right[index] === '*' || String(leftValue) === String(right[index]));
  226. const parseCsvLine = (line) => line.split(',').map((item) => item.trim());
  227. const escapeCsvValue = (value) => {
  228. const text = String(value);
  229. if (!/[",\n]/.test(text)) return text;
  230. return `"${text.replaceAll('"', '""')}"`;
  231. };
  232. const buildSnapshot = (config, values, price, mode, fallbackStrategy) => {
  233. const snapshot = {};
  234. for (const dim of config.dimensions || []) snapshot[dim.key] = values?.[dim.key] ?? null;
  235. snapshot.price = price;
  236. snapshot.billing_unit = config.billing_unit || BILLING_UNITS.perCall;
  237. snapshot.pricing_mode = mode;
  238. if (fallbackStrategy) snapshot.fallback_strategy = fallbackStrategy;
  239. return snapshot;
  240. };