Generate a fully functional, multi-page Next.js MVP application for 'Concrete AI Optimize'. This application is a SaaS platform designed to help American concrete and cement producers optimize their concrete mix designs using AI.
**1. PROJECT OVERVIEW:**
Concrete AI Optimize aims to revolutionize the concrete mix design process by leveraging AI, specifically Meta's BOxCrete model and foundational data. The platform addresses the traditional, slow, and expensive trial-and-error method by providing an intelligent, data-driven solution. It enables users to design concrete mixes that meet competing requirements such as strength, cost, sustainability, and workability, with a focus on American-produced materials. The core value proposition is to accelerate design cycles, reduce R&D costs, improve concrete quality, enhance sustainability, and promote the use of domestic cementitious materials.
**2. TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL compatible)
- **Database:** PostgreSQL (managed via Vercel Postgres or similar)
- **UI Library:** shadcn/ui for components
- **Authentication:** NextAuth.js (or Clerk for easier integration if preferred)
- **State Management:** React Context API / Zustand for global state, local state where appropriate.
- **Forms:** React Hook Form with Zod for validation
- **Charting:** Recharts or Chart.js for data visualization
- **Deployment:** Vercel
- **Other:** React Query for server state management, Nodemailer for email notifications (e.g., password reset).
**3. DATABASE SCHEMA:**
We will use PostgreSQL with Drizzle ORM. Key tables:
- **users:**
- id: uuid (PK, default: uuid_generate_v4())
- name: varchar
- email: varchar (unique)
- emailVerified: timestamp
- image: varchar (nullable)
- hashedPassword: varchar (nullable)
- role: varchar (e.g., 'admin', 'user', 'editor')
- createdAt: timestamp (default: now())
- updatedAt: timestamp
- **accounts:** (For NextAuth.js)
- id: uuid (PK, default: uuid_generate_v4())
- userId: uuid (FK to users.id)
- type: varchar
- provider: varchar
- providerAccountId: varchar
- refresh_token: text (nullable)
- access_token: text (nullable)
- expires_at: bigint (nullable)
- token_type: varchar (nullable)
- scope: varchar (nullable)
- id_token: text (nullable)
- session_state: varchar (nullable)
- **sessions:** (For NextAuth.js)
- id: uuid (PK, default: uuid_generate_v4())
- userId: uuid (FK to users.id)
- expires: timestamp
- sessionToken: varchar (unique)
- **verificationTokens:** (For NextAuth.js)
- id: bigint (PK, auto_increment)
- token: varchar (unique)
- identifier: varchar
- expires: timestamp
- **companies:**
- id: uuid (PK, default: uuid_generate_v4())
- name: varchar
- industry: varchar (e.g., 'Cement', 'Concrete', 'Construction')
- location: varchar
- createdAt: timestamp (default: now())
- updatedAt: timestamp
- **company_members:**
- id: uuid (PK, default: uuid_generate_v4())
- companyId: uuid (FK to companies.id)
- userId: uuid (FK to users.id)
- role: varchar ('owner', 'member')
- joinedAt: timestamp (default: now())
- **material_types:**
- id: uuid (PK, default: uuid_generate_v4())
- name: varchar (e.g., 'Portland Cement', 'Fly Ash', 'Water', 'Superplasticizer')
- description: text (nullable)
- unit: varchar (e.g., 'kg/m³', 'l/m³')
- origin_type: varchar ('Domestic', 'Imported')
- default_properties: jsonb (e.g., { density: 1.5, cost_per_unit: 0.2 })
- **mix_designs:**
- id: uuid (PK, default: uuid_generate_v4())
- userId: uuid (FK to users.id)
- companyId: uuid (FK to companies.id)
- name: varchar
- description: text (nullable)
- target_strength_mpa: decimal
- target_slump_mm: decimal
- target_cost_per_m3: decimal (nullable)
- target_co2_kg_per_m3: decimal (nullable)
- created_by_ai: boolean (default: false)
- createdAt: timestamp (default: now())
- updatedAt: timestamp
- **mix_design_materials:**
- id: uuid (PK, default: uuid_generate_v4())
- mixDesignId: uuid (FK to mix_designs.id)
- materialTypeId: uuid (FK to material_types.id)
- quantity: decimal
- quantity_unit: varchar (e.g., 'kg/m³', '% by weight')
- cost_per_unit: decimal (nullable)
- co2_per_unit: decimal (nullable)
- **ai_optimization_jobs:**
- id: uuid (PK, default: uuid_generate_v4())
- userId: uuid (FK to users.id)
- companyId: uuid (FK to companies.id)
- status: varchar ('pending', 'processing', 'completed', 'failed')
- target_parameters: jsonb (e.g., { strength: 50, cost_max: 150, sustainability_index: 0.8 })
- results: jsonb (nullable, contains optimized mix designs)
- createdAt: timestamp (default: now())
- updatedAt: timestamp
**4. CORE FEATURES & USER FLOW:**
- **Authentication Flow:**
1. User lands on the homepage.
2. Clicks 'Sign Up' or 'Log In'.
3. Sign Up: Enters email, password, name. Optionally joins an existing company or creates a new one. Receives a verification email.
4. Log In: Enters email and password. Redirected to dashboard if successful.
5. Password Reset: User clicks 'Forgot Password', enters email. Receives a reset link. Follows link to set a new password.
6. Company Association: Users can be invited to or create companies. The company entity helps manage shared projects and potentially different subscription tiers.
- **Dashboard:**
1. User logs in.
2. Sees a personalized dashboard with:
- Quick stats (e.g., recent mix designs, active optimization jobs).
- Links to key sections (Mix Design, AI Optimizer, Materials, Projects).
- Company overview if associated with one.
- Notifications (e.g., job completion, new invites).
- **Mix Design Management:**
1. User navigates to 'Mix Designs'.
2. Sees a list of their created mix designs (paginated, searchable, sortable).
3. Clicks 'Create New Mix Design'.
- **Manual Design:**
1. Enters basic info: Name, Description, Target Strength, Slump.
2. Adds materials one by one using a searchable dropdown (powered by `material_types` table).
3. For each material, specifies quantity and unit (e.g., 'kg/m³'). Units should be validated against expected values or converted.
4. Input fields for `cost_per_unit` and `co2_per_unit` for materials are present.
5. The system calculates total cost and CO2 footprint based on material costs and quantities. (Form validation: Quantities must sum to a reasonable total, e.g., 1 m³ effective volume).
6. User saves the design.
- **AI-Optimized Design (Initiation):** User clicks 'Create AI Optimized Design'. Navigates to AI Optimizer section.
4. User can view, edit, duplicate, or delete existing mix designs.
5. Viewing a design shows a detailed breakdown of materials, quantities, costs, and CO2 impact, possibly with charts.
- **AI Optimizer:**
1. User navigates to 'AI Optimizer'.
2. Clicks 'Start New Optimization Job'.
3. Specifies target parameters:
- Minimum Strength (MPa)
- Maximum Cost per m³ (USD)
- Maximum CO2 per m³ (kg) (Optional)
- Desired Slump (mm) (Optional)
- Material Constraints: Select preferred/required materials, specify minimum/maximum percentages for certain types (e.g., 'must use at least 10% fly ash', 'cement content between 300-400 kg/m³'). This uses `material_types` and `company_members` (to filter for preferred domestic materials).
- Optimization Goal: Prioritize Cost, Sustainability, or Balanced.
4. System initiates an asynchronous job (`ai_optimization_jobs` table status: 'pending').
5. User sees a list of their optimization jobs with status.
6. When a job is 'completed', user can view results.
- Results display several optimized mix design proposals.
- Each proposal shows material composition, calculated properties (strength, cost, CO2), and a confidence score or feasibility rating.
- User can select a proposal to save it as a new 'Mix Design'.
- **Material Management:**
1. User (admin/editor) navigates to 'Materials'.
2. Sees a list of available materials (`material_types`).
3. Can filter by origin ('Domestic' vs 'Imported').
4. Can add new materials, specifying name, unit, default properties (density, cost, CO2 factor - these can be updated per project).
5. Admins can potentially manage company-specific material cost overrides.
**5. API & DATA FETCHING:**
- **API Structure:** Use Next.js API Routes within the `app/api/` directory.
- **Authentication:** Protected routes using NextAuth.js middleware.
- **Data Fetching:** Primarily use server components for initial data loads. Utilize React Query (or similar) on the client for mutations, refetching, and managing server cache state.
- **Example API Routes:**
- `POST /api/mix-designs`: Create a new mix design.
- Request Body: `{ name: string, description?: string, targetStrength: number, materials: { materialId: string, quantity: number, unit: string }[] }`
- Response: `201 Created` with the new mix design object or `400 Bad Request` with validation errors.
- `GET /api/mix-designs/{id}`: Get details of a specific mix design.
- Response: `200 OK` with mix design object or `404 Not Found`.
- `PUT /api/mix-designs/{id}`: Update an existing mix design.
- Request Body: Similar to POST.
- Response: `200 OK` with updated object or `400`/`404`.
- `POST /api/ai-jobs`: Start a new AI optimization job.
- Request Body: `{ targetParameters: object, materialConstraints?: object, optimizationGoal: string }`
- Response: `202 Accepted` with the job ID and status `pending`.
- `GET /api/ai-jobs/{id}`: Get the status and results of an AI job.
- Response: `200 OK` with job status and results (if available).
- **Data Flow:** Server components fetch data directly from the database using Drizzle ORM. Client components request data via API routes or directly via server actions where appropriate (App Router pattern). Use caching mechanisms effectively.
**6. COMPONENT BREAKDOWN (Next.js App Router):**
- **`app/layout.tsx`:** Root layout (html, body, global providers, ThemeProvider).
- **`app/page.tsx`:** Landing Page (Marketing content, CTA for Sign Up/Log In).
- **`app/(auth)/login/page.tsx`:** Login Form page.
- **`app/(auth)/signup/page.tsx`:** Sign Up Form page.
- **`app/(auth)/reset-password/page.tsx`:** Password Reset page.
- **`app/dashboard/page.tsx`:** Dashboard (summary stats, recent activity, navigation links). Requires authentication.
- **`app/dashboard/layout.tsx`:** Dashboard layout (sidebar navigation, header).
- **`app/dashboard/mix-designs/page.tsx`:** List of all Mix Designs (table view, search, filter, create button). Requires auth.
- **`app/dashboard/mix-designs/[id]/page.tsx`:** View/Edit Mix Design details (form, material breakdown, calculations, save/update buttons). Requires auth.
- **`app/dashboard/mix-designs/new/page.tsx`:** Create New Mix Design form (manual entry). Requires auth.
- **`app/dashboard/ai-optimizer/page.tsx`:** AI Optimization Job initiation form (target parameters, constraints). Requires auth.
- **`app/dashboard/ai-optimizer/jobs/page.tsx`:** List of AI Optimization Jobs (status tracking).
- **`app/dashboard/ai-optimizer/jobs/[id]/page.tsx`:** View AI Optimization Job results (proposals, option to save as mix design).
- **`app/dashboard/materials/page.tsx`:** Material Library (view, filter, potentially add/edit materials - role-based access). Requires auth.
- **`app/dashboard/settings/page.tsx`:** User/Company Settings (profile, company details, member management, subscription info). Requires auth.
**Shared UI Components (using shadcn/ui):**
- `Card`, `Button`, `Input`, `Label`, `Form` (from React Hook Form/Zod)
- `Table` (for lists)
- `Dialog`/`AlertDialog` (for confirmations, modals)
- `Tabs` (e.g., for switching between manual/AI design)
- `Select`/`Combobox` (for material selection)
- `Progress` (for AI job status)
- `Alert` (for error messages)
- `SidebarNav`, `Breadcrumbs` (for navigation)
- `Chart` component wrapper (using Recharts)
**State Management:**
- **Auth State:** Global (e.g., Zustand or Context) to hold user session info.
- **Form State:** Local component state or React Hook Form's internal state.
- **Server Cache State:** React Query for API data (mix designs, jobs, materials).
- **UI State:** Local component state for toggles, modals, etc.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** Minimalist Clean with a professional, technical feel.
- **Color Palette:**
- Primary: `#006AFF` (Vibrant Blue for actions, links)
- Secondary: `#6D788A` (Cool Gray for secondary text, borders)
- Accent: `#2563EB` (Slightly darker blue for active states)
- Background: `#FFFFFF` (White for primary content background)
- Card/Surface: `#F8F9FA` (Very light gray for cards, sections)
- Text (Primary): `#111827` (Dark Gray/Black)
- Text (Secondary): `#6B7280` (Medium Gray)
- Success: `#10B981` (Green)
- Warning: `#F59E0B` (Amber)
- Danger: `#EF4444` (Red)
- **Typography:** Inter (sans-serif) - Modern, highly readable.
- Headings: Bold, various sizes (e.g., 3xl, 2xl, xl).
- Body Text: Regular weight, base size (e.g., 16px).
- **Layout:**
- Sidebar navigation on the left for authenticated users.
- Clean header with logo, user profile menu, and notifications.
- Main content area with clear visual hierarchy using cards and spacing.
- Generous whitespace.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows gracefully. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`).
**8. SAMPLE/MOCK DATA:**
- **`users` Table:**
- `{ id: '...', name: 'Alice Smith', email: 'alice@example.com', role: 'admin', ... }`
- `{ id: '...', name: 'Bob Johnson', email: 'bob@example.com', role: 'user', ... }`
- **`companies` Table:**
- `{ id: '...', name: 'American Concrete Co.', industry: 'Concrete', location: 'Chicago, IL', ... }`
- **`material_types` Table:**
- `{ id: '...', name: 'Portland Cement Type I', unit: 'kg/m³', origin_type: 'Domestic', default_properties: { cost_per_unit: 0.15, co2_per_unit: 0.8 } }`
- `{ id: '...', name: 'Class F Fly Ash', unit: 'kg/m³', origin_type: 'Domestic', default_properties: { cost_per_unit: 0.08, co2_per_unit: 0.1 } }`
- `{ id: '...', name: 'Water', unit: 'l/m³', origin_type: 'Domestic', default_properties: { cost_per_unit: 0.002, co2_per_unit: 0 } }`
- `{ id: '...', name: 'Coarse Aggregate (Gravel)', unit: 'kg/m³', origin_type: 'Domestic', default_properties: { cost_per_unit: 0.05, co2_per_unit: 0.01 } }`
- `{ id: '...', name: 'Superplasticizer (PCE-based)', unit: 'kg/m³', origin_type: 'Imported', default_properties: { cost_per_unit: 2.5, co2_per_unit: 3.0 } }`
- **`mix_designs` Table:**
- `{ id: '...', name: 'Standard High Strength Mix', target_strength_mpa: 50, target_cost_per_m3: 160, userId: '...', companyId: '...', created_by_ai: false, ... }`
- `{ id: '...', name: 'Sustainable Mix v2', target_strength_mpa: 35, target_co2_kg_per_m3: 450, userId: '...', companyId: '...', created_by_ai: true, ... }`
- **`mix_design_materials` Table (example for 'Standard High Strength Mix'):**
- `{ id: '...', mixDesignId: '...', materialTypeId: 'cement_id', quantity: 380, quantity_unit: 'kg/m³' }`
- `{ id: '...', mixDesignId: '...', materialTypeId: 'fly_ash_id', quantity: 100, quantity_unit: 'kg/m³' }`
- `{ id: '...', mixDesignId: '...', materialTypeId: 'water_id', quantity: 160, quantity_unit: 'l/m³' }`
- `{ id: '...', mixDesignId: '...', materialTypeId: 'aggregate_id', quantity: 1800, quantity_unit: 'kg/m³' }`
- `{ id: '...', mixDesignId: '...', materialTypeId: 'superplasticizer_id', quantity: 5, quantity_unit: 'kg/m³' }`
- **`ai_optimization_jobs` Table:**
- `{ id: '...', status: 'completed', userId: '...', companyId: '...', createdAt: '...', results: '[{ name: 'AI Optimized Cost-Effective', materials: [...], strength: 55, cost: 145, co2: 510 }, { name: 'AI Optimized Sustainable', materials: [...], strength: 45, cost: 170, co2: 420 }]', ... }`
- `{ id: '...', status: 'processing', userId: '...', companyId: '...', createdAt: '...', ... }`
**9. TURKISH TRANSLATIONS (for key UI elements):**
- Sign Up: Kayıt Ol
- Log In: Giriş Yap
- Dashboard: Kontrol Paneli
- Mix Designs: Karışım Tasarımları
- New Mix Design: Yeni Karışım Tasarımı
- AI Optimizer: Yapay Zeka Optimize Edici
- Materials: Malzemeler
- Settings: Ayarlar
- Create New: Yeni Oluştur
- Save: Kaydet
- Update: Güncelle
- Cancel: İptal
- Name: Ad
- Description: Açıklama
- Strength (MPa): Dayanım (MPa)
- Slump (mm): Çökme (mm)
- Cost per m³: Maliyet / m³
- CO2 per m³: CO2 / m³
- Target: Hedef
- Optimize: Optimize Et
- Pending: Bekleniyor
- Processing: İşleniyor
- Completed: Tamamlandı
- Failed: Başarısız
- View Details: Detayları Gör
- Edit: Düzenle
- Delete: Sil
- Duplicate: Çoğalt
- Apply Filter: Filtre Uygula
- Search: Ara
- No data available: Veri mevcut değil
- Error: Hata
- Success: Başarılı
- Are you sure?: Emin misin?
- This action cannot be undone.: Bu işlem geri alınamaz.
- Domestic: Yerli Üretim
- Imported: İthal
- Properties: Özellikler
- Add Material: Malzeme Ekle
- Required: Gerekli
- Optional: İsteğe Bağlı
- Optimization Goal: Optimizasyon Hedefi
- Prioritize Cost: Maliyeti Önceliklendir
- Prioritize Sustainability: Sürdürülebilirliği Önceliklendir
- Balanced: Dengeli
- My Profile: Profilim
- Company Settings: Şirket Ayarları
- Manage Members: Üyeleri Yönet
- Subscription: Abonelik
- Invite Member: Üye Davet Et
- Role: Rol
- Owner: Sahip
- Member: Üye
- Invitations: Davetler
**10. ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/out transitions using Next.js `AnimatePresence` (from `framer-motion`).
- **Button Hovers:** Slight scale-up or background color change on hover.
- **Loading States:** Use shadcn/ui `Skeleton` components or button `isLoading` props with spinners for data fetching and form submissions.
- **List Item Transitions:** Animate presence for adding/removing items from lists (e.g., materials in a mix design).
- **Chart Interactions:** Tooltips and hover effects on chart elements.
**11. EDGE CASES:**
- **Auth:** Handle expired sessions, incorrect credentials, unauthorized access (redirect or error messages).
- **Validation:** Client-side (React Hook Form + Zod) and server-side validation for all form inputs and API requests.
- **Empty States:** Display informative messages and clear CTAs when lists (mix designs, jobs, materials) are empty.
- **API Errors:** Gracefully handle network errors or server errors, display user-friendly messages.
- **Zero State for AI Jobs:** If no optimization jobs have been run, show a clear prompt to start one.
- **Data Integrity:** Ensure database constraints (unique fields, foreign keys) are respected.
- **Concurrency:** Consider potential race conditions if users can edit the same mix design simultaneously (though less likely in MVP).
- **API Rate Limiting:** Implement if expecting high traffic or potential abuse.