PROJECT OVERVIEW:
We are building a comprehensive SaaS application called "Microplastic Monitor" designed to address a critical issue in scientific research: the overestimation of microplastic concentrations caused by contamination from nitrile and latex gloves. The application will provide researchers, scientists, and lab technicians with tools to identify, quantify, and report on glove-induced microplastic contamination in their samples. This ensures the integrity and accuracy of scientific data related to microplastics, a growing environmental concern. The core value proposition is to enhance the reliability of microplastic research by mitigating a common and significant source of error.
TECH STACK:
- Frontend: React (Next.js App Router)
- Styling: Tailwind CSS
- ORM: Drizzle ORM (for PostgreSQL)
- Database: PostgreSQL
- Authentication: NextAuth.js (or Clerk for simpler integration)
- UI Components: shadcn/ui
- State Management: Zustand or React Context API
- Charting Library: Chart.js or Recharts
- Form Handling: React Hook Form with Zod for validation
- Other: Axios for API requests, date-fns for date handling, uuid for unique IDs
DATABASE SCHEMA:
We will use PostgreSQL with Drizzle ORM.
1. `users` table:
- `id` (UUID, Primary Key)
- `name` (VARCHAR)
- `email` (VARCHAR, Unique)
- `emailVerified` (TIMESTAMP)
- `image` (VARCHAR, nullable)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
2. `organizations` table (for team/lab management):
- `id` (UUID, Primary Key)
- `name` (VARCHAR, Unique)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
3. `user_organizations` table (many-to-many relationship):
- `userId` (UUID, Foreign Key to `users.id`)
- `organizationId` (UUID, Foreign Key to `organizations.id`)
- `role` (VARCHAR, e.g., 'admin', 'member')
- `joinedAt` (TIMESTAMP)
4. `glove_manufacturers` table:
- `id` (UUID, Primary Key)
- `name` (VARCHAR, Unique)
- `country` (VARCHAR)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
5. `glove_models` table:
- `id` (UUID, Primary Key)
- `manufacturerId` (UUID, Foreign Key to `glove_manufacturers.id`)
- `modelName` (VARCHAR)
- `gloveType` (ENUM: 'nitrile', 'latex', 'vinyl', 'neoprene')
- `color` (VARCHAR, nullable)
- `thicknessMM` (DECIMAL, nullable)
- `description` (TEXT, nullable)
- `addedByUserId` (UUID, Foreign Key to `users.id`, nullable - for user-submitted data)
- `isVerified` (BOOLEAN, default: false)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
6. `glove_contamination_data` table:
- `id` (UUID, Primary Key)
- `gloveModelId` (UUID, Foreign Key to `glove_models.id`)
- `sampleId` (VARCHAR, user-defined identifier for the specific lab sample)
- `analysisMethod` (VARCHAR, e.g., 'FTIR', 'Raman Spectroscopy')
- `microplasticCount` (INTEGER)
- `measurementUnit` (VARCHAR, e.g., 'particles/L', 'particles/m²')
- `sampleVolumeOrArea` (DECIMAL, nullable)
- `contaminationSource` (ENUM: 'glove', 'environment', 'reagent', 'unknown')
- `notes` (TEXT, nullable)
- `analysisDate` (DATE)
- `userId` (UUID, Foreign Key to `users.id`)
- `organizationId` (UUID, Foreign Key to `organizations.id`)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
7. `glove_tests` table (for user-submitted validation data):
- `id` (UUID, Primary Key)
- `gloveModelId` (UUID, Foreign Key to `glove_models.id`)
- `testDate` (DATE)
- `protocolDescription` (TEXT)
- `averageMicroplasticCount` (DECIMAL)
- `standardDeviation` (DECIMAL, nullable)
- `userId` (UUID, Foreign Key to `users.id`)
- `organizationId` (UUID, Foreign Key to `organizations.id`)
- `status` (ENUM: 'pending', 'approved', 'rejected')
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
CORE FEATURES & USER FLOW:
1. **User Authentication & Organization Management:**
- **Flow:** Users sign up using email/password or OAuth (Google/GitHub). Upon first login, they are prompted to create or join an organization (representing their lab or research group). This isolates data and facilitates team collaboration.
- **Details:** Secure authentication using NextAuth.js. Organization roles (admin, member) manage permissions. Admins can invite new members.
2. **Glove Database Management:**
- **Flow:** Users can browse, search, and filter the existing database of glove models (manufacturer, model name, type, color, thickness). Verified entries are marked. Users can also submit new glove models for verification by admins or the community.
- **Details:** Search/filter UI. 'Add Glove' form with fields for manufacturer, model, type, etc. Submissions go into a pending state (`isVerified=false`) in `glove_models` table. Admin dashboard to review and verify submissions.
3. **Contamination Data Entry & Analysis:**
- **Flow:** Users select a glove model, enter sample details (ID, volume/area), analysis method, microplastic count, unit, and date. They can tag the contamination source. The system records this in `glove_contamination_data`. Users can also initiate a comparative analysis by selecting a glove model and entering control sample data (e.g., a sample analyzed without gloves or with a control material).
- **Details:** Intuitive form for data entry. Auto-selection of organization and user ID. Calculation of 'glove-induced' contamination based on user-defined baselines or aggregated data from the database. UI for selecting and comparing sample datasets.
4. **Reporting & Visualization:**
- **Flow:** Users can generate reports based on their entered data or by querying the database. Reports include summary statistics, charts (bar charts for counts, line charts for trends over time), and tables detailing glove type, contamination levels, and confidence intervals.
- **Details:** Dashboard widgets showing recent entries, overall contamination trends. Dedicated reporting section with customizable date ranges and filters. Export options (PDF, CSV).
5. **User-Submitted Glove Testing (MVP Extension):**
- **Flow:** Users perform their own controlled tests to quantify contamination from specific gloves. They enter test details (protocol, average count, std dev) into the `glove_tests` table. These submissions can be flagged for verification and potentially add new data points to the `glove_models` for community use.
- **Details:** Specific form for submitting test results. Admin interface to review and approve/reject these tests. Approved tests can update `glove_models` or contribute to aggregated statistical models.
API & DATA FETCHING:
- Utilize Next.js API Routes (or Server Actions) for backend logic.
- **Auth Endpoints:** `/api/auth/[...nextauth]` (handled by NextAuth.js)
- **Glove Endpoints:**
- `GET /api/gloves`: Fetch list of glove models (with filtering/search parameters).
- `POST /api/gloves`: Add a new glove model (requires authentication).
- `GET /api/gloves/:id`: Fetch details of a specific glove model.
- `POST /api/gloves/:id/submit-test`: Submit a test result for a glove model.
- **Data Entry Endpoints:**
- `POST /api/samples`: Record a new sample analysis result.
- `GET /api/samples`: Fetch user's sample analysis results (with filtering).
- `GET /api/samples/:id`: Fetch details of a specific sample analysis.
- **Reporting Endpoints:**
- `GET /api/reports/summary`: Get aggregated statistics for the dashboard.
- `GET /api/reports/glove-comparison?gloveId1=...&gloveId2=...`: Get data for comparative charts.
- **Data Fetching in Components:** Use server components where possible for direct data access. For client-side interactivity or dynamic updates, use `fetch` within `useEffect` hooks or libraries like SWR/React Query, passing necessary authentication tokens.
- **Request/Response:** Standard JSON. Use zod for request validation and response shaping.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style:** "Minimalist Clean" with a focus on data clarity and scientific professionalism.
- **Color Palette:**
- Primary: `#4A90E2` (Calm Blue)
- Secondary: `#50E3C2` (Teal/Mint Accent)
- Background: `#F8F9FA` (Very Light Gray)
- Text: `#212529` (Dark Gray)
- Muted: `#ADB5BD` (Light Gray for secondary text/borders)
- Alerts: `#F5A623` (Orange), `#D0021B` (Red)
- **Typography:** Inter or SF Pro Display (system font stack). Clear hierarchy with distinct heading sizes and weights.
- **Layout:** Clean, card-based UI. Sidebar navigation for main sections (Dashboard, Gloves, Samples, Reports, Settings). Main content area uses a grid system for responsiveness.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows into single columns. Minimum width of 768px for tablet layouts, 1024px for desktops.
- **Visual Elements:** Subtle use of icons (Lucide React). Clean data tables with hover effects. Progress indicators for loading states. Minimal animations to avoid distraction.
COMPONENT BREAKDOWN (Next.js App Router):
- `app/layout.tsx`: Root layout, global providers (e.g., ThemeProvider, AuthProvider), global styles, font setup.
- `app/(auth)/layout.tsx`: Auth pages layout.
- `app/(auth)/signin/page.tsx`: Sign-in page.
- `app/(auth)/signup/page.tsx`: Sign-up page.
- `app/(app)/layout.tsx`: Main application layout (with sidebar/header).
- `app/(app)/dashboard/page.tsx`: Dashboard page. Displays overview widgets, recent activity, key stats.
- Components: `DashboardStatsGrid`, `RecentEntriesTable`, `ContaminationTrendChart`.
- `app/(app)/gloves/page.tsx`: Glove database browser. Search, filter, list gloves.
- Components: `GloveSearchFilter`, `GloveList`, `GloveListItem`, `AddGloveButton`.
- `app/(app)/gloves/[gloveId]/page.tsx`: Detailed view of a specific glove model.
- Components: `GloveDetailCard`, `ContaminationDataTable` (for this glove), `SubmitTestForm`.
- `app/(app)/samples/page.tsx`: Sample analysis data entry and management.
- Components: `SampleEntryForm`, `SampleList`, `SampleFilter`. Uses `React Hook Form` for `SampleEntryForm`.
- `app/(app)/reports/page.tsx`: Report generation page.
- Components: `ReportFilters`, `ReportChart`, `ReportTable`, `ExportButton`.
- `app/(app)/settings/page.tsx`: User and organization settings.
- Components: `ProfileForm`, `OrganizationSettings`, `MemberManagement`.
- `components/ui/`: Re-exports from shadcn/ui (Button, Input, Card, Table, etc.).
- `components/layout/`: `Sidebar`, `Header`, `Footer`.
- `components/charts/`: Wrapper components for charting libraries.
- `components/forms/`: Reusable form components (e.g., `GloveForm`, `SampleForm`).
- `hooks/`: Custom React hooks (e.g., `useAuth`, `useApi`).
- `lib/`: Utility functions, database client setup (Drizzle).
- `server/`: API route handlers or Server Action implementations.
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/fade-out using Next.js `useRouter` events or Framer Motion (if complexity allows). Default Next.js transition behavior is acceptable for MVP.
- **Loading States:** Skeleton loaders for data fetching. Spinner components (`shadcn/ui/spinner`) integrated into buttons during submission.
- **Hover Effects:** Slight scale or background color change on interactive elements (buttons, table rows, cards).
- **Transitions:** Smooth transitions on expanding/collapsing elements (e.g., table rows, accordions).
EDGE CASES:
- **Authentication:** Redirect unauthenticated users to login. Protect all API routes and app pages requiring login. Handle expired sessions gracefully.
- **Authorization:** Ensure users can only access/modify data belonging to their organization. Implement role-based access control for admin actions.
- **Data Validation:** Use Zod schemas for all form inputs and API request bodies. Implement server-side validation in API routes/Server Actions.
- **Empty States:** Provide clear messages and calls-to-action when lists or data tables are empty (e.g., "No gloves found. Add your first glove model!", "No sample data yet. Start by entering your first analysis.").
- **Error Handling:** Global error handling boundary. Specific error messages for API failures (e.g., "Failed to save sample. Please try again."). Display user-friendly messages, avoid exposing raw error details.
- **API Errors:** Implement consistent error responses from API routes. Handle `400 Bad Request`, `401 Unauthorized`, `403 Forbidden`, `404 Not Found`, `500 Internal Server Error`.
- **Concurrency:** Consider optimistic UI updates for faster perceived performance, but ensure proper rollback on failure.
SAMPLE DATA:
1. **Glove Model:**
- Manufacturer: "ChemProtect"
- Model Name: "NitrilePro Series"
- Type: "nitrile"
- Color: "Blue"
- Thickness: 0.12
2. **Glove Model:**
- Manufacturer: "MediGrip"
- Model Name: "Latex Comfort Fit"
- Type: "latex"
- Color: "Clear"
- Thickness: 0.10
3. **Sample Analysis Data (High Contamination):**
- Glove Model: ChemProtect NitrilePro Series
- Sample ID: "WP-2023-S01"
- Analysis Method: "FTIR"
- Microplastic Count: 150
- Measurement Unit: "particles/L"
- Sample Volume: 1.0
- Contamination Source: "glove"
- Analysis Date: "2023-10-26"
4. **Sample Analysis Data (Low Contamination):**
- Glove Model: MediGrip Latex Comfort Fit
- Sample ID: "FW-2023-S05"
- Analysis Method: "Raman Spectroscopy"
- Microplastic Count: 15
- Measurement Unit: "particles/m²"
- Sample Area: 0.5
- Contamination Source: "environment"
- Analysis Date: "2023-10-25"
5. **Sample Analysis Data (Unknown Source):**
- Glove Model: ChemProtect NitrilePro Series
- Sample ID: "LW-2023-C02"
- Analysis Method: "FTIR"
- Microplastic Count: 75
- Measurement Unit: "particles/L"
- Sample Volume: 1.0
- Contamination Source: "unknown"
- Analysis Date: "2023-10-27"
6. **User Submitted Glove Test:**
- Glove Model: "Generic Nitrile Glove (Brand X)"
- Test Date: "2023-10-20"
- Protocol: "Standardized Soak Test (ISO Method XYZ)"
- Average Count: 95.5
- Std Dev: 12.3
- Status: "pending"
7. **User:**
- Name: "Dr. Elif Arslan"
- Email: "elif.arslan@exampleuni.edu"
8. **Organization:**
- Name: "Oceanic Research Institute"
9. **Mock Report Data (Summary for Dashboard):**
- Total Samples Analyzed: 150
- Average Glove Contamination: 68.2 particles/L
- Most Common Contamination Source: "glove" (65% of samples)
- Verified Glove Models: 45
10. **Another Sample Analysis (Control or different glove):**
- Glove Model: "VinylGuard Standard"
- Sample ID: "HW-2023-S10"
- Analysis Method: "FTIR"
- Microplastic Count: 30
- Measurement Unit: "particles/L"
- Sample Volume: 1.0
- Contamination Source: "environment"
- Analysis Date: "2023-10-28"