## AI Master Prompt for DataTrust Hub MVP Development
**PROJECT OVERVIEW:**
DataTrust Hub is a SaaS platform designed to address the growing ethical concerns surrounding the management of sensitive health data by third-party technology providers. Specifically targeting healthcare professionals within national health systems (like the NHS), it provides an independent auditing, risk assessment, and transparent reporting tool for data platforms. The core value proposition is to empower healthcare staff by offering a trusted, unbiased source of information on the ethical compliance and data security of the platforms they are required to use, thereby mitigating risks to patient privacy and fostering trust in health data management.
**TECH STACK:**
- **Frontend Framework:** React (Next.js with App Router for server components and routing)
- **Styling:** Tailwind CSS (with arbitrary value support and custom configuration)
- **ORM:** Drizzle ORM (PostgreSQL adapter)
- **Database:** PostgreSQL
- **Authentication:** NextAuth.js (with PostgreSQL adapter)
- **UI Components:** shadcn/ui (built on Radix UI and Tailwind CSS)
- **State Management:** Zustand (for global state) and React Context API (for local/shared component state)
- **Form Handling:** React Hook Form with Zod for validation
- **Charting:** Recharts or Chart.js for data visualization
- **API Layer:** Next.js API Routes (or Server Actions for simpler CRUD)
- **Deployment:** Vercel or similar platform
- **Other:** Axios for client-side HTTP requests, date-fns for date manipulation.
**DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
1. **`users` table:**
* `id` (UUID, primary key)
* `name` (TEXT)
* `email` (TEXT, unique)
* `emailVerified` (TIMESTAMPZ)
* `image` (TEXT, nullable)
* `role` (VARCHAR(20) DEFAULT 'user') -- 'user', 'admin', 'auditor'
* `createdAt` (TIMESTAMPZ DEFAULT now())
* `updatedAt` (TIMESTAMPZ DEFAULT now())
2. **`accounts` table:** (For NextAuth.js)
* `id` (TEXT, primary key)
* `userId` (UUID, foreign key to `users.id`)
* `type` (TEXT)
* `provider` (TEXT)
* `providerAccountId` (TEXT)
* `refresh_token` (TEXT, nullable)
* `access_token` (TEXT, nullable)
* `expires_at` (BIGINT, nullable)
* `token_type` (TEXT, nullable)
* `scope` (TEXT, nullable)
* `id_token` (TEXT, nullable)
* `session_state` (TEXT, nullable)
3. **`sessions` table:** (For NextAuth.js)
* `id` (BIGINT, primary key)
* `sessionToken` (TEXT, unique)
* `userId` (UUID, foreign key to `users.id`)
* `expires` (TIMESTAMPZ)
4. **`verificationTokens` table:** (For NextAuth.js)
* `identifier` (TEXT)
* `token` (TEXT)
* `expires` (TIMESTAMPZ)
5. **`dataPlatforms` table:**
* `id` (UUID, primary key)
* `name` (TEXT, not null, unique)
* `provider` (TEXT)
* `description` (TEXT)
* `websiteUrl` (TEXT, nullable)
* `createdAt` (TIMESTAMPZ DEFAULT now())
* `updatedAt` (TIMESTAMPZ DEFAULT now())
6. **`audits` table:**
* `id` (UUID, primary key)
* `platformId` (UUID, foreign key to `dataPlatforms.id`)
* `auditorId` (UUID, foreign key to `users.id`, nullable) -- The user who performed the audit
* `auditDate` (TIMESTAMPZ DEFAULT now())
* `overallScore` (INTEGER) -- e.g., 1-100
* `complianceScore` (INTEGER)
* `securityScore` (INTEGER)
* `ethicalScore` (INTEGER)
* `summary` (TEXT)
* `reportUrl` (TEXT, nullable)
* `createdAt` (TIMESTAMPZ DEFAULT now())
* `updatedAt` (TIMESTAMPZ DEFAULT now())
7. **`auditCriteria` table:** (For defining audit parameters)
* `id` (UUID, primary key)
* `name` (TEXT, not null)
* `description` (TEXT)
* `weight` (FLOAT) -- e.g., 0.2 for weighting in overall score
* `type` (VARCHAR(20)) -- 'compliance', 'security', 'ethical'
8. **`auditResults` table:** (Linking specific audits to criteria scores)
* `id` (UUID, primary key)
* `auditId` (UUID, foreign key to `audits.id`)
* `criterionId` (UUID, foreign key to `auditCriteria.id`)
* `score` (INTEGER)
* `notes` (TEXT, nullable)
9. **`concerns` table:** (User-reported issues)
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to `users.id`, nullable)
* `platformId` (UUID, foreign key to `dataPlatforms.id`, nullable)
* `title` (TEXT, not null)
* `description` (TEXT, not null)
* `isAnonymous` (BOOLEAN DEFAULT true)
* `status` (VARCHAR(20) DEFAULT 'open') -- 'open', 'investigating', 'resolved', 'closed'
* `createdAt` (TIMESTAMPZ DEFAULT now())
* `updatedAt` (TIMESTAMPZ DEFAULT now())
10. **`discussions` table:** (Forum for user discussions)
* `id` (UUID, primary key)
* `parentId` (UUID, foreign key to `discussions.id`, nullable) -- for threading
* `userId` (UUID, foreign key to `users.id`)
* `title` (TEXT)
* `content` (TEXT)
* `createdAt` (TIMESTAMPZ DEFAULT now())
* `updatedAt` (TIMESTAMPZ DEFAULT now())
11. **`platformRatings` table:**
* `id` (UUID, primary key)
* `platformId` (UUID, foreign key to `dataPlatforms.id`)
* `userId` (UUID, foreign key to `users.id`)
* `rating` (INTEGER) -- e.g., 1-5
* `comment` (TEXT, nullable)
* `createdAt` (TIMESTAMPZ DEFAULT now())
**CORE FEATURES & USER FLOW:**
1. **User Authentication:**
* **Flow:** Users can sign up using email/password or OAuth (Google, GitHub). Upon signup, a user record is created. Users can log in via the `pages/api/auth/[...nextauth].ts` route. Protected routes (e.g., dashboard, audit submission) require authentication.
* **Details:** Implement email verification. Role-based access control (RBAC) will be necessary (user, admin, auditor roles).
2. **Platform Management (Admin Only):**
* **Flow:** Admins can add new data platforms, edit existing platform details (name, provider, website), and delete platforms.
* **Details:** This will involve forms and API routes/Server Actions.
3. **Audit Creation & Submission:**
* **Flow:** Authenticated users (specifically auditors or designated staff) can initiate a new audit for a selected platform. They will be presented with a form corresponding to `auditCriteria`. Each criterion will have a score input (e.g., 1-10) and a notes field. After completing all criteria, the user submits the audit. The system calculates `overallScore` based on weighted criteria (`auditCriteria.weight`). A summary and optional report URL can be added.
* **Details:** Use `react-hook-form` for the multi-step audit form. Implement frontend validation. Server-side logic will create entries in `audits`, `auditResults` tables.
4. **Platform Dashboard:**
* **Flow:** An overview page displaying all data platforms. Each platform card shows its name, provider, and a summary of its latest audit score (e.g., average score or latest score). Clicking a platform card navigates to its detail page.
* **Details:** Fetch data from `dataPlatforms` and `audits` tables. Use pagination if the list grows large.
5. **Platform Detail Page:**
* **Flow:** Displays detailed information about a single platform. Shows historical audit scores (perhaps a trend chart using Recharts), list of user concerns, and related discussions. Users can submit new concerns or rate the platform from here.
* **Details:** Fetch data from `dataPlatforms`, `audits`, `concerns`, `discussions`, `platformRatings`. Implement a charting component for historical data.
6. **User Concerns Reporting:**
* **Flow:** Any authenticated user can report an ethical concern related to a platform (or general data handling). They can choose to remain anonymous. The concern is submitted via a form and stored in the `concerns` table.
* **Details:** The form should include platform selection (optional), title, description, and an anonymity checkbox. Admins can view and update the status of concerns.
7. **Discussion Forum:**
* **Flow:** Authenticated users can create new discussion threads or reply to existing ones. The forum is organized hierarchically (parent/child discussions).
* **Details:** Implement CRUD operations for discussions. Use `parentId` for threading. Display discussions in a nested or tree-like structure.
8. **Ethical Alert System (MVP - Basic):**
* **Flow:** Users can set thresholds for specific scores (e.g., notify me if a platform's ethical score drops below 6). The system checks new audits against these thresholds and triggers an in-app notification or email (future enhancement).
* **Details:** Requires a background job or periodic checks. For MVP, focus on displaying alerts on the dashboard if a platform falls below a critical threshold.
**API & DATA FETCHING:**
- **Next.js API Routes:** Utilize `pages/api/` routes or Next.js Server Actions for CRUD operations.
- **Data Fetching:** Use `fetch` within Server Components (App Router) for server-side data fetching. For client-side interactions (e.g., form submissions, real-time updates if needed), use `axios` or the native `fetch` API in client components or API routes.
- **Example API Route (`/api/platforms`):**
* `GET /api/platforms`: Fetch list of platforms with their latest audit scores. Response: `[{ id, name, provider, latestScore, latestAuditDate }, ...]`
* `POST /api/platforms`: Create a new platform (Admin only). Request Body: `{ name, provider, description, websiteUrl }`. Response: `201 Created` or error.
- **Server Actions Example (for Audit Submission):**
```javascript
// app/audits/create/actions.ts
'use server';
import { db } from '@/lib/db'; // Drizzle connection
import { audits, auditResults } from '@/lib/schema'; // Drizzle schema
import { eq } from 'drizzle-orm';
import { revalidatePath } -> 'react';
export async function submitAudit(formData) {
const validatedData = auditSchema.parse(formData); // Zod validation
const { platformId, criteriaScores, ...auditDetails } = validatedData;
// Calculate overall score logic here...
const overallScore = calculateScore(criteriaScores);
try {
const newAudit = await db.insert(audits).values({...auditDetails, overallScore, platformId}).returning({ id: audits.id });
const auditId = newAudit[0].id;
for (const criterion of criteriaScores) {
await db.insert(auditResults).values({ auditId, criterionId: criterion.id, score: criterion.score, notes: criterion.notes });
}
revalidatePath('/dashboard'); // Revalidate cache
return { success: true, auditId };
} catch (error) {
console.error('Audit submission failed:', error);
return { success: false, message: 'Failed to submit audit.' };
}
}
```
**COMPONENT BREAKDOWN (Next.js App Router):**
- **`app/layout.tsx`:** Root layout (HTML, body, providers, global styles).
- **`app/page.tsx`:** Landing Page (Marketing content, value proposition, CTA).
- **`app/(auth)/login/page.tsx`:** Login page (using shadcn/ui form).
- **`app/(auth)/signup/page.tsx`:** Signup page.
- **`app/dashboard/page.tsx`:** Main dashboard. Lists platforms, shows alerts. Fetches data from `platforms` and `audits` API/Server Actions.
- **Components:** `PlatformList`, `PlatformCard`, `AlertBanner`.
- **`app/platforms/[platformId]/page.tsx`:** Platform Detail Page. Shows platform info, audit history, charts, concerns, discussions.
- **Components:** `PlatformInfo`, `AuditHistoryChart`, `ConcernList`, `DiscussionThread`, `RatePlatformForm`.
- **`app/audits/new/page.tsx`:** New Audit Form Page. Multi-step form for submitting audit data.
- **Components:** `AuditFormStep1`, `AuditFormStep2`, `AuditCriteriaItem`, `SubmitButton`.
- **`app/concerns/page.tsx`:** Report a Concern Page. Form for submitting user concerns.
- **Components:** `ConcernForm`.
- **`app/discussions/page.tsx`:** Discussion Forum Page. Lists discussion threads.
- **Components:** `DiscussionList`, `DiscussionListItem`, `CreateThreadButton`.
- **`app/discussions/[threadId]/page.tsx`:** Individual Discussion Thread Page. Shows posts and allows replies.
- **Components:** `PostList`, `ReplyForm`.
- **`app/admin/platforms/page.tsx`:** Admin - Manage Platforms. CRUD interface.
- **Components:** `PlatformTable`, `AddPlatformForm`, `EditPlatformForm`.
- **`app/admin/users/page.tsx`:** Admin - Manage Users (view, roles).
- **Components:** `UserTable`.
- **`app/settings/page.tsx`:** User Settings Page (profile, alert preferences).
- **Components:** `ProfileForm`, `AlertSettings`.
- **`app/api/auth/[...nextauth]/route.ts`:** NextAuth.js configuration.
- **`lib/components/*`:** Shared UI components (Button, Input, Card, etc. from shadcn/ui or custom).
- **`lib/db.ts`:** Drizzle ORM database connection setup.
- **`lib/schema.ts`:** Drizzle schema definitions.
- **`hooks/*`:** Custom React hooks (e.g., `useAuth`, `useFetch`).
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** Minimalist Clean with a focus on trust and clarity.
- **Color Palette:**
- Primary: `#1A73E8` (Trustworthy Blue)
- Secondary: `#34A853` (Positive Green for good scores)
- Accent/Alert: `#EA4335` (Warning Red for low scores/concerns)
- Neutral Dark: `#202124` (Backgrounds, dark text)
- Neutral Light: `#F8F9FA` (Backgrounds, light text)
- Grays: `#BDC1C6`, `#DADCE0`, `#E8EAED` (Borders, subtle backgrounds)
- **Typography:** Google Fonts - 'Inter' for body text (clean, readable), 'Roboto Slab' for headings (slightly formal, trustworthy).
- `h1`, `h2`, `h3`: Roboto Slab, Semi-bold
- `body`, `p`, `span`: Inter, Regular
- **Layout:** Use a consistent grid system (e.g., 12-column responsive grid). Generous whitespace. Clear visual hierarchy.
- **Section Layout:** Header (Logo, Nav, Auth status), Main Content Area, Footer (Links, Copyright).
- **Components:** Use shadcn/ui components for consistency. Ensure clear affordances (buttons look like buttons, inputs look like inputs).
- **Responsiveness:** Mobile-first approach. Ensure usability on screens from 320px to 1920px+. Use Tailwind's responsive modifiers (`sm:`, `md:`, `lg:`, `xl:`).
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/slide-in animations for new pages/routes using Next.js `useRouter` and a library like `Framer Motion` (optional, keep it light).
- **Hover Effects:** Slight scale-up or background color change on interactive elements (buttons, links, cards).
- **Loading States:** Use shadcn/ui's `Skeleton` component or spinners (`lucide-react` icons) for data fetching placeholders.
- **Transitions:** Smooth transitions for UI changes (e.g., expanding/collapsing sections, form feedback).
**SAMPLE/MOCK DATA:**
1. **`dataPlatforms`:**
* `{ id: 'uuid-1', name: 'Federated Data Platform (FDP)', provider: 'Palantir', websiteUrl: '...' }
* `{ id: 'uuid-2', name: 'HealthData Nexus', provider: 'Optum', websiteUrl: '...' }
* `{ id: 'uuid-3', name: 'PatientCare Insights', provider: 'Cerner', websiteUrl: '...' }
2. **`auditCriteria`:**
* `{ id: 'crit-1', name: 'Data Encryption Standards', weight: 0.25, type: 'security' }
* `{ id: 'crit-2', name: 'Third-Party Data Sharing Policy', weight: 0.3, type: 'ethical' }
* `{ id: 'crit-3', name: 'Anonymization Techniques', weight: 0.2, type: 'compliance' }
* `{ id: 'crit-4', name: 'Breach Notification Process', weight: 0.25, type: 'security' }
3. **`audits` (with calculated scores):**
* `{ id: 'audit-1', platformId: 'uuid-1', auditDate: '2024-01-15T10:00:00Z', overallScore: 75, complianceScore: 7, securityScore: 8, ethicalScore: 6, summary: 'Met basic requirements...' }
* `{ id: 'audit-2', platformId: 'uuid-1', auditDate: '2024-07-20T11:30:00Z', overallScore: 68, complianceScore: 6, securityScore: 7, ethicalScore: 5, summary: 'Concerns regarding data sharing...' }
* `{ id: 'audit-3', platformId: 'uuid-2', auditDate: '2024-05-10T09:00:00Z', overallScore: 88, complianceScore: 9, securityScore: 8, ethicalScore: 9, summary: 'Strong compliance...' }
4. **`auditResults`:**
* `{ auditId: 'audit-1', criterionId: 'crit-1', score: 8, notes: 'Uses AES-256...' }
* `{ auditId: 'audit-1', criterionId: 'crit-2', score: 5, notes: 'Ambiguous policy on sharing...' }
* `{ auditId: 'audit-1', criterionId: 'crit-3', score: 7, notes: 'Standard anonymization applied...' }
* `{ auditId: 'audit-1', criterionId: 'crit-4', score: 7, notes: 'Process documented...' }
5. **`concerns`:**
* `{ id: 'conc-1', platformId: 'uuid-1', title: 'Unclear data usage', description: 'Staff are concerned about how patient data is aggregated and potentially shared without explicit consent.', isAnonymous: true, status: 'open' }
* `{ id: 'conc-2', userId: 'user-abc', platformId: 'uuid-1', title: 'Palantir's Defense Ties', description: 'Ethical conflict arises from Palantir's work with US defense contractors, raising questions about data security in healthcare.', isAnonymous: false, status: 'investigating' }
6. **`discussions`:**
* `{ id: 'disc-1', userId: 'user-xyz', title: 'FDP Ethical Dilemmas', content: 'How are others navigating the ethical concerns with the FDP? Are there official channels to voice these concerns?', createdAt: '...' }
* `{ id: 'disc-2', parentId: 'disc-1', userId: 'user-abc', content: 'We have submitted a formal concern via the platform reporting tool. Status is 'open'.', createdAt: '...' }
**EDGE CASES:**
- **Authentication:** Handle invalid login attempts, password resets, session expiry. Ensure only authenticated users can access protected features. Implement RBAC for different user roles.
- **Authorization:** Ensure users can only perform actions permitted by their role (e.g., only admins can add platforms).
- **Data Validation:** Rigorous validation on all form inputs (frontend with Zod/React Hook Form and backend via API route/Server Action logic) to prevent invalid data entry (e.g., scores out of range, missing required fields).
- **Empty States:** Design informative empty states for lists (e.g., "No platforms added yet.", "No concerns reported for this platform.").
- **Error Handling:** Graceful error handling for API requests and data processing. Display user-friendly error messages. Implement global error boundaries.
- **API Failures:** Retry mechanisms (client-side) or clear error messages indicating potential service unavailability.
- **Database Errors:** Transaction management for critical operations (like audit submission) to ensure data consistency.
- **Concurrency:** Consider potential race conditions if multiple users try to update the same data simultaneously (though less critical for MVP).
- **Platform Data Integrity:** Ensure referential integrity using database constraints (foreign keys).
**TURKISH TRANSLATIONS:**
- **App Title:** Veri Güvenliği Merkezi
- **Navigation:** Kontrol Paneli (Dashboard), Platformlar (Platforms), Denetimler (Audits), Endişeler (Concerns), Tartışmalar (Discussions), Ayarlar (Settings), Yönetim (Admin)
- **Buttons:** Denetim Gönder (Submit Audit), Raporla (Report), Oturum Aç (Login), Kayıt Ol (Sign Up), Kaydet (Save), Filtrele (Filter), Ara (Search)
- **Labels/Placeholders:** Platform Adı (Platform Name), Sağlayıcı (Provider), Açıklama (Description), Puan (Score), Tarih (Date), Lütfen Seçin (Please Select), Endişe Başlığı (Concern Title), Endişe Açıklaması (Concern Description)
- **Page Titles:** Yeni Denetim Oluştur (Create New Audit), Platform Detayları (Platform Details), Kullanıcı Endişeleri (User Concerns)
- **Messages:** Denetim başarıyla gönderildi. (Audit submitted successfully.), Platform başarıyla eklendi. (Platform added successfully.), Bir hata oluştu. (An error occurred.), Lütfen giriş yapın. (Please log in.)
- **UI Elements:** Güvenilir Mavi (Trustworthy Blue), Uyarı Kırmızısı (Warning Red), Yeşil (Green)
- **Score Meanings:** Yüksek Puan (High Score - Green), Orta Puan (Medium Score - Yellow/Orange), Düşük Puan (Low Score - Red)