Epic 5 Complete: Billing, Subscriptions, and Admin Features

Resolve all 5 deferred items from Epic 5 adversarial code review:
- Migration 124: Add CASCADE to subscriptionstatus enum drop (prevent orphaned references)
- Stripe rate limiting: In-memory per-user limiter (20 calls/60s) on verify-checkout-session
- Subscription request cooldown: 24h cooldown before resubmitting rejected requests
- Token reset date: Initialize on first subscription activation
- Checkout URL validation: Confirmed HTTPS-only (Stripe always returns HTTPS)

Implement Story 5.4 (Usage Tracking & Rate Limit Enforcement):
- Page quota pre-check at HTTP upload layer
- Extend UserRead schema with token quota fields
- Frontend 402 error handling in document upload
- Quota indicator in dashboard sidebar

Story 5.5 (Admin Seed & Approval Flow):
- Seed admin user migration with default credentials warning
- Subscription approval/rejection routes with admin guard
- 24h rejection cooldown enforcement

Story 5.6 (Admin-Only Model Config):
- Global model config visible across all search spaces
- Per-search-space model configs with user access control
- Superuser CRUD for global configs

Additional fixes from code review:
- PageLimitService: PAST_DUE subscriptions enforce free-tier limits
- TokenQuotaService: PAST_DUE subscriptions enforce free-tier limits
- Config routes: Fixed user_id.is_(None) filter on mutation endpoints
- Stripe webhook: Added guard against silent plan downgrade on unrecognized price_id

All changes formatted with Ruff (Python) and Biome (TypeScript).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Vonic 2026-04-15 03:54:45 +07:00
parent 20c4f128bb
commit 4eb6ed18d6
41 changed files with 1771 additions and 318 deletions

View file

