feat: design system overhaul — sidebar, AI chats, settings, brainstorm, color cleanup
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 12s
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 12s
- Sidebar: dynamic brand-accent colors, brainstorm section restyled - AI chat general: popup panel with expand/collapse, hides when contextual AI open - AI chat contextual: tabs reordered (Actions first), X close button, height fix - Settings: all tabs restyled, 6 new color presets (sage, terracotta, iron, etc.) - Global color cleanup: emerald/orange hardcoded → brand-accent dynamic - Brainstorm page: orange → brand-accent throughout - PageEntry animation component added to key pages - Floating AI button: bg-brand-accent instead of hardcoded black - i18n: all 15 locales updated with new AI/billing keys - Billing: freemium quota tracking, BYOK, stripe subscription scaffolding - Admin: integrated into new design - AGENTS.md + CLAUDE.md project rules added
This commit is contained in:
@@ -174,6 +174,10 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
const [selectedEmbeddingModel, setSelectedEmbeddingModel] = useState<string>(config.AI_MODEL_EMBEDDING || '')
|
||||
const [selectedChatModel, setSelectedChatModel] = useState<string>(config.AI_MODEL_CHAT || '')
|
||||
|
||||
const [tagsFallbackProvider, setTagsFallbackProvider] = useState<string>(config.AI_PROVIDER_TAGS_FALLBACK || '')
|
||||
const [embedFallbackProvider, setEmbedFallbackProvider] = useState<string>(config.AI_PROVIDER_EMBEDDING_FALLBACK || '')
|
||||
const [chatFallbackProvider, setChatFallbackProvider] = useState<string>(config.AI_PROVIDER_CHAT_FALLBACK || '')
|
||||
|
||||
// Dynamic Models State (for local providers with /api/tags or /v1/models endpoints)
|
||||
const [dynamicModels, setDynamicModels] = useState<Record<ModelPurpose, string[]>>({
|
||||
tags: [],
|
||||
@@ -309,6 +313,11 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
const tagsModel = formData.get('AI_MODEL_TAGS') as string
|
||||
if (tagsModel) data.AI_MODEL_TAGS = tagsModel
|
||||
|
||||
const tagsFallbackProv = formData.get('AI_PROVIDER_TAGS_FALLBACK') as string
|
||||
data.AI_PROVIDER_TAGS_FALLBACK = tagsFallbackProv?.trim() ?? ''
|
||||
const tagsFallbackModel = formData.get('AI_MODEL_TAGS_FALLBACK') as string
|
||||
if (tagsFallbackModel) data.AI_MODEL_TAGS_FALLBACK = tagsFallbackModel
|
||||
|
||||
// Save provider-specific config for tags
|
||||
if (tagsProv === 'ollama') {
|
||||
const ollamaUrl = formData.get('BASE_URL_ollama_tags') as string
|
||||
@@ -337,6 +346,11 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
const embedModel = formData.get('AI_MODEL_EMBEDDING') as string
|
||||
if (embedModel) data.AI_MODEL_EMBEDDING = embedModel
|
||||
|
||||
const embedFallbackProv = formData.get('AI_PROVIDER_EMBEDDING_FALLBACK') as string
|
||||
data.AI_PROVIDER_EMBEDDING_FALLBACK = embedFallbackProv?.trim() ?? ''
|
||||
const embedFallbackModel = formData.get('AI_MODEL_EMBEDDING_FALLBACK') as string
|
||||
if (embedFallbackModel) data.AI_MODEL_EMBEDDING_FALLBACK = embedFallbackModel
|
||||
|
||||
// Save provider-specific config for embeddings
|
||||
if (embedProv === 'ollama') {
|
||||
const ollamaUrl = formData.get('BASE_URL_ollama_embeddings') as string
|
||||
@@ -365,6 +379,11 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
const chatModel = formData.get('AI_MODEL_CHAT') as string
|
||||
if (chatModel) data.AI_MODEL_CHAT = chatModel
|
||||
|
||||
const chatFallbackProv = formData.get('AI_PROVIDER_CHAT_FALLBACK') as string
|
||||
data.AI_PROVIDER_CHAT_FALLBACK = chatFallbackProv?.trim() ?? ''
|
||||
const chatFallbackModel = formData.get('AI_MODEL_CHAT_FALLBACK') as string
|
||||
if (chatFallbackModel) data.AI_MODEL_CHAT_FALLBACK = chatFallbackModel
|
||||
|
||||
// Save provider-specific config for chat
|
||||
if (chatProv === 'ollama') {
|
||||
const ollamaUrl = formData.get('BASE_URL_ollama_chat') as string
|
||||
@@ -717,6 +736,33 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
|
||||
<input type="hidden" name="AI_MODEL_TAGS" value={selectedTagsModel} />
|
||||
{renderProviderConfig(tagsProvider, 'tags', selectedTagsModel, setSelectedTagsModel)}
|
||||
|
||||
<div className="space-y-2 pt-3 border-t border-border/40">
|
||||
<p className="text-xs font-medium text-muted-foreground">{t('admin.ai.fallbackSectionTitle')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('admin.ai.fallbackSectionDescription')}</p>
|
||||
<Label htmlFor="AI_PROVIDER_TAGS_FALLBACK">{t('admin.ai.fallbackProvider')}</Label>
|
||||
<select
|
||||
id="AI_PROVIDER_TAGS_FALLBACK"
|
||||
name="AI_PROVIDER_TAGS_FALLBACK"
|
||||
value={tagsFallbackProvider}
|
||||
onChange={(e) => setTagsFallbackProvider(e.target.value)}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">{t('admin.ai.fallbackNone')}</option>
|
||||
{providerOptions.map((opt) => (
|
||||
<option key={`fb-tags-${opt.value}`} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Label htmlFor="AI_MODEL_TAGS_FALLBACK">{t('admin.ai.fallbackModel')}</Label>
|
||||
<Input
|
||||
id="AI_MODEL_TAGS_FALLBACK"
|
||||
name="AI_MODEL_TAGS_FALLBACK"
|
||||
defaultValue={config.AI_MODEL_TAGS_FALLBACK || ''}
|
||||
placeholder={t('admin.ai.fallbackModelPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Embeddings Provider */}
|
||||
@@ -752,6 +798,33 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
|
||||
<input type="hidden" name="AI_MODEL_EMBEDDING" value={selectedEmbeddingModel} />
|
||||
{renderProviderConfig(embeddingsProvider, 'embeddings', selectedEmbeddingModel, setSelectedEmbeddingModel)}
|
||||
|
||||
<div className="space-y-2 pt-3 border-t border-border/40">
|
||||
<p className="text-xs font-medium text-muted-foreground">{t('admin.ai.fallbackSectionTitle')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('admin.ai.fallbackSectionDescription')}</p>
|
||||
<Label htmlFor="AI_PROVIDER_EMBEDDING_FALLBACK">{t('admin.ai.fallbackProvider')}</Label>
|
||||
<select
|
||||
id="AI_PROVIDER_EMBEDDING_FALLBACK"
|
||||
name="AI_PROVIDER_EMBEDDING_FALLBACK"
|
||||
value={embedFallbackProvider}
|
||||
onChange={(e) => setEmbedFallbackProvider(e.target.value)}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">{t('admin.ai.fallbackNone')}</option>
|
||||
{embeddingsProviderOptions.map((opt) => (
|
||||
<option key={`fb-embed-${opt.value}`} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Label htmlFor="AI_MODEL_EMBEDDING_FALLBACK">{t('admin.ai.fallbackModel')}</Label>
|
||||
<Input
|
||||
id="AI_MODEL_EMBEDDING_FALLBACK"
|
||||
name="AI_MODEL_EMBEDDING_FALLBACK"
|
||||
defaultValue={config.AI_MODEL_EMBEDDING_FALLBACK || ''}
|
||||
placeholder={t('admin.ai.fallbackModelPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chat Provider */}
|
||||
@@ -782,6 +855,33 @@ export function AdminSettingsForm({ config }: { config: Record<string, string> }
|
||||
|
||||
<input type="hidden" name="AI_MODEL_CHAT" value={selectedChatModel} />
|
||||
{renderProviderConfig(chatProvider, 'chat', selectedChatModel, setSelectedChatModel)}
|
||||
|
||||
<div className="space-y-2 pt-3 border-t border-border/40">
|
||||
<p className="text-xs font-medium text-muted-foreground">{t('admin.ai.fallbackSectionTitle')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('admin.ai.fallbackSectionDescription')}</p>
|
||||
<Label htmlFor="AI_PROVIDER_CHAT_FALLBACK">{t('admin.ai.fallbackProvider')}</Label>
|
||||
<select
|
||||
id="AI_PROVIDER_CHAT_FALLBACK"
|
||||
name="AI_PROVIDER_CHAT_FALLBACK"
|
||||
value={chatFallbackProvider}
|
||||
onChange={(e) => setChatFallbackProvider(e.target.value)}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">{t('admin.ai.fallbackNone')}</option>
|
||||
{providerOptions.map((opt) => (
|
||||
<option key={`fb-chat-${opt.value}`} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Label htmlFor="AI_MODEL_CHAT_FALLBACK">{t('admin.ai.fallbackModel')}</Label>
|
||||
<Input
|
||||
id="AI_MODEL_CHAT_FALLBACK"
|
||||
name="AI_MODEL_CHAT_FALLBACK"
|
||||
defaultValue={config.AI_MODEL_CHAT_FALLBACK || ''}
|
||||
placeholder={t('admin.ai.fallbackModelPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-6 pb-6 flex flex-col sm:flex-row gap-3 sm:justify-between pt-6">
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useCallback, useMemo, useEffect, useRef } from 'react'
|
||||
import { motion } from 'motion/react'
|
||||
import { PageEntry } from '@/components/page-entry'
|
||||
import { Plus, Bot, Search, LifeBuoy } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
@@ -204,6 +205,7 @@ export function AgentsPageClient({
|
||||
const showDetail = selectedAgent !== null || isNewAgent
|
||||
|
||||
return (
|
||||
<PageEntry>
|
||||
<>
|
||||
{showDetail ? (
|
||||
<AgentDetailView
|
||||
@@ -332,5 +334,6 @@ export function AgentsPageClient({
|
||||
<AgentHelp onClose={() => setShowHelp(false)} />
|
||||
)}
|
||||
</>
|
||||
</PageEntry>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { detectUserLanguage, parseAcceptLanguage } from "@/lib/i18n/detect-user-
|
||||
import { loadTranslations } from "@/lib/i18n/load-translations";
|
||||
import { getAISettings } from "@/app/actions/ai-settings";
|
||||
import { AIChatLayoutBridge } from "@/components/ai-chat-layout-bridge";
|
||||
import { PageTransition } from "@/components/page-transition";
|
||||
|
||||
export default async function MainLayout({
|
||||
children,
|
||||
@@ -37,7 +38,9 @@ export default async function MainLayout({
|
||||
</Suspense>
|
||||
|
||||
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-smooth bg-memento-paper dark:bg-background">
|
||||
{children}
|
||||
<PageTransition>
|
||||
{children}
|
||||
</PageTransition>
|
||||
</main>
|
||||
|
||||
{showAIAssistant && <AIChatLayoutBridge />}
|
||||
|
||||
@@ -6,8 +6,8 @@ export function AISettingsHeader() {
|
||||
const { t } = useLanguage()
|
||||
|
||||
return (
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
<h3 className="text-[10px] font-bold uppercase tracking-[0.4em] text-concrete opacity-60">
|
||||
{t('aiSettings.description')}
|
||||
</p>
|
||||
</h3>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { auth } from '@/auth'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { AISettingsPanel } from '@/components/ai/ai-settings-panel'
|
||||
import { ByokSettingsPanel } from '@/components/ai/byok-settings-panel'
|
||||
import { getAISettings } from '@/app/actions/ai-settings'
|
||||
import { AISettingsHeader } from './ai-settings-header'
|
||||
|
||||
@@ -17,6 +18,7 @@ export default async function AISettingsPage() {
|
||||
<div className="space-y-6">
|
||||
<AISettingsHeader />
|
||||
<AISettingsPanel initialSettings={settings} />
|
||||
<ByokSettingsPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,28 +1,54 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { updateAISettings } from '@/app/actions/ai-settings'
|
||||
import { updateUserSettings } from '@/app/actions/user-settings'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { toast } from 'sonner'
|
||||
import { Palette, Type } from 'lucide-react'
|
||||
import { Palette, Type, LayoutGrid, Maximize } from 'lucide-react'
|
||||
import { applyDocumentTheme, normalizeThemeId, type ThemeId } from '@/lib/apply-document-theme'
|
||||
import { motion } from 'motion/react'
|
||||
|
||||
const PRESET_COLORS = [
|
||||
{ name: 'Warm Earth', value: '#A47148' },
|
||||
{ name: 'Sage', value: '#4E594A' },
|
||||
{ name: 'Terracotta', value: '#B1523E' },
|
||||
{ name: 'Iron', value: '#4A5568' },
|
||||
{ name: 'Charcoal', value: '#1E293B' },
|
||||
{ name: 'Slate', value: '#475569' },
|
||||
{ name: 'Olive', value: '#7C8363' },
|
||||
{ name: 'Wine', value: '#722F37' },
|
||||
]
|
||||
|
||||
interface AppearanceSettingsClientProps {
|
||||
initialFontSize: string
|
||||
initialTheme: string
|
||||
initialFontFamily?: string
|
||||
initialAccentColor?: string
|
||||
}
|
||||
|
||||
export function AppearanceSettingsClient({
|
||||
initialFontSize,
|
||||
initialTheme,
|
||||
initialFontFamily = 'inter',
|
||||
initialAccentColor = '#A47148',
|
||||
}: AppearanceSettingsClientProps) {
|
||||
const { t } = useLanguage()
|
||||
const [theme, setTheme] = useState<ThemeId>(normalizeThemeId(initialTheme || 'light'))
|
||||
const [fontSize, setFontSize] = useState(initialFontSize || 'medium')
|
||||
const [fontFamily, setFontFamily] = useState(initialFontFamily)
|
||||
const [accentColor, setAccentColor] = useState(initialAccentColor)
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.style.setProperty('--color-brand-accent', accentColor)
|
||||
}, [accentColor])
|
||||
|
||||
const handleAccentColorChange = async (color: string) => {
|
||||
setAccentColor(color)
|
||||
document.documentElement.style.setProperty('--color-brand-accent', color)
|
||||
localStorage.setItem('accent-color', color)
|
||||
await updateUserSettings({ accentColor: color })
|
||||
}
|
||||
|
||||
const handleThemeChange = async (value: string) => {
|
||||
const next = normalizeThemeId(value)
|
||||
@@ -74,21 +100,21 @@ export function AppearanceSettingsClient({
|
||||
optionGroups?: { label: string; options: { value: string; label: string }[] }[]
|
||||
onChange: (v: string) => void
|
||||
}) => (
|
||||
<div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
|
||||
<div className="bg-white/40 dark:bg-white/5 border border-border rounded-2xl p-8 space-y-8 group transition-all duration-300 hover:shadow-xl hover:shadow-slate/5">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-paper dark:bg-white/10 rounded-2xl text-slate border border-border group-hover:scale-110 transition-transform duration-300">
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">{title}</h3>
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
<div className="space-y-0.5 text-left">
|
||||
<h4 className="text-base font-bold text-foreground">{title}</h4>
|
||||
<p className="text-[11px] text-muted-foreground leading-tight">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-2">
|
||||
<div className="relative group/select">
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="w-full h-11 px-4 bg-muted border border-border rounded-lg text-foreground text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none appearance-none cursor-pointer transition-colors"
|
||||
className="w-full bg-white/50 dark:bg-black/40 border border-border rounded-xl px-5 py-4 text-sm outline-none focus:ring-1 ring-slate/20 appearance-none cursor-pointer text-foreground font-bold transition-all hover:bg-white dark:hover:bg-black/60"
|
||||
>
|
||||
{optionGroups
|
||||
? optionGroups.map((g) => (
|
||||
@@ -106,9 +132,9 @@ export function AppearanceSettingsClient({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-muted-foreground">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
<div className="absolute right-5 top-1/2 -translate-y-1/2 pointer-events-none text-muted-foreground group-hover/select:text-foreground transition-colors">
|
||||
<svg width="10" height="6" viewBox="0 0 10 6" fill="none">
|
||||
<path d="M1 1L5 5L9 1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
@@ -141,52 +167,116 @@ export function AppearanceSettingsClient({
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Section label — architectural style */}
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
{t('appearance.description') || "Personnalisez l'interface"}
|
||||
</p>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="space-y-16 pb-20"
|
||||
>
|
||||
<div className="space-y-10">
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
{t('appearance.description') || "Personnalisez l'interface"}
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<SelectCard
|
||||
icon={Palette}
|
||||
title={t('settings.theme')}
|
||||
description={t('appearance.selectTheme')}
|
||||
value={theme}
|
||||
optionGroups={themeOptionGroups}
|
||||
onChange={handleThemeChange}
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* Accent Color Section */}
|
||||
<div className="md:col-span-2 bg-white/40 dark:bg-white/5 border border-border rounded-3xl p-10 space-y-8 group transition-all duration-300 hover:shadow-xl hover:shadow-brand-accent/5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-paper dark:bg-white/10 rounded-2xl border border-border group-hover:scale-110 transition-transform duration-300 shadow-sm" style={{ color: accentColor }}>
|
||||
<Palette size={20} />
|
||||
</div>
|
||||
<div className="space-y-0.5 text-left">
|
||||
<h4 className="text-base font-bold text-foreground">{t('appearance.accentColorTitle') || 'Couleur d\'accentuation'}</h4>
|
||||
<p className="text-[11px] text-muted-foreground leading-tight">{t('appearance.accentColorDescription') || 'Définissez la couleur principale de votre espace de travail'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 bg-slate-50 dark:bg-black/20 px-4 py-2 rounded-xl border border-border/40">
|
||||
<div className="w-4 h-4 rounded-full border border-border/60" style={{ backgroundColor: accentColor }} />
|
||||
<span className="text-xs font-mono font-medium text-muted-foreground uppercase tracking-widest">{accentColor}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SelectCard
|
||||
icon={Type}
|
||||
title={t('profile.fontSize')}
|
||||
description={t('profile.fontSizeDescription')}
|
||||
value={fontSize}
|
||||
options={[
|
||||
{ value: 'small', label: t('profile.fontSizeSmall') },
|
||||
{ value: 'medium', label: t('profile.fontSizeMedium') },
|
||||
{ value: 'large', label: t('profile.fontSizeLarge') },
|
||||
{ value: 'extra-large', label: t('profile.fontSizeExtraLarge') },
|
||||
]}
|
||||
onChange={handleFontSizeChange}
|
||||
/>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{PRESET_COLORS.map((color) => (
|
||||
<button
|
||||
key={color.value}
|
||||
onClick={() => handleAccentColorChange(color.value)}
|
||||
className={`relative w-12 h-12 rounded-2xl transition-all duration-300 hover:scale-110 flex items-center justify-center p-1 border-2 ${
|
||||
accentColor.toLowerCase() === color.value.toLowerCase()
|
||||
? 'border-foreground shadow-lg'
|
||||
: 'border-transparent hover:border-muted-foreground/20'
|
||||
}`}
|
||||
title={color.name}
|
||||
>
|
||||
<div
|
||||
className="w-full h-full rounded-xl shadow-inner"
|
||||
style={{ backgroundColor: color.value }}
|
||||
/>
|
||||
{accentColor.toLowerCase() === color.value.toLowerCase() && (
|
||||
<motion.div
|
||||
layoutId="color-check"
|
||||
className="absolute inset-0 flex items-center justify-center text-white mix-blend-difference"
|
||||
>
|
||||
<Palette size={14} />
|
||||
</motion.div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
|
||||
<SelectCard
|
||||
icon={Type}
|
||||
title={t('appearance.fontFamilyLabel') || 'Police'}
|
||||
description={t('appearance.fontFamilyDescription') || "Choisissez la police de l'application"}
|
||||
value={fontFamily}
|
||||
options={[
|
||||
{ value: 'inter', label: 'Inter (défaut)' },
|
||||
{ value: 'playfair', label: 'Playfair Display' },
|
||||
{ value: 'jetbrains', label: 'JetBrains Mono' },
|
||||
{ value: 'system', label: t('appearance.fontSystem') || 'Système' },
|
||||
]}
|
||||
onChange={handleFontFamilyChange}
|
||||
/>
|
||||
<div className="h-12 w-px bg-border/40 mx-2" />
|
||||
|
||||
<div className="relative group/custom">
|
||||
<input
|
||||
type="color"
|
||||
value={accentColor}
|
||||
onChange={(e) => handleAccentColorChange(e.target.value)}
|
||||
className="w-12 h-12 rounded-2xl cursor-pointer opacity-0 absolute inset-0 z-10"
|
||||
/>
|
||||
<div className="w-12 h-12 rounded-2xl border-2 border-dashed border-muted-foreground/30 flex items-center justify-center text-muted-foreground transition-all group-hover/custom:border-foreground group-hover/custom:text-foreground">
|
||||
<Maximize size={16} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SelectCard
|
||||
icon={Palette}
|
||||
title={t('settings.theme')}
|
||||
description={t('appearance.selectTheme')}
|
||||
value={theme}
|
||||
optionGroups={themeOptionGroups}
|
||||
onChange={handleThemeChange}
|
||||
/>
|
||||
|
||||
<SelectCard
|
||||
icon={Type}
|
||||
title={t('profile.fontSize')}
|
||||
description={t('profile.fontSizeDescription')}
|
||||
value={fontSize}
|
||||
options={[
|
||||
{ value: 'small', label: t('profile.fontSizeSmall') },
|
||||
{ value: 'medium', label: t('profile.fontSizeMedium') },
|
||||
{ value: 'large', label: t('profile.fontSizeLarge') },
|
||||
{ value: 'extra-large', label: t('profile.fontSizeExtraLarge') },
|
||||
]}
|
||||
onChange={handleFontSizeChange}
|
||||
/>
|
||||
|
||||
<SelectCard
|
||||
icon={Type}
|
||||
title={t('appearance.fontFamilyLabel') || 'Police'}
|
||||
description={t('appearance.fontFamilyDescription') || "Choisissez la police de l'application"}
|
||||
value={fontFamily}
|
||||
options={[
|
||||
{ value: 'inter', label: t('appearance.fontInterDefault') },
|
||||
{ value: 'playfair', label: t('appearance.fontPlayfairDisplay') },
|
||||
{ value: 'jetbrains', label: t('appearance.fontJetBrainsMono') },
|
||||
{ value: 'system', label: t('appearance.fontSystem') || 'Système' },
|
||||
]}
|
||||
onChange={handleFontFamilyChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export default async function AppearanceSettingsPage() {
|
||||
initialFontSize={aiSettings.fontSize}
|
||||
initialTheme={userSettings.theme}
|
||||
initialFontFamily={aiSettings.fontFamily || 'inter'}
|
||||
initialAccentColor={userSettings.accentColor || '#A47148'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
23
memento-note/app/(main)/settings/billing/page.tsx
Normal file
23
memento-note/app/(main)/settings/billing/page.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Suspense } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { BillingPlans } from '@/components/settings/billing-plans';
|
||||
|
||||
export const metadata = {
|
||||
title: 'Billing',
|
||||
};
|
||||
|
||||
function Fallback() {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function BillingPage() {
|
||||
return (
|
||||
<Suspense fallback={<Fallback />}>
|
||||
<BillingPlans />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Download, Upload, Trash2, Loader2, RefreshCw, Sparkles, Database } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { motion } from 'motion/react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export default function DataSettingsPage() {
|
||||
const { t } = useLanguage()
|
||||
@@ -117,114 +118,134 @@ export default function DataSettingsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const cards = [
|
||||
{
|
||||
icon: Download,
|
||||
iconColor: 'text-zinc-600 dark:text-zinc-400',
|
||||
iconBg: 'bg-zinc-500/10 dark:bg-zinc-500/20',
|
||||
title: t('dataManagement.export.title'),
|
||||
description: t('dataManagement.export.description'),
|
||||
loading: isExporting,
|
||||
loadingText: t('dataManagement.exporting'),
|
||||
buttonText: t('dataManagement.export.button'),
|
||||
onAction: handleExport,
|
||||
btnClass: 'bg-ink text-paper shadow-xl shadow-ink/20 hover:scale-[1.02] active:scale-95',
|
||||
},
|
||||
{
|
||||
icon: Upload,
|
||||
iconColor: 'text-emerald-600 dark:text-emerald-400',
|
||||
iconBg: 'bg-emerald-500/10 dark:bg-emerald-500/20',
|
||||
title: t('dataManagement.import.title'),
|
||||
description: t('dataManagement.import.description'),
|
||||
loading: isImporting,
|
||||
loadingText: t('dataManagement.importing'),
|
||||
buttonText: t('dataManagement.import.button'),
|
||||
onAction: () => document.getElementById('import-file')?.click(),
|
||||
btnClass: 'bg-white dark:bg-white/10 text-ink dark:text-paper border border-border hover:scale-[1.02] active:scale-95',
|
||||
fileInput: true,
|
||||
},
|
||||
{
|
||||
icon: Sparkles,
|
||||
iconColor: 'text-amber-600 dark:text-amber-400',
|
||||
iconBg: 'bg-amber-500/10 dark:bg-amber-500/20',
|
||||
title: t('dataManagement.indexing.title'),
|
||||
description: t('dataManagement.indexing.description'),
|
||||
loading: isReindexing,
|
||||
loadingText: t('dataManagement.exporting'),
|
||||
buttonText: t('dataManagement.indexing.button'),
|
||||
onAction: handleReindex,
|
||||
btnClass: 'bg-white dark:bg-white/10 text-ink dark:text-paper border border-border hover:scale-[1.02] active:scale-95',
|
||||
},
|
||||
{
|
||||
icon: Database,
|
||||
iconColor: 'text-purple-600 dark:text-purple-400',
|
||||
iconBg: 'bg-purple-500/10 dark:bg-purple-500/20',
|
||||
title: t('dataManagement.cleanup.title'),
|
||||
description: t('dataManagement.cleanup.description'),
|
||||
loading: isCleaningUp,
|
||||
loadingText: t('dataManagement.exporting'),
|
||||
buttonText: t('dataManagement.cleanup.button'),
|
||||
onAction: handleCleanup,
|
||||
btnClass: 'bg-white dark:bg-white/10 text-ink dark:text-paper border border-border hover:scale-[1.02] active:scale-95',
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="space-y-12"
|
||||
>
|
||||
<h3 className="text-[10px] font-bold uppercase tracking-[0.3em] text-concrete">
|
||||
{t('dataManagement.toolsDescription')}
|
||||
</p>
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Export card */}
|
||||
<div className="bg-card rounded-xl border border-border p-6 shadow-sm flex flex-col justify-between transition-all hover:shadow-md">
|
||||
<div className="space-y-4">
|
||||
<div className="w-12 h-12 rounded-full bg-zinc-500/10 flex items-center justify-center text-zinc-600 shrink-0">
|
||||
<Download className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-foreground">{t('dataManagement.export.title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 leading-relaxed">
|
||||
{t('dataManagement.export.description')}
|
||||
</p>
|
||||
{cards.map((card) => (
|
||||
<div
|
||||
key={card.title}
|
||||
className="bg-white/40 dark:bg-white/5 border border-border rounded-2xl p-8 flex flex-col justify-between group hover:shadow-xl hover:shadow-black/5 transition-all duration-300"
|
||||
>
|
||||
<div className="space-y-6">
|
||||
<div className={cn('w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 border border-border/50', card.iconBg, card.iconColor)}>
|
||||
<card.icon className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-sm font-bold text-ink">{card.title}</h4>
|
||||
<p className="text-[11px] text-concrete leading-relaxed mt-1.5">
|
||||
{card.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{card.fileInput && (
|
||||
<input type="file" accept=".json" onChange={handleImport} disabled={isImporting} className="hidden" id="import-file" />
|
||||
)}
|
||||
<button
|
||||
onClick={card.onAction}
|
||||
disabled={card.loading}
|
||||
className={cn(
|
||||
'mt-8 w-full py-3.5 rounded-2xl text-[10px] font-bold uppercase tracking-[0.2em] transition-all duration-300',
|
||||
card.btnClass,
|
||||
'disabled:opacity-60 disabled:pointer-events-none'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{card.loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <card.icon className="h-4 w-4" />}
|
||||
{card.loading ? card.loadingText : card.buttonText}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
<Button onClick={handleExport} disabled={isExporting} className="mt-6 w-full">
|
||||
{isExporting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Download className="h-4 w-4 mr-2" />}
|
||||
{isExporting ? t('dataManagement.exporting') : t('dataManagement.export.button')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import card */}
|
||||
<div className="bg-card rounded-xl border border-border p-6 shadow-sm flex flex-col justify-between transition-all hover:shadow-md">
|
||||
<div className="space-y-4">
|
||||
<div className="w-12 h-12 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 shrink-0">
|
||||
<Upload className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-foreground">{t('dataManagement.import.title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 leading-relaxed">
|
||||
{t('dataManagement.import.description')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<input type="file" accept=".json" onChange={handleImport} disabled={isImporting} className="hidden" id="import-file" />
|
||||
<Button onClick={() => document.getElementById('import-file')?.click()} disabled={isImporting} variant="outline" className="mt-6 w-full">
|
||||
{isImporting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Upload className="h-4 w-4 mr-2" />}
|
||||
{isImporting ? t('dataManagement.importing') : t('dataManagement.import.button')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Reindex card */}
|
||||
<div className="bg-card rounded-xl border border-border p-6 shadow-sm flex flex-col justify-between transition-all hover:shadow-md">
|
||||
<div className="space-y-4">
|
||||
<div className="w-12 h-12 rounded-full bg-amber-500/10 flex items-center justify-center text-amber-600 shrink-0">
|
||||
<Sparkles className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-foreground">{t('dataManagement.indexing.title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 leading-relaxed">
|
||||
{t('dataManagement.indexing.description')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={handleReindex} disabled={isReindexing} variant="secondary" className="mt-6 w-full">
|
||||
{isReindexing ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <RefreshCw className="h-4 w-4 mr-2" />}
|
||||
{isReindexing ? t('dataManagement.exporting') : t('dataManagement.indexing.button')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Cleanup card */}
|
||||
<div className="bg-card rounded-xl border border-border p-6 shadow-sm flex flex-col justify-between transition-all hover:shadow-md">
|
||||
<div className="space-y-4">
|
||||
<div className="w-12 h-12 rounded-full bg-purple-500/10 flex items-center justify-center text-purple-600 shrink-0">
|
||||
<Database className="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-foreground">{t('dataManagement.cleanup.title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 leading-relaxed">
|
||||
{t('dataManagement.cleanup.description')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={handleCleanup} disabled={isCleaningUp} variant="secondary" className="mt-6 w-full">
|
||||
{isCleaningUp ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Database className="h-4 w-4 mr-2" />}
|
||||
{isCleaningUp ? t('dataManagement.exporting') : t('dataManagement.cleanup.button')}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Danger zone */}
|
||||
<div className="bg-destructive/5 rounded-xl border border-destructive/20 p-6 shadow-sm mt-12">
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<div className="w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center text-destructive shrink-0">
|
||||
<Trash2 className="h-6 w-6" />
|
||||
<div className="bg-rose-50/50 dark:bg-rose-500/5 rounded-2xl border border-rose-200/50 dark:border-rose-500/20 p-8 mt-12">
|
||||
<div className="flex items-center gap-5 mb-8">
|
||||
<div className="p-3 bg-rose-500/10 rounded-2xl text-rose-600 dark:text-rose-400 border border-rose-500/20">
|
||||
<Trash2 size={20} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-destructive">{t('dataManagement.dangerZone')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('dataManagement.dangerZoneDescription')}</p>
|
||||
<h4 className="text-sm font-bold text-rose-600 dark:text-rose-400">{t('dataManagement.dangerZone')}</h4>
|
||||
<p className="text-[11px] text-concrete mt-0.5">{t('dataManagement.dangerZoneDescription')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-background/50 rounded-lg border border-destructive/10 gap-4">
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-6 bg-white/60 dark:bg-black/20 rounded-2xl border border-rose-200/30 dark:border-rose-500/10 gap-4">
|
||||
<div className="space-y-1">
|
||||
<p className="font-semibold text-destructive">{t('dataManagement.delete.title')}</p>
|
||||
<p className="text-sm text-muted-foreground">{t('dataManagement.delete.description')}</p>
|
||||
<p className="text-[13px] font-bold text-ink">{t('dataManagement.delete.title')}</p>
|
||||
<p className="text-[11px] text-concrete">{t('dataManagement.delete.description')}</p>
|
||||
</div>
|
||||
<Button variant="destructive" onClick={handleDeleteAll} disabled={isDeleting} className="shrink-0 w-full sm:w-auto">
|
||||
{isDeleting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
|
||||
{isDeleting ? t('dataManagement.deleting') : t('dataManagement.delete.button')}
|
||||
</Button>
|
||||
<button
|
||||
onClick={handleDeleteAll}
|
||||
disabled={isDeleting}
|
||||
className="shrink-0 px-6 py-3 rounded-2xl bg-rose-600 text-white text-[10px] font-bold uppercase tracking-[0.2em] shadow-xl shadow-rose-600/20 hover:scale-[1.02] active:scale-95 transition-all duration-300 disabled:opacity-60 disabled:pointer-events-none"
|
||||
>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{isDeleting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
|
||||
{isDeleting ? t('dataManagement.deleting') : t('dataManagement.delete.button')}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import { updateAISettings } from '@/app/actions/ai-settings'
|
||||
import { toast } from 'sonner'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Globe, Bell } from 'lucide-react'
|
||||
import { motion } from 'motion/react'
|
||||
import { PageEntry } from '@/components/page-entry'
|
||||
|
||||
interface GeneralSettingsClientProps {
|
||||
initialSettings: {
|
||||
@@ -51,7 +53,7 @@ export function GeneralSettingsClient({ initialSettings }: GeneralSettingsClient
|
||||
await updateAISettings({ desktopNotifications: enabled })
|
||||
toast.success(t('settings.settingsSaved') || 'Saved')
|
||||
}
|
||||
|
||||
|
||||
const handleAutoSaveChange = async (enabled: boolean) => {
|
||||
setAutoSave(enabled)
|
||||
await updateAISettings({ autoSave: enabled })
|
||||
@@ -59,29 +61,32 @@ export function GeneralSettingsClient({ initialSettings }: GeneralSettingsClient
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="space-y-12"
|
||||
>
|
||||
<h3 className="text-[10px] font-bold uppercase tracking-[0.3em] text-concrete">
|
||||
{t('generalSettings.description')}
|
||||
</p>
|
||||
</h3>
|
||||
|
||||
{/* 2-column card grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Language card */}
|
||||
<div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
|
||||
<Globe className="h-5 w-5" />
|
||||
<div className="bg-white/40 dark:bg-white/5 border border-border rounded-xl p-8 space-y-6">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-paper dark:bg-white/10 rounded-2xl text-concrete border border-border">
|
||||
<Globe size={18} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">{t('settings.language')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('settings.selectLanguage')}</p>
|
||||
<div className="space-y-0.5">
|
||||
<h4 className="text-base font-bold text-ink">{t('settings.language')}</h4>
|
||||
<p className="text-[11px] text-concrete">{t('settings.selectLanguage')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-2">
|
||||
|
||||
<div className="relative group">
|
||||
<select
|
||||
value={language}
|
||||
onChange={(e) => handleLanguageChange(e.target.value)}
|
||||
className="w-full h-11 px-4 bg-muted border border-border rounded-lg text-foreground text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none appearance-none cursor-pointer transition-colors"
|
||||
className="w-full bg-white/50 dark:bg-black/40 border border-border rounded-xl px-5 py-3.5 text-sm outline-none focus:ring-1 ring-brand-accent/20 appearance-none cursor-pointer transition-all hover:bg-white dark:hover:bg-black/60 text-ink font-medium"
|
||||
>
|
||||
<option value="auto">{t('profile.autoDetect')}</option>
|
||||
<option value="en">English</option>
|
||||
@@ -100,75 +105,76 @@ export function GeneralSettingsClient({ initialSettings }: GeneralSettingsClient
|
||||
<option value="nl">Nederlands</option>
|
||||
<option value="pl">Polski</option>
|
||||
</select>
|
||||
<div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none text-muted-foreground">
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
|
||||
<div className="absolute right-5 top-1/2 -translate-y-1/2 pointer-events-none opacity-40 text-concrete">
|
||||
<svg width="10" height="6" viewBox="0 0 10 6" fill="none">
|
||||
<path d="M1 1L5 5L9 1" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Notifications card */}
|
||||
<div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
|
||||
<Bell className="h-5 w-5" />
|
||||
<div className="bg-white/40 dark:bg-white/5 border border-border rounded-xl p-8 space-y-6">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="p-3 bg-paper dark:bg-white/10 rounded-2xl text-concrete border border-border">
|
||||
<Bell size={18} />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">{t('settings.notifications')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('settings.notificationsDesc')}</p>
|
||||
<div className="space-y-0.5">
|
||||
<h4 className="text-base font-bold text-ink">{t('settings.notifications')}</h4>
|
||||
<p className="text-[11px] text-concrete">{t('settings.notificationsDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 space-y-5">
|
||||
{/* Email toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">{t('settings.emailNotifications')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('settings.emailNotificationsDesc')}</p>
|
||||
|
||||
<div className="space-y-6 divide-y divide-border/40 text-left">
|
||||
<div className="flex items-center justify-between pt-0">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-bold text-ink">{t('settings.emailNotifications')}</p>
|
||||
<p className="text-[10px] text-concrete leading-relaxed">{t('settings.emailNotificationsDesc')}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={emailNotifications}
|
||||
onClick={() => handleEmailNotificationsChange(!emailNotifications)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary/30 ${emailNotifications ? 'bg-primary' : 'bg-muted-foreground/30'}`}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${emailNotifications ? 'translate-x-6' : 'translate-x-1'}`} />
|
||||
</button>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="sr-only peer"
|
||||
checked={emailNotifications}
|
||||
onChange={(e) => handleEmailNotificationsChange(e.target.checked)}
|
||||
/>
|
||||
<div className="w-11 h-6 bg-gray-200 dark:bg-white/10 rounded-full peer peer-checked:after:translate-x-[20px] peer-checked:after:border-white after:content-[''] after:absolute after:top-[4px] after:left-[4px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all duration-300 ease-in-out peer-checked:bg-ink" />
|
||||
</label>
|
||||
</div>
|
||||
{/* Desktop toggle */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">{t('settings.desktopNotifications')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('settings.desktopNotificationsDesc')}</p>
|
||||
|
||||
<div className="flex items-center justify-between pt-6">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-bold text-ink">{t('settings.desktopNotifications')}</p>
|
||||
<p className="text-[10px] text-concrete leading-relaxed">{t('settings.desktopNotificationsDesc')}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={desktopNotifications}
|
||||
onClick={() => handleDesktopNotificationsChange(!desktopNotifications)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary/30 ${desktopNotifications ? 'bg-primary' : 'bg-muted-foreground/30'}`}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${desktopNotifications ? 'translate-x-6' : 'translate-x-1'}`} />
|
||||
</button>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="sr-only peer"
|
||||
checked={desktopNotifications}
|
||||
onChange={(e) => handleDesktopNotificationsChange(e.target.checked)}
|
||||
/>
|
||||
<div className="w-11 h-6 bg-gray-200 dark:bg-white/10 rounded-full peer peer-checked:after:translate-x-[20px] peer-checked:after:border-white after:content-[''] after:absolute after:top-[4px] after:left-[4px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all duration-300 ease-in-out peer-checked:bg-ink" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-5 flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">{t('settings.autoSave') || 'Auto-Save'}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('settings.autoSaveDesc') || 'Sauvegarder automatiquement les modifications'}</p>
|
||||
|
||||
<div className="flex items-center justify-between pt-6">
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-bold text-ink">{t('settings.autoSave') || 'Auto-Save'}</p>
|
||||
<p className="text-[10px] text-concrete leading-relaxed">{t('settings.autoSaveDesc') || 'Sauvegarder automatiquement les modifications'}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={autoSave}
|
||||
onClick={() => handleAutoSaveChange(!autoSave)}
|
||||
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary/30 ${autoSave ? 'bg-primary' : 'bg-muted-foreground/30'}`}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${autoSave ? 'translate-x-6' : 'translate-x-1'}`} />
|
||||
</button>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="sr-only peer"
|
||||
checked={autoSave}
|
||||
onChange={(e) => handleAutoSaveChange(e.target.checked)}
|
||||
/>
|
||||
<div className="w-11 h-6 bg-gray-200 dark:bg-white/10 rounded-full peer peer-checked:after:translate-x-[20px] peer-checked:after:border-white after:content-[''] after:absolute after:top-[4px] after:left-[4px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all duration-300 ease-in-out peer-checked:bg-ink" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,24 +8,20 @@ export default function SettingsLayout({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-[#F2F0E9]">
|
||||
{/* Architectural header — matches Agents page */}
|
||||
<header className="flex flex-col px-12 pt-10 pb-0 border-b border-border/40 shrink-0">
|
||||
<div className="flex items-end justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="font-memento-serif text-4xl font-medium tracking-tight text-foreground leading-tight">
|
||||
Paramètres
|
||||
</h1>
|
||||
<p className="text-[11px] text-muted-foreground uppercase tracking-[0.2em] font-bold mt-2">
|
||||
Configuration & Préférences
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col h-full bg-[#F2F0E9] dark:bg-dark-paper">
|
||||
<header className="px-12 pt-20 pb-16 space-y-12 shrink-0">
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-[64px] font-serif text-ink tracking-tight leading-none italic font-medium">
|
||||
Paramètres
|
||||
</h1>
|
||||
<p className="text-[10px] font-bold uppercase tracking-[0.4em] text-concrete opacity-60">
|
||||
Configuration & Préférences
|
||||
</p>
|
||||
</div>
|
||||
{/* Tab nav flush to the border-bottom of header */}
|
||||
<SettingsNav className="-mb-px" />
|
||||
|
||||
<SettingsNav />
|
||||
</header>
|
||||
|
||||
{/* Page Content */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="max-w-5xl mx-auto px-12 py-10 space-y-8">
|
||||
{children}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { auth } from '@/auth'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { McpSettingsPanel } from '@/components/mcp/mcp-settings-panel'
|
||||
import { listMcpKeys, getMcpServerStatus } from '@/app/actions/mcp-keys'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
|
||||
export default async function McpSettingsPage() {
|
||||
const session = await auth()
|
||||
@@ -14,9 +15,9 @@ export default async function McpSettingsPage() {
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
<h3 className="text-[10px] font-bold uppercase tracking-[0.3em] text-concrete">
|
||||
Gérez vos clés API et serveurs MCP connectés.
|
||||
</p>
|
||||
</h3>
|
||||
<McpSettingsPanel initialKeys={keys} serverStatus={serverStatus} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -2,8 +2,6 @@ import { auth } from '@/auth'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { ProfileForm } from './profile-form'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { ProfilePageHeader } from '@/components/profile-page-header'
|
||||
import { AISettingsLinkCard } from './ai-settings-link-card'
|
||||
|
||||
export default async function ProfilePage() {
|
||||
const session = await auth()
|
||||
@@ -12,33 +10,18 @@ export default async function ProfilePage() {
|
||||
redirect('/login')
|
||||
}
|
||||
|
||||
// Parallel queries
|
||||
const [user, aiSettings] = await Promise.all([
|
||||
prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { name: true, email: true, role: true }
|
||||
}),
|
||||
prisma.userAISettings.findUnique({
|
||||
where: { userId: session.user.id }
|
||||
})
|
||||
])
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { name: true, email: true, role: true, image: true }
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
redirect('/login')
|
||||
}
|
||||
|
||||
const userAISettings = {
|
||||
preferredLanguage: aiSettings?.preferredLanguage || 'auto',
|
||||
showRecentNotes: aiSettings?.showRecentNotes ?? false
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl">
|
||||
<ProfilePageHeader />
|
||||
<ProfileForm user={user} userAISettings={userAISettings} />
|
||||
|
||||
{/* AI Settings Link */}
|
||||
<AISettingsLinkCard />
|
||||
<ProfileForm user={user} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,91 +1,157 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useState } from 'react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { updateProfile, changePassword } from '@/app/actions/profile'
|
||||
import { updateUserSettings } from '@/app/actions/user-settings'
|
||||
import { signOut } from 'next-auth/react'
|
||||
import { toast } from 'sonner'
|
||||
import { useLanguage } from '@/lib/i18n'
|
||||
import { User, Lock } from 'lucide-react'
|
||||
import { User, Mail, Shield, LogOut, Camera, Bell } from 'lucide-react'
|
||||
import { motion } from 'motion/react'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
|
||||
export function ProfileForm({ user, userAISettings }: { user: any; userAISettings?: any }) {
|
||||
export function ProfileForm({ user }: { user: { name: string | null; email: string; image: string | null } }) {
|
||||
const { t } = useLanguage()
|
||||
const [desktopNotif, setDesktopNotif] = useState(false)
|
||||
|
||||
const initial = (user.name || user.email || 'U')[0].toUpperCase()
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<p className="text-[11px] font-bold uppercase tracking-[0.2em] text-muted-foreground">
|
||||
{t('profile.description')}
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Profile info card */}
|
||||
<div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
|
||||
<User className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">{t('profile.title')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('profile.description')}</p>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="space-y-12 max-w-2xl"
|
||||
>
|
||||
<div className="space-y-8">
|
||||
{/* Avatar + Name */}
|
||||
<div className="flex items-center gap-8">
|
||||
<div className="relative group">
|
||||
<div className="w-24 h-24 rounded-[32px] bg-brand-accent/10 border-2 border-brand-accent/20 flex items-center justify-center overflow-hidden">
|
||||
{user.image ? (
|
||||
<Avatar className="size-24 rounded-[32px]">
|
||||
<AvatarImage src={user.image} alt="" />
|
||||
<AvatarFallback className="text-2xl font-serif font-bold text-brand-accent">{initial}</AvatarFallback>
|
||||
</Avatar>
|
||||
) : (
|
||||
<User size={40} className="text-brand-accent" />
|
||||
)}
|
||||
</div>
|
||||
<button className="absolute -bottom-2 -right-2 p-2 bg-ink text-white rounded-xl shadow-lg border border-border opacity-0 group-hover:opacity-100 transition-all hover:scale-110">
|
||||
<Camera size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-2xl font-serif font-bold text-ink">{user.name || 'Utilisateur'}</h3>
|
||||
<p className="text-sm text-concrete font-light">{user.email}</p>
|
||||
</div>
|
||||
<form action={async (formData) => {
|
||||
const result = await updateProfile({ name: formData.get('name') as string })
|
||||
if (result?.error) toast.error(t('profile.updateFailed'))
|
||||
else toast.success(t('profile.updateSuccess'))
|
||||
}} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="name" className="text-sm font-medium text-foreground">{t('profile.displayName')}</label>
|
||||
<Input id="name" name="name" defaultValue={user.name} className="bg-muted border-border focus:border-primary" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="email" className="text-sm font-medium text-foreground">{t('profile.email')}</label>
|
||||
<Input id="email" value={user.email} disabled className="bg-muted border-border opacity-60" />
|
||||
</div>
|
||||
<Button type="submit" className="w-full mt-2">{t('general.save')}</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Password card */}
|
||||
<div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
|
||||
<Lock className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-foreground">{t('profile.changePassword')}</h3>
|
||||
<p className="text-sm text-muted-foreground">{t('profile.changePasswordDescription')}</p>
|
||||
{/* Personal info */}
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-[10px] font-bold uppercase tracking-[0.2em] text-concrete opacity-60">
|
||||
{t('profile.description')}
|
||||
</h4>
|
||||
<div className="space-y-3">
|
||||
{/* Name edit */}
|
||||
<form action={async (formData) => {
|
||||
const result = await updateProfile({ name: formData.get('name') as string })
|
||||
if (result?.error) toast.error(t('profile.updateFailed'))
|
||||
else toast.success(t('profile.updateSuccess'))
|
||||
}} className="p-4 bg-white/40 dark:bg-white/5 border border-border rounded-2xl flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<User size={18} className="text-concrete" />
|
||||
<div>
|
||||
<p className="text-[10px] uppercase font-bold text-concrete tracking-widest">{t('profile.displayName')}</p>
|
||||
<Input name="name" defaultValue={user.name || ''} className="border-0 bg-transparent p-0 h-auto text-sm text-ink focus:ring-0 focus:outline-none" />
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" className="text-[10px] font-bold text-brand-accent uppercase tracking-widest hover:underline">
|
||||
{t('general.save')}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{/* Email */}
|
||||
<div className="p-4 bg-white/40 dark:bg-white/5 border border-border rounded-2xl flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Mail size={18} className="text-concrete" />
|
||||
<div>
|
||||
<p className="text-[10px] uppercase font-bold text-concrete tracking-widest">Email</p>
|
||||
<p className="text-sm text-ink">{user.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Security / Password */}
|
||||
<form action={async (formData) => {
|
||||
const result = await changePassword(formData)
|
||||
if (result?.error) {
|
||||
const msg = '_form' in result.error
|
||||
? result.error._form[0]
|
||||
: result.error.currentPassword?.[0] || result.error.newPassword?.[0] || result.error.confirmPassword?.[0] || t('profile.passwordChangeFailed')
|
||||
toast.error(msg)
|
||||
} else {
|
||||
toast.success(t('profile.passwordChangeSuccess'))
|
||||
}
|
||||
}} className="p-4 bg-white/40 dark:bg-white/5 border border-border rounded-2xl space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Shield size={18} className="text-concrete" />
|
||||
<div>
|
||||
<p className="text-[10px] uppercase font-bold text-concrete tracking-widest">{t('profile.changePassword')}</p>
|
||||
<p className="text-sm text-ink">{t('profile.changePasswordDescription')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3 ms-10">
|
||||
<Input name="currentPassword" type="password" required placeholder={t('profile.currentPassword')} className="bg-white/50 dark:bg-black/20 border-border text-sm h-9" />
|
||||
<Input name="newPassword" type="password" required minLength={6} placeholder={t('profile.newPassword')} className="bg-white/50 dark:bg-black/20 border-border text-sm h-9" />
|
||||
<Input name="confirmPassword" type="password" required minLength={6} placeholder={t('profile.confirmPassword')} className="bg-white/50 dark:bg-black/20 border-border text-sm h-9" />
|
||||
</div>
|
||||
<div className="flex justify-end ms-10">
|
||||
<button type="submit" className="text-[10px] font-bold text-brand-accent uppercase tracking-widest hover:underline">
|
||||
{t('profile.updatePassword')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<form action={async (formData) => {
|
||||
const result = await changePassword(formData)
|
||||
if (result?.error) {
|
||||
const msg = '_form' in result.error
|
||||
? result.error._form[0]
|
||||
: result.error.currentPassword?.[0] || result.error.newPassword?.[0] || result.error.confirmPassword?.[0] || t('profile.passwordChangeFailed')
|
||||
toast.error(msg)
|
||||
} else {
|
||||
toast.success(t('profile.passwordChangeSuccess'))
|
||||
const form = document.querySelector('form#password-form') as HTMLFormElement
|
||||
form?.reset()
|
||||
}
|
||||
}} id="password-form" className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="currentPassword" className="text-sm font-medium text-foreground">{t('profile.currentPassword')}</label>
|
||||
<Input id="currentPassword" name="currentPassword" type="password" required className="bg-muted border-border focus:border-primary" />
|
||||
|
||||
{/* Preferences */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-[10px] font-bold uppercase tracking-[0.2em] text-concrete opacity-60">
|
||||
{t('profile.preferences') || 'Préférences de compte'}
|
||||
</h4>
|
||||
<div className="p-4 bg-white/40 dark:bg-white/5 border border-border rounded-2xl flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Bell size={18} className="text-concrete" />
|
||||
<div>
|
||||
<p className="text-sm text-ink">{t('profile.desktopNotifications') || 'Notification bureau'}</p>
|
||||
<p className="text-[10px] text-concrete font-light pe-4">{t('profile.desktopNotificationsDesc') || 'Recevez des alertes pour vos rappels et activités IA.'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setDesktopNotif(!desktopNotif)}
|
||||
className={`w-10 h-5 rounded-full relative p-0.5 cursor-pointer transition-all duration-300 ${desktopNotif ? 'bg-brand-accent' : 'bg-gray-200 dark:bg-white/10'}`}
|
||||
>
|
||||
<div className={`w-3.5 h-3.5 bg-white rounded-full transition-all duration-300 ${desktopNotif ? 'translate-x-[18px]' : 'translate-x-0'}`} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="newPassword" className="text-sm font-medium text-foreground">{t('profile.newPassword')}</label>
|
||||
<Input id="newPassword" name="newPassword" type="password" required minLength={6} className="bg-muted border-border focus:border-primary" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="confirmPassword" className="text-sm font-medium text-foreground">{t('profile.confirmPassword')}</label>
|
||||
<Input id="confirmPassword" name="confirmPassword" type="password" required minLength={6} className="bg-muted border-border focus:border-primary" />
|
||||
</div>
|
||||
<Button type="submit" className="w-full mt-2">{t('profile.updatePassword')}</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Logout */}
|
||||
<div className="pt-8 border-t border-border/40">
|
||||
<button
|
||||
onClick={() => signOut({ callbackUrl: '/login' })}
|
||||
className="flex items-center gap-3 px-6 py-3 bg-rose-50 dark:bg-rose-500/10 text-rose-600 rounded-xl font-bold uppercase tracking-widest text-[10px] hover:bg-rose-100 transition-colors"
|
||||
>
|
||||
<LogOut size={16} />
|
||||
{t('sidebar.signOut') || 'Déconnexion'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { motion, AnimatePresence } from 'motion/react'
|
||||
import { PageEntry } from '@/components/page-entry'
|
||||
import {
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
@@ -137,6 +138,7 @@ export function TrashClient({
|
||||
}
|
||||
|
||||
return (
|
||||
<PageEntry>
|
||||
<div className="h-full flex flex-col bg-[#F9F8F6] dark:bg-[#1a1a1a]">
|
||||
<header className="px-12 pt-12 pb-8 flex flex-col gap-6 sticky top-0 bg-[#F9F8F6]/80 dark:bg-[#1a1a1a]/80 backdrop-blur-md z-30 border-b border-border/20">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -206,12 +208,12 @@ export function TrashClient({
|
||||
<motion.div
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${(daysLeft / 30) * 100}%` }}
|
||||
className={`h-full ${daysLeft < 5 ? 'bg-rose-500' : 'bg-blueprint'}`}
|
||||
className={`h-full ${daysLeft < 5 ? 'bg-rose-500' : 'bg-terreo'}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-start mb-6">
|
||||
<div className={`p-3 rounded-2xl ${item.itemType === 'note' ? 'bg-blueprint/10 text-blueprint' : 'bg-concrete/10 text-concrete'}`}>
|
||||
<div className={`p-3 rounded-2xl ${item.itemType === 'note' ? 'bg-terreo/10 text-terreo' : 'bg-concrete/10 text-concrete'}`}>
|
||||
{item.itemType === 'note' ? <FileText size={20} /> : <Folder size={20} />}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -236,7 +238,7 @@ export function TrashClient({
|
||||
{item.title}
|
||||
</h3>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded border ${daysLeft < 5 ? 'border-rose-200 text-rose-500 bg-rose-50' : 'border-blueprint/20 text-blueprint bg-blueprint/5'}`}>
|
||||
<div className={`text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded border ${daysLeft < 5 ? 'border-rose-200 text-rose-500 bg-rose-50' : 'border-terreo/20 text-terreo bg-terreo/5'}`}>
|
||||
{daysLeft} {t('trash.daysRemaining') || 'DAYS LEFT'}
|
||||
</div>
|
||||
{item.deletedAt && (
|
||||
@@ -287,5 +289,6 @@ export function TrashClient({
|
||||
</p>
|
||||
</footer>
|
||||
</div>
|
||||
</PageEntry>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
'use server'
|
||||
|
||||
import { semanticSearchService, SearchResult } from '@/lib/ai/services/semantic-search.service'
|
||||
import { auth } from '@/auth'
|
||||
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements'
|
||||
|
||||
export interface SemanticSearchResponse {
|
||||
results: SearchResult[]
|
||||
@@ -20,6 +22,17 @@ export async function semanticSearch(
|
||||
notebookId?: string // NEW: Filter by notebook for contextual search (IA5)
|
||||
}
|
||||
): Promise<SemanticSearchResponse> {
|
||||
const session = await auth();
|
||||
if (session?.user?.id) {
|
||||
try {
|
||||
await checkEntitlementOrThrow(session.user.id, 'semantic_search');
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) throw err;
|
||||
console.error('[semantic-search] Quota check error (fail-open):', err);
|
||||
}
|
||||
incrementUsageAsync(session.user.id, 'semantic_search');
|
||||
}
|
||||
|
||||
try {
|
||||
const results = await semanticSearchService.search(query, {
|
||||
limit: options?.limit || 20,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { normalizeThemeId, type ThemeId } from '@/lib/apply-document-theme'
|
||||
export type UserSettingsData = {
|
||||
theme?: ThemeId
|
||||
cardSizeMode?: 'variable' | 'uniform'
|
||||
accentColor?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,9 +24,10 @@ export async function updateUserSettings(settings: UserSettingsData) {
|
||||
}
|
||||
|
||||
try {
|
||||
const data: { theme?: string; cardSizeMode?: 'variable' | 'uniform' } = {}
|
||||
const data: { theme?: string; cardSizeMode?: 'variable' | 'uniform'; accentColor?: string } = {}
|
||||
if (settings.theme !== undefined) data.theme = normalizeThemeId(settings.theme)
|
||||
if (settings.cardSizeMode !== undefined) data.cardSizeMode = settings.cardSizeMode
|
||||
if (settings.accentColor !== undefined) data.accentColor = settings.accentColor
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: session.user.id },
|
||||
@@ -38,7 +40,7 @@ export async function updateUserSettings(settings: UserSettingsData) {
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Error updating user settings:', error)
|
||||
throw new Error('Failed to update user settings')
|
||||
throw new Error('Failed to update user settings: ' + (error instanceof Error ? error.message : String(error)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,12 +49,13 @@ const getCachedUserSettings = unstable_cache(
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { theme: true, cardSizeMode: true },
|
||||
select: { theme: true, cardSizeMode: true, accentColor: true },
|
||||
})
|
||||
|
||||
return {
|
||||
theme: normalizeThemeId(user?.theme || 'light'),
|
||||
cardSizeMode: (user?.cardSizeMode || 'variable') as 'variable' | 'uniform',
|
||||
accentColor: user?.accentColor || '#A47148',
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting user settings:', error)
|
||||
@@ -78,6 +81,7 @@ export async function getUserSettings(userId?: string) {
|
||||
return {
|
||||
theme: 'light' as const satisfies ThemeId,
|
||||
cardSizeMode: 'variable' as const,
|
||||
accentColor: '#A47148',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service';
|
||||
import { getTagsProvider } from '@/lib/ai/factory';
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user';
|
||||
import { getSystemConfig } from '@/lib/config';
|
||||
import { z } from 'zod';
|
||||
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements';
|
||||
|
||||
import { getAISettings } from '@/app/actions/ai-settings';
|
||||
|
||||
@@ -25,6 +26,18 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ tags: [] });
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getSystemConfig();
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, session.user.id);
|
||||
if (!willUseByok) {
|
||||
await checkEntitlementOrThrow(session.user.id, 'auto_tag');
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
return NextResponse.json(err.toJSON(), { status: 402 });
|
||||
}
|
||||
console.error('[/api/ai/tags] Quota check error (fail-open):', err);
|
||||
}
|
||||
const body = await req.json();
|
||||
const { content, notebookId, language } = requestSchema.parse(body);
|
||||
|
||||
@@ -58,8 +71,13 @@ export async function POST(req: NextRequest) {
|
||||
// Otherwise, use legacy auto-tagging (generates new tags)
|
||||
try {
|
||||
const config = await getSystemConfig();
|
||||
const provider = getTagsProvider(config);
|
||||
const tags = await provider.generateTags(content, language);
|
||||
const { result: tags, usedByok } = await runLaneWithBillingUser(
|
||||
'tags',
|
||||
config,
|
||||
session.user.id,
|
||||
(provider) => provider.generateTags(content, language),
|
||||
);
|
||||
if (!usedByok) incrementUsageAsync(session.user.id, 'auto_tag');
|
||||
return NextResponse.json({ tags });
|
||||
} catch (err) {
|
||||
console.error('[/api/ai/tags] legacy tagging failed:', err)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getTagsProvider } from '@/lib/ai/factory'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { auth } from '@/auth'
|
||||
import { getAISettings } from '@/app/actions/ai-settings'
|
||||
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements'
|
||||
import { z } from 'zod'
|
||||
|
||||
const requestSchema = z.object({
|
||||
@@ -13,14 +14,27 @@ export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Check authentication and user setting
|
||||
const session = await auth()
|
||||
if (session?.user?.id) {
|
||||
const settings = await getAISettings(session.user.id)
|
||||
if (settings.titleSuggestions === false) {
|
||||
return NextResponse.json({ suggestions: [] })
|
||||
}
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const settings = await getAISettings(session.user.id)
|
||||
if (settings.titleSuggestions === false) {
|
||||
return NextResponse.json({ suggestions: [] })
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getSystemConfig()
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, session.user.id);
|
||||
if (!willUseByok) {
|
||||
await checkEntitlementOrThrow(session.user.id, 'auto_title');
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
return NextResponse.json(err.toJSON(), { status: 402 });
|
||||
}
|
||||
console.error('[/api/ai/title-suggestions] Quota check error (fail-open):', err);
|
||||
}
|
||||
const body = await req.json()
|
||||
const { content } = requestSchema.parse(body)
|
||||
|
||||
@@ -35,7 +49,6 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
const config = await getSystemConfig()
|
||||
const provider = getTagsProvider(config)
|
||||
|
||||
// Détecter la langue du contenu (simple détection basée sur les caractères et mots)
|
||||
const hasNonLatinChars = /[\u0400-\u04FF\u0600-\u06FF\u4E00-\u9FFF\u0E00-\u0E7F]/.test(content)
|
||||
@@ -95,7 +108,13 @@ CONTENT_START: ${content.substring(0, 500)} CONTENT_END
|
||||
|
||||
Réponds SEULEMENT avec un tableau JSON: [{"title": "titre1", "confidence": 0.95}, {"title": "titre2", "confidence": 0.85}, {"title": "titre3", "confidence": 0.75}]`
|
||||
|
||||
const titles = await provider.generateTitles(titlePrompt)
|
||||
const { result: titles, usedByok } = await runLaneWithBillingUser(
|
||||
'tags',
|
||||
config,
|
||||
session.user.id,
|
||||
(provider) => provider.generateTitles(titlePrompt),
|
||||
)
|
||||
if (!usedByok) incrementUsageAsync(session.user.id, 'auto_title')
|
||||
|
||||
// Créer les suggestions
|
||||
const suggestions = titles.map((t: any) => ({
|
||||
|
||||
68
memento-note/app/api/billing/create-checkout/route.ts
Normal file
68
memento-note/app/api/billing/create-checkout/route.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { stripe } from '@/lib/stripe';
|
||||
import { resolvePriceId } from '@/lib/billing/stripe-prices';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { z } from 'zod';
|
||||
|
||||
const bodySchema = z.object({
|
||||
tier: z.enum(['PRO', 'BUSINESS']),
|
||||
interval: z.enum(['month', 'year']),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id || !session.user.email) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const parsed = bodySchema.safeParse(await req.json());
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { tier, interval } = parsed.data;
|
||||
const userId = session.user.id;
|
||||
const userEmail = session.user.email;
|
||||
|
||||
try {
|
||||
const priceId = resolvePriceId(tier, interval);
|
||||
|
||||
const subscription = await prisma.subscription.findUnique({ where: { userId } });
|
||||
let customerId = subscription?.stripeCustomerId ?? undefined;
|
||||
|
||||
if (!customerId) {
|
||||
const customer = await stripe.customers.create({
|
||||
email: userEmail,
|
||||
metadata: { userId },
|
||||
});
|
||||
customerId = customer.id;
|
||||
}
|
||||
|
||||
const origin = req.headers.get('origin') ?? process.env.NEXTAUTH_URL ?? 'http://localhost:3000';
|
||||
|
||||
const sessionParams = {
|
||||
customer: customerId,
|
||||
mode: 'subscription' as const,
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
ui_mode: 'embedded',
|
||||
return_url: `${origin}/settings/billing?session_id={CHECKOUT_SESSION_ID}`,
|
||||
metadata: { userId, tier },
|
||||
subscription_data: { metadata: { userId, tier } },
|
||||
customer_update: { address: 'auto' },
|
||||
};
|
||||
const checkoutSession = await stripe.checkout.sessions.create(sessionParams as any);
|
||||
|
||||
if (checkoutSession.client_secret) {
|
||||
return NextResponse.json({
|
||||
clientSecret: checkoutSession.client_secret,
|
||||
sessionId: checkoutSession.id,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ url: checkoutSession.url });
|
||||
} catch (error) {
|
||||
console.error('[billing/create-checkout]', error);
|
||||
return NextResponse.json({ error: 'Failed to create checkout session' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
32
memento-note/app/api/billing/portal/route.ts
Normal file
32
memento-note/app/api/billing/portal/route.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { stripe } from '@/lib/stripe';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
|
||||
try {
|
||||
const subscription = await prisma.subscription.findUnique({ where: { userId } });
|
||||
if (!subscription?.stripeCustomerId) {
|
||||
return NextResponse.json({ error: 'No active subscription found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const origin = req.headers.get('origin') ?? process.env.NEXTAUTH_URL ?? 'http://localhost:3000';
|
||||
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: subscription.stripeCustomerId,
|
||||
return_url: `${origin}/settings/billing`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: portalSession.url });
|
||||
} catch (error) {
|
||||
console.error('[billing/portal]', error);
|
||||
return NextResponse.json({ error: 'Failed to create portal session' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
32
memento-note/app/api/billing/status/route.ts
Normal file
32
memento-note/app/api/billing/status/route.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { getUserInfo, getEffectiveTier } from '@/lib/entitlements';
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const userId = session.user.id;
|
||||
|
||||
try {
|
||||
const { tier, status, currentPeriodEnd } = await getUserInfo(userId);
|
||||
const effectiveTier = await getEffectiveTier(userId);
|
||||
|
||||
const { prisma } = await import('@/lib/prisma');
|
||||
const subscription = await prisma.subscription.findUnique({ where: { userId } });
|
||||
|
||||
return NextResponse.json({
|
||||
tier,
|
||||
effectiveTier,
|
||||
status,
|
||||
currentPeriodEnd: currentPeriodEnd ?? null,
|
||||
cancelAtPeriodEnd: subscription?.cancelAtPeriodEnd ?? false,
|
||||
hasStripeSubscription: !!subscription?.stripeSubscriptionId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[billing/status]', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch billing status' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
98
memento-note/app/api/billing/webhook/route.ts
Normal file
98
memento-note/app/api/billing/webhook/route.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { stripe } from '@/lib/stripe';
|
||||
import {
|
||||
syncSubscriptionFromStripe,
|
||||
handleSubscriptionDeleted,
|
||||
resolveUserIdFromStripeEvent,
|
||||
} from '@/lib/billing/sync-subscription-from-stripe';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import type Stripe from 'stripe';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.text();
|
||||
const headersList = await headers();
|
||||
const sig = headersList.get('stripe-signature');
|
||||
|
||||
if (!sig) {
|
||||
return NextResponse.json({ error: 'Missing stripe-signature header' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!process.env.STRIPE_WEBHOOK_SECRET) {
|
||||
console.error('[billing/webhook] STRIPE_WEBHOOK_SECRET not configured');
|
||||
return NextResponse.json({ error: 'Webhook not configured' }, { status: 500 });
|
||||
}
|
||||
|
||||
let event: Stripe.Event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET);
|
||||
} catch (err) {
|
||||
console.error('[billing/webhook] Signature verification failed:', err);
|
||||
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
switch (event.type) {
|
||||
case 'checkout.session.completed': {
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
if (session.mode === 'subscription' && session.subscription) {
|
||||
const subscriptionId = typeof session.subscription === 'string'
|
||||
? session.subscription
|
||||
: session.subscription.id;
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
const userId = (session.metadata?.userId as string | undefined)
|
||||
?? (subscription.metadata?.userId as string | undefined);
|
||||
if (userId) {
|
||||
await syncSubscriptionFromStripe(subscription, userId);
|
||||
} else {
|
||||
console.warn('[billing/webhook] checkout.session.completed: no userId in metadata', session.id);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.created':
|
||||
case 'customer.subscription.updated': {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const userId = await resolveUserIdFromStripeEvent(subscription);
|
||||
if (userId) {
|
||||
await syncSubscriptionFromStripe(subscription, userId);
|
||||
} else {
|
||||
console.warn('[billing/webhook] subscription event: no userId found', subscription.id);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'customer.subscription.deleted': {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
await handleSubscriptionDeleted(subscription);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'invoice.payment_failed': {
|
||||
const invoice = event.data.object as Stripe.Invoice & { subscription?: string | { id: string } };
|
||||
if (invoice.subscription) {
|
||||
const subscriptionId = typeof invoice.subscription === 'string'
|
||||
? invoice.subscription
|
||||
: invoice.subscription.id;
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
const userId = await resolveUserIdFromStripeEvent(subscription);
|
||||
if (userId) {
|
||||
await syncSubscriptionFromStripe(subscription, userId);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return NextResponse.json({ received: true });
|
||||
} catch (error) {
|
||||
console.error('[billing/webhook] Handler error:', error);
|
||||
return NextResponse.json({ error: 'Webhook handler failed' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,15 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { auth } from '@/auth'
|
||||
import { z } from 'zod'
|
||||
import { getTagsProvider } from '@/lib/ai/factory'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { embeddingService } from '@/lib/ai/services/embedding.service'
|
||||
import {
|
||||
checkSessionEntitlementOrThrow,
|
||||
QuotaExceededError,
|
||||
} from '@/lib/entitlements'
|
||||
import {
|
||||
billingOwnerFromSession,
|
||||
verifyParticipant,
|
||||
resolveAiContextUserId,
|
||||
sanitizeNotesForGuest,
|
||||
@@ -182,7 +187,23 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Session not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const parentIdea = brainstormSession.ideas.find(i => i.id === ideaId)
|
||||
const { billingOwnerId, isGuestActor } = billingOwnerFromSession(
|
||||
brainstormSession.userId,
|
||||
session.user.id,
|
||||
)
|
||||
// Story 3.5: per-provider BYOK bypass
|
||||
const earlyConfig = await getSystemConfig()
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('tags', earlyConfig, billingOwnerId)
|
||||
if (!willUseByok) {
|
||||
await checkSessionEntitlementOrThrow(
|
||||
billingOwnerId,
|
||||
session.user.id,
|
||||
isGuestActor,
|
||||
'brainstorm_expand',
|
||||
)
|
||||
}
|
||||
|
||||
const parentIdea = (brainstormSession.ideas || []).find(i => i.id === ideaId)
|
||||
if (!parentIdea) {
|
||||
return NextResponse.json({ error: 'Idea not found' }, { status: 404 })
|
||||
}
|
||||
@@ -205,7 +226,6 @@ export async function POST(
|
||||
}
|
||||
|
||||
const config = await getSystemConfig()
|
||||
const provider = getTagsProvider(config)
|
||||
|
||||
const prompt = buildExpandPromptV2(
|
||||
parentIdea.title,
|
||||
@@ -216,7 +236,12 @@ export async function POST(
|
||||
locale
|
||||
)
|
||||
|
||||
const llmResponse = await provider.generateText(prompt)
|
||||
const { result: llmResponse } = await runLaneWithBillingUser(
|
||||
'tags',
|
||||
config,
|
||||
billingOwnerId,
|
||||
(provider) => provider.generateText(prompt),
|
||||
)
|
||||
|
||||
let newIdeas: any[]
|
||||
try {
|
||||
@@ -311,6 +336,9 @@ export async function POST(
|
||||
|
||||
return NextResponse.json({ success: true, data: updatedSession })
|
||||
} catch (error: any) {
|
||||
if (error instanceof QuotaExceededError) {
|
||||
return NextResponse.json(error.toJSON(), { status: 402 })
|
||||
}
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json({ error: error.issues }, { status: 400 })
|
||||
}
|
||||
|
||||
@@ -2,10 +2,20 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { auth } from '@/auth'
|
||||
import { z } from 'zod'
|
||||
import { verifyParticipant, logActivity, resolveAiContextUserId, captureSnapshot } from '@/lib/brainstorm-collab'
|
||||
import {
|
||||
billingOwnerFromSession,
|
||||
verifyParticipant,
|
||||
logActivity,
|
||||
resolveAiContextUserId,
|
||||
captureSnapshot,
|
||||
} from '@/lib/brainstorm-collab'
|
||||
import { embeddingService } from '@/lib/ai/services/embedding.service'
|
||||
import { getTagsProvider } from '@/lib/ai/factory'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import {
|
||||
reserveUsageOrThrow,
|
||||
QuotaExceededError,
|
||||
} from '@/lib/entitlements'
|
||||
import { emitToSession } from '@/lib/socket-emit'
|
||||
|
||||
const manualSchema = z.object({
|
||||
@@ -43,6 +53,11 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Session not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const { billingOwnerId, isGuestActor } = billingOwnerFromSession(
|
||||
brainstormSession.userId,
|
||||
session.user.id,
|
||||
)
|
||||
|
||||
let wave = 1
|
||||
let parentIdea: any = null
|
||||
if (parentIdeaId) {
|
||||
@@ -78,8 +93,25 @@ export async function POST(
|
||||
},
|
||||
})
|
||||
|
||||
// [UPDATE - SÉCURITÉ] Recherche vectorielle guest-safe
|
||||
// Story 3.5: per-provider BYOK bypass for enrich
|
||||
let enrichBlocked = false
|
||||
try {
|
||||
const config = await getSystemConfig()
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, billingOwnerId)
|
||||
if (!willUseByok) {
|
||||
await reserveUsageOrThrow(billingOwnerId, 'brainstorm_enrich')
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
enrichBlocked = true
|
||||
} else {
|
||||
console.error('[manual-idea] reserveUsage error:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// [UPDATE - SÉCURITÉ] Recherche vectorielle guest-safe (skipped when host quota exhausted)
|
||||
let relatedNoteIds: string[] = []
|
||||
if (!enrichBlocked) {
|
||||
try {
|
||||
const { isGuest, publicNoteIds, aiUserId } = await resolveAiContextUserId(sessionId, session.user.id)
|
||||
|
||||
@@ -117,7 +149,10 @@ export async function POST(
|
||||
}
|
||||
relatedNoteIds = results.map((r: any) => r.id)
|
||||
}
|
||||
} catch {}
|
||||
} catch (vectorErr) {
|
||||
console.error('[manual-idea] vector context search failed:', vectorErr)
|
||||
}
|
||||
}
|
||||
|
||||
if (relatedNoteIds.length > 0) {
|
||||
const notes = await prisma.note.findMany({
|
||||
@@ -155,6 +190,16 @@ export async function POST(
|
||||
const requestingUserId = session.user!.id
|
||||
|
||||
const enrichAsync = async () => {
|
||||
if (enrichBlocked) {
|
||||
await emitToSession(sessionId, 'idea:ai_failed', {
|
||||
ideaId: idea.id,
|
||||
reason: 'quota_exceeded',
|
||||
isGuestActor,
|
||||
billingOwnerId,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Notifier le room que l'IA traite ce nœud (bordure pulsante violet)
|
||||
await emitToSession(sessionId, 'idea:ai_processing', {
|
||||
@@ -163,7 +208,6 @@ export async function POST(
|
||||
})
|
||||
|
||||
const config = await getSystemConfig()
|
||||
const provider = getTagsProvider(config)
|
||||
const lang = locale === 'fr' ? 'French' : locale === 'es' ? 'Spanish' : locale === 'de' ? 'German' : locale === 'it' ? 'Italian' : locale === 'pt' ? 'Portuguese' : locale === 'ja' ? 'Japanese' : locale === 'ko' ? 'Korean' : locale === 'zh' ? 'Chinese' : locale === 'ar' ? 'Arabic' : "the user's language"
|
||||
|
||||
const enrichPrompt = `You are an idea enrichment assistant. Given a user's raw brainstorm idea and context, produce a JSON object with:
|
||||
@@ -181,7 +225,12 @@ User's raw description: "${description || 'none provided'}"
|
||||
|
||||
Respond ONLY with the JSON object, no markdown.`
|
||||
|
||||
const raw = await provider.generateText(enrichPrompt)
|
||||
const { result: raw } = await runLaneWithBillingUser(
|
||||
'tags',
|
||||
config,
|
||||
billingOwnerId,
|
||||
(provider) => provider.generateText(enrichPrompt),
|
||||
)
|
||||
const cleaned = raw.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim()
|
||||
const enriched = JSON.parse(cleaned)
|
||||
|
||||
@@ -195,7 +244,6 @@ Respond ONLY with the JSON object, no markdown.`
|
||||
data: { title: enrichedTitle, description: enrichedDescription, connectionToSeed, noveltyScore },
|
||||
})
|
||||
|
||||
// [UPDATE - TEMPS RÉEL] Notifier la complétion avec les données enrichies
|
||||
await emitToSession(sessionId, 'idea:ai_completed', {
|
||||
ideaId: idea.id,
|
||||
title: enrichedTitle,
|
||||
|
||||
@@ -2,9 +2,14 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { auth } from '@/auth'
|
||||
import { z } from 'zod'
|
||||
import { getTagsProvider } from '@/lib/ai/factory'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { embeddingService } from '@/lib/ai/services/embedding.service'
|
||||
import {
|
||||
checkEntitlementOrThrow,
|
||||
QuotaExceededError,
|
||||
incrementUsageAsync,
|
||||
} from '@/lib/entitlements'
|
||||
import { logActivity, captureSnapshot } from '@/lib/brainstorm-collab'
|
||||
|
||||
const waveSchema = z.object({
|
||||
@@ -64,11 +69,7 @@ async function autoContextSearch(
|
||||
snippet: (n.content || '').slice(0, 300),
|
||||
}))
|
||||
|
||||
try {
|
||||
const config = await getSystemConfig()
|
||||
const provider = getTagsProvider(config)
|
||||
|
||||
const classifyPrompt = `Given the seed idea: "${seedIdea}"
|
||||
const classifyPrompt = `Given the seed idea: "${seedIdea}"
|
||||
|
||||
Classify each note as SUPPORT (confirms/reinforces the seed), TENSION (contradicts/questions the seed), or EXTENSION (extends the seed into an adjacent domain).
|
||||
|
||||
@@ -78,7 +79,14 @@ ${notesForLLM.map(n => `[${n.id}] "${n.title}": ${n.snippet}`).join('\n')}
|
||||
Respond ONLY with a valid JSON array of objects:
|
||||
{ "noteId": string, "category": "SUPPORT" | "TENSION" | "EXTENSION" }`
|
||||
|
||||
const raw = await provider.generateText(classifyPrompt)
|
||||
try {
|
||||
const config = await getSystemConfig()
|
||||
const { result: raw } = await runLaneWithBillingUser(
|
||||
'tags',
|
||||
config,
|
||||
userId,
|
||||
(provider) => provider.generateText(classifyPrompt),
|
||||
)
|
||||
const cleaned = raw.replace(/```json\n?/g, '').replace(/```\n?/g, '').trim()
|
||||
const classifications: { noteId: string; category: 'SUPPORT' | 'TENSION' | 'EXTENSION' }[] = JSON.parse(cleaned)
|
||||
|
||||
@@ -199,13 +207,23 @@ export async function POST(request: NextRequest) {
|
||||
const body = await request.json()
|
||||
const { seedIdea, sourceNoteId, contextNoteIds, locale } = waveSchema.parse(body)
|
||||
|
||||
// Story 3.5: per-provider BYOK bypass
|
||||
const config = await getSystemConfig()
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('tags', config, userId)
|
||||
if (!willUseByok) {
|
||||
await checkEntitlementOrThrow(userId, 'brainstorm_create')
|
||||
}
|
||||
|
||||
const classifiedNotes = await autoContextSearch(userId, seedIdea, contextNoteIds)
|
||||
|
||||
const config = await getSystemConfig()
|
||||
const provider = getTagsProvider(config)
|
||||
|
||||
const prompt = buildPromptV2(seedIdea, classifiedNotes, locale)
|
||||
const llmResponse = await provider.generateText(prompt)
|
||||
const { result: llmResponse, usedByok } = await runLaneWithBillingUser(
|
||||
'tags',
|
||||
config,
|
||||
userId,
|
||||
(provider) => provider.generateText(prompt),
|
||||
)
|
||||
if (!usedByok) incrementUsageAsync(userId, 'brainstorm_create')
|
||||
|
||||
let ideas: any[]
|
||||
try {
|
||||
@@ -312,6 +330,9 @@ export async function POST(request: NextRequest) {
|
||||
},
|
||||
}, { status: 201 })
|
||||
} catch (error: any) {
|
||||
if (error instanceof QuotaExceededError) {
|
||||
return NextResponse.json(error.toJSON(), { status: 402 })
|
||||
}
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json({ error: error.issues }, { status: 400 })
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { streamText, UIMessage, stepCountIs } from 'ai'
|
||||
import { getChatProvider } from '@/lib/ai/factory'
|
||||
import { resolveAiRouteWithTiming, formatAiRouteDebug } from '@/lib/ai/router'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
import { semanticSearchService } from '@/lib/ai/services/semantic-search.service'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { auth } from '@/auth'
|
||||
import { loadTranslations, getTranslationValue, SupportedLanguage } from '@/lib/i18n'
|
||||
import { toolRegistry } from '@/lib/ai/tools'
|
||||
import { checkEntitlementOrThrow, QuotaExceededError, incrementUsageAsync } from '@/lib/entitlements'
|
||||
import { trackFeatureUsage } from '@/lib/usage-tracker'
|
||||
import { readFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
|
||||
@@ -46,6 +49,20 @@ export async function POST(req: Request) {
|
||||
}
|
||||
const userId = session.user.id
|
||||
|
||||
// 1.5 Quota check (per-provider BYOK bypass — only when BYOK will be used for resolved provider)
|
||||
try {
|
||||
const sysConfigEarly = await getSystemConfig()
|
||||
const { usedByok: willUseByok } = await willUseByokForLane('chat', sysConfigEarly, userId)
|
||||
if (!willUseByok) {
|
||||
await checkEntitlementOrThrow(userId, 'chat')
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof QuotaExceededError) {
|
||||
return Response.json(err.toJSON(), { status: 402 })
|
||||
}
|
||||
console.error('[chat] Quota check error (fail-open):', err)
|
||||
}
|
||||
|
||||
// 2. Parse request body
|
||||
const body = await req.json()
|
||||
const { messages: rawMessages, conversationId, notebookId, language, webSearch, noteContext, format, noteId } = body as {
|
||||
@@ -323,27 +340,43 @@ Focus ONLY on this note unless asked otherwise.`
|
||||
|
||||
// 6. Execute stream
|
||||
const sysConfig = await getSystemConfig()
|
||||
|
||||
const routeDebug =
|
||||
process.env.NODE_ENV !== 'production' || process.env.MEMENTO_AI_ROUTE_DEBUG === '1'
|
||||
if (routeDebug) {
|
||||
console.debug('[ai-route]', formatAiRouteDebug(resolveAiRouteWithTiming('chat', sysConfig)))
|
||||
}
|
||||
|
||||
const chatTools = noteContext
|
||||
? toolRegistry.buildToolsForChat({ userId, config: sysConfig, webSearch, notebookId: notebookId || undefined })
|
||||
: toolRegistry.buildToolsForChat({ userId, config: sysConfig, webSearch, notebookId: notebookId || undefined })
|
||||
|
||||
const provider = getChatProvider(sysConfig)
|
||||
const result = await streamText({
|
||||
model: provider.getModel(),
|
||||
system: systemPrompt,
|
||||
messages: incomingMessages,
|
||||
tools: chatTools,
|
||||
stopWhen: stepCountIs(5),
|
||||
onFinish: async (final) => {
|
||||
const userContent = incomingMessages[incomingMessages.length - 1].content
|
||||
await prisma.chatMessage.create({
|
||||
data: { conversationId: conversation.id, role: 'user', content: userContent }
|
||||
})
|
||||
await prisma.chatMessage.create({
|
||||
data: { conversationId: conversation.id, role: 'assistant', content: final.text }
|
||||
})
|
||||
}
|
||||
})
|
||||
const { result, usedByok } = await runLaneWithBillingUser(
|
||||
'chat',
|
||||
sysConfig,
|
||||
userId,
|
||||
async (provider) =>
|
||||
streamText({
|
||||
model: provider.getModel(),
|
||||
system: systemPrompt,
|
||||
messages: incomingMessages,
|
||||
tools: chatTools,
|
||||
stopWhen: stepCountIs(5),
|
||||
onFinish: async (final) => {
|
||||
const userContent = incomingMessages[incomingMessages.length - 1].content
|
||||
await prisma.chatMessage.create({
|
||||
data: { conversationId: conversation.id, role: 'user', content: userContent },
|
||||
})
|
||||
await prisma.chatMessage.create({
|
||||
data: { conversationId: conversation.id, role: 'assistant', content: final.text },
|
||||
})
|
||||
if (!usedByok) {
|
||||
trackFeatureUsage(userId, 'chat', final.usage?.totalTokens ?? 0)
|
||||
incrementUsageAsync(userId, 'chat')
|
||||
}
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
return result.toUIMessageStreamResponse()
|
||||
}
|
||||
|
||||
122
memento-note/app/api/cron/sync-usage/route.ts
Normal file
122
memento-note/app/api/cron/sync-usage/route.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { redis } from '@/lib/redis';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { parseRedisInt, getCurrentPeriodKey } from '@/lib/quota-utils';
|
||||
|
||||
function verifyCronAuth(req: NextRequest): boolean {
|
||||
const cronSecret = process.env.CRON_SECRET;
|
||||
if (!cronSecret) {
|
||||
console.error('[sync-usage] CRON_SECRET env var is required but not set');
|
||||
return false;
|
||||
}
|
||||
const authHeader = req.headers.get('authorization');
|
||||
return authHeader === `Bearer ${cronSecret}`;
|
||||
}
|
||||
|
||||
async function scanKeys(pattern: string): Promise<string[]> {
|
||||
const keys: string[] = [];
|
||||
let cursor = '0';
|
||||
do {
|
||||
const [nextCursor, batch] = await redis.scan(
|
||||
cursor,
|
||||
'MATCH',
|
||||
pattern,
|
||||
'COUNT',
|
||||
200,
|
||||
);
|
||||
cursor = nextCursor;
|
||||
keys.push(...batch);
|
||||
} while (cursor !== '0');
|
||||
return keys;
|
||||
}
|
||||
|
||||
function parseUsageKey(key: string, period: string): { userId: string; feature: string } | null {
|
||||
const suffix = `:${period}`;
|
||||
if (!key.endsWith(suffix)) return null;
|
||||
if (key.endsWith(':tokens')) return null;
|
||||
|
||||
const prefix = key.slice(0, key.length - suffix.length);
|
||||
const firstColon = prefix.indexOf(':');
|
||||
if (firstColon === -1) return null;
|
||||
|
||||
const afterPrefix = prefix.slice(firstColon + 1);
|
||||
const lastColon = afterPrefix.lastIndexOf(':');
|
||||
if (lastColon === -1) return null;
|
||||
|
||||
const userId = afterPrefix.slice(0, lastColon);
|
||||
const feature = afterPrefix.slice(lastColon + 1);
|
||||
|
||||
if (!userId || !feature) return null;
|
||||
return { userId, feature };
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!verifyCronAuth(req)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const period = getCurrentPeriodKey();
|
||||
const pattern = `usage:*:${period}`;
|
||||
const keys = await scanKeys(pattern);
|
||||
|
||||
let synced = 0;
|
||||
let errors = 0;
|
||||
|
||||
for (const key of keys) {
|
||||
if (key.endsWith(':tokens')) continue;
|
||||
|
||||
try {
|
||||
const parsed = parseUsageKey(key, period);
|
||||
if (!parsed) continue;
|
||||
|
||||
const { userId, feature } = parsed;
|
||||
|
||||
const [counter, tokens] = await Promise.all([
|
||||
redis.get(key),
|
||||
redis.get(`${key}:tokens`),
|
||||
]);
|
||||
|
||||
const periodStart = new Date(`${period}-01`);
|
||||
const periodEnd = new Date(
|
||||
periodStart.getFullYear(),
|
||||
periodStart.getMonth() + 1,
|
||||
1,
|
||||
);
|
||||
|
||||
await prisma.usageLog.upsert({
|
||||
where: {
|
||||
userId_feature_periodStart: {
|
||||
userId,
|
||||
feature,
|
||||
periodStart,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
feature,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
requestsCount: parseRedisInt(counter),
|
||||
tokensUsed: parseRedisInt(tokens),
|
||||
},
|
||||
update: {
|
||||
requestsCount: parseRedisInt(counter),
|
||||
tokensUsed: parseRedisInt(tokens),
|
||||
syncedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
synced++;
|
||||
} catch (err) {
|
||||
errors++;
|
||||
console.error(`[sync-usage] Failed to sync key ${key}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ synced, errors, total: keys.length });
|
||||
} catch (error) {
|
||||
console.error('[sync-usage] Error:', error);
|
||||
return NextResponse.json({ error: 'Sync failed' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ export async function PATCH(
|
||||
try {
|
||||
const { id } = await params
|
||||
const body = await request.json()
|
||||
const { name, icon, color, order, trashedAt } = body
|
||||
const { name, icon, color, order, trashedAt, parentId } = body
|
||||
|
||||
const existing = await prisma.notebook.findUnique({
|
||||
where: { id },
|
||||
@@ -49,12 +49,40 @@ export async function PATCH(
|
||||
)
|
||||
}
|
||||
|
||||
if (parentId !== undefined) {
|
||||
if (parentId !== null) {
|
||||
if (parentId === id) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'A notebook cannot be its own parent' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const target = await prisma.notebook.findFirst({
|
||||
where: { id: parentId, userId: session.user.id }
|
||||
})
|
||||
if (!target) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Parent notebook not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
const descendants = await getDescendantIds(id)
|
||||
if (descendants.includes(parentId)) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Cannot move a notebook into its own descendant' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const updateData: any = {}
|
||||
if (name !== undefined) updateData.name = name.trim()
|
||||
if (icon !== undefined) updateData.icon = icon
|
||||
if (color !== undefined) updateData.color = color
|
||||
if (order !== undefined) updateData.order = order
|
||||
if (trashedAt !== undefined) updateData.trashedAt = trashedAt
|
||||
if (parentId !== undefined) updateData.parentId = parentId
|
||||
|
||||
if (trashedAt !== undefined) {
|
||||
const descendantIds = await getDescendantIds(id)
|
||||
|
||||
@@ -4,124 +4,103 @@ import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
// Check authentication
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
)
|
||||
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Fetch all notes with related data
|
||||
const notes = await prisma.note.findMany({
|
||||
where: {
|
||||
userId: session.user.id,
|
||||
trashedAt: null
|
||||
},
|
||||
include: {
|
||||
labelRelations: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true
|
||||
}
|
||||
},
|
||||
notebook: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc'
|
||||
}
|
||||
})
|
||||
const userId = session.user.id
|
||||
|
||||
// Fetch labels separately
|
||||
const labels = await prisma.label.findMany({
|
||||
where: {
|
||||
userId: session.user.id
|
||||
},
|
||||
include: {
|
||||
notes: {
|
||||
select: {
|
||||
id: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
const [allNotes, labels, notebooks] = await Promise.all([
|
||||
prisma.note.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
prisma.label.findMany({
|
||||
where: { userId },
|
||||
include: { notes: { select: { id: true } } },
|
||||
}),
|
||||
prisma.notebook.findMany({
|
||||
where: { userId },
|
||||
include: { notes: { select: { id: true } } },
|
||||
}),
|
||||
])
|
||||
|
||||
// Fetch notebooks
|
||||
const notebooks = await prisma.notebook.findMany({
|
||||
where: {
|
||||
userId: session.user.id
|
||||
},
|
||||
include: {
|
||||
notes: {
|
||||
select: {
|
||||
id: true
|
||||
}
|
||||
}
|
||||
const noteLabelMap = new Map<string, string[]>()
|
||||
for (const label of labels) {
|
||||
for (const note of label.notes) {
|
||||
const arr = noteLabelMap.get(note.id) || []
|
||||
arr.push(label.id)
|
||||
noteLabelMap.set(note.id, arr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Create export object
|
||||
const exportData = {
|
||||
version: '1.0.0',
|
||||
version: '2.0.0',
|
||||
exportDate: new Date().toISOString(),
|
||||
user: {
|
||||
id: session.user.id,
|
||||
email: session.user.email,
|
||||
name: session.user.name
|
||||
id: userId,
|
||||
email: session.user.email ?? '',
|
||||
name: session.user.name ?? '',
|
||||
},
|
||||
data: {
|
||||
labels: labels.map(label => ({
|
||||
id: label.id,
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
noteCount: label.notes.length
|
||||
notebooks: notebooks.map(nb => ({
|
||||
id: nb.id,
|
||||
name: nb.name,
|
||||
icon: nb.icon,
|
||||
color: nb.color,
|
||||
order: nb.order,
|
||||
parentId: nb.parentId,
|
||||
trashedAt: nb.trashedAt?.toISOString() ?? null,
|
||||
createdAt: nb.createdAt.toISOString(),
|
||||
updatedAt: nb.updatedAt.toISOString(),
|
||||
noteIds: nb.notes.map(n => n.id),
|
||||
})),
|
||||
notebooks: notebooks.map(notebook => ({
|
||||
id: notebook.id,
|
||||
name: notebook.name,
|
||||
noteCount: notebook.notes.length
|
||||
labels: labels.map(lb => ({
|
||||
id: lb.id,
|
||||
name: lb.name,
|
||||
color: lb.color,
|
||||
notebookId: lb.notebookId,
|
||||
type: lb.type,
|
||||
createdAt: lb.createdAt.toISOString(),
|
||||
updatedAt: lb.updatedAt.toISOString(),
|
||||
noteIds: lb.notes.map(n => n.id),
|
||||
})),
|
||||
notes: notes.map(note => ({
|
||||
id: note.id,
|
||||
title: note.title,
|
||||
content: note.content,
|
||||
color: note.color,
|
||||
isPinned: note.isPinned,
|
||||
isArchived: note.isArchived,
|
||||
type: note.type,
|
||||
checkItems: note.checkItems,
|
||||
images: note.images,
|
||||
links: note.links,
|
||||
createdAt: note.createdAt,
|
||||
updatedAt: note.updatedAt,
|
||||
notebookId: note.notebookId,
|
||||
labelRelations: note.labelRelations.map(label => ({
|
||||
id: label.id,
|
||||
name: label.name
|
||||
}))
|
||||
}))
|
||||
}
|
||||
notes: allNotes.map(n => ({
|
||||
id: n.id,
|
||||
title: n.title,
|
||||
content: n.content,
|
||||
color: n.color,
|
||||
isPinned: n.isPinned,
|
||||
isArchived: n.isArchived,
|
||||
type: n.type,
|
||||
order: n.order,
|
||||
isMarkdown: n.isMarkdown,
|
||||
size: n.size,
|
||||
autoGenerated: n.autoGenerated,
|
||||
historyEnabled: n.historyEnabled,
|
||||
checkItems: n.checkItems,
|
||||
images: n.images,
|
||||
links: n.links,
|
||||
trashedAt: n.trashedAt?.toISOString() ?? null,
|
||||
notebookId: n.notebookId,
|
||||
createdAt: n.createdAt.toISOString(),
|
||||
updatedAt: n.updatedAt.toISOString(),
|
||||
contentUpdatedAt: n.contentUpdatedAt?.toISOString() ?? null,
|
||||
labelIds: noteLabelMap.get(n.id) || [],
|
||||
})),
|
||||
},
|
||||
}
|
||||
|
||||
// Return as JSON file
|
||||
const jsonString = JSON.stringify(exportData, null, 2)
|
||||
return new NextResponse(jsonString, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Disposition': `attachment; filename="memento-export-${new Date().toISOString().split('T')[0]}.json"`
|
||||
}
|
||||
'Content-Disposition': `attachment; filename="memento-export-${new Date().toISOString().split('T')[0]}.json"`,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Export error:', error)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to export notes' },
|
||||
{ status: 500 }
|
||||
)
|
||||
return NextResponse.json({ success: false, error: 'Failed to export notes' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,162 +3,231 @@ import { auth } from '@/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
|
||||
function parseDate(v: unknown): Date | null {
|
||||
if (!v) return null
|
||||
const d = new Date(v as string)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
// Check authentication
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
)
|
||||
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Parse form data
|
||||
const userId = session.user.id
|
||||
const formData = await req.formData()
|
||||
const file = formData.get('file') as File
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'No file provided' },
|
||||
{ status: 400 }
|
||||
)
|
||||
return NextResponse.json({ success: false, error: 'No file provided' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Parse JSON file
|
||||
const text = await file.text()
|
||||
let importData: any
|
||||
|
||||
try {
|
||||
importData = JSON.parse(text)
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Invalid JSON file' },
|
||||
{ status: 400 }
|
||||
)
|
||||
} catch {
|
||||
return NextResponse.json({ success: false, error: 'Invalid JSON file' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Validate import data structure
|
||||
if (!importData.data || !importData.data.notes) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Invalid import format' },
|
||||
{ status: 400 }
|
||||
)
|
||||
return NextResponse.json({ success: false, error: 'Invalid import format' }, { status: 400 })
|
||||
}
|
||||
|
||||
let importedNotes = 0
|
||||
let importedLabels = 0
|
||||
let importedNotebooks = 0
|
||||
const stats = { notes: 0, labels: 0, notebooks: 0, skipped: 0 }
|
||||
|
||||
// Import labels first
|
||||
if (importData.data.labels && Array.isArray(importData.data.labels)) {
|
||||
for (const label of importData.data.labels) {
|
||||
// Check if label already exists
|
||||
const existing = await prisma.label.findFirst({
|
||||
where: {
|
||||
userId: session.user.id,
|
||||
name: label.name
|
||||
}
|
||||
})
|
||||
// 1. Notebooks — parents first, preserve original IDs
|
||||
if (importData.data.notebooks?.length) {
|
||||
const sorted = [...importData.data.notebooks].sort((a: any, b: any) => {
|
||||
if (!a.parentId && b.parentId) return -1
|
||||
if (a.parentId && !b.parentId) return 1
|
||||
return 0
|
||||
})
|
||||
|
||||
if (!existing) {
|
||||
await prisma.label.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
name: label.name,
|
||||
color: label.color
|
||||
}
|
||||
for (const nb of sorted) {
|
||||
try {
|
||||
await prisma.notebook.upsert({
|
||||
where: { id: nb.id },
|
||||
update: {
|
||||
name: nb.name,
|
||||
icon: nb.icon ?? null,
|
||||
color: nb.color ?? null,
|
||||
order: nb.order ?? 0,
|
||||
parentId: nb.parentId ?? null,
|
||||
trashedAt: parseDate(nb.trashedAt),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
create: {
|
||||
id: nb.id,
|
||||
name: nb.name,
|
||||
icon: nb.icon ?? null,
|
||||
color: nb.color ?? null,
|
||||
order: nb.order ?? 0,
|
||||
parentId: nb.parentId ?? null,
|
||||
trashedAt: parseDate(nb.trashedAt),
|
||||
userId,
|
||||
createdAt: parseDate(nb.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(nb.updatedAt) ?? new Date(),
|
||||
},
|
||||
})
|
||||
importedLabels++
|
||||
stats.notebooks++
|
||||
} catch (e: any) {
|
||||
if (e.code === 'P2002') {
|
||||
// unique constraint — try with new ID
|
||||
const parentId = nb.parentId ?? null
|
||||
await prisma.notebook.create({
|
||||
data: {
|
||||
name: nb.name,
|
||||
icon: nb.icon ?? null,
|
||||
color: nb.color ?? null,
|
||||
order: nb.order ?? 0,
|
||||
parentId,
|
||||
trashedAt: parseDate(nb.trashedAt),
|
||||
userId,
|
||||
createdAt: parseDate(nb.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(nb.updatedAt) ?? new Date(),
|
||||
},
|
||||
})
|
||||
stats.notebooks++
|
||||
} else {
|
||||
stats.skipped++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Import notebooks
|
||||
const notebookIdMap = new Map<string, string>()
|
||||
if (importData.data.notebooks && Array.isArray(importData.data.notebooks)) {
|
||||
for (const notebook of importData.data.notebooks) {
|
||||
// Check if notebook already exists
|
||||
const existing = await prisma.notebook.findFirst({
|
||||
where: {
|
||||
userId: session.user.id,
|
||||
name: notebook.name
|
||||
}
|
||||
})
|
||||
|
||||
let newNotebookId
|
||||
if (!existing) {
|
||||
const created = await prisma.notebook.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
name: notebook.name,
|
||||
order: 0
|
||||
}
|
||||
// 2. Labels — preserve original IDs
|
||||
if (importData.data.labels?.length) {
|
||||
for (const lb of importData.data.labels) {
|
||||
try {
|
||||
await prisma.label.upsert({
|
||||
where: { id: lb.id },
|
||||
update: {
|
||||
name: lb.name,
|
||||
color: lb.color ?? null,
|
||||
notebookId: lb.notebookId ?? null,
|
||||
type: lb.type ?? 'user',
|
||||
},
|
||||
create: {
|
||||
id: lb.id,
|
||||
name: lb.name,
|
||||
color: lb.color ?? null,
|
||||
notebookId: lb.notebookId ?? null,
|
||||
type: lb.type ?? 'user',
|
||||
userId,
|
||||
createdAt: parseDate(lb.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(lb.updatedAt) ?? new Date(),
|
||||
},
|
||||
})
|
||||
newNotebookId = created.id
|
||||
notebookIdMap.set(notebook.id, newNotebookId)
|
||||
importedNotebooks++
|
||||
} else {
|
||||
notebookIdMap.set(notebook.id, existing.id)
|
||||
stats.labels++
|
||||
} catch {
|
||||
stats.skipped++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Import notes
|
||||
if (importData.data.notes && Array.isArray(importData.data.notes)) {
|
||||
for (const note of importData.data.notes) {
|
||||
// Map notebook ID
|
||||
const mappedNotebookId = notebookIdMap.get(note.notebookId) || null
|
||||
// 3. Notes — preserve original IDs
|
||||
if (importData.data.notes?.length) {
|
||||
for (const n of importData.data.notes) {
|
||||
try {
|
||||
const labelIds: string[] = n.labelIds || []
|
||||
const validLabelIds = labelIds.length
|
||||
? await prisma.label.findMany({
|
||||
where: { id: { in: labelIds }, userId },
|
||||
select: { id: true },
|
||||
}).then(ls => ls.map(l => l.id))
|
||||
: []
|
||||
|
||||
// Get label IDs
|
||||
const labelNames = (note.labels || note.labelRelations || []).map((l: any) => l.name).filter(Boolean)
|
||||
const labels = await prisma.label.findMany({
|
||||
where: {
|
||||
userId: session.user.id,
|
||||
name: {
|
||||
in: labelNames
|
||||
}
|
||||
await prisma.note.upsert({
|
||||
where: { id: n.id },
|
||||
update: {
|
||||
title: n.title || 'Untitled',
|
||||
content: n.content || '',
|
||||
color: n.color || 'default',
|
||||
isPinned: n.isPinned ?? false,
|
||||
isArchived: n.isArchived ?? false,
|
||||
type: n.type || 'richtext',
|
||||
order: n.order ?? 0,
|
||||
isMarkdown: n.isMarkdown ?? false,
|
||||
size: n.size || 'small',
|
||||
autoGenerated: n.autoGenerated ?? false,
|
||||
historyEnabled: n.historyEnabled ?? true,
|
||||
checkItems: n.checkItems ?? undefined,
|
||||
images: n.images ?? undefined,
|
||||
links: n.links ?? undefined,
|
||||
trashedAt: parseDate(n.trashedAt),
|
||||
notebookId: n.notebookId ?? null,
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt),
|
||||
updatedAt: new Date(),
|
||||
labelRelations: {
|
||||
set: validLabelIds.map(id => ({ id })),
|
||||
},
|
||||
},
|
||||
create: {
|
||||
id: n.id,
|
||||
title: n.title || 'Untitled',
|
||||
content: n.content || '',
|
||||
color: n.color || 'default',
|
||||
isPinned: n.isPinned ?? false,
|
||||
isArchived: n.isArchived ?? false,
|
||||
type: n.type || 'richtext',
|
||||
order: n.order ?? 0,
|
||||
isMarkdown: n.isMarkdown ?? false,
|
||||
size: n.size || 'small',
|
||||
autoGenerated: n.autoGenerated ?? false,
|
||||
historyEnabled: n.historyEnabled ?? true,
|
||||
checkItems: n.checkItems ?? undefined,
|
||||
images: n.images ?? undefined,
|
||||
links: n.links ?? undefined,
|
||||
trashedAt: parseDate(n.trashedAt),
|
||||
notebookId: n.notebookId ?? null,
|
||||
userId,
|
||||
createdAt: parseDate(n.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(n.updatedAt) ?? new Date(),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt),
|
||||
labelRelations: {
|
||||
connect: validLabelIds.map(id => ({ id })),
|
||||
},
|
||||
},
|
||||
})
|
||||
stats.notes++
|
||||
} catch (e: any) {
|
||||
if (e.code === 'P2002') {
|
||||
await prisma.note.create({
|
||||
data: {
|
||||
title: n.title || 'Untitled',
|
||||
content: n.content || '',
|
||||
color: n.color || 'default',
|
||||
isPinned: n.isPinned ?? false,
|
||||
isArchived: n.isArchived ?? false,
|
||||
type: n.type || 'richtext',
|
||||
order: n.order ?? 0,
|
||||
isMarkdown: n.isMarkdown ?? false,
|
||||
size: n.size || 'small',
|
||||
notebookId: n.notebookId ?? null,
|
||||
userId,
|
||||
createdAt: parseDate(n.createdAt) ?? new Date(),
|
||||
updatedAt: parseDate(n.updatedAt) ?? new Date(),
|
||||
contentUpdatedAt: parseDate(n.contentUpdatedAt),
|
||||
},
|
||||
})
|
||||
stats.notes++
|
||||
} else {
|
||||
stats.skipped++
|
||||
}
|
||||
})
|
||||
|
||||
// Create note
|
||||
await prisma.note.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
title: note.title || 'Untitled',
|
||||
content: note.content || '',
|
||||
color: note.color || 'default',
|
||||
isPinned: note.isPinned || false,
|
||||
isArchived: note.isArchived || false,
|
||||
type: note.type || 'richtext',
|
||||
checkItems: note.checkItems || null,
|
||||
images: note.images || null,
|
||||
links: note.links || null,
|
||||
notebookId: mappedNotebookId,
|
||||
labelRelations: {
|
||||
connect: labels.map(label => ({ id: label.id }))
|
||||
}
|
||||
}
|
||||
})
|
||||
importedNotes++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Revalidate paths
|
||||
revalidatePath('/')
|
||||
revalidatePath('/settings/data')
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
count: importedNotes,
|
||||
labels: importedLabels,
|
||||
notebooks: importedNotebooks
|
||||
})
|
||||
return NextResponse.json({ success: true, ...stats })
|
||||
} catch (error) {
|
||||
console.error('Import error:', error)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Failed to import notes' },
|
||||
{ status: 500 }
|
||||
)
|
||||
return NextResponse.json({ success: false, error: 'Failed to import notes' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
22
memento-note/app/api/usage/current/route.ts
Normal file
22
memento-note/app/api/usage/current/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { getUserQuotas } from '@/lib/entitlements';
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const quotas = await getUserQuotas(session.user.id);
|
||||
return NextResponse.json({ quotas });
|
||||
} catch (error) {
|
||||
console.error('[usage/current] Failed to fetch quotas:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch usage data' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
}
|
||||
56
memento-note/app/api/user/api-keys/[provider]/route.ts
Normal file
56
memento-note/app/api/user/api-keys/[provider]/route.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { VALID_PROVIDERS } from '@/lib/ai/router';
|
||||
|
||||
type RouteContext = { params: Promise<{ provider: string }> };
|
||||
|
||||
export async function PATCH(req: NextRequest, context: RouteContext) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { provider } = await context.params;
|
||||
if (!VALID_PROVIDERS.has(provider)) {
|
||||
return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = (await req.json().catch(() => ({}))) as { isActive?: boolean };
|
||||
if (typeof body.isActive !== 'boolean') {
|
||||
return NextResponse.json({ error: 'isActive boolean required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const updated = await prisma.userAPIKey.updateMany({
|
||||
where: { userId: session.user.id, provider },
|
||||
data: { isActive: body.isActive },
|
||||
});
|
||||
|
||||
if (updated.count === 0) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(_req: NextRequest, context: RouteContext) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { provider } = await context.params;
|
||||
if (!VALID_PROVIDERS.has(provider)) {
|
||||
return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });
|
||||
}
|
||||
|
||||
const deleted = await prisma.userAPIKey.deleteMany({
|
||||
where: { userId: session.user.id, provider },
|
||||
});
|
||||
|
||||
if (deleted.count === 0) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
99
memento-note/app/api/user/api-keys/route.ts
Normal file
99
memento-note/app/api/user/api-keys/route.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { auth } from '@/auth';
|
||||
import { getEffectiveTier } from '@/lib/entitlements';
|
||||
import {
|
||||
getAllowedByokProviders,
|
||||
isByokProviderAllowed,
|
||||
} from '@/lib/byok';
|
||||
import {
|
||||
upsertUserApiKey,
|
||||
toPublicApiKey,
|
||||
} from '@/lib/byok';
|
||||
import { validateProviderApiKey } from '@/lib/byok/validate-key';
|
||||
import { VALID_PROVIDERS, type AiGatewayProvider } from '@/lib/ai/router';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
|
||||
const createSchema = z.object({
|
||||
provider: z.string().min(1),
|
||||
apiKey: z.string().min(8),
|
||||
alias: z.string().max(120).optional(),
|
||||
model: z.string().max(120).optional(),
|
||||
baseUrl: z.string().url().optional(),
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const keys = await prisma.userAPIKey.findMany({
|
||||
where: { userId: session.user.id },
|
||||
orderBy: { provider: 'asc' },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
keys: keys.map(toPublicApiKey),
|
||||
allowedProviders: getAllowedByokProviders(await getEffectiveTier(session.user.id)),
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const tier = await getEffectiveTier(session.user.id);
|
||||
if (tier === 'BASIC') {
|
||||
return NextResponse.json(
|
||||
{ error: 'TIER_LIMITED', message: 'BYOK requires a Pro plan or higher' },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: z.infer<typeof createSchema>;
|
||||
try {
|
||||
body = createSchema.parse(await req.json());
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 });
|
||||
}
|
||||
|
||||
const provider = body.provider as AiGatewayProvider;
|
||||
if (!VALID_PROVIDERS.has(provider)) {
|
||||
return NextResponse.json({ error: 'Unknown provider' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!isByokProviderAllowed(tier, provider)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'TIER_LIMITED', message: `Provider "${provider}" is not available on your plan` },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const effectiveBaseUrl = provider === 'custom' ? body.baseUrl : undefined;
|
||||
if (provider !== 'custom' && body.baseUrl) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_REQUEST', message: 'baseUrl is only allowed for custom providers' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await validateProviderApiKey(provider, body.apiKey, effectiveBaseUrl);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Invalid API key';
|
||||
return NextResponse.json({ error: 'INVALID_API_KEY', message }, { status: 400 });
|
||||
}
|
||||
|
||||
const row = await upsertUserApiKey({
|
||||
userId: session.user.id,
|
||||
provider,
|
||||
plaintext: body.apiKey,
|
||||
alias: body.alias,
|
||||
model: body.model,
|
||||
});
|
||||
|
||||
return NextResponse.json({ key: toPublicApiKey(row) });
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
--color-primary: #ACB995;
|
||||
--color-memento-accent: #D4A373;
|
||||
--color-memento-blue: #A47148;
|
||||
--color-brand-accent: #A47148;
|
||||
--color-memento-paper-elevated: #faf9f5;
|
||||
--color-background-light: var(--color-memento-paper);
|
||||
--color-background-dark: #202020;
|
||||
|
||||
@@ -123,7 +123,7 @@ export default async function RootLayout({
|
||||
<SessionProviderWrapper>
|
||||
<ErrorReporter />
|
||||
<DirectionInitializer />
|
||||
<ThemeInitializer theme={userSettings.theme} fontSize={aiSettings.fontSize} fontFamily={aiSettings.fontFamily} />
|
||||
<ThemeInitializer theme={userSettings.theme} fontSize={aiSettings.fontSize} fontFamily={aiSettings.fontFamily} accentColor={userSettings.accentColor} />
|
||||
{children}
|
||||
<Toaster />
|
||||
</SessionProviderWrapper>
|
||||
|
||||
Reference in New Issue
Block a user