You are an AI assistant tasked with generating a fully functional, multi-page Next.js MVP application for a SaaS product called 'CodeGuard Pro'. This application aims to help software development teams, particularly those with less mature technical infrastructure, adopt best practices in version control, code quality, and deployment.
PROJECT OVERVIEW:
CodeGuard Pro addresses the critical issue of technical debt and inefficient development workflows caused by the lack of proper version control, inconsistent coding standards, and manual, error-prone deployment processes. The problem is exemplified by teams deploying code via thumb drives without version control, struggling with complex technical challenges like AR rendering due to a lack of fundamental development practices. CodeGuard Pro will integrate with code repositories (GitHub, GitLab, Bitbucket), automatically detect the absence or misuse of version control, flag basic code quality issues, analyze deployment methods, and provide educational resources. The core value proposition is to provide an automated, easy-to-adopt solution that elevates a team's development maturity, reduces errors, and improves overall project efficiency and maintainability.
TECH STACK:
- **Framework:** Next.js (App Router)
- **Frontend:** React, Tailwind CSS, shadcn/ui (for pre-built, accessible components)
- **ORM:** Drizzle ORM (PostgreSQL as the database)
- **Authentication:** NextAuth.js (for secure authentication, supporting GitHub and email/password)
- **Database:** PostgreSQL (via Vercel Postgres or a similar managed service)
- **State Management:** React Context API and Server State (e.g., `use` hook in App Router)
- **Deployment:** Vercel (recommended for seamless Next.js deployment)
- **Other Packages:** `zod` for schema validation, `react-hook-form` for form management, `clsx` for conditional class names, `date-fns` for date manipulation.
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. **`users` table:**
* `id` (uuid, primary key, default generated)
* `name` (text)
* `email` (text, unique)
* `emailVerified` (timestampz)
* `image` (text, optional)
* `createdAt` (timestampz, default now())
* `updatedAt` (timestampz, default now())
2. **`accounts` table (for NextAuth.js):
* `id` (bigint, primary key, auto increment)
* `userId` (uuid, foreign key to users.id)
* `type` (text, e.g., 'oauth', 'credentials')
* `provider` (text)
* `providerAccountId` (text)
* `refresh_token` (text, optional)
* `access_token` (text, optional)
* `expires_at` (bigint, optional)
* `token_type` (text, optional)
* `scope` (text, optional)
* `id_token` (text, optional)
* `session_state` (text, optional)
3. **`sessions` table (for NextAuth.js):
* `sessionToken` (text, primary key)
* `userId` (uuid, foreign key to users.id)
* `expires` (timestampz)
4. **`verificationTokens` table (for NextAuth.js):
* `identifier` (text)
* `token` (text, primary key)
* `expires` (timestampz)
5. **`teams` table:**
* `id` (uuid, primary key, default generated)
* `name` (text, not null)
* `ownerId` (uuid, foreign key to users.id, not null)
* `createdAt` (timestampz, default now())
6. **`teamMembers` table (Many-to-Many relation between users and teams):
* `teamId` (uuid, foreign key to teams.id, not null)
* `userId` (uuid, foreign key to users.id, not null)
* `role` (text, e.g., 'admin', 'member', default 'member')
* `joinedAt` (timestampz, default now())
* Primary Key (`teamId`, `userId`)
7. **`repositories` table:**
* `id` (uuid, primary key, default generated)
* `teamId` (uuid, foreign key to teams.id, not null)
* `gitProvider` (enum: 'github', 'gitlab', 'bitbucket')
* `repoOwner` (text, not null)
* `repoName` (text, not null)
* `accessToken` (text) // Store encrypted access token for the provider
* `lastAnalysis` (timestampz, optional)
* `hasVersionControl` (boolean, default false)
* `issuesDetected` (integer, default 0)
* `createdAt` (timestampz, default now())
* Unique Constraint (`teamId`, `gitProvider`, `repoOwner`, `repoName`)
8. **`analysisResults` table:**
* `id` (uuid, primary key, default generated)
* `repositoryId` (uuid, foreign key to repositories.id, not null)
* `analysisType` (enum: 'version_control', 'code_quality', 'deployment_method')
* `result` (jsonb) // Stores detailed findings (e.g., { "detected": false, "message": "Git repository not detected." } or { "score": 75, "rules_failed": ["INDENTATION_STYLE"] })
* `timestamp` (timestampz, default now())
CORE FEATURES & USER FLOW:
1. **Authentication Flow:**
* **Guest User:** Lands on the marketing/pricing page. Sees options to Sign Up or Log In.
* **Sign Up:** User clicks 'Sign Up'. Presented with options: 'Continue with GitHub' or 'Sign Up with Email'.
* **GitHub Sign Up/In:** User clicks 'Continue with GitHub'. Redirected to GitHub OAuth. Upon successful authentication, a new user record is created (if not exists), and the user is redirected to the dashboard.
* **Email Sign Up:** User enters Name, Email, Password. `zod` validation on the form. Email verification link sent (future enhancement, for MVP, assume valid email). User record created. Redirected to dashboard.
* **Login:** User enters Email and Password. Credentials verified against the `users` table. Redirected to dashboard.
* **Team Creation (First Login):** If the user has no teams, prompt to create a team. User enters Team Name. A new team is created, user is added as 'admin' member.
* **Dashboard:** Displays an overview of connected repositories, recent analysis results, and quick links to add new repositories or manage settings.
2. **Repository Integration & Analysis:**
* **User Action:** Navigates to 'Settings' > 'Repositories' > 'Add Repository'.
* **Provider Selection:** User chooses GitHub, GitLab, or Bitbucket.
* **Authentication:** User is prompted to authorize CodeGuard Pro via the chosen provider's OAuth flow (requires setting up OAuth apps on provider platforms). A token is securely stored (encrypted or handled via secure backend storage).
* **Repository Selection:** User selects one or more repositories to connect from their account.
* **Initial Analysis:** Upon connection, the backend triggers an initial analysis for the selected repository.
* **Analysis Process (Backend):**
* **Version Control Check:** Fetches repository metadata. Checks for `.git` directory presence (via API if possible, or infers from repo structure/commit history if not directly accessible). Sets `hasVersionControl` flag in `repositories` table. Logs result to `analysisResults`.
* **Code Quality Check (Basic MVP):** Analyzes file structure against predefined simple rules (e.g., presence of `src/` or `app/` folder, consistent naming conventions for top-level files like `README.md`). More complex linting is out of MVP scope. Logs result to `analysisResults`.
* **Deployment Method Analysis (Heuristic):** This is challenging via API alone. For MVP, we can infer based on commit frequency, branch activity, and potentially comments/issue discussions if the API allows. A more robust MVP might rely on user input or integrations with CI/CD tools (future). For now, flag repositories with suspiciously low commit activity or lack of established CI/CD pipeline indicators (e.g., no `.github/workflows` or `.gitlab-ci.yml`). Logs result to `analysisResults`.
* **Display Results:** The dashboard and repository detail pages show the analysis status and findings. Visual indicators (e.g., green checkmarks, red warning icons) are used.
3. **Dashboard & Reporting:**
* **Overview:** Displays a summary of all connected repositories, highlighting those failing basic checks.
* **Repository Detail View:** Clicking a repository shows detailed analysis results, including specific issues detected and links to educational resources.
* **Team Overview:** Shows overall team compliance with best practices.
4. **Educational Module:**
* **Access:** Accessible via a dedicated 'Learn' section or contextually from analysis results.
* **Content (MVP):** Short articles/guides on: What is Git? Basic Git Commands (init, add, commit, push, pull, branch, merge), Why Version Control Matters, What is CI/CD?, Secure Deployment Practices.
* **Format:** Markdown-based content rendered within the application.
API & DATA FETCHING:
- **API Routes (Next.js App Router - `app/api/...`):**
* `POST /api/auth/...`: Handled by NextAuth.js for login/signup.
* `POST /api/repositories`: To connect a new repository (handles OAuth callback and initial analysis trigger).
* `GET /api/repositories`: Fetch list of repositories for the logged-in user's team.
* `GET /api/repositories/[repoId]`: Fetch details and analysis results for a specific repository.
* `POST /api/webhooks/{provider}`: (Future) To receive real-time updates from Git providers.
* `GET /api/analysis/trigger/{repoId}`: (Internal/Admin) To manually trigger a re-analysis.
- **Data Fetching:**
* Server Components will fetch data directly from the database using Drizzle ORM for initial page loads (e.g., dashboard, repository list).
* Client Components will use Server Actions or API routes for mutations (adding repos) and potentially revalidation/fetching updated data client-side.
* Example `GET /api/repositories/[repoId]` response:
```json
{
"id": "uuid",
"gitProvider": "github",
"repoOwner": "octocat",
"repoName": "Spoon-Knife",
"hasVersionControl": true,
"lastAnalysis": "2024-07-27T10:00:00Z",
"analysisResults": [
{
"id": "uuid",
"analysisType": "version_control",
"result": {"detected": true, "message": "Git repository detected.", "details": "Standard Git history found."},
"timestamp": "2024-07-27T10:00:00Z"
},
{
"id": "uuid",
"analysisType": "code_quality",
"result": {"score": 85, "rules_passed": ["FILE_NAMING"], "rules_failed": ["PROJECT_STRUCTURE_MINIMAL"]},
"timestamp": "2024-07-27T10:00:05Z"
},
{
"id": "uuid",
"analysisType": "deployment_method",
"result": {"detected": false, "message": "No standard CI/CD pipeline detected. Consider automation."},
"timestamp": "2024-07-27T10:00:10Z"
}
]
}
```
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/`**
* **`(auth)/`** (Route Group for Auth Pages)
* `layout.tsx`: Basic layout for auth pages (centered content).
* `sign-in/page.tsx`: Sign-in form (Email/Password, GitHub Button).
* `sign-up/page.tsx`: Sign-up form (Name, Email, Password).
* **`(app)/`** (Route Group for Authenticated App)
* `layout.tsx`: Main application layout including sidebar/header, navigation, and protected route handling.
* `page.tsx` (Dashboard): Main landing page after login. Displays overview widgets for repositories, recent alerts, quick actions. Fetches data using Server Components.
* `repositories/page.tsx`: List of all connected repositories for the team. Fetches `repositories` data. Each item links to the detail page.
* `repositories/[repoId]/page.tsx`: Detailed view for a single repository. Fetches repository data and `analysisResults`. Displays detailed findings and links to educational content.
* `repositories/add/page.tsx`: Page/modal for adding/connecting new repositories. Handles provider selection and initiates OAuth flow.
* `settings/page.tsx`: User and Team settings (profile, team members, billing - future).
* `settings/team/page.tsx`: Manage team members, roles.
* `settings/repositories/page.tsx`: Manage connected repositories (re-analyze, disconnect).
* `learn/page.tsx`: Educational content listing.
* `learn/[topic]/page.tsx`: Individual learning module page (e.g., `learn/git-basics`).
* `api/`
* `auth/[...nextauth]/route.ts`: NextAuth.js configuration.
* `repositories/route.ts`: API route for adding repositories.
* `repositories/[repoId]/route.ts`: API route for fetching repository details.
* `webhooks/{provider}/route.ts`: (Future) Webhook handlers.
* `layout.tsx`: Root layout (html, body, global providers like Next-auth SessionProvider).
* `global.css`: Tailwind CSS base and configuration.
- **`components/`**
* `ui/`: Re-exported components from `shadcn/ui` (e.g., `Button`, `Input`, `Card`, `Table`, `Dialog`, `Alert`, `Avatar`, `Tabs`).
* `auth/`: Auth-related components (e.g., `SignInForm`, `SignUpForm`, `OAuthButtons`).
* `dashboard/`: Components specific to the dashboard (e.g., `RepoOverviewCard`, `RecentActivityFeed`).
* `repositories/`: Components for repository listing and details (e.g., `RepositoryTable`, `AnalysisResultDetails`, `RepoConnectionForm`).
* `layout/`: Layout components (e.g., `Navbar`, `Sidebar`, `Footer`).
* `common/`: General-purpose components (e.g., `LoadingSpinner`, `ErrorMessage`, `StatusIndicator`).
* `charts/`: (Optional, if adding visual charts later) Charting components.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, Professional, Trustworthy.
- **Color Palette:**
* Primary: `#3B82F6` (Tailwind `blue-500`) - For primary actions, links, highlights.
* Secondary: `#6366F1` (Tailwind `indigo-500`) - For secondary elements, accents.
* Background: `#FFFFFF` (Base) / `#F9FAFB` (Slightly off-white for sections) - Light mode. Consider a dark mode variant later (`#111827` - Tailwind `gray-900` dark).
* Text (Dark): `#1F2937` (Tailwind `gray-800`)
* Text (Light): `#FFFFFF` (For dark backgrounds).
* Success: `#10B981` (Tailwind `green-500`)
* Warning: `#F59E0B` (Tailwind `amber-500`)
* Error: `#EF4444` (Tailwind `red-500`)
- **Typography:** Inter or Inter-like sans-serif font (e.g., Tailwind's default sans-serif). Clear hierarchy using font weights and sizes.
* Headings: `font-bold`, `text-2xl`/`3xl`
* Body: `text-base`, `leading-relaxed`
- **Layout:** Use a sidebar for main navigation within the authenticated app. Content area uses cards and tables for information display. Consistent padding and spacing (e.g., multiples of 4px or 8px).
- **Responsive Rules:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows and adapts. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`).
- **Visual Elements:** Use clear icons (e.g., from Lucide Icons used by shadcn/ui) for actions and status indicators. Subtle use of borders and shadows to define sections. Focus on clarity and readability.
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js's `useRouter` and a layout wrapper (e.g., Framer Motion if needed, but aim for CSS transitions initially).
- **Hover Effects:** Subtle background color changes or slight scaling on interactive elements (buttons, links, cards).
- **Loading States:** Use `shadcn/ui`'s `Skeleton` or `Spinner` components with Tailwind's `animate-spin` for loading data. Indicate loading states clearly on buttons during submission.
- **Transitions:** Smooth transitions for elements appearing/disappearing (e.g., dropdown menus, modals).
EDGE CASES:
- **Authentication:** Handle expired sessions, invalid credentials gracefully. Protect all authenticated routes.
- **Repository Connection:** Handle OAuth errors, invalid tokens, API rate limits from providers.
- **Analysis Failures:** If an analysis job fails (e.g., due to provider API issues), mark it as failed and provide an option to retry.
- **Empty States:** Display user-friendly messages and clear calls-to-action when lists are empty (e.g., "No repositories connected yet. Add your first repository!").
- **Validation:** Implement robust server-side and client-side validation for all forms (signup, login, repository connection details) using `zod` and `react-hook-form`.
- **Permissions:** Ensure users can only access data belonging to their team. Implement role-based access control (e.g., only admins can invite members - future enhancement).
- **Error Handling:** Implement global error handling for API routes and display user-friendly error messages on the UI.
SAMPLE DATA (for frontend development or initial state seeding):
1. **User:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Alice Wonderland",
"email": "alice@example.com",
"image": "https://example.com/alice.jpg"
}
```
2. **Team:**
```json
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"name": "Wonderland Devs",
"ownerId": "a1b2c3d4-e5f6-7890-1234-567890abcdef"
}
```
3. **Repository (Connected, VC detected, basic quality issues):
```json
{
"id": "11223344-aabb-ccdd-eeff-001122334455",
"teamId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"gitProvider": "github",
"repoOwner": "wonderland-devs",
"repoName": "magic-beans",
"hasVersionControl": true,
"lastAnalysis": "2024-07-26T14:30:00Z",
"analysisResults": [
{ "analysisType": "version_control", "result": {"detected": true, "message": "Standard Git history found."} },
{ "analysisType": "code_quality", "result": {"score": 65, "rules_failed": ["INDENTATION_STYLE", "MAX_LINE_LENGTH"]} },
{ "analysisType": "deployment_method", "result": {"detected": false, "message": "Manual deployment suspected."} }
]
}
```
4. **Repository (Not Connected Yet - Placeholder for UI):
```json
{
"id": "aabbccdd-eeff-0011-2233-445566778899",
"teamId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"gitProvider": "github",
"repoOwner": "wonderland-devs",
"repoName": "tea-party-planner",
"hasVersionControl": null, // or undefined
"lastAnalysis": null
}
```
5. **Repository (Analysis in Progress):
```json
{
"id": "99887766-5544-3322-1100-ddccbbaa9988",
"teamId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"gitProvider": "gitlab",
"repoOwner": "wonderland-devs",
"repoName": "talking-cards",
"hasVersionControl": null,
"lastAnalysis": null
}
```
6. **Analysis Result (VC Not Detected):
```json
{
"id": "result-vc-fail-1",
"repositoryId": "...",
"analysisType": "version_control",
"result": {"detected": false, "message": "No Git repository detected. Commits seem to be managed manually or via file sharing.", "learnTopic": "git-basics"},
"timestamp": "2024-07-27T11:00:00Z"
}
```
7. **Analysis Result (Deployment Warning):
```json
{
"id": "result-deploy-warn-1",
"repositoryId": "...",
"analysisType": "deployment_method",
"result": {"detected": false, "message": "High commit frequency without detected CI/CD pipeline. Consider automating deployments to reduce errors.", "learnTopic": "cicd-intro"},
"timestamp": "2024-07-27T11:05:00Z"
}
```
8. **Learning Module Data (Example):
```json
{
"slug": "git-basics",
"title": "Git Basics for Teams",
"content": "# Git Basics... (Markdown content)",
"relatedAnalysisTypes": ["version_control"]
}
```
This prompt provides a detailed blueprint for building the CodeGuard Pro MVP, covering all essential aspects from backend structure to frontend components and user experience.