dynamic-price.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import { formatBillingCurrencyFromUSD } from '@/lib/currency'
  2. import { TOKEN_UNIT_DIVISORS } from '../constants'
  3. import {
  4. BILLING_PRICING_VARS,
  5. parseTiersFromExpr,
  6. splitBillingExprAndRequestRules,
  7. tryParseRequestRuleExpr,
  8. type BillingVar,
  9. type ParsedTier,
  10. } from './billing-expr'
  11. import type { PricingModel, TokenUnit } from '../types'
  12. type DynamicPriceOptions = {
  13. tokenUnit: TokenUnit
  14. showRechargePrice?: boolean
  15. priceRate?: number
  16. usdExchangeRate?: number
  17. groupRatioMultiplier?: number
  18. }
  19. export type DynamicPriceEntry = {
  20. key: string
  21. field: string
  22. label: string
  23. shortLabel: string
  24. value: number
  25. formatted: string
  26. variable: BillingVar
  27. }
  28. export type DynamicPricingSummary = {
  29. tiers: ParsedTier[]
  30. tier: ParsedTier | null
  31. tierCount: number
  32. hasRequestRules: boolean
  33. isSpecialExpression: boolean
  34. rawExpression: string
  35. entries: DynamicPriceEntry[]
  36. primaryEntries: DynamicPriceEntry[]
  37. secondaryEntries: DynamicPriceEntry[]
  38. }
  39. const PRIMARY_DYNAMIC_FIELDS = new Set(['inputPrice', 'outputPrice'])
  40. export function isDynamicPricingModel(model: PricingModel): boolean {
  41. return model.billing_mode === 'tiered_expr' && Boolean(model.billing_expr)
  42. }
  43. export function getDynamicDisplayGroupRatio(model: PricingModel): number {
  44. const groups = Array.isArray(model.enable_groups) ? model.enable_groups : []
  45. const ratios = model.group_ratio || {}
  46. if (groups.length === 0) return 1
  47. let minRatio = Number.POSITIVE_INFINITY
  48. for (const group of groups) {
  49. const ratio = ratios[group]
  50. if (ratio !== undefined && ratio < minRatio) {
  51. minRatio = ratio
  52. }
  53. }
  54. return minRatio === Number.POSITIVE_INFINITY ? 1 : minRatio
  55. }
  56. function applyRechargeRate(
  57. price: number,
  58. showWithRecharge: boolean,
  59. priceRate: number,
  60. usdExchangeRate: number
  61. ): number {
  62. if (!showWithRecharge) return price
  63. return (price * priceRate) / usdExchangeRate
  64. }
  65. export function formatDynamicUnitPrice(
  66. valuePerMillionTokens: number,
  67. options: DynamicPriceOptions
  68. ): string {
  69. const groupRatio = options.groupRatioMultiplier ?? 1
  70. const priceRate = options.priceRate ?? 1
  71. const usdExchangeRate = options.usdExchangeRate ?? 1
  72. const priceUSD =
  73. (valuePerMillionTokens * groupRatio) /
  74. TOKEN_UNIT_DIVISORS[options.tokenUnit]
  75. const displayPrice = applyRechargeRate(
  76. priceUSD,
  77. options.showRechargePrice ?? false,
  78. priceRate,
  79. usdExchangeRate
  80. )
  81. return formatBillingCurrencyFromUSD(displayPrice, {
  82. digitsLarge: 4,
  83. digitsSmall: 6,
  84. abbreviate: false,
  85. })
  86. }
  87. export function getDynamicPricingTiers(model: PricingModel): ParsedTier[] {
  88. if (!isDynamicPricingModel(model)) return []
  89. const { billingExpr } = splitBillingExprAndRequestRules(model.billing_expr || '')
  90. return parseTiersFromExpr(billingExpr)
  91. }
  92. export function hasDynamicRequestRules(model: PricingModel): boolean {
  93. if (!isDynamicPricingModel(model)) return false
  94. const { requestRuleExpr } = splitBillingExprAndRequestRules(
  95. model.billing_expr || ''
  96. )
  97. return Boolean(tryParseRequestRuleExpr(requestRuleExpr || '')?.length)
  98. }
  99. export function getDynamicPriceEntries(
  100. tier: ParsedTier | null,
  101. options: DynamicPriceOptions
  102. ): DynamicPriceEntry[] {
  103. if (!tier) return []
  104. return BILLING_PRICING_VARS.flatMap((variable) => {
  105. if (!variable.field) return []
  106. const value = Number(tier[variable.field])
  107. if (!Number.isFinite(value) || value <= 0) return []
  108. return [
  109. {
  110. key: variable.key,
  111. field: variable.field,
  112. label: variable.label,
  113. shortLabel: variable.shortLabel,
  114. value,
  115. formatted: formatDynamicUnitPrice(value, options),
  116. variable,
  117. },
  118. ]
  119. }).sort((a, b) => {
  120. const aPrimary = PRIMARY_DYNAMIC_FIELDS.has(a.field)
  121. const bPrimary = PRIMARY_DYNAMIC_FIELDS.has(b.field)
  122. if (aPrimary !== bPrimary) return aPrimary ? -1 : 1
  123. return 0
  124. })
  125. }
  126. export function getDynamicPricingSummary(
  127. model: PricingModel,
  128. options: DynamicPriceOptions
  129. ): DynamicPricingSummary | null {
  130. if (!isDynamicPricingModel(model)) return null
  131. const tiers = getDynamicPricingTiers(model)
  132. const tier = tiers[0] || null
  133. const entries = getDynamicPriceEntries(tier, options)
  134. const rawExpression = model.billing_expr || ''
  135. return {
  136. tiers,
  137. tier,
  138. tierCount: tiers.length,
  139. hasRequestRules: hasDynamicRequestRules(model),
  140. isSpecialExpression: rawExpression.trim().length > 0 && tiers.length === 0,
  141. rawExpression,
  142. entries,
  143. primaryEntries: entries.filter((entry) =>
  144. PRIMARY_DYNAMIC_FIELDS.has(entry.field)
  145. ),
  146. secondaryEntries: entries.filter(
  147. (entry) => !PRIMARY_DYNAMIC_FIELDS.has(entry.field)
  148. ),
  149. }
  150. }