PROJECT OVERVIEW:
Develop a fully functional, multi-page Next.js MVP application called 'Smart Intercom Access'. This application bridges the gap between traditional apartment intercom systems and modern smart home technology, specifically Apple HomeKit. The core problem solved is the inconvenience and lack of control users experience with outdated intercoms, especially when managing frequent visitors or dealing with non-functional building management services. Smart Intercom Access allows residents to discreetly modify their existing intercom to work seamlessly with Apple Home, enabling features like remote door unlocking, real-time visitor notifications, temporary access code generation, and a comprehensive visitor log. The value proposition is enhanced convenience, security, and control over apartment access.
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- ORM: Drizzle ORM
- Database: PostgreSQL (or any Drizzle-compatible SQL database)
- Authentication: NextAuth.js (with credentials provider for potential custom auth, and OAuth for Apple Sign-In)
- UI Library: shadcn/ui (for pre-built, accessible components)
- State Management: React Context API / Zustand (for global state, if needed)
- Real-time: Optional - Socket.IO or similar for immediate push notifications if webhooks are not sufficient.
- Hardware Integration: Requires a custom-built or off-the-shelf hardware module (e.g., Raspberry Pi Pico W, ESP32) running firmware that interfaces with the intercom's physical buttons/logic and communicates with the backend API via MQTT or HTTP. The prompt will focus on the software MVP, assuming the hardware module is functional and communicates with a designated API endpoint.
- Required Packages: next, react, react-dom, typescript, tailwindcss, drizzle-orm, pg, next-auth, @clerkinc/nextjs (or similar auth provider if preferred over NextAuth.js), @heroicons/react, zod, react-hook-form, @tanstack/react-query, @shadcn/ui packages (button, card, input, label, dialog, toast, etc.), axios (for API calls)
DATABASE SCHEMA (Drizzle ORM - PostgreSQL):
1. `users` table:
- `id`: uuid (primary key, default: uuid_generate_v4())
- `name`: text
- `email`: text (unique)
- `emailVerified`: timestamp
- `image`: text (optional, for profile picture)
- `hashedPassword`: text (for custom credentials)
- `createdAt`: timestamp (default: now())
- `updatedAt`: timestamp (default: now())
2. `accounts` table (for NextAuth.js/OAuth):
- `id`: uuid (primary key, default: uuid_generate_v4())
- `userId`: uuid (foreign key to users.id, references 'users')
- `type`: text (e.g., 'oauth', 'email')
- `provider`: text
- `providerAccountId`: text
- `refresh_token`: text (optional)
- `access_token`: text (optional)
- `expires_at`: timestamp (optional)
- `token_type`: text (optional)
- `scope`: text (optional)
- `id_token`: text (optional)
- `session_state`: text (optional)
3. `sessions` table (for NextAuth.js):
- `sessionToken`: text (primary key)
- `userId`: uuid (foreign key to users.id, references 'users')
- `expires`: timestamp
4. `verificationTokens` table (for NextAuth.js email verification):
- `identifier`: text
- `token`: text (unique)
- `expires`: timestamp
5. `apartments` table:
- `id`: uuid (primary key, default: uuid_generate_v4())
- `userId`: uuid (foreign key to users.id, references 'apartments')
- `intercomModel`: text (e.g., 'Doorking 1834-080')
- `locationIdentifier`: text (e.g., 'Unit 3B', 'Building A, Floor 5')
- `hardwareDeviceId`: text (unique, identifier for the connected hardware module)
- `isAppleHomeIntegrated`: boolean (default: false)
- `createdAt`: timestamp (default: now())
- `updatedAt`: timestamp (default: now())
6. `accessLogs` table:
- `id`: uuid (primary key, default: uuid_generate_v4())
- `apartmentId`: uuid (foreign key to apartments.id, references 'apartments')
- `guestName`: text (optional, if provided by guest)
- `guestIdentifier`: text (e.g., phone number, temporary code used)
- `accessGrantedAt`: timestamp (default: now())
- `accessMethod`: enum ('manual_open', 'code', 'scheduled', 'homekit')
- `notes`: text (optional, e.g., 'Front door opened')
7. `temporaryAccessCodes` table:
- `id`: uuid (primary key, default: uuid_generate_v4())
- `apartmentId`: uuid (foreign key to apartments.id, references 'apartments')
- `code`: text (unique, generated code)
- `validUntil`: timestamp
- `createdByUserId`: uuid (foreign key to users.id, references 'users')
- `notes`: text (optional)
- `isActive`: boolean (default: true)
- `createdAt`: timestamp (default: now())
CORE FEATURES & USER FLOW:
1. **User Authentication & Onboarding:**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Log In'.
* **Sign Up:** User can sign up using Email/Password or OAuth (Apple Sign-In recommended for HomeKit synergy).
* **Login:** Existing users log in.
* **Onboarding (First Login):** After successful login, user is prompted to set up their apartment. They enter details like `intercomModel`, `locationIdentifier`.
* **Hardware Setup Prompt:** User is instructed on how to connect the hardware module (details to be provided separately, focusing on API endpoint). They will need to input their unique `hardwareDeviceId`.
* **Apple Home Integration:** User is guided through linking their Apple HomeKit setup. This may involve generating a HomeKit accessory code or pairing process initiated via the app, which then configures the hardware module.
* **Error Handling:** Invalid credentials, email already exists, OAuth errors, hardware ID already in use.
2. **Dashboard (Primary View after Login):**
* **Flow:** User logs in, directed to the dashboard.
* **Content:** Displays current apartment status (e.g., 'Apple Home Integrated: Yes/No'), recent access logs (last 3-5 entries), quick action buttons ('Open Door', 'Generate Code').
* **State:** Shows real-time status if connection is active.
3. **Manual Door Unlock:**
* **Flow:** User clicks 'Open Door' button on the dashboard or relevant page.
* **Action:** App sends a request to the backend API (e.g., `/api/apartments/{id}/unlock`).
* **Backend:** API triggers the hardware module (via MQTT or direct HTTP call) to activate the intercom's unlock mechanism.
* **Response:** API confirms success/failure to the frontend. Frontend displays a toast notification ('Door Unlocked' / 'Failed to Unlock').
* **Logging:** An entry is created in the `accessLogs` table with `accessMethod: 'manual_open'`.
* **Edge Case:** If hardware is offline or fails, display 'Device Unreachable' or 'Unlock Failed' message.
4. **Temporary Access Code Generation:**
* **Flow:** User navigates to 'Access Codes' section. Clicks 'Generate New Code'.
* **Form:** User inputs optional `notes`, `guestIdentifier` (e.g., 'John Doe - Gardener'), and sets `validUntil` date/time.
* **Action:** App sends a POST request to `/api/apartments/{id}/access-codes` with form data.
* **Backend:** Generates a unique, secure code. Stores it in `temporaryAccessCodes` table, linked to the `apartmentId`. Returns the code to the frontend.
* **Frontend:** Displays the generated code. Provides options to 'Copy Code' or 'Share via...' (using native share functionality).
* **Logging:** An entry in `accessLogs` is created when the code is *used* (triggered by hardware confirming unlock via code).
* **Code Usage:** When a guest uses the code at the intercom, the hardware module verifies it against the backend/its cache and sends an unlock confirmation. The `accessLogs` entry will have `accessMethod: 'code'`. The `isActive` status in `temporaryAccessCodes` is updated to `false` or the entry is marked used.
* **Expiration:** Cron job or scheduled task cleans up expired codes or updates their `isActive` status.
5. **Visitor Log:**
* **Flow:** User navigates to 'Access Log' page.
* **Content:** Displays a paginated, sortable list of entries from the `accessLogs` table for their apartment.
* **Data:** Shows `accessGrantedAt`, `guestName` (if provided), `guestIdentifier`, `accessMethod`.
* **Filtering/Sorting:** Allow filtering by date range, access method.
6. **Apple HomeKit Integration Management:**
* **Flow:** User navigates to 'Settings' -> 'Integrations'.
* **Content:** Shows connection status to Apple HomeKit. Provides options to 'Connect/Reconnect' or 'Disconnect'.
* **Action (Connect):** Initiates the pairing process. May involve displaying a QR code for the Home app to scan or guiding the user through HomeKit's native pairing.
* **Backend:** Handles the HomeKit accessory setup and communication protocols (e.g., HAP-NodeJS or cloud-to-cloud integration if available).
* **Notifications:** When integrated, visitor events (like someone ringing the bell, if intercom supports it) trigger Apple Home notifications and can be configured to trigger the door unlock via HomeKit automations.
API & DATA FETCHING:
- Use RESTful API principles for backend endpoints.
- Utilize Next.js API Routes (App Router structure: `src/app/api/...`).
- Data fetching in components will primarily use React Query (`@tanstack/react-query`) for caching, background updates, and state management.
- Example Endpoints:
- `POST /api/auth/signup`: User registration.
- `POST /api/auth/login`: User login.
- `GET /api/apartments/me`: Get current user's apartment details and integration status.
- `POST /api/apartments`: Create/configure apartment details.
- `PUT /api/apartments/{id}`: Update apartment settings.
- `POST /api/apartments/{id}/unlock`: Trigger manual door unlock.
- `POST /api/apartments/{id}/access-codes`: Generate a new temporary access code.
- `GET /api/apartments/{id}/access-codes`: List active temporary codes.
- `DELETE /api/apartments/{id}/access-codes/{codeId}`: Revoke a code.
- `GET /api/apartments/{id}/logs`: Get access log history (with pagination/filtering).
- `POST /api/hardware/callback`: Endpoint for the hardware module to report status or trigger events (e.g., button press detected, code usage).
- Request/Response Bodies: Use JSON. Validate requests using Zod.
COMPONENT BREAKDOWN (Next.js App Router Structure):
`src/app/`
├── `(auth)/` (Auth layout and pages)
│ ├── `layout.tsx`
│ ├── `login/page.tsx`
│ ├── `signup/page.tsx`
│ └── `reset-password/page.tsx`
├── `(app)/` (Main application layout after authentication)
│ ├── `layout.tsx` (Main layout with Sidebar/Navbar)
│ ├── `dashboard/page.tsx` (Dashboard view)
│ ├── `apartment/page.tsx` (Apartment settings/configuration)
│ ├── `access-codes/page.tsx` (Manage temporary access codes)
│ ├── `access-log/page.tsx` (View visitor history)
│ ├── `settings/page.tsx` (User profile, integrations, security)
│ └── `integrations/apple-home/page.tsx` (Specific Apple HomeKit setup)
├── `api/` (API Routes)
│ ├── `auth/[...nextauth]/route.ts`
│ ├── `apartments/[id]/.../route.ts`
│ ├── `hardware/callback/route.ts`
│ └── ...
├── `page.tsx` (Homepage / Landing Page)
├── `layout.tsx` (Root layout, providers)
└── `globals.css`
`src/components/`
- `ui/`: Re-exports from shadcn/ui (e.g., Button, Card, Input, Toast, Dialog).
- `layout/`: Navbar, Sidebar, Footer, AuthLayout.
- `dashboard/`: WidgetCard, RecentLogsList, QuickActions.
- `apartment/`: ApartmentConfigForm, HardwareConnectGuide.
- `access-codes/`: AccessCodeGeneratorForm, AccessCodeListItem, ShareCodeButton.
- `access-log/`: LogTable, LogFilter.
- `auth/`: LoginForm, SignupForm.
- `common/`: LoadingSpinner, ErrorMessage, StateDisplay.
State Management: Primarily managed by React Query for server state. Local component state using `useState`. Global state (e.g., user session) via NextAuth.js context or Zustand if needed.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style:** Clean, Modern, Professional, with a hint of tech-forward elegance.
- **Color Palette:**
- Primary: `{#4F46E5}` (Indigo-600) - For main actions, active states.
- Secondary: `{#6366F1}` (Indigo-500) - For less prominent actions, accents.
- Accent: `{#06B6D4}` (Cyan-500) - For highlights, status indicators (like successful integration).
- Neutral Dark: `{#1F2937}` (Gray-800) - Backgrounds, text.
- Neutral Light: `{#F9FAFB}` (Gray-50) - Backgrounds, cards.
- Success: `{#10B981}` (Green-500)
- Warning: `{#F59E0B}` (Amber-500)
- Error: `{#EF4444}` (Red-500)
- **Typography:** Inter (from Google Fonts) - Sans-serif, clean, readable.
- Headings: Inter Bold (e.g., 3xl, 2xl)
- Body Text: Inter Regular (e.g., base, sm)
- **Layout:**
- Desktop: Sidebar navigation on the left, main content area on the right. Use of cards for distinct sections.
- Mobile: Collapsible sidebar (hamburger menu), content takes full width. Prioritize key actions.
- **Responsiveness:** Mobile-first approach. Tailwind CSS utility classes for responsive breakpoints (`sm:`, `md:`, `lg:`).
- **Visual Elements:** Subtle use of gradients in headers or buttons. Clean icons (Heroicons or similar). Minimalistic illustrations for onboarding or empty states.
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out using Next.js `AnimatePresence` (if using `framer-motion`).
- **Button Hovers:** Slight scale-up or background color change.
- **Loading States:** Skeleton loaders for data fetching, spinners within buttons during API calls.
- **Element Transitions:** Smooth appearance of new elements (e.g., adding a log entry).
- **Toggles/Switches:** Smooth animation for status changes.
EDGE CASES:
- **Authentication:** Handle expired sessions, incorrect login attempts, OAuth callback errors, email verification flow.
- **Authorization:** Ensure users can only access/modify their own apartment data (`middleware.ts` or server-side checks).
- **Hardware Connectivity:** Gracefully handle cases where the hardware device is offline or unresponsive. Display clear status indicators ('Device Offline', 'Last seen: ...'). Implement retry mechanisms.
- **API Errors:** Robust error handling for all API calls. Display user-friendly error messages via toasts.
- **Form Validation:** Use Zod with `react-hook-form` for client-side and server-side validation (e.g., email format, password strength, valid dates, code uniqueness).
- **Empty States:** Design informative and visually appealing empty states for Dashboard, Access Log, and Access Codes pages (e.g., 'No access logs yet. Start granting access!').
- **Rate Limiting:** Implement rate limiting on sensitive API endpoints (login, unlock, code generation) to prevent abuse.
- **Data Consistency:** Ensure data integrity between the hardware module and the backend, especially regarding access code usage and unlocking events.
SAMPLE/MOCK DATA:
1. **User:** `{ id: 'uuid-user-1', name: 'Alice Wonderland', email: 'alice@example.com', image: '...' }`
2. **Apartment:** `{ id: 'uuid-apt-1', userId: 'uuid-user-1', intercomModel: 'Doorking 1834-080', locationIdentifier: 'Unit 10A', isAppleHomeIntegrated: true, hardwareDeviceId: 'HWID-ALICE-123' }`
3. **Access Log Entry (Manual Unlock):** `{ id: 'uuid-log-1', apartmentId: 'uuid-apt-1', guestName: null, guestIdentifier: null, accessGrantedAt: '2024-07-27T10:30:00Z', accessMethod: 'manual_open', notes: 'Opened by Alice via app' }`
4. **Access Log Entry (Code Used):** `{ id: 'uuid-log-2', apartmentId: 'uuid-apt-1', guestName: 'Bob The Builder', guestIdentifier: 'Code: 5X8Z', accessGrantedAt: '2024-07-27T11:15:00Z', accessMethod: 'code', notes: null }`
5. **Access Log Entry (Scheduled/HomeKit):** `{ id: 'uuid-log-3', apartmentId: 'uuid-apt-1', guestName: 'Charlie', guestIdentifier: 'HomeKit Automation', accessGrantedAt: '2024-07-27T14:00:00Z', accessMethod: 'homekit', notes: 'Delivery scheduled' }`
6. **Temporary Access Code:** `{ id: 'uuid-code-1', apartmentId: 'uuid-apt-1', code: 'A7B3', validUntil: '2024-07-28T09:00:00Z', createdByUserId: 'uuid-user-1', notes: 'For plumber visit', isActive: true }`
7. **Temporary Access Code (Expired):** `{ id: 'uuid-code-2', apartmentId: 'uuid-apt-1', code: 'C4D9', validUntil: '2024-07-26T18:00:00Z', createdByUserId: 'uuid-user-1', notes: 'Guest departed', isActive: false }`
8. **Hardware Status (Callback):** `{ hardwareDeviceId: 'HWID-ALICE-123', status: 'online', lastSeen: '2024-07-27T12:00:00Z', batteryLevel: 85 }` (This would be part of the `/api/hardware/callback` response or payload).
9. **Empty Access Log:** `[]`
10. **Empty Access Codes:** `[]`
TURKISH TRANSLATIONS:
- **App Title:** Akıllı Kapı Sistemi (Smart Door System) / Akıllı Giriş Kontrolü (Smart Access Control)
- **Buttons:** Giriş Yap (Log In), Kayıt Ol (Sign Up), Kapıyı Aç (Open Door), Kod Oluştur (Generate Code), Kodu Kopyala (Copy Code), Ayarlar (Settings), Entegrasyonlar (Integrations), Güncelle (Update), Kaydet (Save), Geri Dön (Go Back), Oturumu Kapat (Log Out).
- **Page Titles:** Kontrol Paneli (Dashboard), Daire Ayarları (Apartment Settings), Erişim Kodları (Access Codes), Ziyaretçi Kayıtları (Access Log), Entegrasyonlar (Integrations), Profil Ayarları (Profile Settings).
- **Labels/Placeholders:** E-posta (Email), Şifre (Password), Daire Adresi/Tanımı (Apartment Address/Identifier), İnterkom Modeli (Intercom Model), Misafir Adı (Guest Name), Geçerlilik Süresi (Valid Until), Notlar (Notes), Cihaz ID'si (Device ID).
- **Messages:** Kapı başarıyla açıldı (Door unlocked successfully), Erişim kodu oluşturuldu (Access code generated), Cihaz çevrimdışı (Device offline), Lütfen dairenizi yapılandırın (Please configure your apartment), Henüz kayıt yok (No logs yet).
- **Feature Names:** Uzaktan Erişim (Remote Access), Geçici Kodlar (Temporary Codes), Ziyaretçi Takibi (Visitor Tracking), Apple Home Entegrasyonu (Apple Home Integration).