chore(repo): initialize Tradarr repository

Add the existing application baseline and repository documentation/ignore rules.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 18:38:53 +01:00
commit 1b0625f91c
115 changed files with 18728 additions and 0 deletions

24
frontend/Dockerfile Normal file
View File

@ -0,0 +1,24 @@
FROM node:22 AS builder
RUN apt-get update && apt-get install -y --no-install-recommends librsvg2-bin && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
COPY . .
# Generate PNG icons from SVG source
RUN mkdir -p public/icons && \
rsvg-convert -w 192 -h 192 public/icon-source.svg -o public/icons/icon-192.png && \
rsvg-convert -w 512 -h 512 public/icon-source.svg -o public/icons/icon-512.png
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

18
frontend/index.html Normal file
View File

@ -0,0 +1,18 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f7f4ef" />
<meta name="description" content="Votre journal financier augmenté par l'IA" />
<title>FinancIAl</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

43
frontend/nginx.conf Normal file
View File

@ -0,0 +1,43 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# Gzip
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
# Résolveur DNS Docker — résolution à la requête, pas au démarrage
resolver 127.0.0.11 valid=10s ipv6=off;
# Proxy API vers backend
location /api/ {
set $backend http://backend:8080;
proxy_pass $backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 3600s;
proxy_connect_timeout 10s;
proxy_send_timeout 3600s;
}
# Service Worker — ne pas mettre en cache
location = /sw.js {
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
expires 0;
}
# Assets statiques avec cache long
location /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
# SPA — renvoyer index.html pour toutes les routes React
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache";
}
}

9997
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

44
frontend/package.json Normal file
View File

@ -0,0 +1,44 @@
{
"name": "tradarr",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint ."
},
"dependencies": {
"@radix-ui/react-avatar": "^1.1.3",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-dropdown-menu": "^2.1.6",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-select": "^2.1.6",
"@radix-ui/react-separator": "^1.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-switch": "^1.1.3",
"@radix-ui/react-tabs": "^1.1.3",
"@radix-ui/react-toast": "^1.2.6",
"@radix-ui/react-tooltip": "^1.1.8",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.475.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.5",
"tailwind-merge": "^2.6.0"
},
"devDependencies": {
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"eslint": "^9.19.0",
"postcss": "^8.5.2",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.3",
"vite": "^6.1.0",
"vite-plugin-pwa": "^0.21.1"
}
}

View File

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#C47038" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/>
<polyline points="16 7 22 7 22 13"/>
</svg>

After

Width:  |  Height:  |  Size: 252 B

View File

@ -0,0 +1,13 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Background -->
<rect width="512" height="512" rx="96" fill="#1C1209"/>
<!-- Chart line scaled to center safe zone (~360px) -->
<g transform="translate(76, 76) scale(15)">
<polyline points="22 7 13.5 15.5 8.5 10.5 2 17"
fill="none" stroke="#C47038" stroke-width="2.2"
stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="16 7 22 7 22 13"
fill="none" stroke="#C47038" stroke-width="2.2"
stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 570 B

74
frontend/src/api/admin.ts Normal file
View File

@ -0,0 +1,74 @@
import { api } from './client'
export interface AIProvider {
id: string; name: string; model: string; endpoint: string
is_active: boolean; has_key: boolean
}
export interface AIRoleConfig { provider_id: string; model: string }
export interface AIRoles { summary: AIRoleConfig; report: AIRoleConfig; filter: AIRoleConfig }
export interface OllamaModelInfo {
name: string; size: number; modified_at: string
details: { parameter_size: string; quantization_level: string; family: string }
}
export interface Source { id: string; name: string; type: string; enabled: boolean }
export interface ScrapeJob {
id: string; source_id: string; source_name: string; status: string
started_at: { Time: string; Valid: boolean } | null
finished_at: { Time: string; Valid: boolean } | null
articles_found: number; error_msg: string; created_at: string
}
export interface Setting { key: string; value: string }
export interface ScheduleSlot { id?: string; day_of_week: number; hour: number; minute: number }
export interface AdminUser { id: string; email: string; role: string; created_at: string }
export interface Credential { source_id: string; source_name: string; username: string; has_password: boolean }
export const adminApi = {
// Credentials
getCredentials: () => api.get<Credential[]>('/admin/credentials'),
updateCredentials: (data: { source_id: string; username: string; password?: string }) =>
api.put<void>('/admin/credentials', data),
// AI Providers
listProviders: () => api.get<AIProvider[]>('/admin/ai-providers'),
createProvider: (data: { name: string; api_key?: string; model?: string; endpoint?: string }) =>
api.post<AIProvider>('/admin/ai-providers', data),
updateProvider: (id: string, data: { name: string; api_key?: string; model?: string; endpoint?: string }) =>
api.put<void>(`/admin/ai-providers/${id}`, data),
activateProvider: (id: string) => api.post<void>(`/admin/ai-providers/${id}/activate`),
deleteProvider: (id: string) => api.delete<void>(`/admin/ai-providers/${id}`),
listModels: (id: string) => api.get<string[]>(`/admin/ai-providers/${id}/models`),
probeModels: (data: { name: string; api_key?: string; endpoint?: string }) =>
api.post<string[]>('/admin/ai-providers/probe-models', data),
// AI Roles
getRoles: () => api.get<AIRoles>('/admin/ai-roles'),
updateRole: (role: string, data: AIRoleConfig) => api.put<void>(`/admin/ai-roles/${role}`, data),
// Ollama model management
listOllamaModels: () => api.get<OllamaModelInfo[]>('/admin/ollama/models'),
pullOllamaModel: (name: string) => api.post<void>('/admin/ollama/pull', { name }),
deleteOllamaModel: (name: string) => api.delete<void>(`/admin/ollama/models/${encodeURIComponent(name)}`),
// Sources
listSources: () => api.get<Source[]>('/admin/sources'),
updateSource: (id: string, enabled: boolean) => api.put<void>(`/admin/sources/${id}`, { enabled }),
// Jobs
listJobs: () => api.get<ScrapeJob[]>('/admin/scrape-jobs'),
triggerJob: (source_id: string) => api.post<void>('/admin/scrape-jobs/trigger', { source_id }),
// Settings
listSettings: () => api.get<Setting[]>('/admin/settings'),
updateSettings: (settings: Setting[]) => api.put<void>('/admin/settings', { settings }),
getDefaultPrompt: () => api.get<{ prompt: string }>('/admin/settings/default-prompt'),
// Schedule
getSchedule: () => api.get<ScheduleSlot[]>('/admin/schedule'),
updateSchedule: (slots: ScheduleSlot[]) => api.put<void>('/admin/schedule', { slots }),
// Users
listUsers: () => api.get<AdminUser[]>('/admin/users'),
updateUser: (id: string, email: string, role: string) =>
api.put<AdminUser>(`/admin/users/${id}`, { email, role }),
deleteUser: (id: string) => api.delete<void>(`/admin/users/${id}`),
}

View File

@ -0,0 +1,25 @@
import { api } from './client'
export interface Article {
id: string
source_id: string
source_name: string
title: string
content: string
url: string
published_at: { Time: string; Valid: boolean } | null
created_at: string
symbols?: string[]
}
export const articlesApi = {
list: (params?: { symbol?: string; limit?: number; offset?: number }) => {
const q = new URLSearchParams()
if (params?.symbol) q.set('symbol', params.symbol)
if (params?.limit) q.set('limit', String(params.limit))
if (params?.offset) q.set('offset', String(params.offset))
const qs = q.toString()
return api.get<Article[]>(`/articles${qs ? `?${qs}` : ''}`)
},
get: (id: string) => api.get<Article>(`/articles/${id}`),
}

View File

@ -0,0 +1,9 @@
import { api } from './client'
export interface Asset { id: string; user_id: string; symbol: string; name: string; created_at: string }
export const assetsApi = {
list: () => api.get<Asset[]>('/me/assets'),
add: (symbol: string, name: string) => api.post<Asset>('/me/assets', { symbol, name }),
remove: (symbol: string) => api.delete<void>(`/me/assets/${symbol}`),
}

12
frontend/src/api/auth.ts Normal file
View File

@ -0,0 +1,12 @@
import { api } from './client'
export interface User { id: string; email: string; role: 'admin' | 'user' }
interface AuthResponse { token: string; user: User }
export const authApi = {
login: (email: string, password: string) =>
api.post<AuthResponse>('/auth/login', { email, password }),
register: (email: string, password: string) =>
api.post<AuthResponse>('/auth/register', { email, password }),
me: () => api.get<User>('/me'),
}

View File

