## AI Master Prompt: TechnoLogica - Data-Driven Societal Efficiency Platform
**PROJECT OVERVIEW:**
TechnoLogica is a sophisticated SaaS platform designed to bring the principles of technocracy – efficiency, data-driven decision-making, and engineering-focused problem-solving – into the 21st century. Inspired by the historical movement of the 1930s, TechnoLogica aims to address complex societal and systemic challenges by providing tools for in-depth analysis, scenario modeling, and impact simulation. The platform will empower policymakers, urban planners, researchers, engineers, and organizations to understand the current state of systems (e.g., energy, transportation, resource management), generate data-backed improvement scenarios, and simulate the potential outcomes of these scenarios. The core value proposition is to facilitate rational, evidence-based decision-making for building more efficient, sustainable, and optimized societal structures.
**TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL)
- **UI Library:** shadcn/ui
- **State Management:** React Context API / Zustand (for global state, e.g., auth)
- **Database:** PostgreSQL
- **Authentication:** NextAuth.js (or Clerk for a faster setup)
- **Charting:** Recharts or Chart.js
- **Form Handling:** React Hook Form + Zod for validation
- **Deployment:** Vercel
**DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
1. **`users` Table:**
* `id` (UUID, Primary Key)
* `name` (VARCHAR)
* `email` (VARCHAR, Unique)
* `emailVerified` (TIMESTAMP)
* `image` (VARCHAR, Optional)
* `role` ENUM ('admin', 'user', 'guest') DEFAULT 'user'
* `createdAt` (TIMESTAMP)
* `updatedAt` (TIMESTAMP)
2. **`organizations` Table:** (For B2B features)
* `id` (UUID, Primary Key)
* `name` (VARCHAR, Unique)
* `ownerId` (UUID, Foreign Key to `users.id`)
* `createdAt` (TIMESTAMP)
* `updatedAt` (TIMESTAMP)
3. **`organizationMembers` Table:** (Many-to-many relationship between users and organizations)
* `userId` (UUID, Foreign Key to `users.id`)
* `organizationId` (UUID, Foreign Key to `organizations.id`)
* `role` ENUM ('member', 'admin') DEFAULT 'member'
* `joinedAt` (TIMESTAMP)
* Primary Key (`userId`, `organizationId`)
4. **`systems` Table:** (Represents a system to be analyzed, e.g., 'City X Energy Grid')
* `id` (UUID, Primary Key)
* `organizationId` (UUID, Foreign Key to `organizations.id`, Optional - for shared systems)
* `userId` (UUID, Foreign Key to `users.id`, Owner)
* `name` (VARCHAR)
* `description` (TEXT)
* `category` ENUM ('Energy', 'Transportation', 'Resource Management', 'Education', 'Other')
* `createdAt` (TIMESTAMP)
* `updatedAt` (TIMESTAMP)
5. **`datasets` Table:** (Stores raw data points or references for a system)
* `id` (UUID, Primary Key)
* `systemId` (UUID, Foreign Key to `systems.id`)
* `name` (VARCHAR)
* `description` (TEXT)
* `dataType` ENUM ('JSON', 'CSV', 'TimeSeries', 'KeyPerformanceIndicator')
* `source` (VARCHAR, Optional - e.g., URL, manual entry)
* `uploadedAt` (TIMESTAMP)
* `data` (JSONB, Optional - for simple KPI storage)
6. **`analysisResults` Table:** (Stores the results of an analysis run on a dataset/system)
* `id` (UUID, Primary Key)
* `systemId` (UUID, Foreign Key to `systems.id`)
* `datasetId` (UUID, Foreign Key to `datasets.id`, Optional)
* `analysisType` (VARCHAR - e.g., 'Efficiency Score', 'Bottleneck Identification')
* `results` (JSONB)
* `generatedAt` (TIMESTAMP)
* `generatedByUserId` (UUID, Foreign Key to `users.id`)
7. **`scenarios` Table:** (Represents a proposed change or intervention)
* `id` (UUID, Primary Key)
* `systemId` (UUID, Foreign Key to `systems.id`)
* `name` (VARCHAR)
* `description` (TEXT)
* `parameters` (JSONB - e.g., {'efficiency_target': 0.15, 'investment': 1000000})
* `basedOnAnalysisId` (UUID, Foreign Key to `analysisResults.id`, Optional)
* `createdAt` (TIMESTAMP)
* `createdByUserId` (UUID, Foreign Key to `users.id`)
8. **`simulationResults` Table:** (Stores the output of a simulation run for a scenario)
* `id` (UUID, Primary Key)
* `scenarioId` (UUID, Foreign Key to `scenarios.id`)
* `simulationType` (VARCHAR - e.g., 'Economic Impact', 'Environmental Footprint')
* `results` (JSONB - e.g., {'predicted_gdp_change': 0.02, 'co2_reduction': '5000 tons'})
* `simulatedAt` (TIMESTAMP)
* `simulatedByUserId` (UUID, Foreign Key to `users.id`)
**CORE FEATURES & USER FLOW:**
1. **Authentication & Authorization:**
* **Flow:** User lands on the homepage. Clicks 'Sign In' or 'Sign Up'. Redirected to auth provider (e.g., Google, Email/Password). Upon successful authentication, user is directed to their dashboard.
* **Roles:** 'admin' (full access), 'user' (standard access, can create/manage own systems), 'guest' (read-only access to public data/reports).
* **Edge Case:** Handle failed sign-in attempts, email verification flow, password reset.
2. **System Analysis Module:**
* **Flow:** User navigates to 'Systems' > 'Create New System'. Enters System Name, Description, Category. User then navigates to the System's detail page > 'Datasets' > 'Upload Data'. Selects data type (e.g., KPI, TimeSeries), uploads file or enters manual data. Clicks 'Analyze'. System triggers an analysis task.
* **Functionality:** Backend processes uploaded data, calculates key metrics (efficiency, resource utilization, etc.). Results are stored in `analysisResults` and displayed on the System detail page using charts (Recharts) and key figures.
* **Edge Case:** Handle large file uploads, data validation errors, insufficient data for analysis.
3. **Scenario Generation:**
* **Flow:** From a System's detail page, user clicks 'Create Scenario'. User selects a base analysis result or starts from scratch. User inputs proposed changes via a form (e.g., increase renewable energy input by 20%, optimize public transport routes). Form uses dynamic fields based on system category. Scenario is saved to `scenarios` table.
* **Functionality:** Captures user's proposed intervention parameters. Links the scenario to the system and potentially a prior analysis.
* **Edge Case:** Invalid parameter ranges, unclear scenario descriptions.
4. **Impact Simulation:**
* **Flow:** User navigates to a saved Scenario. Clicks 'Simulate Impact'. User selects simulation type (e.g., Economic, Environmental). A simplified simulation model (backend logic) runs based on the scenario parameters and historical/system data. Results are stored in `simulationResults` and displayed visually.
* **Functionality:** Implements predefined, simplified algorithms to predict outcomes. Focuses on key indicators relevant to the simulation type.
* **Edge Case:** Simulation runtime exceeding limits, unpredictable outcomes, need for user confirmation before simulation.
5. **Reporting & Sharing:**
* **Flow:** User views Analysis Results or Simulation Results. Clicks 'Generate Report'. A PDF or structured text report is generated summarizing the findings. User can download the report or get a shareable link (if permissions allow).
* **Functionality:** Aggregates data from `analysisResults`, `scenarios`, `simulationResults` into a presentable format. Generates unique, potentially time-limited, shareable URLs.
* **Edge Case:** Report generation errors, expired share links, access control for shared reports.
**API & DATA FETCHING:**
- **API Routes (Next.js App Router):** Located in `app/api/`. Examples:
- `POST /api/auth/[...nextauth]/route.ts`: Handles authentication requests.
- `POST /api/systems`: Create a new system.
- `GET /api/systems`: Fetch list of systems for the logged-in user/organization.
- `GET /api/systems/[systemId]`: Fetch details of a specific system.
- `POST /api/systems/[systemId]/datasets`: Upload data for a system.
- `POST /api/systems/[systemId]/analyze`: Trigger a data analysis job (async task).
- `POST /api/systems/[systemId]/scenarios`: Create a new scenario.
- `POST /api/scenarios/[scenarioId]/simulate`: Trigger a simulation job (async task).
- `GET /api/reports/[reportId]`: Fetch generated report data.
- **Data Fetching:** Primarily using server components where possible for direct DB access (via Drizzle ORM within route handlers or server actions). Client components will use `fetch` with appropriate caching or revalidation strategies, or libraries like SWR/React Query if more complex client-side state management is needed. API routes will return JSON payloads.
- **Example Request/Response (POST /api/systems):**
- Request Body (JSON): `{"name": "New York Energy Grid", "description": "Analysis of power consumption and sources in NYC.", "category": "Energy"}`
- Response Body (JSON): `{"id": "uuid-for-new-system", "message": "System created successfully."}`
**COMPONENT BREAKDOWN (Next.js App Router Structure):**
- **`app/`**
- **`(auth)` Group (Optional, for cleaner routing if needed):**
- `layout.tsx`: Auth layout (e.g., centered card).
- `signin/page.tsx`: Sign-in form page.
- `signup/page.tsx`: Sign-up form page.
- **`(app)` Group (Protected Routes):**
- `layout.tsx`: Main application layout (Sidebar, Header, Content Area).
- `dashboard/page.tsx`: User dashboard (overview of systems, recent activity). **Components:** `DashboardHeader`, `SystemOverviewCard` (list), `RecentActivityFeed`.
- `systems/page.tsx`: List of all user's systems. **Components:** `SystemListTable`, `CreateSystemButton`, `SystemListItem`.
- `systems/[systemId]/`:
- `page.tsx`: System detail view. **Components:** `SystemHeader`, `SystemTabs` (Analysis, Scenarios, Settings), `AnalysisSummaryCard`, `ScenarioList`, `DatasetUploadForm`.
- `analysis/[analysisId]/page.tsx`: Detailed view of a specific analysis result. **Components:** `AnalysisChart`, `KeyMetricsTable`, `GenerateReportButton`.
- `scenarios/[scenarioId]/page.tsx`: Detailed view of a scenario and its simulation. **Components:** `ScenarioDetails`, `SimulationResultsChart`, `RunSimulationButton`, `DownloadReportButton`.
- `settings/page.tsx`: User profile and account settings. **Components:** `ProfileForm`, `SecuritySettings`, `OrganizationManagement` (if applicable).
- **`layout.tsx`:** Root layout (HTML, Body, Providers).
- **`page.tsx`:** Landing Page (Public).
- **`api/`:** API routes (as described above).
- **`components/ui/`:** Reusable UI components from shadcn/ui.
- **`components/`:** Custom application components.
- `AuthButton.tsx`
- `Sidebar.tsx`
- `Header.tsx`
- `ChartComponent.tsx` (Wrapper for Recharts/Chart.js)
- `DataTable.tsx` (For lists of systems, scenarios, etc.)
- `FormInput.tsx` (Wrapper for RHF/Zod)
- `LoadingSpinner.tsx`
- `EmptyState.tsx`
- **`lib/`:** Utility functions, database client (Drizzle), auth config.
- **`hooks/`:** Custom React Hooks.
- **`styles/`:** Global CSS (if any, beyond Tailwind).
**State Management:** Primarily prop drilling or Context API for simpler global states like user authentication status. For complex data fetching and caching, consider React Query or SWR within client components. Server Components fetch data directly.
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** Modern, Clean, Data-Centric.
- **Color Palette:**
- Primary: `#007AFF` (Vibrant Blue - for interactive elements, highlights)
- Secondary: `#5856D6` (Slightly muted purple/blue - for secondary actions, accents)
- Background: `#F8F9FA` (Very Light Gray - main background)
- Surface/Card Background: `#FFFFFF` (White - for cards, modals)
- Text (Primary): `#212529` (Dark Gray)
- Text (Secondary): `#6C757D` (Medium Gray)
- Accent/Success: `#28A745` (Green)
- Warning/Alert: `#FFC107` (Amber)
- Error: `#DC3545` (Red)
- **Typography:**
- Headings: Inter (Variable Font, Bold)
- Body Text: Inter (Variable Font, Regular)
- **Layout:** Generous whitespace. Clear information hierarchy. A persistent sidebar for navigation in authenticated views. Header for user profile, notifications, and global search (future).
- **Responsive Rules:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content adjusts fluidly. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`) extensively.
- **Interactions:** Subtle hover effects on buttons and links. Smooth transitions for expanding/collapsing sections. Loading states clearly indicated with spinners or skeleton screens.
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/fade-out using Next.js's built-in features or libraries like `Framer Motion` if more complex animations are desired.
- **Hover Effects:** Slight scale-up or background color change on interactive elements (`transition-all duration-200 ease-in-out`).
- **Loading States:** Use `shadcn/ui`'s `Skeleton` component or a simple `LoadingSpinner` component when data is being fetched or operations are in progress. Indeterminate progress bars for longer tasks like analysis/simulation.
- **Data Entry:** Smooth focus transitions on form inputs.
**EDGE CASES:**
- **Authentication:** Handle expired tokens, different provider flows, social login errors, email verification.
- **Data Handling:** Gracefully handle invalid file formats, empty datasets, missing required fields during upload. Provide clear error messages to the user. Implement backend validation for all data inputs.
- **Empty States:** All lists (systems, datasets, scenarios) should display informative 'Empty State' messages with clear calls to action (e.g., "You haven't created any systems yet. Click here to add one.").
- **Authorization:** Ensure users can only access/modify their own data or data within their organization, based on role.
- **API Errors:** Implement global error handling for API routes. Return consistent error formats (e.g., `{"error": "message", "statusCode": 400}`).
- **Long-Running Tasks:** For analysis and simulation, implement asynchronous processing using job queues (e.g., BullMQ with Redis, or simpler background tasks on Vercel if feasible) and provide feedback to the user on progress/completion.
- **Validation:** Implement robust validation on all user inputs using Zod and React Hook Form (e.g., non-empty strings, valid number ranges, correct data formats).
**SAMPLE DATA (Mock Data Examples):**
1. **System:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-123",
"name": "Cityville Public Transport Efficiency",
"category": "Transportation",
"createdAt": "2024-03-10T10:00:00Z"
}
```
2. **Dataset (KPI):**
```json
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"systemId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Monthly Ridership & On-Time Performance",
"dataType": "KeyPerformanceIndicator",
"data": {
"month": "2024-02",
"total_riders": 1205000,
"avg_on_time_percentage": 88.5,
"avg_delay_minutes": 3.2
},
"uploadedAt": "2024-03-11T11:30:00Z"
}
```
3. **Analysis Result:**
```json
{
"id": "11223344-5566-7788-9900-aabbccddeeff",
"systemId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"datasetId": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"analysisType": "Efficiency Score & Bottleneck Identification",
"results": {
"overall_efficiency_score": 78,
"key_metrics": [
{"name": "Ridership Growth Rate", "value": "+5% MoM"},
{"name": "On-Time Performance", "value": "88.5%", "target": "90%"},
{"name": "Average Delay", "value": "3.2 min", "target": "< 3 min"}
],
"bottlenecks": ["Route 5 frequency", "Station A overcrowding"]
},
"generatedAt": "2024-03-11T14:00:00Z"
}
```
4. **Scenario:**
```json
{
"id": "abcdef12-3456-7890-abcd-ef1234567890",
"systemId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Increase Route 5 Frequency & Add Express Buses",
"description": "Add 5 more buses to Route 5 during peak hours and introduce 2 express routes connecting major hubs.",
"parameters": {
"route_5_frequency_increase": 0.20, // 20%
"new_express_routes": 2,
"estimated_cost": 1500000
},
"basedOnAnalysisId": "11223344-5566-7788-9900-aabbccddeeff",
"createdAt": "2024-03-12T09:00:00Z"
}
```
5. **Simulation Result:**
```json
{
"id": "98765432-10fe-dcba-9876-543210fedcba",
"scenarioId": "abcdef12-3456-7890-abcd-ef1234567890",
"simulationType": "Potential Impact (Ridership & Delay)",
"results": {
"predicted_ridership_increase": "+15%",
"predicted_on_time_percentage": "92%",
"predicted_delay_reduction": "1.5 min",
"estimated_cost_vs_benefit_ratio": 1.8,
"environmental_impact": "-5% CO2 emissions due to reduced idling"
},
"simulatedAt": "2024-03-12T11:45:00Z"
}
```
6. **User (Admin):**
```json
{
"id": "admin-uuid-001",
"name": "Admin User",
"email": "admin@technologica.com",
"role": "admin",
"createdAt": "2024-01-01T00:00:00Z"
}
```
7. **Organization:**
```json
{
"id": "org-uuid-metro",
"name": "Metro Transit Authority",
"ownerId": "user-uuid-123",
"createdAt": "2024-03-05T15:00:00Z"
}
```
8. **Organization Member:**
```json
{
"userId": "user-uuid-456",
"organizationId": "org-uuid-metro",
"role": "member",
"joinedAt": "2024-03-05T15:05:00Z"
}
```
9. **Report (Summary Object):**
```json
{
"reportId": "rep-uuid-xyz",
"title": "Analysis & Simulation Report: Cityville Public Transport",
"generatedFor": {
"systemName": "Cityville Public Transport Efficiency",
"analysisName": "Efficiency Score & Bottleneck Identification",
"scenarioName": "Increase Route 5 Frequency & Add Express Buses"
},
"summary": "Proposed scenario shows significant potential for improving on-time performance and reducing delays, with a positive ridership growth projection.",
"generatedAt": "2024-03-12T12:00:00Z",
"generatedBy": "user-uuid-123"
}
```
10. **Notification:**
```json
{
"id": "notif-uuid-abc",
"userId": "user-uuid-123",
"message": "Your analysis for 'Cityville Public Transport Efficiency' is complete.",
"type": "analysis_complete",
"read": false,
"createdAt": "2024-03-11T14:05:00Z"
}
```