You are an AI assistant tasked with generating a fully functional, multi-page Next.js MVP application for 'LegacyCode Optimize'. This application will help businesses analyze and optimize their legacy codebases. The goal is to create a robust MVP that goes beyond a simple landing page, incorporating database integration, user authentication, and core CRUD functionalities.
**1. PROJECT OVERVIEW:**
LegacyCode Optimize is a SaaS platform designed to address the significant challenge businesses face with outdated, inefficient, and resource-intensive legacy code. Inspired by the resourcefulness of systems like Voyager 1, our application will analyze user-uploaded code snippets or repositories to identify performance bottlenecks, suggest modernization strategies (e.g., refactoring, library updates, technology migration), and estimate potential cost savings. The core value proposition is enabling companies to reduce technical debt, improve system efficiency, and lower operational costs associated with maintaining legacy systems.
**2. TECH STACK:**
- **Frontend Framework:** React with Next.js (App Router)
- **Styling:** Tailwind CSS for rapid UI development.
- **UI Components:** shadcn/ui for a set of beautiful, accessible, and customizable components.
- **ORM:** Drizzle ORM for type-safe database interactions.
- **Database:** PostgreSQL (recommended for production, SQLite can be used for local development via Drizzle).
- **Authentication:** NextAuth.js (or Lucia Auth) for secure user authentication (email/password, OAuth).
- **State Management:** Zustand or React Context API for global state management.
- **API Layer:** Next.js API Routes (or Server Actions) for backend logic.
- **Deployment:** Vercel (recommended for Next.js)
- **Other Libraries:** Axios (for API calls), React Hook Form (for form handling), Zod (for schema validation).
**3. DATABASE SCHEMA (using Drizzle ORM syntax for PostgreSQL):**
```typescript
// schema.ts
import { pgTable, serial, varchar, text, timestamp, integer, uuid, primaryKey, foreignKey, boolean } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// User Table
export const users = pgTable('users', {
id: uuid('id').primaryKey(),
name: varchar('name'),
email: varchar('email', { length: 255 }).notNull().unique(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: varchar('image'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
export const accounts = pgTable('accounts', {
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
type: varchar('type', { length: 100 }).$type<"oauth" | "email" | "apple" | "google">().notNull(),
provider: varchar('provider', { length: 100 }).notNull(),
providerAccountId: varchar('providerAccountId', { length: 255 }).notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: varchar('token_type', { length: 50 }),
scope: varchar('scope', { length: 255 }),
id_token: text('id_token'),
session_state: varchar('session_state', { length: 255 }),
}, (t) => ({ pk: primaryKey(t.provider, t.providerAccountId) }));
export const sessions = pgTable('sessions', {
sessionToken: varchar('sessionToken', { length: 255 }).primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
expires: timestamp('expires', { mode: 'date' }).notNull(),
});
export const verificationTokens = pgTable('verificationTokens', {
identifier: varchar('identifier', { length: 255 }).notNull(),
token: varchar('token', { length: 255 }).notNull(),
expires: timestamp('expires', { mode: 'date' }).notNull(),
}, (t) => ({ pk: primaryKey(t.identifier, t.token) }));
// Projects Table
export const projects = pgTable('projects', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 255 }).notNull(),
description: text('description'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Code Analysis Table
export const analyses = pgTable('analyses', {
id: uuid('id').primaryKey(),
projectId: uuid('projectId').notNull().references(() => projects.id, { onDelete: 'cascade' }),
submittedCode: text('submittedCode'), // Can store snippet or reference to uploaded file
language: varchar('language', { length: 50 }), // e.g., 'javascript', 'python', 'java'
status: varchar('status', { length: 50 }).default('pending'), // e.g., 'pending', 'analyzing', 'completed', 'failed'
results: text('results'), // JSON string of analysis results
createdAt: timestamp('createdAt').defaultNow(),
completedAt: timestamp('completedAt'),
});
// Relations
export const usersRelations = relations(users, ({ many }) => ({
projects: many(projects)
}));
export const projectsRelations = relations(projects, ({ one, many }) => ({
user: one(users, { fields: [projects.userId], relations: [usersRelations] }),
analyses: many(analyses)
}));
export const analysesRelations = relations(analyses, ({ one }) => ({
project: one(projects, { fields: [analyses.projectId], relations: [projectsRelations] })
}));
// Define your Drizzle database instance (e.g., using drizzle-orm/pg-adapter)
// import { Pool } from 'pg';
// import { drizzle } from 'drizzle-orm/pg-adapter';
// const pool = new Pool({ connectionString: process.env.DATABASE_URL });
// export const db = drizzle(pool);
```
**4. CORE FEATURES & USER FLOW:**
* **User Authentication:**
* Flow: User lands on the homepage -> Clicks 'Sign Up' or 'Login' -> Redirected to Auth page (using NextAuth.js callbacks) -> Enters credentials (email/password) or uses OAuth (Google/GitHub) -> Redirected to Dashboard upon successful login.
* Edge Cases: Incorrect credentials, account lockout, email verification pending, OAuth provider errors.
* **Project Creation:**
* Flow: Logged-in user navigates to 'Projects' page -> Clicks 'New Project' button -> A modal appears with fields for 'Project Name' and 'Description' -> User fills details and clicks 'Create' -> Project is saved to the database and the user is redirected to the project's detail page.
* Validation: Project name is required and must be unique per user.
* **Code Analysis Submission:**
* Flow: User navigates to a specific project's page -> Clicks 'Analyze Code' -> A modal/page appears with options: paste code snippet or upload a file (e.g., .zip, .tar.gz containing source code) -> User selects language (auto-detection preferred, manual override possible) -> Clicks 'Submit for Analysis' -> An 'Analysis' record is created in the DB with status 'pending' -> A background job/server action is triggered to process the code.
* Edge Cases: Invalid file format, unsupported language, excessively large upload, missing code.
* **Analysis Processing (Background Job/Server Action):**
* Flow: A trigger (e.g., queue message, direct server action) picks up 'pending' analysis tasks -> Updates status to 'analyzing' -> Executes the chosen analysis engine (could be a custom script, a third-party API, or internal logic) -> Parses the output into a structured JSON format -> Updates the 'results' field and status to 'completed' in the 'analyses' table.
* Error Handling: If analysis fails, update status to 'failed' and log the error details.
* **Viewing Analysis Results:**
* Flow: User navigates to a project -> Clicks on a completed analysis in the project's analysis list -> Redirected to the Analysis Results page -> Displays a summary of findings, performance metrics, modernization suggestions, and estimated cost impact, presented using various UI components (tables, charts, lists).
* Data Display: Show 'before/after' if applicable, highlight critical issues.
**5. API & DATA FETCHING:**
- **NextAuth.js Endpoints:** Handled by the library (`/api/auth/[...nextauth]`).
- **Project API Routes/Server Actions:**
- `POST /api/projects`: Create a new project.
- `GET /api/projects`: Get list of user's projects.
- `GET /api/projects/[projectId]`: Get details of a specific project.
- `PUT /api/projects/[projectId]`: Update project details.
- `DELETE /api/projects/[projectId]`: Delete a project.
- **Analysis API Routes/Server Actions:**
- `POST /api/projects/[projectId]/analyses`: Submit a new code analysis.
- `GET /api/analyses/[analysisId]`: Get details and results of a specific analysis.
- **Data Fetching:** Utilize `fetch` within Server Components where possible for direct data access. Use client-side fetching (Axios or `fetch` in `useEffect`) in Client Components, potentially with libraries like SWR or React Query for caching and state management.
- **Request/Response:** Standard JSON payloads. Use Zod for request validation on API routes.
**6. COMPONENT BREAKDOWN (Next.js App Router Structure):**
- **`app/` directory:**
- **`(auth)/` group:**
- `layout.tsx`: Auth layout (centered card, minimal).
- `login/page.tsx`: Login form component.
- `signup/page.tsx`: Signup form component.
- **`(app)/` group (Protected Routes):
- `layout.tsx`: Main application layout with sidebar/header.
- `dashboard/page.tsx`: Overview of projects, recent analyses, quick stats. Fetches project list and recent analysis summaries.
- `projects/page.tsx`: List of all user projects. Includes 'New Project' button and project cards. Fetches user projects.
- `projects/[projectId]/page.tsx`: Project detail page. Shows project info, list of analyses for this project, 'Analyze Code' button.
- Components: `ProjectDetailHeader`, `AnalysisList`, `NewAnalysisFormModal`.
- `analyses/[analysisId]/page.tsx`: Detailed results page for a specific analysis.
- Components: `AnalysisResultsSummary`, `PerformanceMetricsChart` (using a charting library), `ModernizationSuggestionsList`, `CodeSnippetViewer`.
- `settings/page.tsx`: User profile and settings management.
- **`page.tsx`:** Public homepage/landing page (initially, can be enhanced later).
- **`layout.tsx`:** Root layout (html, body, providers).
- **`components/` directory:**
- **`ui/`:** Re-export of shadcn/ui components (`Button`, `Card`, `Input`, `Label`, `Form`, `Dialog`, `Table`, `Tabs`, `Alert`, `Spinner`, `Avatar`, etc.).
- **`auth/`:** Auth related components (`LoginForm`, `SignupForm`, `OAuthButtons`).
- **`projects/`:** `ProjectCard`, `ProjectForm`, `ProjectList`.
- **`analyses/`:** `AnalysisListItem`, `AnalysisResultsViewer`, `CodeUploader`.
- **`layout/`:** `Sidebar`, `Header`, `Footer`.
- **`common/`:** `Spinner`, `ErrorDisplay`, `EmptyState`, `DataTable`.
- **`lib/`:** Helper functions, API clients, Drizzle setup, validation schemas (Zod).
- **`hooks/`:** Custom React hooks.
- **`styles/`:** Global CSS imports.
- **`actions/`:** Server Actions for mutations (e.g., creating projects, submitting analysis).
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** "Modern Professional". Clean, minimalist aesthetic with a focus on clarity and data visualization. Subtle use of gradients and depth.
- **Color Palette:**
- Primary: `#0E7490` (Deep Cyan/Teal)
- Secondary: `#3B82F6` (Bright Blue)
- Accent: `#10B981` (Emerald Green for success states)
- Background: `#F9FAFB` (Light Gray)
- Card/Surface: `#FFFFFF` (White)
- Text (Primary): `#1F2937` (Dark Gray)
- Text (Secondary): `#6B7280` (Medium Gray)
- Alert/Error: `#EF4444` (Red)
- **Typography:** Use a sans-serif font like Inter or Poppins for readability. Clear hierarchy with distinct heading sizes.
- **Layout:** Use a two-column layout for most pages within the app group: a persistent sidebar for navigation and a main content area. Utilize cards for displaying project summaries and analysis overviews. Ensure responsive design for all screen sizes.
- **Branding:** Logo should be abstract, suggesting code or optimization (e.g., stylized brackets, upward trend arrow). Name 'LegacyCode Optimize' should be prominent in headers/nav.
**8. SAMPLE/MOCK DATA:**
* **User:** `{
id: 'user-123',
name: 'John Doe',
email: 'john.doe@example.com',
image: 'https://example.com/avatar.jpg'
}`
* **Project:** `{
id: 'proj-abc',
userId: 'user-123',
name: 'Core Banking System',
description: 'Maintains customer accounts and transactions.',
createdAt: '2023-10-26T10:00:00Z'
}`
* **Completed Analysis:** `{
id: 'analysis-xyz',
projectId: 'proj-abc',
language: 'java',
status: 'completed',
results: JSON.stringify({
summary: 'High memory usage detected in transaction processing module.',
metrics: {
cpu: '65%',
memory: '85%',
io: 'Medium'
},
suggestions: [
{ title: 'Refactor TransactionManager Class', description: 'Optimize loops and data structures.', severity: 'high', estimatedEffort: '2 weeks' },
{ title: 'Update Spring Boot Version', description: 'Upgrade to latest stable version for performance improvements.', severity: 'medium', estimatedEffort: '1 week' }
],
potentialSavings: '$50,000 / year'
}),
createdAt: '2023-10-26T11:00:00Z',
completedAt: '2023-10-26T11:15:00Z'
}`
* **Pending Analysis:** `{
id: 'analysis-pqr',
projectId: 'proj-abc',
language: 'javascript',
status: 'pending',
results: null,
createdAt: '2023-10-27T09:00:00Z',
completedAt: null
}`
* **Failed Analysis:** `{
id: 'analysis-def',
projectId: 'proj-abc',
language: 'python',
status: 'failed',
results: JSON.stringify({ error: 'Unsupported Python version 2.7 detected. Please use Python 3.x.' }),
createdAt: '2023-10-25T14:00:00Z',
completedAt: '2023-10-25T14:05:00Z'
}`
**9. TURKISH TRANSLATIONS:**
* **App Title:** Legacy Kodu Optimize Et
* **Homepage:** Ana Sayfa
* **Login:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Dashboard:** Kontrol Paneli
* **Projects:** Projelerim
* **New Project:** Yeni Proje
* **Analyze Code:** Kodu Analiz Et
* **Project Name:** Proje Adı
* **Description:** Açıklama
* **Analysis Results:** Analiz Sonuçları
* **Status:** Durum
* **Pending:** Bekliyor
* **Analyzing:** Analiz Ediliyor
* **Completed:** Tamamlandı
* **Failed:** Başarısız
* **Settings:** Ayarlar
* **Submit:** Gönder
* **Cancel:** İptal
* **View Details:** Detayları Gör
* **Modernization Suggestions:** Modernizasyon Önerileri
* **Performance Metrics:** Performans Metrikleri
* **Potential Savings:** Potansiyel Tasarruf
* **Code Snippet:** Kod Parçacığı
* **Upload File:** Dosya Yükle
* **Select Language:** Dil Seçin
* **Save:** Kaydet
* **Edit:** Düzenle
* **Delete:** Sil
* **Are you sure?** Emin misin?
**10. ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/fade-out or slide animations between pages using Next.js's built-in capabilities or a library like `Framer Motion`.
- **Loading States:** Use `shadcn/ui`'s `Spinner` or skeleton loaders for indeterminate loading states (e.g., fetching data, submitting analysis). Add subtle animations to buttons during submission.
- **Hover Effects:** Gentle scaling or background color changes on interactive elements like buttons and cards.
- **Data Updates:** Animate chart updates if new data is loaded.
**11. EDGE CASES:**
- **Authentication:** Handle `unauthenticated` state gracefully, redirecting to login. Implement role-based access control if needed later.
- **Empty States:** Display user-friendly messages and calls to action when lists are empty (e.g., 'No projects yet. Create your first project!').
- **Form Validation:** Use Zod and React Hook Form for robust client-side and server-side validation. Provide clear error messages next to fields.
- **API Errors:** Implement global error handling for API requests, displaying user-friendly messages (e.g., using a toast notification system).
- **Data Integrity:** Ensure database constraints are respected (e.g., unique project names per user). Use transactions for multi-step database operations.
- **File Uploads:** Implement robust handling for file uploads, including size limits, type validation, and secure storage (e.g., using cloud storage like AWS S3 or Vercel Blob).
- **Code Analysis Failures:** Provide clear feedback to the user when analysis fails, including any error messages returned by the analysis engine.