@ -0,0 +1,39 @@
const BASE = '/api'
function getToken() {
return localStorage.getItem('token')
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = getToken()
const res = await fetch(`${BASE}${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options.headers,
},
})
if (res.status === 401) {
localStorage.removeItem('token')
localStorage.removeItem('user')
window.location.href = '/login'
throw new Error('Session expirée')
}
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || res.statusText)
}
if (res.status === 204) return undefined as T
const json = await res.json()
return json.data !== undefined ? json.data : json
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) =>
request<T>(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined }),
put: <T>(path: string, body?: unknown) =>
request<T>(path, { method: 'PUT', body: body ? JSON.stringify(body) : undefined }),
delete: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
}

View File

@ -0,0 +1,32 @@
import { api } from './client'
export interface Report {
id: string
user_id: string
summary_id: string | null
context_excerpt: string
question: string
answer: string
status: 'generating' | 'done' | 'error'
error_msg: string
created_at: string
}
export interface ReportMessage {
id: string
report_id: string
role: 'user' | 'assistant'
content: string
status: 'done' | 'generating' | 'error'
created_at: string
}
export const reportsApi = {
list: () => api.get<Report[]>('/reports'),
create: (data: { summary_id?: string; excerpts: string[]; question: string }) =>
api.post<Report>('/reports', data),
delete: (id: string) => api.delete<void>(`/reports/${id}`),
listMessages: (reportId: string) => api.get<ReportMessage[]>(`/reports/${reportId}/messages`),
createMessage: (reportId: string, content: string) =>
api.post<ReportMessage>(`/reports/${reportId}/messages`, { content }),
}

View File

@ -0,0 +1,15 @@
import { api } from './client'
export interface Summary {
id: string
user_id: string
content: string
ai_provider_id: string | null
generated_at: string
}
export const summariesApi = {
list: (limit = 10) => api.get<Summary[]>(`/summaries?limit=${limit}`),
generate: () => api.post<Summary>('/summaries/generate'),
status: () => api.get<{ generating: boolean }>('/summaries/status'),
}

View File

@ -0,0 +1,26 @@
import { Outlet, Navigate } from 'react-router-dom'
import { useAuth } from '@/lib/auth'
import { Sidebar } from './Sidebar'
import { MobileNav } from './MobileNav'
export function AppLayout() {
const { token } = useAuth()
if (!token) return <Navigate to="/login" replace />
return (
<div className="flex h-screen overflow-hidden">
{/* Sidebar desktop */}
<div className="hidden md:flex">
<Sidebar />
</div>
{/* Main content */}
<main className="flex-1 overflow-y-auto pb-16 md:pb-0">
<Outlet />
</main>
{/* Bottom nav mobile */}
<MobileNav />
</div>
)
}

View File

@ -0,0 +1,34 @@
import { NavLink } from 'react-router-dom'
import { LayoutDashboard, Newspaper, Star, Settings, FileText } from 'lucide-react'
import { cn } from '@/lib/cn'
const items = [
{ to: '/', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/feed', icon: Newspaper, label: 'Actus' },
{ to: '/watchlist', icon: Star, label: 'Watchlist' },
{ to: '/reports', icon: FileText, label: 'Rapports' },
{ to: '/admin', icon: Settings, label: 'Admin' },
]
export function MobileNav() {
return (
<nav className="fixed bottom-0 left-0 right-0 z-50 flex border-t bg-card md:hidden shadow-sm">
{items.map(({ to, icon: Icon, label }) => (
<NavLink
key={to}
to={to}
end={to === '/'}
className={({ isActive }) =>
cn(
'flex flex-1 flex-col items-center gap-1 py-3 text-xs transition-colors',
isActive ? 'text-primary font-medium' : 'text-muted-foreground'
)
}
>
<Icon className="h-5 w-5" />
{label}
</NavLink>
))}
</nav>
)
}

View File

@ -0,0 +1,94 @@
import { NavLink } from 'react-router-dom'
import { LayoutDashboard, Newspaper, Star, Settings, Key, Cpu, Database, ClipboardList, Users, LogOut, CalendarDays, FileText } from 'lucide-react'
import { useAuth } from '@/lib/auth'
import { cn } from '@/lib/cn'
const navItems = [
{ to: '/', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/feed', icon: Newspaper, label: 'Actualités' },
{ to: '/watchlist', icon: Star, label: 'Watchlist' },
{ to: '/reports', icon: FileText, label: 'Rapports' },
]
const adminItems = [
{ to: '/admin/ai', icon: Cpu, label: 'Fournisseurs IA' },
{ to: '/admin/credentials', icon: Key, label: 'Identifiants' },
{ to: '/admin/sources', icon: Database, label: 'Sources' },
{ to: '/admin/jobs', icon: ClipboardList, label: 'Jobs' },
{ to: '/admin/users', icon: Users, label: 'Utilisateurs' },
{ to: '/admin/schedule', icon: CalendarDays, label: 'Planning' },
{ to: '/admin/settings', icon: Settings, label: 'Paramètres' },
]
function NavItem({ to, icon: Icon, label }: { to: string; icon: React.ElementType; label: string }) {
return (
<NavLink
to={to}
end={to === '/'}
className={({ isActive }) =>
cn(
'flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors',
isActive
? 'bg-primary/8 text-primary font-medium border-l-2 border-primary pl-[10px]'
: 'text-muted-foreground hover:bg-accent hover:text-foreground font-normal'
)
}
>
<Icon className="h-4 w-4 shrink-0" />
{label}
</NavLink>
)
}
export function Sidebar() {
const { user, logout, isAdmin } = useAuth()
return (
<aside className="flex h-screen w-60 flex-col border-r bg-card px-3 py-5">
{/* Logo */}
<div className="mb-7 px-3">
<span className="font-serif text-xl font-bold tracking-tight text-foreground">
Financ<span className="text-primary">IA</span>l
</span>
<p className="text-[10px] text-muted-foreground mt-0.5 tracking-wide uppercase">Journal financier IA</p>
</div>
{/* Séparateur */}
<div className="border-t mb-4" />
{/* Navigation principale */}
<nav className="flex flex-col gap-0.5">
{navItems.map(item => <NavItem key={item.to} {...item} />)}
</nav>
{/* Section admin */}
{isAdmin && (
<>
<div className="mt-5 mb-2 px-3 flex items-center gap-2">
<div className="flex-1 border-t" />
<p className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">Admin</p>
<div className="flex-1 border-t" />
</div>
<nav className="flex flex-col gap-0.5">
{adminItems.map(item => <NavItem key={item.to} {...item} />)}
</nav>
</>
)}
{/* User + logout */}
<div className="mt-auto border-t pt-4">
<div className="px-3 mb-2">
<p className="text-sm font-medium truncate text-foreground">{user?.email}</p>
<p className="text-xs text-muted-foreground capitalize">{user?.role}</p>
</div>
<button
onClick={logout}
className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
>
<LogOut className="h-4 w-4" />
Déconnexion
</button>
</div>
</aside>
)
}

View File

@ -0,0 +1,26 @@
import { type HTMLAttributes } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/cn'
const badgeVariants = cva(
'inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium transition-colors',
{
variants: {
variant: {
default: 'border-transparent bg-primary text-primary-foreground',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
destructive: 'border-transparent bg-destructive/10 text-destructive border-destructive/20',
outline: 'text-foreground border-border',
bullish: 'border-transparent bg-bullish/10 text-bullish',
bearish: 'border-transparent bg-bearish/10 text-bearish',
},
},
defaultVariants: { variant: 'default' },
}
)
export interface BadgeProps extends HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
export function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
}

View File

@ -0,0 +1,35 @@
import { forwardRef, type ButtonHTMLAttributes } from 'react'
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/cn'
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline: 'border border-input bg-transparent hover:bg-accent hover:text-accent-foreground',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-7 rounded px-2.5 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-8 w-8',
},
},
defaultVariants: { variant: 'default', size: 'default' },
}
)
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {}
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, ...props }, ref) => (
<button className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
)
)
Button.displayName = 'Button'

View File

@ -0,0 +1,37 @@
import { forwardRef, type HTMLAttributes } from 'react'
import { cn } from '@/lib/cn'
export const Card = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('rounded-md border bg-card text-card-foreground shadow-sm', className)} {...props} />
)
)
Card.displayName = 'Card'
export const CardHeader = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-5', className)} {...props} />
)
)
CardHeader.displayName = 'CardHeader'
export const CardTitle = forwardRef<HTMLParagraphElement, HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn('font-semibold leading-none tracking-tight', className)} {...props} />
)
)
CardTitle.displayName = 'CardTitle'
export const CardContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-5 pt-0', className)} {...props} />
)
)
CardContent.displayName = 'CardContent'
export const CardFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex items-center p-5 pt-0', className)} {...props} />
)
)
CardFooter.displayName = 'CardFooter'

View File

@ -0,0 +1,17 @@
import { forwardRef, type InputHTMLAttributes } from 'react'
import { cn } from '@/lib/cn'
export interface InputProps extends InputHTMLAttributes<HTMLInputElement> {}
export const Input = forwardRef<HTMLInputElement, InputProps>(({ className, type, ...props }, ref) => (
<input
type={type}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
className
)}
ref={ref}
{...props}
/>
))
Input.displayName = 'Input'

View File

@ -0,0 +1,13 @@
import { forwardRef, type LabelHTMLAttributes } from 'react'
import { cn } from '@/lib/cn'
export const Label = forwardRef<HTMLLabelElement, LabelHTMLAttributes<HTMLLabelElement>>(
({ className, ...props }, ref) => (
<label
ref={ref}
className={cn('text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70', className)}
{...props}
/>
)
)
Label.displayName = 'Label'

View File

@ -0,0 +1,28 @@
import React from 'react'
function renderInline(text: string): React.ReactNode {
const parts = text.split(/(\*\*[^*]+\*\*)/g)
return parts.map((part, i) =>
part.startsWith('**') && part.endsWith('**')
? <strong key={i}>{part.slice(2, -2)}</strong>
: part
)
}
export function Markdown({ content, className }: { content: string; className?: string }) {
const lines = content.split('\n')
return (
<div className={`space-y-1 text-sm leading-relaxed select-text ${className ?? ''}`}>
{lines.map((line, i) => {
if (line.startsWith('##### ')) return <h5 key={i} className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mt-3">{renderInline(line.slice(6))}</h5>
if (line.startsWith('#### ')) return <h4 key={i} className="text-sm font-semibold mt-3">{renderInline(line.slice(5))}</h4>
if (line.startsWith('### ')) return <h3 key={i} className="text-sm font-semibold text-primary mt-4">{renderInline(line.slice(4))}</h3>
if (line.startsWith('## ')) return <h2 key={i} className="text-base font-bold mt-5 first:mt-0 border-b pb-1">{renderInline(line.slice(3))}</h2>
if (line.startsWith('# ')) return <h1 key={i} className="text-lg font-bold mt-5 first:mt-0">{renderInline(line.slice(2))}</h1>
if (line.startsWith('- ') || line.startsWith('* ')) return <li key={i} className="ml-4 text-muted-foreground list-disc">{renderInline(line.slice(2))}</li>
if (line.trim() === '') return <div key={i} className="h-2" />
return <p key={i} className="text-muted-foreground">{renderInline(line)}</p>
})}
</div>
)
}

View File

@ -0,0 +1,22 @@
import { forwardRef, type SelectHTMLAttributes } from 'react'
import { cn } from '@/lib/cn'
import { ChevronDown } from 'lucide-react'
export interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {}
export const Select = forwardRef<HTMLSelectElement, SelectProps>(({ className, children, ...props }, ref) => (
<div className="relative">
<select
ref={ref}
className={cn(
'flex h-9 w-full appearance-none rounded-md border border-input bg-transparent px-3 py-1 pr-8 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
>
{children}
</select>
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
</div>
))
Select.displayName = 'Select'

View File

@ -0,0 +1,7 @@
import { cn } from '@/lib/cn'
export function Spinner({ className }: { className?: string }) {
return (
<div className={cn('h-5 w-5 animate-spin rounded-full border-2 border-current border-t-transparent', className)} />
)
}

95
frontend/src/index.css Normal file
View File

@ -0,0 +1,95 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
/* ── Fond & texte ── */
--background: 36 28% 97%;
--foreground: 20 15% 9%;
/* ── Cartes ── */
--card: 0 0% 100%;
--card-foreground: 20 15% 9%;
/* ── Bordures & inputs ── */
--border: 30 18% 87%;
--input: 30 18% 87%;
--ring: 22 62% 28%;
/* ── Primaire : brun cognac ── */
--primary: 22 62% 28%;
--primary-foreground: 36 30% 96%;
/* ── Secondaire & muted ── */
--secondary: 36 20% 93%;
--secondary-foreground: 20 12% 25%;
--muted: 35 18% 92%;
--muted-foreground: 25 10% 34%;
/* ── Accent (hover) ── */
--accent: 35 18% 90%;
--accent-foreground: 20 15% 9%;
/* ── Destructif ── */
--destructive: 0 78% 52%;
--destructive-foreground: 0 0% 98%;
--radius: 0.375rem;
}
.dark {
/* ── Fond & texte ── */
--background: 22 18% 7%;
--foreground: 36 22% 91%;
/* ── Cartes ── */
--card: 22 15% 10%;
--card-foreground: 36 22% 91%;
/* ── Bordures & inputs ── */
--border: 25 14% 18%;
--input: 25 14% 18%;
--ring: 22 55% 48%;
/* ── Primaire : cognac clair (lisible sur fond sombre) ── */
--primary: 22 55% 50%;
--primary-foreground: 36 30% 96%;
/* ── Secondaire & muted ── */
--secondary: 22 13% 14%;
--secondary-foreground: 36 18% 78%;
--muted: 22 12% 13%;
--muted-foreground: 30 10% 66%;
/* ── Accent (hover) ── */
--accent: 22 13% 15%;
--accent-foreground: 36 22% 91%;
/* ── Destructif ── */
--destructive: 0 72% 55%;
--destructive-foreground: 0 0% 98%;
}
}
@layer base {
* { @apply border-border; }
body {
@apply bg-background text-foreground;
font-feature-settings: "rlig" 1, "calt" 1;
}
}
.font-serif {
font-family: 'Playfair Display', Georgia, serif;
}
/* Scrollbar */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: hsl(var(--muted)); }
::-webkit-scrollbar-thumb { background: hsl(var(--border)); border-radius: 9999px; }
@layer utilities {
.scrollbar-none { scrollbar-width: none; }
.scrollbar-none::-webkit-scrollbar { display: none; }
}

51
frontend/src/lib/auth.tsx Normal file
View File

@ -0,0 +1,51 @@
import { createContext, useContext, useState, type ReactNode } from 'react'
interface User {
id: string
email: string
role: 'admin' | 'user'
}
interface AuthCtx {
user: User | null
token: string | null
login: (token: string, user: User) => void
logout: () => void
isAdmin: boolean
}
const AuthContext = createContext<AuthCtx | null>(null)
export function AuthProvider({ children }: { children: ReactNode }) {
const [token, setToken] = useState<string | null>(() => localStorage.getItem('token'))
const [user, setUser] = useState<User | null>(() => {
const u = localStorage.getItem('user')
return u ? JSON.parse(u) : null
})
function login(t: string, u: User) {
localStorage.setItem('token', t)
localStorage.setItem('user', JSON.stringify(u))
setToken(t)
setUser(u)
}
function logout() {
localStorage.removeItem('token')
localStorage.removeItem('user')
setToken(null)
setUser(null)
}
return (
<AuthContext.Provider value={{ user, token, login, logout, isAdmin: user?.role === 'admin' }}>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
return ctx
}

6
frontend/src/lib/cn.ts Normal file
View File

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@ -0,0 +1,42 @@
import { createBrowserRouter } from 'react-router-dom'
import { AppLayout } from '@/components/layout/AppLayout'
import { Login } from '@/pages/Login'
import { Dashboard } from '@/pages/Dashboard'
import { Feed } from '@/pages/Feed'
import { Watchlist } from '@/pages/Watchlist'
import { AdminLayout } from '@/pages/admin/AdminLayout'
import { AIProviders } from '@/pages/admin/AIProviders'
import { Credentials } from '@/pages/admin/Credentials'
import { Sources } from '@/pages/admin/Sources'
import { Jobs } from '@/pages/admin/Jobs'
import { AdminUsers } from '@/pages/admin/AdminUsers'
import { AdminSettings } from '@/pages/admin/AdminSettings'
import { Schedule } from '@/pages/admin/Schedule'
import { Reports } from '@/pages/Reports'
export const router = createBrowserRouter([
{ path: '/login', element: <Login /> },
{
element: <AppLayout />,
children: [
{ path: '/', element: <Dashboard /> },
{ path: '/feed', element: <Feed /> },
{ path: '/watchlist', element: <Watchlist /> },
{ path: '/reports', element: <Reports /> },
{
path: '/admin',
element: <AdminLayout />,
children: [
{ index: true, element: <AIProviders /> },
{ path: 'ai', element: <AIProviders /> },
{ path: 'credentials', element: <Credentials /> },
{ path: 'sources', element: <Sources /> },
{ path: 'jobs', element: <Jobs /> },
{ path: 'users', element: <AdminUsers /> },
{ path: 'settings', element: <AdminSettings /> },
{ path: 'schedule', element: <Schedule /> },
],
},
],
},
])

View File

@ -0,0 +1,40 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
type Theme = 'light' | 'dark'
interface ThemeCtx {
theme: Theme
setTheme: (t: Theme) => void
}
const ThemeContext = createContext<ThemeCtx | null>(null)
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(() => {
const saved = localStorage.getItem('theme') as Theme | null
if (saved === 'light' || saved === 'dark') return saved
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
})
useEffect(() => {
const root = document.documentElement
root.classList.toggle('dark', theme === 'dark')
localStorage.setItem('theme', theme)
}, [theme])
function setTheme(t: Theme) {
setThemeState(t)
}
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
)
}
export function useTheme() {
const ctx = useContext(ThemeContext)
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
return ctx
}

17
frontend/src/main.tsx Normal file
View File

@ -0,0 +1,17 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { RouterProvider } from 'react-router-dom'
import { AuthProvider } from '@/lib/auth'
import { ThemeProvider } from '@/lib/theme'
import { router } from '@/lib/router'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<ThemeProvider>
<AuthProvider>
<RouterProvider router={router} />
</AuthProvider>
</ThemeProvider>
</StrictMode>
)

View File

@ -0,0 +1,349 @@
import { useState, useEffect, useRef, useCallback } from 'react'
import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send, ChevronDown, ChevronUp } from 'lucide-react'
import { summariesApi, type Summary } from '@/api/summaries'
import { reportsApi } from '@/api/reports'
import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Markdown } from '@/components/ui/markdown'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth'
// ── Text-selection floating button ─────────────────────────────────────────
function useTextSelection(containerRef: React.RefObject<HTMLElement>) {
const [selection, setSelection] = useState<{ text: string; x: number; y: number } | null>(null)
useEffect(() => {
function readSelection() {
const sel = window.getSelection()
const text = sel?.toString().trim()
if (!text || !containerRef.current) { setSelection(null); return }
const range = sel!.getRangeAt(0)
const rect = range.getBoundingClientRect()
const containerRect = containerRef.current.getBoundingClientRect()
setSelection({
text,
x: rect.left - containerRect.left + rect.width / 2,
y: rect.top - containerRect.top - 8,
})
}
function onMouseUp() { readSelection() }
// On mobile, selectionchange fires after the user lifts their finger
function onSelectionChange() {
const sel = window.getSelection()
if (!sel?.toString().trim()) setSelection(null)
else readSelection()
}
function onPointerDown(e: PointerEvent) {
if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
}
document.addEventListener('mouseup', onMouseUp)
document.addEventListener('selectionchange', onSelectionChange)
document.addEventListener('pointerdown', onPointerDown)
return () => {
document.removeEventListener('mouseup', onMouseUp)
document.removeEventListener('selectionchange', onSelectionChange)
document.removeEventListener('pointerdown', onPointerDown)
}
}, [containerRef])
return selection
}
// ── Context panel (extraits + question) ────────────────────────────────────
function ContextPanel({
excerpts,
onRemove,
onClear,
onSubmit,
}: {
excerpts: string[]
onRemove: (i: number) => void
onClear: () => void
onSubmit: (question: string) => Promise<void>
}) {
const [question, setQuestion] = useState('')
const [submitting, setSubmitting] = useState(false)
const [submitted, setSubmitted] = useState(false)
const [showExcerpts, setShowExcerpts] = useState(false)
async function submit() {
if (!question.trim() || submitting) return
setSubmitting(true)
try {
await onSubmit(question)
setSubmitted(true)
setQuestion('')
setTimeout(() => setSubmitted(false), 2000)
} finally {
setSubmitting(false)
}
}
return (
<div className="fixed bottom-16 left-0 right-0 z-40 flex flex-col bg-card border-t shadow-2xl overflow-hidden md:bottom-4 md:left-auto md:right-4 md:w-96 md:rounded-xl md:border">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
<button
className="text-sm font-semibold flex items-center gap-2 hover:text-primary transition-colors"
onClick={() => setShowExcerpts(v => !v)}
>
<MessageSquarePlus className="h-4 w-4 text-primary" />
Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
<span className="md:hidden">{showExcerpts ? <ChevronDown className="h-3 w-3" /> : <ChevronUp className="h-3 w-3" />}</span>
</button>
<button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
Tout effacer
</button>
</div>
{/* Extraits — toujours visible sur desktop, togglable sur mobile */}
<div className={`flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0 max-h-[25vh] ${showExcerpts ? 'block' : 'hidden'} md:block`}>
{excerpts.map((e, i) => (
<div key={i} className="flex items-start gap-2 group">
<div className="flex-1 rounded bg-muted/60 px-2 py-1.5 text-xs text-muted-foreground italic line-clamp-3">
«&nbsp;{e}&nbsp;»
</div>
<button
onClick={() => onRemove(i)}
className="mt-1 shrink-0 text-muted-foreground hover:text-destructive md:opacity-0 md:group-hover:opacity-100 transition-opacity"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
{/* Question */}
<div className="border-t px-4 py-3 space-y-2">
<textarea
className="w-full rounded border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"
rows={2}
placeholder="Votre question…"
value={question}
onChange={e => setQuestion(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }}
/>
<Button size="sm" className="w-full" onClick={submit} disabled={!question.trim() || submitting || submitted}>
{submitting
? <><Loader2 className="h-3 w-3 animate-spin" /> Envoi…</>
: submitted
? 'Envoyé !'
: <><Send className="h-3 w-3" /> Envoyer (Ctrl+Entrée)</>}
</Button>
</div>
</div>
)
}
// ── Summary content renderer ────────────────────────────────────────────────
function SummaryContent({ content }: { content: string }) {
return <Markdown content={content} />
}
// ── Dashboard ───────────────────────────────────────────────────────────────
export function Dashboard() {
const { user } = useAuth()
const [summaries, setSummaries] = useState<Summary[]>([])
const [assets, setAssets] = useState<Asset[]>([])
const [loading, setLoading] = useState(true)
const [generating, setGenerating] = useState(false)
const [current, setCurrent] = useState<Summary | null>(null)
const [excerpts, setExcerpts] = useState<string[]>([])
const summaryRef = useRef<HTMLDivElement>(null)
const textSel = useTextSelection(summaryRef as React.RefObject<HTMLElement>)
useEffect(() => { load() }, [])
// Poll generating status every 5s
useEffect(() => {
const interval = setInterval(async () => {
try {
const status = await summariesApi.status()
const wasGenerating = generating
setGenerating(status.generating)
if (wasGenerating && !status.generating) load()
} catch { /* ignore */ }
}, 5000)
return () => clearInterval(interval)
}, [generating])
async function load() {
setLoading(true)
try {
const [s, a] = await Promise.all([summariesApi.list(5), assetsApi.list()])
setSummaries(s ?? [])
setAssets(a ?? [])
setCurrent(s?.[0] ?? null)
} finally { setLoading(false) }
}
async function generate() {
setGenerating(true)
try {
const s = await summariesApi.generate()
setSummaries(prev => [s, ...prev])
setCurrent(s)
} catch (e) {
alert(e instanceof Error ? e.message : 'Erreur lors de la génération')
} finally { setGenerating(false) }
}
const addExcerpt = useCallback(() => {
if (!textSel) return
setExcerpts(prev => [...prev, textSel.text])
window.getSelection()?.removeAllRanges()
}, [textSel])
async function submitQuestion(question: string) {
await reportsApi.create({
summary_id: current?.id,
excerpts,
question,
})
setExcerpts([])
}
return (
<div className="p-4 md:p-6 space-y-6">
{/* Generating banner */}
{generating && (
<div className="flex items-center gap-3 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
<Loader2 className="h-4 w-4 animate-spin shrink-0" />
Génération d'un résumé IA en cours — cela peut prendre plusieurs minutes…
</div>
)}
{/* Header */}
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h1 className="text-2xl font-bold">Bonjour 👋</h1>
<p className="text-muted-foreground text-sm">{user?.email}</p>
</div>
<Button onClick={generate} disabled={generating || assets.length === 0}>
{generating ? <><Spinner className="h-4 w-4" /> Génération…</> : <><Sparkles className="h-4 w-4" /> Générer un résumé</>}
</Button>
</div>
{assets.length === 0 && !loading && (
<Card className="border-dashed">
<CardContent className="py-8 text-center">
<TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3" />
<p className="font-medium">Votre watchlist est vide</p>
<p className="text-sm text-muted-foreground mt-1">Ajoutez des symboles dans la section Watchlist pour obtenir des résumés personnalisés</p>
</CardContent>
</Card>
)}
{assets.length > 0 && (
<div className="flex flex-wrap gap-2">
{assets.map(a => (
<Badge key={a.id} variant="secondary" className="font-mono">{a.symbol}</Badge>
))}
</div>
)}
{/* Résumé actuel */}
<div className="grid gap-6 lg:grid-cols-3">
<div className="lg:col-span-2 space-y-4">
{loading ? (
<div className="flex justify-center py-20"><Spinner /></div>
) : current ? (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2">
<Sparkles className="h-5 w-5 text-primary" /> Résumé IA
</CardTitle>
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Clock className="h-3 w-3" />
{new Date(current.generated_at).toLocaleString('fr-FR')}
</div>
</div>
</CardHeader>
<CardContent>
<div ref={summaryRef} className="relative">
<SummaryContent content={current.content} />
{/* Desktop: floating button above selection */}
{textSel && (
<button
data-context-action
onClick={addExcerpt}
className="absolute z-10 hidden md:flex items-center gap-1 rounded-full bg-primary text-primary-foreground text-xs px-2 py-1 shadow-lg hover:bg-primary/90 transition-colors"
style={{ left: textSel.x, top: textSel.y, transform: 'translate(-50%, -100%)' }}
>
<Plus className="h-3 w-3" />
Ajouter au contexte
</button>
)}
</div>
{/* Mobile: fixed bottom bar — avoids conflict with native selection menu */}
{textSel && (
<div className="md:hidden fixed bottom-16 left-0 right-0 z-50 flex justify-center px-4 pointer-events-none">
<button
data-context-action
onClick={addExcerpt}
className="pointer-events-auto flex items-center gap-2 rounded-full bg-primary text-primary-foreground text-sm px-4 py-2.5 shadow-xl"
>
<Plus className="h-4 w-4" />
Ajouter au contexte
</button>
</div>
)}
<p className="text-xs text-muted-foreground mt-4 italic">
Sélectionnez du texte pour l'ajouter au contexte, puis posez une question dans le panneau qui apparaît.
</p>
</CardContent>
</Card>
) : (
<Card className="border-dashed">
<CardContent className="py-12 text-center text-muted-foreground">
<Sparkles className="h-8 w-8 mx-auto mb-3 opacity-50" />
<p>Aucun résumé disponible</p>
<p className="text-xs mt-1">Cliquez sur "Générer un résumé" pour commencer</p>
</CardContent>
</Card>
)}
</div>
{/* Historique résumés */}
{summaries.length > 1 && (
<div className="space-y-3">
<h2 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">Historique</h2>
{summaries.slice(1).map(s => (
<Card
key={s.id}
className={`cursor-pointer transition-colors hover:border-primary/50 ${current?.id === s.id ? 'border-primary/50' : ''}`}
onClick={() => setCurrent(s)}
>
<CardContent className="py-3">
<div className="flex items-center gap-1 text-xs text-muted-foreground mb-1">
<Clock className="h-3 w-3" />
{new Date(s.generated_at).toLocaleString('fr-FR')}
</div>
<p className="text-sm line-clamp-3">{s.content.slice(0, 120)}…</p>
</CardContent>
</Card>
))}
</div>
)}
</div>
{/* Panneau contexte flottant */}
{excerpts.length > 0 && (
<ContextPanel
excerpts={excerpts}
onRemove={i => setExcerpts(prev => prev.filter((_, idx) => idx !== i))}
onClear={() => setExcerpts([])}
onSubmit={submitQuestion}
/>
)}
</div>
)
}

116
frontend/src/pages/Feed.tsx Normal file
View File

@ -0,0 +1,116 @@
import { useState, useEffect } from 'react'
import { ExternalLink, RefreshCw, Search } from 'lucide-react'
import { articlesApi, type Article } from '@/api/articles'
import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
function fmtDate(a: Article) {
const d = a.published_at?.Valid ? new Date(a.published_at.Time) : new Date(a.created_at)
const now = Date.now()
const diff = now - d.getTime()
if (diff < 3600000) return `Il y a ${Math.floor(diff / 60000)} min`
if (diff < 86400000) return `Il y a ${Math.floor(diff / 3600000)} h`
return d.toLocaleDateString('fr-FR')
}
export function Feed() {
const [articles, setArticles] = useState<Article[]>([])
const [assets, setAssets] = useState<Asset[]>([])
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState('')
const [filterSymbol, setFilterSymbol] = useState('')
const [offset, setOffset] = useState(0)
const limit = 30
useEffect(() => {
assetsApi.list().then(a => setAssets(a ?? []))
}, [])
useEffect(() => { load(0) }, [filterSymbol])
async function load(newOffset = 0) {
setLoading(true)
try {
const data = await articlesApi.list({ symbol: filterSymbol || undefined, limit, offset: newOffset })
if (newOffset === 0) setArticles(data ?? [])
else setArticles(prev => [...prev, ...(data ?? [])])
setOffset(newOffset + limit)
} finally { setLoading(false) }
}
const filtered = search
? articles.filter(a => a.title.toLowerCase().includes(search.toLowerCase()) || a.source_name?.toLowerCase().includes(search.toLowerCase()))
: articles
return (
<div className="p-4 md:p-6 space-y-4">
<div className="flex flex-wrap items-center gap-4">
<h1 className="text-2xl font-bold flex-1">Actualités</h1>
<Button variant="outline" size="icon" onClick={() => load(0)}><RefreshCw className="h-4 w-4" /></Button>
</div>
{/* Filtres */}
<div className="flex flex-wrap gap-3">
<div className="relative flex-1 min-w-48">
<Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input className="pl-8" placeholder="Rechercher…" value={search} onChange={e => setSearch(e.target.value)} />
</div>
<Select value={filterSymbol} onChange={e => setFilterSymbol(e.target.value)} className="w-40">
<option value="">Tous les symboles</option>
{assets.map(a => <option key={a.id} value={a.symbol}>{a.symbol}</option>)}
</Select>
</div>
{loading && articles.length === 0 ? (
<div className="flex justify-center py-20"><Spinner /></div>
) : (
<>
<div className="space-y-3">
{filtered.map(a => (
<Card key={a.id} className="hover:border-border/80 transition-colors">
<CardContent className="py-4">
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap mb-1">
<Badge variant="outline" className="text-xs">{a.source_name}</Badge>
<span className="text-xs text-muted-foreground">{fmtDate(a)}</span>
</div>
<h3 className="font-medium leading-snug mb-2">{a.title}</h3>
{a.content && (
<p className="text-sm text-muted-foreground line-clamp-2">{a.content}</p>
)}
</div>
<a
href={a.url}
target="_blank"
rel="noopener noreferrer"
className="shrink-0 text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-4 w-4" />
</a>
</div>
</CardContent>
</Card>
))}
{filtered.length === 0 && (
<Card><CardContent className="py-12 text-center text-muted-foreground">Aucun article</CardContent></Card>
)}
</div>
{filtered.length >= limit && (
<div className="flex justify-center pt-2">
<Button variant="outline" onClick={() => load(offset)} disabled={loading}>
{loading ? <Spinner className="h-4 w-4" /> : 'Charger plus'}
</Button>
</div>
)}
</>
)}
</div>
)
}

View File

@ -0,0 +1,94 @@
import { useState, type FormEvent } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '@/lib/auth'
import { authApi } from '@/api/auth'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
export function Login() {
const { token, login } = useAuth()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
if (token) return <Navigate to="/" replace />
async function handleSubmit(e: FormEvent) {
e.preventDefault()
setError('')
setLoading(true)
try {
const { token: t, user } = await authApi.login(email, password)
login(t, user)
} catch (err) {
setError(err instanceof Error ? err.message : 'Erreur de connexion')
} finally {
setLoading(false)
}
}
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
{/* Motif de fond discret */}
<div className="absolute inset-0 opacity-[0.03] pointer-events-none"
style={{ backgroundImage: 'repeating-linear-gradient(0deg, hsl(20 15% 9%), hsl(20 15% 9%) 1px, transparent 1px, transparent 40px), repeating-linear-gradient(90deg, hsl(20 15% 9%), hsl(20 15% 9%) 1px, transparent 1px, transparent 40px)' }}
/>
<div className="relative w-full max-w-sm">
{/* En-tête */}
<div className="mb-8 text-center">
<h1 className="font-serif text-4xl font-bold text-foreground">
Financ<span className="text-primary">IA</span>l
</h1>
<p className="mt-2 text-sm text-muted-foreground tracking-wide">
Votre journal financier augmenté par l'IA
</p>
</div>
{/* Carte formulaire */}
<div className="rounded-lg border bg-card shadow-sm p-6">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="email">Adresse email</Label>
<Input
id="email"
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
required
autoComplete="email"
placeholder="vous@exemple.com"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="password">Mot de passe</Label>
<Input
id="password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
required
autoComplete="current-password"
placeholder="••••••••"
/>
</div>
{error && (
<p className="text-sm text-destructive border border-destructive/20 bg-destructive/5 rounded px-3 py-2">
{error}
</p>
)}
<Button type="submit" className="w-full mt-2" disabled={loading}>
{loading ? 'Connexion…' : 'Se connecter'}
</Button>
</form>
</div>
<p className="mt-6 text-center text-xs text-muted-foreground">
© {new Date().getFullYear()} FinancIAl — Accès restreint
</p>
</div>
</div>
)
}

View File

@ -0,0 +1,252 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { Trash2, FileText, Clock, Loader2, XCircle, AlertCircle, Send } from 'lucide-react'
import { reportsApi, type Report, type ReportMessage } from '@/api/reports'
import { Card, CardContent } from '@/components/ui/card'
import { Markdown } from '@/components/ui/markdown'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Spinner } from '@/components/ui/spinner'
import { Badge } from '@/components/ui/badge'
function StatusBadge({ status }: { status: Report['status'] }) {
if (status === 'generating') return (
<Badge variant="secondary" className="gap-1 text-xs">
<Loader2 className="h-3 w-3 animate-spin" /> En cours
</Badge>
)
if (status === 'error') return (
<Badge variant="destructive" className="gap-1 text-xs">
<AlertCircle className="h-3 w-3" /> Erreur
</Badge>
)
return null
}
function MessageBubble({ msg }: { msg: ReportMessage }) {
const isUser = msg.role === 'user'
return (
<div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
<div className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${
isUser
? 'bg-primary text-primary-foreground'
: 'bg-muted'
}`}>
{msg.status === 'generating' ? (
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
<span className="text-xs">Génération…</span>
</div>
) : msg.status === 'error' ? (
<span className="text-destructive text-xs">{msg.content || 'Erreur lors de la génération.'}</span>
) : isUser ? (
<p>{msg.content}</p>
) : (
<Markdown content={msg.content} />
)}
</div>
</div>
)
}
function ReportChat({ report }: { report: Report }) {
const [messages, setMessages] = useState<ReportMessage[]>([])
const [input, setInput] = useState('')
const [sending, setSending] = useState(false)
const bottomRef = useRef<HTMLDivElement>(null)
const loadMessages = useCallback(async () => {
const msgs = await reportsApi.listMessages(report.id)
setMessages(msgs ?? [])
}, [report.id])
useEffect(() => { loadMessages() }, [loadMessages])
// Poll tant qu'un message assistant est en cours de génération
useEffect(() => {
const hasGenerating = messages.some(m => m.status === 'generating')
if (!hasGenerating) return
const interval = setInterval(loadMessages, 2000)
return () => clearInterval(interval)
}, [messages, loadMessages])
// Scroll vers le bas à chaque nouveau message
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [messages])
async function send() {
const content = input.trim()
if (!content || sending) return
setInput('')
setSending(true)
try {
// Optimistic: ajouter le message user immédiatement
const optimisticUser: ReportMessage = {
id: `tmp-${Date.now()}`,
report_id: report.id,
role: 'user',
content,
status: 'done',
created_at: new Date().toISOString(),
}
const optimisticAssistant: ReportMessage = {
id: `tmp-assistant-${Date.now()}`,
report_id: report.id,
role: 'assistant',
content: '',
status: 'generating',
created_at: new Date().toISOString(),
}
setMessages(prev => [...prev, optimisticUser, optimisticAssistant])
await reportsApi.createMessage(report.id, content)
await loadMessages()
} finally {
setSending(false)
}
}
const hasGenerating = messages.some(m => m.status === 'generating')
return (
<div className="border-t pt-3 space-y-3">
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Conversation</p>
{messages.length > 0 && (
<div className="space-y-2">
{messages.map(msg => (
<MessageBubble key={msg.id} msg={msg} />
))}
<div ref={bottomRef} />
</div>
)}
<div className="flex gap-2">
<Input
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && !e.shiftKey && send()}
placeholder="Posez une question sur cette réponse…"
disabled={hasGenerating || sending}
className="text-sm"
/>
<Button
size="sm"
onClick={send}
disabled={!input.trim() || hasGenerating || sending}
className="shrink-0"
>
{sending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</Button>
</div>
</div>
)
}
export function Reports() {
const [reports, setReports] = useState<Report[]>([])
const [loading, setLoading] = useState(true)
const load = useCallback(async () => {
try { setReports((await reportsApi.list()) ?? []) }
finally { setLoading(false) }
}, [])
useEffect(() => { load() }, [load])
// Poll toutes les 3s tant qu'il y a des rapports en cours
useEffect(() => {
const hasGenerating = reports.some(r => r.status === 'generating')
if (!hasGenerating) return
const interval = setInterval(load, 3000)
return () => clearInterval(interval)
}, [reports, load])
async function remove(id: string) {
await reportsApi.delete(id)
setReports(prev => prev.filter(r => r.id !== id))
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
return (
<div className="p-4 md:p-6 space-y-6">
<div>
<h1 className="text-2xl font-bold">Rapports IA</h1>
<p className="text-muted-foreground text-sm">
Vos questions posées sur des extraits de résumés, avec les réponses de l'IA.
</p>
</div>
{reports.length === 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 text-center text-muted-foreground">
<FileText className="h-8 w-8 mx-auto mb-3 opacity-50" />
<p>Aucun rapport enregistré</p>
<p className="text-xs mt-1">Sélectionnez du texte dans un résumé et posez une question à l'IA.</p>
</CardContent>
</Card>
) : (
<div className="space-y-4">
{reports.map(r => (
<Card key={r.id} className={r.status === 'generating' ? 'border-primary/30' : ''}>
<CardContent className="pt-4 pb-4 space-y-3">
{/* Meta */}
<div className="flex items-start justify-between gap-4">
<div className="flex items-center gap-2 flex-wrap">
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Clock className="h-3 w-3" />
{new Date(r.created_at).toLocaleString('fr-FR')}
</div>
<StatusBadge status={r.status} />
</div>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive shrink-0"
onClick={() => remove(r.id)}
title={r.status === 'generating' ? 'Annuler' : 'Supprimer'}
>
{r.status === 'generating'
? <XCircle className="h-3 w-3" />
: <Trash2 className="h-3 w-3" />}
</Button>
</div>
{/* Extraits de contexte */}
{r.context_excerpt.split('\n\n---\n\n').map((excerpt, i) => (
<div key={i} className="rounded bg-muted/60 px-3 py-2 text-xs text-muted-foreground italic">
«&nbsp;{excerpt}&nbsp;»
</div>
))}
{/* Question */}
<p className="text-sm font-medium">{r.question}</p>
{/* Réponse initiale */}
{r.status === 'generating' && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
L'IA génère la réponse…
</div>
)}
{r.status === 'done' && (
<div className="border-t pt-3">
<Markdown content={r.answer} />
</div>
)}
{r.status === 'error' && (
<div className="text-sm text-destructive border-t pt-3">
Erreur : {r.error_msg || 'Une erreur est survenue lors de la génération.'}
</div>
)}
{/* Chat de suivi (uniquement quand le rapport est terminé) */}
{r.status === 'done' && <ReportChat report={r} />}
</CardContent>
</Card>
))}
</div>
)}
</div>
)
}

