PROJECT OVERVIEW:
Develop a comprehensive SaaS application called 'ElderCare Audit' using Next.js (App Router) and Tailwind CSS. The primary goal is to bring financial transparency and accountability to the elderly care home industry, which is increasingly being influenced by private equity. The application will provide tools for investors, family members, and regulatory bodies to monitor the financial health, operational efficiency, and ethical compliance of care homes. It aims to solve the problem highlighted by concerns that private equity firms are treating care homes as 'human ATMs,' potentially compromising the quality of care for vulnerable residents. The core value proposition is to empower stakeholders with data-driven insights and audit capabilities, ensuring ethical practices and sustainable business models in elder care.
TECH STACK:
- Frontend Framework: React with Next.js (App Router)
- Styling: Tailwind CSS
- ORM: Drizzle ORM for PostgreSQL
- Database: PostgreSQL
- Authentication: NextAuth.js (Credentials Provider, potentially Google/Oauth)
- UI Components: shadcn/ui (for accessible and customizable components)
- State Management: React Context API / Zustand (for global state)
- Form Handling: React Hook Form with Zod for validation
- Data Fetching: Server Actions and Route Handlers in Next.js App Router
- Charting Library: Chart.js or Recharts
- Other essential packages: date-fns, clsx, lucide-react (for icons)
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. **Users Table:**
* `id`: UUID (Primary Key)
* `name`: VARCHAR(255)
* `email`: VARCHAR(255) UNIQUE NOT NULL
* `hashedPassword`: VARCHAR(255) (if using Credentials Provider)
* `role`: ENUM('admin', 'investor', 'family_member', 'care_home_owner', 'auditor') NOT NULL DEFAULT 'investor'
* `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
2. **CareHomes Table:**
* `id`: UUID (Primary Key)
* `name`: VARCHAR(255) NOT NULL
* `address`: TEXT
* `city`: VARCHAR(100)
* `country`: VARCHAR(100)
* `registrationNumber`: VARCHAR(100) UNIQUE
* `ownerId`: UUID (Foreign Key to Users.id, nullable if ownership is complex)
* `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `updatedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
3. **FinancialReports Table:**
* `id`: UUID (Primary Key)
* `careHomeId`: UUID (Foreign Key to CareHomes.id) NOT NULL
* `reportDate`: DATE NOT NULL
* `period`: VARCHAR(50) NOT NULL (e.g., 'Q1-2023', 'FY-2023')
* `revenue`: DECIMAL(15, 2) DEFAULT 0.00
* `expenses`: DECIMAL(15, 2) DEFAULT 0.00
* `netProfit`: DECIMAL(15, 2) DEFAULT 0.00
* `cashFlow`: DECIMAL(15, 2) DEFAULT 0.00
* `submittedAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
* `isVerified`: BOOLEAN DEFAULT FALSE
4. **Audits Table:**
* `id`: UUID (Primary Key)
* `careHomeId`: UUID (Foreign Key to CareHomes.id) NOT NULL
* `auditorId`: UUID (Foreign Key to Users.id) NOT NULL
* `auditDate`: DATE NOT NULL
* `auditPeriodStart`: DATE
* `auditPeriodEnd`: DATE
* `complianceScore`: INTEGER (e.g., 1-100)
* `findings`: TEXT
* `recommendations`: TEXT
* `completedAt`: TIMESTAMP WITH TIME ZONE
* `createdAt`: TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
5. **UserCareHomeAccess Table (Many-to-Many mapping for investors/family to specific care homes):**
* `userId`: UUID (Foreign Key to Users.id)
* `careHomeId`: UUID (Foreign Key to CareHomes.id)
* `accessLevel`: ENUM('read_only', 'contributor', 'auditor_assigned')
* `PRIMARY KEY (userId, careHomeId)`
CORE FEATURES & USER FLOW:
1. **Authentication & Authorization:**
* User registration (with role selection).
* Login via email/password (Credentials Provider) and potentially OAuth.
* NextAuth.js for session management.
* Role-based access control (RBAC) enforced at the route and component level (e.g., only 'admin' or 'auditor' can create audits, only assigned users can view specific care home data).
* Password reset flow.
* User Management (Admin role only): Ability to invite users, assign roles, and manage user accounts.
2. **Care Home Management:**
* **Care Home Owners/Admins:** Add new care homes, update details (name, address, registration number).
* **Investors/Family Members:** Request access to view a care home's data (requires approval from owner or admin).
* User Flow: Owner/Admin logs in -> Navigates to 'Care Homes' -> Clicks 'Add New' -> Fills in Care Home details -> Saves. Investor logs in -> Searches for Care Home -> Requests Access -> Owner receives notification -> Approves/Rejects. Investor logs in -> Views 'My Care Homes' -> Selects a care home.
3. **Financial Reporting:**
* **Care Home Owners/Admins:** Upload financial reports (CSV, Excel, or manual entry form) for specific periods. Reports include revenue, expenses, net profit, cash flow.
* **Investors/Auditors:** View financial reports for assigned care homes. View aggregated financial data (e.g., revenue trends over time, expense breakdown, profit margins).
* **Admin:** Oversee all submitted reports, mark reports as verified.
* User Flow: Owner logs in -> Selects Care Home -> Navigates to 'Financial Reports' -> Clicks 'Upload Report' -> Selects file/fills form -> Submits. Investor logs in -> Selects Care Home -> Navigates to 'Financial Reports' -> Views list of reports -> Clicks a report to see details or selects 'Analytics' to view charts.
4. **Auditing Module:**
* **Admin/Auditors:** Initiate a new audit for a specific care home and period. Assign an auditor.
* **Assigned Auditors:** Access audit details, input compliance score, document findings, provide recommendations, mark audit as complete.
* **Investors/Family Members:** View completed audit reports for assigned care homes.
* User Flow: Admin logs in -> Navigates to 'Audits' -> Clicks 'Create New Audit' -> Selects Care Home, Period, Auditor -> Submits. Auditor logs in -> Views assigned audits -> Clicks an audit -> Fills in details (score, findings, recommendations) -> Marks as Complete. Investor logs in -> Selects Care Home -> Navigates to 'Audits' -> Views list of completed audits.
5. **Dashboard & Analytics:**
* **All Users (based on role/access):** A personalized dashboard displaying key metrics. Investors see portfolio overview (aggregated financial health of their care homes). Owners see their home's performance. Auditors see assigned audits. Admins see system-wide overview.
* Visualizations: Revenue vs. Expenses over time, Profit Margin trends, Cash Flow analysis, Compliance Score trends.
* User Flow: User logs in -> Lands on Dashboard -> Views relevant charts and summary statistics.
API & DATA FETCHING:
- Use Next.js Server Actions for mutations (CRUD operations) directly within components, leveraging Drizzle ORM.
- Use Route Handlers (API Routes) for read operations or complex data aggregation requiring server-side logic not suitable for Server Actions.
- API endpoints will handle requests like:
- `POST /api/auth/signup`: User registration.
- `POST /api/auth/login`: User login.
- `POST /api/care-homes`: Create a new care home (Server Action).
- `GET /api/care-homes`: Fetch list of care homes for the logged-in user.
- `GET /api/care-homes/{id}`: Fetch details of a specific care home.
- `POST /api/reports`: Upload financial report data (Server Action).
- `GET /api/care-homes/{id}/reports`: Fetch financial reports for a care home.
- `POST /api/audits`: Create a new audit (Server Action).
- `GET /api/audits/{id}`: Fetch audit details.
- `PUT /api/audits/{id}`: Update audit details (Server Action).
- `GET /api/dashboard/summary`: Fetch aggregated data for the dashboard.
- Data will be fetched server-side or using Server Actions to ensure data is fresh and security is maintained. Client-side fetching can be used sparingly for non-critical UI updates using libraries like SWR or React Query if needed, but prioritize Server Actions for most data interactions.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, Trustworthy, Professional.
- **Color Palette:** Primary: Deep Blue (#1A237E), Secondary: Teal (#00ACC1), Accent: Light Gray (#ECEFF1), Text: Dark Gray (#263238), Success: Green (#4CAF50), Warning: Orange (#FB8C00), Error: Red (#E53935).
- **Typography:** A clean sans-serif font family like Inter or Poppins for headings and body text. Ensure good readability and hierarchy.
- **Layout:** Utilize a consistent grid system (e.g., 12-column). Employ clear sectioning with ample whitespace. Use cards for displaying summarized information (e.g., care home cards, report summaries).
- **Responsiveness:** Mobile-first approach. Ensure all layouts and components are fully responsive and adapt seamlessly to various screen sizes (mobile, tablet, desktop).
- **Navigation:** Clear and intuitive navigation using Next.js App Router's layout structure. Sidebar for main navigation in larger screens, off-canvas menu for mobile.
- **Microinteractions:** Subtle animations on hover states, loading spinners, and smooth transitions between pages/states.
COMPONENT BREAKDOWN (Next.js App Router structure):
- **`app/`**
- **`layout.tsx`**: Root layout (includes providers, global styles, font loading).
- **`page.tsx`**: Landing page (if not fully authenticated).
- **`(auth)/`** (Authentication Group):
- `login/page.tsx`
- `signup/page.tsx`
- `reset-password/page.tsx`
- **`(app)/`** (Authenticated App Group):
- **`layout.tsx`**: Main app layout (sidebar, header, content area).
- **`dashboard/page.tsx`**: Main dashboard view with aggregated data and charts. (State: User data, summary stats, chart data).
- **`care-homes/page.tsx`**: List of care homes accessible to the user. (State: List of care homes).
- **`care-homes/[id]/page.tsx`**: Detailed view of a single care home. (State: Care home details, recent reports, audits).
- **`components/care-homes/FinancialsTable.tsx`**: Displays financial reports. (Props: report data).
- **`components/care-homes/AuditsList.tsx`**: Displays audit summaries. (Props: audit data).
- **`care-homes/new/page.tsx`**: Form to add a new care home. (State: Form inputs).
- **`reports/upload/page.tsx`**: Form to upload financial reports. (State: Form inputs, file upload).
- **`audits/page.tsx`**: List of assigned or completed audits. (State: Audit list).
- **`audits/[id]/page.tsx`**: Detailed view of an audit. (State: Audit details, findings, recommendations).
- **`components/audits/AuditForm.tsx`**: Form to fill out audit details. (Props: audit data, onSubmit handler).
- **`settings/page.tsx`**: User profile and settings. (State: User profile data).
- **`admin/page.tsx`** (Conditional based on role):
- **`components/admin/UserManagement.tsx`**: Table and form for user management.
- **`components/admin/CareHomeManagement.tsx`**: Table for managing all care homes.
- **`components/`** (Shared UI Components):
- `ui/Button.tsx`, `ui/Input.tsx`, `ui/Card.tsx`, `ui/Table.tsx`, `ui/Chart.tsx`, `ui/Sidebar.tsx`, `ui/Header.tsx`, `ui/Alert.tsx`, `ui/Spinner.tsx` etc. (from shadcn/ui)
- `AuthButton.tsx`: Handles login/logout actions.
- `RoleGate.tsx`: Component for role-based rendering.
- `DataTable.tsx`: Generic table component.
- `ErrorBoundary.tsx`: For error handling.
ANIMATIONS:
- **Page Transitions:** Use `AnimatePresence` from `framer-motion` for smooth cross-fade or slide transitions between pages managed by the App Router (if feasible within App Router structure, otherwise use simpler CSS transitions).
- **Hover Effects:** Subtle scale or background color changes on buttons and interactive elements using Tailwind CSS's `hover:` variants.
- **Loading States:** Implement skeleton loaders or spinners (e.g., `react-spinners` or custom shadcn/ui spinners) within `Suspense` boundaries or data fetching components while data is being loaded.
- **Data Updates:** Animate chart updates when new data becomes available.
- **Form Feedback:** Animate error messages or success indicators after form submissions.
EDGE CASES:
- **Authentication:** Handle expired sessions, redirect to login. Securely manage tokens/sessions. Implement robust validation for login/signup forms.
- **Authorization:** Gracefully handle unauthorized access attempts (e.g., show 403 page or redirect).
- **Data Fetching:** Implement error handling for API requests. Display user-friendly error messages. Handle empty states gracefully (e.g., 'No care homes found', 'No reports for this period').
- **Form Validation:** Use Zod with React Hook Form for comprehensive client-side and server-side validation of all user inputs (registration, care home details, financial data, audit forms).
- **Database Constraints:** Ensure database-level constraints (unique keys, foreign keys) prevent data integrity issues.
- **File Uploads:** Handle potential errors during file uploads (size limits, file types, network issues).
- **Role-Specific Views:** Ensure UI elements and data displayed are strictly filtered based on the logged-in user's role and assigned access.
SAMPLE DATA:
1. **User (Investor):**
* `id`: "a1b2c3d4-e5f6-7890-1234-567890abcdef"
* `name`: "Alex Johnson"
* `email`: "alex.j@investcorp.com"
* `role`: "investor"
2. **User (Care Home Owner):**
* `id`: "f0e9d8c7-b6a5-4321-fedc-ba0987654321"
* `name`: "Sarah Chen"
* `email`: "sarah.chen@harmonyhomes.com"
* `role`: "care_home_owner"
3. **CareHome:**
* `id`: "123e4567-e89b-12d3-a456-426614174000"
* `name`: "Harmony Senior Living"
* `address`: "123 Serene Lane, Anytown, CA 90210"
* `registrationNumber`: "CH-87654"
* `ownerId`: "f0e9d8c7-b6a5-4321-fedc-ba0987654321"
4. **FinancialReport (Q3-2023):**
* `id`: "98765432-abcd-ef01-2345-67890abcdef0"
* `careHomeId`: "123e4567-e89b-12d3-a456-426614174000"
* `reportDate`: "2023-09-30"
* `period`: "Q3-2023"
* `revenue`: 150000.00
* `expenses`: 110000.00
* `netProfit`: 40000.00
* `cashFlow`: 35000.00
5. **FinancialReport (Q4-2023):**
* `id`: "abcdef01-2345-6789-abcd-ef0123456789"
* `careHomeId`: "123e4567-e89b-12d3-a456-426614174000"
* `reportDate`: "2023-12-31"
* `period`: "Q4-2023"
* `revenue`: 155000.00
* `expenses`: 115000.00
* `netProfit`: 40000.00
* `cashFlow`: 38000.00
6. **Audit:**
* `id`: "a1b2c3d4-e5f6-7890-1234-567890fedcba"
* `careHomeId`: "123e4567-e89b-12d3-a456-426614174000"
* `auditorId`: "some-auditor-user-id"
* `auditDate`: "2023-11-15"
* `auditPeriodStart`: "2023-01-01"
* `auditPeriodEnd`: "2023-09-30"
* `complianceScore`: 85
* `findings`: "Minor discrepancies in expense reporting. Staffing levels meet minimum requirements but could be improved for higher quality care."
* `recommendations`: "Implement a more rigorous expense verification process. Consider hiring additional support staff."
* `completedAt`: "2023-11-20T14:30:00Z"
7. **User (Auditor):**
* `id`: "auditor-user-id-1234"
* `name`: "Quality Assurance Group"
* `email`: "audits@qagroup.com"
* `role`: "auditor"
8. **UserCareHomeAccess (Investor access to Harmony):**
* `userId`: "a1b2c3d4-e5f6-7890-1234-567890abcdef"
* `careHomeId`: "123e4567-e89b-12d3-a456-426614174000"
* `accessLevel`: "read_only"
9. **CareHome (Another one):**
* `id`: "d4e5f678-9012-3456-7890-abcdef123456"
* `name`: "Golden Years Residence"
* `address`: "456 Sunset Blvd, Anytown, CA 90210"
* `registrationNumber`: "CH-12345"
* `ownerId`: "another-owner-id"
10. **FinancialReport (Harmony, Q2-2023):**
* `id`: "cba98765-fedc-ba09-8765-43210fedcba9"
* `careHomeId`: "123e4567-e89b-12d3-a456-426614174000"
* `reportDate`: "2023-06-30"
* `period`: "Q2-2023"
* `revenue`: 140000.00
* `expenses`: 105000.00
* `netProfit`: 35000.00
* `cashFlow`: 30000.00