## AI Master Prompt for Open Science Hub - Next.js MVP Generation
**PROJECT OVERVIEW:**
Open Science Hub aims to revolutionize academic publishing by providing a free, accessible, and transparent platform for researchers, particularly those affiliated with institutions in European countries participating in the ORE consortium. It addresses the problem of high Article Processing Charges (APCs) and the complexities of traditional publishing by implementing a 'diamond open access' model. The core value proposition is to democratize scholarly communication, promote equity, diversity, and transparency, and accelerate the dissemination of research findings without financial barriers for authors. The platform will be built using a modern tech stack to ensure scalability, maintainability, and a superior user experience.
**TARGET AUDIENCE (Detailed):**
- **Primary:** Researchers, academics, and scientists from institutions within participating ORE consortium countries (Austria, France, Germany, Italy, Netherlands, Norway, Portugal, Slovenia, Spain, Sweden, Switzerland) and European Commission-funded researchers.
- **Secondary:** Universities, research institutions, national funding agencies (members of the ORE consortium), librarians, policymakers interested in open science initiatives, and the broader scientific community seeking free access to research.
**TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **UI Components:** shadcn/ui (for pre-built, accessible components)
- **Database ORM:** Drizzle ORM (with PostgreSQL adapter)
- **Database:** PostgreSQL
- **Authentication:** NextAuth.js (Credentials Provider, Google Provider)
- **State Management:** Zustand (or React Context API for simpler cases)
- **Form Handling:** React Hook Form + Zod (for validation)
- **API Routes:** Next.js API Routes (Server Actions)
- **Deployment:** Vercel
**DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
1. **`users` Table:**
* `id`: `uuid` (Primary Key, default: `uuid_generate_v4()`)
* `name`: `varchar(255)`
* `email`: `varchar(255)` (Unique)
* `emailVerified`: `timestamp with time zone`
* `image`: `text` (URL to profile picture)
* `hashedPassword`: `text` (Nullable, for credentials provider)
* `institutionId`: `uuid` (Foreign Key to `institutions.id`, Nullable)
* `role`: `varchar(50)` (e.g., 'researcher', 'reviewer', 'editor', 'admin')
* `createdAt`: `timestamp with time zone` (default: `now()`)
* `updatedAt`: `timestamp with time zone` (default: `now()`)
2. **`institutions` Table:**
* `id`: `uuid` (Primary Key, default: `uuid_generate_v4()`)
* `name`: `varchar(255)` (Unique)
* `country`: `varchar(100)`
* `logoUrl`: `text` (Nullable)
* `createdAt`: `timestamp with time zone` (default: `now()`)
* `updatedAt`: `timestamp with time zone` (default: `now()`)
3. **`articles` Table:**
* `id`: `uuid` (Primary Key, default: `uuid_generate_v4()`)
* `title`: `varchar(500)`
* `abstract`: `text`
* `submissionDate`: `timestamp with time zone` (default: `now()`)
* `publicationDate`: `timestamp with time zone` (Nullable)
* `status`: `varchar(50)` (e.g., 'draft', 'under_review', 'rejected', 'accepted', 'published')
* `doi`: `varchar(100)` (Unique, Nullable, assigned upon publication)
* `pdfUrl`: `text` (URL to the final published PDF)
* `correspondingAuthorId`: `uuid` (Foreign Key to `users.id`)
* `createdAt`: `timestamp with time zone` (default: `now()`)
* `updatedAt`: `timestamp with time zone` (default: `now()`)
4. **`article_authors` Table (Many-to-Many relationship between `articles` and `users`):**
* `articleId`: `uuid` (Foreign Key to `articles.id`)
* `userId`: `uuid` (Foreign Key to `users.id`)
* `authorOrder`: `integer` (Defines the order of authors)
* `isCorresponding`: `boolean` (default: false)
* PRIMARY KEY (`articleId`, `userId`)
5. **`review_assignments` Table:**
* `id`: `uuid` (Primary Key, default: `uuid_generate_v4()`)
* `articleId`: `uuid` (Foreign Key to `articles.id`)
* `reviewerId`: `uuid` (Foreign Key to `users.id`)
* `assignmentDate`: `timestamp with time zone` (default: `now()`)
* `status`: `varchar(50)` (e.g., 'assigned', 'submitted', 'declined')
* `createdAt`: `timestamp with time zone` (default: `now()`)
* `updatedAt`: `timestamp with time zone` (default: `now()`)
6. **`reviews` Table:**
* `id`: `uuid` (Primary Key, default: `uuid_generate_v4()`)
* `reviewAssignmentId`: `uuid` (Foreign Key to `review_assignments.id`)
* `recommendation`: `varchar(50)` (e.g., 'accept', 'reject', 'minor_revision', 'major_revision')
* `comments`: `text` (Public comments for author)
* `confidentialNotes`: `text` (Private notes for editor)
* `reviewDate`: `timestamp with time zone` (default: `now()`)
* `createdAt`: `timestamp with time zone` (default: `now()`)
* `updatedAt`: `timestamp with time zone` (default: `now()`)
7. **`article_topics` Table (Many-to-Many relationship between `articles` and `topics`):**
* `articleId`: `uuid` (Foreign Key to `articles.id`)
* `topicId`: `uuid` (Foreign Key to `topics.id`)
* PRIMARY KEY (`articleId`, `topicId`)
8. **`topics` Table:**
* `id`: `uuid` (Primary Key, default: `uuid_generate_v4()`)
* `name`: `varchar(100)` (Unique)
*Note: Consider adding `roles` table for more granular role management if needed. Add indexes on foreign keys and frequently queried columns.* For the sake of MVP, initial roles in `users` table are sufficient.
**CORE FEATURES & USER FLOWS:**
1. **Authentication (NextAuth.js):
* **Flow:** User lands on `/login`. Can sign up using email/password or Google OAuth. Upon successful sign-up/login, user is redirected to the dashboard. Session management via JWT/cookies. Protected routes will redirect unauthenticated users to `/login`.
* **Credentials:** Email, Password (hashed with bcrypt).
* **OAuth:** Google Provider configured.
* **Edge Cases:** Email already exists, incorrect password, OAuth callback errors, session expiry.
2. **User Profile Management:
* **Flow:** Authenticated user navigates to `/profile`. Can view/edit name, institution (if not set), and role (if admin). Upload profile picture.
* **UI:** Form with input fields, save button. Profile picture upload component.
* **API:** Server Action to update user data.
* **Edge Cases:** Invalid input, upload failures.
3. **Article Submission:
* **Flow:** Authenticated user (researcher role) navigates to `/submit-article`. Fills out a multi-step form:
1. **Metadata:** Title, Abstract, Keywords/Topics (tag input).
2. **Authors:** Add co-authors by email (system searches for existing users or allows adding as external). Designate corresponding author.
3. **File Upload:** Upload manuscript PDF. Validations for file type and size.
4. **Review:** Review submission details. Submit.
* **UI:** Multi-step form (using `tabs` or progress indicator from shadcn/ui), form validation, file upload component with progress. Search functionality for adding authors.
* **API:** Server Actions for metadata saving, author association, and file upload (using `multer` or similar if using API routes, or directly handled by Next.js API routes/Server Actions with `formidable`). Initial status: 'draft'.
* **Edge Cases:** Incomplete form, invalid file, network errors during upload, author not found.
4. **Article Dashboard:
* **Flow:** Authenticated user navigates to `/dashboard`. Sees a list of their submitted articles (if researcher) or articles assigned for review (if reviewer) or articles pending decisions (if editor). Displays article title, status, submission date. Links to article detail pages.
* **UI:** Data table (shadcn/ui DataTable) displaying articles. Filtering and sorting options.
* **API:** Server Action to fetch articles relevant to the logged-in user based on role.
* **Edge Cases:** No articles submitted/assigned (empty state UI).
5. **Article Viewing (Detail Page):
* **Flow:** User clicks an article from the dashboard. Navigates to `/articles/[id]`. Displays title, abstract, authors, publication date, status, and a link to the PDF if published.
* **UI:** Read-only view of article details. Conditional rendering for 'published' status and PDF link.
* **API:** Server Action to fetch specific article data.
* **Edge Cases:** Article not found (404).
6. **Review Assignment (Editor Flow):
* **Flow:** Editor navigates to an article's detail page. Clicks 'Assign Reviewers'. System suggests potential reviewers based on topics or allows manual search/selection. Editor assigns 1-3 reviewers.
* **UI:** Search/select component for reviewers, confirmation modal.
* **API:** Server Action to create `review_assignments` records.
* **Edge Cases:** No suitable reviewers found, assigning self, assigning already assigned reviewer.
7. **Review Submission (Reviewer Flow):
* **Flow:** Reviewer receives an email notification. Navigates to `/review/[assignmentId]`. Fills out a form: Recommendation (dropdown), Public Comments, Confidential Notes. Submits review.
* **UI:** Form with recommendation selection, text areas for comments. Validation.
* **API:** Server Action to create `reviews` record and update `review_assignments` status.
* **Edge Cases:** Submitting without recommendation, network errors.
8. **Editorial Decision (Editor Flow):
* **Flow:** Editor reviews all submitted reviews for an article. Clicks 'Make Decision'. Selects 'Accept', 'Reject', or 'Request Revisions'. If revisions requested, notifies authors and potentially assigns reviewers again. If accepted, sets `publicationDate`, `status` to 'published', and assigns a DOI (placeholder for MVP).
* **UI:** Buttons for decision making, modal confirmation.
* **API:** Server Action to update article status and dates.
* **Edge Cases:** Missing reviews, conflicting recommendations.
9. **Institution Management (Admin/Consortium Lead Flow):
* **Flow:** Authorized user navigates to `/admin/institutions`. Can add new institutions, view member researchers, edit institution details.
* **UI:** Data tables, forms for adding/editing institutions.
* **API:** Server Actions for CRUD operations on `institutions` and associating `users`.
* **Edge Cases:** Duplicate institution names, user not found.
**API & DATA FETCHING:**
- **Approach:** Primarily use Next.js Server Actions for mutations (POST, PUT, DELETE) and data fetching on the server. For client-side fetching (e.g., in response to user interactions not directly tied to a form submission), use `fetch` within client components, leveraging Next.js's caching and revalidation mechanisms.
- **API Routes:** Will be used for auth endpoints (provided by NextAuth.js) and potentially for complex background jobs or external API integrations if needed, though Server Actions are preferred for most CRUD operations.
- **Data Structure:** API responses (if any) and Server Action return values will be JSON objects. Components will receive data directly from Server Actions or client-side fetches.
- **Example (Server Action for Article Submission):**
```typescript
// app/actions.ts
'use server';
import { db } from '@/lib/db'; // Drizzle connection
import { articles, articleAuthors } from '@/lib/schema';
import { auth } from '@/lib/auth';
import { eq } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
export async function submitArticle(formData: FormData) {
const session = await auth();
if (!session?.user?.id) {
throw new Error('Unauthorized');
}
const title = formData.get('title') as string;
const abstract = formData.get('abstract') as string;
// ... other fields and file handling ...
try {
const newArticle = await db.insert(articles).values({
title,
abstract,
correspondingAuthorId: session.user.id,
status: 'draft',
}).returning({ id: articles.id });
// Add corresponding author
await db.insert(articleAuthors).values({
articleId: newArticle[0].id,
userId: session.user.id,
authorOrder: 1,
isCorresponding: true,
});
revalidatePath('/dashboard'); // Revalidate dashboard cache
return { success: true, articleId: newArticle[0].id };
} catch (error) {
console.error('Article submission failed:', error);
return { success: false, error: 'Failed to submit article' };
}
}
```
**COMPONENT BREAKDOWN (Next.js App Router):**
- **`app/layout.tsx`:** Root layout component. Includes HTML boilerplate, `<body>` tag, setup for Tailwind CSS, Shadcn UI's `ThemeProvider`, and potentially global error/loading boundaries.
- **`app/page.tsx`:** Landing Page. Hero section, value proposition, call to action (Sign Up/Login).
- **`app/(auth)/login/page.tsx`:** Login page. Includes forms for email/password login and Google OAuth button.
- **`app/(auth)/signup/page.tsx`:** Sign up page. Similar to login but for new user registration.
- **`app/dashboard/page.tsx`:** User Dashboard. Displays a DataTable of the user's articles (submitted or assigned for review) based on their role. Links to article detail and submission pages.
- **`app/submit-article/page.tsx`:** Multi-step form for submitting a new article (Metadata, Authors, File Upload).
- **`app/articles/[id]/page.tsx`:** Article Detail Page. Displays full article information. Role-specific actions (e.g., 'Assign Reviewers' for editors).
- **`app/profile/page.tsx`:** User Profile Page. View and edit profile information.
- **`app/review/[assignmentId]/page.tsx`:** Review Submission Form. For reviewers to submit their evaluation.
- **`app/admin/page.tsx`:** Admin Dashboard (placeholder).
- **`app/admin/institutions/page.tsx`:** Institution Management Page. CRUD operations for institutions.
- **`app/components/ui/`:** Directory for all imported shadcn/ui components (e.g., `Button`, `Input`, `Card`, `DataTable`, `Dialog`, `Form`, `Select`, `Tabs`, `Progress`).
- **`app/components/`:** Custom shared components.
- **`Navbar.tsx`:** Navigation bar with logo, links, user avatar dropdown (if logged in).
- **`Footer.tsx`:** Footer with copyright and links.
- **`ArticleCard.tsx`:** Small card representation for articles in lists.
- **`FileUpload.tsx`:** Component for handling file uploads with progress indication.
- **`UserAvatar.tsx`:** Displays user avatar and name.
- **`SubmitArticleForm.tsx`:** The core multi-step form component logic.
- **`ReviewForm.tsx`:** Component for reviewers.
- **`DataTable.tsx`:** Generic data table component (likely wrapping shadcn/ui's DataTable).
- **`lib/`:** Utility functions, database connection, schema definitions, auth configuration, API client helpers.
- **`lib/db.ts`:** Drizzle ORM connection setup.
- **`lib/schema.ts`:** Drizzle schema definitions.
- **`lib/auth.ts`:** NextAuth.js configuration.
- **`lib/utils.ts`:** General utility functions.
- **`contexts/` or `store/`:** For global state management (e.g., Zustand store for user session, loading states).
**UI/UX DESIGN & VISUAL IDENTITY:**
- **Design Style:** Modern Minimalist Clean with a professional and trustworthy feel.
- **Color Palette:**
- Primary: Deep Blue (`#1E3A8A` - slate-800)
- Secondary: Teal (`#0D9487` - teal-600)
- Accent: Light Gray (`#F3F4F6` - neutral-100)
- Text: Dark Gray (`#1F2937` - gray-800)
- Background: White (`#FFFFFF`)
- Success: Green (`#10B981` - emerald-500)
- Warning/Revision: Orange (`#F59E0B` - amber-500)
- Danger/Reject: Red (`#EF4444` - red-500)
- **Typography:** Inter font family (Google Fonts). Use sans-serif for a clean, readable look. Hierarchy established through font weights and sizes.
- **Layout:** Focus on clear information hierarchy. Use whitespace effectively. Consistent padding and margins. Responsive grid system (Tailwind CSS `grid` and `container`). Main content centered, max-width applied.
- **Sections:** Clear separation between sections on landing page and dashboard using cards or subtle background color changes.
- **Interactivity:** Subtle hover effects on buttons and links. Smooth transitions for modals and dropdowns.
- **Responsiveness:** Mobile-first approach. Ensure usability across devices (phones, tablets, desktops). Tailwind's responsive modifiers (`sm:`, `md:`, `lg:`) will be used extensively.
- **Icons:** Use a consistent icon set like Lucide Icons (integrated with shadcn/ui).
**ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/out using Next.js's `<AnimatePresence>` (from `framer-motion` if needed, but aim for CSS-based transitions first for simplicity).
- **Loading States:** Use spinners (shadcn/ui `Spinner` or `Progress`) within buttons during form submissions and skeleton loaders for data fetching where appropriate.
- **Hover Effects:** Slight scale-up or background color change on interactive elements (buttons, cards, links).
- **Micro-interactions:** Smooth opening/closing of modals and dropdowns.
**EDGE CASES:**
- **Authentication:** Handle expired sessions, invalid credentials, OAuth errors gracefully. Redirect to login page with appropriate messages.
- **Empty States:** Design clear and informative empty states for dashboards, article lists, review sections when no data is available. Include CTAs to guide users (e.g., "Submit your first article").
- **Form Validation:** Implement robust client-side (Zod + React Hook Form) and server-side validation for all user inputs. Provide clear error messages.
- **Error Handling:** Implement global error handling (e.g., using `error.tsx` in Next.js App Router) and specific error messages for API failures or unexpected issues. Log errors to a monitoring service.
- **File Uploads:** Handle network interruptions, file size/type limits, and provide user feedback during upload.
- **Permissions:** Ensure users can only access and perform actions allowed by their role (e.g., only editors can make decisions, only researchers can submit).
- **Data Integrity:** Use database transactions where necessary to maintain data consistency during complex operations.
**SAMPLE DATA (for Frontend Mocking & Initial DB State):**
1. **User (Researcher):**
* `id`: `uuid`
* `name`: "Dr. Elif Yılmaz"
* `email`: "elif.yilmaz@example.edu.tr"
* `institution`: { `name`: "Boğaziçi Üniversitesi", `country`: "Turkey" }
* `role`: "researcher"
2. **User (Editor):**
* `id`: `uuid`
* `name`: "Prof. Dr. Mehmet Demir"
* `email`: "mehmet.demir@example.uni-heidelberg.de"
* `institution`: { `name`: "Heidelberg University", `country`: "Germany" }
* `role`: "editor"
3. **Institution:**
* `id`: `uuid`
* `name`: "Sorbonne University"
* `country`: "France"
4. **Article (Under Review):**
* `id`: `uuid`
* `title`: "Quantum Entanglement in Macroscopic Systems"
* `abstract`: "Investigating the potential for observable quantum entanglement effects in larger-than-microscopic systems..."
* `status`: "under_review"
* `submissionDate`: "2024-05-15T10:00:00Z"
* `correspondingAuthor`: "Dr. Elif Yılmaz"
5. **Article (Published):**
* `id`: `uuid`
* `title`: "Novel Catalysts for CO2 Reduction"
* `abstract`: "Development of new metal-organic frameworks for efficient electrochemical reduction of carbon dioxide..."
* `status`: "published"
* `submissionDate`: "2023-11-20T14:30:00Z"
* `publicationDate`: "2024-03-10T09:00:00Z"
* `doi`: "10.1000/ore.2024.12345"
* `pdfUrl`: "/pdfs/catalysts-co2-reduction.pdf"
6. **Article (Draft):**
* `id`: `uuid`
* `title`: "The Impact of AI on Renewable Energy Grids"
* `abstract`: "Preliminary study on how AI models can optimize energy distribution..."
* `status`: "draft"
* `submissionDate`: "2024-05-20T11:00:00Z"
* `correspondingAuthor`: "Dr. Elif Yılmaz"
7. **Review Assignment:**
* `id`: `uuid`
* `articleId`: (UUID of Article 5)
* `reviewerId`: (UUID of Dr. Elif Yılmaz)
* `assignmentDate`: "2024-05-01T00:00:00Z"
* `status`: "submitted"
8. **Review:**
* `id`: `uuid`
* `reviewAssignmentId`: (UUID of Review Assignment 7)
* `recommendation`: "minor_revision"
* `comments`: "The methodology is sound, but the discussion section could be expanded to address limitations more thoroughly."
* `confidentialNotes`: "Consider asking the author about alternative data sources."
* `reviewDate`: "2024-05-18T16:00:00Z"
*Ensure all IDs are valid UUIDs. Populate `institutionId` on users where applicable. Mock data should reflect different article statuses and user roles.*