Enhance user plan management and update related endpoints
CI / Backend (build + test) (push) Failing after 1m23s
CI / Frontend (lint + typecheck + build) (push) Successful in 34s

- Added new configuration options for user plans in `.env.example`, including `Plans__MaxCustomConfigCount` and `Plans__MinCustomConfigCount`.
- Introduced `MapPlanEndpoints` in `Program.cs` to handle plan-related API routes.
- Implemented `SetUserPlan` endpoint in `RoleEndpoints` to allow admins to assign plans to users.
- Removed deprecated role request approval endpoints from `AdminSupportEndpoints`.
- Updated `ITelegramNotifier` and related classes to reflect changes in role request handling and payment notifications.
- Refactored role management commands to remove `MaxConfigs` and focus on `MaxIpLimit` and billing settings.
- Enhanced billing request handling to accommodate plan changes instead of role changes.
- Updated various interfaces and command handlers to support new plan management features.
This commit is contained in:
Leonid Pershin
2026-07-23 22:52:20 +03:00
parent 2c5b730500
commit fad03c2834
152 changed files with 4060 additions and 2240 deletions
+1
View File
@@ -11,6 +11,7 @@ const TABS = [
{ to: '/admin/users', key: 'users' },
{ to: '/admin/configs', key: 'configs' },
{ to: '/admin/roles', key: 'roles' },
{ to: '/admin/plans', key: 'plans' },
{ to: '/admin/pricing', key: 'pricing' },
{ to: '/admin/billing', key: 'billing' },
{ to: '/admin/nodes', key: 'nodes' },
+3 -3
View File
@@ -20,7 +20,7 @@ import {
export const Route = createFileRoute('/admin/billing')({ component: AdminBillingPage })
const KIND_FILTERS: (PaymentRequestKind | 'All')[] = ['Subscription', 'RoleChangeTopUp', 'All']
const KIND_FILTERS: (PaymentRequestKind | 'All')[] = ['Subscription', 'PlanChangeTopUp', 'All']
const STATUS_FILTERS: (PaymentRequestStatus | 'All')[] = [
'AwaitingConfirmation',
@@ -162,7 +162,7 @@ function RequestsSection() {
<SelectContent>
{KIND_FILTERS.map((k) => (
<SelectItem key={k} value={k}>
{k === 'All' ? t('admin.billing.allKinds') : k === 'RoleChangeTopUp' ? t('billing.roleChangeTopUp') : t('billing.subscription')}
{k === 'All' ? t('admin.billing.allKinds') : k === 'PlanChangeTopUp' ? t('billing.planChangeTopUp') : t('billing.subscription')}
</SelectItem>
))}
</SelectContent>
@@ -200,7 +200,7 @@ function RequestsSection() {
<tr key={request.id} className="border-b border-border">
<td className="py-2">{request.userName}</td>
<td className="py-2">
{request.kind === 'RoleChangeTopUp' ? t('billing.roleChangeTopUp') : t(`billing.periods.${request.period}`)}
{request.kind === 'PlanChangeTopUp' ? t('billing.planChangeTopUp') : t(`billing.periods.${request.period}`)}
</td>
<td className="py-2">{request.amountSnapshot} </td>
<td className="py-2">
+122
View File
@@ -0,0 +1,122 @@
import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/shared/ui/toast-store'
import { Button } from '@/shared/ui/button'
import { Badge } from '@/shared/ui/badge'
import { listAdminPlans, deletePlan } from '@/features/admin/plans/api'
import { PlanFormDialog } from '@/features/admin/plans/PlanFormDialog'
import { getPricingSettings } from '@/features/admin/pricing/api'
import { applyDiscount, resolveDiscountPercent } from '@/shared/lib/pricing'
import type { AdminPlanDto } from '@/shared/api/types'
export const Route = createFileRoute('/admin/plans')({ component: AdminPlansPage })
function AdminPlansPage() {
const { t } = useTranslation()
const queryClient = useQueryClient()
const [editing, setEditing] = useState<AdminPlanDto | null>(null)
const { data, isLoading, isError, refetch } = useQuery({ queryKey: ['admin-plans'], queryFn: listAdminPlans })
const { data: pricing } = useQuery({ queryKey: ['admin-pricing'], queryFn: getPricingSettings })
const priceCell = (monthlyRate: number | null | undefined, configCount: number, months: number) => {
if (monthlyRate == null) return <span>{t('admin.plans.noPrice')}</span>
const original = monthlyRate * months * configCount
const percent = resolveDiscountPercent(pricing?.discountTiers ?? [], configCount)
if (percent <= 0) return <span>{original} </span>
const discounted = applyDiscount(original, percent)
return (
<span className="flex flex-col">
<span className="text-xs text-muted-foreground line-through">{original} </span>
<span className="flex items-center gap-1">
{discounted}
<Badge variant="success">-{percent}%</Badge>
</span>
</span>
)
}
const deleteMutation = useMutation({
mutationFn: deletePlan,
onSuccess: async () => {
toast.success(t('admin.plans.deleted'))
await queryClient.invalidateQueries({ queryKey: ['admin-plans'] })
},
onError: () => toast.error(t('auth.genericError')),
})
return (
<div className="flex flex-col gap-4">
<div className="flex justify-end">
<PlanFormDialog />
</div>
{isLoading && <p className="text-sm text-muted-foreground"></p>}
{isError && (
<div className="flex items-center gap-2">
<p className="text-sm text-muted-foreground">{t('auth.genericError')}</p>
<Button variant="outline" size="sm" onClick={() => void refetch()}>
{t('activation.retry')}
</Button>
</div>
)}
{data?.length === 0 && <p className="text-sm text-muted-foreground">{t('admin.plans.empty')}</p>}
{data && data.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead>
<tr className="border-b border-border text-muted-foreground">
<th className="py-2 font-medium">{t('admin.plans.name')}</th>
<th className="py-2 font-medium">{t('admin.plans.configCount')}</th>
<th className="py-2 font-medium">{t('admin.plans.totalPerQuarter')}</th>
<th className="py-2 font-medium">{t('admin.plans.totalHalfYear')}</th>
<th className="py-2 font-medium">{t('admin.plans.totalPerYear')}</th>
<th className="py-2" />
<th className="py-2" />
</tr>
</thead>
<tbody>
{data.map((plan) => (
<tr key={plan.id} className="border-b border-border">
<td className="py-2">
{plan.name} {!plan.isEnabled && <Badge variant="outline">{t('admin.plans.disabled')}</Badge>}
</td>
<td className="py-2">{plan.configCount}</td>
<td className="py-2">{priceCell(pricing?.pricePerConfigPerQuarter, plan.configCount, 3)}</td>
<td className="py-2">{priceCell(pricing?.pricePerConfigPerHalfYear, plan.configCount, 6)}</td>
<td className="py-2">{priceCell(pricing?.pricePerConfigPerYear, plan.configCount, 12)}</td>
<td className="py-2 text-right">
<Button size="sm" variant="outline" onClick={() => setEditing(plan)}>
{t('admin.plans.edit')}
</Button>
</td>
<td className="py-2 text-right">
<Button
size="sm"
variant="ghost"
disabled={deleteMutation.isPending}
onClick={() => {
if (confirm(t('admin.plans.confirmDelete'))) deleteMutation.mutate(plan.id)
}}
>
{t('admin.plans.delete')}
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{editing && <PlanFormDialog plan={editing} open={!!editing} onOpenChange={(open) => !open && setEditing(null)} />}
</div>
)
}
-32
View File
@@ -7,8 +7,6 @@ import { Button } from '@/shared/ui/button'
import { Badge } from '@/shared/ui/badge'
import { listRoles, deleteRole } from '@/features/admin/roles/api'
import { RoleFormDialog } from '@/features/admin/roles/RoleFormDialog'
import { getPricingSettings } from '@/features/admin/pricing/api'
import { applyDiscount, resolveDiscountPercent } from '@/shared/lib/pricing'
import type { RoleDto } from '@/shared/api/types'
export const Route = createFileRoute('/admin/roles')({ component: AdminRolesPage })
@@ -19,28 +17,6 @@ function AdminRolesPage() {
const [editing, setEditing] = useState<RoleDto | null>(null)
const { data, isLoading, isError, refetch } = useQuery({ queryKey: ['admin-roles'], queryFn: listRoles })
const { data: pricing } = useQuery({ queryKey: ['admin-pricing'], queryFn: getPricingSettings })
// Ставки — цена за конфиг В МЕСЯЦ при данном тарифе; итог за период = ставка × месяцев × квота,
// затем скидка по лесенке (см. shared/lib/pricing) — за роль с большей квотой конфигов.
const priceCell = (monthlyRate: number | null | undefined, maxConfigs: number, months: number) => {
if (monthlyRate == null || maxConfigs < 0) return <span>{t('admin.roles.noPrice')}</span>
const original = monthlyRate * months * maxConfigs
const percent = resolveDiscountPercent(pricing?.discountTiers ?? [], maxConfigs)
if (percent <= 0) return <span>{original} </span>
const discounted = applyDiscount(original, percent)
return (
<span className="flex flex-col">
<span className="text-xs text-muted-foreground line-through">{original} </span>
<span className="flex items-center gap-1">
{discounted}
<Badge variant="success">-{percent}%</Badge>
</span>
</span>
)
}
const deleteMutation = useMutation({
mutationFn: deleteRole,
@@ -74,11 +50,7 @@ function AdminRolesPage() {
<thead>
<tr className="border-b border-border text-muted-foreground">
<th className="py-2 font-medium">{t('admin.roles.name')}</th>
<th className="py-2 font-medium">{t('admin.roles.maxConfigs')}</th>
<th className="py-2 font-medium">{t('admin.roles.maxIpLimit')}</th>
<th className="py-2 font-medium">{t('admin.roles.totalPerQuarter')}</th>
<th className="py-2 font-medium">{t('admin.roles.totalHalfYear')}</th>
<th className="py-2 font-medium">{t('admin.roles.totalPerYear')}</th>
<th className="py-2" />
<th className="py-2" />
</tr>
@@ -90,11 +62,7 @@ function AdminRolesPage() {
{role.name} {role.isSystem && <Badge variant="outline">{t('admin.roles.system')}</Badge>}{' '}
{role.billingEnabled && <Badge variant="success">{t('admin.roles.billingBadge')}</Badge>}
</td>
<td className="py-2">{role.maxConfigs < 0 ? t('unlimited') : role.maxConfigs}</td>
<td className="py-2">{role.maxIpLimit < 0 ? t('unlimited') : role.maxIpLimit}</td>
<td className="py-2">{priceCell(pricing?.pricePerConfigPerQuarter, role.maxConfigs, 3)}</td>
<td className="py-2">{priceCell(pricing?.pricePerConfigPerHalfYear, role.maxConfigs, 6)}</td>
<td className="py-2">{priceCell(pricing?.pricePerConfigPerYear, role.maxConfigs, 12)}</td>
<td className="py-2 text-right">
<Button size="sm" variant="outline" onClick={() => setEditing(role)}>
{t('admin.roles.edit')}
+1 -1
View File
@@ -10,7 +10,7 @@ import { AdminTicketDetailDialog } from '@/features/admin/support/AdminTicketDet
import { listAllTickets } from '@/features/admin/support/api'
import type { TicketStatus, TicketType } from '@/shared/api/types'
const TYPES: TicketType[] = ['BugReport', 'RoleRequest', 'ExtensionRequest']
const TYPES: TicketType[] = ['BugReport', 'ExtensionRequest']
const STATUSES: TicketStatus[] = ['Open', 'Resolved', 'Closed']
export const Route = createFileRoute('/admin/support')({
+6 -2
View File
@@ -43,9 +43,13 @@ function ConfigsList() {
<h1 className="text-2xl font-semibold tracking-tight">{t('configs.title')}</h1>
{data && (
<p className="text-sm text-muted-foreground">
{data.maxConfigs < 0
{data.configQuota < 0
? t('configs.quotaUnlimited', { used: data.configs.length })
: t('configs.quota', { used: data.configs.length, max: data.maxConfigs })}
: t('configs.quota', { used: data.configs.length, max: data.configQuota })}
{' · '}
<Link to="/plan" className="underline underline-offset-2 hover:text-foreground">
{t('plan.changePlan')}
</Link>
</p>
)}
{billingStatusQuery.data?.billingEnabled && (
+181
View File
@@ -0,0 +1,181 @@
import { useEffect, useMemo, useState } from 'react'
import { createFileRoute, Link } from '@tanstack/react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { useRequireAuth } from '@/features/auth/guards'
import { ActivationGate } from '@/features/activation/ActivationGate'
import { Button } from '@/shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'
import { Input } from '@/shared/ui/input'
import { toast } from '@/shared/ui/toast-store'
import { HttpError } from '@/shared/api/client'
import { applyDiscount, resolveDiscountPercent } from '@/shared/lib/pricing'
import { getMyConfigs } from '@/features/configs/api'
import { getSupportPricing } from '@/features/support/api'
import { changePlan, getMyPlanStatus, listPlans } from '@/features/plans/api'
export const Route = createFileRoute('/plan')({ component: PlanPage })
function PlanPage() {
const { isReady } = useRequireAuth()
if (!isReady) return null
return (
<ActivationGate>
<PlanContent />
</ActivationGate>
)
}
function PlanContent() {
const { t } = useTranslation()
const queryClient = useQueryClient()
const plansQuery = useQuery({ queryKey: ['plans'], queryFn: listPlans })
const statusQuery = useQuery({ queryKey: ['my-plan-status'], queryFn: getMyPlanStatus })
const pricingQuery = useQuery({ queryKey: ['support-pricing'], queryFn: getSupportPricing })
const configsQuery = useQuery({ queryKey: ['my-configs'], queryFn: getMyConfigs })
const [selection, setSelection] = useState<string>('')
const [customCount, setCustomCount] = useState('3')
const [configIdsToRevoke, setConfigIdsToRevoke] = useState<string[]>([])
useEffect(() => {
if (!selection && statusQuery.data) {
setSelection(statusQuery.data.planId ?? 'custom')
if (statusQuery.data.planId == null) setCustomCount(String(statusQuery.data.configQuota))
}
}, [selection, statusQuery.data])
const targetCount = selection === 'custom' ? Number(customCount) || 0 : (plansQuery.data?.find((p) => p.id === selection)?.configCount ?? 0)
// Expired (приостановленные за неуплату) тоже занимают квоту — при следующей оплате они
// вернутся в Active целиком, так что не выбрать их здесь на понижении означало бы превысить
// новую квоту после оплаты (см. ChangePlanCommandHandler).
const liveConfigs = useMemo(
() => configsQuery.data?.configs.filter((c) => c.status === 'Active' || c.status === 'Expired') ?? [],
[configsQuery.data],
)
const excess = Math.max(0, liveConfigs.length - targetCount)
const needsRevokePicker = excess > 0
const mutation = useMutation({
mutationFn: () =>
changePlan(
selection === 'custom' ? undefined : selection,
selection === 'custom' ? Number(customCount) : undefined,
configIdsToRevoke,
),
onSuccess: async (result) => {
toast.success(t('plan.changed'))
if (result.topUpAmount != null) toast.success(t('plan.topUpCreated'))
setConfigIdsToRevoke([])
await queryClient.invalidateQueries({ queryKey: ['my-plan-status'] })
await queryClient.invalidateQueries({ queryKey: ['my-configs'] })
await queryClient.invalidateQueries({ queryKey: ['my-billing-status'] })
},
onError: (error) => toast.error(error instanceof HttpError ? error.detail : t('auth.genericError')),
})
const priceFor = (monthlyRate: number | null | undefined, count: number, months: number) => {
if (monthlyRate == null || count <= 0) return t('plan.noPrice')
const original = monthlyRate * months * count
const percent = resolveDiscountPercent(pricingQuery.data?.discountTiers ?? [], count)
return percent > 0 ? `${applyDiscount(original, percent)}` : `${original}`
}
const toggleConfig = (id: string) => {
setConfigIdsToRevoke((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]))
}
const canSubmit = targetCount >= 1 && (!needsRevokePicker || configIdsToRevoke.length === excess)
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-6 px-6 py-10">
<div>
<h1 className="text-2xl font-semibold tracking-tight">{t('plan.title')}</h1>
{statusQuery.data && (
<p className="text-sm text-muted-foreground">
{statusQuery.data.configQuota < 0
? t('plan.currentUnlimited')
: t('plan.current', { count: statusQuery.data.configQuota })}
</p>
)}
</div>
<div className="flex flex-col gap-3">
{plansQuery.data?.map((p) => (
<label
key={p.id}
className="flex cursor-pointer items-center justify-between rounded-md border border-border p-3 text-sm has-[:checked]:border-foreground"
>
<span className="flex items-center gap-2">
<input type="radio" name="plan" checked={selection === p.id} onChange={() => setSelection(p.id)} />
<span className="font-medium">{p.name}</span>
<span className="text-muted-foreground"> {p.configCount}</span>
</span>
<span className="flex flex-col items-end text-xs text-muted-foreground">
<span>{t('plan.perQuarter', { price: priceFor(pricingQuery.data?.pricePerConfigPerQuarter, p.configCount, 3) })}</span>
<span>{t('plan.perHalfYear', { price: priceFor(pricingQuery.data?.pricePerConfigPerHalfYear, p.configCount, 6) })}</span>
<span>{t('plan.perYear', { price: priceFor(pricingQuery.data?.pricePerConfigPerYear, p.configCount, 12) })}</span>
</span>
</label>
))}
<label className="flex cursor-pointer items-center gap-3 rounded-md border border-border p-3 text-sm has-[:checked]:border-foreground">
<input type="radio" name="plan" checked={selection === 'custom'} onChange={() => setSelection('custom')} />
<span className="font-medium">{t('plan.custom')}</span>
<Input
type="number"
min={3}
className="w-24"
value={customCount}
onChange={(e) => {
setCustomCount(e.target.value)
setSelection('custom')
}}
/>
</label>
</div>
{needsRevokePicker && (
<div className="flex flex-col gap-2 rounded-md border border-border p-3">
<p className="text-sm font-medium">{t('plan.downgradeNotice')}</p>
<p className="text-xs text-muted-foreground">{t('plan.selectExactly', { count: excess })}</p>
<div className="flex flex-col gap-1">
{liveConfigs.map((c) => (
<label key={c.id} className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={configIdsToRevoke.includes(c.id)}
onChange={() => toggleConfig(c.id)}
/>
{c.label || c.clientEmail} <span className="text-xs text-muted-foreground">({c.location})</span>
{c.status === 'Expired' && (
<span className="text-xs text-muted-foreground"> {t('configs.status.Expired')}</span>
)}
</label>
))}
</div>
</div>
)}
<Button disabled={!canSubmit || mutation.isPending} onClick={() => mutation.mutate()}>
{t('plan.submit')}
</Button>
{mutation.data?.topUpAmount != null && (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('plan.topUpCreated')}</CardTitle>
</CardHeader>
<CardContent>
<Link to="/billing" className="font-medium text-foreground underline underline-offset-2">
{t('plan.goToBilling')}
</Link>
</CardContent>
</Card>
)}
</div>
)
}