Files
PnvPanel/frontend/src/features/configs/CreateConfigDialog.tsx
T
mrleo1nidandClaude Opus 5.5 bb5e59904f
CI / Backend (build + test) (push) Failing after 1m36s
CI / Frontend (lint + typecheck + build) (push) Successful in 41s
Add inbound country flags and node load in location picker
- Inbound.CountryCode (ISO alpha-2), set on publish; flag shown before
  the location name (SVG via country-flag-icons on the site, emoji in bot)
- Node.Capacity (optional, not a limit); available inbounds report load
  percent of capacity or active config count, sorted least loaded first

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 19:45:17 +03:00

132 lines
5.1 KiB
TypeScript

import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { Plus } from 'lucide-react'
import { toast } from '@/shared/ui/toast-store'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/shared/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { HttpError } from '@/shared/api/client'
import type { AvailableInboundDto } from '@/shared/api/types'
import { CountryFlag } from '@/shared/ui/country-flag'
import { cn } from '@/shared/lib/cn'
import { createConfig } from './api'
// Пороги «светофора» загрузки ноды, % от ёмкости.
const LOAD_MEDIUM = 50
const LOAD_HIGH = 80
function NodeLoad({ inbound }: { inbound: AvailableInboundDto }) {
const { t } = useTranslation()
if (inbound.loadPercent !== null) {
const level = inbound.loadPercent >= LOAD_HIGH ? 'high' : inbound.loadPercent >= LOAD_MEDIUM ? 'medium' : 'low'
return (
<span className="ml-auto flex items-center gap-1.5 pl-3 text-xs text-muted-foreground">
<span
className={cn(
'h-2 w-2 rounded-full',
level === 'high' ? 'bg-red-500' : level === 'medium' ? 'bg-amber-500' : 'bg-emerald-500',
)}
aria-hidden
/>
{t(`configs.load.${level}`)} · {inbound.loadPercent}%
</span>
)
}
if (inbound.nodeConfigCount !== null) {
return (
<span className="ml-auto pl-3 text-xs text-muted-foreground">
{t('configs.nodeConfigs', { count: inbound.nodeConfigCount })}
</span>
)
}
return null
}
export function CreateConfigDialog({ inbounds }: { inbounds: AvailableInboundDto[] }) {
const { t } = useTranslation()
const queryClient = useQueryClient()
const navigate = useNavigate()
const [open, setOpen] = useState(false)
const [inboundId, setInboundId] = useState('')
const [label, setLabel] = useState('')
const createMutation = useMutation({
mutationFn: () => createConfig(inboundId, label.trim() || undefined),
onSuccess: async () => {
toast.success(t('configs.created'))
await queryClient.invalidateQueries({ queryKey: ['my-configs'] })
setOpen(false)
setInboundId('')
setLabel('')
},
onError: (error) => {
// Safety-net: дашборд уже скрывает эту кнопку при истёкшей оплате (см. dashboard.tsx), но
// между открытием страницы и отправкой формы биллинг мог протухнуть — сервер всё равно
// проверяет (ConfigErrors.BillingRequired) и на всякий случай отправляем на оплату.
if (error instanceof HttpError && error.title === 'Configs.BillingRequired') {
toast.error(t('configs.billingRequiredNotice'))
setOpen(false)
void navigate({ to: '/billing' })
return
}
const message =
error instanceof HttpError && error.status === 409 ? t('configs.quotaExceeded') : t('auth.genericError')
toast.error(message)
},
})
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4" />
{t('configs.create')}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('configs.create')}</DialogTitle>
</DialogHeader>
<form
className="flex flex-col gap-4"
onSubmit={(e) => {
e.preventDefault()
if (inboundId) createMutation.mutate()
}}
>
<div className="flex flex-col gap-1.5">
<Label>{t('configs.location')}</Label>
<Select value={inboundId} onValueChange={setInboundId}>
<SelectTrigger>
<SelectValue placeholder={t('configs.selectLocation')} />
</SelectTrigger>
<SelectContent>
{inbounds.map((inbound) => (
<SelectItem key={inbound.inboundId} value={inbound.inboundId}>
<span className="flex w-full items-center gap-2">
<CountryFlag code={inbound.countryCode} />
{inbound.displayName} ({inbound.protocol})
<NodeLoad inbound={inbound} />
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="label">{t('configs.label')}</Label>
<Input id="label" value={label} onChange={(e) => setLabel(e.target.value)} />
</div>
<Button type="submit" disabled={!inboundId || createMutation.isPending}>
{t('configs.create')}
</Button>
</form>
</DialogContent>
</Dialog>
)
}