View File

@ -0,0 +1,117 @@
import { useState, useEffect, type FormEvent } from 'react'
import { Plus, Trash2, TrendingUp } from 'lucide-react'
import { assetsApi, type Asset } from '@/api/assets'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
export function Watchlist() {
const [assets, setAssets] = useState<Asset[]>([])
const [loading, setLoading] = useState(true)
const [symbol, setSymbol] = useState('')
const [name, setName] = useState('')
const [adding, setAdding] = useState(false)
const [removing, setRemoving] = useState<string | null>(null)
const [error, setError] = useState('')
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try { setAssets(await assetsApi.list() ?? []) } finally { setLoading(false) }
}
async function add(e: FormEvent) {
e.preventDefault()
if (!symbol) return
setAdding(true); setError('')
try {
await assetsApi.add(symbol.toUpperCase(), name)
setSymbol(''); setName('')
await load()
} catch (err) { setError(err instanceof Error ? err.message : 'Erreur') } finally { setAdding(false) }
}
async function remove(sym: string) {
setRemoving(sym)
await assetsApi.remove(sym)
await load()
setRemoving(null)
}
return (
<div className="p-4 md:p-6 space-y-6">
<div>
<h1 className="text-2xl font-bold">Watchlist</h1>
<p className="text-muted-foreground text-sm">Les symboles suivis seront utilisés pour personnaliser vos résumés IA</p>
</div>
{/* Formulaire d'ajout */}
<Card>
<CardHeader><CardTitle className="text-base">Ajouter un actif</CardTitle></CardHeader>
<CardContent>
<form onSubmit={add} className="flex flex-wrap gap-3 items-end">
<div className="space-y-1 flex-1 min-w-32">
<Label>Symbole</Label>
<Input
placeholder="AAPL, TSLA, BTC…"
value={symbol}
onChange={e => setSymbol(e.target.value.toUpperCase())}
className="font-mono"
required
/>
</div>
<div className="space-y-1 flex-1 min-w-40">
<Label>Nom <span className="text-muted-foreground">(optionnel)</span></Label>
<Input
placeholder="Apple Inc."
value={name}
onChange={e => setName(e.target.value)}
/>
</div>
<Button type="submit" disabled={adding || !symbol}>
{adding ? <Spinner className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
Ajouter
</Button>
</form>
{error && <p className="mt-2 text-sm text-destructive">{error}</p>}
</CardContent>
</Card>
{/* Liste */}
{loading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : assets.length === 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 text-center">
<TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3 opacity-50" />
<p className="text-muted-foreground">Aucun actif dans votre watchlist</p>
</CardContent>
</Card>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{assets.map(a => (
<Card key={a.id} className="flex items-center justify-between p-4">
<div className="flex items-center gap-3 min-w-0">
<Badge variant="secondary" className="font-mono shrink-0">{a.symbol}</Badge>
{a.name && <span className="text-sm text-muted-foreground truncate">{a.name}</span>}
</div>
<Button
variant="ghost"
size="icon"
className="shrink-0 h-7 w-7 text-muted-foreground hover:text-destructive"
onClick={() => remove(a.symbol)}
disabled={removing === a.symbol}
>
{removing === a.symbol ? <Spinner className="h-3 w-3" /> : <Trash2 className="h-3 w-3" />}
</Button>
</Card>
))}
</div>
)}
</div>
)
}

