correction affichage dashboard chapitre mot par jour + nombre livre max

This commit is contained in:
2026-02-26 23:35:49 +01:00
parent 4e1637a792
commit c3d2711d28
1416 changed files with 69307 additions and 136233 deletions

View File

@@ -1,10 +1,43 @@
export const dynamic = 'force-dynamic';
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import getDB from '@/lib/prisma';
import { generateStoryContent } from '@/lib/gemini';
const PLAN_AI_LIMITS: Record<string, number> = {
free: 100,
pro: 5000,
master: 999999,
};
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
}
const prisma = getDB();
// Check AI usage limit from DB
const dbUser = await prisma.user.findUnique({
where: { id: session.user.id },
select: { plan: true, aiActionsUsed: true },
});
if (!dbUser) {
return NextResponse.json({ error: 'Utilisateur non trouvé' }, { status: 404 });
}
const limit = PLAN_AI_LIMITS[dbUser.plan] || PLAN_AI_LIMITS.free;
if (dbUser.aiActionsUsed >= limit) {
return NextResponse.json(
{ error: `Limite de ${limit} actions IA atteinte pour le plan ${dbUser.plan}. Passez au plan supérieur !` },
{ status: 403 }
);
}
const body = await request.json();
const { project, chapterId, prompt, user } = body;
@@ -15,9 +48,17 @@ export async function POST(request: NextRequest) {
);
}
const result = await generateStoryContent(project, chapterId || '', prompt, user);
// Pass real plan from DB to gemini for model selection
const userWithPlan = { ...user, subscription: { ...user.subscription, plan: dbUser.plan } };
const result = await generateStoryContent(project, chapterId || '', prompt, userWithPlan);
return NextResponse.json(result);
// Increment usage in DB
await prisma.user.update({
where: { id: session.user.id },
data: { aiActionsUsed: { increment: 1 } },
});
return NextResponse.json({ ...result, aiActionsUsed: dbUser.aiActionsUsed + 1 });
} catch (error) {
console.error('AI generate error:', error);
return NextResponse.json(

View File

@@ -1,10 +1,43 @@
export const dynamic = 'force-dynamic';
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import getDB from '@/lib/prisma';
import { transformTextServer } from '@/lib/gemini';
const PLAN_AI_LIMITS: Record<string, number> = {
free: 100,
pro: 5000,
master: 999999,
};
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
}
const prisma = getDB();
// Check AI usage limit from DB
const dbUser = await prisma.user.findUnique({
where: { id: session.user.id },
select: { plan: true, aiActionsUsed: true },
});
if (!dbUser) {
return NextResponse.json({ error: 'Utilisateur non trouvé' }, { status: 404 });
}
const limit = PLAN_AI_LIMITS[dbUser.plan] || PLAN_AI_LIMITS.free;
if (dbUser.aiActionsUsed >= limit) {
return NextResponse.json(
{ error: `Limite de ${limit} actions IA atteinte pour le plan ${dbUser.plan}. Passez au plan supérieur !` },
{ status: 403 }
);
}
const body = await request.json();
const { text, mode, context, user } = body;
@@ -17,7 +50,13 @@ export async function POST(request: NextRequest) {
const result = await transformTextServer(text, mode, context || '', user);
return NextResponse.json({ text: result });
// Increment usage in DB
await prisma.user.update({
where: { id: session.user.id },
data: { aiActionsUsed: { increment: 1 } },
});
return NextResponse.json({ text: result, aiActionsUsed: dbUser.aiActionsUsed + 1 });
} catch (error) {
console.error('AI transform error:', error);
return NextResponse.json(

View File

@@ -22,6 +22,13 @@ export async function GET() {
return NextResponse.json(projects);
}
// Plan limits for project creation
const PLAN_PROJECT_LIMITS: Record<string, number> = {
free: 3,
pro: 20,
master: 999,
};
// POST /api/projects — Create a new project
export async function POST(request: NextRequest) {
const session = await auth();
@@ -29,9 +36,24 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
}
const prisma = getDB();
// Check plan limit
const user = await prisma.user.findUnique({ where: { id: session.user.id }, select: { plan: true } });
const plan = user?.plan || 'free';
const limit = PLAN_PROJECT_LIMITS[plan] || PLAN_PROJECT_LIMITS.free;
const currentCount = await prisma.project.count({ where: { userId: session.user.id } });
if (currentCount >= limit) {
return NextResponse.json(
{ error: `Limite de ${limit} projets atteinte pour le plan ${plan}. Passez au plan supérieur !` },
{ status: 403 }
);
}
const body = await request.json();
const project = await getDB().project.create({
const project = await prisma.project.create({
data: {
title: body.title || 'Nouveau Roman',
author: body.author || session.user.name || 'Auteur',

View File

@@ -0,0 +1,74 @@
export const dynamic = 'force-dynamic';
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import getDB from '@/lib/prisma';
// GET /api/user/profile — Get current user profile with stats
export async function GET() {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
}
const prisma = getDB();
const user = await prisma.user.findUnique({
where: { id: session.user.id },
});
if (!user) {
return NextResponse.json({ error: 'Utilisateur non trouvé' }, { status: 404 });
}
// Compute total word count from all chapters content
const chapters = await prisma.chapter.findMany({
where: { project: { userId: session.user.id } },
select: { content: true },
});
const totalWords = chapters.reduce((total, chapter) => {
const text = (chapter.content || '').replace(/<[^>]*>/g, ' ').trim();
return total + (text ? text.split(/\s+/).length : 0);
}, 0);
return NextResponse.json({
id: user.id,
email: user.email,
name: user.name,
avatar: user.avatar,
bio: user.bio,
plan: user.plan,
aiActionsUsed: user.aiActionsUsed,
dailyWordGoal: user.dailyWordGoal,
writingStreak: user.writingStreak,
lastWriteDate: user.lastWriteDate,
createdAt: user.createdAt,
totalWords,
});
}
// PUT /api/user/profile — Update user profile
export async function PUT(request: NextRequest) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
}
const prisma = getDB();
const body = await request.json();
const data: Record<string, unknown> = {};
if (body.name !== undefined) data.name = body.name;
if (body.avatar !== undefined) data.avatar = body.avatar;
if (body.bio !== undefined) data.bio = body.bio;
if (body.dailyWordGoal !== undefined) data.dailyWordGoal = body.dailyWordGoal;
if (body.writingStreak !== undefined) data.writingStreak = body.writingStreak;
if (body.lastWriteDate !== undefined) data.lastWriteDate = body.lastWriteDate ? new Date(body.lastWriteDate) : null;
const updated = await prisma.user.update({
where: { id: session.user.id },
data,
});
return NextResponse.json(updated);
}

View File

@@ -39,10 +39,19 @@ export default function DashboardPage() {
router.push(`/project/${id}`);
}}
onCreate={async () => {
const id = await createProject();
if (id) {
setCurrentProjectId(id);
router.push(`/project/${id}`);
try {
const id = await createProject();
if (id) {
setCurrentProjectId(id);
router.push(`/project/${id}`);
}
} catch (err: any) {
if (err?.message?.includes('Limite')) {
alert(err.message);
router.push('/pricing');
} else {
alert('Erreur lors de la création du projet');
}
}
}}
onLogout={() => {

View File

@@ -6,151 +6,151 @@ import { BookProject, UserProfile } from '@/lib/types';
import { Plus, Book, Clock, Star, ChevronRight, LogOut, LayoutDashboard, User, Target, Flame, Edit3 } from 'lucide-react';
interface DashboardProps {
user: UserProfile;
projects: BookProject[];
onSelect: (id: string) => void;
onCreate: () => void;
onLogout: () => void;
onPricing: () => void;
onProfile: () => void;
user: UserProfile;
projects: BookProject[];
onSelect: (id: string) => void;
onCreate: () => void;
onLogout: () => void;
onPricing: () => void;
onProfile: () => void;
}
const Dashboard: React.FC<DashboardProps> = ({ user, projects, onSelect, onCreate, onLogout, onPricing, onProfile }) => {
return (
<div className="min-h-screen bg-[#eef2ff] p-8 font-sans">
<div className="max-w-6xl mx-auto space-y-8">
{/* User Card */}
<div className="flex flex-col md:flex-row justify-between items-center bg-white p-8 rounded-[2rem] shadow-sm border border-indigo-100 gap-6">
<div className="flex items-center gap-6">
<div className="relative">
<img src={user.avatar} className="w-20 h-20 rounded-full border-4 border-slate-50 shadow-lg object-cover" alt="Avatar" />
<div className="absolute -bottom-1 -right-1 bg-green-500 w-5 h-5 rounded-full border-4 border-white" />
</div>
<div>
<h2 className="text-3xl font-black text-slate-900">Bonjour, {user.name} 👋</h2>
<div className="flex items-center gap-3 mt-1">
<span className="px-3 py-1 rounded-full bg-indigo-100 text-indigo-700 text-[10px] uppercase font-black tracking-widest">{user.subscription.plan}</span>
<span className="text-slate-400 text-xs font-medium">Membre depuis le 24 janv.</span>
return (
<div className="min-h-screen bg-[#eef2ff] p-8 font-sans">
<div className="max-w-6xl mx-auto space-y-8">
{/* User Card */}
<div className="flex flex-col md:flex-row justify-between items-center bg-white p-8 rounded-[2rem] shadow-sm border border-indigo-100 gap-6">
<div className="flex items-center gap-6">
<div className="relative">
<img src={user.avatar} className="w-20 h-20 rounded-full border-4 border-slate-50 shadow-lg object-cover" alt="Avatar" />
<div className="absolute -bottom-1 -right-1 bg-green-500 w-5 h-5 rounded-full border-4 border-white" />
</div>
<div>
<h2 className="text-3xl font-black text-slate-900">Bonjour, {user.name} 👋</h2>
<div className="flex items-center gap-3 mt-1">
<span className="px-3 py-1 rounded-full bg-indigo-100 text-indigo-700 text-[10px] uppercase font-black tracking-widest">{user.subscription.plan}</span>
<span className="text-slate-400 text-xs font-medium">Membre depuis le 24 janv.</span>
</div>
</div>
</div>
<div className="flex items-center gap-3">
<button onClick={onProfile} className="bg-slate-50 text-slate-700 px-5 py-2.5 rounded-xl text-sm font-bold hover:bg-slate-100 transition-all flex items-center gap-2 border border-slate-200">
<User size={18} /> Mon Profil
</button>
<button onClick={onLogout} className="p-3 text-slate-400 hover:text-red-500 rounded-full hover:bg-red-50 transition-colors"><LogOut size={20} /></button>
</div>
</div>
</div>
<div className="flex items-center gap-3">
<button onClick={onProfile} className="bg-slate-50 text-slate-700 px-5 py-2.5 rounded-xl text-sm font-bold hover:bg-slate-100 transition-all flex items-center gap-2 border border-slate-200">
<User size={18} /> Mon Profil
</button>
<button onClick={onLogout} className="p-3 text-slate-400 hover:text-red-500 rounded-full hover:bg-red-50 transition-colors"><LogOut size={20} /></button>
</div>
</div>
{/* Stats Section */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-3xl shadow-sm border border-indigo-50 flex items-center gap-4">
<div className="bg-orange-100 p-3 rounded-2xl text-orange-600"><Flame size={24} /></div>
<div>
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Série actuelle</p>
<p className="text-2xl font-black text-slate-900">{user.stats.writingStreak} Jours</p>
</div>
</div>
<div className="bg-white p-6 rounded-3xl shadow-sm border border-indigo-50 flex items-center gap-4">
<div className="bg-blue-100 p-3 rounded-2xl text-blue-600"><Edit3 size={24} /></div>
<div>
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Mots écrits</p>
<p className="text-2xl font-black text-slate-900">{user.stats.totalWordsWritten.toLocaleString()}</p>
</div>
</div>
<div className="bg-white p-6 rounded-3xl shadow-sm border border-indigo-50 flex items-center gap-4">
<div className="bg-indigo-100 p-3 rounded-2xl text-indigo-600"><Target size={24} /></div>
<div>
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Objectif du jour</p>
<p className="text-2xl font-black text-slate-900">{user.preferences.dailyWordGoal} Mots</p>
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Project List */}
<div className="lg:col-span-2 space-y-4">
<div className="flex justify-between items-center mb-6">
<h3 className="text-2xl font-black text-slate-900">Mes Romans</h3>
<button
onClick={onCreate}
className="flex items-center gap-2 bg-blue-600 text-white px-6 py-3 rounded-2xl font-bold hover:bg-blue-700 transition-all shadow-xl shadow-blue-200"
>
<Plus size={20} /> Écrire un nouveau livre
</button>
{/* Stats Section */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-3xl shadow-sm border border-indigo-50 flex items-center gap-4">
<div className="bg-orange-100 p-3 rounded-2xl text-orange-600"><Flame size={24} /></div>
<div>
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Série actuelle</p>
<p className="text-2xl font-black text-slate-900">{user.stats.writingStreak} Jours</p>
</div>
</div>
<div className="bg-white p-6 rounded-3xl shadow-sm border border-indigo-50 flex items-center gap-4">
<div className="bg-blue-100 p-3 rounded-2xl text-blue-600"><Edit3 size={24} /></div>
<div>
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Mots écrits</p>
<p className="text-2xl font-black text-slate-900">{user.stats.totalWordsWritten.toLocaleString()}</p>
</div>
</div>
<div className="bg-white p-6 rounded-3xl shadow-sm border border-indigo-50 flex items-center gap-4">
<div className="bg-indigo-100 p-3 rounded-2xl text-indigo-600"><Target size={24} /></div>
<div>
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Objectif du jour</p>
<p className="text-2xl font-black text-slate-900">{user.preferences.dailyWordGoal} Mots</p>
</div>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{projects.map(p => (
<div
key={p.id}
onClick={() => onSelect(p.id)}
className="bg-white p-8 rounded-[2.5rem] border border-indigo-50 shadow-sm hover:shadow-2xl hover:scale-[1.02] transition-all cursor-pointer group flex flex-col justify-between h-64"
>
<div>
<div className="bg-blue-50 w-12 h-12 rounded-2xl flex items-center justify-center text-blue-600 mb-6 group-hover:bg-blue-600 group-hover:text-white transition-colors">
<Book size={24} />
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* Project List */}
<div className="lg:col-span-2 space-y-4">
<div className="flex justify-between items-center mb-6">
<h3 className="text-2xl font-black text-slate-900">Mes Romans</h3>
<button
onClick={onCreate}
className="flex items-center gap-2 bg-blue-600 text-white px-6 py-3 rounded-2xl font-bold hover:bg-blue-700 transition-all shadow-xl shadow-blue-200"
>
<Plus size={20} /> Écrire un nouveau livre
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{projects.map(p => (
<div
key={p.id}
onClick={() => onSelect(p.id)}
className="bg-white p-8 rounded-[2.5rem] border border-indigo-50 shadow-sm hover:shadow-2xl hover:scale-[1.02] transition-all cursor-pointer group flex flex-col justify-between h-64"
>
<div>
<div className="bg-blue-50 w-12 h-12 rounded-2xl flex items-center justify-center text-blue-600 mb-6 group-hover:bg-blue-600 group-hover:text-white transition-colors">
<Book size={24} />
</div>
<h4 className="font-black text-slate-900 text-xl truncate mb-1">{p.title}</h4>
<p className="text-slate-400 text-sm">Dernière modification : {new Date(p.lastModified).toLocaleDateString()}</p>
</div>
<div className="flex justify-between items-center text-[10px] text-slate-400 font-black uppercase tracking-widest border-t border-slate-50 pt-4">
<span>{p.chapters.length} Chapitres</span>
<ChevronRight size={20} className="group-hover:text-blue-600 transition-transform group-hover:translate-x-1 duration-300" />
</div>
</div>
<h4 className="font-black text-slate-900 text-xl truncate mb-1">{p.title}</h4>
<p className="text-slate-400 text-sm">Dernière modification : {new Date(p.lastModified).toLocaleDateString()}</p>
</div>
<div className="flex justify-between items-center text-[10px] text-slate-400 font-black uppercase tracking-widest border-t border-slate-50 pt-4">
<span>{p.chapters.length} Chapitres</span>
<ChevronRight size={20} className="group-hover:text-blue-600 transition-transform group-hover:translate-x-1 duration-300" />
</div>
</div>
))}
{projects.length === 0 && (
<div className="col-span-2 py-24 bg-white rounded-[3rem] border-2 border-dashed border-indigo-100 flex flex-col items-center justify-center text-indigo-300">
<Book size={64} className="mb-6 opacity-20" />
<p className="font-bold text-lg">Prêt à commencer votre premier roman ?</p>
<button onClick={onCreate} className="mt-4 text-blue-600 font-bold hover:underline">Créer un projet maintenant</button>
</div>
)}
</div>
</div>
{/* Sidebar Stats & Plan */}
<div className="space-y-6">
<div className="bg-slate-900 text-white p-8 rounded-[2.5rem] shadow-xl relative overflow-hidden">
<div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/20 blur-[60px] -z-1" />
<h3 className="font-black text-xl mb-6 flex items-center gap-2"><Star size={20} className="text-yellow-400" /> Utilisation</h3>
<div className="space-y-8">
<div>
<div className="flex justify-between text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">
<span>Actions IA</span>
<span>{user.usage.aiActionsCurrent} / {user.usage.aiActionsLimit === 999999 ? '∞' : user.usage.aiActionsLimit}</span>
</div>
<div className="h-3 w-full bg-slate-800 rounded-full overflow-hidden">
<div
className="h-full bg-blue-500 transition-all duration-1000 shadow-[0_0_10px_rgba(59,130,246,0.5)]"
style={{ width: `${Math.min(100, (user.usage.aiActionsCurrent / user.usage.aiActionsLimit) * 100)}%` }}
/>
</div>
</div>
<div>
<div className="flex justify-between text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">
<span>Emplacements Roman</span>
<span>{projects.length} / {user.usage.projectsLimit}</span>
</div>
<div className="h-3 w-full bg-slate-800 rounded-full overflow-hidden">
<div
className="h-full bg-indigo-500 transition-all duration-1000 shadow-[0_0_10px_rgba(99,102,241,0.5)]"
style={{ width: `${Math.min(100, (projects.length / user.usage.projectsLimit) * 100)}%` }}
/>
</div>
))}
{projects.length === 0 && (
<div className="col-span-2 py-24 bg-white rounded-[3rem] border-2 border-dashed border-indigo-100 flex flex-col items-center justify-center text-indigo-300">
<Book size={64} className="mb-6 opacity-20" />
<p className="font-bold text-lg">Prêt à commencer votre premier roman ?</p>
<button onClick={onCreate} className="mt-4 text-blue-600 font-bold hover:underline">Créer un projet maintenant</button>
</div>
)}
</div>
</div>
{/* Sidebar Stats & Plan */}
<div className="space-y-6">
<div className="bg-slate-900 text-white p-8 rounded-[2.5rem] shadow-xl relative overflow-hidden">
<div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/20 blur-[60px] -z-1" />
<h3 className="font-black text-xl mb-6 flex items-center gap-2"><Star size={20} className="text-yellow-400" /> Utilisation</h3>
<div className="space-y-8">
<div>
<div className="flex justify-between text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">
<span>Actions IA</span>
<span>{user.usage.aiActionsCurrent} / {user.usage.aiActionsLimit === 999999 ? '∞' : user.usage.aiActionsLimit}</span>
</div>
<div className="h-3 w-full bg-slate-800 rounded-full overflow-hidden">
<div
className="h-full bg-blue-500 transition-all duration-1000 shadow-[0_0_10px_rgba(59,130,246,0.5)]"
style={{ width: `${Math.min(100, (user.usage.aiActionsCurrent / user.usage.aiActionsLimit) * 100)}%` }}
/>
</div>
</div>
<div>
<div className="flex justify-between text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">
<span>Emplacements Roman</span>
<span>{projects.length} / {user.usage.projectsLimit}</span>
</div>
<div className="h-3 w-full bg-slate-800 rounded-full overflow-hidden">
<div
className="h-full bg-indigo-500 transition-all duration-1000 shadow-[0_0_10px_rgba(99,102,241,0.5)]"
style={{ width: `${Math.min(100, (projects.length / user.usage.projectsLimit) * 100)}%` }}
/>
</div>
</div>
</div>
<button onClick={onPricing} className="w-full mt-10 bg-white/10 hover:bg-white/20 py-4 rounded-2xl text-sm font-bold transition-all">
Upgrade Plan
</button>
</div>
</div>
<button onClick={onPricing} className="w-full mt-10 bg-white/10 hover:bg-white/20 py-4 rounded-2xl text-sm font-bold transition-all">
Upgrade Plan
</button>
</div>
</div>
</div>
</div>
</div>
);
);
};
export default Dashboard;

View File

@@ -78,9 +78,19 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
const filename = project.title.replace(/[^a-z0-9]/gi, '_').toLowerCase();
if (format === 'pdf') {
// Use the classic window print tool via parent callback
onPrint({ includeCover, includeTOC });
}
// Open print dialog with the formatted content
const content = generateContentHTML();
const printWindow = window.open('', '_blank');
if (printWindow) {
printWindow.document.write(content);
printWindow.document.close();
printWindow.focus();
setTimeout(() => {
printWindow.print();
}, 300);
}
onClose();
}
else if (format === 'word') {
// Export as HTML with specific Word namespaces -> interpreted as doc by Word
const content = generateContentHTML();
@@ -88,7 +98,7 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
type: 'application/msword'
});
downloadBlob(blob, `${filename}.doc`);
}
}
else if (format === 'epub') {
// Export as a single XHTML file (Ebook ready)
const content = generateContentHTML();
@@ -98,14 +108,14 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
downloadBlob(blob, `${filename}.xhtml`);
}
else if (format === 'markdown') {
let md = `# ${project.title}\nBy ${project.author}\n\n`;
project.chapters.forEach(c => {
// Very basic HTML to Text conversion
const text = c.content.replace(/<[^>]+>/g, '\n');
md += `## ${c.title}\n\n${text}\n\n---\n\n`;
});
const blob = new Blob([md], { type: 'text/markdown' });
downloadBlob(blob, `${filename}.md`);
let md = `# ${project.title}\nBy ${project.author}\n\n`;
project.chapters.forEach(c => {
// Very basic HTML to Text conversion
const text = c.content.replace(/<[^>]+>/g, '\n');
md += `## ${c.title}\n\n${text}\n\n---\n\n`;
});
const blob = new Blob([md], { type: 'text/markdown' });
downloadBlob(blob, `${filename}.md`);
}
};
@@ -124,7 +134,7 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-in fade-in duration-200 no-print">
<div className="bg-white rounded-xl shadow-2xl w-[600px] overflow-hidden flex flex-col max-h-[90vh]">
{/* Header */}
<div className="bg-slate-900 text-white p-6 flex justify-between items-center">
<div>
@@ -140,18 +150,18 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
{/* Body */}
<div className="p-6 overflow-y-auto flex-1">
{/* Format Selection */}
<div className="grid grid-cols-2 gap-4 mb-8">
<button
<button
onClick={() => setFormat('pdf')}
className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'pdf' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
>
<Printer size={32} />
<div className="font-semibold">PDF (Impression)</div>
</button>
<button
<button
onClick={() => setFormat('word')}
className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'word' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
>
@@ -159,7 +169,7 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
<div className="font-semibold">Microsoft Word</div>
</button>
<button
<button
onClick={() => setFormat('epub')}
className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'epub' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
>
@@ -167,7 +177,7 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
<div className="font-semibold">EPUB / Ebook</div>
</button>
<button
<button
onClick={() => setFormat('markdown')}
className={`p-4 rounded-lg border-2 flex flex-col items-center gap-3 transition-all ${format === 'markdown' ? 'border-blue-600 bg-blue-50 text-blue-800' : 'border-slate-200 hover:border-slate-300 text-slate-600'}`}
>
@@ -186,8 +196,8 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
{format === 'pdf' && (
<div className="flex items-center justify-between">
<div className="flex flex-col">
<label className="text-slate-700 font-medium">Format du papier</label>
<span className="text-xs text-slate-400">Géré par l'imprimante (A4, A5...)</span>
<label className="text-slate-700 font-medium">Format du papier</label>
<span className="text-xs text-slate-400">Géré par l'imprimante (A4, A5...)</span>
</div>
<div className="bg-slate-200 px-3 py-1 rounded text-xs font-mono text-slate-600">Auto</div>
</div>
@@ -195,9 +205,9 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
<div className="flex items-center justify-between">
<label className="text-slate-700 font-medium cursor-pointer" htmlFor="cover">Inclure la page de titre</label>
<input
<input
id="cover"
type="checkbox"
type="checkbox"
checked={includeCover}
onChange={(e) => setIncludeCover(e.target.checked)}
className="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
@@ -206,9 +216,9 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
<div className="flex items-center justify-between">
<label className="text-slate-700 font-medium cursor-pointer" htmlFor="toc">Générer la table des matières</label>
<input
<input
id="toc"
type="checkbox"
type="checkbox"
checked={includeTOC}
onChange={(e) => setIncludeTOC(e.target.checked)}
className="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
@@ -216,9 +226,9 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
</div>
{format === 'epub' && (
<p className="text-xs text-amber-600 bg-amber-50 p-2 rounded mt-2">
Note: L'export EPUB génère un fichier XHTML optimisé prêt à être converti par Calibre ou Kindle Previewer.
</p>
<p className="text-xs text-amber-600 bg-amber-50 p-2 rounded mt-2">
Note: L'export EPUB génère un fichier XHTML optimisé prêt à être converti par Calibre ou Kindle Previewer.
</p>
)}
</div>
</div>
@@ -226,13 +236,13 @@ const ExportModal: React.FC<ExportModalProps> = ({ isOpen, onClose, project, onP
{/* Footer */}
<div className="p-4 border-t border-slate-200 bg-slate-50 flex justify-end gap-3">
<button
<button
onClick={onClose}
className="px-5 py-2 text-slate-600 hover:bg-slate-200 rounded-lg font-medium transition-colors"
>
Annuler
</button>
<button
<button
onClick={handleExport}
className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium shadow-md transition-all flex items-center gap-2"
>

View File

@@ -2,26 +2,62 @@
import { useState, useEffect, useCallback } from 'react';
import { signIn, signOut, useSession } from 'next-auth/react';
import { UserProfile } from '@/lib/types';
import { UserProfile, PlanType } from '@/lib/types';
import api from '@/lib/api';
const PLAN_LIMITS: Record<string, { aiActions: number; projects: number }> = {
free: { aiActions: 100, projects: 3 },
pro: { aiActions: 5000, projects: 20 },
master: { aiActions: 999999, projects: 999 },
};
export const useAuth = () => {
const { data: session, status } = useSession();
const [user, setUser] = useState<UserProfile | null>(null);
const loading = status === 'loading';
// Sync session to UserProfile
// Fetch real profile from DB when session is available
useEffect(() => {
if (session?.user) {
setUser({
id: session.user.id || '',
email: session.user.email || '',
name: session.user.name || 'User',
subscription: { plan: 'free', startDate: Date.now(), status: 'active' },
usage: { aiActionsCurrent: 0, aiActionsLimit: 100, projectsLimit: 3 },
preferences: { theme: 'light', dailyWordGoal: 500, language: 'fr' },
stats: { totalWordsWritten: 0, writingStreak: 0, lastWriteDate: 0 },
});
if (session?.user?.id) {
fetch('/api/user/profile')
.then(res => res.json())
.then(dbUser => {
const plan = (dbUser.plan || 'free') as PlanType;
const limits = PLAN_LIMITS[plan] || PLAN_LIMITS.free;
setUser({
id: dbUser.id,
email: dbUser.email,
name: dbUser.name || 'User',
avatar: dbUser.avatar,
bio: dbUser.bio,
subscription: { plan, startDate: new Date(dbUser.createdAt).getTime(), status: 'active' },
usage: {
aiActionsCurrent: dbUser.aiActionsUsed || 0,
aiActionsLimit: limits.aiActions,
projectsLimit: limits.projects,
},
preferences: { theme: 'light', dailyWordGoal: dbUser.dailyWordGoal || 500, language: 'fr' },
stats: {
totalWordsWritten: dbUser.totalWords || 0,
writingStreak: dbUser.writingStreak || 0,
lastWriteDate: dbUser.lastWriteDate ? new Date(dbUser.lastWriteDate).getTime() : 0,
},
});
})
.catch(err => {
console.error('Failed to fetch user profile:', err);
// Fallback to session data
setUser({
id: session.user.id || '',
email: session.user.email || '',
name: session.user.name || 'User',
subscription: { plan: 'free', startDate: Date.now(), status: 'active' },
usage: { aiActionsCurrent: 0, aiActionsLimit: 100, projectsLimit: 3 },
preferences: { theme: 'light', dailyWordGoal: 500, language: 'fr' },
stats: { totalWordsWritten: 0, writingStreak: 0, lastWriteDate: 0 },
});
});
} else if (status === 'unauthenticated') {
setUser(null);
}
@@ -43,16 +79,12 @@ export const useAuth = () => {
}, []);
const signup = useCallback(async (email: string, password: string, name: string) => {
// 1. Register via API
await api.auth.register(email, password, name);
// 2. Auto-login
const result = await signIn('credentials', {
email,
password,
redirect: false,
});
if (result?.error) {
throw new Error('Compte créé mais erreur de connexion automatique');
}
@@ -63,11 +95,14 @@ export const useAuth = () => {
setUser(null);
}, []);
const incrementUsage = useCallback(() => {
const incrementUsage = useCallback((serverCount?: number) => {
if (user) {
setUser({
...user,
usage: { ...user.usage, aiActionsCurrent: user.usage.aiActionsCurrent + 1 },
usage: {
...user.usage,
aiActionsCurrent: serverCount !== undefined ? serverCount : user.usage.aiActionsCurrent + 1,
},
});
}
}, [user]);

View File

@@ -35,8 +35,9 @@ export const useProjects = (user: UserProfile | null) => {
title: p.title,
author: p.author,
lastModified: new Date(p.updatedAt).getTime(),
chapters: [],
entities: [],
// Use _count for display before full details are loaded
chapters: Array.from({ length: p._count?.chapters || 0 }, (_, i) => ({ id: `placeholder-${i}`, title: '', content: '' })),
entities: Array.from({ length: p._count?.entities || 0 }, (_, i) => ({ id: `placeholder-${i}`, type: 'character' as any, name: '', description: '' })),
ideas: [],
settings: p.settings || undefined
}));
@@ -139,6 +140,7 @@ export const useProjects = (user: UserProfile | null) => {
return created.id;
} catch (err) {
console.error('Failed to create project', err);
throw err;
}
};