@ -1,7 +1,8 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useSetAtom } from "jotai";
import { useAtomValue, useSetAtom } from "jotai";
import { currentUserAtom } from "@/atoms/user/user-query.atoms";
import { selectedSystemModelIdAtom } from "@/atoms/new-llm-config/system-models-query.atoms";
import { ImageConfigDialog } from "@/components/shared/image-config-dialog";
import { ModelConfigDialog } from "@/components/shared/model-config-dialog";
@ -24,6 +25,9 @@ interface ChatHeaderProps {
}
export function ChatHeader({ searchSpaceId, className }: ChatHeaderProps) {
const { data: currentUser } = useAtomValue(currentUserAtom);
const isAdmin = !!currentUser?.is_superuser;
// Reset system model selection when search space changes
const setSelectedSystemModelId = useSetAtom(selectedSystemModelIdAtom);
useEffect(() => {
@ -129,12 +133,12 @@ export function ChatHeader({ searchSpaceId, className }: ChatHeaderProps) {
<SystemModelSelector className={className} />
) : (
<ModelSelector
onEditLLM={handleEditLLMConfig}
onAddNewLLM={handleAddNewLLM}
onEditImage={handleEditImageConfig}
onAddNewImage={handleAddImageModel}
onEditVision={handleEditVisionConfig}
onAddNewVision={handleAddVisionModel}
onEditLLM={isAdmin ? handleEditLLMConfig : undefined}
onAddNewLLM={isAdmin ? handleAddNewLLM : undefined}
onEditImage={isAdmin ? handleEditImageConfig : undefined}
onAddNewImage={isAdmin ? handleAddImageModel : undefined}
onEditVision={isAdmin ? handleEditVisionConfig : undefined}
onAddNewVision={isAdmin ? handleAddVisionModel : undefined}
className={className}
/>
)}

View file

@ -2,7 +2,7 @@
import { useAtomValue } from "jotai";
import { Bot, Check, ChevronDown, Edit3, Eye, ImageIcon, Plus, Search, Zap } from "lucide-react";
import { type UIEvent, useCallback, useMemo, useState } from "react";
import { type UIEvent, useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import {
globalImageGenConfigsAtom,
@ -45,8 +45,8 @@ import { getProviderIcon } from "@/lib/provider-icons";
import { cn } from "@/lib/utils";
interface ModelSelectorProps {
onEditLLM: (config: NewLLMConfigPublic | GlobalNewLLMConfig, isGlobal: boolean) => void;
onAddNewLLM: () => void;
onEditLLM?: (config: NewLLMConfigPublic | GlobalNewLLMConfig, isGlobal: boolean) => void;
onAddNewLLM?: () => void;
onEditImage?: (config: ImageGenerationConfig | GlobalImageGenConfig, isGlobal: boolean) => void;
onAddNewImage?: () => void;
onEditVision?: (config: VisionLLMConfig | GlobalVisionLLMConfig, isGlobal: boolean) => void;
@ -155,6 +155,30 @@ export function ModelSelector({
);
}, [currentVisionConfig]);
// ─── Auto-reset stale config selections ───
// When configs finish loading and a saved preference points to a deleted config,
// silently clear the stale ID so the UI shows "Select a model" instead of erroring.
useEffect(() => {
if (!preferences || !searchSpaceId || llmUserLoading || llmGlobalLoading || prefsLoading)
return;
const agentLlmId = preferences.agent_llm_id;
if (agentLlmId === null || agentLlmId === undefined) return;
const existsInUser = llmUserConfigs?.some((c) => c.id === agentLlmId);
const existsInGlobal = llmGlobalConfigs?.some((c) => c.id === agentLlmId);
if (!existsInUser && !existsInGlobal) {
updatePreferences({ search_space_id: Number(searchSpaceId), data: { agent_llm_id: null } });
}
}, [
preferences,
llmUserConfigs,
llmGlobalConfigs,
llmUserLoading,
llmGlobalLoading,
prefsLoading,
searchSpaceId,
updatePreferences,
]);
// ─── LLM filtering ───
const filteredLLMGlobal = useMemo(() => {
if (!llmGlobalConfigs) return [];
@ -520,7 +544,7 @@ export function ModelSelector({
</div>
</div>
</div>
{!isAutoMode && (
{!isAutoMode && onEditLLM && (
<Button
variant="ghost"
size="icon"
@ -585,14 +609,16 @@ export function ModelSelector({
</div>
</div>
</div>
<Button
variant="ghost"
size="icon"
className="size-7 shrink-0 rounded-md hover:bg-muted opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => handleEditLLMConfig(e, config, false)}
>
<Edit3 className="size-3.5 text-muted-foreground" />
</Button>
{onEditLLM && (
<Button
variant="ghost"
size="icon"
className="size-7 shrink-0 rounded-md hover:bg-muted opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => handleEditLLMConfig(e, config, false)}
>
<Edit3 className="size-3.5 text-muted-foreground" />
</Button>
)}
</div>
</CommandItem>
);
@ -600,21 +626,23 @@ export function ModelSelector({
</CommandGroup>
)}
{/* Add New LLM Config */}
<div className="p-2 bg-muted/20 dark:bg-neutral-900">
<Button
variant="ghost"
size="sm"
className="w-full justify-start gap-2 h-9 rounded-lg hover:bg-accent/50 dark:hover:bg-white/[0.06]"
onClick={() => {
setOpen(false);
onAddNewLLM();
}}
>
<Plus className="size-4 text-primary" />
<span className="text-sm font-medium">Add Model</span>
</Button>
</div>
{/* Add New LLM Config — admin only */}
{onAddNewLLM && (
<div className="p-2 bg-muted/20 dark:bg-neutral-900">
<Button
variant="ghost"
size="sm"
className="w-full justify-start gap-2 h-9 rounded-lg hover:bg-accent/50 dark:hover:bg-white/[0.06]"
onClick={() => {
setOpen(false);
onAddNewLLM();
}}
>
<Plus className="size-4 text-primary" />
<span className="text-sm font-medium">Add Model</span>
</Button>
</div>
)}
</CommandList>
</Command>
</TabsContent>