/*
Copyright (C) 2023-2026 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 {
AlertTriangle,
ChevronDown,
Search,
X,
Info,
Plus,
Trash2,
} from 'lucide-react'
import { Reorder } from 'motion/react'
import {
useState,
useMemo,
useEffect,
useCallback,
memo,
type ReactNode,
} from 'react'
import { useTranslation } from 'react-i18next'
import { AutoGroupOrderItem } from '@/components/auto-group-order-item'
import { StaticDataTable } from '@/components/data-table/static/static-data-table'
import { StaticRowActions } from '@/components/data-table/static/static-row-actions'
import { Dialog } from '@/components/dialog'
import {
sideDrawerContentClassName,
sideDrawerFormClassName,
sideDrawerHeaderClassName,
} from '@/components/drawer-layout'
import { EmptyState } from '@/components/empty-state'
import { StatusBadge } from '@/components/status-badge'
import { Button } from '@/components/ui/button'
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card'
import { Checkbox } from '@/components/ui/checkbox'
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { Combobox } from '@/components/ui/combobox'
import { Input } from '@/components/ui/input'
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { toIntlLocale } from '@/i18n/languages'
import { formatNumber } from '@/lib/format'
import { safeJsonParse } from '../utils/json-parser'
import { GroupSpecialUsableRulesEditor } from './group-special-usable-editor'
export type GroupSettingsSection =
| 'pricing'
| 'overrides'
| 'visibility'
| 'auto'
type GroupRatioVisualEditorProps = {
section: GroupSettingsSection
onSectionChange: (section: GroupSettingsSection) => void
defaultUseAutoGroupField: ReactNode
groupRatio: string
topupGroupRatio: string
userUsableGroups: string
groupGroupRatio: string
autoGroups: string
maxTokenAutoGroupsField: ReactNode
groupSpecialUsableGroup: string
onChange: (field: string, value: string) => void
}
type GroupPricingRow = {
_id: string
name: string
ratio: string
topupRatio: string
selectable: boolean
description: string
}
type RegistryEntry = {
name: string
ratio: number
}
const sectionCardClassName = 'min-w-0 shadow-none'
const sectionHeaderClassName = 'gap-2 border-b'
let groupPricingIdCounter = 0
function createGroupPricingId() {
groupPricingIdCounter += 1
return `gpr_${groupPricingIdCounter}`
}
function normalizeRatio(value: unknown): number {
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : 1
}
function parseRatioMap(value: string): Record {
return safeJsonParse>(value, {
fallback: {},
silent: true,
})
}
function parseUsableMap(value: string): Record {
return safeJsonParse>(value, {
fallback: {},
silent: true,
})
}
function parseNestedRatioMap(
value: string
): Record> {
return safeJsonParse>>(value, {
fallback: {},
silent: true,
})
}
function buildGroupPricingRows(
groupRatio: string,
userUsableGroups: string,
topupGroupRatio: string
): GroupPricingRow[] {
const ratioMap = parseRatioMap(groupRatio)
const usableMap = parseUsableMap(userUsableGroups)
const topupMap = parseRatioMap(topupGroupRatio)
const names = new Set([
...Object.keys(ratioMap),
...Object.keys(usableMap),
...Object.keys(topupMap),
])
return [...names].map((name) => ({
_id: createGroupPricingId(),
name,
ratio: String(normalizeRatio(ratioMap[name])),
topupRatio: Object.hasOwn(topupMap, name) ? String(topupMap[name]) : '',
selectable: Object.hasOwn(usableMap, name),
description: String(usableMap[name] ?? ''),
}))
}
function serializeGroupPricingRows(rows: GroupPricingRow[]) {
const groupRatio: Record = {}
const userUsableGroups: Record = {}
const topupGroupRatio: Record = {}
for (const row of rows) {
const name = row.name.trim()
if (!name) continue
groupRatio[name] = normalizeRatio(row.ratio)
if (row.selectable) {
userUsableGroups[name] = row.description
}
const topup = row.topupRatio.trim()
if (topup !== '' && Number.isFinite(Number(topup))) {
topupGroupRatio[name] = Number(topup)
}
}
return {
GroupRatio: JSON.stringify(groupRatio, null, 2),
UserUsableGroups: JSON.stringify(userUsableGroups, null, 2),
TopupGroupRatio: JSON.stringify(topupGroupRatio, null, 2),
}
}
function groupPricingSignature(rows: GroupPricingRow[]): string {
const serialized = serializeGroupPricingRows(rows)
return JSON.stringify({
groupRatio: parseRatioMap(serialized.GroupRatio),
userUsableGroups: parseUsableMap(serialized.UserUsableGroups),
topupGroupRatio: parseRatioMap(serialized.TopupGroupRatio),
})
}
function sourceGroupPricingSignature(
groupRatio: string,
userUsableGroups: string,
topupGroupRatio: string
): string {
return JSON.stringify({
groupRatio: parseRatioMap(groupRatio),
userUsableGroups: parseUsableMap(userUsableGroups),
topupGroupRatio: parseRatioMap(topupGroupRatio),
})
}
function UnknownGroupBadge() {
const { t } = useTranslation()
return (
{t('Not in pricing table')}
)
}
type GroupNameSelectProps = {
options: string[]
value: string | null
placeholder: string
onValueChange: (value: string) => void
className?: string
}
function GroupNameSelect(props: GroupNameSelectProps) {
const options = useMemo(() => {
if (props.value && !props.options.includes(props.value)) {
return [props.value, ...props.options]
}
return props.options
}, [props.options, props.value])
return (
({ value: name, label: name }))}
value={props.value}
onValueChange={(value) => {
if (value) props.onValueChange(value)
}}
className={props.className ?? 'w-48'}
placeholder={props.placeholder}
aria-label={props.placeholder}
/>
)
}
export const GroupRatioVisualEditor = memo(function GroupRatioVisualEditor({
section,
onSectionChange,
defaultUseAutoGroupField,
groupRatio,
topupGroupRatio,
userUsableGroups,
groupGroupRatio,
autoGroups,
maxTokenAutoGroupsField,
groupSpecialUsableGroup,
onChange,
}: GroupRatioVisualEditorProps) {
const { t, i18n } = useTranslation()
const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language)
const [detailGroup, setDetailGroup] = useState(null)
const registry = useMemo(() => {
const ratioMap = parseRatioMap(groupRatio)
const usableMap = parseUsableMap(userUsableGroups)
const topupMap = parseRatioMap(topupGroupRatio)
const names = new Set([
...Object.keys(ratioMap),
...Object.keys(usableMap),
...Object.keys(topupMap),
])
return [...names].map((name) => ({
name,
ratio: normalizeRatio(ratioMap[name]),
}))
}, [groupRatio, userUsableGroups, topupGroupRatio])
const registryNames = useMemo(
() => registry.map((entry) => entry.name),
[registry]
)
// Auto groups
const autoGroupsList = useMemo(() => {
return safeJsonParse(autoGroups, {
fallback: [],
context: 'auto groups',
})
}, [autoGroups])
const handleAutoGroupAdd = useCallback(
(name: string) => {
if (autoGroupsList.includes(name)) return
onChange('AutoGroups', JSON.stringify([...autoGroupsList, name], null, 2))
},
[autoGroupsList, onChange]
)
const handleAutoGroupDelete = useCallback(
(index: number) => {
const list = autoGroupsList.filter((_, i) => i !== index)
onChange('AutoGroups', JSON.stringify(list, null, 2))
},
[autoGroupsList, onChange]
)
const handleAutoGroupMove = useCallback(
(index: number, direction: 'up' | 'down') => {
const list = [...autoGroupsList]
const newIndex = direction === 'up' ? index - 1 : index + 1
if (newIndex < 0 || newIndex >= list.length) return
;[list[index], list[newIndex]] = [list[newIndex], list[index]]
onChange('AutoGroups', JSON.stringify(list, null, 2))
},
[autoGroupsList, onChange]
)
const autoGroupCandidates = useMemo(
() => registryNames.filter((name) => !autoGroupsList.includes(name)),
[registryNames, autoGroupsList]
)
return (
onSectionChange(value as GroupSettingsSection)}
className='min-w-0 gap-5'
>
{t('Pricing groups')}
{t('Special ratio rules')}
{t('Group visibility')}
{t('Auto group order')}
onChange('GroupSpecialUsableGroup', value)}
/>
{t('Auto group order')}
{t(
'Priority order for tokens in the auto group. The system tries groups from top to bottom.'
)}
{t('Pricing groups')}
{t(
'All group names live here. Ratio applies when calls are billed as this group; top-up ratio applies to users whose account is in this group.'
)}