View File

@ -0,0 +1,652 @@
import { useState, useEffect, useCallback } from 'react'
import { Plus, Trash2, Star, Download, HardDrive, Cpu, ChevronDown, ChevronUp, X } from 'lucide-react'
import { adminApi, type AIProvider, type AIRoles, type OllamaModelInfo } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
const PROVIDER_NAMES = ['openai', 'anthropic', 'gemini', 'ollama', 'claudecode'] as const
const CUSTOM_MODELS_KEY = 'ollama_custom_models'
const KNOWN_OLLAMA_MODELS: { name: string; family: string; tags: { tag: string; size: string }[] }[] = [
{ name: 'qwen3', family: 'Qwen3', tags: [{ tag: '0.6b', size: '~0.4 GB' }, { tag: '1.7b', size: '~1.1 GB' }, { tag: '4b', size: '~2.6 GB' }, { tag: '8b', size: '~5.2 GB' }, { tag: '14b', size: '~9.3 GB' }, { tag: '32b', size: '~20 GB' }] },
{ name: 'qwen2.5', family: 'Qwen2.5', tags: [{ tag: '0.5b', size: '~0.4 GB' }, { tag: '1.5b', size: '~1 GB' }, { tag: '3b', size: '~2 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] },
{ name: 'llama3.2', family: 'Llama 3.2', tags: [{ tag: '1b', size: '~1.3 GB' }, { tag: '3b', size: '~2 GB' }] },
{ name: 'llama3.1', family: 'Llama 3.1', tags: [{ tag: '8b', size: '~4.9 GB' }, { tag: '70b', size: '~40 GB' }] },
{ name: 'gemma3', family: 'Gemma 3', tags: [{ tag: '1b', size: '~0.8 GB' }, { tag: '4b', size: '~3.3 GB' }, { tag: '12b', size: '~8 GB' }, { tag: '27b', size: '~17 GB' }] },
{ name: 'mistral', family: 'Mistral', tags: [{ tag: '7b', size: '~4.1 GB' }] },
{ name: 'phi4', family: 'Phi-4', tags: [{ tag: 'latest', size: '~9 GB' }] },
{ name: 'phi4-mini', family: 'Phi-4 Mini', tags: [{ tag: 'latest', size: '~2.5 GB' }] },
{ name: 'deepseek-r1', family: 'DeepSeek-R1', tags: [{ tag: '1.5b', size: '~1.1 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '8b', size: '~4.9 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] },
]
function formatSize(bytes: number): string {
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`
if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB`
return `${bytes} B`
}
function loadCustomModels(): string[] {
try { return JSON.parse(localStorage.getItem(CUSTOM_MODELS_KEY) ?? '[]') } catch { return [] }
}
function saveCustomModels(models: string[]) {
localStorage.setItem(CUSTOM_MODELS_KEY, JSON.stringify(models))
}
// ── Confirmation dialog ────────────────────────────────────────────────────
function ConfirmDownloadDialog({ modelName, onConfirm, onCancel }: {
modelName: string
onConfirm: () => void
onCancel: () => void
}) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="bg-card border rounded-xl shadow-2xl p-6 w-full max-w-sm mx-4 space-y-4">
<div className="flex items-start justify-between">
<div>
<p className="font-semibold">Télécharger ce modèle ?</p>
<p className="text-sm text-muted-foreground mt-1">
<span className="font-mono text-foreground">{modelName}</span> sera téléchargé depuis Ollama Hub.
Le téléchargement peut prendre plusieurs minutes.
</p>
</div>
<button onClick={onCancel} className="text-muted-foreground hover:text-foreground ml-3 shrink-0">
<X className="h-4 w-4" />
</button>
</div>
<div className="flex gap-2 justify-end">
<Button variant="outline" size="sm" onClick={onCancel}>Annuler</Button>
<Button size="sm" onClick={onConfirm}>
<Download className="h-3 w-3 mr-1" /> Télécharger
</Button>
</div>
</div>
</div>
)
}
// ── Shared model catalogue ─────────────────────────────────────────────────
function ModelCatalogue({
installedNames,
pulling,
onPull,
}: {
installedNames: Set<string>
pulling: string | null
onPull: (name: string) => void
}) {
const [customName, setCustomName] = useState('')
const [pendingModel, setPendingModel] = useState<string | null>(null)
const [customModels, setCustomModels] = useState<string[]>(loadCustomModels)
// All model names in the hardcoded catalogue
const knownNames = new Set(
KNOWN_OLLAMA_MODELS.flatMap(f => f.tags.map(t => `${f.name}:${t.tag}`))
)
function requestPull(name: string) {
setPendingModel(name)
}
function confirmPull() {
if (!pendingModel) return
// If not in hardcoded catalogue, add to custom list
if (!knownNames.has(pendingModel)) {
const updated = [...new Set([...customModels, pendingModel])]
setCustomModels(updated)
saveCustomModels(updated)
}
onPull(pendingModel)
setPendingModel(null)
}
function submitCustom() {
const name = customName.trim()
if (!name) return
const fullName = name.includes(':') ? name : `${name}:latest`
setCustomName('')
requestPull(fullName)
}
// Families to display: hardcoded + custom entries
const customEntries = customModels.filter(m => !knownNames.has(m))
return (
<>
{pendingModel && (
<ConfirmDownloadDialog
modelName={pendingModel}
onConfirm={confirmPull}
onCancel={() => setPendingModel(null)}
/>
)}
<div className="space-y-4">
{/* Free-text input */}
<div>
<p className="text-xs font-semibold text-muted-foreground mb-1.5">Nom personnalisé</p>
<div className="flex gap-2">
<Input
className="h-8 text-sm font-mono"
placeholder="ex: llama3.2:3b, mymodel:latest…"
value={customName}
onChange={e => setCustomName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && submitCustom()}
disabled={pulling !== null}
/>
<Button size="sm" className="h-8 shrink-0" onClick={submitCustom}
disabled={!customName.trim() || pulling !== null}>
<Download className="h-3 w-3" /> Installer
</Button>
</div>
</div>
{/* Custom models section */}
{customEntries.length > 0 && (
<div>
<p className="text-xs font-semibold text-muted-foreground mb-1.5">Personnalisés</p>
<div className="flex flex-wrap gap-1.5">
{customEntries.map(fullName => {
const installed = installedNames.has(fullName)
const isPulling = pulling === fullName
return <ModelTag key={fullName} fullName={fullName} size="?" installed={installed} isPulling={isPulling} pulling={pulling} onRequest={requestPull} />
})}
</div>
</div>
)}
{/* Hardcoded catalogue */}
<div className="space-y-3">
{KNOWN_OLLAMA_MODELS.map(family => (
<div key={family.name}>
<p className="text-xs font-semibold text-muted-foreground mb-1.5">{family.family}</p>
<div className="flex flex-wrap gap-1.5">
{family.tags.map(({ tag, size }) => {
const fullName = `${family.name}:${tag}`
const installed = installedNames.has(fullName)
const isPulling = pulling === fullName
return <ModelTag key={fullName} fullName={fullName} size={size} installed={installed} isPulling={isPulling} pulling={pulling} onRequest={requestPull} />
})}
</div>
</div>
))}
</div>
</div>
</>
)
}
function ModelTag({ fullName, size, installed, isPulling, pulling, onRequest }: {
fullName: string; size: string
installed: boolean; isPulling: boolean; pulling: string | null
onRequest: (name: string) => void
}) {
return (
<button
type="button"
disabled={installed || pulling !== null}
onClick={() => !installed && !isPulling && onRequest(fullName)}
className={[
'flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors',
installed
? 'border-primary/40 bg-primary/5 text-primary cursor-default'
: isPulling
? 'border-border bg-muted text-muted-foreground cursor-wait'
: pulling !== null
? 'border-border bg-background text-muted-foreground opacity-50 cursor-not-allowed'
: 'border-border bg-background hover:border-primary/60 hover:bg-primary/5 cursor-pointer',
].join(' ')}
>
{isPulling
? <><Spinner className="h-2.5 w-2.5" /> Téléchargement…</>
: installed
? <><span className="text-[10px]">✓</span> {fullName}</>
: <><Download className="h-2.5 w-2.5" /> {fullName} {size !== '?' && <span className="text-muted-foreground">{size}</span>}</>
}
</button>
)
}
// ── Cloud model picker (OpenAI / Anthropic / Gemini / …) ──────────────────
function CloudModelPicker({ value, providerName, apiKey, endpoint, onChange }: {
value: string; providerName: string; apiKey: string; endpoint: string
onChange: (model: string) => void
}) {
const [models, setModels] = useState<string[]>([])
const [loading, setLoading] = useState(false)
const [loadError, setLoadError] = useState('')
const noKeyNeeded = providerName === 'claudecode'
useEffect(() => {
if (noKeyNeeded) loadModels()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [providerName])
async function loadModels() {
if (!noKeyNeeded && !apiKey) { setLoadError('Renseigne la clé API d\'abord'); return }
setLoading(true); setLoadError('')
try {
const list = await adminApi.probeModels({ name: providerName, api_key: apiKey, endpoint })
setModels(list ?? [])
if ((list ?? []).length === 0) setLoadError('Aucun modèle trouvé')
} catch (e) {
setLoadError(e instanceof Error ? e.message : 'Erreur')
} finally { setLoading(false) }
}
return (
<div className="space-y-1.5">
<div className="flex gap-2">
<Input
placeholder="gpt-4o-mini, claude-sonnet-4-6…"
value={value}
onChange={e => onChange(e.target.value)}
list="cloud-models-list"
className="flex-1"
/>
<Button type="button" variant="outline" size="sm" className="shrink-0" onClick={loadModels} disabled={loading}>
{loading ? <Spinner className="h-3 w-3" /> : 'Charger'}
</Button>
</div>
{models.length > 0 && (
<datalist id="cloud-models-list">
{models.map(m => <option key={m} value={m} />)}
</datalist>
)}
{models.length > 0 && (
<Select value={value} onChange={e => onChange(e.target.value)}>
<option value="">— Sélectionner un modèle —</option>
{models.map(m => <option key={m} value={m}>{m}</option>)}
</Select>
)}
{loadError && <p className="text-xs text-destructive">{loadError}</p>}
</div>
)
}
// ── Ollama model picker (inside provider form) ─────────────────────────────
function OllamaModelPicker({ value, installedModels, onSelect, onRefresh }: {
value: string
installedModels: OllamaModelInfo[]
onSelect: (name: string) => void
onRefresh: () => Promise<OllamaModelInfo[]>
}) {
const [showCatalogue, setShowCatalogue] = useState(installedModels.length === 0)
const [pulling, setPulling] = useState<string | null>(null)
const installedNames = new Set(installedModels.map(m => m.name))
async function pull(fullName: string) {
setPulling(fullName)
try {
await adminApi.pullOllamaModel(fullName)
await new Promise<void>(resolve => {
const iv = setInterval(async () => {
try {
const updated = await onRefresh()
if (updated.some(m => m.name === fullName)) { clearInterval(iv); onSelect(fullName); setShowCatalogue(false); resolve() }
} catch { /* ignore */ }
}, 4000)
setTimeout(() => { clearInterval(iv); resolve() }, 1800000)
})
} finally { setPulling(null) }
}
return (
<div className="space-y-2">
<Select value={value} onChange={e => onSelect(e.target.value)}>
<option value="">— Choisir un modèle installé —</option>
{installedModels.map(m => (
<option key={m.name} value={m.name}>
{m.name}{m.details.parameter_size ? ` (${m.details.parameter_size})` : ''}
</option>
))}
</Select>
<button type="button" className="flex items-center gap-1 text-xs text-primary hover:underline"
onClick={() => setShowCatalogue(v => !v)}>
{showCatalogue ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
{showCatalogue ? 'Masquer le catalogue' : 'Installer un nouveau modèle'}
</button>
{showCatalogue && (
<div className="rounded-lg border bg-muted/30 p-3 max-h-72 overflow-y-auto">
<ModelCatalogue installedNames={installedNames} pulling={pulling} onPull={pull} />
</div>
)}
</div>
)
}
// ── Role Assignment ────────────────────────────────────────────────────────
const ROLE_LABELS: Record<string, { label: string; desc: string }> = {
summary: { label: 'Résumés', desc: 'Génération du résumé quotidien (passe 2)' },
report: { label: 'Rapports', desc: 'Réponses aux questions sur les résumés' },
filter: { label: 'Filtre articles', desc: 'Sélection des articles pertinents (passe 1)' },
}
function RoleCard({ role, providers, currentProviderID, onSave }: {
role: string; providers: AIProvider[]; currentProviderID: string
onSave: (providerID: string) => Promise<void>
}) {
const [providerID, setProviderID] = useState(currentProviderID)
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
useEffect(() => { setProviderID(currentProviderID) }, [currentProviderID])
const { label, desc } = ROLE_LABELS[role]
async function save() {
setSaving(true)
try { await onSave(providerID); setSaved(true); setTimeout(() => setSaved(false), 2000) }
finally { setSaving(false) }
}
return (
<div className="grid gap-3 sm:grid-cols-[1fr_auto] items-end">
<div>
<Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{label}</Label>
<p className="text-xs text-muted-foreground mb-2">{desc}</p>
<Select value={providerID} onChange={e => setProviderID(e.target.value)}>
<option value="">— Fournisseur par défaut —</option>
{providers.map(p => <option key={p.id} value={p.id}>{p.name}{p.model ? ` — ${p.model}` : ''}</option>)}
</Select>
</div>
<Button size="sm" onClick={save} disabled={saving} className="whitespace-nowrap">
{saving ? <Spinner className="h-3 w-3" /> : saved ? '✓ Sauvegardé' : 'Appliquer'}
</Button>
</div>
)
}
// ── Ollama model manager card ──────────────────────────────────────────────
function OllamaModelsCard({ installedModels, onRefresh, onDelete }: {
installedModels: OllamaModelInfo[]
onRefresh: () => Promise<OllamaModelInfo[]>
onDelete: (name: string) => Promise<void>
}) {
const [showCatalogue, setShowCatalogue] = useState(false)
const [pulling, setPulling] = useState<string | null>(null)
const [deleting, setDeleting] = useState<string | null>(null)
const installedNames = new Set(installedModels.map(m => m.name))
async function pull(fullName: string) {
setPulling(fullName)
try {
await adminApi.pullOllamaModel(fullName)
await new Promise<void>(resolve => {
const iv = setInterval(async () => {
try {
const updated = await onRefresh()
if (updated.some(m => m.name === fullName)) { clearInterval(iv); resolve() }
} catch { /* ignore */ }
}, 4000)
setTimeout(() => { clearInterval(iv); resolve() }, 1800000)
})
} finally { setPulling(null) }
}
async function remove(name: string) {
setDeleting(name)
try { await onDelete(name) } finally { setDeleting(null) }
}
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2 text-base">
<HardDrive className="h-4 w-4" /> Modèles Ollama
</CardTitle>
<Button variant="outline" size="sm" onClick={() => setShowCatalogue(v => !v)}>
{showCatalogue ? <><ChevronUp className="h-3.5 w-3.5" /> Masquer</> : <><Download className="h-3.5 w-3.5" /> Installer</>}
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div>
<h3 className="text-sm font-semibold mb-2 flex items-center gap-1.5">
<Cpu className="h-3.5 w-3.5" /> Installés ({installedModels.length})
</h3>
{installedModels.length === 0 ? (
<p className="text-sm text-muted-foreground italic">Aucun modèle installé</p>
) : (
<div className="space-y-1.5">
{installedModels.map(m => (
<div key={m.name} className="flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2">
<div>
<span className="font-mono text-sm font-medium">{m.name}</span>
<span className="ml-3 text-xs text-muted-foreground">
{formatSize(m.size)}
{m.details.parameter_size && <> · {m.details.parameter_size}</>}
{m.details.quantization_level && <> · {m.details.quantization_level}</>}
</span>
</div>
<Button variant="ghost" size="sm"
className="text-destructive hover:text-destructive h-7 w-7 p-0"
onClick={() => remove(m.name)} disabled={deleting === m.name}>
{deleting === m.name ? <Spinner className="h-3 w-3" /> : <Trash2 className="h-3 w-3" />}
</Button>
</div>
))}
</div>
)}
</div>
{showCatalogue && (
<div className="rounded-lg border bg-muted/30 p-4">
<p className="text-sm font-semibold mb-3">Catalogue</p>
<ModelCatalogue installedNames={installedNames} pulling={pulling} onPull={pull} />
</div>
)}
</CardContent>
</Card>
)
}
// ── Main Page ──────────────────────────────────────────────────────────────
export function AIProviders() {
const [providers, setProviders] = useState<AIProvider[]>([])
const [roles, setRoles] = useState<AIRoles | null>(null)
const [ollamaModels, setOllamaModels] = useState<OllamaModelInfo[]>([])
const [loading, setLoading] = useState(true)
const [showForm, setShowForm] = useState(false)
const [form, setForm] = useState({ name: 'openai', api_key: '', model: '', endpoint: '' })
const [editId, setEditId] = useState<string | null>(null)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const isOllamaForm = form.name === 'ollama'
const isClaudeCodeForm = form.name === 'claudecode'
const loadOllamaModels = useCallback(async (): Promise<OllamaModelInfo[]> => {
try {
console.log('[ollama] fetching installed models…')
const m = await adminApi.listOllamaModels()
const list = m ?? []
console.log(`[ollama] ${list.length} model(s):`, list.map(x => x.name))
setOllamaModels(list)
return list
} catch (e) {
console.error('[ollama] error:', e)
return []
}
}, [])
const load = useCallback(async () => {
setLoading(true)
try {
const [p, r] = await Promise.all([adminApi.listProviders(), adminApi.getRoles()])
setProviders(p ?? [])
setRoles(r)
await loadOllamaModels()
} finally { setLoading(false) }
}, [loadOllamaModels])
useEffect(() => { load() }, [load])
async function save() {
setSaving(true); setError('')
try {
if (editId) { await adminApi.updateProvider(editId, form) }
else { await adminApi.createProvider(form) }
setShowForm(false); setEditId(null)
setForm({ name: 'openai', api_key: '', model: '', endpoint: '' })
await load()
} catch (e) { setError(e instanceof Error ? e.message : 'Erreur') }
finally { setSaving(false) }
}
async function setDefault(id: string) { await adminApi.activateProvider(id); await load() }
async function remove(id: string) {
if (!confirm('Supprimer ce fournisseur ?')) return
await adminApi.deleteProvider(id); await load()
}
function startEdit(p: AIProvider) {
setEditId(p.id); setForm({ name: p.name, api_key: '', model: p.model, endpoint: p.endpoint }); setShowForm(true)
}
async function saveRole(role: string, providerID: string) {
await adminApi.updateRole(role, { provider_id: providerID, model: '' }); await load()
}
async function deleteOllamaModel(name: string) {
await adminApi.deleteOllamaModel(name); await loadOllamaModels()
}
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Fournisseurs IA</h1>
<p className="text-muted-foreground text-sm">Configurez les fournisseurs et assignez un modèle à chaque tâche</p>
</div>
{loading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : (
<>
{/* Role assignments */}
{roles && providers.length > 0 && (
<Card>
<CardHeader><CardTitle className="text-base">Assignation des tâches</CardTitle></CardHeader>
<CardContent className="space-y-5 divide-y">
{(['summary', 'report', 'filter'] as const).map(role => (
<div key={role} className={role !== 'summary' ? 'pt-5' : ''}>
<RoleCard role={role} providers={providers}
currentProviderID={roles[role].provider_id}
onSave={pid => saveRole(role, pid)} />
</div>
))}
</CardContent>
</Card>
)}
{/* Providers list */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-base">Fournisseurs configurés</CardTitle>
<Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm({ name: 'openai', api_key: '', model: '', endpoint: '' }) }}>
<Plus className="h-4 w-4" /> Ajouter
</Button>
</div>
</CardHeader>
<CardContent className="space-y-3">
{showForm && (
<div className="rounded-lg border p-4 space-y-4 bg-muted/30">
<p className="font-medium text-sm">{editId ? 'Modifier le fournisseur' : 'Nouveau fournisseur'}</p>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label>Fournisseur</Label>
<Select value={form.name} disabled={!!editId}
onChange={e => {
const name = e.target.value
setForm(f => ({ ...f, name, model: '', api_key: '', endpoint: name === 'ollama' ? 'http://ollama:11434' : '' }))
}}>
{PROVIDER_NAMES.map(n => <option key={n} value={n}>{n}</option>)}
</Select>
</div>
{!isOllamaForm && !isClaudeCodeForm && (
<div className="space-y-1">
<Label>Clé API {editId && <span className="text-muted-foreground text-xs">(vide = conserver)</span>}</Label>
<Input type="password" placeholder="sk-…" value={form.api_key} onChange={e => setForm(f => ({ ...f, api_key: e.target.value }))} />
</div>
)}
{isOllamaForm && (
<div className="space-y-1">
<Label>Endpoint</Label>
<Input value={form.endpoint || 'http://ollama:11434'} onChange={e => setForm(f => ({ ...f, endpoint: e.target.value }))} />
</div>
)}
</div>
<div className="space-y-1">
<Label>Modèle par défaut</Label>
{isOllamaForm ? (
<OllamaModelPicker value={form.model} installedModels={ollamaModels}
onSelect={m => setForm(f => ({ ...f, model: m }))}
onRefresh={loadOllamaModels} />
) : (
<CloudModelPicker
value={form.model}
providerName={form.name}
apiKey={form.api_key}
endpoint={form.endpoint}
onChange={m => setForm(f => ({ ...f, model: m }))}
/>
)}
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<div className="flex gap-2">
<Button size="sm" onClick={save} disabled={saving}>{saving ? <Spinner className="h-4 w-4" /> : 'Enregistrer'}</Button>
<Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null) }}>Annuler</Button>
</div>
</div>
)}
{providers.length === 0 && !showForm && (
<p className="text-sm text-muted-foreground text-center py-4">Aucun fournisseur configuré</p>
)}
{providers.map(p => (
<div key={p.id} className={`flex flex-wrap items-center gap-3 rounded-md border px-3 py-2.5 ${p.is_active ? 'border-primary/50 bg-primary/5' : ''}`}>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold capitalize text-sm">{p.name}</span>
{p.is_active && <Badge variant="default" className="text-xs">Défaut</Badge>}
{!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' && <Badge variant="outline" className="text-yellow-500 border-yellow-500 text-xs">Sans clé</Badge>}
</div>
<div className="text-xs text-muted-foreground flex gap-3 mt-0.5">
{p.model && <span>Modèle : <strong>{p.model}</strong></span>}
{p.endpoint && <span>{p.endpoint}</span>}
</div>
</div>
<div className="flex items-center gap-1.5">
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => startEdit(p)}>Modifier</Button>
{!p.is_active && (
<Button size="sm" variant="outline" className="h-7 px-2 text-xs" onClick={() => setDefault(p.id)}>
<Star className="h-3 w-3 mr-1" /> Défaut
</Button>
)}
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" onClick={() => remove(p.id)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
))}
</CardContent>
</Card>
{/* Ollama model manager — always shown so user can install even without provider configured */}
<OllamaModelsCard
installedModels={ollamaModels}
onRefresh={loadOllamaModels}
onDelete={deleteOllamaModel}
/>
</>
)}
</div>
)
}

