## AI Master Prompt: EcoBloom AI - MVP Application Generation
**1. PROJECT OVERVIEW:**
EcoBloom AI is a Software-as-a-Service (SaaS) platform designed to help businesses identify and transform their waste streams into valuable resources. Inspired by real-world examples like the Costa Rican orange peel reforestation project, the platform uses AI to analyze waste data, propose innovative recycling, upcycling, or repurposing solutions, and connect businesses with potential partners or case studies. Our core value proposition is to turn environmental liabilities into economic assets, promoting circular economy principles and sustainable business practices.
**2. TECH STACK:**
- **Frontend Framework:** React (using Next.js App Router for server components and routing)
- **Styling:** Tailwind CSS (with Headless UI for accessibility and component primitives)
- **UI Library/Components:** shadcn/ui (for a curated set of accessible, themeable, and customizable components)
- **State Management:** React Context API and Zustand (for global state and performance optimization)
- **Database:** PostgreSQL (via Drizzle ORM)
- **ORM:** Drizzle ORM (for type-safe database interactions with PostgreSQL)
- **Authentication:** NextAuth.js (for secure user authentication, supporting email/password and potentially OAuth providers)
- **Forms:** React Hook Form (for efficient form handling and validation)
- **Data Fetching:** Server Actions (Next.js) for mutations, and client-side fetching with React Query or SWR for reads where appropriate.
- **Deployment:** Vercel
**3. DATABASE SCHEMA (Drizzle ORM - PostgreSQL):**
```typescript
// schema.ts
import { pgTable, serial, text, timestamp, integer, boolean, pgEnum, varchar, jsonb } from 'drizzle-orm/pg-core';
// Enum for waste categories (example)
export const wasteCategoryEnum = pgEnum('waste_category', [
'organic',
'plastic',
'metal',
'glass',
'textile',
'electronic',
'construction',
'other'
]);
// Users Table
export const users = pgTable('users', {
id: text('id').primaryKey(), // From NextAuth.js
name: text('name'),
email: text('email').unique().notNull(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: text('image'),
createdAt: timestamp('createdAt').defaultNow()
});
// Accounts Table (for NextAuth.js)
export const accounts = pgTable('accounts', {
id: text('id').primaryKey(),
userId: text('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
type: text('type').$type<string>().notNull(),
provider: text('provider').notNull(),
providerAccountId: text('providerAccountId').notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: text('token_type'),
scope: text('scope'),
id_token: text('id_token'),
session_state: text('session_state')
});
// Sessions Table (for NextAuth.js)
export const sessions = pgTable('sessions', {
sessionToken: text('sessionToken').primaryKey(),
userId: text('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
expires: timestamp('expires', { mode: 'date' }).notNull()
});
// Verification Tokens Table (for NextAuth.js)
export const verificationTokens = pgTable('verification_tokens', {
identifier: text('identifier').notNull(),
token: text('token').notNull(),
expires: timestamp('expires', { mode: 'date' }).notNull(),
// Ensure a token can only be used once per identifier
primaryKey(identifier, token)
});
// Companies Table
export const companies = pgTable('companies', {
id: serial('id').primaryKey(),
userId: text('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 100 }).notNull(),
industry: varchar('industry', { length: 100 }),
address: text('address'),
createdAt: timestamp('createdAt').defaultNow()
});
// Waste Streams Table
export const wasteStreams = pgTable('waste_streams', {
id: serial('id').primaryKey(),
companyId: integer('company_id').notNull().references(() => companies.id, { onDelete: 'cascade' }),
name: varchar('name', { length: 150 }).notNull(),
category: wasteCategoryEnum('category').notNull(),
description: text('description'),
averageVolumePerMonth: integer('average_volume_per_month'), // e.g., in kg, liters, m^3
volumeUnit: varchar('volume_unit', { length: 20 }),
currentDisposalCost: integer('current_disposal_cost'), // per month
costUnit: varchar('cost_unit', { length: 20 }), // e.g., USD, EUR
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow()
});
// Potential Solutions Table
export const potentialSolutions = pgTable('potential_solutions', {
id: serial('id').primaryKey(),
wasteStreamId: integer('waste_stream_id').notNull().references(() => wasteStreams.id, { onDelete: 'cascade' }),
solutionType: varchar('solution_type', { length: 50 }), // e.g., 'Recycle', 'Upcycle', 'Repurpose', 'Energy Recovery'
description: text('description').notNull(),
estimatedValue: integer('estimated_value'), // Potential revenue or cost saving
valueUnit: varchar('value_unit', { length: 20 }),
implementationEffort: varchar('implementation_effort', { length: 50 }), // e.g., 'Low', 'Medium', 'High'
environmentalImpact: text('environmental_impact'),
source: varchar('source', { length: 255 }), // Link to case study, research paper, etc.
aiGenerated: boolean('ai_generated').default(true),
createdAt: timestamp('createdAt').defaultNow()
});
// Case Studies Table (Can be linked to solutions or standalone)
export const caseStudies = pgTable('case_studies', {
id: serial('id').primaryKey(),
title: varchar('title', { length: 200 }).notNull(),
industry: varchar('industry', { length: 100 }),
wasteType: wasteCategoryEnum('waste_type'),
summary: text('summary'),
fullDescription: text('full_description'),
results: jsonb('results'), // e.g., { costSavings: 15000, revenueGenerated: 5000, co2Reduced: 50 }
imageUrl: text('image_url'),
link: text('link'),
createdAt: timestamp('createdAt').defaultNow()
});
```
**4. CORE FEATURES & USER FLOW:**
* **User Authentication:**
* Flow: User signs up via email/password or OAuth (Google).
* After sign-up/login, user is redirected to the dashboard.
* Email verification is required for initial sign-up (using NextAuth.js default flow).
* Password reset functionality is available.
* **Company Onboarding:**
* Flow: Upon first login, user is prompted to create a company profile.
* Fields: Company Name, Industry, Address.
* User is linked to the company via `userId`.
* **Waste Stream Management:**
* Flow: User navigates to 'Waste Streams' section.
* Action: Click 'Add New Waste Stream'.
* Form: Name, Category (dropdown using `wasteCategoryEnum`), Description, Average Volume (with unit), Current Disposal Cost (with unit).
* On Submit: Data is saved to the `wasteStreams` table via a Next.js Server Action. The `companyId` is automatically linked to the logged-in user's company.
* View: A table displays all waste streams for the company. Each row has options to 'View Details', 'Edit', or 'Delete'.
* **AI-Powered Solution Generation:**
* Flow: From the 'Waste Stream Details' page or the main 'Waste Streams' table.
* Action: Click 'Generate Solutions'.
* Process: A Server Action is triggered. This action sends the waste stream data (category, volume, description) to a hypothetical AI service (e.g., a Python backend with an ML model or an external API like OpenAI's GPT).
* AI Logic: The AI analyzes the input and queries a knowledge base (could be a separate DB table or pre-trained data) for relevant recycling, upcycling, or repurposing methods. It considers factors like industry best practices, material properties, and potential economic/environmental impact.
* Response: The AI returns a list of potential solutions, each with a description, estimated value, implementation effort, environmental benefits, and a link to a relevant case study if available. These are saved into the `potentialSolutions` table, linked to the `wasteStreamId`.
* Display: Solutions are displayed on the 'Waste Stream Details' page, possibly categorized or ranked by AI.
* **Case Study Browsing:**
* Flow: User navigates to the 'Case Studies' section.
* View: A searchable and filterable grid or list of case studies.
* Filtering: By industry, waste type.
* Details: Clicking a case study shows its title, summary, results, image, and link.
* **Reporting Dashboard:**
* Flow: User navigates to the 'Dashboard'.
* Content: A summary view of the company's waste streams, total volume, estimated disposal costs, and a high-level overview of potential savings or revenue generated from AI-suggested solutions. (MVP might show counts and basic totals, more advanced reporting later).
**5. API & DATA FETCHING:**
* **NextAuth.js:** Handles `/api/auth/*` endpoints for authentication.
* **Server Actions:** Used for all data mutations (POST, PUT, DELETE requests) to the database (e.g., adding waste streams, updating company info). They run on the server, ensuring secure database operations.
* **Route Handlers (API Routes):** For specific read operations or integrations where Server Actions might not be suitable. e.g., `/api/ai/generate-solutions` might be a Route Handler that calls the external AI service.
* **Data Fetching in Components:**
* Server Components: Fetch data directly within the component during render using async operations (e.g., `async function Page() { const data = await db.query... }`). Ideal for initial page loads and SEO.
* Client Components: Use libraries like `react-query` or `swr` for client-side data fetching, caching, revalidation, and managing loading/error states, especially for dynamic data or user interactions.
* **Request/Response Examples:**
* POST `/api/waste-streams` (Server Action):
* Request Body: `{ name: 'Plastic Bottles', category: 'plastic', averageVolumePerMonth: 500, volumeUnit: 'kg', ... }`
* Response: `{ success: true, id: 123 }` or `{ success: false, error: '...' }`
* GET `/api/companies/[companyId]/waste-streams` (Route Handler or Server Component Fetch):
* Response Body: `[ { id: 1, name: 'Plastic Bottles', ... }, { id: 2, name: 'Cardboard', ... } ]`
**6. COMPONENT BREAKDOWN (Next.js App Router):**
* **`app/` directory:**
* `(auth)/` group:
* `layout.tsx`: Auth layout (simple centered card).
* `login/page.tsx`: Login form component.
* `signup/page.tsx`: Sign up form component.
* `reset-password/page.tsx`: Password reset form.
* `(app)/` group (Protected Routes):
* `layout.tsx`: Main application layout (Sidebar, Header, Content Area).
* `dashboard/page.tsx`: Dashboard landing page. Displays summary cards for waste streams, potential savings. Fetches data for logged-in company. (Server Component).
* `company/profile/page.tsx`: Company profile form (edit/create). Uses `useForm` from React Hook Form. (Client Component, fetches data on mount).
* `waste-streams/page.tsx`: Table view of all waste streams. Includes 'Add New' button. Fetches data. (Server Component, with Client Component for the table/actions).
* `waste-streams/[id]/page.tsx`: Detailed view for a single waste stream. Shows details, disposal costs, and a list of AI-generated `potentialSolutions`. Includes 'Generate Solutions' button. (Server Component for details, Client Component for AI interaction and solution list).
* `case-studies/page.tsx`: Browse and filter case studies. Search bar and filter controls. Fetches data. (Server Component, with Client Components for interactive filters).
* `settings/page.tsx`: User settings (e.g., change password, manage account).
* `api/auth/[...nextauth]/route.ts`: NextAuth.js handler.
* `api/ai/generate-solutions/route.ts`: (Optional) Route Handler for AI service interaction.
* `layout.tsx`: Root layout (includes global providers, font loading).
* `page.tsx`: Landing Page (for unauthenticated users).
* `loading.tsx`: Global loading indicator.
* `error.tsx`: Global error handler.
* **Key UI Components (in `components/` directory):**
* `AuthForm.tsx`: Reusable login/signup form.
* `CompanyForm.tsx`: Company profile form.
* `WasteStreamForm.tsx`: Form for adding/editing waste streams.
* `WasteStreamTable.tsx`: Displays waste streams data in a table with pagination and actions (using shadcn/ui `DataTable`).
* `SolutionCard.tsx`: Displays a single potential solution card.
* `CaseStudyCard.tsx`: Displays a single case study card.
* `Sidebar.tsx`: Navigation menu.
* `Header.tsx`: Top navigation/user menu.
* `Card.tsx`, `Button.tsx`, `Input.tsx`, `Select.tsx`, `Dialog.tsx`, `Tabs.tsx`, etc. (From shadcn/ui).
**7. UI/UX DESIGN & VISUAL IDENTITY:**
* **Design Style:** Minimalist Clean with subtle Gradient Accents.
* **Color Palette:**
* Primary: `#2563eb` (a calming blue)
* Secondary: `#10b981` (a vibrant green for positive actions/outcomes)
* Background: `#ffffff` (light mode default)
* Dark Background (for cards/sections): `#f9fafb`
* Text (Primary): `#111827` (dark gray)
* Text (Secondary): `#6b7280` (medium gray)
* Accent Gradient (subtle, used sparingly on headers or buttons): Linear gradient from `#6366f1` to `#8b5cf6`.
* **Typography:**
* Headings: Inter (Variable font, weights 700-900)
* Body Text: Inter (Variable font, weights 400-500)
* **Layout:**
* Use a standard 3-column layout for larger screens (Sidebar Left, Content Center, potentially extra info Right).
* Center-aligned content cards for auth pages.
* Consistent padding and spacing using Tailwind's spacing scale.
* **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on small screens. Content reflows gracefully. Use `max-width` containers.
* **Interactions:** Subtle hover effects on buttons and cards. Smooth transitions for opening/closing modals and expanding sections. Loading spinners/skeletons for data fetching.
**8. SAMPLE/MOCK DATA:**
* **`users`:**
* `{ id: 'user-123', name: 'Alice Smith', email: 'alice@example.com', image: '...' }`
* **`companies`:**
* `{ id: 1, userId: 'user-123', name: 'GreenHarvest Farms', industry: 'Agriculture', address: '123 Agro Rd, Fertile Valley' }`
* **`wasteStreams`:**
* `{ id: 1, companyId: 1, name: 'Spent Grain Mash', category: 'organic', description: 'Byproduct from brewery', averageVolumePerMonth: 15000, volumeUnit: 'kg', currentDisposalCost: 500, costUnit: 'USD' }`
* `{ id: 2, companyId: 1, name: 'Plastic Pallets', category: 'plastic', description: 'Damaged shipping pallets', averageVolumePerMonth: 50, volumeUnit: 'units', currentDisposalCost: 100, costUnit: 'USD' }`
* `{ id: 3, companyId: 1, name: 'Vegetable Scraps', category: 'organic', description: 'Trimmings from processing', averageVolumePerMonth: 8000, volumeUnit: 'kg', currentDisposalCost: 300, costUnit: 'USD' }`
* **`potentialSolutions`:**
* `{ id: 101, wasteStreamId: 1, solutionType: 'Animal Feed Supplement', description: 'Dried spent grain can be used as a high-protein supplement for livestock feed.', estimatedValue: 2000, valueUnit: 'USD/month', implementationEffort: 'Medium', environmentalImpact: 'Reduces landfill waste, provides sustainable feed.', source: '/case-studies/spent-grain-feed' }`
* `{ id: 102, wasteStreamId: 2, solutionType: 'Upcycled Furniture', description: 'Sturdy plastic pallets can be broken down and reformed into durable outdoor furniture.', estimatedValue: 500, valueUnit: 'USD/month', implementationEffort: 'High', environmentalImpact: 'Diverts plastic from landfill, creates durable goods.', source: '/case-studies/plastic-furniture' }`
* `{ id: 103, wasteStreamId: 3, solutionType: 'Composting / Biogas', description: 'High-moisture organic waste is ideal for large-scale composting or anaerobic digestion to produce biogas and fertilizer.', estimatedValue: 1500, valueUnit: 'USD/month', implementationEffort: 'Medium', environmentalImpact: 'Creates valuable soil amendment and renewable energy, reduces methane emissions.', source: '/case-studies/farm-biogas' }`
* **`caseStudies`:**
* `{ id: 1, title: 'Brewery Waste to Livestock Feed', industry: 'Agriculture', wasteType: 'organic', summary: 'A local farm partnered with a brewery to use spent grain mash...', results: { costSavings: 24000, revenueGenerated: null, co2Reduced: 15 }, imageUrl: '/images/casestudy1.jpg', link: '/case-studies/spent-grain-feed' }`
* `{ id: 2, title: 'Plastic Pallets: From Waste to Wonder', industry: 'Manufacturing', wasteType: 'plastic', summary: 'Innovative company transforms damaged pallets into long-lasting outdoor furniture...', results: { costSavings: null, revenueGenerated: 6000, co2Reduced: 5 }, imageUrl: '/images/casestudy2.jpg', link: '/case-studies/plastic-furniture' }`
**9. TURKISH TRANSLATIONS (for UI elements):**
* Dashboard: `Gösterge Paneli`
* Waste Streams: `Atık Akışları`
* Add New Waste Stream: `Yeni Atık Akışı Ekle`
* Generate Solutions: `Çözümler Üret`
* Case Studies: `Vaka Çalışmaları`
* Company Profile: `Şirket Profili`
* Settings: `Ayarlar`
* Login: `Giriş Yap`
* Sign Up: `Kayıt Ol`
* Name: `Ad`
* Category: `Kategori`
* Description: `Açıklama`
* Average Volume: `Ortalama Hacim`
* Volume Unit: `Hacim Birimi`
* Current Disposal Cost: `Mevcut Bertaraf Maliyeti`
* Cost Unit: `Maliyet Birimi`
* Potential Value: `Potansiyel Değer`
* Implementation Effort: `Uygulama Zorluğu`
* Environmental Impact: `Çevresel Etki`
* Save: `Kaydet`
* Edit: `Düzenle`
* Delete: `Sil`
* Search: `Ara`
* Filter: `Filtrele`
* View Details: `Detayları Gör`
* Email: `E-posta`
* Password: `Şifre`
* Forgot Password?: `Şifremi Unuttum?`
* Log Out: `Çıkış Yap`
* Welcome, [User Name]!: `Hoş Geldin, [Kullanıcı Adı]!`
* No data available: `Veri mevcut değil`
* Loading...: `Yükleniyor...`
* Error loading data: `Veri yüklenirken hata oluştu`
**10. ANIMATIONS:**
* **Page Transitions:** Use Next.js's built-in support or a library like `Framer Motion` for smooth fade/slide transitions between pages.
* **Button Hovers:** Subtle background color change or slight scale-up effect on buttons.
* **Card Hovers:** Slight shadow increase or translateY effect on cards when hovered.
* **Loading States:** Use shadcn/ui's `Skeleton` component or a custom spinner component for data fetching placeholders.
* **Form Validation:** Error messages appear with a subtle fade-in animation.
* **Accordions/Toggles:** Smooth expand/collapse animations for sections like detailed solution breakdowns.
**11. EDGE CASES:**
* **Authentication:** Handle expired tokens, unauthorized access attempts (redirect to login), session management.
* **Empty States:** Design user-friendly empty states for when there are no waste streams, no solutions, or no case studies yet. Include clear calls to action.
* **Form Validation:** Implement robust validation on all forms (e.g., required fields, valid number formats, email format) both client-side (using React Hook Form) and server-side (via Server Actions).
* **AI Service Failures:** Gracefully handle errors if the AI service is unavailable or returns an error. Display a user-friendly message and potentially retry logic or a fallback to manual suggestions.
* **Database Errors:** Implement try-catch blocks around database operations (especially in Server Actions) to handle potential connection issues or query failures. Return appropriate error messages to the user.
* **Data Integrity:** Ensure foreign key constraints are respected (e.g., cannot delete a company if it has waste streams unless cascading delete is intended and confirmed).
* **Authorization:** Ensure users can only access and modify data belonging to their own company.
This comprehensive prompt provides the necessary details for an AI to generate a functional, multi-page MVP of EcoBloom AI using Next.js, Drizzle ORM, Tailwind CSS, and shadcn/ui, complete with authentication, database interactions, and AI integration points.