dynamic-pricing-breakdown.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import { useMemo } from 'react'
  2. import { Tag as TagIcon } from 'lucide-react'
  3. import { useTranslation } from 'react-i18next'
  4. import { useSystemConfigStore } from '@/stores/system-config-store'
  5. import { cn } from '@/lib/utils'
  6. import { Badge } from '@/components/ui/badge'
  7. import {
  8. Table,
  9. TableBody,
  10. TableCell,
  11. TableHead,
  12. TableHeader,
  13. TableRow,
  14. } from '@/components/ui/table'
  15. import {
  16. BILLING_PRICING_VARS,
  17. MATCH_CONTAINS,
  18. MATCH_EQ,
  19. MATCH_EXISTS,
  20. MATCH_GTE,
  21. MATCH_LT,
  22. MATCH_RANGE,
  23. SOURCE_TIME,
  24. parseTiersFromExpr,
  25. splitBillingExprAndRequestRules,
  26. tryParseRequestRuleExpr,
  27. type ParsedTier,
  28. type RequestCondition,
  29. type RequestRuleGroup,
  30. type TierCondition,
  31. } from '../lib/billing-expr'
  32. type DynamicPricingBreakdownProps = {
  33. billingExpr: string | null | undefined
  34. /**
  35. * Label of the tier that fired for the current request. When provided,
  36. * the corresponding row is highlighted and tagged as "Matched". Used by
  37. * the usage-log details dialog to show which tier the engine selected.
  38. */
  39. matchedTierLabel?: string | null
  40. /**
  41. * Hide cache-pricing columns regardless of the per-tier values. The log
  42. * details dialog passes this when the actual request did not consume any
  43. * cache tokens, so users only see pricing rows that were relevant to the
  44. * call they are inspecting. Defaults to false (show all configured prices).
  45. */
  46. hideCacheColumns?: boolean
  47. }
  48. const VAR_LABELS: Record<string, string> = {
  49. p: 'Input',
  50. c: 'Output',
  51. len: 'Length',
  52. }
  53. const OP_LABELS: Record<string, string> = {
  54. '<': '<',
  55. '<=': '≤',
  56. '>': '>',
  57. '>=': '≥',
  58. }
  59. const TIME_FUNC_LABELS: Record<string, string> = {
  60. hour: 'Hour',
  61. minute: 'Minute',
  62. weekday: 'Weekday',
  63. month: 'Month',
  64. day: 'Day',
  65. }
  66. function formatTokenHint(value: string | number): string {
  67. const n = Number(value)
  68. if (!Number.isFinite(n) || n === 0) return ''
  69. if (n >= 1_000_000) {
  70. return `${(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
  71. }
  72. if (n >= 1000) {
  73. return `${(n / 1000).toFixed(n % 1000 === 0 ? 0 : 1)}K`
  74. }
  75. return String(n)
  76. }
  77. function formatConditionSummary(
  78. conditions: TierCondition[],
  79. t: (key: string) => string
  80. ): string {
  81. return conditions
  82. .map((c) => {
  83. const varLabel = t(VAR_LABELS[c.var] || c.var)
  84. const hint = formatTokenHint(c.value)
  85. return `${varLabel} ${OP_LABELS[c.op] || c.op} ${hint || c.value}`
  86. })
  87. .filter(Boolean)
  88. .join(' && ')
  89. }
  90. function describeCondition(
  91. cond: RequestCondition,
  92. t: (key: string) => string
  93. ): string {
  94. if (cond.source === SOURCE_TIME) {
  95. const fn = t(TIME_FUNC_LABELS[cond.timeFunc] || cond.timeFunc)
  96. const tz = cond.timezone || 'UTC'
  97. if (cond.mode === MATCH_RANGE) {
  98. return `${fn} ${cond.rangeStart}:00~${cond.rangeEnd}:00 (${tz})`
  99. }
  100. const opMap: Record<string, string> = {
  101. [MATCH_EQ]: '=',
  102. [MATCH_GTE]: '≥',
  103. [MATCH_LT]: '<',
  104. }
  105. return `${fn} ${opMap[cond.mode] || '='} ${cond.value} (${tz})`
  106. }
  107. const src = cond.source === 'header' ? t('Header') : t('Body param')
  108. const path = cond.path || ''
  109. if (cond.mode === MATCH_EXISTS) return `${src} ${path} ${t('Exists')}`
  110. if (cond.mode === MATCH_CONTAINS) {
  111. return `${src} ${path} ${t('Contains')} "${cond.value}"`
  112. }
  113. const opMap: Record<string, string> = {
  114. eq: '=',
  115. gt: '>',
  116. gte: '≥',
  117. lt: '<',
  118. lte: '≤',
  119. }
  120. return `${src} ${path} ${opMap[cond.mode] || '='} ${cond.value}`
  121. }
  122. function describeGroup(
  123. group: RequestRuleGroup,
  124. t: (key: string) => string
  125. ): string {
  126. return (group.conditions || [])
  127. .map((c) => describeCondition(c, t))
  128. .join(' && ')
  129. }
  130. export function DynamicPricingBreakdown({
  131. billingExpr,
  132. matchedTierLabel,
  133. hideCacheColumns = false,
  134. }: DynamicPricingBreakdownProps) {
  135. const { t } = useTranslation()
  136. const expr = billingExpr || ''
  137. const currency = useSystemConfigStore((s) => s.config.currency)
  138. const { symbol, rate } = useMemo(() => {
  139. if (currency.quotaDisplayType === 'CNY') {
  140. return { symbol: '¥', rate: currency.usdExchangeRate || 7 }
  141. }
  142. if (currency.quotaDisplayType === 'CUSTOM') {
  143. return {
  144. symbol: currency.customCurrencySymbol || '¤',
  145. rate: currency.customCurrencyExchangeRate || 1,
  146. }
  147. }
  148. return { symbol: '$', rate: 1 }
  149. }, [currency])
  150. const { tiers, ruleGroups } = useMemo(() => {
  151. const split = splitBillingExprAndRequestRules(expr)
  152. const parsedTiers = parseTiersFromExpr(split.billingExpr)
  153. const parsedRules = tryParseRequestRuleExpr(split.requestRuleExpr || '')
  154. return {
  155. tiers: parsedTiers,
  156. ruleGroups: parsedRules || [],
  157. }
  158. }, [expr])
  159. const hasTiers = tiers.length > 0
  160. const hasRules = ruleGroups.length > 0
  161. if (!expr) return null
  162. if (!hasTiers) {
  163. return (
  164. <section className='min-w-0 py-4'>
  165. <div className='mb-3 flex items-center gap-2'>
  166. <span className='inline-flex size-6 items-center justify-center rounded-full bg-amber-100 text-amber-700 shadow-sm dark:bg-amber-500/20 dark:text-amber-300'>
  167. <TagIcon className='size-3.5' />
  168. </span>
  169. <div>
  170. <div className='text-foreground text-base font-medium'>
  171. {t('Special billing expression')}
  172. </div>
  173. <div className='text-muted-foreground text-xs'>
  174. {t('Unable to parse structured pricing')}
  175. </div>
  176. </div>
  177. </div>
  178. <div className='text-muted-foreground mb-1 text-[10px] font-medium tracking-wider uppercase'>
  179. {t('Raw expression')}
  180. </div>
  181. <code className='text-muted-foreground block text-xs break-all'>
  182. {expr}
  183. </code>
  184. </section>
  185. )
  186. }
  187. const visiblePriceFields = BILLING_PRICING_VARS.filter((v) => {
  188. if (!hasTiers) return false
  189. if (hideCacheColumns && v.group === 'cache') return false
  190. return tiers.some(
  191. (tier) => Number(tier[v.field as string as keyof ParsedTier] || 0) > 0
  192. )
  193. })
  194. return (
  195. <section className='min-w-0 py-3 sm:py-4'>
  196. <div className='mb-3 flex items-start gap-2 sm:mb-4'>
  197. <span className='mt-0.5 inline-flex size-6 items-center justify-center rounded-full bg-amber-100 text-amber-700 shadow-sm dark:bg-amber-500/20 dark:text-amber-300'>
  198. <TagIcon className='size-3.5' />
  199. </span>
  200. <div>
  201. <div className='text-foreground text-base font-medium'>
  202. {t('Dynamic Pricing')}
  203. </div>
  204. <div className='text-muted-foreground text-xs'>
  205. {t('Prices vary by usage tier and request conditions')}
  206. </div>
  207. </div>
  208. </div>
  209. {hasTiers && (
  210. <div className='mb-3 sm:mb-4'>
  211. <div className='text-foreground mb-2 text-sm font-semibold'>
  212. {t('Tiered price table')}
  213. </div>
  214. <div className='space-y-1.5 sm:hidden'>
  215. {tiers.map((tier, i) => {
  216. const condSummary = formatConditionSummary(tier.conditions, t)
  217. const isMatched =
  218. matchedTierLabel != null &&
  219. matchedTierLabel !== '' &&
  220. tier.label === matchedTierLabel
  221. return (
  222. <div
  223. key={`tier-mobile-${i}`}
  224. className={cn(
  225. 'rounded-md border p-2',
  226. isMatched &&
  227. 'border-emerald-500/40 bg-emerald-500/10'
  228. )}
  229. >
  230. <div className='mb-1.5 flex flex-wrap items-center gap-1.5'>
  231. <Badge
  232. variant='secondary'
  233. className='bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300'
  234. >
  235. {tier.label || t('Default')}
  236. </Badge>
  237. {isMatched && (
  238. <Badge
  239. variant='secondary'
  240. className='bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'
  241. >
  242. {t('Matched')}
  243. </Badge>
  244. )}
  245. </div>
  246. {condSummary && (
  247. <div className='text-muted-foreground mb-1.5 text-xs'>
  248. {condSummary}
  249. </div>
  250. )}
  251. <div className='grid grid-cols-2 gap-x-3 gap-y-1.5'>
  252. {visiblePriceFields.map((v) => {
  253. const value = Number(
  254. tier[v.field as string as keyof ParsedTier] || 0
  255. )
  256. return (
  257. <div key={v.field} className='min-w-0'>
  258. <div className='text-muted-foreground truncate text-[10px] font-medium tracking-wider uppercase'>
  259. {t(v.shortLabel)}
  260. </div>
  261. <div className='truncate font-mono text-sm font-semibold'>
  262. {value > 0
  263. ? `${symbol}${(value * rate).toFixed(4)}`
  264. : '-'}
  265. </div>
  266. </div>
  267. )
  268. })}
  269. </div>
  270. </div>
  271. )
  272. })}
  273. </div>
  274. <div className='hidden overflow-x-auto sm:block'>
  275. <Table className='text-sm'>
  276. <TableHeader>
  277. <TableRow className='hover:bg-transparent'>
  278. <TableHead className='text-muted-foreground py-2 text-[10px] font-medium tracking-wider uppercase'>
  279. {t('Tier')}
  280. </TableHead>
  281. {visiblePriceFields.map((v) => (
  282. <TableHead
  283. key={v.field}
  284. className='text-muted-foreground py-2 text-right text-[10px] font-medium tracking-wider uppercase'
  285. >
  286. {t(v.shortLabel)}
  287. </TableHead>
  288. ))}
  289. </TableRow>
  290. </TableHeader>
  291. <TableBody>
  292. {tiers.map((tier, i) => {
  293. const condSummary = formatConditionSummary(tier.conditions, t)
  294. const isMatched =
  295. matchedTierLabel != null &&
  296. matchedTierLabel !== '' &&
  297. tier.label === matchedTierLabel
  298. return (
  299. <TableRow
  300. key={`tier-${i}`}
  301. className={cn(
  302. isMatched &&
  303. 'bg-emerald-50/70 hover:bg-emerald-50/70 dark:bg-emerald-500/10 dark:hover:bg-emerald-500/10'
  304. )}
  305. >
  306. <TableCell className='py-2.5 align-top'>
  307. <div className='flex flex-wrap items-center gap-1.5'>
  308. <Badge
  309. variant='secondary'
  310. className='bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300'
  311. >
  312. {tier.label || t('Default')}
  313. </Badge>
  314. {isMatched && (
  315. <Badge
  316. variant='secondary'
  317. className='bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'
  318. >
  319. {t('Matched')}
  320. </Badge>
  321. )}
  322. </div>
  323. {condSummary && (
  324. <div className='text-muted-foreground mt-1 text-xs'>
  325. {condSummary}
  326. </div>
  327. )}
  328. </TableCell>
  329. {visiblePriceFields.map((v) => {
  330. const value = Number(
  331. tier[v.field as string as keyof ParsedTier] || 0
  332. )
  333. return (
  334. <TableCell
  335. key={v.field}
  336. className='py-2.5 text-right align-top font-mono'
  337. >
  338. {value > 0 ? (
  339. <span className='font-semibold'>
  340. {`${symbol}${(value * rate).toFixed(4)}`}
  341. </span>
  342. ) : (
  343. '-'
  344. )}
  345. </TableCell>
  346. )
  347. })}
  348. </TableRow>
  349. )
  350. })}
  351. </TableBody>
  352. </Table>
  353. </div>
  354. </div>
  355. )}
  356. {hasRules && (
  357. <div>
  358. <div className='text-foreground mb-2 text-sm font-semibold'>
  359. {t('Conditional multipliers')}
  360. </div>
  361. <ul className='space-y-1.5'>
  362. {ruleGroups.map((group, gi) => (
  363. <li
  364. key={`group-${gi}`}
  365. className='bg-muted/50 flex items-center justify-between gap-3 rounded-md px-3 py-2'
  366. >
  367. <span className='text-foreground text-sm break-all'>
  368. {describeGroup(group, t)}
  369. </span>
  370. <Badge
  371. variant='secondary'
  372. className='shrink-0 bg-orange-100 text-orange-700 dark:bg-orange-500/20 dark:text-orange-300'
  373. >
  374. {group.multiplier}x
  375. </Badge>
  376. </li>
  377. ))}
  378. </ul>
  379. </div>
  380. )}
  381. </section>
  382. )
  383. }