View File

@ -0,0 +1,47 @@
import { NavLink, Outlet, Navigate } from 'react-router-dom'
import { Cpu, Key, Database, ClipboardList, Users, CalendarDays, Settings } from 'lucide-react'
import { useAuth } from '@/lib/auth'
import { cn } from '@/lib/cn'
const adminItems = [
{ to: '/admin/ai', icon: Cpu, label: 'Fournisseurs IA' },
{ to: '/admin/credentials', icon: Key, label: 'Identifiants' },
{ to: '/admin/sources', icon: Database, label: 'Sources' },
{ to: '/admin/jobs', icon: ClipboardList,label: 'Jobs' },
{ to: '/admin/users', icon: Users, label: 'Utilisateurs' },
{ to: '/admin/schedule', icon: CalendarDays, label: 'Planning' },
{ to: '/admin/settings', icon: Settings, label: 'Paramètres' },
]
export function AdminLayout() {
const { isAdmin } = useAuth()
if (!isAdmin) return <Navigate to="/" replace />
return (
<div>
{/* Mobile sub-nav — scrollable horizontal tabs */}
<nav className="md:hidden flex overflow-x-auto border-b bg-card scrollbar-none sticky top-0 z-10">
{adminItems.map(({ to, icon: Icon, label }) => (
<NavLink
key={to}
to={to}
className={({ isActive }) =>
cn(
'flex shrink-0 flex-col items-center gap-1 px-4 py-3 text-xs font-medium transition-colors border-b-2',
isActive
? 'border-primary text-primary'
: 'border-transparent text-muted-foreground'
)
}
>
<Icon className="h-4 w-4" />
{label}
</NavLink>
))}
</nav>
<div className="p-6">
<Outlet />
</div>
</div>
)
}

View File

@ -0,0 +1,209 @@
import { useState, useEffect } from 'react'
import { Save, RotateCcw, Sun, Moon } from 'lucide-react'
import { adminApi, type Setting } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Spinner } from '@/components/ui/spinner'
import { useTheme } from '@/lib/theme'
const NUMERIC_SETTINGS: Record<string, { label: string; description: string }> = {
summary_max_articles: { label: 'Articles max par résumé', description: 'Nombre maximum d\'articles envoyés à l\'IA pour la passe 2 (résumé)' },
filter_batch_size: { label: 'Taille des batches (filtre)', description: 'Nombre d\'articles par appel IA lors de la passe 1 (filtrage). Réduire pour des réponses plus rapides.' },
}
const COMMON_TIMEZONES = [
'Europe/Paris', 'Europe/London', 'Europe/Berlin', 'Europe/Madrid', 'Europe/Rome',
'America/New_York', 'America/Chicago', 'America/Los_Angeles',
'Asia/Tokyo', 'Asia/Hong_Kong', 'Asia/Singapore',
'UTC',
]
export function AdminSettings() {
const { theme, setTheme } = useTheme()
const [settings, setSettings] = useState<Setting[]>([])
const [loading, setLoading] = useState(true)
const [values, setValues] = useState<Record<string, string>>({})
const [defaultPrompt, setDefaultPrompt] = useState('')
const [saving, setSaving] = useState(false)
const [savingTz, setSavingTz] = useState(false)
const [savingPrompt, setSavingPrompt] = useState(false)
const [saved, setSaved] = useState(false)
const [savedTz, setSavedTz] = useState(false)
const [savedPrompt, setSavedPrompt] = useState(false)
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try {
const [s, d] = await Promise.all([
adminApi.listSettings(),
adminApi.getDefaultPrompt(),
])
const settled = s ?? []
setSettings(settled)
setDefaultPrompt(d?.prompt ?? '')
const v: Record<string, string> = {}
for (const setting of settled) v[setting.key] = setting.value
setValues(v)
} finally { setLoading(false) }
}
async function saveNumeric() {
setSaving(true); setSaved(false)
const numericKeys = Object.keys(NUMERIC_SETTINGS)
await adminApi.updateSettings(
settings
.filter(s => numericKeys.includes(s.key))
.map(s => ({ key: s.key, value: values[s.key] ?? s.value }))
)
setSaving(false); setSaved(true)
setTimeout(() => setSaved(false), 2000)
}
async function saveTimezone() {
setSavingTz(true); setSavedTz(false)
await adminApi.updateSettings([{ key: 'timezone', value: values['timezone'] ?? 'Europe/Paris' }])
setSavingTz(false); setSavedTz(true)
setTimeout(() => setSavedTz(false), 2000)
}
async function savePrompt() {
setSavingPrompt(true); setSavedPrompt(false)
await adminApi.updateSettings([{ key: 'ai_system_prompt', value: values['ai_system_prompt'] ?? '' }])
setSavingPrompt(false); setSavedPrompt(true)
setTimeout(() => setSavedPrompt(false), 2000)
}
function resetPrompt() {
setValues(v => ({ ...v, ai_system_prompt: defaultPrompt }))
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
const currentPrompt = values['ai_system_prompt'] ?? defaultPrompt
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Paramètres</h1>
<p className="text-muted-foreground text-sm">Configuration globale du service</p>
</div>
{/* Apparence */}
<Card>
<CardHeader><CardTitle>Apparence</CardTitle></CardHeader>
<CardContent>
<div className="flex items-center gap-3">
<button
onClick={() => setTheme('light')}
className={`flex items-center gap-2 px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
theme === 'light'
? 'bg-primary text-primary-foreground border-primary'
: 'bg-transparent text-muted-foreground border-border hover:bg-accent hover:text-foreground'
}`}
>
<Sun className="h-4 w-4" />
Clair
</button>
<button
onClick={() => setTheme('dark')}
className={`flex items-center gap-2 px-4 py-2 rounded-md border text-sm font-medium transition-colors ${
theme === 'dark'
? 'bg-primary text-primary-foreground border-primary'
: 'bg-transparent text-muted-foreground border-border hover:bg-accent hover:text-foreground'
}`}
>
<Moon className="h-4 w-4" />
Sombre
</button>
</div>
</CardContent>
</Card>
{/* Fuseau horaire */}
<Card>
<CardHeader><CardTitle>Fuseau horaire</CardTitle></CardHeader>
<CardContent className="space-y-4">
<div className="space-y-1">
<Label>Timezone (IANA)</Label>
<p className="text-xs text-muted-foreground">
Utilisé pour le planning de scraping et l'horodatage des résumés
</p>
<div className="flex gap-2 max-w-sm">
<Input
list="tz-list"
value={values['timezone'] ?? 'Europe/Paris'}
onChange={e => setValues(v => ({ ...v, timezone: e.target.value }))}
placeholder="Europe/Paris"
/>
<datalist id="tz-list">
{COMMON_TIMEZONES.map(tz => <option key={tz} value={tz} />)}
</datalist>
</div>
</div>
<Button onClick={saveTimezone} disabled={savingTz}>
{savingTz ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
{savedTz ? 'Enregistré !' : 'Enregistrer'}
</Button>
</CardContent>
</Card>
{/* Paramètres généraux */}
<Card>
<CardHeader><CardTitle>Paramètres généraux</CardTitle></CardHeader>
<CardContent className="space-y-6">
{settings.filter(s => NUMERIC_SETTINGS[s.key]).map(s => {
const meta = NUMERIC_SETTINGS[s.key]
return (
<div key={s.key} className="space-y-1">
<Label>{meta.label}</Label>
<p className="text-xs text-muted-foreground">{meta.description}</p>
<Input
value={values[s.key] ?? ''}
onChange={e => setValues(v => ({ ...v, [s.key]: e.target.value }))}
className="max-w-xs"
type="number"
min="1"
/>
</div>
)
})}
<Button onClick={saveNumeric} disabled={saving}>
{saving ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
{saved ? 'Enregistré !' : 'Enregistrer'}
</Button>
</CardContent>
</Card>
{/* Contexte IA */}
<Card>
<CardHeader>
<CardTitle>Contexte IA</CardTitle>
<p className="text-sm text-muted-foreground">
Instructions envoyées à l'IA avant les articles. Les actifs de ta watchlist et les articles sont ajoutés automatiquement après ce texte.
</p>
</CardHeader>
<CardContent className="space-y-4">
<textarea
className="w-full min-h-[280px] rounded-md border border-input bg-background px-3 py-2 text-sm font-mono resize-y focus:outline-none focus:ring-2 focus:ring-ring"
value={currentPrompt}
onChange={e => setValues(v => ({ ...v, ai_system_prompt: e.target.value }))}
spellCheck={false}
/>
<div className="flex gap-2">
<Button onClick={savePrompt} disabled={savingPrompt}>
{savingPrompt ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
{savedPrompt ? 'Enregistré !' : 'Enregistrer le contexte'}
</Button>
<Button variant="outline" onClick={resetPrompt} title="Remettre le contexte par défaut">
<RotateCcw className="h-4 w-4" /> Réinitialiser
</Button>
</div>
</CardContent>
</Card>
</div>
)
}

View File

@ -0,0 +1,113 @@
import { useState, useEffect } from 'react'
import { Trash2, Pencil } from 'lucide-react'
import { adminApi, type AdminUser } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
import { useAuth } from '@/lib/auth'
export function AdminUsers() {
const { user: me } = useAuth()
const [users, setUsers] = useState<AdminUser[]>([])
const [loading, setLoading] = useState(true)
const [editId, setEditId] = useState<string | null>(null)
const [editForm, setEditForm] = useState({ email: '', role: 'user' })
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try { setUsers((await adminApi.listUsers()) ?? []) } finally { setLoading(false) }
}
function startEdit(u: AdminUser) {
setEditId(u.id); setEditForm({ email: u.email, role: u.role }); setError('')
}
async function save() {
if (!editId) return
setSaving(true); setError('')
try {
await adminApi.updateUser(editId, editForm.email, editForm.role)
setEditId(null); await load()
} catch (e) { setError(e instanceof Error ? e.message : 'Erreur') } finally { setSaving(false) }
}
async function remove(id: string) {
if (!confirm('Supprimer cet utilisateur ?')) return
await adminApi.deleteUser(id)
await load()
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Utilisateurs</h1>
<p className="text-muted-foreground text-sm">{users.length} utilisateur(s)</p>
</div>
<Card>
<CardHeader><CardTitle>Liste</CardTitle></CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b">
<tr className="text-left text-muted-foreground">
<th className="px-4 py-3">Email</th>
<th className="px-4 py-3">Rôle</th>
<th className="px-4 py-3">Inscrit le</th>
<th className="px-4 py-3">Actions</th>
</tr>
</thead>
<tbody>
{users.map(u => (
<tr key={u.id} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3">
{editId === u.id ? (
<Input value={editForm.email} onChange={e => setEditForm(f => ({ ...f, email: e.target.value }))} className="h-7" />
) : (
<span className={u.id === me?.id ? 'font-medium' : ''}>{u.email}</span>
)}
</td>
<td className="px-4 py-3">
{editId === u.id ? (
<Select value={editForm.role} onChange={e => setEditForm(f => ({ ...f, role: e.target.value }))} className="h-7 w-28">
<option value="user">user</option>
<option value="admin">admin</option>
</Select>
) : (
<Badge variant={u.role === 'admin' ? 'default' : 'secondary'}>{u.role}</Badge>
)}
</td>
<td className="px-4 py-3 text-muted-foreground">{new Date(u.created_at).toLocaleDateString('fr-FR')}</td>
<td className="px-4 py-3">
{editId === u.id ? (
<div className="flex gap-2">
<Button size="sm" onClick={save} disabled={saving}>{saving ? <Spinner className="h-3 w-3" /> : 'OK'}</Button>
<Button size="sm" variant="outline" onClick={() => setEditId(null)}>Annuler</Button>
{error && <span className="text-destructive text-xs">{error}</span>}
</div>
) : (
<div className="flex gap-2">
<Button variant="outline" size="icon" className="h-7 w-7" onClick={() => startEdit(u)}><Pencil className="h-3 w-3" /></Button>
{u.id !== me?.id && (
<Button variant="destructive" size="icon" className="h-7 w-7" onClick={() => remove(u.id)}><Trash2 className="h-3 w-3" /></Button>
)}
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
</div>
)
}

View File

@ -0,0 +1,114 @@
import { useState, useEffect } from 'react'
import { Eye, EyeOff, Save } from 'lucide-react'
import { adminApi, type Credential } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Spinner } from '@/components/ui/spinner'
export function Credentials() {
const [creds, setCreds] = useState<Credential[]>([])
const [loading, setLoading] = useState(true)
const [forms, setForms] = useState<Record<string, { username: string; password: string; show: boolean }>>({})
const [saving, setSaving] = useState<string | null>(null)
const [success, setSuccess] = useState<string | null>(null)
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try {
const data = await adminApi.getCredentials()
setCreds(data ?? [])
const init: typeof forms = {}
for (const c of data ?? []) {
init[c.source_id] = { username: c.username, password: '', show: false }
}
setForms(init)
} finally { setLoading(false) }
}
function update(sourceId: string, field: string, value: string | boolean) {
setForms(f => ({ ...f, [sourceId]: { ...f[sourceId], [field]: value } }))
}
async function save(sourceId: string) {
setSaving(sourceId); setSuccess(null)
const f = forms[sourceId]
await adminApi.updateCredentials({
source_id: sourceId,
username: f.username,
...(f.password ? { password: f.password } : {}),
})
setSaving(null)
setSuccess(sourceId)
setTimeout(() => setSuccess(null), 2000)
await load()
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Identifiants de scraping</h1>
<p className="text-muted-foreground text-sm">Les mots de passe sont chiffrés en AES-256-GCM côté serveur</p>
</div>
{creds.length === 0 && (
<Card><CardContent className="py-8 text-center text-muted-foreground">Aucune source nécessitant des identifiants</CardContent></Card>
)}
{creds.map(cred => {
const f = forms[cred.source_id] ?? { username: '', password: '', show: false }
return (
<Card key={cred.source_id}>
<CardHeader>
<CardTitle className="flex items-center gap-2">{cred.source_name}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor={`user-${cred.source_id}`}>Identifiant / Email</Label>
<Input
id={`user-${cred.source_id}`}
value={f.username}
onChange={e => update(cred.source_id, 'username', e.target.value)}
placeholder="votre@email.com"
/>
</div>
<div className="space-y-1">
<Label htmlFor={`pwd-${cred.source_id}`}>
Mot de passe {cred.has_password && <span className="text-muted-foreground">(déjà défini — laisser vide pour ne pas changer)</span>}
</Label>
<div className="relative">
<Input
id={`pwd-${cred.source_id}`}
type={f.show ? 'text' : 'password'}
value={f.password}
onChange={e => update(cred.source_id, 'password', e.target.value)}
placeholder={cred.has_password ? '••••••••' : 'Nouveau mot de passe'}
className="pr-10"
/>
<button
type="button"
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
onClick={() => update(cred.source_id, 'show', !f.show)}
>
{f.show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
</div>
</div>
<Button onClick={() => save(cred.source_id)} disabled={saving === cred.source_id}>
{saving === cred.source_id ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
{success === cred.source_id ? 'Enregistré !' : 'Enregistrer'}
</Button>
</CardContent>
</Card>
)
})}
</div>
)
}

View File

@ -0,0 +1,109 @@
import { useState, useEffect } from 'react'
import { Play, RefreshCw } from 'lucide-react'
import { adminApi, type ScrapeJob, type Source } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Select } from '@/components/ui/select'
import { Spinner } from '@/components/ui/spinner'
function jobStatusVariant(status: string) {
if (status === 'done') return 'bullish'
if (status === 'error') return 'bearish'
if (status === 'running') return 'default'
return 'outline'
}
function fmtDate(t: { Time: string; Valid: boolean } | null) {
if (!t?.Valid) return '—'
return new Date(t.Time).toLocaleString('fr-FR')
}
export function Jobs() {
const [jobs, setJobs] = useState<ScrapeJob[]>([])
const [sources, setSources] = useState<Source[]>([])
const [loading, setLoading] = useState(true)
const [triggering, setTriggering] = useState(false)
const [selectedSource, setSelectedSource] = useState('')
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try {
const [j, s] = await Promise.all([adminApi.listJobs(), adminApi.listSources()])
setJobs(j ?? [])
setSources(s ?? [])
if (s?.[0]) setSelectedSource(s[0].id)
} finally { setLoading(false) }
}
async function trigger() {
if (!selectedSource) return
setTriggering(true)
await adminApi.triggerJob(selectedSource)
setTimeout(() => { load(); setTriggering(false) }, 1000)
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold">Jobs de scraping</h1>
<p className="text-muted-foreground text-sm">Historique et déclenchement manuel</p>
</div>
<div className="flex items-center gap-2">
<Select value={selectedSource} onChange={e => setSelectedSource(e.target.value)} className="w-40">
{sources.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</Select>
<Button onClick={trigger} disabled={triggering || !selectedSource}>
{triggering ? <Spinner className="h-4 w-4" /> : <Play className="h-4 w-4" />}
Lancer
</Button>
<Button variant="outline" size="icon" onClick={load}><RefreshCw className="h-4 w-4" /></Button>
</div>
</div>
{loading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : (
<Card>
<CardHeader><CardTitle>Historique</CardTitle></CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b">
<tr className="text-left text-muted-foreground">
<th className="px-4 py-3">Source</th>
<th className="px-4 py-3">Statut</th>
<th className="px-4 py-3">Début</th>
<th className="px-4 py-3">Fin</th>
<th className="px-4 py-3">Articles</th>
<th className="px-4 py-3">Erreur</th>
</tr>
</thead>
<tbody>
{jobs.map(j => (
<tr key={j.id} className="border-b last:border-0 hover:bg-muted/30">
<td className="px-4 py-3 font-medium">{j.source_name}</td>
<td className="px-4 py-3">
<Badge variant={jobStatusVariant(j.status) as 'bullish' | 'bearish' | 'default' | 'outline'}>{j.status}</Badge>
</td>
<td className="px-4 py-3 text-muted-foreground">{fmtDate(j.started_at)}</td>
<td className="px-4 py-3 text-muted-foreground">{fmtDate(j.finished_at)}</td>
<td className="px-4 py-3">{j.articles_found}</td>
<td className="px-4 py-3 text-destructive max-w-xs truncate">{j.error_msg || '—'}</td>
</tr>
))}
{jobs.length === 0 && (
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">Aucun job</td></tr>
)}
</tbody>
</table>
</div>
</CardContent>
</Card>
)}
</div>
)
}

View File

@ -0,0 +1,145 @@
import { useState, useEffect } from 'react'
import { Plus, Trash2, Save } from 'lucide-react'
import { adminApi, type ScheduleSlot } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/spinner'
const DAYS = [
{ label: 'Lundi', short: 'LUN', value: 1 },
{ label: 'Mardi', short: 'MAR', value: 2 },
{ label: 'Mercredi', short: 'MER', value: 3 },
{ label: 'Jeudi', short: 'JEU', value: 4 },
{ label: 'Vendredi', short: 'VEN', value: 5 },
{ label: 'Samedi', short: 'SAM', value: 6 },
{ label: 'Dimanche', short: 'DIM', value: 0 },
]
type SlotKey = `${number}-${number}-${number}`
function toKey(s: ScheduleSlot): SlotKey {
return `${s.day_of_week}-${s.hour}-${s.minute}`
}
function fmt(h: number, m: number) {
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`
}
export function Schedule() {
const [slots, setSlots] = useState<ScheduleSlot[]>([])
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [newTimes, setNewTimes] = useState<Record<number, string>>({})
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try { setSlots((await adminApi.getSchedule()) ?? []) } finally { setLoading(false) }
}
function slotsForDay(day: number) {
return slots
.filter(s => s.day_of_week === day)
.sort((a, b) => a.hour !== b.hour ? a.hour - b.hour : a.minute - b.minute)
}
function addSlot(day: number) {
const time = newTimes[day] || '06:00'
const [h, m] = time.split(':').map(Number)
const newSlot: ScheduleSlot = { day_of_week: day, hour: h, minute: m }
if (slots.some(s => toKey(s) === toKey(newSlot))) return
setSlots(prev => [...prev, newSlot])
setNewTimes(p => ({ ...p, [day]: '06:00' }))
}
function removeSlot(slot: ScheduleSlot) {
setSlots(prev => prev.filter(s => toKey(s) !== toKey(slot)))
}
async function save() {
setSaving(true); setSaved(false)
await adminApi.updateSchedule(slots)
setSaving(false); setSaved(true)
setTimeout(() => setSaved(false), 2000)
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold">Planning hebdomadaire</h1>
<p className="text-muted-foreground text-sm">
Définissez les créneaux de scraping + résumé IA pour chaque jour
</p>
</div>
<Button onClick={save} disabled={saving}>
{saving ? <Spinner className="h-4 w-4" /> : <Save className="h-4 w-4" />}
{saved ? 'Enregistré !' : 'Enregistrer'}
</Button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-7 gap-3">
{DAYS.map(day => {
const daySlots = slotsForDay(day.value)
const isWeekend = day.value === 0 || day.value === 6
return (
<Card key={day.value} className={isWeekend ? 'border-muted' : ''}>
<CardHeader className="pb-2 pt-4 px-4">
<CardTitle className="text-sm font-semibold">
<span className="hidden xl:block">{day.label}</span>
<span className="xl:hidden">{day.short}</span>
</CardTitle>
</CardHeader>
<CardContent className="px-4 pb-4 space-y-2">
{/* Créneaux existants */}
{daySlots.length === 0 && (
<p className="text-xs text-muted-foreground italic">Aucun créneau</p>
)}
{daySlots.map(slot => (
<div
key={toKey(slot)}
className="flex items-center justify-between rounded bg-primary/10 px-2 py-1"
>
<span className="text-sm font-mono font-medium">
{fmt(slot.hour, slot.minute)}
</span>
<button
onClick={() => removeSlot(slot)}
className="text-muted-foreground hover:text-destructive transition-colors ml-2"
>
<Trash2 className="h-3 w-3" />
</button>
</div>
))}
{/* Ajout d'un créneau */}
<div className="flex items-center gap-1 pt-1">
<input
type="time"
value={newTimes[day.value] ?? '06:00'}
onChange={e => setNewTimes(p => ({ ...p, [day.value]: e.target.value }))}
className="flex-1 min-w-0 rounded border border-input bg-background px-2 py-1 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-ring"
/>
<button
onClick={() => addSlot(day.value)}
className="rounded bg-primary/10 p-1 hover:bg-primary/20 transition-colors"
>
<Plus className="h-3 w-3" />
</button>
</div>
</CardContent>
</Card>
)
})}
</div>
<p className="text-xs text-muted-foreground">
À chaque créneau, le service lance le scraping de toutes les sources actives puis génère les résumés IA.
</p>
</div>
)
}

View File

@ -0,0 +1,56 @@
import { useState, useEffect } from 'react'
import { adminApi, type Source } from '@/api/admin'
import { Card, CardContent } from '@/components/ui/card'
import { Spinner } from '@/components/ui/spinner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
export function Sources() {
const [sources, setSources] = useState<Source[]>([])
const [loading, setLoading] = useState(true)
const [toggling, setToggling] = useState<string | null>(null)
useEffect(() => { load() }, [])
async function load() {
setLoading(true)
try { setSources((await adminApi.listSources()) ?? []) } finally { setLoading(false) }
}
async function toggle(s: Source) {
setToggling(s.id)
await adminApi.updateSource(s.id, !s.enabled)
await load()
setToggling(null)
}
if (loading) return <div className="flex justify-center py-20"><Spinner /></div>
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Sources de news</h1>
<p className="text-muted-foreground text-sm">Activez ou désactivez les sources de données</p>
</div>
<div className="space-y-3">
{sources.map(s => (
<Card key={s.id}>
<CardContent className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<span className="font-semibold">{s.name}</span>
<span className="ml-2 text-xs text-muted-foreground capitalize">({s.type})</span>
</div>
<div className="flex items-center gap-2">
<Badge variant={s.enabled ? 'default' : 'outline'}>
{s.enabled ? 'Activée' : 'Désactivée'}
</Badge>
<Button variant="outline" size="sm" onClick={() => toggle(s)} disabled={toggling === s.id}>
{toggling === s.id ? <Spinner className="h-3 w-3" /> : s.enabled ? 'Désactiver' : 'Activer'}
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</div>
)
}

View File

@ -0,0 +1,35 @@
import type { Config } from 'tailwindcss'
export default {
darkMode: ['class'],
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: {
extend: {
fontFamily: {
serif: ['Playfair Display', 'Georgia', 'serif'],
},
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' },
secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' },
destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' },
muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' },
accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' },
card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' },
bullish: '#15803d',
bearish: '#b91c1c',
neutral: '#78716c',
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
},
},
},
plugins: [],
} satisfies Config

21
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"paths": { "@/*": ["./src/*"] }
},
"include": ["src"]
}

45
frontend/vite.config.ts Normal file
View File

@ -0,0 +1,45 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'
import path from 'path'
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.svg', 'icons/*.png'],
manifest: {
name: 'Tradarr',
short_name: 'Tradarr',
description: 'Agrégateur de news financières avec résumés IA',
theme_color: '#0f172a',
background_color: '#0f172a',
display: 'standalone',
start_url: '/',
icons: [
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
],
},
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
runtimeCaching: [
{
urlPattern: /^\/api\//,
handler: 'NetworkFirst',
options: { cacheName: 'api-cache', expiration: { maxEntries: 50, maxAgeSeconds: 300 } },
},
],
},
}),
],
resolve: {
alias: { '@': path.resolve(__dirname, 'src') },
},
server: {
proxy: {
'/api': { target: 'http://localhost:8080', changeOrigin: true },
},
},
})