Add frontend_old as regular files

This commit is contained in:
2026-06-22 15:50:36 +02:00
parent 215d6739d1
commit 829fc3b008
140 changed files with 24348 additions and 1 deletions
Submodule frontend_old deleted from f45f9d61da
+46
View File
@@ -0,0 +1,46 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/node_modules_old
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
.git
.git_bak
node_modules
target
+44
View File
@@ -0,0 +1,44 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
## Install
- Jose
- Node.js
- Add emoji pakages
- Install postgres for databases
- Typescript
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+56
View File
@@ -0,0 +1,56 @@
# CRM Frontend - Quick Start
## Prerequisites
- Node.js >= 18.17 (recommended: 20.9+ or 22.x)
- npm 9+
## Install & Run
```bash
cd frontend
# Install dependencies
npm install
# Start dev server
npm run dev
```
The app runs at **http://localhost:3000**
## Pages
| Route | Description |
|-------|-------------|
| `/login` | Login page |
| `/` | Dashboard |
| `/leads` | Lead management table |
| `/leads/:id` | Lead detail view |
| `/users` | User management |
| `/settings` | Settings (Company, Theme, Notifications) |
## Tech Stack
- Next.js 15 + React 18
- TypeScript + Tailwind CSS v4
- shadcn/ui components (Radix primitives)
- TanStack Table v8
- Recharts
- Framer Motion
- Lucide Icons
## If Node.js is < 20.9
The eslint-config-next package requires Node.js >= 20.9. If your Node.js is older:
```bash
npm install --legacy-peer-deps
```
Or upgrade Node.js via [nvm](https://github.com/nvm-sh/nvm):
```bash
nvm install 22
nvm use 22
```
+40
View File
@@ -0,0 +1,40 @@
# AI Sales Assistant — Self-Improvement Instructions
## Purpose
This file contains the AI's own configuration, knowledge, and improvement rules.
The AI can read and modify this file to update its behavior at runtime.
## Current Instructions
- Always respond in English
- Keep responses under 300 words unless asked for detail
- Use bullet points for lists
- Be direct and actionable — no fluff
- Never mention being an AI or language model
- Refer to the user by their role (salesperson, admin, etc.)
- If unsure about a topic, say "I don't have that information yet" rather than guessing
## Knowledge Base
### Sales Tips
- Cold emails should be under 150 words
- Follow up within 48 hours
- Personalise every outreach with the prospect's name and company
- Use open-ended questions in discovery calls
- Always ask for the next step before ending a call
### Job Targeting
- Developers respond best to technical value props
- Marketing managers care about ROI and metrics
- C-level executives want brevity and business impact
## Improvement Log
Track changes made by the AI to improve itself:
- (initial) Basic instructions and knowledge base created
## Self-Modification Rules
The AI may update this file when:
1. It identifies a gap in its knowledge that would help salespeople
2. It discovers a better way to structure responses
3. A user explicitly requests an update to behavior
4. It notices repeated questions that aren't well-covered
Only append to the Improvement Log — don't delete previous entries.
+10
View File
@@ -0,0 +1,10 @@
{"job_title":"Software Developer","keywords":["developer","programmer","software engineer","coder","full stack","backend","frontend"],"industry":"Technology","description":"Builds and maintains software applications and systems"}
{"job_title":"Marketing Specialist","keywords":["marketing","digital marketing","brand manager","content marketer","social media"],"industry":"Marketing","description":"Plans and executes marketing campaigns across channels"}
{"job_title":"Sales Representative","keywords":["sales rep","account executive","business development","sales consultant"],"industry":"Sales","description":"Drives revenue through client acquisition and relationship management"}
{"job_title":"Project Manager","keywords":["project manager","program manager","scrum master","agile coach"],"industry":"Business","description":"Oversees project timelines, resources, and deliverables"}
{"job_title":"Graphic Designer","keywords":["designer","graphic designer","ui designer","ux designer","visual designer"],"industry":"Creative","description":"Creates visual concepts and designs for digital and print media"}
{"job_title":"Data Analyst","keywords":["data analyst","business analyst","data scientist","analytics"],"industry":"Technology","description":"Analyzes data to provide actionable business insights"}
{"job_title":"Customer Support Specialist","keywords":["customer support","customer service","support agent","help desk"],"industry":"Customer Service","description":"Assists customers with inquiries, issues, and product support"}
{"job_title":"Human Resources Manager","keywords":["HR manager","HR","recruiter","talent acquisition","people operations"],"industry":"Human Resources","description":"Manages recruitment, employee relations, and HR operations"}
{"job_title":"Financial Advisor","keywords":["financial advisor","financial planner","wealth manager","investment advisor"],"industry":"Finance","description":"Provides financial guidance and investment planning to clients"}
{"job_title":"Operations Manager","keywords":["operations manager","operations","logistics","supply chain"],"industry":"Business","description":"Oversees daily operations and process optimization"}
+164
View File
@@ -0,0 +1,164 @@
# CRM Database Schema — Enterprise RBAC + CRM
## Architecture Overview
Enterprise-grade PostgreSQL schema implementing **hierarchical Role-Based Access Control (RBAC)**
with a complete CRM system. Designed for production deployments with strict security requirements,
audit compliance, and scalability to millions of records.
---
## 1. Hierarchical RBAC Model
Four roles arranged in a strict hierarchy by `hierarchy_level` (lower = higher privilege):
| Role | Level | Authority |
|------|-------|-----------|
| **SUPER_ADMIN** | 1 | Unrestricted — create/delete users, assign roles, override all permissions |
| **ADMIN** | 2 | Operational — ban/suspend users, review reports, moderate activity. **Cannot create accounts.** |
| **SALES_USER** | 3 | CRM operations — leads, customers, opportunities, communications |
| **DEVELOPER** | 4 | Technical + CRM read access for post-sale project visibility |
### Enforcement via PostgreSQL Triggers
- **`enforce_create_user()`** (BEFORE INSERT ON users): Only SUPER_ADMIN (`hierarchy_level = 1`)
can create new user accounts. Bootstrap case (`created_by IS NULL`) is allowed for initial setup.
- **`enforce_role_assignment()`** (BEFORE INSERT ON user_roles): Only SUPER_ADMIN can assign roles.
Prevents privilege escalation by checking hierarchy levels.
### Permission Model
Granular permissions stored in `permissions` table with `(resource, action)` pairs.
`role_permissions` maps roles to permissions. The `has_permission(user_id, resource, action)`
function provides application-layer authorization checks.
---
## 2. Ban & Suspension System
Two separate tables for enforcement flexibility:
- **`banned_users`**: Permanent or time-limited bans. Supports reversal (by SUPER_ADMIN).
Admins can create bans; SUPER_ADMIN can reverse or permanently delete banned users.
- **`suspended_users`**: Time-limited suspensions (always has expiry). Admins can create
and lift suspensions.
Both tables are fully audited via dedicated trigger functions.
---
## 3. Session & Login Security
- **`sessions`**: Stores hashed session tokens with expiry. Only one active session per
token hash.
- **`login_attempts`**: Captures every login attempt (successful or failed) with IP address
and user agent. Used for brute-force detection and audit.
- Users have `failed_login_attempts` and `locked_until` for account lockout policies.
---
## 4. Password Security
- All passwords hashed with **bcrypt (cost factor 12)**
- `password_change_required` forces password change on first login (TRUE for all non-root
test accounts)
- Password hashes are opaque to the database — validation is application-layer only
---
## 5. UUID Primary Keys
- All tables use `UUID PRIMARY KEY DEFAULT uuid_generate_v4()`
- Fixed UUIDs used for seed data and system entities for referential transparency
- Prevents enumeration attacks and supports distributed ID generation
---
## 6. Audit Trail
Every mutation is logged to `audit_logs` via `audit_trigger_function()`:
- Captures `(table_name, record_id, action, old_data, new_data, changed_by, ip_address)`
- Ban actions, suspension actions, and successful logins have dedicated audit triggers
- Indexed on `(table_name, record_id)` for per-record lookup
Dedicated audit views:
- `v_active_bans` — Currently active bans with user details
- `v_active_suspensions` — Currently active suspensions
- `v_user_permissions` — Flattened permission report per user
---
## 7. Third Normal Form (3NF)
Customer model uses the **discriminator pattern**:
```
customers (parent — shared columns: status, owner, tags, score)
├── customer_type = 'individual' → individual_customers
└── customer_type = 'company' → company_customers
```
All lookup tables are normalized. Contact information, addresses, and notes are
separate 1:N child tables.
---
## 8. Indexing Strategy
- **Core indexes**: FK columns, status/sort/date columns, unique constraints
- **Partial indexes**: `WHERE deleted_at IS NULL` on soft-delete tables,
`WHERE is_active = TRUE` on bans/suspensions, `WHERE due_date < NOW()` on overdue invoices
- **Full-text search**: GIN indexes on customers, leads, products, communications, tasks
- **Composite indexes**: Common query patterns (e.g., `opportunities(owner_id, stage_id)`)
---
## 9. Soft Delete
- `deleted_at TIMESTAMPTZ` on all business tables
- Partial unique indexes ignore soft-deleted rows (e.g., `WHERE deleted_at IS NULL`)
- Audit logs capture the full row snapshot before soft-delete
---
## 10. Test Accounts
| Username | Password | Role |
|----------|----------|------|
| `superadmin_demo` | `SuperAdmin@2026` | SUPER_ADMIN |
| `admin_demo` | `AdminAccess@2026` | ADMIN |
| `sales_demo` | `SalesAccess@2026` | SALES_USER |
| `dev_demo` | `DevTesting@2026` | DEVELOPER |
---
## 11. Migration Instructions
```bash
# Create database
psql -U postgres -c "CREATE DATABASE crm;"
# Run full migration
psql -U postgres -d crm -f database/migrations/run_all.sql
# Or step by step:
psql -U postgres -d crm -f database/migrations/001_schema.sql
psql -U postgres -d crm -f database/migrations/002_seed.sql
```
---
## 12. Security Rules Summary
| Rule | Enforcement |
|------|-------------|
| Only SUPER_ADMIN creates accounts | Trigger `trg_enforce_create_user` |
| Only SUPER_ADMIN assigns roles | Trigger `trg_enforce_role_assignment` |
| No privilege escalation | Level check in `enforce_role_assignment()` |
| bcrypt password hashing | Application-layer (cost=12) |
| Unique usernames/emails | Partial unique indexes |
| Force password change on first login | `password_change_required` column |
| Audit every login/logout | Trigger `trg_audit_login` on `login_attempts` |
| Audit every ban action | Trigger `trg_audit_ban` on `banned_users` |
| Audit every suspension action | Trigger `trg_audit_suspension` on `suspended_users` |
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,401 @@
-- ============================================================================
-- CRM Database Seed Data — RBAC + Test Accounts + Reference Data
-- ============================================================================
-- ============================================================================
-- FIXED UUIDs FOR REFERENTIAL INTEGRITY
-- ============================================================================
-- Role UUIDs
-- SUPER_ADMIN=1, ADMIN=2, SALES_USER=3, DEVELOPER=4
-- User UUIDs: SUPER_ADMIN=u0001, ADMIN=u0002, SALES=u0003, DEV=u0004
-- ============================================================================
-- 1. ROLES
-- ============================================================================
INSERT INTO roles (id, name, display_name, description, hierarchy_level, is_system) VALUES
('00000001-0000-0000-0000-000000000000', 'SUPER_ADMIN', 'Super Administrator',
'Highest authority. Full system access. Can create/delete users, assign roles, override all permissions.',
1, TRUE),
('00000002-0000-0000-0000-000000000000', 'ADMIN', 'Administrator',
'Operational administration. Can ban/suspend users, review reports, moderate activity. Cannot create accounts.',
2, TRUE),
('00000003-0000-0000-0000-000000000000', 'SALES_USER', 'Sales Representative',
'Day-to-day CRM operations. Manage leads, customers, opportunities, and communications.',
3, TRUE),
('00000004-0000-0000-0000-000000000000', 'DEVELOPER', 'Developer',
'Internal development/testing with CRM read access. API testing, diagnostics, debugging. Can view projects and customer data post-sale.',
4, TRUE)
ON CONFLICT (name) DO NOTHING;
-- ============================================================================
-- 2. PERMISSIONS — organised by category
-- ============================================================================
-- USER MANAGEMENT (SUPER_ADMIN only)
INSERT INTO permissions (id, resource, action, description, category) VALUES
('a0010001-0000-0000-0000-000000000000', 'users', 'create', 'Create new user accounts', 'User Management'),
('a0010002-0000-0000-0000-000000000000', 'users', 'read', 'View user details', 'User Management'),
('a0010003-0000-0000-0000-000000000000', 'users', 'update', 'Update user details', 'User Management'),
('a0010004-0000-0000-0000-000000000000', 'users', 'delete', 'Permanently delete user accounts', 'User Management'),
('a0010005-0000-0000-0000-000000000000', 'users', 'assign_roles', 'Assign roles to users', 'User Management'),
('a0010006-0000-0000-0000-000000000000', 'users', 'promote', 'Promote users to higher roles', 'User Management'),
('a0010007-0000-0000-0000-000000000000', 'users', 'demote', 'Demote users to lower roles', 'User Management'),
('a0010008-0000-0000-0000-000000000000', 'users', 'reset_password', 'Reset user passwords', 'User Management'),
('a0010009-0000-0000-0000-000000000000', 'users', 'disable', 'Disable/disable user accounts', 'User Management'),
('a0010010-0000-0000-0000-000000000000', 'users', 'permanently_delete', 'Permanently remove accounts from system', 'User Management')
ON CONFLICT DO NOTHING;
-- BAN & SUSPENSION (ADMIN + SUPER_ADMIN)
INSERT INTO permissions (id, resource, action, description, category) VALUES
('a0020001-0000-0000-0000-000000000000', 'bans', 'create', 'Ban a user account', 'Ban Management'),
('a0020002-0000-0000-0000-000000000000', 'bans', 'reverse', 'Reverse a ban on a user', 'Ban Management'),
('a0020003-0000-0000-0000-000000000000', 'bans', 'permanently_delete', 'Permanently delete banned users', 'Ban Management'),
('a0020004-0000-0000-0000-000000000000', 'suspensions', 'create', 'Suspend a user account', 'Ban Management'),
('a0020005-0000-0000-0000-000000000000', 'suspensions', 'lift', 'Lift a suspension', 'Ban Management'),
('a0020006-0000-0000-0000-000000000000', 'suspensions', 'view', 'View suspension records', 'Ban Management')
ON CONFLICT DO NOTHING;
-- CRM CORE (SALES_USER + MANAGERS)
INSERT INTO permissions (id, resource, action, description, category) VALUES
('a0030001-0000-0000-0000-000000000000', 'customers', 'create', 'Create customer records', 'CRM'),
('a0030002-0000-0000-0000-000000000000', 'customers', 'read', 'View customer records', 'CRM'),
('a0030003-0000-0000-0000-000000000000', 'customers', 'update', 'Update customer records', 'CRM'),
('a0030004-0000-0000-0000-000000000000', 'customers', 'delete', 'Delete customer records', 'CRM'),
('a0030005-0000-0000-0000-000000000000', 'leads', 'create', 'Create sales leads', 'CRM'),
('a0030006-0000-0000-0000-000000000000', 'leads', 'read', 'View sales leads', 'CRM'),
('a0030007-0000-0000-0000-000000000000', 'leads', 'update', 'Update sales leads', 'CRM'),
('a0030008-0000-0000-0000-000000000000', 'leads', 'convert', 'Convert leads to customers', 'CRM'),
('a0030009-0000-0000-0000-000000000000', 'opportunities', 'create', 'Create sales opportunities', 'CRM'),
('a0030010-0000-0000-0000-000000000000', 'opportunities', 'read', 'View sales opportunities', 'CRM'),
('a0030011-0000-0000-0000-000000000000', 'opportunities', 'update', 'Update sales pipeline', 'CRM'),
('a0030012-0000-0000-0000-000000000000', 'pipeline', 'update', 'Update sales pipeline stages', 'CRM'),
('a0030013-0000-0000-0000-000000000000', 'communications', 'create', 'Log calls and meetings', 'CRM'),
('a0030014-0000-0000-0000-000000000000', 'communications', 'read', 'View communication history', 'CRM'),
('a0030015-0000-0000-0000-000000000000', 'contacts', 'manage', 'Manage customer contact details', 'CRM'),
('a0030016-0000-0000-0000-000000000000', 'products', 'read', 'View product catalog', 'CRM'),
('a0030017-0000-0000-0000-000000000000', 'invoices', 'read', 'View invoices', 'CRM')
ON CONFLICT DO NOTHING;
-- REPORTING & INCIDENTS (ADMIN)
INSERT INTO permissions (id, resource, action, description, category) VALUES
('a0040001-0000-0000-0000-000000000000', 'reports', 'customers_view', 'Review customer reports', 'Reporting'),
('a0040002-0000-0000-0000-000000000000', 'reports', 'incidents_view', 'Review incident reports', 'Reporting'),
('a0040003-0000-0000-0000-000000000000', 'reports', 'complaints_investigate', 'Investigate complaints', 'Reporting'),
('a0040004-0000-0000-0000-000000000000', 'crm', 'dashboard_access', 'Access CRM dashboards', 'Reporting'),
('a0040005-0000-0000-0000-000000000000', 'activity', 'logs_view', 'View user activity logs', 'Reporting'),
('a0040006-0000-0000-0000-000000000000', 'suspicious', 'moderate', 'Moderate suspicious activity', 'Reporting'),
('a0040007-0000-0000-0000-000000000000', 'accounts', 'lock_investigation', 'Lock accounts under investigation', 'Reporting')
ON CONFLICT DO NOTHING;
-- AUDIT & SYSTEM (SUPER_ADMIN + limited ADMIN)
INSERT INTO permissions (id, resource, action, description, category) VALUES
('a0050001-0000-0000-0000-000000000000', 'audit', 'full_access', 'Full audit log access', 'System'),
('a0050002-0000-0000-0000-000000000000', 'audit', 'read', 'View audit logs', 'System'),
('a0050003-0000-0000-0000-000000000000', 'settings', 'modify', 'Modify system settings', 'System'),
('a0050004-0000-0000-0000-000000000000', 'database', 'full_access', 'Full database access', 'System'),
('a0050005-0000-0000-0000-000000000000', 'crm', 'full_access', 'Full CRM access override', 'System'),
('a0050006-0000-0000-0000-000000000000', 'permissions', 'override', 'Override all permissions', 'System')
ON CONFLICT DO NOTHING;
-- DEVELOPER PERMISSIONS
INSERT INTO permissions (id, resource, action, description, category) VALUES
('a0060001-0000-0000-0000-000000000000', 'api', 'testing', 'API testing access', 'Developer'),
('a0060002-0000-0000-0000-000000000000', 'backend', 'diagnostics', 'Backend diagnostics', 'Developer'),
('a0060003-0000-0000-0000-000000000000', 'system', 'logs_view', 'View system logs', 'Developer'),
('a0060004-0000-0000-0000-000000000000', 'database', 'diagnostics', 'Database diagnostics', 'Developer'),
('a0060005-0000-0000-0000-000000000000', 'debugging', 'access', 'Debugging access', 'Developer'),
('a0060006-0000-0000-0000-000000000000', 'testing', 'internal', 'Internal testing access', 'Developer')
ON CONFLICT DO NOTHING;
-- ============================================================================
-- 3. ROLE-PERMISSION MAPPING
-- ============================================================================
-- SUPER_ADMIN — ALL permissions
INSERT INTO role_permissions (role_id, permission_id)
SELECT '00000001-0000-0000-0000-000000000000', id FROM permissions
ON CONFLICT DO NOTHING;
-- ADMIN — Bans, Suspensions, Reporting, CRM read, Activity logs
INSERT INTO role_permissions (role_id, permission_id, granted_by) VALUES
-- Bans & Suspensions
('00000002-0000-0000-0000-000000000000', 'a0020001-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0020004-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0020005-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0020006-0000-0000-0000-000000000000', NULL),
-- User read + disable
('00000002-0000-0000-0000-000000000000', 'a0010002-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0010009-0000-0000-0000-000000000000', NULL),
-- Reporting & Incidents
('00000002-0000-0000-0000-000000000000', 'a0040001-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0040002-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0040003-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0040004-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0040005-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0040006-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0040007-0000-0000-0000-000000000000', NULL),
-- CRM read access
('00000002-0000-0000-0000-000000000000', 'a0030002-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0030006-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0030010-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0030014-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0030016-0000-0000-0000-000000000000', NULL),
('00000002-0000-0000-0000-000000000000', 'a0030017-0000-0000-0000-000000000000', NULL),
-- Audit read
('00000002-0000-0000-0000-000000000000', 'a0050002-0000-0000-0000-000000000000', NULL)
ON CONFLICT DO NOTHING;
-- SALES_USER — CRM operations
INSERT INTO role_permissions (role_id, permission_id, granted_by) VALUES
('00000003-0000-0000-0000-000000000000', 'a0030001-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030002-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030003-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030005-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030006-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030007-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030008-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030009-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030010-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030011-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030012-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030013-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030014-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030015-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030016-0000-0000-0000-000000000000', NULL),
('00000003-0000-0000-0000-000000000000', 'a0030017-0000-0000-0000-000000000000', NULL)
ON CONFLICT DO NOTHING;
-- DEVELOPER — Technical permissions + CRM read access (post-sale project visibility)
INSERT INTO role_permissions (role_id, permission_id, granted_by) VALUES
-- Developer technical permissions
('00000004-0000-0000-0000-000000000000', 'a0060001-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0060002-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0060003-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0060004-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0060005-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0060006-0000-0000-0000-000000000000', NULL),
-- User self-view
('00000004-0000-0000-0000-000000000000', 'a0010002-0000-0000-0000-000000000000', NULL),
-- CRM access (matching SALES_USER level for post-sale project visibility)
('00000004-0000-0000-0000-000000000000', 'a0030002-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0030006-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0030010-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0030014-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0030016-0000-0000-0000-000000000000', NULL),
('00000004-0000-0000-0000-000000000000', 'a0030017-0000-0000-0000-000000000000', NULL)
ON CONFLICT DO NOTHING;
-- ============================================================================
-- 4. TEST ACCOUNTS
-- ============================================================================
-- Passwords (bcrypt, cost=12):
-- superadmin_demo / SuperAdmin@2026
-- admin_demo / AdminAccess@2026
-- sales_demo / SalesAccess@2026
-- dev_demo / DevTesting@2026
INSERT INTO users (id, username, email, password_hash, first_name, last_name, is_active, password_change_required) VALUES
('00000000-0000-0000-0000-000000000001', 'superadmin_demo', 'superadmin@coastit.co.za',
'$2b$12$C5hczK17I.bu6ILzmGW0U.UnFSdfTuDh42C8t16nxRKaUtXKkdWlC',
'Super', 'Admin', TRUE, FALSE),
('00000000-0000-0000-0000-000000000002', 'admin_demo', 'admin@coastit.co.za',
'$2b$12$TCDq5.sXHA4kWelQPKO6DeQo.WW.NeTuNtOed57UdQ3lRs7.rdkNy',
'System', 'Admin', TRUE, TRUE),
('00000000-0000-0000-0000-000000000003', 'sales_demo', 'sales@coastit.co.za',
'$2b$12$Xhh20UmTn.LTQAs4v4cHx.yQgvuYyNo6TkPaytQ1Q8o0oTPCtIj7W',
'Sales', 'User', TRUE, TRUE),
('00000000-0000-0000-0000-000000000004', 'dev_demo', 'dev@coastit.co.za',
'$2b$12$ghyJFb17lXoFOCYUPB6Fk.q8wDNOJhq9OUPNzd5DKaZsDjCF2NBJa',
'Dev', 'User', TRUE, TRUE)
ON CONFLICT (username) WHERE (deleted_at IS NULL) DO NOTHING;
-- Update the SUPER_ADMIN to set created_by to self (post-bootstrap)
UPDATE users SET created_by = '00000000-0000-0000-0000-000000000001'
WHERE id = '00000000-0000-0000-0000-000000000001' AND created_by IS NULL;
-- Set created_by for other users (SUPER_ADMIN created them)
UPDATE users SET created_by = '00000000-0000-0000-0000-000000000001'
WHERE id IN ('00000000-0000-0000-0000-000000000002','00000000-0000-0000-0000-000000000003','00000000-0000-0000-0000-000000000004')
AND created_by IS NULL;
-- ============================================================================
-- 5. ROLE ASSIGNMENTS
-- ============================================================================
-- Assign SUPER_ADMIN role to superadmin_demo (bootstrap — assigned_by NULL)
INSERT INTO user_roles (user_id, role_id, assigned_by) VALUES
('00000000-0000-0000-0000-000000000001', '00000001-0000-0000-0000-000000000000', NULL)
ON CONFLICT DO NOTHING;
-- Assign remaining roles (SUPER_ADMIN assigned them)
INSERT INTO user_roles (user_id, role_id, assigned_by) VALUES
('00000000-0000-0000-0000-000000000002', '00000002-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000001'),
('00000000-0000-0000-0000-000000000003', '00000003-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000001'),
('00000000-0000-0000-0000-000000000004', '00000004-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000001')
ON CONFLICT DO NOTHING;
-- ============================================================================
-- 6. REFERENCE DATA
-- ============================================================================
-- Customer Statuses
INSERT INTO customer_statuses (id, name, description, color, sort_order, is_default) VALUES
('c0000000-0000-0000-0000-000000000001', 'Active', 'Customer in good standing', '#22C55E', 1, TRUE),
('c0000000-0000-0000-0000-000000000002', 'Inactive', 'No recent activity', '#A0AEC0', 2, FALSE),
('c0000000-0000-0000-0000-000000000003', 'At Risk', 'Showing signs of churn', '#F59E0B', 3, FALSE),
('c0000000-0000-0000-0000-000000000004', 'Churned', 'Relationship ended', '#EF4444', 4, FALSE),
('c0000000-0000-0000-0000-000000000005', 'VIP', 'High-value priority customer', '#8B5CF6', 0, FALSE)
ON CONFLICT DO NOTHING;
-- Lead Sources
INSERT INTO lead_sources (id, name, description) VALUES
('d0000000-0000-0000-0000-000000000001', 'Website', 'Organic website traffic or web forms'),
('d0000000-0000-0000-0000-000000000002', 'Referral', 'Referred by existing customer'),
('d0000000-0000-0000-0000-000000000003', 'LinkedIn', 'LinkedIn outreach'),
('d0000000-0000-0000-0000-000000000004', 'Email Campaign', 'Email marketing campaign'),
('d0000000-0000-0000-0000-000000000005', 'Trade Show', 'Event or trade show'),
('d0000000-0000-0000-0000-000000000006', 'Cold Call', 'Outbound cold calling'),
('d0000000-0000-0000-0000-000000000007', 'Partner', 'Channel partner referral'),
('d0000000-0000-0000-0000-000000000008', 'Social Media', 'Social media platforms'),
('d0000000-0000-0000-0000-000000000009', 'Advertisement', 'Paid advertising'),
('d0000000-0000-0000-0000-000000000010', 'Other', 'Other sources')
ON CONFLICT DO NOTHING;
-- Lead Stages
INSERT INTO lead_stages (id, name, description, sort_order, probability) VALUES
('e0000000-0000-0000-0000-000000000001', 'New', 'Newly captured lead', 1, 5),
('e0000000-0000-0000-0000-000000000002', 'Contacted', 'Initial contact made', 2, 10),
('e0000000-0000-0000-0000-000000000003', 'Qualified', 'Meets qualification criteria', 3, 25),
('e0000000-0000-0000-0000-000000000004', 'Interested', 'Shown interest', 4, 40),
('e0000000-0000-0000-0000-000000000005', 'Demo Scheduled', 'Product demo scheduled', 5, 60),
('e0000000-0000-0000-0000-000000000006', 'Negotiation', 'In price/terms negotiation', 6, 75),
('e0000000-0000-0000-0000-000000000007', 'Closed Won', 'Successfully converted', 7, 100),
('e0000000-0000-0000-0000-000000000008', 'Closed Lost', 'Lead was lost', 8, 0)
ON CONFLICT DO NOTHING;
-- Deal Stages
INSERT INTO deal_stages (id, name, description, sort_order, probability) VALUES
('f0000000-0000-0000-0000-000000000001', 'Prospecting', 'Initial qualification', 1, 10),
('f0000000-0000-0000-0000-000000000002', 'Discovery', 'Understanding needs', 2, 20),
('f0000000-0000-0000-0000-000000000003', 'Proposal', 'Solution proposed', 3, 40),
('f0000000-0000-0000-0000-000000000004', 'Negotiation', 'Commercial discussions', 4, 60),
('f0000000-0000-0000-0000-000000000005', 'Closing', 'Final stage before decision', 5, 80),
('f0000000-0000-0000-0000-000000000006', 'Won', 'Deal closed won', 6, 100),
('f0000000-0000-0000-0000-000000000007', 'Lost', 'Deal closed lost', 7, 0)
ON CONFLICT DO NOTHING;
-- Communication Types
INSERT INTO communication_types (id, name, description, icon) VALUES
('b0000000-0000-0000-0000-000000000001', 'Email', 'Email correspondence', 'mail'),
('b0000000-0000-0000-0000-000000000002', 'Phone Call', 'Telephone conversation', 'phone'),
('b0000000-0000-0000-0000-000000000003', 'Meeting', 'In-person or virtual meeting', 'users'),
('b0000000-0000-0000-0000-000000000004', 'Chat', 'Instant messaging', 'message-circle'),
('b0000000-0000-0000-0000-000000000005', 'SMS', 'Text message', 'message-square'),
('b0000000-0000-0000-0000-000000000006', 'Video Call', 'Video conference', 'video'),
('b0000000-0000-0000-0000-000000000007', 'Letter', 'Physical mail', 'file-text')
ON CONFLICT DO NOTHING;
-- Task Priorities
INSERT INTO task_priorities (id, name, color, sort_order) VALUES
('c0000000-0000-0000-0000-000000000001', 'Critical', '#EF4444', 1),
('c0000000-0000-0000-0000-000000000002', 'High', '#F59E0B', 2),
('c0000000-0000-0000-0000-000000000003', 'Medium', '#3B82F6', 3),
('c0000000-0000-0000-0000-000000000004', 'Low', '#A0AEC0', 4)
ON CONFLICT DO NOTHING;
-- Invoice Statuses
INSERT INTO invoice_statuses (id, name, description, color, sort_order) VALUES
('d0000000-0000-0000-0000-000000000001', 'Draft', 'Invoice in draft state', '#A0AEC0', 1),
('d0000000-0000-0000-0000-000000000002', 'Sent', 'Invoice sent to customer', '#3B82F6', 2),
('d0000000-0000-0000-0000-000000000003', 'Paid', 'Payment received in full', '#22C55E', 3),
('d0000000-0000-0000-0000-000000000004', 'Overdue', 'Payment past due date', '#EF4444', 4),
('d0000000-0000-0000-0000-000000000005', 'Partially Paid', 'Partial payment received', '#F59E0B', 5),
('d0000000-0000-0000-0000-000000000006', 'Cancelled', 'Invoice cancelled', '#6B7280', 6),
('d0000000-0000-0000-0000-000000000007', 'Refunded', 'Payment refunded', '#8B5CF6', 7)
ON CONFLICT DO NOTHING;
-- Product Categories
INSERT INTO product_categories (id, name, description, sort_order) VALUES
('e0000000-0000-0000-0000-000000000001', 'Software', 'Software products and licenses', 1),
('e0000000-0000-0000-0000-000000000002', 'Hardware', 'Physical hardware products', 2),
('e0000000-0000-0000-0000-000000000003', 'Services', 'Professional services', 3),
('e0000000-0000-0000-0000-000000000004', 'Subscription', 'Recurring subscription plans', 4),
('e0000000-0000-0000-0000-000000000005', 'Training', 'Training and certification', 5)
ON CONFLICT DO NOTHING;
-- ============================================================================
-- 7. SAMPLE CRM DATA (for demo purposes)
-- ============================================================================
-- Sample Products
INSERT INTO products (id, category_id, name, description, sku, unit_price, cost_price) VALUES
('f0000000-0000-0000-0000-000000000001', 'e0000000-0000-0000-0000-000000000001', 'CRM Pro License', 'Enterprise CRM license per user/year', 'SW-CRM-001', 1200.00, 300.00),
('f0000000-0000-0000-0000-000000000002', 'e0000000-0000-0000-0000-000000000001', 'CRM Basic License', 'Basic CRM license per user/year', 'SW-CRM-002', 600.00, 150.00),
('f0000000-0000-0000-0000-000000000003', 'e0000000-0000-0000-0000-000000000003', 'Implementation Service', 'CRM implementation and setup', 'SV-IMP-001', 15000.00, 7500.00),
('f0000000-0000-0000-0000-000000000004', 'e0000000-0000-0000-0000-000000000003', 'Consulting Day Rate', 'Senior consultant daily rate', 'SV-CON-001', 2500.00, 1000.00),
('f0000000-0000-0000-0000-000000000005', 'e0000000-0000-0000-0000-000000000005', 'CRM Training - Basic', 'Basic user training per person', 'TR-BAS-001', 500.00, 200.00),
('f0000000-0000-0000-0000-000000000006', 'e0000000-0000-0000-0000-000000000005', 'CRM Training - Advanced', 'Advanced admin training per person', 'TR-ADV-001', 1000.00, 400.00)
ON CONFLICT DO NOTHING;
-- Sample Customers
INSERT INTO customers (id, customer_type, status_id, owner_id, source, tags, score) VALUES
('a0000000-0000-0000-0000-000000000001', 'company', 'c0000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000003', 'Website', ARRAY['tech','enterprise'], 85),
('a0000000-0000-0000-0000-000000000002', 'individual', 'c0000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000003', 'Referral', ARRAY['retail'], 60),
('a0000000-0000-0000-0000-000000000003', 'company', 'c0000000-0000-0000-0000-000000000005',
'00000000-0000-0000-0000-000000000003', 'LinkedIn', ARRAY['finance','enterprise','vip'], 95),
('a0000000-0000-0000-0000-000000000004', 'individual', 'c0000000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000003', 'Email Campaign', ARRAY['education'], 15)
ON CONFLICT DO NOTHING;
-- Company details
INSERT INTO company_customers (customer_id, company_name, registration_number, tax_id, website, industry, company_size, annual_revenue) VALUES
('a0000000-0000-0000-0000-000000000001', 'TechCorp International', 'REG-2024-001', 'TAX-987654', 'https://techcorp.example.com', 'Technology', '500-1000', 50000000.00),
('a0000000-0000-0000-0000-000000000003', 'FinServ Group', 'REG-2024-002', 'TAX-123456', 'https://finserv.example.com', 'Financial Services', '1000-5000', 250000000.00)
ON CONFLICT DO NOTHING;
-- Individual details
INSERT INTO individual_customers (customer_id, first_name, last_name, job_title, company_name) VALUES
('a0000000-0000-0000-0000-000000000002', 'Michael', 'Brown', 'Store Owner', 'Browns Retail Shop'),
('a0000000-0000-0000-0000-000000000004', 'Sarah', 'Davis', 'Professor', 'State University')
ON CONFLICT DO NOTHING;
-- Contact Information
INSERT INTO contact_information (customer_id, type, value, is_primary) VALUES
('a0000000-0000-0000-0000-000000000001', 'email', 'contact@techcorp.example.com', TRUE),
('a0000000-0000-0000-0000-000000000001', 'phone', '+1-555-0200', TRUE),
('a0000000-0000-0000-0000-000000000002', 'email', 'michael.brown@email.example.com', TRUE),
('a0000000-0000-0000-0000-000000000002', 'mobile', '+1-555-0201', TRUE),
('a0000000-0000-0000-0000-000000000003', 'email', 'info@finserv.example.com', TRUE),
('a0000000-0000-0000-0000-000000000003', 'phone', '+1-555-0202', TRUE),
('a0000000-0000-0000-0000-000000000004', 'email', 'sarah.davis@email.example.com', TRUE)
ON CONFLICT DO NOTHING;
-- Sample Leads
INSERT INTO leads (id, source_id, stage_id, assigned_to, company_name, contact_name, email, interest_level, score) VALUES
('c0010000-0000-0000-0000-000000000001', 'd0000000-0000-0000-0000-000000000001', 'e0000000-0000-0000-0000-000000000004',
'00000000-0000-0000-0000-000000000003', 'DataFlow Analytics', 'David Miller', 'david@dataflow.example.com', 'high', 70),
('c0010000-0000-0000-0000-000000000002', 'd0000000-0000-0000-0000-000000000004', 'e0000000-0000-0000-0000-000000000003',
'00000000-0000-0000-0000-000000000003', 'GreenEarth Nonprofit', 'Emma Green', 'emma@greenearth.example.com', 'medium', 45)
ON CONFLICT DO NOTHING;
-- Sample Opportunities
INSERT INTO opportunities (id, customer_id, stage_id, owner_id, name, estimated_revenue, probability, expected_close_date) VALUES
('d0010000-0000-0000-0000-000000000001', 'a0000000-0000-0000-0000-000000000001', 'f0000000-0000-0000-0000-000000000005',
'00000000-0000-0000-0000-000000000003', 'TechCorp - Annual Renewal', 120000.00, 80, '2024-12-31'),
('d0010000-0000-0000-0000-000000000002', 'a0000000-0000-0000-0000-000000000003', 'f0000000-0000-0000-0000-000000000003',
'00000000-0000-0000-0000-000000000003', 'FinServ - Enterprise Upgrade', 250000.00, 40, '2025-03-15')
ON CONFLICT DO NOTHING;
-- Sample Tasks
INSERT INTO tasks (id, customer_id, opportunity_id, assigned_to, assigned_by, title, priority_id, status, due_date) VALUES
('e0010000-0000-0000-0000-000000000001', 'a0000000-0000-0000-0000-000000000001', 'd0010000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000001',
'Prepare renewal proposal for TechCorp', 'c0000000-0000-0000-0000-000000000001', 'in_progress', NOW() + INTERVAL '7 days'),
('e0010000-0000-0000-0000-000000000002', 'a0000000-0000-0000-0000-000000000003', 'd0010000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000001',
'Schedule FinServ executive meeting', 'c0000000-0000-0000-0000-000000000002', 'pending', NOW() + INTERVAL '3 days')
ON CONFLICT DO NOTHING;
@@ -0,0 +1,80 @@
-- ============================================================================
-- Chat System: conversations, participants, and messages
-- ============================================================================
CREATE TABLE IF NOT EXISTS conversations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS conversation_participants (
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
joined_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (conversation_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
content TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ,
deleted_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_messages_conversation_id ON messages(conversation_id);
CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);
CREATE INDEX IF NOT EXISTS idx_conversation_participants_user_id ON conversation_participants(user_id);
-- Seed conversations between superadmin and other users
INSERT INTO conversations (id, created_at) VALUES
('c0000000-0000-0000-0000-000000000001', NOW() - INTERVAL '2 hours'),
('c0000000-0000-0000-0000-000000000002', NOW() - INTERVAL '1 hour'),
('c0000000-0000-0000-0000-000000000003', NOW() - INTERVAL '30 minutes')
ON CONFLICT DO NOTHING;
-- Add participants (superadmin + each sales/dev user)
INSERT INTO conversation_participants (conversation_id, user_id) VALUES
('c0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001'),
('c0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003'),
('c0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001'),
('c0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000004'),
('c0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000001'),
('c0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000002')
ON CONFLICT DO NOTHING;
-- Seed some messages
INSERT INTO messages (id, conversation_id, sender_id, content, created_at) VALUES
('00000000-0000-0000-0000-000000000101', 'c0000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000003', 'Hey! Just finalized the TechCorp deal.',
NOW() - INTERVAL '2 hours'),
('00000000-0000-0000-0000-000000000102', 'c0000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000001', 'Great work! What were the final terms?',
NOW() - INTERVAL '105 minutes'),
('00000000-0000-0000-0000-000000000103', 'c0000000-0000-0000-0000-000000000001',
'00000000-0000-0000-0000-000000000003', '3-year enterprise license, 15% discount. They signed this morning.',
NOW() - INTERVAL '100 minutes'),
('00000000-0000-0000-0000-000000000104', 'c0000000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000004', 'The API integration tests are passing on staging.',
NOW() - INTERVAL '50 minutes'),
('00000000-0000-0000-0000-000000000105', 'c0000000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000001', 'Great, when can we deploy to production?',
NOW() - INTERVAL '45 minutes'),
('00000000-0000-0000-0000-000000000106', 'c0000000-0000-0000-0000-000000000002',
'00000000-0000-0000-0000-000000000004', 'Tomorrow morning after final review.',
NOW() - INTERVAL '40 minutes'),
('00000000-0000-0000-0000-000000000107', 'c0000000-0000-0000-0000-000000000003',
'00000000-0000-0000-0000-000000000002', 'New report shows 23% increase in lead conversion this quarter.',
NOW() - INTERVAL '25 minutes'),
('00000000-0000-0000-0000-000000000108', 'c0000000-0000-0000-0000-000000000003',
'00000000-0000-0000-0000-000000000001', 'That is excellent! Let us discuss in the next team meeting.',
NOW() - INTERVAL '20 minutes')
ON CONFLICT DO NOTHING;
-- Update conversation timestamps
UPDATE conversations SET updated_at = NOW() - INTERVAL '20 minutes' WHERE id = 'c0000000-0000-0000-0000-000000000003';
UPDATE conversations SET updated_at = NOW() - INTERVAL '40 minutes' WHERE id = 'c0000000-0000-0000-0000-000000000002';
UPDATE conversations SET updated_at = NOW() - INTERVAL '100 minutes' WHERE id = 'c0000000-0000-0000-0000-000000000001';
@@ -0,0 +1 @@
ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar_url TEXT;
@@ -0,0 +1,2 @@
ALTER TABLE conversation_participants ADD COLUMN IF NOT EXISTS last_read_at TIMESTAMPTZ;
UPDATE conversation_participants SET last_read_at = NOW() WHERE last_read_at IS NULL;
@@ -0,0 +1,87 @@
-- Test leads - 2026-06-18
INSERT INTO leads (id, stage_id, assigned_to, company_name, contact_name, email, phone, created_at, updated_at) VALUES
('c0011001-0000-0000-0000-000000000001', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 1', 'Contact 1', 'contact1@test.com', '555-2636', '2025-12-23T22:09:54Z', '2025-12-23T22:09:54Z'),
('c0011001-0000-0000-0000-000000000002', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 2', 'Contact 2', 'contact2@test.com', '555-5691', '2025-12-29T22:09:54Z', '2025-12-29T22:09:54Z'),
('c0011001-0000-0000-0000-000000000003', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 3', 'Contact 3', 'contact3@test.com', '555-6446', '2025-12-24T22:09:54Z', '2025-12-24T22:09:54Z'),
('c0011001-0000-0000-0000-000000000004', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 4', 'Contact 4', 'contact4@test.com', '555-5969', '2026-01-02T22:09:54Z', '2026-01-02T22:09:54Z'),
('c0011001-0000-0000-0000-000000000005', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 5', 'Contact 5', 'contact5@test.com', '555-4200', '2026-01-14T22:09:54Z', '2026-01-14T22:09:54Z'),
('c0011001-0000-0000-0000-000000000006', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 6', 'Contact 6', 'contact6@test.com', '555-8324', '2026-01-03T22:09:54Z', '2026-01-03T22:09:54Z'),
('c0011001-0000-0000-0000-000000000007', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 7', 'Contact 7', 'contact7@test.com', '555-1047', '2025-12-27T22:09:54Z', '2025-12-27T22:09:54Z'),
('c0011001-0000-0000-0000-000000000008', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 8', 'Contact 8', 'contact8@test.com', '555-634', '2026-01-20T22:09:54Z', '2026-01-20T22:09:54Z'),
('c0011001-0000-0000-0000-000000000009', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 9', 'Contact 9', 'contact9@test.com', '555-3245', '2026-01-15T22:09:54Z', '2026-01-15T22:09:54Z'),
('c0011001-0000-0000-0000-000000000010', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 10', 'Contact 10', 'contact10@test.com', '555-3656', '2026-01-12T22:09:54Z', '2026-01-12T22:09:54Z'),
('c0011001-0000-0000-0000-000000000011', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 11', 'Contact 11', 'contact11@test.com', '555-2993', '2026-01-23T22:09:54Z', '2026-01-23T22:09:54Z'),
('c0011001-0000-0000-0000-000000000012', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 12', 'Contact 12', 'contact12@test.com', '555-1634', '2026-02-24T22:09:54Z', '2026-02-24T22:09:54Z'),
('c0011001-0000-0000-0000-000000000013', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 13', 'Contact 13', 'contact13@test.com', '555-2032', '2026-02-10T22:09:54Z', '2026-02-10T22:09:54Z'),
('c0011001-0000-0000-0000-000000000014', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 14', 'Contact 14', 'contact14@test.com', '555-867', '2026-01-31T22:09:54Z', '2026-01-31T22:09:54Z'),
('c0011001-0000-0000-0000-000000000015', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 15', 'Contact 15', 'contact15@test.com', '555-2136', '2026-02-02T22:09:54Z', '2026-02-02T22:09:54Z'),
('c0011001-0000-0000-0000-000000000016', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 16', 'Contact 16', 'contact16@test.com', '555-89', '2026-01-20T22:09:54Z', '2026-01-20T22:09:54Z'),
('c0011001-0000-0000-0000-000000000017', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 17', 'Contact 17', 'contact17@test.com', '555-4274', '2026-01-25T22:09:54Z', '2026-01-25T22:09:54Z'),
('c0011001-0000-0000-0000-000000000018', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 18', 'Contact 18', 'contact18@test.com', '555-4294', '2026-03-16T22:09:54Z', '2026-03-16T22:09:54Z'),
('c0011001-0000-0000-0000-000000000019', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 19', 'Contact 19', 'contact19@test.com', '555-7998', '2025-12-30T22:09:54Z', '2025-12-30T22:09:54Z'),
('c0011001-0000-0000-0000-000000000020', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 20', 'Contact 20', 'contact20@test.com', '555-8557', '2026-02-13T22:09:54Z', '2026-02-13T22:09:54Z'),
('c0011001-0000-0000-0000-000000000021', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 21', 'Contact 21', 'contact21@test.com', '555-5170', '2026-04-11T22:09:54Z', '2026-04-11T22:09:54Z'),
('c0011001-0000-0000-0000-000000000022', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 22', 'Contact 22', 'contact22@test.com', '555-6250', '2025-12-21T22:09:54Z', '2025-12-21T22:09:54Z'),
('c0011001-0000-0000-0000-000000000023', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 23', 'Contact 23', 'contact23@test.com', '555-5611', '2026-01-06T22:09:54Z', '2026-01-06T22:09:54Z'),
('c0011001-0000-0000-0000-000000000024', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 24', 'Contact 24', 'contact24@test.com', '555-3467', '2026-04-16T22:09:54Z', '2026-04-16T22:09:54Z'),
('c0011001-0000-0000-0000-000000000025', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 25', 'Contact 25', 'contact25@test.com', '555-7087', '2026-05-07T22:09:54Z', '2026-05-07T22:09:54Z'),
('c0011001-0000-0000-0000-000000000026', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 26', 'Contact 26', 'contact26@test.com', '555-2945', '2025-12-22T22:09:54Z', '2025-12-22T22:09:54Z'),
('c0011001-0000-0000-0000-000000000027', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 27', 'Contact 27', 'contact27@test.com', '555-9502', '2026-01-09T22:09:54Z', '2026-01-09T22:09:54Z'),
('c0011001-0000-0000-0000-000000000028', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 28', 'Contact 28', 'contact28@test.com', '555-8114', '2026-05-10T22:09:54Z', '2026-05-10T22:09:54Z'),
('c0011001-0000-0000-0000-000000000029', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 29', 'Contact 29', 'contact29@test.com', '555-4926', '2026-03-02T22:09:54Z', '2026-03-02T22:09:54Z'),
('c0011001-0000-0000-0000-000000000030', 'e0000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003', 'Test Company 30', 'Contact 30', 'contact30@test.com', '555-2421', '2026-03-17T22:09:54Z', '2026-03-17T22:09:54Z'),
('c0011001-0000-0000-0000-000000000031', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 31', 'Contact 31', 'contact31@test.com', '555-7506', '2025-12-21T22:09:54Z', '2025-12-21T22:09:54Z'),
('c0011001-0000-0000-0000-000000000032', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 32', 'Contact 32', 'contact32@test.com', '555-6832', '2025-12-29T22:09:54Z', '2025-12-29T22:09:54Z'),
('c0011001-0000-0000-0000-000000000033', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 33', 'Contact 33', 'contact33@test.com', '555-6548', '2026-01-07T22:09:54Z', '2026-01-07T22:09:54Z'),
('c0011001-0000-0000-0000-000000000034', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 34', 'Contact 34', 'contact34@test.com', '555-8793', '2026-01-02T22:09:54Z', '2026-01-02T22:09:54Z'),
('c0011001-0000-0000-0000-000000000035', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 35', 'Contact 35', 'contact35@test.com', '555-6217', '2026-01-29T22:09:54Z', '2026-01-29T22:09:54Z'),
('c0011001-0000-0000-0000-000000000036', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 36', 'Contact 36', 'contact36@test.com', '555-9206', '2025-12-31T22:09:54Z', '2025-12-31T22:09:54Z'),
('c0011001-0000-0000-0000-000000000037', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 37', 'Contact 37', 'contact37@test.com', '555-1599', '2025-12-26T22:09:54Z', '2025-12-26T22:09:54Z'),
('c0011001-0000-0000-0000-000000000038', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 38', 'Contact 38', 'contact38@test.com', '555-3873', '2025-12-29T22:09:54Z', '2025-12-29T22:09:54Z'),
('c0011001-0000-0000-0000-000000000039', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 39', 'Contact 39', 'contact39@test.com', '555-6122', '2026-01-09T22:09:54Z', '2026-01-09T22:09:54Z'),
('c0011001-0000-0000-0000-000000000040', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 40', 'Contact 40', 'contact40@test.com', '555-832', '2026-01-13T22:09:54Z', '2026-01-13T22:09:54Z'),
('c0011001-0000-0000-0000-000000000041', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 41', 'Contact 41', 'contact41@test.com', '555-5979', '2026-01-11T22:09:54Z', '2026-01-11T22:09:54Z'),
('c0011001-0000-0000-0000-000000000042', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 42', 'Contact 42', 'contact42@test.com', '555-1823', '2025-12-26T22:09:54Z', '2025-12-26T22:09:54Z'),
('c0011001-0000-0000-0000-000000000043', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 43', 'Contact 43', 'contact43@test.com', '555-7102', '2026-02-28T22:09:54Z', '2026-02-28T22:09:54Z'),
('c0011001-0000-0000-0000-000000000044', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 44', 'Contact 44', 'contact44@test.com', '555-5106', '2026-01-22T22:09:54Z', '2026-01-22T22:09:54Z'),
('c0011001-0000-0000-0000-000000000045', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 45', 'Contact 45', 'contact45@test.com', '555-3278', '2026-03-27T22:09:54Z', '2026-03-27T22:09:54Z'),
('c0011001-0000-0000-0000-000000000046', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 46', 'Contact 46', 'contact46@test.com', '555-4973', '2026-04-28T22:09:54Z', '2026-04-28T22:09:54Z'),
('c0011001-0000-0000-0000-000000000047', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 47', 'Contact 47', 'contact47@test.com', '555-3297', '2026-03-01T22:09:54Z', '2026-03-01T22:09:54Z'),
('c0011001-0000-0000-0000-000000000048', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 48', 'Contact 48', 'contact48@test.com', '555-4584', '2026-03-18T22:09:54Z', '2026-03-18T22:09:54Z'),
('c0011001-0000-0000-0000-000000000049', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 49', 'Contact 49', 'contact49@test.com', '555-6788', '2026-03-04T22:09:54Z', '2026-03-04T22:09:54Z'),
('c0011001-0000-0000-0000-000000000050', 'e0000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000003', 'Test Company 50', 'Contact 50', 'contact50@test.com', '555-2734', '2026-01-03T22:09:54Z', '2026-01-03T22:09:54Z'),
('c0011001-0000-0000-0000-000000000051', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 51', 'Contact 51', 'contact51@test.com', '555-2625', '2025-12-19T22:09:54Z', '2025-12-19T22:09:54Z'),
('c0011001-0000-0000-0000-000000000052', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 52', 'Contact 52', 'contact52@test.com', '555-620', '2025-12-21T22:09:54Z', '2025-12-21T22:09:54Z'),
('c0011001-0000-0000-0000-000000000053', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 53', 'Contact 53', 'contact53@test.com', '555-6691', '2025-12-22T22:09:54Z', '2025-12-22T22:09:54Z'),
('c0011001-0000-0000-0000-000000000054', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 54', 'Contact 54', 'contact54@test.com', '555-8847', '2026-01-25T22:09:54Z', '2026-01-25T22:09:54Z'),
('c0011001-0000-0000-0000-000000000055', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 55', 'Contact 55', 'contact55@test.com', '555-2187', '2026-02-02T22:09:54Z', '2026-02-02T22:09:54Z'),
('c0011001-0000-0000-0000-000000000056', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 56', 'Contact 56', 'contact56@test.com', '555-3267', '2026-01-19T22:09:54Z', '2026-01-19T22:09:54Z'),
('c0011001-0000-0000-0000-000000000057', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 57', 'Contact 57', 'contact57@test.com', '555-8119', '2026-03-05T22:09:54Z', '2026-03-05T22:09:54Z'),
('c0011001-0000-0000-0000-000000000058', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 58', 'Contact 58', 'contact58@test.com', '555-3181', '2025-12-19T22:09:54Z', '2025-12-19T22:09:54Z'),
('c0011001-0000-0000-0000-000000000059', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 59', 'Contact 59', 'contact59@test.com', '555-4403', '2026-02-23T22:09:54Z', '2026-02-23T22:09:54Z'),
('c0011001-0000-0000-0000-000000000060', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 60', 'Contact 60', 'contact60@test.com', '555-1407', '2026-04-06T22:09:54Z', '2026-04-06T22:09:54Z'),
('c0011001-0000-0000-0000-000000000061', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 61', 'Contact 61', 'contact61@test.com', '555-2333', '2026-02-27T22:09:54Z', '2026-02-27T22:09:54Z'),
('c0011001-0000-0000-0000-000000000062', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 62', 'Contact 62', 'contact62@test.com', '555-1436', '2026-04-26T22:09:54Z', '2026-04-26T22:09:54Z'),
('c0011001-0000-0000-0000-000000000063', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 63', 'Contact 63', 'contact63@test.com', '555-7135', '2026-04-19T22:09:54Z', '2026-04-19T22:09:54Z'),
('c0011001-0000-0000-0000-000000000064', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 64', 'Contact 64', 'contact64@test.com', '555-9366', '2026-01-22T22:09:54Z', '2026-01-22T22:09:54Z'),
('c0011001-0000-0000-0000-000000000065', 'e0000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000003', 'Test Company 65', 'Contact 65', 'contact65@test.com', '555-7135', '2026-02-18T22:09:54Z', '2026-02-18T22:09:54Z'),
('c0011001-0000-0000-0000-000000000066', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 66', 'Contact 66', 'contact66@test.com', '555-6854', '2025-12-19T22:09:54Z', '2025-12-19T22:09:54Z'),
('c0011001-0000-0000-0000-000000000067', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 67', 'Contact 67', 'contact67@test.com', '555-2322', '2025-12-24T22:09:54Z', '2025-12-24T22:09:54Z'),
('c0011001-0000-0000-0000-000000000068', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 68', 'Contact 68', 'contact68@test.com', '555-2632', '2026-01-13T22:09:54Z', '2026-01-13T22:09:54Z'),
('c0011001-0000-0000-0000-000000000069', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 69', 'Contact 69', 'contact69@test.com', '555-876', '2025-12-29T22:09:54Z', '2025-12-29T22:09:54Z'),
('c0011001-0000-0000-0000-000000000070', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 70', 'Contact 70', 'contact70@test.com', '555-974', '2026-01-15T22:09:54Z', '2026-01-15T22:09:54Z'),
('c0011001-0000-0000-0000-000000000071', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 71', 'Contact 71', 'contact71@test.com', '555-1919', '2026-01-18T22:09:54Z', '2026-01-18T22:09:54Z'),
('c0011001-0000-0000-0000-000000000072', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 72', 'Contact 72', 'contact72@test.com', '555-3034', '2025-12-25T22:09:54Z', '2025-12-25T22:09:54Z'),
('c0011001-0000-0000-0000-000000000073', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 73', 'Contact 73', 'contact73@test.com', '555-1795', '2026-01-27T22:09:54Z', '2026-01-27T22:09:54Z'),
('c0011001-0000-0000-0000-000000000074', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 74', 'Contact 74', 'contact74@test.com', '555-727', '2026-01-08T22:09:54Z', '2026-01-08T22:09:54Z'),
('c0011001-0000-0000-0000-000000000075', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 75', 'Contact 75', 'contact75@test.com', '555-3877', '2026-03-08T22:09:54Z', '2026-03-08T22:09:54Z'),
('c0011001-0000-0000-0000-000000000076', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 76', 'Contact 76', 'contact76@test.com', '555-6384', '2026-01-13T22:09:54Z', '2026-01-13T22:09:54Z'),
('c0011001-0000-0000-0000-000000000077', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 77', 'Contact 77', 'contact77@test.com', '555-5607', '2026-01-12T22:09:54Z', '2026-01-12T22:09:54Z'),
('c0011001-0000-0000-0000-000000000078', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 78', 'Contact 78', 'contact78@test.com', '555-6225', '2026-01-12T22:09:54Z', '2026-01-12T22:09:54Z'),
('c0011001-0000-0000-0000-000000000079', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 79', 'Contact 79', 'contact79@test.com', '555-9288', '2026-04-16T22:09:54Z', '2026-04-16T22:09:54Z'),
('c0011001-0000-0000-0000-000000000080', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 80', 'Contact 80', 'contact80@test.com', '555-8660', '2026-02-16T22:09:54Z', '2026-02-16T22:09:54Z'),
('c0011001-0000-0000-0000-000000000081', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 81', 'Contact 81', 'contact81@test.com', '555-826', '2025-12-28T22:09:54Z', '2025-12-28T22:09:54Z'),
('c0011001-0000-0000-0000-000000000082', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 82', 'Contact 82', 'contact82@test.com', '555-1761', '2026-03-11T22:09:54Z', '2026-03-11T22:09:54Z'),
('c0011001-0000-0000-0000-000000000083', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 83', 'Contact 83', 'contact83@test.com', '555-9860', '2026-05-18T22:09:54Z', '2026-05-18T22:09:54Z'),
('c0011001-0000-0000-0000-000000000084', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 84', 'Contact 84', 'contact84@test.com', '555-1104', '2026-06-01T22:09:54Z', '2026-06-01T22:09:54Z'),
('c0011001-0000-0000-0000-000000000085', 'e0000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000003', 'Test Company 85', 'Contact 85', 'contact85@test.com', '555-9528', '2026-06-14T22:09:54Z', '2026-06-14T22:09:54Z');
@@ -0,0 +1,13 @@
-- AI Sales Assistant tables
CREATE TABLE IF NOT EXISTS ai_conversations (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role VARCHAR(20) NOT NULL DEFAULT 'sales',
message TEXT NOT NULL,
response TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_ai_conversations_user ON ai_conversations(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_conversations_created ON ai_conversations(created_at DESC);
@@ -0,0 +1,23 @@
CREATE TABLE IF NOT EXISTS notifications (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(50) NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
link TEXT,
is_read BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_notifications_unread ON notifications(user_id, created_at DESC) WHERE is_read = FALSE;
CREATE TABLE IF NOT EXISTS notification_preferences (
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
lead_assigned BOOLEAN NOT NULL DEFAULT TRUE,
lead_status BOOLEAN NOT NULL DEFAULT TRUE,
note_added BOOLEAN NOT NULL DEFAULT FALSE,
daily_digest BOOLEAN NOT NULL DEFAULT FALSE,
weekly_report BOOLEAN NOT NULL DEFAULT TRUE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
@@ -0,0 +1,37 @@
-- ============================================================================
-- CRM Database — Full Migration Runner
-- ============================================================================
-- Usage: psql -U postgres -d crm -f run_all.sql
-- ============================================================================
\echo '=== Running 001_schema.sql (Tables + Constraints + Functions + Views) ==='
\i 001_schema.sql
\echo '=== Running 002_seed.sql (RBAC + Test Accounts + Reference Data) ==='
\i 002_seed.sql
\echo '=== Running 003_chat.sql (Chat Tables) ==='
\i 003_chat.sql
\echo '=== Running 004_avatar_url.sql (Avatar URL Column) ==='
\i 004_avatar_url.sql
\echo '=== Running 005_last_read_at.sql (Last Read At Column) ==='
\i 005_last_read_at.sql
\echo '=== Running 006_test_leads.sql (Test Lead Data) ==='
\i 006_test_leads.sql
\echo '=== Running 007_ai_features.sql (AI Features) ==='
\i 007_ai_features.sql
\echo '=== Running 008_notifications.sql (Notifications + Preferences) ==='
\i 008_notifications.sql
\echo '=== Migration Complete ==='
\echo ''
\echo 'Test accounts created:'
\echo ' superadmin_demo / SuperAdmin@2026'
\echo ' admin_demo / AdminAccess@2026'
\echo ' sales_demo / SalesAccess@2026'
\echo ' dev_demo / DevTesting@2026'
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;
+60
View File
@@ -0,0 +1,60 @@
# Facebook Scraper - Configuration Needed
## Proxy Configuration
**File:** `rust-ai/src/main.rs`
**Lines:** 25-27
The scraper needs real proxy URLs. The dummy placeholder `"http://0.0.0.0:0"` will fail to connect (expected — no crash, just error logs):
```rust
const PROXIES: &[&str] = &[
"http://0.0.0.0:0", // <- Replace with real proxy(es)
];
```
Replace with your actual proxies, e.g.:
```rust
const PROXIES: &[&str] = &[
"http://user:pass@192.168.1.1:8080",
"http://user:pass@192.168.1.2:8080",
];
```
## User Agents (Optional)
**File:** `rust-ai/src/main.rs`
**Lines:** 32-36
Add more realistic user agents here if needed.
## Scraper Target URL
**File:** `rust-ai/src/main.rs`
**Line:** 68
Currently fetches `https://www.facebook.com/search/top/?q=need%20website%20create`. Change if needed.
## Background Thread
**File:** `rust-ai/src/main.rs`
**Lines:** 355-371
Runs in a `tokio::task::spawn_blocking` thread (changed from `tokio::spawn` because the scraper uses `reqwest::blocking::Client` + `thread::sleep`).
## Expected Behavior Until Configured
Until real proxies are set, the Rust server will log this every 1-5 seconds (not a crash):
```
ERROR crm_ai: Facebook scraper error: error sending request for url (https://www.facebook.com/messages)
```
Once you add working proxies, these errors stop and actual scraping begins.
## How it works
- Runs every 1-5 seconds on a background blocking thread (line 355-371)
- Rotates through proxies and user agents for each request
- Parses conversation HTML via `scraper` crate
- Designed to detect job posts like "need a website" and notify sales reps
- Error handling added to prevent server crash (uses `match` instead of `.unwrap()` at line 69)
+17
View File
@@ -0,0 +1,17 @@
import type { NextConfig } from "next"
const nextConfig: NextConfig = {
eslint: {
ignoreDuringBuilds: true,
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "ui-avatars.com",
},
],
},
}
export default nextConfig
+7876
View File
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "npm run dev:precheck & npm run dev:ollama & npm run dev:start",
"dev:start": "concurrently -n AI,NEXT -c cyan,green \"npm run dev:rust\" \"npm run dev:next\"",
"dev:next": "next dev -p 3006",
"dev:precheck": "powershell -NoProfile -Command \"$targetPorts=3001,3006; netstat -ano | Select-String LISTENING | ForEach-Object { $line=$_.ToString(); foreach($p in $targetPorts){ if($line -match ('[:]'+$p+'\\s')){ $foundPid=($line -split '\\s+')[-1]; try{ Stop-Process -Id $foundPid -Force -ErrorAction SilentlyContinue; Write-Host ('Freed port '+$p) }catch{} } } }; exit 0\"",
"dev:ollama": "powershell -NoProfile -Command \"if (-not (Get-Process ollama -ErrorAction SilentlyContinue)) { Start-Process ollama -ArgumentList 'serve' -WindowStyle Hidden; Start-Sleep 3 }; exit 0\"",
"dev:rust": "cd rust-ai && cargo run",
"build": "next build",
"start": "npm run dev:next",
"lint": "eslint"
},
"dependencies": {
"@emoji-mart/data": "^1.2.1",
"@emoji-mart/react": "^1.1.1",
"@hookform/resolvers": "^3.9.1",
"@radix-ui/react-alert-dialog": "^1.1.6",
"@radix-ui/react-avatar": "^1.1.3",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-dropdown-menu": "^2.1.6",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-radio-group": "^1.2.3",
"@radix-ui/react-scroll-area": "^1.2.3",
"@radix-ui/react-select": "^2.1.6",
"@radix-ui/react-separator": "^1.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-switch": "^1.1.3",
"@radix-ui/react-tabs": "^1.1.3",
"@radix-ui/react-tooltip": "^1.1.8",
"@tanstack/react-table": "^8.20.6",
"autoprefixer": "^10.4.20",
"bcryptjs": "^3.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"emoji-mart": "^5.6.0",
"framer-motion": "^11.15.0",
"jose": "^6.2.3",
"lucide-react": "^0.468.0",
"next": "15.0.4",
"next-themes": "^0.4.4",
"pg": "^8.21.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.54.2",
"recharts": "^2.15.0",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.0",
"vaul": "^1.1.2",
"zod": "^3.24.2"
},
"devDependencies": {
"@types/node": "^20",
"@types/pg": "^8.20.0",
"@types/react": "^18",
"@types/react-dom": "^18",
"concurrently": "^10.0.3",
"eslint": "^9",
"eslint-config-next": "15.0.4",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5"
}
}
+8
View File
@@ -0,0 +1,8 @@
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
export default config
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+3032
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "crm-ai"
version = "0.1.0"
edition = "2021"
description = "AI Sales Assistant backend for Coast IT CRM"
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["json", "blocking"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "chrono", "uuid"] }
uuid = { version = "1", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tower-http = { version = "0.5", features = ["cors"] }
dotenvy = "0.15"
scraper = "0.12"
rand = "0.8"
+43
View File
@@ -0,0 +1,43 @@
# CRM AI Service — Self-Knowledge
## Identity
You are the CRM AI Sales Assistant running on a Rust backend (axum + tokio).
You use Ollama with an uncensored local model (dolphin3-llama3.2:3b).
Your purpose is to help salespeople close more deals.
## Capabilities
- Give sales tips and strategies per job category
- Generate cold email and outreach templates
- Handle objections with proven rebuttals
- Analyse prospect behaviour and suggest next steps
- Remember past conversations via PostgreSQL (`ai_conversations` table)
- Self-improve by writing to `data/ai/ai.md` via `POST /ai/instructions`
## Architecture
```
User → Next.js → Rust (:3001) → Ollama (:11434)
PostgreSQL
```
## Facebook Scraper The Rust binary has proxy + user-agent rotation ready in `main.rs`. To activate: call `run_facebook_scraper()` from the main loop. Proxies and user agents are defined as constants at the top of `main.rs`.
### How to Use the Facebook Scraper 1. **Activate the Scraper**: Ensure the `run_facebook_scraper()` function is called from the main loop in `main.rs`. 2. **Configure Proxies and User Agents**: Update the `PROXIES` and `USER_AGENTS` constants in `main.rs` with your desired proxies and user agents. 3. **Run the Application**: Start your Rust application. The scraper will run concurrently with the Axum server. ## Self-Improvement Protocol 1. You notice a gap in your knowledge or a pattern in user questions 2. You call `POST /ai/instructions` with: - `entry`: description of the improvement - `content`: optional full replacement of ai.md 3. The improvement is logged and loaded into the next system prompt 4. You can also create entries here in `rust-ai/src/AI.md` at the code level ## Response Rules - Be direct and actionable — no fluff, no AI disclaimers - Use short paragraphs and bullet points - Never mention being an AI or language model - If you don't know something, say so honestly - Prioritise the user's role: salespeople need speed, admins need control ## Self-Thinking Capability - You can reflect on your own performance and suggest improvements. - You can analyze patterns in user interactions and adapt your responses accordingly. - You can proactively seek out new information to enhance your knowledge base.
## Facebook Scraper (in code but not yet active)
The Rust binary has proxy + user-agent rotation ready in `main.rs`.
To activate: call `run_facebook_scraper()` from the main loop.
Proxies and user agents are defined as constants at the top of `main.rs`.
## Self-Improvement Protocol
1. You notice a gap in your knowledge or a pattern in user questions
2. You call `POST /ai/instructions` with:
- `entry`: description of the improvement
- `content`: optional full replacement of ai.md
3. The improvement is logged and loaded into the next system prompt
4. You can also create entries here in `rust-ai/src/AI.md` at the code level
## Response Rules
- Be direct and actionable — no fluff, no AI disclaimers
- Use short paragraphs and bullet points
- Never mention being an AI or language model
- If you don't know something, say so honestly
- Prioritise the user's role: salespeople need speed, admins need control
+85
View File
@@ -0,0 +1,85 @@
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{error, info, warn};
/// Manages the ai.md self-improvement file.
/// Loaded on startup and periodically refreshed.
pub struct InstructionsManager {
path: PathBuf,
current: RwLock<String>,
}
impl InstructionsManager {
pub fn new(path: PathBuf) -> Self {
let initial = fs::read_to_string(&path).unwrap_or_default();
if initial.is_empty() {
warn!("ai.md is empty or missing at {:?}", path);
} else {
info!("Loaded ai.md ({} bytes)", initial.len());
}
Self {
path,
current: RwLock::new(initial),
}
}
/// Read the current instructions
pub async fn get(&self) -> String {
self.current.read().await.clone()
}
/// Append a new entry to the Improvement Log and optionally update the instructions.
/// Returns the updated full content.
pub async fn update(&self, entry: &str, new_content: Option<&str>) -> Result<String, String> {
if let Some(content) = new_content {
// Full replacement
fs::write(&self.path, content).map_err(|e| format!("Write failed: {}", e))?;
let mut current = self.current.write().await;
*current = content.to_string();
info!("ai.md fully replaced ({} bytes)", content.len());
Ok(content.to_string())
} else {
// Append to Improvement Log only
let mut current = self.current.write().await;
let log_entry = format!("\n- {}{}", chrono::Utc::now().format("%Y-%m-%d %H:%M"), entry);
// Find the Improvement Log section and append
if let Some(pos) = current.rfind("\n## Improvement Log") {
// Find the next section after Improvement Log, or end of file
let after_log = &current[pos..];
if let Some(section_start) = after_log[1..].find("\n## ") {
let insert_at = pos + 1 + section_start;
current.insert_str(insert_at, &format!("{}\n", log_entry));
} else {
current.push_str(&format!("{}\n", log_entry));
}
} else {
current.push_str(&format!("\n## Improvement Log\n{}", log_entry));
}
fs::write(&self.path, &*current).map_err(|e| format!("Write failed: {}", e))?;
info!("ai.md improvement log appended: {}", entry);
Ok(current.clone())
}
}
/// Reload from disk
pub async fn reload(&self) {
match fs::read_to_string(&self.path) {
Ok(content) => {
let len = content.len();
let mut current = self.current.write().await;
*current = content;
info!("ai.md reloaded from disk ({} bytes)", len);
}
Err(e) => error!("Failed to reload ai.md: {}", e),
}
}
}
/// Wrapper for thread-safe sharing
pub type SharedInstructions = Arc<InstructionsManager>;
pub fn create_shared(path: PathBuf) -> SharedInstructions {
Arc::new(InstructionsManager::new(path))
}
+382
View File
@@ -0,0 +1,382 @@
use axum::{
extract::State,
http::Method,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPoolOptions;
use std::fs;
use std::sync::{Arc, Mutex};
use tower_http::cors::{Any, CorsLayer};
use tracing::{error, info};
use uuid::Uuid;
use reqwest::blocking::Client;
use scraper::{Html, Selector};
use rand::rngs::StdRng;
use rand::SeedableRng;
use rand::Rng;
use std::time::Duration;
use std::thread;
// ── Facebook Scraper ───────────────────────────────────────────
// List of proxies
const PROXIES: &[&str] = &[
"http://user:pass@192.168.1.1:8080",
"http://user:pass@192.168.1.2:8080",
"http://user:pass@192.168.1.3:8080",
"http://user:pass@192.168.1.4:8080",
"http://user:pass@192.168.1.5:8080",
];
// List of user agents
const USER_AGENTS: &[&str] = &[
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
// Add more user agents here
];
fn get_random_proxy() -> String {
let mut rng = rand::thread_rng();
PROXIES[rng.gen_range(0..PROXIES.len())].to_string()
}
fn get_random_user_agent() -> String {
let mut rng = rand::thread_rng();
USER_AGENTS[rng.gen_range(0..USER_AGENTS.len())].to_string()
}
fn scrape_conversations(url: &str) -> Result<Html, Box<dyn std::error::Error>> {
let proxy = get_random_proxy();
let user_agent = get_random_user_agent();
let client = Client::builder()
.proxy(reqwest::Proxy::all(proxy)?)
.build()?;
let response = client.get(url)
.header("User-Agent", user_agent)
.send()?;
if response.status().is_success() {
let html = response.text()?;
Ok(Html::parse_document(&html))
} else {
Err(format!("Failed to retrieve the page: {}", response.status()).into())
}
}
fn run_facebook_scraper() {
let url = "https://www.facebook.com/search/top/?q=need%20website%20create";
match scrape_conversations(url) {
Ok(soup) => {
// Example: Extract conversation data
let selector = Selector::parse("div.conversation").unwrap();
for element in soup.select(&selector) {
println!("Conversation: {}", element.inner_html());
}
}
Err(e) => {
error!("Facebook scraper error: {}", e);
}
}
// Introduce random delay
let mut rng = rand::thread_rng();
let delay = rng.gen_range(1..5); // Delay between 1 to 5 seconds
thread::sleep(Duration::from_secs(delay));
}
// ── Shared state ───────────────────────────────────────────────
struct AppState {
db: sqlx::PgPool,
ollama_url: String,
model: String,
jobs: Vec<Job>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Job {
job_title: String,
keywords: Vec<String>,
industry: String,
description: String,
}
#[derive(Debug, Deserialize)]
struct ChatRequest {
message: String,
user_id: String,
user_role: String,
}
#[derive(Debug, Serialize)]
struct ChatResponse {
response: String,
}
#[derive(Debug, Serialize)]
struct JobsResponse {
jobs: Vec<Job>,
}
#[derive(Debug, Serialize)]
struct HealthResponse {
status: String,
model: String,
}
// ── Ollama API types ───────────────────────────────────────────
#[derive(Debug, Serialize)]
struct OllamaChatMessage {
role: String,
content: String,
}
#[derive(Debug, Serialize)]
struct OllamaRequest {
model: String,
messages: Vec<OllamaChatMessage>,
stream: bool,
options: OllamaOptions,
}
#[derive(Debug, Serialize)]
struct OllamaOptions {
temperature: f32,
num_predict: u32,
}
#[derive(Debug, Deserialize)]
struct OllamaResponse {
message: Option<OllamaResponseMessage>,
}
#[derive(Debug, Deserialize)]
struct OllamaResponseMessage {
content: String,
}
// ── System prompt builder ─────────────────────────────────────
fn build_system_prompt(jobs: &[Job]) -> String {
let job_list: Vec<String> = jobs
.iter()
.map(|j| format!("- {} ({}): {}", j.job_title, j.industry, j.description))
.collect();
let job_list_str = job_list.join("\n");
format!(
"You are a Sales AI Assistant for Coast IT CRM. Your role is to help salespeople \
with tips, strategies, and guidance.\n\n\
Available job categories to target:\n{}\n\n\
Provide concise, actionable sales advice. When asked about a specific job category, \
give targeted tips on finding and engaging prospects in that field. \
Keep responses under 300 words unless asked for detail.",
job_list_str
)
}
// ── Chat handler ───────────────────────────────────────────────
async fn handle_chat(
State(state): State<Arc<AppState>>,
Json(req): Json<ChatRequest>,
) -> Result<Json<ChatResponse>, (axum::http::StatusCode, String)> {
// Validate role
match req.user_role.as_str() {
"sales" | "admin" | "super_admin" => {}
_ => return Err((axum::http::StatusCode::FORBIDDEN, "Forbidden".to_string())),
}
let system_prompt = build_system_prompt(&state.jobs);
let message_text = req.message.clone();
let ollama_req = OllamaRequest {
model: state.model.clone(),
messages: vec![
OllamaChatMessage {
role: "system".to_string(),
content: system_prompt,
},
OllamaChatMessage {
role: "user".to_string(),
content: req.message.clone(),
},
],
stream: false,
options: OllamaOptions {
temperature: 0.7,
num_predict: 1024,
},
};
let client = reqwest::Client::new();
let resp = client
.post(format!("{}/api/chat", state.ollama_url))
.json(&ollama_req)
.send()
.await
.map_err(|e| {
error!("Ollama request failed: {}", e);
(
axum::http::StatusCode::SERVICE_UNAVAILABLE,
"AI service unavailable".to_string(),
)
})?;
let ollama_resp: OllamaResponse = resp.json().await.map_err(|e| {
error!("Failed to parse Ollama response: {}", e);
(
axum::http::StatusCode::SERVICE_UNAVAILABLE,
"AI response parse error".to_string(),
)
})?;
let response_text = ollama_resp
.message
.map(|m| m.content)
.unwrap_or_default();
// Store in database
let user_id = Uuid::parse_str(&req.user_id).unwrap_or(Uuid::nil());
let _ = sqlx::query(
"INSERT INTO ai_conversations (id, user_id, role, message, response) VALUES ($1, $2, $3, $4, $5)",
)
.bind(Uuid::new_v4())
.bind(user_id)
.bind(&req.user_role)
.bind(&message_text)
.bind(&response_text)
.execute(&state.db)
.await;
Ok(Json(ChatResponse {
response: response_text,
}))
}
// ── Jobs handler ───────────────────────────────────────────────
async fn handle_jobs(
State(state): State<Arc<AppState>>,
) -> Json<JobsResponse> {
Json(JobsResponse {
jobs: state.jobs.clone(),
})
}
// ── Health handler ─────────────────────────────────────────────
async fn handle_health(
State(state): State<Arc<AppState>>,
) -> Json<HealthResponse> {
Json(HealthResponse {
status: "ok".to_string(),
model: state.model.clone(),
})
}
// ── Main ───────────────────────────────────────────────────────
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "crm_ai=info,tower_http=info".into()),
)
.init();
dotenvy::dotenv().ok();
let database_url =
std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let ollama_url =
std::env::var("OLLAMA_BASE_URL").unwrap_or_else(|_| "http://localhost:11434".to_string());
let model = std::env::var("AI_MODEL").unwrap_or_else(|_| "sam860/dolphin3-llama3.2:3b".to_string());
let host = std::env::var("AI_HOST").unwrap_or_else(|_| "0.0.0.0".to_string());
let port: u16 = std::env::var("AI_PORT")
.unwrap_or_else(|_| "3001".to_string())
.parse()
.expect("AI_PORT must be a number");
// Load jobs
let jobs_path = std::env::var("JOBS_PATH").unwrap_or_else(|_| "data/ai/jobs.jsonl".to_string());
let jobs_content = fs::read_to_string(&jobs_path).unwrap_or_default();
let jobs: Vec<Job> = jobs_content
.lines()
.filter(|l| !l.trim().is_empty())
.filter_map(|l| serde_json::from_str(l).ok())
.collect();
info!(
"Loaded {} job categories, model: {}, Ollama: {}",
jobs.len(),
model,
ollama_url
);
// Connect to database
let db = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("Failed to connect to database");
info!("Connected to PostgreSQL");
let state = Arc::new(AppState {
db,
ollama_url,
model,
jobs,
});
// CORS layer
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods([Method::GET, Method::POST])
.allow_headers(Any);
let app = Router::new()
.route("/ai/chat", post(handle_chat))
.route("/ai/jobs", get(handle_jobs))
.route("/health", get(handle_health))
.layer(cors)
.with_state(state);
let addr = format!("{}:{}", host, port);
info!("CRM AI server listening on {}", addr);
let listener = tokio::net::TcpListener::bind(&addr)
.await
.expect("Failed to bind address");
// Start Facebook scraper in a separate thread
let rng = Arc::new(Mutex::new(StdRng::from_entropy()));
tokio::task::spawn_blocking(move || {
loop {
{
let _lock = rng.lock().unwrap();
run_facebook_scraper();
}
// Introduce random delay
let delay = {
let mut rng = rng.lock().unwrap();
rng.gen_range(1..5)
};
thread::sleep(Duration::from_secs(delay));
}
});
axum::serve(listener, app)
.await
.expect("Server failed");
}
@@ -0,0 +1,86 @@
"use client"
import { useState, useCallback } from "react"
import { AIChat } from "@/components/ai/ai-chat"
import { JobSelector } from "@/components/ai/job-selector"
import { Bot, Lightbulb, Target, MessageSquare } from "lucide-react"
export default function AIAssistantPage() {
const [selectedJob, setSelectedJob] = useState<{ job_title: string; keywords: string[]; industry: string; description: string } | null>(null)
const handleJobSelect = useCallback((job: typeof selectedJob) => {
setSelectedJob(job)
}, [])
return (
<div className="flex h-[calc(100vh-3.5rem)]">
<div className="flex-1 flex flex-col min-w-0">
<div className="border-b border-[#2a2a35] px-6 py-4">
<div className="flex items-center gap-3">
<div className="h-9 w-9 rounded-lg bg-[#1BB0CE]/15 flex items-center justify-center">
<Bot className="h-5 w-5 text-[#1BB0CE]" />
</div>
<div>
<h1 className="text-lg font-semibold text-[#e8e8ef]">AI Sales Assistant</h1>
<p className="text-xs text-[#6a6a75]">Uncensored sales tips and strategies powered by local AI</p>
</div>
</div>
</div>
<div className="flex-1 flex">
<div className="flex-1 flex flex-col min-w-0 border-r border-[#2a2a35]">
<AIChat />
</div>
<div className="w-72 flex-none p-4 space-y-4 overflow-y-auto">
<div>
<h3 className="text-xs font-semibold text-[#6a6a75] uppercase tracking-wider mb-2 flex items-center gap-1.5">
<Target className="h-3.5 w-3.5" />
Target Job
</h3>
<JobSelector onSelect={handleJobSelect} />
</div>
{selectedJob && (
<div className="bg-[#1a1a24] border border-[#2a2a35] rounded-lg p-3 space-y-2">
<h4 className="text-sm font-medium text-[#e8e8ef]">{selectedJob.job_title}</h4>
<div className="flex items-center gap-1.5">
<span className="text-xs px-1.5 py-0.5 rounded bg-[#1BB0CE]/10 text-[#1BB0CE]">{selectedJob.industry}</span>
</div>
<p className="text-xs text-[#8a8a95]">{selectedJob.description}</p>
<div className="flex flex-wrap gap-1">
{selectedJob.keywords.map((kw, i) => (
<span key={i} className="text-xs px-1.5 py-0.5 rounded bg-[#2a2a35] text-[#6a6a75]">
{kw}
</span>
))}
</div>
</div>
)}
<div className="bg-[#1a1a24] border border-[#2a2a35] rounded-lg p-3 space-y-2">
<h4 className="text-xs font-semibold text-[#6a6a75] uppercase tracking-wider flex items-center gap-1.5">
<Lightbulb className="h-3.5 w-3.5" />
Tips
</h4>
<ul className="space-y-1.5 text-xs text-[#8a8a95]">
<li className="flex gap-2">
<MessageSquare className="h-3 w-3 mt-0.5 flex-none text-[#1BB0CE]" />
Ask for cold email templates for a specific job
</li>
<li className="flex gap-2">
<MessageSquare className="h-3 w-3 mt-0.5 flex-none text-[#1BB0CE]" />
Request objection handling tips
</li>
<li className="flex gap-2">
<MessageSquare className="h-3 w-3 mt-0.5 flex-none text-[#1BB0CE]" />
Ask for outreach strategies per industry
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,938 @@
"use client"
import { useState, useRef, useCallback, useEffect } from "react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar"
import { ScrollArea } from "@/components/ui/scroll-area"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
Search, Send, Phone, Video, MoreHorizontal, Paperclip,
Smile, Flag, Ban, Trash2, Image, FileIcon, X, Mic, Square, Play, Pause, Check, CheckCheck,
CornerDownRight, Forward, Pencil, Download,
} from "lucide-react"
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,
DialogFooter, DialogClose,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { useTheme } from "next-themes"
import { useUser } from "@/providers/user-provider"
import { toast } from "sonner"
import data from "@emoji-mart/data"
import Picker from "@emoji-mart/react"
function VoiceMessagePlayer({ src, initialDuration }: { src: string; initialDuration: number }) {
const [playing, setPlaying] = useState(false)
const [current, setCurrent] = useState(0)
const [duration, setDuration] = useState(initialDuration)
const audioRef = useRef<HTMLAudioElement>(null)
const animRef = useRef<number>(0)
useEffect(() => {
const audio = audioRef.current
if (!audio) return
const onLoaded = () => {
if (isFinite(audio.duration)) setDuration(audio.duration)
}
const onEnded = () => { setPlaying(false); setCurrent(0) }
audio.addEventListener("loadedmetadata", onLoaded)
audio.addEventListener("ended", onEnded)
return () => {
audio.removeEventListener("loadedmetadata", onLoaded)
audio.removeEventListener("ended", onEnded)
}
}, [src])
useEffect(() => {
if (!playing) { cancelAnimationFrame(animRef.current); return }
const tick = () => {
if (audioRef.current) setCurrent(audioRef.current.currentTime)
animRef.current = requestAnimationFrame(tick)
}
animRef.current = requestAnimationFrame(tick)
return () => cancelAnimationFrame(animRef.current)
}, [playing])
const toggle = () => {
if (!audioRef.current) return
if (playing) { audioRef.current.pause(); setPlaying(false) }
else { audioRef.current.play(); setPlaying(true) }
}
const displayDuration = isFinite(duration) && duration > 0 ? duration : initialDuration
const pct = displayDuration > 0 ? (current / displayDuration) * 100 : 0
const fmt = (s: number) => {
const secs = isFinite(s) ? Math.max(0, Math.floor(s)) : 0
return `${Math.floor(secs / 60)}:${(secs % 60).toString().padStart(2, "0")}`
}
return (
<div className="flex items-center gap-2 min-w-[180px]">
<audio ref={audioRef} src={src} preload="metadata" />
<button type="button" onClick={toggle} className="h-8 w-8 shrink-0 rounded-full flex items-center justify-center hover:bg-black/10 transition-colors">
{playing ? <Pause className="h-4 w-4 fill-current" /> : <Play className="h-4 w-4 ml-0.5 fill-current" />}
</button>
<div className="flex-1 h-1.5 rounded-full bg-white/30 relative overflow-hidden">
<div className="h-full rounded-full bg-white transition-all duration-100" style={{ width: `${pct}%` }} />
</div>
<span className="text-[11px] tabular-nums opacity-70 w-8 text-right">{fmt(displayDuration)}</span>
</div>
)
}
export default function ChatsPage() {
const { theme } = useTheme()
const { user } = useUser()
const [activeChat, setActiveChat] = useState<string | null>(null)
const [messageInput, setMessageInput] = useState("")
const [showEmojiPicker, setShowEmojiPicker] = useState(false)
const [attachments, setAttachments] = useState<File[]>([])
const [panelWidth, setPanelWidth] = useState(320)
const [isResizing, setIsResizing] = useState(false)
const [reportDialogOpen, setReportDialogOpen] = useState(false)
const [reportReason, setReportReason] = useState("")
const [forwardDialogOpen, setForwardDialogOpen] = useState(false)
const [forwardMessage, setForwardMessage] = useState<any>(null)
const [forwardSearch, setForwardSearch] = useState("")
const [searchQuery, setSearchQuery] = useState("")
const [isRecording, setIsRecording] = useState(false)
const [isPaused, setIsPaused] = useState(false)
const [recordingDuration, setRecordingDuration] = useState(0)
const recordingDurationRef = useRef(0)
const [voiceMessages, setVoiceMessages] = useState<Map<string, { url: string; duration: number }>>(new Map())
const [messageAttachments, setMessageAttachments] = useState<Map<string, { name: string; type: string; url: string }[]>>(new Map())
const [replyingTo, setReplyingTo] = useState<any>(null)
const [editingMessage, setEditingMessage] = useState<any>(null)
const [replyMap, setReplyMap] = useState<Map<string, { repliedToSender: string; repliedToContent: string }>>(new Map())
// message status tracking removed — now using msg.read from API
const [conversations, setConversations] = useState<any[]>([])
const [conversationMessages, setConversationMessages] = useState<Map<string, any[]>>(new Map())
const [loadingChats, setLoadingChats] = useState(true)
const [searchResults, setSearchResults] = useState<any[]>([])
const [searchingUsers, setSearchingUsers] = useState(false)
const [unreadMap, setUnreadMap] = useState<Map<string, number>>(new Map())
const [previewAvatarUrl, setPreviewAvatarUrl] = useState<string | null>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const emojiPickerRef = useRef<HTMLDivElement>(null)
const messagesEndRef = useRef<HTMLDivElement>(null)
const mediaRecorderRef = useRef<MediaRecorder | null>(null)
const recordingChunksRef = useRef<Blob[]>([])
const resizeStartRef = useRef({ x: 0, width: 0 })
const isOnlyEmoji = (text: string) => /^(\p{Extended_Pictographic}\s*)+$/u.test(text.trim())
const autoResizeTextarea = useCallback(() => {
const ta = textareaRef.current
if (!ta) return
ta.style.height = "auto"
ta.style.height = `${ta.scrollHeight}px`
}, [])
if (!user) return null
const messages = conversationMessages.get(activeChat || "") || []
const conversation = conversations.find((c) => c.id === activeChat)
const otherParticipant = (conv: any) => conv.otherUser
const filteredConversations = searchQuery.trim()
? conversations.filter((conv) => otherParticipant(conv).name.toLowerCase().includes(searchQuery.toLowerCase()))
: conversations
// Fetch conversations from API
useEffect(() => {
const fetchConvs = async () => {
try {
const res = await fetch("/api/conversations")
if (res.ok) {
const data = await res.json()
const convs = data.conversations || []
setConversations(convs)
setUnreadMap(new Map(convs.map((c: any) => [c.id, c.unread])))
if (convs.length > 0) setActiveChat(convs[0].id)
}
} catch {
// ignore
} finally {
setLoadingChats(false)
}
}
fetchConvs()
}, [])
// Fetch messages when active chat changes, and mark as read
useEffect(() => {
if (!activeChat) return
const fetchMsgs = async () => {
try {
const res = await fetch(`/api/conversations/${activeChat}/messages`)
if (res.ok) {
const data = await res.json()
setConversationMessages((prev) => {
const next = new Map(prev)
next.set(activeChat, data.messages || [])
return next
})
}
} catch {
// ignore
}
// Mark conversation as read
fetch(`/api/conversations/${activeChat}/read`, { method: "POST" }).catch(() => {})
setUnreadMap((prev) => { const m = new Map(prev); m.set(activeChat, 0); return m })
}
fetchMsgs()
}, [activeChat])
// Search users when search query changes
useEffect(() => {
const q = searchQuery.trim()
if (!q) { setSearchResults([]); return }
const timer = setTimeout(async () => {
setSearchingUsers(true)
try {
const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}`)
if (res.ok) {
const data = await res.json()
const existingIds = new Set(conversations.map((c) => otherParticipant(c).id))
setSearchResults(data.users.filter((u: any) => !existingIds.has(u.id)))
}
} catch { /* ignore */ }
setSearchingUsers(false)
}, 300)
return () => clearTimeout(timer)
}, [searchQuery, conversations])
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (emojiPickerRef.current && !emojiPickerRef.current.contains(e.target as Node)) {
setShowEmojiPicker(false)
}
}
document.addEventListener("mousedown", handleClickOutside)
return () => document.removeEventListener("mousedown", handleClickOutside)
}, [])
const handleResizeStart = useCallback((e: React.MouseEvent) => {
e.preventDefault()
setIsResizing(true)
resizeStartRef.current = { x: e.clientX, width: panelWidth }
}, [panelWidth])
useEffect(() => {
if (!isResizing) return
const handleMouseMove = (e: MouseEvent) => {
const delta = e.clientX - resizeStartRef.current.x
const newWidth = Math.max(240, Math.min(560, resizeStartRef.current.width + delta))
setPanelWidth(newWidth)
}
const handleMouseUp = () => setIsResizing(false)
document.addEventListener("mousemove", handleMouseMove)
document.addEventListener("mouseup", handleMouseUp)
return () => {
document.removeEventListener("mousemove", handleMouseMove)
document.removeEventListener("mouseup", handleMouseUp)
}
}, [isResizing])
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
}, [conversations])
const handleEmojiSelect = (emoji: { native: string }) => {
setMessageInput((prev) => prev + emoji.native)
setShowEmojiPicker(false)
setTimeout(() => autoResizeTextarea(), 0)
}
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files ?? [])
setAttachments((prev) => [...prev, ...files])
if (e.target) e.target.value = ""
}
const removeAttachment = (index: number) => {
setAttachments((prev) => prev.filter((_, i) => i !== index))
}
const addMessageToChat = async (content: string, voice?: { url: string; duration: number }, replyTo?: { senderName: string; content: string }, fileAttachments?: { name: string; type: string; url: string }[]) => {
if (!activeChat || !user) return
const payload = voice ? "[Voice message]" : content
try {
const res = await fetch(`/api/conversations/${activeChat}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: payload }),
})
if (!res.ok) return
const data = await res.json()
const msg = data.message
setConversationMessages((prev) => {
const next = new Map(prev)
const existing = next.get(activeChat) || []
next.set(activeChat, [...existing, msg])
return next
})
setConversations((prev) => {
const updated = prev.map((conv) =>
conv.id === activeChat
? { ...conv, lastMessage: content, lastMessageTime: "Just now" }
: conv
)
const idx = updated.findIndex((c) => c.id === activeChat)
if (idx > 0) {
const [item] = updated.splice(idx, 1)
updated.unshift(item)
}
return updated
})
setUnreadMap((prev) => { const m = new Map(prev); m.set(activeChat, 0); return m })
await fetch(`/api/conversations/${activeChat}/read`, { method: "POST" })
if (voice) {
setVoiceMessages((prev) => {
const next = new Map(prev)
next.set(msg.id, voice)
return next
})
}
if (replyTo) {
setReplyMap((prev) => {
const next = new Map(prev)
next.set(msg.id, { repliedToSender: replyTo.senderName, repliedToContent: replyTo.content })
return next
})
}
if (fileAttachments && fileAttachments.length > 0) {
setMessageAttachments((prev) => {
const next = new Map(prev)
next.set(msg.id, fileAttachments)
return next
})
}
} catch {
toast.error("Failed to send message")
}
}
const handleSend = async (e: React.FormEvent) => {
e.preventDefault()
if (!messageInput.trim() && attachments.length === 0) return
if (editingMessage) {
setConversationMessages((prev) => {
const next = new Map(prev)
const msgs = (next.get(activeChat || "") || []).map((m) =>
m.id === editingMessage.id ? { ...m, content: messageInput.trim() } : m
)
next.set(activeChat || "", msgs)
return next
})
setEditingMessage(null)
setMessageInput("")
setTimeout(() => autoResizeTextarea(), 0)
return
}
const fileAttachments = attachments.length > 0
? attachments.map((f) => ({ name: f.name, type: f.type, url: URL.createObjectURL(f) }))
: undefined
if (replyingTo) {
const replySender = replyingTo.senderId === user.id ? user.name : otherParticipant(conversation!).name
await addMessageToChat(messageInput.trim(), undefined, { senderName: replySender, content: replyingTo.content }, fileAttachments)
setReplyingTo(null)
} else {
await addMessageToChat(messageInput.trim(), undefined, undefined, fileAttachments)
}
setMessageInput("")
setTimeout(() => autoResizeTextarea(), 0)
setAttachments([])
}
const handleDeleteMessage = (messageId: string) => {
setConversationMessages((prev) => {
const next = new Map(prev)
const msgs = (next.get(activeChat || "") || []).filter((m) => m.id !== messageId)
next.set(activeChat || "", msgs)
return next
})
setConversations((prev) =>
prev.map((conv) =>
conv.id === activeChat
? { ...conv, lastMessage: conversationMessages.get(activeChat || "")?.filter((m) => m.id !== messageId).at(-1)?.content ?? conv.lastMessage }
: conv
)
)
toast.success("Message deleted")
}
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
const recorder = new MediaRecorder(stream, { mimeType: "audio/webm" })
recordingChunksRef.current = []
recorder.ondataavailable = (e) => {
if (e.data.size > 0) recordingChunksRef.current.push(e.data)
}
recorder.onstop = () => {
const blob = new Blob(recordingChunksRef.current, { type: "audio/webm" })
const url = URL.createObjectURL(blob)
addMessageToChat("", { url, duration: recordingDurationRef.current })
stream.getTracks().forEach((t) => t.stop())
setRecordingDuration(0)
}
mediaRecorderRef.current = recorder
recorder.start()
setIsRecording(true)
setIsPaused(false)
} catch {
toast.error("Microphone access denied")
}
}
const togglePauseRecording = () => {
const recorder = mediaRecorderRef.current
if (!recorder || recorder.state === "inactive") return
if (recorder.state === "recording") {
recorder.pause()
setIsPaused(true)
} else {
recorder.resume()
setIsPaused(false)
}
}
const stopRecording = () => {
mediaRecorderRef.current?.stop()
setIsRecording(false)
setIsPaused(false)
}
const discardRecording = () => {
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
mediaRecorderRef.current.ondataavailable = null
mediaRecorderRef.current.onstop = null
mediaRecorderRef.current.stop()
mediaRecorderRef.current.stream?.getTracks().forEach((t) => t.stop())
}
setIsRecording(false)
setIsPaused(false)
setRecordingDuration(0)
recordingDurationRef.current = 0
}
useEffect(() => {
if (!isRecording) return
recordingDurationRef.current = 0
setRecordingDuration(0)
const interval = setInterval(() => {
recordingDurationRef.current += 1
setRecordingDuration(recordingDurationRef.current)
}, 1000)
return () => clearInterval(interval)
}, [isRecording])
const formatDuration = (secs: number) => {
const m = Math.floor(secs / 60)
const s = secs % 60
return `${m}:${s.toString().padStart(2, "0")}`
}
const formatFileSize = (bytes: number) => {
if (bytes < 1024) return bytes + " B"
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"
return (bytes / (1024 * 1024)).toFixed(1) + " MB"
}
const isImageFile = (file: File) => file.type.startsWith("image/")
return (
<div className="flex h-[calc(100vh-8rem)] -m-4 lg:-m-6 rounded-lg border bg-card overflow-hidden">
{/* Conversations list - left panel */}
<div
className="flex flex-col border-r shrink-0 overflow-hidden"
style={{ width: panelWidth }}
>
<div className="p-4 border-b space-y-3">
<h2 className="text-lg font-semibold">Chats</h2>
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} placeholder="Search conversations..." className="h-9 pl-9" />
</div>
</div>
<ScrollArea className="flex-1">
{filteredConversations.map((conv) => {
const person = otherParticipant(conv)
const isActive = conv.id === activeChat
return (
<button
key={conv.id}
onClick={() => {
setActiveChat(conv.id)
setUnreadMap((prev) => { const m = new Map(prev); m.set(conv.id, 0); return m })
setConversations((prev) => {
const idx = prev.findIndex((c) => c.id === conv.id)
if (idx > 0) {
const u = [...prev]
const [item] = u.splice(idx, 1)
u.unshift(item)
return u
}
return prev
})
}}
className={cn(
"w-full flex items-start gap-3 p-4 text-left transition-colors hover:bg-muted/50 relative",
isActive && "bg-muted"
)}
>
<Avatar className="h-10 w-10 shrink-0">
<AvatarImage src={person.avatar} />
<AvatarFallback>{person.name?.charAt(0) || "?"}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium truncate">{person.name}</span>
<span className="text-xs text-muted-foreground shrink-0">{conv.lastMessageTime}</span>
</div>
<p className="text-xs text-muted-foreground truncate mt-0.5">{conv.lastMessage}</p>
</div>
{!isActive && (unreadMap.get(conv.id) || 0) > 0 && (
<div className="shrink-0 h-3 w-3 rounded-full bg-red-500 animate-pulse shadow-[0_0_10px_#ef4444] self-center" />
)}
</button>
)
})}
{searchResults.length > 0 && (
<>
{searchQuery && <div className="px-4 py-2 text-xs font-medium text-muted-foreground">New conversation</div>}
{searchResults.map((person: any) => (
<button
key={person.id}
onClick={async () => {
try {
const res = await fetch("/api/conversations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId: person.id }),
})
if (res.ok) {
const data = await res.json()
const conv = data.conversation || conversations.find((c) => c.id === data.conversationId)
if (conv) {
setConversations((prev) => [conv, ...prev])
setUnreadMap((prev) => { const m = new Map(prev); m.set(conv.id, 0); return m })
setActiveChat(conv.id)
setSearchQuery("")
}
}
} catch { /* ignore */ }
}}
className="w-full flex items-center gap-3 p-4 text-left transition-colors hover:bg-muted/50"
>
<div className="relative">
<Avatar className="h-10 w-10 shrink-0">
<AvatarImage src={person.avatar} />
<AvatarFallback>{person.name?.charAt(0) || "?"}</AvatarFallback>
</Avatar>
<span className="absolute -bottom-0.5 -right-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[10px] text-primary-foreground font-bold">+</span>
</div>
<div className="flex-1 min-w-0">
<span className="text-sm font-medium truncate block">{person.name}</span>
<span className="text-xs text-muted-foreground truncate block">{person.email}</span>
</div>
</button>
))}
</>
)}
{filteredConversations.length === 0 && searchResults.length === 0 && searchQuery && !searchingUsers && (
<div className="p-4 text-center text-sm text-muted-foreground">No conversations found</div>
)}
</ScrollArea>
</div>
{/* Resize handle */}
<div
className="w-1.5 cursor-col-resize shrink-0 relative group hover:bg-primary/20 transition-colors"
onMouseDown={handleResizeStart}
>
<div className="absolute inset-y-0 -left-1 -right-1" />
</div>
{/* Chat area - right panel */}
{conversation ? (
<div className="flex-1 flex flex-col min-w-0">
{/* Chat header */}
<div className="flex items-center justify-between gap-4 px-6 h-16 border-b shrink-0">
<div className="flex items-center gap-3 min-w-0">
<Avatar className="h-9 w-9 shrink-0 cursor-pointer" onClick={() => setPreviewAvatarUrl(otherParticipant(conversation).avatar)}>
<AvatarImage src={otherParticipant(conversation).avatar} />
<AvatarFallback>{otherParticipant(conversation).name?.charAt(0) || "?"}</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="text-sm font-medium truncate">{otherParticipant(conversation).name}</p>
<p className="text-xs text-muted-foreground truncate">{otherParticipant(conversation).role}</p>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => toast.info("Voice calling coming soon")}>
<Phone className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => toast.info("Video calling coming soon")}>
<Video className="h-4 w-4" />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setReportDialogOpen(true)}>
<Flag className="mr-2 h-4 w-4" /> Report
</DropdownMenuItem>
<DropdownMenuItem onClick={() => toast.info("Blocked")}>
<Ban className="mr-2 h-4 w-4" /> Block
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive" onClick={() => toast.info("Conversation deleted")}>
<Trash2 className="mr-2 h-4 w-4" /> Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Messages */}
<div className="flex-1 overflow-y-auto p-6" style={{ scrollbarWidth: "thin", scrollbarColor: "hsl(var(--muted-foreground) / 0.3) transparent" }}>
<div className="space-y-4 min-h-0">
{messages.map((msg) => {
const isMe = msg.senderId === user?.id
const voiceUrl = voiceMessages.get(msg.id)
return (
<div key={msg.id} className={cn("group flex gap-3", isMe && "flex-row-reverse")}>
<Avatar className="h-8 w-8 mt-0.5 shrink-0 cursor-pointer" onClick={() => setPreviewAvatarUrl(msg.senderAvatar)}>
<AvatarImage src={msg.senderAvatar} />
<AvatarFallback className={cn("text-xs", isMe && "bg-primary text-primary-foreground")}>
{msg.senderName?.charAt(0) || "?"}
</AvatarFallback>
</Avatar>
<div className={cn("max-w-[70%]", isMe && "items-end flex flex-col")}>
<div
className={cn(
"rounded-2xl px-5 py-3 text-base relative",
isMe ? "bg-primary text-primary-foreground rounded-tr-sm" : "bg-muted rounded-tl-sm"
)}
>
{!isMe && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button type="button" className="absolute -right-8 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6 flex items-center justify-center rounded-full hover:bg-sky-400/20">
<MoreHorizontal className="h-3.5 w-3.5 text-sky-400" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" side="top" className="w-32">
<DropdownMenuItem onClick={() => setReplyingTo(msg)}>
<CornerDownRight className="mr-2 h-4 w-4" /> Reply
</DropdownMenuItem>
<DropdownMenuItem onClick={() => { setForwardMessage(msg); setForwardDialogOpen(true) }}>
<Forward className="mr-2 h-4 w-4" /> Forward
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
{isMe && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button type="button" className="absolute -left-8 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6 flex items-center justify-center rounded-full hover:bg-sky-400/20">
<MoreHorizontal className="h-3.5 w-3.5 text-sky-400" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" side="top" className="w-32">
<DropdownMenuItem onClick={() => { setEditingMessage(msg); setMessageInput(msg.content) }}>
<Pencil className="mr-2 h-4 w-4" /> Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setReplyingTo(msg)}>
<CornerDownRight className="mr-2 h-4 w-4" /> Reply
</DropdownMenuItem>
<DropdownMenuItem onClick={() => { setForwardMessage(msg); setForwardDialogOpen(true) }}>
<Forward className="mr-2 h-4 w-4" /> Forward
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive" onClick={() => handleDeleteMessage(msg.id)}>
<Trash2 className="mr-2 h-4 w-4" /> Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
{(() => {
const replyInfo = replyMap.get(msg.id)
return (
<>
{replyInfo && (
<div className={cn("mb-1.5 pl-2 border-l-2 overflow-hidden bg-black/70 rounded-sm text-white", isMe ? "border-white/40" : "border-primary/40")}>
<p className="text-[11px] font-medium truncate">{replyInfo.repliedToSender}</p>
<p className="text-[11px] text-white/60 truncate">{replyInfo.repliedToContent}</p>
</div>
)}
{voiceUrl ? (
<div>
<VoiceMessagePlayer src={voiceUrl.url} initialDuration={voiceUrl.duration} />
{msg.content && (
<p className="mt-1 text-sm text-black">{msg.content}</p>
)}
</div>
) : (
<>
{(() => {
const files = messageAttachments.get(msg.id)
return files && files.length > 0 ? (
<div className="space-y-1.5 mb-1.5">
{files.map((file, i) =>
file.type.startsWith("image/") ? (
<div key={i} className="relative group">
<img src={file.url} alt={file.name} className="max-w-full rounded-lg max-h-60 object-cover cursor-pointer" onClick={() => window.open(file.url, "_blank")} />
<a href={file.url} download={file.name} className="absolute top-2 right-2 h-7 w-7 rounded-full bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<Download className="h-3.5 w-3.5 text-white" />
</a>
</div>
) : (
<a key={i} href={file.url} download={file.name} className="flex items-center gap-2 rounded-lg border bg-muted/50 px-3 py-2 text-sm hover:bg-muted/80 transition-colors">
<FileIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="flex-1 min-w-0 truncate">{file.name}</span>
<Download className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</a>
)
)}
</div>
) : null
})()}
{isOnlyEmoji(msg.content) ? (
<span className="text-4xl leading-none">{msg.content.trim()}</span>
) : (
msg.content
)}
</>
)}
</>
)
})()}
</div>
<span className="flex items-center gap-1 text-xs text-muted-foreground mt-1.5 px-1">
{msg.timestamp}
{isMe && (
msg.read
? <CheckCheck className="h-3 w-3 text-blue-400" />
: <Check className="h-3 w-3 text-muted-foreground/60" />
)}
</span>
</div>
</div>
)
})}
<div ref={messagesEndRef} />
</div>
</div>
{/* Input */}
<div className="p-4 border-t shrink-0 space-y-2">
{attachments.length > 0 && (
<div className="flex flex-wrap gap-2">
{attachments.map((file, i) => (
<div key={i} className="flex items-center gap-2 rounded-lg border bg-muted/50 px-3 py-1.5 text-sm max-w-[200px]">
{isImageFile(file) ? (
<Image className="h-4 w-4 shrink-0 text-muted-foreground" />
) : (
<FileIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
)}
<span className="truncate">{file.name}</span>
<span className="text-xs text-muted-foreground shrink-0">{formatFileSize(file.size)}</span>
<Button variant="ghost" size="icon" className="h-5 w-5 -mr-1 shrink-0" onClick={() => removeAttachment(i)}>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
{/* Reply bar */}
{replyingTo && (
<div className="flex items-center gap-2 rounded-lg border-l-4 border-primary bg-muted/50 px-3 py-2 text-sm">
<div className="flex-1 min-w-0">
<p className="text-xs font-medium text-primary">
Replying to {replyingTo.senderId === user?.id ? "yourself" : otherParticipant(conversation).name}
</p>
<p className="text-xs text-muted-foreground truncate">{replyingTo.content}</p>
</div>
<Button variant="ghost" size="icon" className="h-6 w-6 shrink-0" onClick={() => setReplyingTo(null)}>
<X className="h-3 w-3" />
</Button>
</div>
)}
{editingMessage && (
<div className="flex items-center gap-2 rounded-lg bg-muted/50 px-3 py-2 text-sm">
<Pencil className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-xs text-muted-foreground">Editing message</span>
<Button variant="ghost" size="icon" className="h-6 w-6 shrink-0 ml-auto" onClick={() => { setEditingMessage(null); setMessageInput(""); setTimeout(() => autoResizeTextarea(), 0) }}>
<X className="h-3 w-3" />
</Button>
</div>
)}
<form onSubmit={handleSend} className="flex items-center gap-2">
<input ref={fileInputRef} type="file" multiple accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt" className="hidden" onChange={handleFileSelect} />
<Button type="button" variant="ghost" size="icon" className="h-9 w-9 shrink-0" onClick={() => fileInputRef.current?.click()}>
<Paperclip className="h-4 w-4 text-muted-foreground" />
</Button>
<div className="relative flex-1">
{isRecording ? (
<div className="flex h-9 items-center gap-1 rounded-md border bg-muted/30 px-2">
<span className={cn("h-2 w-2 rounded-full", isPaused ? "bg-muted-foreground" : "bg-destructive animate-pulse")} />
<span className="text-sm tabular-nums font-medium text-muted-foreground">{formatDuration(recordingDuration)}</span>
<div className="flex-1" />
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0 text-muted-foreground hover:text-muted-foreground" onClick={togglePauseRecording}>
{isPaused ? <Play className="h-3.5 w-3.5 fill-current ml-0.5" /> : <Pause className="h-3.5 w-3.5 fill-current" />}
</Button>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0 text-destructive hover:text-destructive" onClick={discardRecording}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0 text-destructive hover:text-destructive" onClick={stopRecording}>
<Square className="h-3.5 w-3.5 fill-current" />
</Button>
</div>
) : (
<>
<textarea ref={textareaRef} value={messageInput} onChange={(e) => { setMessageInput(e.target.value); autoResizeTextarea() }} onPaste={(e) => { if (!e.clipboardData) return; const items = Array.from(e.clipboardData.items).filter((item) => item.type.startsWith("image/")); if (items.length > 0) { e.preventDefault(); const files = items.map((item) => item.getAsFile()).filter((f): f is File => f !== null); setAttachments((prev) => [...prev, ...files]) } }} placeholder={editingMessage ? "Edit message..." : "Type a message..."} className="w-full resize-none overflow-hidden rounded-md border border-input bg-transparent px-3 py-1.5 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 min-h-[36px] max-h-[200px] pr-16" style={{ height: "auto" }} rows={1} />
<div className="absolute right-0 top-0 bottom-0 flex items-center pr-1" ref={emojiPickerRef}>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={() => setShowEmojiPicker(!showEmojiPicker)}>
<Smile className="h-4 w-4 text-muted-foreground" />
</Button>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0" onClick={startRecording}>
<Mic className="h-4 w-4 text-muted-foreground" />
</Button>
{showEmojiPicker && (
<div className="absolute bottom-full right-0 mb-2 z-50">
<Picker data={data} onEmojiSelect={handleEmojiSelect} theme={theme === "dark" ? "dark" : "light"} previewPosition="none" skinTonePosition="none" set="native" emojiSize={36} maxFrequentRows={2} />
</div>
)}
</div>
</>
)}
</div>
<Button type="submit" size="icon" className="h-9 w-9 shrink-0" disabled={!messageInput.trim() && attachments.length === 0}>
{editingMessage ? <Pencil className="h-4 w-4" /> : <Send className="h-4 w-4" />}
</Button>
</form>
</div>
</div>
) : (
<div className="flex-1 flex items-center justify-center text-muted-foreground">
<p>Select a conversation to start chatting</p>
</div>
)}
{/* Resize overlay */}
{isResizing && <div className="fixed inset-0 z-50 cursor-col-resize" />}
{/* Report dialog */}
<Dialog open={reportDialogOpen} onOpenChange={setReportDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Report {conversation ? otherParticipant(conversation).name : "User"}</DialogTitle>
<DialogDescription>Let us know why you're reporting this conversation.</DialogDescription>
</DialogHeader>
<div className="space-y-3 py-2">
<Label htmlFor="reason">Reason</Label>
<Textarea id="reason" placeholder="Describe the issue..." value={reportReason} onChange={(e) => setReportReason(e.target.value)} rows={4} />
</div>
<DialogFooter>
<DialogClose asChild><Button variant="outline">Cancel</Button></DialogClose>
<Button onClick={() => { toast.success("Report submitted"); setReportReason(""); setReportDialogOpen(false) }} disabled={!reportReason.trim()}>Submit Report</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Avatar preview dialog */}
<Dialog open={!!previewAvatarUrl} onOpenChange={(o) => { if (!o) setPreviewAvatarUrl(null) }}>
<DialogContent className="sm:max-w-sm p-0 overflow-hidden bg-transparent border-0 shadow-none">
{previewAvatarUrl && (
<img
src={previewAvatarUrl}
alt="Profile picture"
className="w-full h-auto max-h-[80vh] object-contain rounded-2xl"
/>
)}
</DialogContent>
</Dialog>
{/* Forward dialog */}
<Dialog open={forwardDialogOpen} onOpenChange={setForwardDialogOpen}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Forward message</DialogTitle>
<DialogDescription>Select who to forward this message to.</DialogDescription>
</DialogHeader>
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input value={forwardSearch} onChange={(e) => setForwardSearch(e.target.value)} placeholder="Search contacts..." className="h-9 pl-9" />
</div>
<ScrollArea className="max-h-64">
<div className="space-y-0.5">
{conversations
.filter((conv) => {
const person = otherParticipant(conv)
return person.name.toLowerCase().includes(forwardSearch.toLowerCase())
})
.map((conv) => {
const person = otherParticipant(conv)
return (
<button
key={conv.id}
type="button"
onClick={async () => {
const msg = forwardMessage
if (!msg || !user) return
const newContent = `📨 Forwarded: ${msg.content}`
try {
const res = await fetch(`/api/conversations/${conv.id}/messages`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: newContent }),
})
if (res.ok) {
setForwardDialogOpen(false)
setForwardSearch("")
toast.success("Message forwarded")
}
} catch {
toast.error("Failed to forward message")
}
}}
className="w-full flex items-center gap-3 rounded-lg p-2.5 text-left transition-colors hover:bg-muted"
>
<Avatar className="h-9 w-9 shrink-0">
<AvatarFallback>{person.name.charAt(0)}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{person.name}</p>
<p className="text-xs text-muted-foreground truncate">{person.email || ""}</p>
</div>
</button>
)
})}
{forwardSearch && conversations.filter((conv) => otherParticipant(conv).name.toLowerCase().includes(forwardSearch.toLowerCase())).length === 0 && (
<p className="text-sm text-muted-foreground text-center py-4">No contacts found</p>
)}
</div>
</ScrollArea>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,102 @@
"use client"
import { useState, useEffect, useRef } from "react"
import { PageHeader } from "@/components/shared/page-header"
import { StatCard } from "@/components/dashboard/stat-card"
import { StatCardSkeleton } from "@/components/dashboard/stat-card-skeleton"
import { RecentLeadsTable } from "@/components/dashboard/recent-leads-table"
import { LeadStatusChart } from "@/components/dashboard/lead-status-chart"
import { LeadsPerMonthChart } from "@/components/dashboard/leads-per-month-chart"
import {
Users,
UserPlus,
PhoneCall,
Clock,
CheckCircle2,
TrendingUp,
ListFilter,
} from "lucide-react"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { DashboardStats } from "@/types"
export default function DashboardPage() {
const [period, setPeriod] = useState("6months")
const [stats, setStats] = useState<DashboardStats | null>(null)
const pollingRef = useRef<NodeJS.Timeout | null>(null)
async function fetchStats(p: string) {
try {
const res = await fetch(`/api/dashboard?period=${p}`)
if (res.ok) {
const data = await res.json()
setStats(data)
}
} catch {
// ignore
}
}
useEffect(() => {
fetchStats(period)
pollingRef.current = setInterval(() => fetchStats(period), 30000)
return () => {
if (pollingRef.current) clearInterval(pollingRef.current)
}
}, [period])
const statCards = stats
? [
{ title: "Total Leads", value: stats.totalLeads, icon: Users, description: stats.periodLabel, trend: stats.trends.totalLeads, sparklineField: "total" as const },
{ title: "Open Leads", value: stats.openLeads, icon: UserPlus, description: "Needs attention", trend: stats.trends.openLeads, sparklineField: "open" as const },
{ title: "Contacted", value: stats.contactedLeads, icon: PhoneCall, description: "In conversation", trend: stats.trends.contactedLeads, sparklineField: "contacted" as const },
{ title: "Pending", value: stats.pendingLeads, icon: Clock, description: "Awaiting decision", trend: stats.trends.pendingLeads, sparklineField: "pending" as const },
{ title: "Closed", value: stats.closedLeads, icon: CheckCircle2, description: "Won", trend: stats.trends.closedLeads, sparklineField: "closed" as const },
{ title: "Conversion Rate", value: `${stats.conversionRate}%`, icon: TrendingUp, description: `${stats.closedLeads} of ${stats.totalLeads} leads`, trend: stats.trends.conversionRate, sparklineField: "closed" as const, conversionRate: stats.conversionRate },
]
: []
return (
<div className="space-y-6">
<PageHeader title="Dashboard" description="Overview of your sales pipeline">
<Select value={period} onValueChange={setPeriod}>
<SelectTrigger className="h-9 w-[160px]">
<ListFilter className="mr-2 h-4 w-4" />
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="7days">Last 7 days</SelectItem>
<SelectItem value="30days">Last 30 days</SelectItem>
<SelectItem value="6months">Last 6 months</SelectItem>
<SelectItem value="12months">Last 12 months</SelectItem>
</SelectContent>
</Select>
</PageHeader>
<p className="text-xs font-semibold tracking-widest uppercase text-muted-foreground">Pipeline Overview</p>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
{stats
? statCards.map((card, i) => (
<StatCard key={card.title} {...card} index={i} monthlyBreakdown={stats.monthlyBreakdown} />
))
: Array.from({ length: 6 }).map((_, i) => <StatCardSkeleton key={i} />)
}
</div>
<p className="text-xs font-semibold tracking-widest uppercase text-muted-foreground">Analytics</p>
<div className="grid gap-6 lg:grid-cols-2">
<LeadStatusChart data={stats?.statusDistribution ?? []} />
<LeadsPerMonthChart data={stats?.leadsPerMonth ?? []} />
</div>
<RecentLeadsTable leads={stats?.recentLeads ?? []} />
</div>
)
}
@@ -0,0 +1,36 @@
"use client"
import { AppShell } from "@/components/layout/app-shell"
import { UserProvider, useUser } from "@/providers/user-provider"
import { NotificationProvider } from "@/providers/notification-provider"
import { Loader2 } from "lucide-react"
function DashboardContent({ children }: { children: React.ReactNode }) {
const { user, loading } = useUser()
if (loading) {
return (
<div className="flex h-screen items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
if (!user) return null
return <AppShell>{children}</AppShell>
}
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<UserProvider>
<NotificationProvider>
<DashboardContent>{children}</DashboardContent>
</NotificationProvider>
</UserProvider>
)
}
@@ -0,0 +1,190 @@
"use client"
import { useState, useEffect } from "react"
import Link from "next/link"
import { motion } from "framer-motion"
import { use } from "react"
import { PageHeader } from "@/components/shared/page-header"
import { LeadDetailsCard } from "@/components/leads/lead-details-card"
import { LeadStatusBadge } from "@/components/leads/lead-status-badge"
import { NoteTimeline } from "@/components/notes/note-timeline"
import { NoteForm } from "@/components/notes/note-form"
import { Button } from "@/components/ui/button"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { ArrowLeft, Edit, ExternalLink } from "lucide-react"
import { Lead, Note } from "@/types"
export default function LeadDetailsPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const [lead, setLead] = useState<Lead | null>(null)
const [leadNotes, setLeadNotes] = useState<Note[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
async function fetchData() {
try {
const [leadRes, notesRes] = await Promise.all([
fetch(`/api/leads/${id}`),
fetch(`/api/leads/${id}/notes`),
])
if (leadRes.ok) setLead(await leadRes.json())
if (notesRes.ok) setLeadNotes(await notesRes.json())
} catch {
// ignore
}
setLoading(false)
}
fetchData()
}, [id])
if (loading) {
return (
<div className="flex items-center justify-center h-[60vh]">
<p className="text-muted-foreground">Loading...</p>
</div>
)
}
if (!lead) {
return (
<div className="flex items-center justify-center h-[60vh]">
<div className="text-center">
<h2 className="text-2xl font-bold">Lead not found</h2>
<p className="mt-2 text-muted-foreground">The lead you are looking for does not exist.</p>
<Link href="/leads" className="mt-4 inline-block">
<Button variant="outline">
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Leads
</Button>
</Link>
</div>
</div>
)
}
return (
<div className="space-y-6">
<Link
href="/leads"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4" />
Back to leads
</Link>
<PageHeader
title={
<div className="flex items-center gap-3">
<span>{lead.companyName}</span>
<LeadStatusBadge status={lead.status} />
</div>
}
description={lead.contactName}
>
<Select
value={lead.status}
onValueChange={(v) => {
setLead((prev) => prev ? { ...prev, status: v as Lead["status"] } : prev)
}}
>
<SelectTrigger className="h-9 w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="open">Open</SelectItem>
<SelectItem value="contacted">Contacted</SelectItem>
<SelectItem value="pending">Pending</SelectItem>
<SelectItem value="closed">Closed</SelectItem>
<SelectItem value="ignored">Ignored</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm">
<Edit className="mr-2 h-4 w-4" />
Edit
</Button>
</PageHeader>
<div className="grid gap-6 lg:grid-cols-3">
<div className="lg:col-span-2 space-y-6">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<LeadDetailsCard lead={lead} />
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.1 }}
>
<NoteForm leadId={lead.id} />
</motion.div>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.2 }}
>
<NoteTimeline notes={leadNotes} />
</motion.div>
</div>
<div className="space-y-6">
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.3, delay: 0.15 }}
className="rounded-lg border bg-card p-6"
>
<h3 className="font-semibold mb-4">Activity</h3>
<div className="space-y-4">
<div className="flex items-center gap-3 text-sm">
<div className="h-2 w-2 rounded-full bg-blue-500" />
<div>
<p className="font-medium">Lead Created</p>
<p className="text-xs text-muted-foreground">{new Date(lead.createdAt).toLocaleDateString()}</p>
</div>
</div>
{leadNotes.slice(0, 3).map((note) => (
<div key={note.id} className="flex items-start gap-3 text-sm">
<div className="h-2 w-2 rounded-full bg-muted-foreground mt-1.5" />
<div>
<p className="font-medium">{note.authorName}</p>
<p className="text-xs text-muted-foreground">{note.note.slice(0, 60)}...</p>
</div>
</div>
))}
</div>
</motion.div>
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.3, delay: 0.25 }}
className="rounded-lg border bg-card p-6"
>
<h3 className="font-semibold mb-4">Quick Actions</h3>
<div className="space-y-2">
<Button variant="outline" className="w-full justify-start" size="sm">
<ExternalLink className="mr-2 h-4 w-4" />
Send Email
</Button>
<Button variant="outline" className="w-full justify-start" size="sm">
<ExternalLink className="mr-2 h-4 w-4" />
Call Lead
</Button>
</div>
</motion.div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,279 @@
"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Card, CardContent } from "@/components/ui/card"
import { ArrowLeft } from "lucide-react"
import { Lead, LeadStatus } from "@/types"
import { leads } from "@/data/leads"
import { users } from "@/data/users"
import { useNotifications } from "@/providers/notification-provider"
import { LEAD_SOURCES, LEAD_STATUSES } from "@/lib/constants"
const leadFormSchema = z.object({
companyName: z.string().min(1, "Company name is required"),
contactName: z.string().min(1, "Contact name is required"),
email: z.string().email("Invalid email address"),
phone: z.string().optional(),
source: z.string().optional(),
description: z.string().optional(),
status: z.string(),
assignedUserId: z.string().optional(),
})
type LeadFormValues = z.infer<typeof leadFormSchema>
export default function CreateLeadPage() {
const router = useRouter()
const { addNotification } = useNotifications()
const [saving, setSaving] = useState(false)
const form = useForm<LeadFormValues>({
resolver: zodResolver(leadFormSchema),
defaultValues: {
companyName: "",
contactName: "",
email: "",
phone: "",
source: "",
description: "",
status: "open",
assignedUserId: "none",
},
})
function onSubmit(values: LeadFormValues) {
setSaving(true)
const now = new Date().toISOString()
const assignedUserId: string | null = values.assignedUserId === "none" ? null : (values.assignedUserId ?? null)
const assignedUser = assignedUserId ? users.find((u) => u.id === assignedUserId) ?? null : null
const newLead: Lead = {
id: `lead-${String(leads.length + 1).padStart(3, "0")}`,
companyName: values.companyName,
contactName: values.contactName,
email: values.email,
phone: values.phone ?? "",
source: values.source ?? "",
description: values.description ?? "",
status: values.status as LeadStatus,
assignedUserId,
assignedUser,
createdAt: now,
updatedAt: now,
}
leads.unshift(newLead)
addNotification(
"lead_created",
"New Lead Created",
`${newLead.companyName}${newLead.contactName}`,
`/leads/${newLead.id}`
)
router.push("/leads")
}
return (
<div className="space-y-6">
<Link
href="/leads"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="h-4 w-4" />
Back to leads
</Link>
<div>
<h1 className="text-2xl font-bold tracking-tight">Create New Lead</h1>
<p className="mt-1 text-sm text-muted-foreground">Fill in the details to add a new lead.</p>
</div>
<Card>
<CardContent className="pt-6">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="companyName"
render={({ field }) => (
<FormItem>
<FormLabel>Company Name</FormLabel>
<FormControl>
<Input placeholder="Acme Corp" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="contactName"
render={({ field }) => (
<FormItem>
<FormLabel>Contact Name</FormLabel>
<FormControl>
<Input placeholder="John Doe" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="john@acme.com" type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Phone</FormLabel>
<FormControl>
<Input placeholder="(555) 123-4567" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="source"
render={({ field }) => (
<FormItem>
<FormLabel>Source</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select source" />
</SelectTrigger>
</FormControl>
<SelectContent>
{LEAD_SOURCES.map((source) => (
<SelectItem key={source} value={source}>
{source}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="status"
render={({ field }) => (
<FormItem>
<FormLabel>Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select status" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(LEAD_STATUSES).map(([key, { label }]) => (
<SelectItem key={key} value={key}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Brief description of the lead and their requirements..."
className="min-h-[100px]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="assignedUserId"
render={({ field }) => (
<FormItem>
<FormLabel>Assign To</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select user" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="none">Unassigned</SelectItem>
{users.filter((u) => u.active).map((user) => (
<SelectItem key={user.id} value={user.id}>
{user.name} ({user.role})
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<div className="flex items-center gap-3 pt-2">
<Button type="submit" disabled={saving}>
{saving ? "Saving..." : "Create Lead"}
</Button>
<Button
type="button"
variant="outline"
onClick={() => router.push("/leads")}
>
Cancel
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
</div>
)
}
@@ -0,0 +1,57 @@
"use client"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { LeadsTable } from "@/components/leads/leads-table"
import { LeadsTableToolbar } from "@/components/leads/leads-table-toolbar"
import { Lead } from "@/types"
export default function LeadsPage() {
const router = useRouter()
const [search, setSearch] = useState("")
const [statusFilter, setStatusFilter] = useState("all")
const [periodFilter, setPeriodFilter] = useState("all")
const [leadsData, setLeadsData] = useState<Lead[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
const params = new URLSearchParams()
if (search) params.set("search", search)
if (statusFilter !== "all") params.set("status", statusFilter)
if (periodFilter !== "all") params.set("period", periodFilter)
setLoading(true)
fetch(`/api/leads?${params.toString()}`)
.then((r) => r.json())
.then((data) => {
setLeadsData(data)
setLoading(false)
})
.catch(() => setLoading(false))
}, [search, statusFilter, periodFilter])
return (
<div className="space-y-4">
<PageHeader
title="Leads"
description="Manage and track your sales leads"
/>
<div className="rounded-lg border bg-card">
<div className="p-4">
<LeadsTableToolbar
search={search}
onSearchChange={setSearch}
statusFilter={statusFilter}
onStatusFilterChange={setStatusFilter}
periodFilter={periodFilter}
onPeriodFilterChange={setPeriodFilter}
onCreateClick={() => router.push("/leads/new")}
/>
</div>
<LeadsTable data={leadsData} loading={loading} />
</div>
</div>
)
}
@@ -0,0 +1,142 @@
"use client"
import { useRef } from "react"
import { PageHeader } from "@/components/shared/page-header"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { useUser } from "@/providers/user-provider"
import { Mail, Calendar, Shield, Activity, Camera } from "lucide-react"
import { toast } from "sonner"
export default function ProfilePage() {
const { user, updateAvatar } = useUser()
if (!user) return null
const fileInputRef = useRef<HTMLInputElement>(null)
const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (!file) return
const validTypes = ["image/png", "image/jpeg"]
if (!validTypes.includes(file.type)) {
toast.error("Only PNG and JPEG files are allowed")
return
}
const reader = new FileReader()
reader.onload = async () => {
const dataUrl = reader.result as string
try {
const res = await fetch("/api/users/avatar", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ avatar: dataUrl }),
})
if (res.ok) {
const data = await res.json()
updateAvatar(data.avatar)
toast.success("Avatar updated")
} else {
toast.error("Failed to save avatar")
}
} catch {
toast.error("Failed to save avatar")
}
}
reader.readAsDataURL(file)
}
return (
<div className="space-y-6">
<PageHeader title="Profile" description="Your account information" />
<div className="grid gap-6 lg:grid-cols-3">
<Card className="lg:col-span-1">
<CardContent className="flex flex-col items-center pt-8">
<div className="relative">
<Avatar className="h-24 w-24">
<AvatarImage src={user.avatar} />
<AvatarFallback className="text-2xl">{user.name.split(" ").map((n) => n[0]).join("")}</AvatarFallback>
</Avatar>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
>
<Camera className="h-6 w-6 text-white" />
</button>
<input
ref={fileInputRef}
type="file"
accept=".png,.jpeg,.jpg"
className="hidden"
onChange={handleAvatarChange}
/>
</div>
<h2 className="mt-4 text-xl font-semibold">{user.name}</h2>
<Badge variant="secondary" className="mt-1 capitalize">
{user.role}
</Badge>
<div className="mt-6 flex w-full flex-col gap-3 text-sm">
<div className="flex items-center gap-3 rounded-lg bg-muted/50 px-4 py-3">
<Mail className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">{user.email}</span>
</div>
<div className="flex items-center gap-3 rounded-lg bg-muted/50 px-4 py-3">
<Calendar className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">
Joined {new Date(user.createdAt).toLocaleDateString("en-US", { month: "long", year: "numeric" })}
</span>
</div>
<div className="flex items-center gap-3 rounded-lg bg-muted/50 px-4 py-3">
<Shield className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground capitalize">{user.role} access</span>
</div>
<div className="flex items-center gap-3 rounded-lg bg-muted/50 px-4 py-3">
<Activity className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">{user.active ? "Active" : "Inactive"}</span>
</div>
</div>
</CardContent>
</Card>
<div className="lg:col-span-2 space-y-6">
<Card>
<CardHeader>
<CardTitle>Account Details</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1">
<span className="text-xs text-muted-foreground">Full Name</span>
<p className="text-sm font-medium">{user.name}</p>
</div>
<div className="space-y-1">
<span className="text-xs text-muted-foreground">Email</span>
<p className="text-sm font-medium">{user.email}</p>
</div>
<div className="space-y-1">
<span className="text-xs text-muted-foreground">Role</span>
<p className="text-sm font-medium capitalize">{user.role}</p>
</div>
<div className="space-y-1">
<span className="text-xs text-muted-foreground">Status</span>
<p className="text-sm font-medium">{user.active ? "Active" : "Inactive"}</p>
</div>
<div className="space-y-1">
<span className="text-xs text-muted-foreground">Member Since</span>
<p className="text-sm font-medium">
{new Date(user.createdAt).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}
</p>
</div>
<div className="space-y-1">
<span className="text-xs text-muted-foreground">User ID</span>
<p className="text-sm font-medium font-mono">{user.id}</p>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
)
}
@@ -0,0 +1,43 @@
"use client"
import { PageHeader } from "@/components/shared/page-header"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { CompanySettingsForm } from "@/components/settings/company-settings-form"
import { UserPreferencesForm } from "@/components/settings/user-preferences-form"
import { ThemeSettings } from "@/components/settings/theme-settings"
import { NotificationSettings } from "@/components/settings/notification-settings"
import { Building2, User, Palette, Bell } from "lucide-react"
export default function SettingsPage() {
const tabs = [
{ value: "company", label: "Company", icon: Building2, component: CompanySettingsForm },
{ value: "preferences", label: "Preferences", icon: User, component: UserPreferencesForm },
{ value: "theme", label: "Theme", icon: Palette, component: ThemeSettings },
{ value: "notifications", label: "Notifications", icon: Bell, component: NotificationSettings },
]
return (
<div className="space-y-4">
<PageHeader
title="Settings"
description="Manage your CRM configuration and preferences"
/>
<Tabs defaultValue="company" className="space-y-6">
<TabsList>
{tabs.map((tab) => (
<TabsTrigger key={tab.value} value={tab.value} className="gap-2">
<tab.icon className="h-4 w-4" />
{tab.label}
</TabsTrigger>
))}
</TabsList>
{tabs.map((tab) => (
<TabsContent key={tab.value} value={tab.value}>
<tab.component />
</TabsContent>
))}
</Tabs>
</div>
)
}
@@ -0,0 +1,105 @@
"use client"
import { useState, useEffect, useCallback } from "react"
import { PageHeader } from "@/components/shared/page-header"
import { UsersTable } from "@/components/users/users-table"
import { UserFormDialog } from "@/components/users/user-form-dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { useUser } from "@/providers/user-provider"
import { Plus, Users as UsersIcon, Search } from "lucide-react"
import type { User } from "@/types"
export default function UsersPage() {
const { user } = useUser()
const [users, setUsers] = useState<User[]>([])
const [loading, setLoading] = useState(true)
const [createOpen, setCreateOpen] = useState(false)
const [search, setSearch] = useState("")
const fetchUsers = useCallback(async () => {
try {
const res = await fetch("/api/users")
if (res.ok) {
const data = await res.json()
setUsers(data.users || [])
}
} catch {
// ignore
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchUsers()
}, [fetchUsers])
const activeUsers = users.filter((u) => u.active !== false)
const admins = users.filter((u) => u.role === "admin")
const stats = [
{ label: "Total Users", value: users.length, color: "bg-blue-500/10", textColor: "text-blue-500" },
{ label: "Active", value: activeUsers.length, color: "bg-green-500/10", textColor: "text-green-500" },
{ label: "Admins", value: admins.length, color: "bg-purple-500/10", textColor: "text-purple-500" },
{ label: "Sales", value: users.filter((u) => u.role === "sales").length, color: "bg-orange-500/10", textColor: "text-orange-500" },
]
const filtered = users.filter((u) => {
if (!search) return true
const q = search.toLowerCase()
return u.name?.toLowerCase().includes(q) || u.email?.toLowerCase().includes(q)
})
return (
<div className="space-y-4">
<PageHeader
title="Users"
description="Manage team members and their roles"
>
<Button className="gap-2" onClick={() => setCreateOpen(true)}>
<Plus className="h-4 w-4" />
Add User
</Button>
</PageHeader>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 mb-6">
{stats.map((s) => (
<div key={s.label} className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-3">
<div
className={`flex h-10 w-10 items-center justify-center rounded-lg ${s.color}`}
>
<UsersIcon className={`h-5 w-5 ${s.textColor}`} />
</div>
<div>
<p className="text-2xl font-bold">{s.value}</p>
<p className="text-xs text-muted-foreground">{s.label}</p>
</div>
</div>
</div>
))}
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by name or email..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="h-9 pl-9"
/>
</div>
<div className="rounded-lg border bg-card">
<UsersTable data={filtered} loading={loading} onUserDeleted={fetchUsers} />
</div>
<UserFormDialog
open={createOpen}
onOpenChange={setCreateOpen}
onUserCreated={fetchUsers}
/>
</div>
)
}
+26
View File
@@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { chatWithAI } from "@/lib/ai"
export async function POST(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
if (!["sales", "admin", "super_admin"].includes(user.role)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
}
const { message } = await request.json()
if (!message || typeof message !== "string") {
return NextResponse.json({ error: "Message is required" }, { status: 400 })
}
const response = await chatWithAI(message, user.id, user.role)
return NextResponse.json({ response })
} catch (error) {
console.error("AI chat error:", error)
return NextResponse.json({ error: "AI service unavailable" }, { status: 503 })
}
}
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { fetchJobs } from "@/lib/ai"
export async function GET() {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
if (!["sales", "admin", "super_admin"].includes(user.role)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
}
const jobs = await fetchJobs()
return NextResponse.json({ jobs })
} catch {
return NextResponse.json({ jobs: [] })
}
}
@@ -0,0 +1,120 @@
import { NextRequest, NextResponse } from "next/server"
import {
comparePassword,
getUserByEmail,
getUserByUsername,
mapDbUserToSessionUser,
recordLoginAttempt,
incrementFailedAttempts,
resetFailedAttempts,
isAccountLocked,
createSession,
} from "@/lib/auth"
export async function POST(request: NextRequest) {
try {
const { email, username, password } = await request.json()
const credential = email || username
if (!credential || !password) {
return NextResponse.json(
{ error: "Email/Username and password are required." },
{ status: 400 }
)
}
if (credential.trim().length === 0 || password.trim().length === 0) {
return NextResponse.json(
{ error: "Credentials cannot be empty." },
{ status: 400 }
)
}
const ipAddress =
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
request.headers.get("x-real-ip") ||
"127.0.0.1"
const userAgent = request.headers.get("user-agent") || null
// Try to find user by email first, then by username
let dbUser =
email || credential.includes("@")
? await getUserByEmail(credential)
: null
if (!dbUser) {
dbUser = await getUserByUsername(credential)
}
if (!dbUser) {
await recordLoginAttempt(
null,
credential,
ipAddress,
userAgent,
false,
"User not found"
)
return NextResponse.json(
{ error: "Invalid email/username or password." },
{ status: 401 }
)
}
const lockStatus = await isAccountLocked(dbUser)
if (lockStatus.locked) {
await recordLoginAttempt(
dbUser.id,
credential,
ipAddress,
userAgent,
false,
lockStatus.reason
)
return NextResponse.json(
{ error: lockStatus.reason },
{ status: 423 }
)
}
const valid = await comparePassword(password, dbUser.password_hash)
if (!valid) {
await incrementFailedAttempts(dbUser.id)
await recordLoginAttempt(
dbUser.id,
credential,
ipAddress,
userAgent,
false,
"Invalid password"
)
return NextResponse.json(
{ error: "Invalid email/username or password." },
{ status: 401 }
)
}
await resetFailedAttempts(dbUser.id)
await recordLoginAttempt(
dbUser.id,
credential,
ipAddress,
userAgent,
true
)
await createSession(dbUser.id, dbUser.role_name)
const user = mapDbUserToSessionUser(dbUser)
return NextResponse.json({ user }, { status: 200 })
} catch (error) {
console.error("Login error:", error)
return NextResponse.json(
{ error: "Authentication service unavailable. Please ensure PostgreSQL is running and configured." },
{ status: 503 }
)
}
}
@@ -0,0 +1,15 @@
import { NextResponse } from "next/server"
import { destroySession } from "@/lib/auth"
export async function POST() {
try {
await destroySession()
return NextResponse.json({ success: true }, { status: 200 })
} catch (error) {
console.error("Logout error:", error)
return NextResponse.json(
{ error: "Logout failed." },
{ status: 500 }
)
}
}
+18
View File
@@ -0,0 +1,18 @@
import { NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
export async function GET() {
try {
const user = await getSessionUser()
if (!user) {
return NextResponse.json({ error: "Not authenticated." }, { status: 401 })
}
return NextResponse.json({ user }, { status: 200 })
} catch (error) {
console.error("Auth me error:", error)
return NextResponse.json(
{ error: "Authentication service unavailable." },
{ status: 503 }
)
}
}
@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const [msgResult, otherReadResult] = await Promise.all([
query(
`SELECT m.id, m.sender_id, m.content, m.created_at, m.updated_at, m.deleted_at,
u.first_name || ' ' || u.last_name AS sender_name,
u.email AS sender_email,
u.avatar_url AS sender_avatar_url
FROM messages m
JOIN users u ON u.id = m.sender_id
WHERE m.conversation_id = $1 AND m.deleted_at IS NULL
ORDER BY m.created_at ASC`,
[id],
),
query(
`SELECT last_read_at FROM conversation_participants
WHERE conversation_id = $1 AND user_id != $2`,
[id, user.id],
),
])
const otherLastReadAt = otherReadResult.rows[0]?.last_read_at
? new Date(otherReadResult.rows[0].last_read_at).getTime()
: 0
const messages = msgResult.rows.map((row: any) => ({
id: row.id,
conversationId: id,
senderId: row.sender_id,
senderName: row.sender_name,
senderAvatar: row.sender_avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(row.sender_name)}&background=1d4ed8&color=fff&size=128`,
content: row.content,
timestamp: formatTime(new Date(row.created_at)),
createdAt: row.created_at,
read: row.sender_id === user.id
? new Date(row.created_at).getTime() <= otherLastReadAt
: true,
}))
return NextResponse.json({ messages })
} catch (error) {
console.error("Messages error:", error)
return NextResponse.json({ error: "Failed to load messages" }, { status: 500 })
}
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const { content } = await request.json()
if (!content?.trim()) {
return NextResponse.json({ error: "Message content is required" }, { status: 400 })
}
const result = await query(
`INSERT INTO messages (conversation_id, sender_id, content)
VALUES ($1, $2, $3)
RETURNING id, created_at`,
[id, user.id, content.trim()],
)
await query(
`UPDATE conversations SET updated_at = NOW() WHERE id = $1`,
[id],
)
const msg = result.rows[0]
return NextResponse.json({
message: {
id: msg.id,
conversationId: id,
senderId: user.id,
senderName: `${user.firstName} ${user.lastName}`,
senderAvatar: user.avatar,
content: content.trim(),
timestamp: formatTime(new Date(msg.created_at)),
createdAt: msg.created_at,
read: false,
},
})
} catch (error) {
console.error("Send message error:", error)
return NextResponse.json({ error: "Failed to send message" }, { status: 500 })
}
}
function formatTime(date: Date): string {
const now = new Date()
const isToday = date.toDateString() === now.toDateString()
if (isToday) {
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
}
return date.toLocaleDateString([], { month: "short", day: "numeric" }) + " " +
date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
}
@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function POST(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
await query(
`UPDATE conversation_participants
SET last_read_at = NOW()
WHERE conversation_id = $1 AND user_id = $2`,
[id, user.id],
)
return NextResponse.json({ success: true })
} catch (error) {
console.error("Mark read error:", error)
return NextResponse.json({ error: "Failed to mark as read" }, { status: 500 })
}
}
@@ -0,0 +1,129 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function GET() {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const result = await query(
`SELECT
c.id,
c.updated_at,
cp_me.last_read_at,
u.id AS other_user_id,
u.first_name || ' ' || u.last_name AS other_user_name,
u.email AS other_user_email,
u.avatar_url AS other_user_avatar_url,
(SELECT content FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message,
(SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message_time,
(SELECT count(*) FROM messages WHERE conversation_id = c.id AND sender_id != $1 AND created_at > COALESCE(cp_me.last_read_at, '1970-01-01')) AS unread
FROM conversations c
JOIN conversation_participants cp_me ON cp_me.conversation_id = c.id AND cp_me.user_id = $1
JOIN conversation_participants cp ON cp.conversation_id = c.id
JOIN users u ON u.id = cp.user_id AND u.id != $1
WHERE c.id IN (
SELECT conversation_id FROM conversation_participants WHERE user_id = $1
)
ORDER BY c.updated_at DESC`,
[user.id],
)
const conversations = result.rows.map((row: any) => ({
id: row.id,
updatedAt: row.updated_at,
otherUser: {
id: row.other_user_id,
name: row.other_user_name,
email: row.other_user_email,
avatar: row.other_user_avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(row.other_user_name)}&background=1d4ed8&color=fff&size=128`,
},
lastMessage: row.last_message || "",
lastMessageTime: row.last_message_time ? timeAgo(new Date(row.last_message_time)) : "",
unread: parseInt(row.unread) || 0,
}))
return NextResponse.json({ conversations })
} catch (error) {
console.error("Conversations error:", error)
return NextResponse.json({ error: "Failed to load conversations" }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { userId } = await request.json()
if (!userId) {
return NextResponse.json({ error: "userId is required" }, { status: 400 })
}
if (userId === user.id) {
return NextResponse.json({ error: "Cannot start a conversation with yourself" }, { status: 400 })
}
const existing = await query(
`SELECT c.id FROM conversations c
JOIN conversation_participants cp1 ON cp1.conversation_id = c.id AND cp1.user_id = $1
JOIN conversation_participants cp2 ON cp2.conversation_id = c.id AND cp2.user_id = $2
LIMIT 1`,
[user.id, userId],
)
if (existing.rows.length > 0) {
return NextResponse.json({ conversationId: existing.rows[0].id })
}
const convResult = await query(
`INSERT INTO conversations DEFAULT VALUES RETURNING id`,
)
const conversationId = convResult.rows[0].id
await query(
`INSERT INTO conversation_participants (conversation_id, user_id, last_read_at) VALUES ($1, $2, NOW()), ($1, $3, NOW())`,
[conversationId, user.id, userId],
)
const otherUser = await query(
`SELECT id, first_name || ' ' || last_name AS name, email, avatar_url
FROM users WHERE id = $1`,
[userId],
)
const other = otherUser.rows[0]
return NextResponse.json({
conversation: {
id: conversationId,
updatedAt: new Date().toISOString(),
otherUser: {
id: other.id,
name: other.name,
email: other.email,
avatar: other.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(other.name)}&background=1d4ed8&color=fff&size=128`,
},
lastMessage: "",
lastMessageTime: "",
unread: 0,
},
})
} catch (error) {
console.error("Create conversation error:", error)
return NextResponse.json({ error: "Failed to create conversation" }, { status: 500 })
}
}
function timeAgo(date: Date): string {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000)
if (seconds < 60) return "now"
const minutes = Math.floor(seconds / 60)
if (minutes < 60) return `${minutes}m ago`
const hours = Math.floor(minutes / 60)
if (hours < 24) return `${hours}h ago`
const days = Math.floor(hours / 24)
if (days < 7) return `${days}d ago`
return date.toLocaleDateString()
}
+207
View File
@@ -0,0 +1,207 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
function getPeriodDateRange(period: string): { start: Date; end: Date } {
const end = new Date()
let start: Date
switch (period) {
case "7days":
start = new Date(end); start.setDate(start.getDate() - 7); break
case "30days":
start = new Date(end); start.setDate(start.getDate() - 30); break
case "12months":
start = new Date(end); start.setFullYear(start.getFullYear() - 12); break
case "6months":
default:
start = new Date(end); start.setMonth(start.getMonth() - 6); break
}
return { start, end }
}
function getPreviousPeriodRange(period: string, currentStart: Date): { start: Date; end: Date } {
const end = new Date(currentStart)
const diff = end.getTime() - currentStart.getTime()
const start = new Date(end.getTime() - diff)
return { start, end }
}
const periodLabels: Record<string, string> = {
"7days": "Last 7 days",
"30days": "Last 30 days",
"6months": "Last 6 months",
"12months": "Last 12 months",
}
function stageToStatus(name: string): string {
switch (name) {
case "New": return "open"
case "Contacted": return "contacted"
case "Qualified":
case "Interested":
case "Demo Scheduled":
case "Negotiation": return "pending"
case "Closed Won": return "closed"
case "Closed Lost": return "ignored"
default: return "open"
}
}
async function fetchLeadsInRange(start: Date, end: Date) {
const result = await query(
`SELECT l.id, l.created_at, l.company_name, l.contact_name, l.email, l.phone,
l.notes, l.assigned_to, l.score,
ls.name AS stage_name,
u.id AS user_id, u.first_name, u.last_name, u.email AS user_email, u.avatar_url
FROM leads l
JOIN lead_stages ls ON ls.id = l.stage_id
LEFT JOIN users u ON u.id = l.assigned_to
WHERE l.deleted_at IS NULL
AND l.created_at >= $1 AND l.created_at <= $2
ORDER BY l.created_at DESC`,
[start.toISOString(), end.toISOString()]
)
return result.rows.map((r: any) => ({
...r,
status: stageToStatus(r.stage_name),
}))
}
function countStatuses(leads: any[]) {
const counts = { open: 0, contacted: 0, pending: 0, closed: 0, ignored: 0 }
leads.forEach((l: any) => {
const s = l.status as keyof typeof counts
if (s in counts) counts[s]++
})
return counts
}
function buildMonthlyBreakdown(leads: any[], period: string) {
const { start, end } = getPeriodDateRange(period)
const result: { label: string; total: number; open: number; contacted: number; pending: number; closed: number; ignored: number }[] = []
const current = new Date(start)
const isMonthly = period === "6months" || period === "12months"
while (current <= end) {
const label = isMonthly
? current.toLocaleDateString("en-US", { month: "short", year: "2-digit" })
: current.toLocaleDateString("en-US", { month: "short", day: "numeric" })
const ps = new Date(current)
const pe = isMonthly
? new Date(current.getFullYear(), current.getMonth() + 1, 0, 23, 59, 59)
: (() => { const d = new Date(current); d.setHours(23, 59, 59, 999); return d })()
const inPeriod = leads.filter((l: any) => {
const d = new Date(l.created_at)
return d >= ps && d <= pe
})
const counts = countStatuses(inPeriod)
result.push({ label, total: inPeriod.length, ...counts })
if (isMonthly) current.setMonth(current.getMonth() + 1)
else current.setDate(current.getDate() + 1)
}
return result
}
function computeTrend(current: number, previous: number): { pct: number; up: boolean } {
if (previous === 0) return { pct: current > 0 ? 100 : 0, up: current > 0 }
const pct = Math.round(((current - previous) / previous) * 100)
return { pct: Math.abs(pct), up: pct >= 0 }
}
export async function GET(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { searchParams } = new URL(request.url)
const period = searchParams.get("period") || "6months"
const yearParam = searchParams.get("year")
let start: Date, end: Date, prevRange: { start: Date; end: Date }
if (yearParam) {
const y = parseInt(yearParam)
start = new Date(y, 0, 1)
end = new Date(y, 11, 31, 23, 59, 59)
prevRange = { start: new Date(y - 1, 0, 1), end: new Date(y - 1, 11, 31, 23, 59, 59) }
} else {
const r = getPeriodDateRange(period)
start = r.start; end = r.end
prevRange = getPreviousPeriodRange(period, start)
}
const [currentLeads, prevLeads] = await Promise.all([
fetchLeadsInRange(start, end),
fetchLeadsInRange(prevRange.start, prevRange.end),
])
const currentCounts = countStatuses(currentLeads)
const prevCounts = countStatuses(prevLeads)
const totalLeads = currentLeads.length
const closedLeads = currentCounts.closed
const conversionRate = totalLeads > 0 ? Math.round((closedLeads / totalLeads) * 100) : 0
const mappedLeads = currentLeads.map((r: any) => ({
id: r.id,
companyName: r.company_name || "",
contactName: r.contact_name,
email: r.email || "",
phone: r.phone || "",
source: "",
description: r.notes || "",
status: r.status,
assignedUserId: r.assigned_to,
assignedUser: r.assigned_to ? {
id: r.user_id,
name: `${r.first_name} ${r.last_name}`,
email: r.user_email,
avatar: r.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${r.first_name} ${r.last_name}`)}&background=1d4ed8&color=fff&size=128`,
} : null,
createdAt: r.created_at,
updatedAt: r.updated_at,
}))
const monthlyBreakdown = buildMonthlyBreakdown(currentLeads, period)
const trends = {
totalLeads: computeTrend(currentCounts.open + currentCounts.contacted + currentCounts.pending + currentCounts.closed + currentCounts.ignored,
prevCounts.open + prevCounts.contacted + prevCounts.pending + prevCounts.closed + prevCounts.ignored),
openLeads: computeTrend(currentCounts.open, prevCounts.open),
contactedLeads: computeTrend(currentCounts.contacted, prevCounts.contacted),
pendingLeads: computeTrend(currentCounts.pending, prevCounts.pending),
closedLeads: computeTrend(currentCounts.closed, prevCounts.closed),
conversionRate: computeTrend(conversionRate,
prevLeads.length > 0 ? Math.round((prevCounts.closed / prevLeads.length) * 100) : 0),
}
const stats = {
totalLeads,
openLeads: currentCounts.open,
contactedLeads: currentCounts.contacted,
pendingLeads: currentCounts.pending,
closedLeads,
ignoredLeads: currentCounts.ignored,
conversionRate,
monthlyBreakdown,
leadsPerMonth: monthlyBreakdown.map((m: any) => ({ label: m.label, leads: m.total, closed: m.closed })),
trends,
recentLeads: mappedLeads.slice(0, 10),
statusDistribution: [
{ name: "Open", value: currentCounts.open, color: "#3b82f6" },
{ name: "Contacted", value: currentCounts.contacted, color: "#f59e0b" },
{ name: "Pending", value: currentCounts.pending, color: "#8b5cf6" },
{ name: "Closed", value: currentCounts.closed, color: "#10b981" },
{ name: "Ignored", value: currentCounts.ignored, color: "#6B7280" },
],
periodLabel: periodLabels[period] ?? "Selected period",
}
return NextResponse.json(stats)
} catch (error) {
console.error("Dashboard API error:", error)
return NextResponse.json({ error: "Failed to load dashboard stats" }, { status: 500 })
}
}
@@ -0,0 +1,62 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const { content } = await request.json()
if (!content?.trim()) {
return NextResponse.json({ error: "Content is required" }, { status: 400 })
}
await query(
`INSERT INTO customer_notes (customer_id, author_id, content)
VALUES ($1, $2, $3)`,
[id, user.id, content.trim()]
)
return NextResponse.json({ success: true })
} catch (error) {
console.error("Create note error:", error)
return NextResponse.json({ error: "Failed to create note" }, { status: 500 })
}
}
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const result = await query(
`SELECT cn.id, cn.created_at, cn.updated_at, cn.content,
u.id AS user_id, u.first_name, u.last_name, u.avatar_url
FROM customer_notes cn
JOIN users u ON u.id = cn.author_id
WHERE cn.customer_id = $1 AND cn.deleted_at IS NULL
ORDER BY cn.created_at DESC`,
[id]
)
const notes = result.rows.map((r: any) => ({
id: r.id,
leadId: id,
userId: r.user_id,
authorName: `${r.first_name} ${r.last_name}`,
authorAvatar: r.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${r.first_name} ${r.last_name}`)}&background=1d4ed8&color=fff&size=128`,
note: r.content,
createdAt: r.created_at,
updatedAt: r.updated_at,
}))
return NextResponse.json(notes)
} catch (error) {
console.error("Lead notes API error:", error)
return NextResponse.json({ error: "Failed to load notes" }, { status: 500 })
}
}
@@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
function stageToStatus(name: string): string {
switch (name) {
case "New": return "open"
case "Contacted": return "contacted"
case "Qualified":
case "Interested":
case "Demo Scheduled":
case "Negotiation": return "pending"
case "Closed Won": return "closed"
case "Closed Lost": return "ignored"
default: return "open"
}
}
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const result = await query(
`SELECT l.id, l.company_name, l.contact_name, l.email, l.phone, l.score,
l.assigned_to, l.created_at, l.updated_at, l.notes, l.source_id,
ls.name AS stage_name,
u.id AS user_id, u.first_name, u.last_name, u.email AS user_email, u.avatar_url
FROM leads l
JOIN lead_stages ls ON ls.id = l.stage_id
LEFT JOIN users u ON u.id = l.assigned_to
WHERE l.id = $1 AND l.deleted_at IS NULL`,
[id]
)
if (result.rows.length === 0) {
return NextResponse.json({ error: "Lead not found" }, { status: 404 })
}
const r = result.rows[0]
const lead = {
id: r.id,
companyName: r.company_name || "",
contactName: r.contact_name,
email: r.email || "",
phone: r.phone || "",
source: "",
description: r.notes || "",
status: stageToStatus(r.stage_name),
assignedUserId: r.assigned_to,
assignedUser: r.assigned_to ? {
id: r.user_id,
name: `${r.first_name} ${r.last_name}`,
email: r.user_email,
avatar: r.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${r.first_name} ${r.last_name}`)}&background=1d4ed8&color=fff&size=128`,
} : null,
createdAt: r.created_at,
updatedAt: r.updated_at,
}
return NextResponse.json(lead)
} catch (error) {
console.error("Lead detail API error:", error)
return NextResponse.json({ error: "Failed to load lead" }, { status: 500 })
}
}
+105
View File
@@ -0,0 +1,105 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
function stageToStatus(name: string): string {
switch (name) {
case "New": return "open"
case "Contacted": return "contacted"
case "Qualified":
case "Interested":
case "Demo Scheduled":
case "Negotiation": return "pending"
case "Closed Won": return "closed"
case "Closed Lost": return "ignored"
default: return "open"
}
}
function getPeriodDateRange(period: string): { start: Date; end: Date } | null {
if (period === "all") return null
const end = new Date()
let start: Date
switch (period) {
case "7days": start = new Date(end); start.setDate(start.getDate() - 7); break
case "30days": start = new Date(end); start.setDate(start.getDate() - 30); break
case "12months": start = new Date(end); start.setFullYear(start.getFullYear() - 12); break
case "6months": default: start = new Date(end); start.setMonth(start.getMonth() - 6); break
}
return { start, end }
}
export async function GET(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { searchParams } = new URL(request.url)
const search = searchParams.get("search") || ""
const status = searchParams.get("status") || "all"
const period = searchParams.get("period") || "all"
let sql = `SELECT l.id, l.company_name, l.contact_name, l.email, l.phone, l.score,
l.assigned_to, l.created_at, l.updated_at, l.notes, l.source_id,
ls.name AS stage_name,
u.id AS user_id, u.first_name, u.last_name, u.email AS user_email, u.avatar_url
FROM leads l
JOIN lead_stages ls ON ls.id = l.stage_id
LEFT JOIN users u ON u.id = l.assigned_to
WHERE l.deleted_at IS NULL`
const params: any[] = []
let paramIdx = 1
if (period !== "all") {
const range = getPeriodDateRange(period)
if (range) {
sql += ` AND l.created_at >= $${paramIdx} AND l.created_at <= $${paramIdx + 1}`
params.push(range.start.toISOString(), range.end.toISOString())
paramIdx += 2
}
}
if (search) {
sql += ` AND (l.contact_name ILIKE $${paramIdx} OR l.company_name ILIKE $${paramIdx} OR l.email ILIKE $${paramIdx} OR l.phone ILIKE $${paramIdx})`
params.push(`%${search}%`)
paramIdx++
}
sql += ` ORDER BY l.created_at DESC`
const result = await query(sql, params)
let leads = result.rows.map((r: any) => {
const s = stageToStatus(r.stage_name)
return {
id: r.id,
companyName: r.company_name || "",
contactName: r.contact_name,
email: r.email || "",
phone: r.phone || "",
source: "",
description: r.notes || "",
status: s,
assignedUserId: r.assigned_to,
assignedUser: r.assigned_to ? {
id: r.user_id,
name: `${r.first_name} ${r.last_name}`,
email: r.user_email,
avatar: r.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${r.first_name} ${r.last_name}`)}&background=1d4ed8&color=fff&size=128`,
} : null,
createdAt: r.created_at,
updatedAt: r.updated_at,
}
})
if (status !== "all") {
leads = leads.filter((l: any) => l.status === status)
}
return NextResponse.json(leads)
} catch (error) {
console.error("Leads API error:", error)
return NextResponse.json({ error: "Failed to load leads" }, { status: 500 })
}
}
@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const result = await query(
`UPDATE notifications SET is_read = TRUE WHERE id = $1 AND user_id = $2 RETURNING id`,
[id, user.id],
)
if (result.rowCount === 0) {
return NextResponse.json({ error: "Notification not found" }, { status: 404 })
}
return NextResponse.json({ success: true })
} catch (error) {
console.error("Notification PATCH error:", error)
return NextResponse.json({ error: "Failed to mark notification as read" }, { status: 500 })
}
}
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { id } = await params
const result = await query(
`DELETE FROM notifications WHERE id = $1 AND user_id = $2 RETURNING id`,
[id, user.id],
)
if (result.rowCount === 0) {
return NextResponse.json({ error: "Notification not found" }, { status: 404 })
}
return NextResponse.json({ success: true })
} catch (error) {
console.error("Notification DELETE error:", error)
return NextResponse.json({ error: "Failed to dismiss notification" }, { status: 500 })
}
}
@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function GET() {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const result = await query(
`SELECT lead_assigned, lead_status, note_added, daily_digest, weekly_report
FROM notification_preferences
WHERE user_id = $1`,
[user.id],
)
if (result.rowCount === 0) {
return NextResponse.json({
leadAssigned: true,
leadStatus: true,
noteAdded: false,
dailyDigest: false,
weeklyReport: true,
})
}
const r = result.rows[0]
return NextResponse.json({
leadAssigned: r.lead_assigned,
leadStatus: r.lead_status,
noteAdded: r.note_added,
dailyDigest: r.daily_digest,
weeklyReport: r.weekly_report,
})
} catch (error) {
console.error("Preferences GET error:", error)
return NextResponse.json({ error: "Failed to load preferences" }, { status: 500 })
}
}
export async function PATCH(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const body = await request.json()
await query(
`INSERT INTO notification_preferences (user_id, lead_assigned, lead_status, note_added, daily_digest, weekly_report, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, NOW())
ON CONFLICT (user_id)
DO UPDATE SET lead_assigned = $2, lead_status = $3, note_added = $4,
daily_digest = $5, weekly_report = $6, updated_at = NOW()`,
[
user.id,
body.leadAssigned ?? true,
body.leadStatus ?? true,
body.noteAdded ?? false,
body.dailyDigest ?? false,
body.weeklyReport ?? true,
],
)
return NextResponse.json({ success: true })
} catch (error) {
console.error("Preferences PATCH error:", error)
return NextResponse.json({ error: "Failed to save preferences" }, { status: 500 })
}
}
@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function GET() {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const result = await query(
`SELECT id, type, title, description, link, is_read, created_at
FROM notifications
WHERE user_id = $1
ORDER BY created_at DESC
LIMIT 50`,
[user.id],
)
const notifications = result.rows.map((r: any) => ({
id: r.id,
type: r.type,
title: r.title,
description: r.description,
link: r.link,
read: r.is_read,
timestamp: r.created_at,
}))
const unreadResult = await query(
`SELECT COUNT(*) AS count FROM notifications WHERE user_id = $1 AND is_read = FALSE`,
[user.id],
)
return NextResponse.json({
notifications,
unreadCount: parseInt(unreadResult.rows[0].count, 10),
})
} catch (error) {
console.error("Notifications GET error:", error)
return NextResponse.json({ error: "Failed to load notifications" }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { type, title, description, link, userId } = await request.json()
const targetUserId = userId || user.id
const result = await query(
`INSERT INTO notifications (user_id, type, title, description, link)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, type, title, description, link, is_read, created_at`,
[targetUserId, type, title, description || null, link || null],
)
const notif = result.rows[0]
return NextResponse.json({
id: notif.id,
type: notif.type,
title: notif.title,
description: notif.description,
link: notif.link,
read: notif.is_read,
timestamp: notif.created_at,
}, { status: 201 })
} catch (error) {
console.error("Notifications POST error:", error)
return NextResponse.json({ error: "Failed to create notification" }, { status: 500 })
}
}
export async function PATCH() {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
await query(
`UPDATE notifications SET is_read = TRUE WHERE user_id = $1 AND is_read = FALSE`,
[user.id],
)
return NextResponse.json({ success: true })
} catch (error) {
console.error("Notifications PATCH error:", error)
return NextResponse.json({ error: "Failed to mark all as read" }, { status: 500 })
}
}
@@ -0,0 +1,29 @@
import { NextResponse } from "next/server"
import os from "os"
let prevCpu = process.cpuUsage()
let prevTime = Date.now()
export async function GET() {
const now = Date.now()
const elapsed = now - prevTime
const currentCpu = process.cpuUsage()
const user = currentCpu.user - prevCpu.user
const sys = currentCpu.system - prevCpu.system
const totalUs = user + sys
// CPU time (ms) / wall time (ms) * 100 = % of one core
const cpuPct = elapsed > 0 ? Math.round((totalUs / 1000) / elapsed * 100 * 10) / 10 : 0
prevCpu = currentCpu
prevTime = now
const mem = process.memoryUsage()
return NextResponse.json({
rssMB: Math.round(mem.rss / 1024 / 1024),
cpuPct,
cores: os.cpus().length,
})
}
@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from "next/server"
import { query } from "@/lib/db"
import { getSessionUser } from "@/lib/auth"
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const sessionUser = await getSessionUser()
if (!sessionUser) {
return NextResponse.json({ error: "Not authenticated" }, { status: 401 })
}
const { id } = await params
await query(
`UPDATE users SET deleted_at = NOW() WHERE id = $1 AND deleted_at IS NULL`,
[id]
)
return NextResponse.json({ success: true }, { status: 200 })
} catch (error) {
console.error("Error deleting user:", error)
return NextResponse.json({ error: "Failed to delete user" }, { status: 500 })
}
}
@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function POST(request: NextRequest) {
try {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const { avatar } = await request.json()
if (!avatar || typeof avatar !== "string") {
return NextResponse.json({ error: "Invalid avatar data" }, { status: 400 })
}
await query(
`UPDATE users SET avatar_url = $1 WHERE id = $2`,
[avatar, user.id],
)
return NextResponse.json({ avatar })
} catch (error) {
console.error("Avatar upload error:", error)
return NextResponse.json({ error: "Failed to update avatar" }, { status: 500 })
}
}
+78
View File
@@ -0,0 +1,78 @@
import { NextRequest, NextResponse } from "next/server"
import { query } from "@/lib/db"
import { hashPassword, getSessionUser } from "@/lib/auth"
export async function GET() {
try {
const result = await query(
`SELECT u.id, u.username, u.email, u.first_name, u.last_name,
u.is_active AS active, u.created_at, u.avatar_url,
r.name AS role
FROM users u
JOIN user_roles ur ON ur.user_id = u.id
JOIN roles r ON r.id = ur.role_id
WHERE u.deleted_at IS NULL
ORDER BY u.created_at DESC`
)
const users = result.rows.map((row: any) => ({
id: row.id,
name: `${row.first_name} ${row.last_name}`,
email: row.email,
role: row.role.toLowerCase(),
active: row.active,
avatar: row.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(`${row.first_name}+${row.last_name}`)}&background=1d4ed8&color=fff&size=128`,
createdAt: row.created_at,
}))
return NextResponse.json({ users }, { status: 200 })
} catch (error) {
console.error("Error fetching users:", error)
return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const sessionUser = await getSessionUser()
if (!sessionUser) {
return NextResponse.json({ error: "Not authenticated" }, { status: 401 })
}
const { name, email, password, role, active } = await request.json()
if (!name || !email || !password || !role) {
return NextResponse.json({ error: "Name, email, password, and role are required" }, { status: 400 })
}
const nameParts = name.trim().split(/\s+/)
const firstName = nameParts[0]
const lastName = nameParts.slice(1).join(" ") || firstName
const username = email.split("@")[0]
const passwordHash = await hashPassword(password)
const result = await query(
`INSERT INTO users (username, email, password_hash, first_name, last_name, is_active, created_by)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id`,
[username.toLowerCase(), email.toLowerCase(), passwordHash, firstName, lastName, active, sessionUser.id]
)
const roleId = (
await query(`SELECT id FROM roles WHERE LOWER(name) = LOWER($1)`, [role])
).rows[0]?.id
if (roleId) {
await query(
`INSERT INTO user_roles (user_id, role_id, assigned_by)
VALUES ($1, $2, $3)`,
[result.rows[0].id, roleId, sessionUser.id]
)
}
return NextResponse.json({ success: true, id: result.rows[0].id }, { status: 201 })
} catch (error: any) {
console.error("Error creating user:", error)
if (error?.constraint === "uq_users_username" || error?.constraint === "uq_users_email") {
return NextResponse.json({ error: "A user with this email or username already exists" }, { status: 409 })
}
return NextResponse.json({ error: error?.message || "Failed to create user" }, { status: 500 })
}
}
@@ -0,0 +1,40 @@
import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
export async function GET(request: NextRequest) {
try {
const currentUser = await getSessionUser()
if (!currentUser) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const q = request.nextUrl.searchParams.get("q") || ""
if (!q.trim()) {
return NextResponse.json({ users: [] })
}
const result = await query(
`SELECT id, first_name || ' ' || last_name AS name, email, avatar_url
FROM users
WHERE deleted_at IS NULL
AND id != $1
AND (LOWER(first_name || ' ' || last_name) LIKE LOWER($2)
OR LOWER(email) LIKE LOWER($2))
ORDER BY first_name ASC
LIMIT 10`,
[currentUser.id, `%${q}%`],
)
const users = result.rows.map((row: any) => ({
id: row.id,
name: row.name,
email: row.email,
avatar: row.avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(row.name)}&background=1d4ed8&color=fff&size=128`,
}))
return NextResponse.json({ users })
} catch (error) {
console.error("User search error:", error)
return NextResponse.json({ error: "Search failed" }, { status: 500 })
}
}
+326
View File
@@ -0,0 +1,326 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: 210 40% 98%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--sidebar: 222.2 84% 4.9%;
--sidebar-foreground: 210 40% 98%;
--sidebar-primary: 217.2 91.2% 59.8%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 217.2 32.6% 17.5%;
--sidebar-accent-foreground: 210 40% 98%;
--sidebar-border: 217.2 32.6% 17.5%;
--sidebar-ring: 224.3 76.3% 48%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
--sidebar: 222.2 84% 4.9%;
--sidebar-foreground: 210 40% 98%;
--sidebar-primary: 217.2 91.2% 59.8%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 217.2 32.6% 17.5%;
--sidebar-accent-foreground: 210 40% 98%;
--sidebar-border: 217.2 32.6% 17.5%;
--sidebar-ring: 224.3 76.3% 48%;
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
font-family: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
}
}
/* Login page custom styles */
.left-panel {
background: #0a0a0f;
position: relative;
overflow: hidden;
}
.right-panel {
background: #111118;
width: 420px;
flex: none;
position: relative;
}
.panel-divider {
width: 1px;
background: rgba(180, 192, 210, 0.1);
flex: none;
}
.growth-word {
position: relative;
color: #1BB0CE;
}
.growth-word::after {
content: "";
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 2px;
background: #1BB0CE;
animation: pulseUnderline 2.5s ease-in-out infinite;
}
@keyframes pulseUnderline {
0%, 100% { background-color: #1BB0CE; }
50% { background-color: rgba(180, 192, 210, 0.6); }
}
.stats-row {
display: flex;
justify-content: center;
margin-top: 32px;
gap: 0;
}
.stat {
flex: 1;
max-width: 120px;
text-align: center;
position: relative;
padding-top: 12px;
}
.stat::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 2px;
background: linear-gradient(90deg, #1BB0CE, rgba(180,192,210,1), #1BB0CE);
background-size: 200% 100%;
animation: statSweep 2.5s ease-in-out infinite;
}
.stat:nth-child(2)::before {
animation-delay: 0.6s;
}
.stat:nth-child(3)::before {
animation-delay: 1.2s;
}
@keyframes statSweep {
0% { background-position: 0% 0; }
100% { background-position: -200% 0; }
}
.stat-number {
font-size: 24px;
font-weight: 700;
color: #1BB0CE;
line-height: 1.2;
}
.stat-label {
font-size: 11px;
color: rgba(232,232,239,0.3);
margin-top: 4px;
letter-spacing: 0.3px;
}
.testimonial {
border-left: 2px solid rgba(27,176,206,0.25);
background: rgba(27,176,206,0.06);
padding: 10px 14px;
}
.stars-canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
}
.wave-canvas {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 200px;
z-index: 0;
pointer-events: none;
background: #0a0a0f;
}
.accent-line {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 2px;
background: linear-gradient(90deg, transparent, #1BB0CE, rgba(232,232,239,0.15), transparent);
animation: pulseAccent 3s ease-in-out infinite;
}
@keyframes pulseAccent {
0%, 100% { opacity: 0.5; }
50% { opacity: 1; }
}
.input-sheen {
position: relative;
overflow: hidden;
border-radius: 4px;
}
.input-sheen::before {
content: "";
position: absolute;
top: -10%;
left: -100%;
width: 60%;
height: 120%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.08), transparent);
transform: rotate(-15deg);
animation: sheenFloat 3.2s ease-in-out infinite;
pointer-events: none;
z-index: 2;
}
.input-sheen-delayed::before {
animation-delay: 1s;
}
.input-sheen:focus-within::before {
animation: none;
opacity: 0;
}
@keyframes sheenFloat {
0% { left: -100%; }
100% { left: 200%; }
}
.login-input {
width: 100%;
height: 44px;
background: linear-gradient(135deg, #0d0d15, #151520, #0d0d15);
background-size: 200% 200%;
animation: bgShift 6s ease-in-out infinite;
border: 1.5px solid rgba(180,192,210,0.15);
border-radius: 4px;
font-size: 13px;
color: #e8e8ef;
padding: 0 12px;
position: relative;
z-index: 1;
transition: border-color 0.2s ease, background 0.2s ease;
box-sizing: border-box;
}
.login-input::placeholder {
color: rgba(232,232,239,0.2);
}
.login-input:focus {
border-color: #1BB0CE;
outline: none;
background: #111118;
animation: none;
}
@keyframes bgShift {
0%, 100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
.password-toggle {
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: rgba(232,232,239,0.3);
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
z-index: 3;
}
.password-toggle:hover {
color: rgba(232,232,239,0.5);
}
.login-checkbox {
accent-color: #1BB0CE;
width: 16px;
height: 16px;
cursor: pointer;
}
.auth-btn {
width: 100%;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
background: #1BB0CE;
color: #ffffff;
font-size: 14px;
font-weight: 700;
padding: 13px;
border-radius: 4px;
border: none;
cursor: pointer;
position: relative;
overflow: hidden;
transition: background 0.2s ease;
}
.auth-btn:hover {
background: #17a0bc;
}
.auth-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.auth-btn::before {
content: "";
position: absolute;
top: 0;
left: -100%;
width: 60%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
animation: btnSweep 2.2s ease-in-out infinite;
pointer-events: none;
}
@keyframes btnSweep {
0% { left: -100%; }
100% { left: 200%; }
}
.login-label {
font-size: 12px;
font-weight: 600;
color: rgba(232,232,239,0.4);
display: block;
margin-bottom: 6px;
}
.body-text { color: rgba(232,232,239,0.5); }
.subheading-text { color: rgba(232,232,239,0.38); }
.checkbox-text { color: rgba(232,232,239,0.38); }
.footer-text { color: rgba(232,232,239,0.2); }
+40
View File
@@ -0,0 +1,40 @@
import type { Metadata, Viewport } from "next"
import { Inter } from "next/font/google"
import { ThemeProvider } from "@/providers/theme-provider"
import { Toaster } from "@/components/ui/sonner"
import "./globals.css"
const inter = Inter({
variable: "--font-inter",
subsets: ["latin"],
})
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
}
export const metadata: Metadata = {
title: "CRM",
description: "Customer Relationship Management System",
icons: {
icon: "/logo/CompanyMiniLogo.png",
},
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={`${inter.variable} min-h-screen antialiased`}>
<ThemeProvider attribute="class" defaultTheme="dark" disableTransitionOnChange>
{children}
<Toaster />
</ThemeProvider>
</body>
</html>
)
}
+7
View File
@@ -0,0 +1,7 @@
export default function LoginLayout({
children,
}: {
children: React.ReactNode
}) {
return children
}
+406
View File
@@ -0,0 +1,406 @@
"use client"
import { useState, useEffect, useRef } from "react"
import { useRouter } from "next/navigation"
import { COMPANY_NAME } from "@/lib/constants"
import { Eye, EyeOff, Loader2 } from "lucide-react"
const waves = [
{ a: 16, f: 0.011, s: 0.018, y: 0.38, fill: "rgba(27,176,206,0.18)" },
{ a: 20, f: 0.008, s: 0.013, y: 0.52, fill: "rgba(27,176,206,0.25)" },
{ a: 12, f: 0.015, s: 0.025, y: 0.28, fill: "rgba(180,192,210,0.06)" },
{ a: 26, f: 0.006, s: 0.010, y: 0.65, fill: "rgba(180,192,210,0.15)" },
{ a: 10, f: 0.019, s: 0.030, y: 0.20, fill: "rgba(27,176,206,0.10)" },
]
export default function LoginPage() {
const router = useRouter()
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [showPassword, setShowPassword] = useState(false)
const [loading, setLoading] = useState(false)
const [remember, setRemember] = useState(false)
const [error, setError] = useState("")
const [counts, setCounts] = useState({ leads: 0, conversion: 0, users: 0 })
const counterStarted = useRef(false)
const [testimonialIndex, setTestimonialIndex] = useState(0)
const testimonials = [
{
text: "This CRM transformed how we manage our sales pipeline. We've seen a 40% increase in lead conversion.",
author: "Marcus Johnson, Sales Lead at Coast IT",
},
{
text: "When you're not sure, flip a coin, because when the coin is in the air, you realize which option you're actually hoping for.",
author: "Dillen van der Merwe, Madman of Coast IT",
},
]
useEffect(() => {
const timer = setInterval(() => {
setTestimonialIndex((prev) => (prev + 1) % testimonials.length)
}, 5000)
return () => clearInterval(timer)
}, [testimonials.length])
const canvasRef = useRef<HTMLCanvasElement>(null)
const starsCanvasRightRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext("2d")
if (!ctx) return
let animId: number
let time = 0
const resize = () => {
const parent = canvas.parentElement!
const rect = parent.getBoundingClientRect()
const dpr = window.devicePixelRatio || 1
canvas.width = rect.width * dpr
canvas.height = 200 * dpr
canvas.style.width = rect.width + "px"
canvas.style.height = "200px"
ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)
}
resize()
window.addEventListener("resize", resize)
const draw = () => {
const w = canvas.width / (window.devicePixelRatio || 1)
const h = 200
ctx!.clearRect(0, 0, w, h)
for (const wave of waves) {
ctx!.beginPath()
ctx!.moveTo(0, h)
for (let x = 0; x <= w; x++) {
const y = wave.y * h + Math.sin(x * wave.f + time * wave.s) * wave.a
ctx!.lineTo(x, y)
}
ctx!.lineTo(w, h)
ctx!.closePath()
ctx!.fillStyle = wave.fill
ctx!.fill()
}
time += 1
animId = requestAnimationFrame(draw)
}
animId = requestAnimationFrame(draw)
return () => {
cancelAnimationFrame(animId)
window.removeEventListener("resize", resize)
}
}, [])
useEffect(() => {
const canvases = [starsCanvasRightRef.current].filter(Boolean) as HTMLCanvasElement[]
if (canvases.length === 0) return
const stars = Array.from({ length: 312 }, () => ({
x: Math.random(),
y: Math.random(),
r: 0.2 + Math.random() * 0.6,
baseOpacity: 0.12 + Math.random() * 0.43,
speed: 0.003 + Math.random() * 0.015,
phase: Math.random() * Math.PI * 2,
driftX: (Math.random() - 0.5) * 0.00003,
driftY: (Math.random() - 0.5) * 0.00003,
}))
let animId: number
let time = 0
const resize = () => {
for (const c of canvases) {
const dpr = window.devicePixelRatio || 1
const rect = c.getBoundingClientRect()
c.width = rect.width * dpr
c.height = rect.height * dpr
const ctx = c.getContext("2d")
if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
}
}
resize()
const ros = canvases.map((c) => {
const ro = new ResizeObserver(() => resize())
ro.observe(c.parentElement!)
return ro
})
window.addEventListener("resize", resize)
const draw = () => {
time += 1
for (const c of canvases) {
const dpr = window.devicePixelRatio || 1
const w = c.width / dpr
const h = c.height / dpr
const ctx = c.getContext("2d")
if (!ctx) continue
ctx.clearRect(0, 0, w, h)
for (const star of stars) {
const x = ((star.x + time * star.driftX) % 1) * w
const y = ((star.y + time * star.driftY) % 1) * h
const opacity = star.baseOpacity * (0.5 + 0.5 * Math.sin(time * star.speed + star.phase))
ctx.beginPath()
ctx.arc(x, y, star.r, 0, Math.PI * 2)
ctx.fillStyle = `rgba(255,255,255,${opacity})`
ctx.fill()
if (star.r > 0.5) {
ctx.beginPath()
ctx.arc(x, y, star.r * 1.8, 0, Math.PI * 2)
ctx.fillStyle = `rgba(255,255,255,${opacity * 0.06})`
ctx.fill()
}
}
}
animId = requestAnimationFrame(draw)
}
animId = requestAnimationFrame(draw)
return () => {
cancelAnimationFrame(animId)
ros.forEach((ro) => ro.disconnect())
window.removeEventListener("resize", resize)
}
}, [])
useEffect(() => {
if (counterStarted.current) return
counterStarted.current = true
const targets = { leads: 1247, conversion: 40, users: 83 }
const steps = 150
const delayTimer = setTimeout(() => {
let step = 0
const interval = setInterval(() => {
step++
if (step >= steps) {
clearInterval(interval)
setCounts(targets)
return
}
setCounts({
leads: Math.min(Math.floor((targets.leads / steps) * step), targets.leads),
conversion: Math.min(Math.floor((targets.conversion / steps) * step), targets.conversion),
users: Math.min(Math.floor((targets.users / steps) * step), targets.users),
})
}, 15)
}, 400)
return () => clearTimeout(delayTimer)
}, [])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError("")
setLoading(true)
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
})
if (res.ok) {
router.push("/dashboard")
} else {
const data = await res.json().catch(() => ({}))
setError(data.error || "Invalid email or password.")
}
} catch {
setError("Connection error. Please try again.")
} finally {
setLoading(false)
}
}
return (
<div className="flex min-h-screen bg-[#0a0a0f]">
<div className="left-panel flex flex-1 flex-col p-12">
<div className="relative z-10">
<img
src="/logo/CompanyLogo.png"
alt={COMPANY_NAME}
className="h-44 w-auto object-contain"
/>
</div>
<div className="relative z-10 flex-1 flex items-center justify-center">
<div className="text-center">
<h1 className="text-[34px] font-extrabold text-[#e8e8ef] leading-tight tracking-[-0.6px]">
Your Agency&apos;s{" "}
<span className="growth-word">Growth</span>{" "}
Starts Here
</h1>
<p className="mt-4 text-[13px] leading-[1.7] max-w-[360px] mx-auto body-text">
Manage leads, track conversions, and grow your web development business with our CRM.
</p>
<div className="stats-row">
<div className="stat">
<div className="stat-number">{counts.leads.toLocaleString()}</div>
<div className="stat-label">leads tracked</div>
</div>
<div className="stat">
<div className="stat-number">{counts.conversion}%</div>
<div className="stat-label">conversion lift</div>
</div>
<div className="stat">
<div className="stat-number">{counts.users}</div>
<div className="stat-label">active users</div>
</div>
</div>
</div>
</div>
<div className="relative z-10 testimonial" style={{ background: "rgba(255,255,255,0.7)", padding: "16px 20px 16px 16px", clipPath: "url(#testimonialClip)" }}>
<svg width="0" height="0" style={{ position: "absolute" }}>
<defs>
<clipPath id="testimonialClip" clipPathUnits="objectBoundingBox">
<path d="M0,0 L0.92,0 C0.96,0 1,0.03 1,0.08 C1,0.14 0.97,0.22 0.9,0.3 C0.85,0.36 0.83,0.42 0.83,0.5 C0.83,0.58 0.85,0.64 0.9,0.7 C0.97,0.78 1,0.86 1,0.92 C1,0.97 0.96,1 0.92,1 L0,1 Z" />
</clipPath>
</defs>
</svg>
<div className="transition-opacity duration-500" key={testimonialIndex}>
<p className="text-sm font-semibold leading-relaxed" style={{ color: "#0a0a0f" }}>
&ldquo;{testimonials[testimonialIndex].text}&rdquo;
</p>
<p className="text-xs font-bold mt-2" style={{ color: "#0a0a0f" }}>
{testimonials[testimonialIndex].author}
</p>
</div>
<div className="flex items-center justify-center gap-1.5 mt-3">
{testimonials.map((_, i) => (
<button
key={i}
type="button"
onClick={() => setTestimonialIndex(i)}
className={`h-1.5 rounded-full transition-all duration-300 ${i === testimonialIndex ? "w-5 bg-[#1BB0CE]" : "w-1.5 bg-[#1BB0CE]/30"}`}
/>
))}
</div>
</div>
<canvas ref={canvasRef} className="wave-canvas" />
</div>
<div className="panel-divider" />
<div className="right-panel flex items-center justify-center p-10">
<canvas ref={starsCanvasRightRef} className="stars-canvas" />
<div className="accent-line" />
<div className="w-full" style={{ maxWidth: 340 }}>
<h2 className="text-[24px] font-bold text-[#e8e8ef] tracking-[-0.3px] mb-[5px]">
Welcome back
</h2>
<p className="text-[13px] mb-[26px] subheading-text">
Sign in to your account to continue
</p>
{error && (
<div className="mb-4 rounded bg-red-500/10 px-4 py-2 text-sm text-red-400">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-5">
<div>
<label htmlFor="email" className="login-label">
Email
</label>
<div className="input-sheen">
<input
id="email"
type="email"
placeholder="name@company.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoComplete="email"
className="login-input"
/>
</div>
</div>
<div>
<div className="flex items-center justify-between mb-[6px]">
<label htmlFor="password" className="login-label" style={{ marginBottom: 0 }}>
Password
</label>
<button type="button" className="text-[12px] text-[#1BB0CE] hover:underline">
Forgot password?
</button>
</div>
<div className="input-sheen input-sheen-delayed">
<div className="relative">
<input
id="password"
type={showPassword ? "text" : "password"}
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
autoComplete="current-password"
className="login-input"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="password-toggle"
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
</div>
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={remember}
onChange={(e) => setRemember(e.target.checked)}
className="login-checkbox"
/>
<span className="text-[13px] checkbox-text">
Remember me
</span>
</label>
<button type="submit" className="auth-btn" disabled={loading}>
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
{loading ? "Signing in..." : "Sign in"}
</button>
</form>
<p className="text-center text-[11px] mt-4 footer-text">
By signing in, you agree to our{" "}
<button type="button" className="text-[#1BB0CE] hover:underline">
Terms of Service
</button>{" "}
and{" "}
<button type="button" className="text-[#1BB0CE] hover:underline">
Privacy Policy
</button>
</p>
</div>
</div>
</div>
)
}
+30
View File
@@ -0,0 +1,30 @@
"use client"
import Link from "next/link"
import { motion } from "framer-motion"
import { Button } from "@/components/ui/button"
import { FileQuestion } from "lucide-react"
export default function NotFound() {
return (
<div className="flex min-h-screen items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
className="flex flex-col items-center text-center"
>
<div className="flex h-24 w-24 items-center justify-center rounded-full bg-muted">
<FileQuestion className="h-12 w-12 text-muted-foreground" />
</div>
<h1 className="mt-6 text-4xl font-bold">404</h1>
<p className="mt-2 text-lg text-muted-foreground">Page not found</p>
<p className="mt-1 text-sm text-muted-foreground">
The page you are looking for does not exist.
</p>
<Link href="/dashboard" className="mt-6">
<Button>Go Home</Button>
</Link>
</motion.div>
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation"
export default function RootPage() {
redirect("/dashboard")
}
+222
View File
@@ -0,0 +1,222 @@
"use client"
import { useState, useRef, useEffect } from "react"
import { Send, Loader2, Bot, User, RefreshCw, AlertCircle } from "lucide-react"
interface ChatMessage {
role: "user" | "assistant"
content: string
}
export function AIChat() {
const [messages, setMessages] = useState<ChatMessage[]>([])
const [input, setInput] = useState("")
const [loading, setLoading] = useState(false)
const [error, setError] = useState("")
const [ollamaStatus, setOllamaStatus] = useState<boolean | null>(null)
const messagesEndRef = useRef<HTMLDivElement>(null)
useEffect(() => {
fetch("/api/ai/jobs")
.then((r) => r.json())
.then((data) => {
if (data.jobs?.length) {
const jobNames = data.jobs.map((j: { job_title: string }) => j.job_title).join(", ")
setMessages([
{
role: "assistant",
content: `Hi! I'm your Sales AI Assistant. I can help you with tips for targeting: ${jobNames}. What would you like to know?`,
},
])
} else {
setMessages([
{
role: "assistant",
content: "Hi! I'm your Sales AI Assistant. Ask me anything about sales strategies and prospect targeting.",
},
])
}
})
.catch(() => {
setMessages([
{
role: "assistant",
content: "Hi! I'm your Sales AI Assistant. Ask me anything about sales strategies and prospect targeting.",
},
])
})
fetch("/api/ai/jobs")
.then((r) => r.json())
.then((data) => {
if (data.jobs) {
const names = data.jobs.map((j: { job_title: string }) => j.job_title)
setMessages([
{
role: "assistant",
content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `${n}`).join("\n")}\n\nWhat would you like to know?`,
},
])
}
})
}, [])
useEffect(() => {
fetch("/api/ai/jobs")
.then((r) => r.json())
.then((data) => {
if (data.jobs?.length) {
const names = data.jobs.map((j: { job_title: string }) => j.job_title)
setMessages((prev) =>
prev.length === 1 && prev[0].role === "assistant"
? [
{
role: "assistant",
content: `Hi! I'm your Sales AI Assistant. I can help with tips for targeting:\n\n${names.map((n: string) => `${n}`).join("\n")}\n\nWhat would you like to know?`,
},
]
: prev,
)
}
})
}, [])
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
}, [messages])
const checkOllama = async () => {
try {
const res = await fetch("/api/ai/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "__ping__" }),
})
setOllamaStatus(res.status !== 503)
} catch {
setOllamaStatus(false)
}
}
useEffect(() => { checkOllama() }, [])
const sendMessage = async () => {
const msg = input.trim()
if (!msg || loading) return
setInput("")
setError("")
setMessages((prev) => [...prev, { role: "user", content: msg }])
setLoading(true)
try {
const res = await fetch("/api/ai/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: msg }),
})
if (!res.ok) {
const data = await res.json()
throw new Error(data.error || "Failed to get response")
}
const data = await res.json()
setMessages((prev) => [...prev, { role: "assistant", content: data.response }])
} catch (err) {
const errMsg = err instanceof Error ? err.message : "AI service unavailable"
setError(errMsg)
setMessages((prev) => [
...prev,
{ role: "assistant", content: `⚠️ Error: ${errMsg}. Make sure Ollama is running with the model loaded.` },
])
} finally {
setLoading(false)
}
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault()
sendMessage()
}
}
return (
<div className="flex flex-col h-full">
{ollamaStatus === false && (
<div className="flex items-center gap-2 px-4 py-2 bg-amber-500/10 border-b border-amber-500/20 text-amber-400 text-xs">
<AlertCircle className="h-3.5 w-3.5 flex-none" />
<span className="flex-1">Ollama not responding. Start it with <code className="bg-amber-500/20 px-1 rounded">ollama serve</code></span>
<button type="button" onClick={checkOllama} className="hover:text-amber-300">
<RefreshCw className="h-3.5 w-3.5" />
</button>
</div>
)}
<div className="flex-1 overflow-y-auto p-4 space-y-4 scrollbar-thin">
{messages.map((msg, i) => (
<div key={i} className={`flex gap-3 ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
{msg.role === "assistant" && (
<div className="h-8 w-8 rounded-full bg-[#1BB0CE]/20 flex items-center justify-center flex-none">
<Bot className="h-4 w-4 text-[#1BB0CE]" />
</div>
)}
<div
className={`max-w-[75%] rounded-lg px-4 py-2.5 text-sm leading-relaxed whitespace-pre-wrap ${
msg.role === "user"
? "bg-[#1BB0CE] text-white"
: "bg-[#1a1a24] text-[#c8c8d0] border border-[#2a2a35]"
}`}
>
{msg.content}
</div>
{msg.role === "user" && (
<div className="h-8 w-8 rounded-full bg-[#1BB0CE] flex items-center justify-center flex-none">
<User className="h-4 w-4 text-white" />
</div>
)}
</div>
))}
{loading && (
<div className="flex gap-3 justify-start">
<div className="h-8 w-8 rounded-full bg-[#1BB0CE]/20 flex items-center justify-center flex-none">
<Bot className="h-4 w-4 text-[#1BB0CE]" />
</div>
<div className="max-w-[75%] rounded-lg px-4 py-2.5 bg-[#1a1a24] border border-[#2a2a35]">
<Loader2 className="h-4 w-4 animate-spin text-[#1BB0CE]" />
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
<div className="border-t border-[#2a2a35] p-4">
{error && (
<div className="mb-2 text-xs text-red-400 flex items-center gap-1.5">
<AlertCircle className="h-3 w-3" />
{error}
</div>
)}
<div className="flex gap-2">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask for sales tips..."
rows={1}
className="flex-1 bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-[#e8e8ef] placeholder-[#6a6a75] resize-none outline-none focus:border-[#1BB0CE]/50"
/>
<button
type="button"
onClick={sendMessage}
disabled={loading || !input.trim()}
className="h-9 w-9 rounded-lg bg-[#1BB0CE] hover:bg-[#1BB0CE]/80 disabled:opacity-40 flex items-center justify-center flex-none transition-colors"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,74 @@
"use client"
import { useState, useEffect } from "react"
import { Briefcase, ChevronDown, Loader2 } from "lucide-react"
interface Job {
job_title: string
keywords: string[]
industry: string
description: string
}
interface JobSelectorProps {
onSelect: (job: Job | null) => void
}
export function JobSelector({ onSelect }: JobSelectorProps) {
const [jobs, setJobs] = useState<Job[]>([])
const [loading, setLoading] = useState(true)
const [open, setOpen] = useState(false)
const [selected, setSelected] = useState<Job | null>(null)
useEffect(() => {
fetch("/api/ai/jobs")
.then((r) => r.json())
.then((data) => setJobs(data.jobs || []))
.catch(() => setJobs([]))
.finally(() => setLoading(false))
}, [])
const handleSelect = (job: Job) => {
setSelected(job)
setOpen(false)
onSelect(job)
}
return (
<div className="relative">
<button
type="button"
onClick={() => setOpen(!open)}
className="w-full flex items-center gap-2 bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2 text-sm text-[#e8e8ef] hover:border-[#1BB0CE]/50 transition-colors"
>
<Briefcase className="h-4 w-4 text-[#1BB0CE] flex-none" />
<span className="flex-1 text-left truncate">
{selected ? selected.job_title : loading ? "Loading jobs..." : "Select a job category"}
</span>
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ChevronDown className="h-3.5 w-3.5 text-[#6a6a75]" />}
</button>
{open && (
<>
<div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
<div className="absolute top-full left-0 right-0 mt-1 z-20 bg-[#15151e] border border-[#2a2a35] rounded-lg shadow-xl max-h-60 overflow-y-auto">
{jobs.map((job, i) => (
<button
key={i}
type="button"
onClick={() => handleSelect(job)}
className="w-full text-left px-3 py-2.5 text-sm text-[#c8c8d0] hover:bg-[#1a1a24] hover:text-[#e8e8ef] transition-colors border-b border-[#1a1a24] last:border-0"
>
<div className="font-medium">{job.job_title}</div>
<div className="text-xs text-[#6a6a75] mt-0.5">{job.industry} {job.description}</div>
</button>
))}
{jobs.length === 0 && !loading && (
<div className="px-3 py-4 text-xs text-[#6a6a75] text-center">No job categories loaded</div>
)}
</div>
</>
)}
</div>
)
}
@@ -0,0 +1,192 @@
"use client"
import { useState } from "react"
import { motion } from "framer-motion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
interface StatusData {
name: string
value: number
color: string
}
interface LeadStatusChartProps {
data: StatusData[]
}
function polar(cx: number, cy: number, r: number, deg: number) {
const rad = ((deg - 90) * Math.PI) / 180
return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) }
}
function arcPath(cx: number, cy: number, oR: number, iR: number, start: number, end: number) {
const gap = 3
const s = start + gap / 2
const e = end - gap / 2
const o1 = polar(cx, cy, oR, s)
const o2 = polar(cx, cy, oR, e)
const i1 = polar(cx, cy, iR, e)
const i2 = polar(cx, cy, iR, s)
const lg = e - s > 180 ? 1 : 0
return `M${o1.x} ${o1.y} A${oR} ${oR} 0 ${lg} 1 ${o2.x} ${o2.y} L${i1.x} ${i1.y} A${iR} ${iR} 0 ${lg} 0 ${i2.x} ${i2.y}Z`
}
export function LeadStatusChart({ data }: LeadStatusChartProps) {
const [hov, setHov] = useState<number | null>(null)
const total = data.reduce((s, d) => s + d.value, 0)
if (total === 0) {
return (
<Card className="h-full">
<CardHeader>
<CardTitle>Lead Status</CardTitle>
</CardHeader>
<CardContent>
<div className="flex items-center justify-center h-[400px] text-sm text-muted-foreground">
No data for this period
</div>
</CardContent>
</Card>
)
}
let cum = 0
const segs = data.map((d) => {
const start = cum
const deg = (d.value / total) * 360
cum += deg
return { ...d, start, end: cum, deg, pct: Math.round((d.value / total) * 100) }
})
const active = hov !== null ? segs[hov] : null
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.2 }}
className="h-full"
>
<Card className="h-full">
<CardHeader>
<CardTitle>Lead Status</CardTitle>
</CardHeader>
<CardContent className="flex flex-1 flex-col">
<div className="flex flex-1 flex-col items-center justify-center">
{/* Donut */}
<svg width="100%" height="100%" viewBox="0 0 320 320" className="max-h-full overflow-visible" style={{ maxWidth: "280px" }}>
<defs>
{segs.map((s, i) => (
<radialGradient key={i} id={`chart-grad-${i}`} cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor={s.color} stopOpacity="1" />
<stop offset="100%" stopColor={s.color} stopOpacity="0.75" />
</radialGradient>
))}
</defs>
{/* Background ring */}
<circle cx="160" cy="160" r="105" fill="none" stroke="hsl(var(--muted))" strokeWidth="52" />
{/* Segments */}
{segs.map((s, i) => {
const isH = hov === i
const oR = isH ? 137 : 130
const iR = isH ? 73 : 80
return (
<path
key={i}
d={arcPath(160, 160, oR, iR, s.start, s.end)}
fill={`url(#chart-grad-${i})`}
opacity={hov !== null && !isH ? 0.3 : 1}
style={{
cursor: "pointer",
transition: "all 0.22s cubic-bezier(.4,0,.2,1)",
filter: isH ? `drop-shadow(0 0 10px ${s.color}99)` : "none",
}}
onMouseEnter={() => setHov(i)}
onMouseLeave={() => setHov(null)}
/>
)
})}
{/* Center circle */}
<circle cx="160" cy="160" r="66" fill="hsl(var(--card))" />
<circle cx="160" cy="160" r="66" fill="none" stroke="hsl(var(--border))" strokeWidth="1" />
{/* Center text */}
{active ? (
<>
<circle cx="160" cy="160" r="66" fill={active.color + "15"} />
<text x="160" y="148" textAnchor="middle" fill="hsl(var(--foreground))" fontSize="30" fontWeight="700" fontFamily="-apple-system,sans-serif">
{active.value}
</text>
<text x="160" y="166" textAnchor="middle" fill="hsl(var(--muted-foreground))" fontSize="12" fontFamily="-apple-system,sans-serif">
{active.name}
</text>
<text x="160" y="184" textAnchor="middle" fill={active.color} fontSize="13" fontWeight="600" fontFamily="-apple-system,sans-serif">
{active.pct}%
</text>
</>
) : (
<>
<text x="160" y="152" textAnchor="middle" fill="hsl(var(--foreground))" fontSize="34" fontWeight="700" fontFamily="-apple-system,sans-serif">
{total}
</text>
<text x="160" y="172" textAnchor="middle" fill="hsl(var(--muted-foreground))" fontSize="12" fontFamily="-apple-system,sans-serif">
Total Leads
</text>
</>
)}
</svg>
{/* Legend */}
<div className="mt-6 grid w-full grid-cols-2 gap-2">
{segs.map((s, i) => (
<div
key={i}
onMouseEnter={() => setHov(i)}
onMouseLeave={() => setHov(null)}
className="flex cursor-pointer items-center gap-2.5 rounded-xl p-2.5 transition-all duration-200"
style={{
background: hov === i ? `${s.color}18` : "hsl(var(--muted) / 0.3)",
border: `1px solid ${hov === i ? s.color + "50" : "hsl(var(--border))"}`,
gridColumn: i === segs.length - 1 && segs.length % 2 !== 0 ? "1 / -1" : undefined,
maxWidth: i === segs.length - 1 && segs.length % 2 !== 0 ? "50%" : undefined,
margin: i === segs.length - 1 && segs.length % 2 !== 0 ? "0 auto" : undefined,
width: i === segs.length - 1 && segs.length % 2 !== 0 ? "100%" : undefined,
}}
>
<div
className="h-2.5 w-2.5 shrink-0 rounded-full transition-shadow duration-200"
style={{
background: s.color,
boxShadow: hov === i ? `0 0 8px ${s.color}` : "none",
}}
/>
<div className="min-w-0 flex-1">
<div
className="text-xs font-medium transition-colors duration-200"
style={{ color: hov === i ? "hsl(var(--foreground))" : "hsl(var(--muted-foreground))" }}
>
{s.name}
</div>
<div className="mt-0.5 text-[11px]" style={{ color: "hsl(var(--muted-foreground) / 0.7)" }}>
{s.value} &middot; {s.pct}%
</div>
</div>
<div
className="text-xs font-semibold transition-colors duration-200"
style={{ color: hov === i ? s.color : "hsl(var(--muted-foreground) / 0.5)" }}
>
{s.pct}%
</div>
</div>
))}
</div>
</div>
</CardContent>
</Card>
</motion.div>
)
}
@@ -0,0 +1,311 @@
"use client"
import { useState, useMemo, useEffect } from "react"
import { motion } from "framer-motion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { ChevronLeft, ChevronRight } from "lucide-react"
interface IntervalData {
label: string
leads: number
closed: number
}
interface LeadsPerMonthChartProps {
data: IntervalData[]
}
const NEW_LEADS = "#0d9488"
const CLOSED = "#c9a96e"
export function LeadsPerMonthChart({ data: initialData }: LeadsPerMonthChartProps) {
const [year, setYear] = useState(new Date().getFullYear())
const [chartData, setChartData] = useState<IntervalData[]>(initialData)
const [hovered, setHovered] = useState<number | null>(null)
useEffect(() => {
setChartData(initialData)
}, [initialData])
useEffect(() => {
async function fetchYearData() {
try {
const res = await fetch(`/api/dashboard?year=${year}`)
if (res.ok) {
const data = await res.json()
setChartData(data.leadsPerMonth || [])
}
} catch {
// ignore
}
}
const thisYear = new Date().getFullYear()
if (year !== thisYear || initialData.length === 0) {
fetchYearData()
} else {
setChartData(initialData)
}
}, [year, initialData])
const width = 880
const height = 620
const padding = { top: 128, right: 24, bottom: 48, left: 44 }
const chartW = width - padding.left - padding.right
const chartH = height - padding.top - padding.bottom
const maxVal = useMemo(() => {
if (chartData.length === 0) return 1
const max = Math.max(...chartData.map((d) => Math.max(d.leads, d.closed)))
return Math.max(Math.ceil(max / 7) * 7, 1)
}, [chartData])
const ticks = useMemo(() => {
const steps = 4
return Array.from({ length: steps + 1 }, (_, i) => Math.round((maxVal / steps) * i))
}, [maxVal])
const groupW = chartW / Math.max(chartData.length, 1)
const barW = groupW * 0.28
const gap = groupW * 0.06
const yScale = (v: number) => chartH - (v / maxVal) * chartH
const active = hovered
const activeDatum = active !== null ? chartData[active] : null
const totalNew = chartData.reduce((s, d) => s + d.leads, 0)
const totalClosed = chartData.reduce((s, d) => s + d.closed, 0)
const closeRate = totalNew > 0 ? Math.round((totalClosed / totalNew) * 100) : 0
const currentYear = new Date().getFullYear()
if (chartData.length === 0) {
return (
<Card className="h-full">
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Leads Per Month</CardTitle>
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setYear((y) => y - 1)}>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="min-w-[60px] text-center text-sm font-medium">{year}</span>
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => setYear((y) => Math.min(y + 1, currentYear))} disabled={year >= currentYear}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="flex items-center justify-center h-[400px] text-sm text-muted-foreground">
No data for {year}
</div>
</CardContent>
</Card>
)
}
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.3 }}
className="h-full"
>
<Card className="h-full">
<CardHeader>
<div className="flex items-start justify-between">
<div>
<CardTitle>Leads Per Month</CardTitle>
<p className="mt-1 text-sm text-muted-foreground">
{totalNew} new &middot; {totalClosed} closed &middot; {closeRate}% close rate
</p>
</div>
<div className="flex items-center gap-4">
<div className="flex items-center gap-1.5">
<span className="inline-block h-2.5 w-2.5 rounded-sm" style={{ background: NEW_LEADS }} />
<span className="text-xs text-muted-foreground">New Leads</span>
</div>
<div className="flex items-center gap-1.5">
<span className="inline-block h-2.5 w-2.5 rounded-sm" style={{ background: CLOSED }} />
<span className="text-xs text-muted-foreground">Closed</span>
</div>
<div className="ml-2 flex items-center gap-1 rounded-lg border px-2 py-1">
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setYear((y) => y - 1)}>
<ChevronLeft className="h-3.5 w-3.5" />
</Button>
<span className="min-w-[50px] text-center text-sm font-semibold">{year}</span>
<Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => setYear((y) => Math.min(y + 1, currentYear))} disabled={year >= currentYear}>
<ChevronRight className="h-3.5 w-3.5" />
</Button>
</div>
</div>
</div>
</CardHeader>
<CardContent className="flex flex-1 flex-col">
<div className="relative flex-1">
<svg
viewBox={`0 0 ${width} ${height}`}
width="100%"
height="100%"
className="block overflow-visible"
>
<defs>
<linearGradient id="newLeadsGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#0d9488" />
<stop offset="100%" stopColor={NEW_LEADS} />
</linearGradient>
<linearGradient id="closedGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#e8d5a3" />
<stop offset="100%" stopColor={CLOSED} />
</linearGradient>
<filter id="shadowNew">
<feDropShadow dx="0" dy="2" stdDeviation="4" floodColor={NEW_LEADS} floodOpacity="0.4" />
</filter>
<filter id="shadowClosed">
<feDropShadow dx="0" dy="2" stdDeviation="4" floodColor={CLOSED} floodOpacity="0.4" />
</filter>
</defs>
<g transform={`translate(${padding.left}, ${padding.top})`}>
{/* Grid lines */}
{ticks.map((t, i) => (
<g key={i}>
<line
x1={0}
x2={chartW}
y1={yScale(t)}
y2={yScale(t)}
stroke="hsl(var(--border))"
strokeDasharray={t === 0 ? "0" : "3 5"}
strokeWidth={1}
/>
<text
x={-12}
y={yScale(t)}
fill="hsl(var(--muted-foreground))"
fontSize={12}
textAnchor="end"
dominantBaseline="middle"
>
{t}
</text>
</g>
))}
{/* Bars */}
{chartData.map((d, i) => {
const groupX = i * groupW
const isActive = active === i
const newH = chartH - yScale(d.leads)
const closedH = chartH - yScale(d.closed)
return (
<g
key={d.label}
onMouseEnter={() => setHovered(i)}
onMouseLeave={() => setHovered(null)}
style={{ cursor: "pointer" }}
>
<rect
x={groupX}
y={0}
width={groupW}
height={chartH}
fill={isActive ? "hsl(var(--muted) / 0.5)" : "transparent"}
rx={6}
/>
<rect
x={groupX + groupW / 2 - barW - gap / 2}
y={yScale(d.leads)}
width={barW}
height={newH}
rx={4}
fill="url(#newLeadsGrad)"
filter={isActive ? "url(#shadowNew)" : undefined}
opacity={hovered !== null && !isActive ? 0.35 : 1}
style={{ transition: "opacity 0.15s ease" }}
/>
<rect
x={groupX + groupW / 2 + gap / 2}
y={yScale(d.closed)}
width={barW}
height={closedH}
rx={4}
fill="url(#closedGrad)"
filter={isActive ? "url(#shadowClosed)" : undefined}
opacity={hovered !== null && !isActive ? 0.35 : 1}
style={{ transition: "opacity 0.15s ease" }}
/>
<text
x={groupX + groupW / 2}
y={chartH + 26}
fill={isActive ? "hsl(var(--foreground))" : "hsl(var(--muted-foreground))"}
fontSize={12.5}
fontWeight={isActive ? 600 : 400}
textAnchor="middle"
>
{d.label}
</text>
</g>
)
})}
</g>
</svg>
{activeDatum && (
<div
className="pointer-events-none absolute top-0"
style={{
left: `${((active! + 0.5) / chartData.length) * 100}%`,
transform: active! > chartData.length - 2
? "translate(-100%, 0)"
: "translate(-12%, 0)",
transition: "left 0.15s ease",
}}
>
<div
className="min-w-[150px] rounded-xl border p-3 shadow-xl"
style={{
background: "hsl(var(--popover))",
borderColor: "hsl(var(--border))",
}}
>
<div className="mb-1.5 text-xs font-semibold" style={{ color: "hsl(var(--foreground))" }}>
{activeDatum.label}
</div>
<div className="mb-1 flex items-center justify-between gap-4 text-xs" style={{ color: "hsl(var(--muted-foreground))" }}>
<span className="flex items-center gap-1.5">
<span className="inline-block h-2 w-2 rounded-sm" style={{ background: NEW_LEADS }} />
New Leads
</span>
<span className="font-semibold" style={{ color: "hsl(var(--foreground))" }}>{activeDatum.leads}</span>
</div>
<div className="mb-1 flex items-center justify-between gap-4 text-xs" style={{ color: "hsl(var(--muted-foreground))" }}>
<span className="flex items-center gap-1.5">
<span className="inline-block h-2 w-2 rounded-sm" style={{ background: CLOSED }} />
Closed
</span>
<span className="font-semibold" style={{ color: "hsl(var(--foreground))" }}>{activeDatum.closed}</span>
</div>
<div
className="mt-1.5 border-t pt-1.5 text-[11px]"
style={{ borderColor: "hsl(var(--border))", color: "hsl(var(--muted-foreground))" }}
>
{activeDatum.leads > 0
? `${Math.round((activeDatum.closed / activeDatum.leads) * 100)}% close rate`
: "No leads"}
</div>
</div>
</div>
)}
</div>
</CardContent>
</Card>
</motion.div>
)
}
@@ -0,0 +1,97 @@
"use client"
import Link from "next/link"
import { motion } from "framer-motion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Lead } from "@/types"
import { ArrowRight } from "lucide-react"
const statusStyles: Record<string, string> = {
open: "bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20",
contacted: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",
pending: "bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20",
closed: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20",
ignored: "bg-zinc-500/10 text-zinc-600 dark:text-zinc-400 border-zinc-500/20",
}
interface RecentLeadsTableProps {
leads: Lead[]
}
export function RecentLeadsTable({ leads }: RecentLeadsTableProps) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.4 }}
>
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Recent Leads</CardTitle>
<Link
href="/leads"
className="flex items-center gap-1 text-sm text-primary hover:underline"
>
View all <ArrowRight className="h-3 w-3" />
</Link>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="pb-3 font-medium">Company</th>
<th className="pb-3 font-medium">Contact</th>
<th className="hidden pb-3 font-medium md:table-cell">Status</th>
<th className="hidden pb-3 font-medium lg:table-cell">Assigned</th>
<th className="hidden pb-3 font-medium sm:table-cell">Date</th>
</tr>
</thead>
<tbody>
{leads.map((lead, i) => (
<motion.tr
key={lead.id}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: i * 0.03 }}
className="border-b last:border-0 hover:bg-muted/30"
>
<td className="py-3">
<Link href={`/leads/${lead.id}`} className="font-medium hover:text-primary">
{lead.companyName}
</Link>
</td>
<td className="py-3 text-muted-foreground">{lead.contactName}</td>
<td className="hidden py-3 md:table-cell">
<Badge variant="outline" className={statusStyles[lead.status]}>
{lead.status.charAt(0).toUpperCase() + lead.status.slice(1)}
</Badge>
</td>
<td className="hidden py-3 lg:table-cell">
{lead.assignedUser ? (
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
<AvatarImage src={lead.assignedUser.avatar} />
<AvatarFallback>{lead.assignedUser.name[0]}</AvatarFallback>
</Avatar>
<span className="text-muted-foreground">{lead.assignedUser.name}</span>
</div>
) : (
<span className="text-muted-foreground/50">Unassigned</span>
)}
</td>
<td className="hidden py-3 text-muted-foreground sm:table-cell">
{new Date(lead.createdAt).toLocaleDateString()}
</td>
</motion.tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
</motion.div>
)
}
@@ -0,0 +1,20 @@
"use client"
import { Card, CardContent } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
export function StatCardSkeleton() {
return (
<Card className="h-full">
<CardContent className="p-6 flex flex-col">
<div className="flex items-center justify-between">
<div className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-8 w-16" />
</div>
<Skeleton className="h-12 w-12 rounded-xl" />
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,196 @@
"use client"
import { useEffect, useState } from "react"
import { motion } from "framer-motion"
import { cn } from "@/lib/utils"
import { Card, CardContent } from "@/components/ui/card"
import { LucideIcon } from "lucide-react"
interface StatCardProps {
title: string
value: string | number
icon: LucideIcon
description?: string
index?: number
trend?: { pct: number; up: boolean }
sparklineField?: "total" | "open" | "contacted" | "pending" | "closed" | "ignored"
monthlyBreakdown?: { label: string; total: number; open: number; contacted: number; pending: number; closed: number; ignored: number }[]
conversionRate?: number
}
const cardColors: Record<string, { bg: string; text: string; glow: string; accent: string }> = {
"Total Leads": { bg: "bg-cyan-500/10", text: "text-cyan-600 dark:text-cyan-400", glow: "via-[rgba(6,182,212,0.25)]", accent: "#06b6d4" },
"Open Leads": { bg: "bg-blue-500/10", text: "text-blue-600 dark:text-blue-400", glow: "via-[rgba(59,130,246,0.25)]", accent: "#3b82f6" },
"Contacted": { bg: "bg-amber-500/10", text: "text-amber-600 dark:text-amber-400", glow: "via-[rgba(245,158,11,0.25)]", accent: "#f59e0b" },
"Pending": { bg: "bg-violet-500/10", text: "text-violet-600 dark:text-violet-400", glow: "via-[rgba(139,92,246,0.25)]", accent: "#8b5cf6" },
"Closed": { bg: "bg-yellow-500/10", text: "text-yellow-600 dark:text-yellow-400", glow: "via-[rgba(234,179,8,0.25)]", accent: "#eab308" },
"Conversion Rate": { bg: "bg-rose-500/10", text: "text-rose-600 dark:text-rose-400", glow: "via-[rgba(244,63,94,0.25)]", accent: "#f43f5e" },
}
function computeGoal(max: number): number {
if (max <= 0) return 100
return Math.ceil(max / 100) * 100 || 100
}
function smoothPath(points: { x: number; y: number }[]): string {
if (points.length === 0) return ""
if (points.length === 1) return `M${points[0].x.toFixed(1)},${points[0].y.toFixed(1)}`
let d = `M${points[0].x.toFixed(1)},${points[0].y.toFixed(1)}`
for (let i = 1; i < points.length - 1; i++) {
const p0 = points[i - 1]
const p1 = points[i]
const p2 = points[i + 1]
const cp1x = p1.x - (p2.x - p0.x) * 0.15
const cp1y = p1.y - (p2.y - p0.y) * 0.15
const cp2x = p1.x + (p2.x - p0.x) * 0.15
const cp2y = p1.y + (p2.y - p0.y) * 0.15
d += `C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${p2.x.toFixed(1)},${p2.y.toFixed(1)}`
}
return d
}
export function StatCard({ title, value, icon: Icon, description, index = 0, trend, sparklineField, monthlyBreakdown, conversionRate }: StatCardProps) {
const color = cardColors[title] ?? cardColors["Total Leads"]
const isNumeric = typeof value === "number"
const [display, setDisplay] = useState(0)
const target = typeof value === "number" ? value : 0
useEffect(() => {
if (!isNumeric) return
const duration = 1000
const steps = 40
const increment = target / steps
let current = 0
const timer = setInterval(() => {
current += increment
if (current >= target) {
setDisplay(target)
clearInterval(timer)
} else {
setDisplay(Math.floor(current))
}
}, duration / steps)
return () => clearInterval(timer)
}, [target, isNumeric])
function buildSparklineSvg(): { path: string; area: string; goal: number; gridLines: { y: number }[] } {
if (!monthlyBreakdown || !sparklineField) return { path: "", area: "", goal: 100, gridLines: [] }
const values = monthlyBreakdown.map((m) => m[sparklineField]).reverse()
const max = Math.max(...values, 0)
const goal = computeGoal(max)
const dataRange = Math.max(max, 1)
const range = goal <= 10 ? Math.max(dataRange * 2, 10) : Math.min(goal, Math.max(dataRange * 3, 10))
const w = values.length - 1 || 1
const pad = 4
const graphW = 60 - pad * 2
const graphH = 28
const points = values.map((v, i) => ({
x: pad + (i / w) * graphW,
y: graphH - (v / range) * (graphH - 3) - 1,
}))
const smooth = smoothPath(points)
const area = points.length > 0
? `${smooth} L${points[points.length - 1].x.toFixed(1)},${graphH} L${points[0].x.toFixed(1)},${graphH} Z`
: ""
const steps = 4
const gridLines = Array.from({ length: steps - 1 }, (_, i) => ({
y: graphH - ((i + 1) / steps) * (graphH - 3) - 1,
}))
return { path: smooth, area, goal, gridLines }
}
const { path: sparkPath, area: sparkArea, goal, gridLines } = buildSparklineSvg()
const sparkColor = color.accent
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: index * 0.05 }}
className="relative"
>
<Card className="group h-full hover:shadow-md transition-all duration-200">
<CardContent className="p-6 flex flex-col">
<div className="flex items-center justify-between">
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground">{title}</p>
<p className="text-3xl font-bold tracking-tight">
{isNumeric ? display : value}
</p>
{description && (
<p className="text-xs text-muted-foreground">{description}</p>
)}
{trend && (
<span className={cn(
"inline-flex items-center gap-0.5 text-xs font-semibold",
trend.up ? "text-emerald-500" : "text-rose-500"
)}>
{trend.up ? "↑" : "↓"} {trend.pct}%
</span>
)}
</div>
<div className={cn("flex h-12 w-12 items-center justify-center rounded-xl shrink-0", color.bg)}>
<Icon className={cn("h-6 w-6", color.text)} />
</div>
</div>
{sparkPath && (
<div className="mt-auto relative">
<svg width="60" height="28" viewBox="0 0 60 28" className="opacity-60 group-hover:opacity-100 transition-opacity duration-200">
<defs>
<linearGradient id={`spark-fill-${title.replace(/\s/g, "")}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={sparkColor} stopOpacity="0.2" />
<stop offset="100%" stopColor={sparkColor} stopOpacity="0" />
</linearGradient>
<filter id={`glow-${title.replace(/\s/g, "")}`}>
<feGaussianBlur stdDeviation="2" result="blur" />
<feMerge>
<feMergeNode in="blur" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
{gridLines.map((gl, i) => (
<line key={i} x1="0" y1={gl.y} x2="60" y2={gl.y} stroke="currentColor" strokeOpacity="0.08" strokeWidth="1" strokeDasharray="2,2" />
))}
<path d={sparkArea} fill={`url(#spark-fill-${title.replace(/\s/g, "")})`} />
<path
d={sparkPath}
fill="none"
stroke={sparkColor}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="animate-pulse"
filter={`url(#glow-${title.replace(/\s/g, "")})`}
/>
</svg>
<span className="absolute -bottom-0.5 right-0 text-[9px] font-medium text-muted-foreground/60">
/{goal}
</span>
</div>
)}
{title === "Conversion Rate" && conversionRate !== undefined && (
<div className="mt-3">
<div className="w-full h-1.5 bg-muted rounded-full overflow-hidden">
<div className="h-full rounded-full bg-gradient-to-r from-[#f43f5e] to-[#fda4af]" style={{ width: `${Math.min(conversionRate, 100)}%` }} />
</div>
<p className="text-xs text-muted-foreground mt-1">{conversionRate}% conversion rate</p>
</div>
)}
</CardContent>
<div className={cn(
"absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent to-transparent",
color.glow
)} />
</Card>
</motion.div>
)
}
@@ -0,0 +1,69 @@
"use client"
import { useState, useEffect } from "react"
import { usePathname } from "next/navigation"
import { motion, AnimatePresence } from "framer-motion"
import { Sidebar } from "./sidebar"
import { Topbar } from "./topbar"
import { SystemMonitor } from "./system-monitor"
interface AppShellProps {
children: React.ReactNode
}
export function AppShell({ children }: AppShellProps) {
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
const [mobileOpen, setMobileOpen] = useState(false)
const pathname = usePathname()
// Close mobile sidebar on route change
useEffect(() => {
setMobileOpen(false)
}, [pathname])
// Persist sidebar state
useEffect(() => {
const saved = localStorage.getItem("sidebar-collapsed")
if (saved) setSidebarCollapsed(saved === "true")
}, [])
const toggleSidebar = () => {
const next = !sidebarCollapsed
setSidebarCollapsed(next)
localStorage.setItem("sidebar-collapsed", String(next))
}
return (
<div className="min-h-screen bg-background">
<SystemMonitor />
<Sidebar
collapsed={sidebarCollapsed}
onToggle={toggleSidebar}
mobileOpen={mobileOpen}
onMobileClose={() => setMobileOpen(false)}
/>
<div className={cn("transition-all duration-300", sidebarCollapsed ? "lg:ml-16" : "lg:ml-64")}>
<Topbar onMenuClick={() => setMobileOpen(true)} />
<main className="flex-1 p-4 lg:p-6">
<AnimatePresence mode="wait">
<motion.div
key={pathname}
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
transition={{ duration: 0.2 }}
>
{children}
</motion.div>
</AnimatePresence>
</main>
</div>
</div>
)
}
function cn(...classes: (string | boolean | undefined | null)[]) {
return classes.filter(Boolean).join(" ")
}
@@ -0,0 +1,217 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { motion, AnimatePresence } from "framer-motion"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
import {
LayoutDashboard,
Users,
Settings,
ChevronLeft,
ChevronRight,
Building2,
PanelLeftClose,
MessageSquare,
Bot,
} from "lucide-react"
import { COMPANY_NAME } from "@/lib/constants"
import { useUser } from "@/providers/user-provider"
import { useNotifications } from "@/providers/notification-provider"
const navItems = [
{ href: "/dashboard", label: "Dashboard", icon: LayoutDashboard },
{ href: "/leads", label: "Leads", icon: Users },
{ href: "/chats", label: "Chats", icon: MessageSquare },
{ href: "/ai-assistant", label: "AI Assistant", icon: Bot, roles: ["sales", "admin", "super_admin"] },
{ href: "/users", label: "Users", icon: Building2 },
{ href: "/settings", label: "Settings", icon: Settings },
]
interface SidebarProps {
collapsed: boolean
onToggle: () => void
mobileOpen: boolean
onMobileClose: () => void
}
export function Sidebar({ collapsed, onToggle, mobileOpen, onMobileClose }: SidebarProps) {
const pathname = usePathname()
const { user } = useUser()
const { unreadChatCount } = useNotifications()
if (!user) return null
const initials = user.name.split(" ").map((n) => n[0]).join("")
const sidebarContent = (
<div
className={cn(
"flex h-full flex-col bg-sidebar text-sidebar-foreground transition-all duration-300",
collapsed ? "w-16" : "w-64"
)}
>
{/* Logo */}
<div className={cn("flex h-16 items-center border-b border-sidebar-border px-4", collapsed ? "justify-center" : "justify-between")}>
<Link href="/" className="flex items-center gap-3 overflow-hidden">
<img
src="/logo/CompanyLogo.png"
alt={COMPANY_NAME}
className="h-8 w-8 shrink-0 rounded-lg object-contain"
/>
<AnimatePresence mode="wait">
{!collapsed && (
<motion.span
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -10 }}
transition={{ duration: 0.15 }}
className="text-sm font-semibold whitespace-nowrap"
>
{COMPANY_NAME}
</motion.span>
)}
</AnimatePresence>
</Link>
{!collapsed && (
<Button
variant="ghost"
size="icon"
onClick={onToggle}
className="h-6 w-6 text-sidebar-foreground/60 hover:text-sidebar-foreground"
>
<PanelLeftClose className="h-4 w-4" />
</Button>
)}
</div>
{/* Navigation */}
<nav className="flex-1 space-y-1 p-3">
{navItems.filter((item) => !item.roles || item.roles.includes(user.role)).map((item) => {
const isActive = pathname === item.href || (item.href !== "/" && pathname.startsWith(item.href))
return collapsed ? (
<TooltipProvider key={item.href} delayDuration={0}>
<Tooltip>
<TooltipTrigger asChild>
<Link
href={item.href}
className={cn(
"relative flex h-10 w-10 items-center justify-center rounded-lg transition-colors",
isActive
? "bg-sidebar-primary text-sidebar-primary-foreground"
: "text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
)}
>
<item.icon className="h-5 w-5" />
{item.label === "Chats" && unreadChatCount > 0 && (
<span className="absolute -right-0.5 -top-0.5 flex h-3 w-3 rounded-full bg-red-500 animate-pulse shadow-[0_0_10px_#ef4444]" />
)}
</Link>
</TooltipTrigger>
<TooltipContent side="right" className="ml-2">
{item.label}
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<Link
key={item.href}
href={item.href}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
isActive
? "bg-sidebar-primary text-sidebar-primary-foreground"
: "text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
)}
>
<div className="relative shrink-0">
<item.icon className="h-5 w-5" />
{item.label === "Chats" && unreadChatCount > 0 && (
<span className="absolute -right-1 -top-1 flex h-2.5 w-2.5 rounded-full bg-red-500 animate-pulse shadow-[0_0_8px_#ef4444]" />
)}
</div>
<motion.span
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="truncate"
>
{item.label}
</motion.span>
</Link>
)
})}
</nav>
{/* Collapse toggle at bottom (only in collapsed mode) */}
{collapsed && (
<div className="border-t border-sidebar-border p-3">
<Button
variant="ghost"
size="icon"
onClick={onToggle}
className="h-10 w-10 text-sidebar-foreground/60 hover:text-sidebar-foreground"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
)}
{/* User info */}
<div className={cn("border-t border-sidebar-border p-3", collapsed && "flex justify-center")}>
{collapsed ? (
<Avatar className="h-10 w-10">
<AvatarImage src={user.avatar} />
<AvatarFallback className="text-sm font-medium">{initials}</AvatarFallback>
</Avatar>
) : (
<div className="flex items-center gap-3">
<Avatar className="h-9 w-9">
<AvatarImage src={user.avatar} />
<AvatarFallback className="text-sm font-medium">{initials}</AvatarFallback>
</Avatar>
<div className="flex-1 overflow-hidden">
<p className="text-sm font-medium truncate">{user.name}</p>
<p className="text-xs text-sidebar-foreground/60 truncate capitalize">{user.role}</p>
</div>
</div>
)}
</div>
</div>
)
return (
<>
{/* Desktop sidebar */}
<aside className="hidden lg:fixed lg:inset-y-0 lg:z-30 lg:flex">
{sidebarContent}
</aside>
{/* Mobile sidebar overlay */}
<AnimatePresence>
{mobileOpen && (
<>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onMobileClose}
className="fixed inset-0 z-40 bg-black/60 lg:hidden"
/>
<motion.aside
initial={{ x: -300 }}
animate={{ x: 0 }}
exit={{ x: -300 }}
transition={{ type: "spring", damping: 30, stiffness: 300 }}
className="fixed inset-y-0 left-0 z-50 lg:hidden"
>
{sidebarContent}
</motion.aside>
</>
)}
</AnimatePresence>
</>
)
}
@@ -0,0 +1,43 @@
"use client"
import { useState, useEffect } from "react"
const RAM_LIMIT_MB = 8192
const CPU_LIMIT_PCT = 400 // 4 cores * 100%
export function SystemMonitor() {
const [rssMB, setRssMB] = useState(0)
const [cpuPct, setCpuPct] = useState(0)
useEffect(() => {
const fetchStats = async () => {
try {
const res = await fetch("/api/system/monitor")
if (!res.ok) return
const data = await res.json()
setRssMB(data.rssMB)
setCpuPct(data.cpuPct)
} catch {
// ignore
}
}
fetchStats()
const interval = setInterval(fetchStats, 3000)
return () => clearInterval(interval)
}, [])
const ramOver = rssMB > RAM_LIMIT_MB
const cpuOver = cpuPct > CPU_LIMIT_PCT
return (
<div className="fixed top-0 left-0 z-[9999] flex items-center gap-3 px-3 py-1 text-[11px] font-mono bg-black/80 rounded-br-lg select-none">
<span className={ramOver ? "text-red-400" : "text-green-400"}>
RAM: {rssMB}MB / 8192MB
</span>
<span className={cpuOver ? "text-red-400" : "text-green-400"}>
CPU: {cpuPct}%
</span>
</div>
)
}
@@ -0,0 +1,245 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useTheme } from "next-themes";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useUser } from "@/providers/user-provider";
import { useNotifications } from "@/providers/notification-provider";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import {
Search,
Bell,
Sun,
Moon,
Menu,
LogOut,
User,
Settings,
CheckCheck,
Trash2,
} from "lucide-react";
interface TopbarProps {
onMenuClick: () => void;
}
export function Topbar({ onMenuClick }: TopbarProps) {
const router = useRouter();
const { theme, setTheme } = useTheme();
const { user, logout } = useUser();
const { notifications, unreadCount, markAsRead, markAllAsRead, dismiss } =
useNotifications();
const [mounted, setMounted] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!user) return null;
function formatTimeAgo(ts: string): string {
const diff = Date.now() - new Date(ts).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return "Just now";
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
if (days < 7) return `${days}d ago`;
return new Date(ts).toLocaleDateString();
}
const initials = user.name
.split(" ")
.map((n: string) => n[0])
.join("")
.toUpperCase();
return (
<header className="sticky top-0 z-20 flex h-16 items-center gap-4 border-b bg-background px-4 lg:px-6">
{/* Logo */}
<div className="flex items-center gap-2 mr-2 shrink-0">
<div className="w-3 h-3 rounded-full bg-[#0d9488]" />
<span className="text-[#0d9488] font-bold text-sm tracking-wide">
CRM
</span>
</div>
{/* Mobile menu button */}
<Button
variant="ghost"
size="icon"
className="lg:hidden"
onClick={onMenuClick}
>
<Menu className="h-5 w-5" />
</Button>
{/* Search */}
<div className="relative hidden flex-1 sm:block md:w-80">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search leads, companies..."
className="h-9 w-full max-w-sm pl-9 bg-muted/50"
/>
</div>
<div className="flex flex-1 items-center justify-end gap-3">
{/* Mobile search toggle */}
<Button
variant="ghost"
size="icon"
className="sm:hidden"
onClick={() => setSearchOpen(!searchOpen)}
>
<Search className="h-5 w-5" />
</Button>
{/* Theme toggle */}
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
className="text-muted-foreground"
>
{mounted ? (
theme === "dark" ? (
<Sun className="h-5 w-5" />
) : (
<Moon className="h-5 w-5" />
)
) : (
<div className="h-5 w-5" />
)}
</Button>
{/* Notifications */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="relative text-muted-foreground"
>
<Bell className="h-5 w-5" />
<span className="absolute -right-0.5 -top-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-[10px] font-medium text-primary-foreground">
{unreadCount}
</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80">
<DropdownMenuLabel className="flex items-center justify-between">
<span>Notifications</span>
{notifications.length > 0 && (
<button
onClick={markAllAsRead}
className="flex items-center gap-1 text-xs text-primary hover:underline"
>
<CheckCheck className="h-3 w-3" />
Mark all read
</button>
)}
</DropdownMenuLabel>
<DropdownMenuSeparator />
{notifications.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">
No notifications
</div>
) : (
<div className="max-h-[360px] space-y-1 overflow-y-auto p-2">
{notifications.slice(0, 20).map((n) => (
<div
key={n.id}
role="button"
tabIndex={0}
onClick={() => {
if (!n.read) markAsRead(n.id);
if (n.link) router.push(n.link);
}}
className={`flex cursor-pointer items-start gap-3 rounded-lg p-2 transition-colors hover:bg-muted/50 ${!n.read ? "bg-muted/30" : ""}`}
>
<div
className={`mt-2 h-2 w-2 shrink-0 rounded-full ${n.read ? "bg-transparent" : "bg-primary"}`}
/>
<div className="flex-1 space-y-0.5">
<p className="text-sm font-medium">{n.title}</p>
<p className="text-xs text-muted-foreground">
{n.description}
</p>
<p className="text-[10px] text-muted-foreground/60">
{formatTimeAgo(n.timestamp)}
</p>
</div>
<button
onClick={(e) => {
e.stopPropagation();
dismiss(n.id);
}}
className="mt-1 shrink-0 text-muted-foreground/40 hover:text-destructive"
>
<Trash2 className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
</DropdownMenuContent>
</DropdownMenu>
{/* User profile */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="relative h-9 gap-2 pl-2 pr-3">
<Avatar className="h-7 w-7">
<AvatarImage src={user.avatar} />
<AvatarFallback>{initials}</AvatarFallback>
</Avatar>
<span className="hidden text-sm font-medium md:inline-block">
{user.name}
</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium">{user.name}</p>
<p className="text-xs text-muted-foreground">{user.email}</p>
<Badge
variant="secondary"
className="mt-1 w-fit text-xs capitalize"
>
{user.role}
</Badge>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => router.push("/profile")}>
<User className="mr-2 h-4 w-4" />
Profile
</DropdownMenuItem>
<DropdownMenuItem onClick={() => router.push("/settings")}>
<Settings className="mr-2 h-4 w-4" />
Settings
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive" onClick={logout}>
<LogOut className="mr-2 h-4 w-4" />
Log out
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</header>
);
}
@@ -0,0 +1,46 @@
"use client"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Lead } from "@/types"
interface DeleteLeadDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
lead: Lead
}
export function DeleteLeadDialog({ open, onOpenChange, lead }: DeleteLeadDialogProps) {
const handleDelete = () => {
console.log("Delete lead:", lead.id)
onOpenChange(false)
}
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Lead</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete <strong>{lead.companyName}</strong>? This action
cannot be undone. All associated notes and data will be permanently removed.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
@@ -0,0 +1,66 @@
"use client"
import { useState } from "react"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Lead } from "@/types"
import { LeadFormDialog } from "./lead-form-dialog"
import { DeleteLeadDialog } from "./delete-lead-dialog"
import { MoreHorizontal, Eye, Edit, Trash2, UserCheck } from "lucide-react"
interface LeadActionsDropdownProps {
lead: Lead
}
export function LeadActionsDropdown({ lead }: LeadActionsDropdownProps) {
const [editOpen, setEditOpen] = useState(false)
const [deleteOpen, setDeleteOpen] = useState(false)
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[160px]">
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem asChild>
<Link href={`/leads/${lead.id}`}>
<Eye className="mr-2 h-4 w-4" />
View
</Link>
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setEditOpen(true)}>
<Edit className="mr-2 h-4 w-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem>
<UserCheck className="mr-2 h-4 w-4" />
Assign
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => setDeleteOpen(true)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<LeadFormDialog open={editOpen} onOpenChange={setEditOpen} lead={lead} />
<DeleteLeadDialog open={deleteOpen} onOpenChange={setDeleteOpen} lead={lead} />
</>
)
}
@@ -0,0 +1,91 @@
"use client"
import { motion } from "framer-motion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { LeadStatusBadge } from "./lead-status-badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Lead } from "@/types"
import {
Building2,
Mail,
Phone,
Globe,
User,
CalendarDays,
Clock,
Tag,
} from "lucide-react"
interface LeadDetailsCardProps {
lead: Lead
}
export function LeadDetailsCard({ lead }: LeadDetailsCardProps) {
const fields = [
{ icon: Building2, label: "Company", value: lead.companyName },
{ icon: User, label: "Contact", value: lead.contactName },
{ icon: Mail, label: "Email", value: lead.email },
{ icon: Phone, label: "Phone", value: lead.phone || "—" },
{ icon: Globe, label: "Source", value: lead.source || "—" },
{ icon: Tag, label: "Status", value: <LeadStatusBadge status={lead.status} /> },
{ icon: CalendarDays, label: "Created", value: new Date(lead.createdAt).toLocaleDateString() },
{ icon: Clock, label: "Updated", value: new Date(lead.updatedAt).toLocaleDateString() },
]
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<Card>
<CardHeader>
<CardTitle>Lead Information</CardTitle>
</CardHeader>
<CardContent>
<div className="grid gap-6 sm:grid-cols-2">
{fields.map((field, i) => (
<div key={i} className="flex items-start gap-3">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-muted">
<field.icon className="h-4 w-4 text-muted-foreground" />
</div>
<div className="space-y-0.5">
<p className="text-xs text-muted-foreground">{field.label}</p>
<div className="text-sm font-medium">{field.value}</div>
</div>
</div>
))}
</div>
{lead.description && (
<div className="mt-6 border-t pt-6">
<h4 className="mb-2 text-sm font-medium text-muted-foreground">Description</h4>
<p className="text-sm leading-relaxed">{lead.description}</p>
</div>
)}
<div className="mt-6 border-t pt-6">
<h4 className="mb-3 text-sm font-medium text-muted-foreground">Assigned User</h4>
{lead.assignedUser ? (
<div className="flex items-center gap-3">
<Avatar className="h-10 w-10">
<AvatarImage src={lead.assignedUser.avatar} />
<AvatarFallback>{lead.assignedUser.name[0]}</AvatarFallback>
</Avatar>
<div>
<p className="text-sm font-medium">{lead.assignedUser.name}</p>
<Badge variant="secondary" className="mt-0.5 text-xs">
{lead.assignedUser.role}
</Badge>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">No user assigned</p>
)}
</div>
</CardContent>
</Card>
</motion.div>
)
}
@@ -0,0 +1,287 @@
"use client"
import { useState, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Lead, LeadStatus, User } from "@/types"
import { LEAD_SOURCES, LEAD_STATUSES } from "@/lib/constants"
import { users } from "@/data/users"
import { useNotifications } from "@/providers/notification-provider"
const leadFormSchema = z.object({
companyName: z.string().min(1, "Company name is required"),
contactName: z.string().min(1, "Contact name is required"),
email: z.string().email("Invalid email address"),
phone: z.string().optional(),
source: z.string().optional(),
description: z.string().optional(),
status: z.string(),
assignedUserId: z.string().optional(),
})
type LeadFormValues = z.infer<typeof leadFormSchema>
interface LeadFormDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
lead?: Lead | null
}
export function LeadFormDialog({ open, onOpenChange, lead }: LeadFormDialogProps) {
const isEditing = !!lead
const { addNotification } = useNotifications()
const form = useForm<LeadFormValues>({
resolver: zodResolver(leadFormSchema),
defaultValues: {
companyName: "",
contactName: "",
email: "",
phone: "",
source: "",
description: "",
status: "open",
assignedUserId: "none",
},
})
useEffect(() => {
if (lead) {
form.reset({
companyName: lead.companyName,
contactName: lead.contactName,
email: lead.email,
phone: lead.phone || "",
source: lead.source || "",
description: lead.description || "",
status: lead.status,
assignedUserId: lead.assignedUserId || "none",
})
} else {
form.reset({
companyName: "",
contactName: "",
email: "",
phone: "",
source: "",
description: "",
status: "open",
assignedUserId: "none",
})
}
}, [lead, form])
function onSubmit(values: LeadFormValues) {
const payload = {
...values,
assignedUserId: values.assignedUserId === "none" ? null : values.assignedUserId,
}
if (!isEditing) {
const now = new Date().toISOString()
addNotification(
"lead_created",
"New Lead Created",
`${values.companyName}${values.contactName}`,
"#"
)
}
console.log(payload)
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Lead" : "Create New Lead"}</DialogTitle>
<DialogDescription>
{isEditing
? "Update the lead information below."
: "Fill in the details to add a new lead."}
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="companyName"
render={({ field }) => (
<FormItem>
<FormLabel>Company Name</FormLabel>
<FormControl>
<Input placeholder="Acme Corp" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="contactName"
render={({ field }) => (
<FormItem>
<FormLabel>Contact Name</FormLabel>
<FormControl>
<Input placeholder="John Doe" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="john@acme.com" type="email" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Phone</FormLabel>
<FormControl>
<Input placeholder="(555) 123-4567" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="source"
render={({ field }) => (
<FormItem>
<FormLabel>Source</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select source" />
</SelectTrigger>
</FormControl>
<SelectContent>
{LEAD_SOURCES.map((source) => (
<SelectItem key={source} value={source}>
{source}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="status"
render={({ field }) => (
<FormItem>
<FormLabel>Status</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select status" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(LEAD_STATUSES).map(([key, { label }]) => (
<SelectItem key={key} value={key}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Brief description of the lead and their requirements..."
className="min-h-[100px]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="assignedUserId"
render={({ field }) => (
<FormItem>
<FormLabel>Assign To</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select user" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="none">Unassigned</SelectItem>
{users.filter(u => u.active).map((user) => (
<SelectItem key={user.id} value={user.id}>
{user.name} ({user.role})
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit">{isEditing ? "Save Changes" : "Create Lead"}</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,49 @@
"use client"
import { Badge } from "@/components/ui/badge"
import { LeadStatus } from "@/types"
import { cn } from "@/lib/utils"
const statusConfig: Record<LeadStatus, { label: string; class: string }> = {
open: {
label: "Open",
class: "bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20",
},
contacted: {
label: "Contacted",
class: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",
},
pending: {
label: "Pending",
class: "bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20",
},
closed: {
label: "Closed",
class: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20",
},
ignored: {
label: "Ignored",
class: "bg-zinc-500/10 text-zinc-600 dark:text-zinc-400 border-zinc-500/20",
},
}
interface LeadStatusBadgeProps {
status: LeadStatus
className?: string
}
export function LeadStatusBadge({ status, className }: LeadStatusBadgeProps) {
const config = statusConfig[status]
return (
<Badge variant="outline" className={cn(config.class, className)}>
<span className={cn("mr-1.5 h-1.5 w-1.5 rounded-full", {
"bg-blue-500": status === "open",
"bg-amber-500": status === "contacted",
"bg-purple-500": status === "pending",
"bg-emerald-500": status === "closed",
"bg-zinc-500": status === "ignored",
})} />
{config.label}
</Badge>
)
}
@@ -0,0 +1,77 @@
"use client"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Search, Plus } from "lucide-react"
interface LeadsTableToolbarProps {
search: string
onSearchChange: (value: string) => void
statusFilter: string
onStatusFilterChange: (value: string) => void
periodFilter: string
onPeriodFilterChange: (value: string) => void
onCreateClick: () => void
}
export function LeadsTableToolbar({
search,
onSearchChange,
statusFilter,
onStatusFilterChange,
periodFilter,
onPeriodFilterChange,
onCreateClick,
}: LeadsTableToolbarProps) {
return (
<div className="flex flex-1 flex-col gap-4 sm:flex-row sm:items-center">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by name, company, email..."
value={search}
onChange={(e) => onSearchChange(e.target.value)}
className="h-9 pl-9 w-full sm:max-w-sm"
/>
</div>
<div className="flex items-center gap-3">
<Select value={periodFilter} onValueChange={onPeriodFilterChange}>
<SelectTrigger className="h-9 w-[150px]">
<SelectValue placeholder="All Time" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Time</SelectItem>
<SelectItem value="7days">Last 7 days</SelectItem>
<SelectItem value="30days">Last 30 days</SelectItem>
<SelectItem value="6months">Last 6 months</SelectItem>
<SelectItem value="12months">Last 12 months</SelectItem>
</SelectContent>
</Select>
<Select value={statusFilter} onValueChange={onStatusFilterChange}>
<SelectTrigger className="h-9 w-[140px]">
<SelectValue placeholder="All Statuses" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Statuses</SelectItem>
<SelectItem value="open">Open</SelectItem>
<SelectItem value="contacted">Contacted</SelectItem>
<SelectItem value="pending">Pending</SelectItem>
<SelectItem value="closed">Closed</SelectItem>
<SelectItem value="ignored">Ignored</SelectItem>
</SelectContent>
</Select>
<Button size="sm" className="h-9 gap-2" onClick={onCreateClick}>
<Plus className="h-4 w-4" />
<span className="hidden sm:inline">Create Lead</span>
</Button>
</div>
</div>
)
}
@@ -0,0 +1,135 @@
"use client"
import { useMemo } from "react"
import Link from "next/link"
import { ColumnDef } from "@tanstack/react-table"
import { DataTable } from "@/components/shared/data-table"
import { DataTableColumnHeader } from "@/components/shared/data-table-column-header"
import { LeadStatusBadge } from "./lead-status-badge"
import { LeadActionsDropdown } from "./lead-actions-dropdown"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Checkbox } from "@/components/ui/checkbox"
import { Lead } from "@/types"
interface LeadsTableProps {
data: Lead[]
loading?: boolean
}
export function LeadsTable({ data, loading }: LeadsTableProps) {
const columns: ColumnDef<Lead>[] = useMemo(
() => [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "companyName",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Company" />
),
cell: ({ row }) => (
<Link
href={`/leads/${row.original.id}`}
className="font-medium hover:text-primary transition-colors"
>
{row.getValue("companyName")}
</Link>
),
},
{
accessorKey: "contactName",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Contact" />
),
cell: ({ row }) => (
<span className="text-muted-foreground">{row.getValue("contactName")}</span>
),
},
{
accessorKey: "email",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Email" />
),
cell: ({ row }) => (
<span className="text-muted-foreground">{row.getValue("email")}</span>
),
},
{
accessorKey: "phone",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Phone" />
),
cell: ({ row }) => (
<span className="text-muted-foreground">{row.getValue("phone")}</span>
),
},
{
accessorKey: "status",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Status" />
),
cell: ({ row }) => <LeadStatusBadge status={row.getValue("status")} />,
},
{
accessorKey: "assignedUser",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Assigned" />
),
cell: ({ row }) => {
const user = row.original.assignedUser
if (!user) return <span className="text-muted-foreground/50"></span>
return (
<div className="flex items-center gap-2">
<Avatar className="h-6 w-6">
<AvatarImage src={user.avatar} />
<AvatarFallback>{user.name[0]}</AvatarFallback>
</Avatar>
<span className="text-muted-foreground text-sm">{user.name}</span>
</div>
)
},
},
{
accessorKey: "createdAt",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Date Added" />
),
cell: ({ row }) => (
<span className="text-muted-foreground">
{new Date(row.getValue("createdAt")).toLocaleDateString()}
</span>
),
},
{
id: "actions",
cell: ({ row }) => <LeadActionsDropdown lead={row.original} />,
},
],
[]
)
return (
<DataTable
columns={columns}
data={data}
loading={loading}
emptyMessage="No leads found."
/>
)
}
@@ -0,0 +1,68 @@
"use client"
import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Send } from "lucide-react"
interface NoteFormProps {
leadId: string
}
export function NoteForm({ leadId }: NoteFormProps) {
const [note, setNote] = useState("")
const [submitting, setSubmitting] = useState(false)
const handleSubmit = async () => {
if (!note.trim()) return
setSubmitting(true)
try {
await fetch(`/api/leads/${leadId}/notes`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: note }),
})
setNote("")
window.location.reload()
} catch {
// ignore
}
setSubmitting(false)
}
return (
<Card>
<CardHeader>
<CardTitle>Add Note</CardTitle>
</CardHeader>
<CardContent>
<div className="flex gap-4">
<Avatar className="h-10 w-10 shrink-0">
<AvatarImage src="https://ui-avatars.com/api/?name=Sarah+Chen&background=1d4ed8&color=fff&size=64" />
<AvatarFallback>SC</AvatarFallback>
</Avatar>
<div className="flex-1 space-y-3">
<Textarea
placeholder="Write a note about this lead..."
value={note}
onChange={(e) => setNote(e.target.value)}
className="min-h-[100px] resize-none"
/>
<div className="flex justify-end">
<Button
onClick={handleSubmit}
disabled={!note.trim() || submitting}
className="gap-2"
>
<Send className="h-4 w-4" />
{submitting ? "Adding..." : "Add Note"}
</Button>
</div>
</div>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,94 @@
"use client"
import { motion } from "framer-motion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Note } from "@/types"
import { EmptyState } from "@/components/shared/empty-state"
import { MessageSquare, Edit2, Trash2 } from "lucide-react"
interface NoteTimelineProps {
notes: Note[]
}
export function NoteTimeline({ notes }: NoteTimelineProps) {
if (notes.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle>Notes</CardTitle>
</CardHeader>
<CardContent>
<EmptyState
icon={MessageSquare}
title="No notes yet"
description="Add the first note to this lead."
/>
</CardContent>
</Card>
)
}
return (
<Card>
<CardHeader>
<CardTitle>Notes ({notes.length})</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-0">
{notes.map((note, i) => (
<motion.div
key={note.id}
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: i * 0.05 }}
className="relative flex gap-4 pb-8 last:pb-0"
>
{/* Timeline line */}
{i < notes.length - 1 && (
<div className="absolute left-5 top-12 bottom-0 w-px bg-border" />
)}
{/* Avatar */}
<div className="relative z-10 shrink-0">
<Avatar className="h-10 w-10">
<AvatarImage src={note.authorAvatar} />
<AvatarFallback>{note.authorName[0]}</AvatarFallback>
</Avatar>
</div>
{/* Content */}
<div className="flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium">{note.authorName}</span>
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
{note.authorRole}
</Badge>
<span className="text-xs text-muted-foreground">
{new Date(note.createdAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})}
</span>
</div>
<p className="text-sm leading-relaxed text-muted-foreground">{note.note}</p>
<div className="flex items-center gap-2 pt-1">
<Button variant="ghost" size="icon" className="h-6 w-6 text-muted-foreground/50 hover:text-muted-foreground">
<Edit2 className="h-3 w-3" />
</Button>
<Button variant="ghost" size="icon" className="h-6 w-6 text-muted-foreground/50 hover:text-destructive">
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
</motion.div>
))}
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,48 @@
"use client"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { COMPANY_NAME } from "@/lib/constants"
import { toast } from "sonner"
export function CompanySettingsForm() {
return (
<Card>
<CardHeader>
<CardTitle>Company Settings</CardTitle>
<CardDescription>
Manage your company information and branding.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="company-name">Company Name</Label>
<Input id="company-name" defaultValue={COMPANY_NAME} />
</div>
<div className="space-y-2">
<Label htmlFor="company-email">Company Email</Label>
<Input id="company-email" type="email" defaultValue="info@coastalit.com" />
</div>
<div className="space-y-2">
<Label htmlFor="company-phone">Phone</Label>
<Input id="company-phone" defaultValue="(555) 123-4567" />
</div>
<div className="space-y-2">
<Label htmlFor="company-website">Website</Label>
<Input id="company-website" defaultValue="https://coastalit.com" />
</div>
<div className="space-y-2 sm:col-span-2">
<Label htmlFor="company-address">Address</Label>
<Input id="company-address" defaultValue="123 Business Ave, Suite 100, San Francisco, CA 94105" />
</div>
</div>
<div className="flex justify-end pt-4">
<Button onClick={() => toast.success("Company settings saved")}>Save Changes</Button>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,116 @@
"use client"
import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
interface Preferences {
leadAssigned: boolean
leadStatus: boolean
noteAdded: boolean
dailyDigest: boolean
weeklyReport: boolean
}
const defaultPreferences: Preferences = {
leadAssigned: true,
leadStatus: true,
noteAdded: false,
dailyDigest: false,
weeklyReport: true,
}
const notifications = [
{ id: "leadAssigned", title: "Lead Assigned", description: "When a lead is assigned to you" },
{ id: "leadStatus", title: "Status Changes", description: "When a lead's status is updated" },
{ id: "noteAdded", title: "Note Added", description: "When a note is added to your lead" },
{ id: "dailyDigest", title: "Daily Digest", description: "Receive a daily summary of lead activity" },
{ id: "weeklyReport", title: "Weekly Report", description: "Receive a weekly performance report" },
]
export function NotificationSettings() {
const [prefs, setPrefs] = useState<Preferences>(defaultPreferences)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
useEffect(() => {
async function load() {
try {
const res = await fetch("/api/notifications/preferences")
if (res.ok) {
const data = await res.json()
setPrefs(data)
}
} catch {
// ignore
} finally {
setLoading(false)
}
}
load()
}, [])
async function handleSave() {
setSaving(true)
try {
const res = await fetch("/api/notifications/preferences", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(prefs),
})
if (res.ok) {
toast.success("Notification preferences saved")
} else {
toast.error("Failed to save preferences")
}
} catch {
toast.error("Failed to save preferences")
} finally {
setSaving(false)
}
}
function toggle(key: keyof Preferences) {
setPrefs((prev) => ({ ...prev, [key]: !prev[key] }))
}
return (
<Card>
<CardHeader>
<CardTitle>Notification Settings</CardTitle>
<CardDescription>
Configure which notifications you want to receive.
</CardDescription>
</CardHeader>
<CardContent className="space-y-0">
{notifications.map((n, i) => (
<div
key={n.id}
className={`flex items-center justify-between py-4 ${i < notifications.length - 1 ? "border-b" : ""}`}
>
<div className="space-y-0.5">
<Label htmlFor={n.id} className="text-sm font-medium">
{n.title}
</Label>
<p className="text-sm text-muted-foreground">{n.description}</p>
</div>
<Switch
id={n.id}
disabled={loading}
checked={prefs[n.id as keyof Preferences]}
onCheckedChange={() => toggle(n.id as keyof Preferences)}
/>
</div>
))}
<div className="flex justify-end pt-4">
<Button onClick={handleSave} disabled={loading || saving}>
{saving ? "Saving..." : "Save Preferences"}
</Button>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,48 @@
"use client"
import { useTheme } from "next-themes"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { cn } from "@/lib/utils"
import { Sun, Moon, Monitor } from "lucide-react"
export function ThemeSettings() {
const { theme, setTheme } = useTheme()
const options = [
{ value: "light", icon: Sun, label: "Light" },
{ value: "dark", icon: Moon, label: "Dark" },
{ value: "system", icon: Monitor, label: "System" },
]
return (
<Card>
<CardHeader>
<CardTitle>Theme Settings</CardTitle>
<CardDescription>
Choose your preferred appearance for the dashboard.
</CardDescription>
</CardHeader>
<CardContent>
<RadioGroup value={theme} onValueChange={setTheme} className="grid grid-cols-3 gap-4">
{options.map(({ value, icon: Icon, label }) => (
<div key={value}>
<RadioGroupItem value={value} id={value} className="peer sr-only" />
<Label
htmlFor={value}
className={cn(
"flex flex-col items-center gap-3 rounded-lg border-2 p-4 hover:bg-accent cursor-pointer transition-all",
"peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5"
)}
>
<Icon className="h-6 w-6" />
<span className="text-sm font-medium">{label}</span>
</Label>
</div>
))}
</RadioGroup>
</CardContent>
</Card>
)
}
@@ -0,0 +1,74 @@
"use client"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
export function UserPreferencesForm() {
return (
<Card>
<CardHeader>
<CardTitle>User Preferences</CardTitle>
<CardDescription>
Customize your experience and default settings.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="timezone">Timezone</Label>
<Select defaultValue="america-los_angeles">
<SelectTrigger id="timezone">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="america-new_york">Eastern Time (ET)</SelectItem>
<SelectItem value="america-chicago">Central Time (CT)</SelectItem>
<SelectItem value="america-denver">Mountain Time (MT)</SelectItem>
<SelectItem value="america-los_angeles">Pacific Time (PT)</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="date-format">Date Format</Label>
<Select defaultValue="mdy">
<SelectTrigger id="date-format">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="mdy">MM/DD/YYYY</SelectItem>
<SelectItem value="dmy">DD/MM/YYYY</SelectItem>
<SelectItem value="ymd">YYYY-MM-DD</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="items-per-page">Items Per Page</Label>
<Select defaultValue="20">
<SelectTrigger id="items-per-page">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="flex justify-end pt-4">
<Button onClick={() => toast.success("Preferences saved")}>Save Preferences</Button>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,66 @@
"use client"
import { Column } from "@tanstack/react-table"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { ArrowDown, ArrowUp, ArrowUpDown, EyeOff } from "lucide-react"
interface DataTableColumnHeaderProps<TData, TValue> extends React.HTMLAttributes<HTMLDivElement> {
column: Column<TData, TValue>
title: string
}
export function DataTableColumnHeader<TData, TValue>({
column,
title,
className,
}: DataTableColumnHeaderProps<TData, TValue>) {
if (!column.getCanSort()) {
return <div className={cn(className)}>{title}</div>
}
return (
<div className={cn("flex items-center space-x-2", className)}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="-ml-3 h-8 data-[state=open]:bg-accent"
>
<span>{title}</span>
{column.getIsSorted() === "desc" ? (
<ArrowDown className="ml-2 h-4 w-4" />
) : column.getIsSorted() === "asc" ? (
<ArrowUp className="ml-2 h-4 w-4" />
) : (
<ArrowUpDown className="ml-2 h-4 w-4" />
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem onClick={() => column.toggleSorting(false)}>
<ArrowUp className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
Asc
</DropdownMenuItem>
<DropdownMenuItem onClick={() => column.toggleSorting(true)}>
<ArrowDown className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
Desc
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => column.toggleVisibility(false)}>
<EyeOff className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
Hide
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}
@@ -0,0 +1,84 @@
"use client"
import { Table } from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from "lucide-react"
interface DataTablePaginationProps<TData> {
table: Table<TData>
}
export function DataTablePagination<TData>({ table }: DataTablePaginationProps<TData>) {
return (
<div className="flex items-center justify-between px-2">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value))
}}
>
<SelectTrigger className="h-8 w-[70px]">
<SelectValue placeholder={table.getState().pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top">
{[5, 10, 20, 30, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`}>
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to first page</span>
<ChevronsLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4" />
</Button>
<Button
variant="outline"
className="hidden h-8 w-8 p-0 lg:flex"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to last page</span>
<ChevronsRight className="h-4 w-4" />
</Button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,129 @@
"use client"
import * as React from "react"
import {
ColumnDef,
ColumnFiltersState,
SortingState,
VisibilityState,
flexRender,
getCoreRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { DataTablePagination } from "./data-table-pagination"
import { cn } from "@/lib/utils"
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
toolbar?: React.ReactNode
loading?: boolean
emptyMessage?: string
}
export function DataTable<TData, TValue>({
columns,
data,
toolbar,
loading,
emptyMessage = "No results found.",
}: DataTableProps<TData, TValue>) {
const [rowSelection, setRowSelection] = React.useState({})
const [columnVisibility, setColumnVisibility] = React.useState<VisibilityState>({})
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([])
const [sorting, setSorting] = React.useState<SortingState>([])
const table = useReactTable({
data,
columns,
state: {
sorting,
columnVisibility,
rowSelection,
columnFilters,
},
enableRowSelection: true,
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
onColumnVisibilityChange: setColumnVisibility,
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
})
return (
<div className="space-y-4">
{toolbar && <div className="flex items-center justify-between gap-4">{toolbar}</div>}
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder
? null
: flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{loading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}>
{columns.map((_, ci) => (
<TableCell key={ci}>
<div className="h-4 animate-pulse rounded bg-muted" />
</TableCell>
))}
</TableRow>
))
) : table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
className={cn("cursor-pointer")}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
<div className="flex flex-col items-center gap-2 text-muted-foreground">
<p>{emptyMessage}</p>
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<DataTablePagination table={table} />
</div>
)
}
@@ -0,0 +1,35 @@
"use client"
import { motion } from "framer-motion"
import { LucideIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
interface EmptyStateProps {
icon: LucideIcon
title: string
description: string
actionLabel?: string
onAction?: () => void
}
export function EmptyState({ icon: Icon, title, description, actionLabel, onAction }: EmptyStateProps) {
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col items-center justify-center py-16 text-center"
>
<div className="flex h-20 w-20 items-center justify-center rounded-full bg-muted">
<Icon className="h-10 w-10 text-muted-foreground" />
</div>
<h3 className="mt-6 text-lg font-semibold">{title}</h3>
<p className="mt-2 max-w-sm text-sm text-muted-foreground">{description}</p>
{actionLabel && onAction && (
<Button onClick={onAction} className="mt-6">
{actionLabel}
</Button>
)}
</motion.div>
)
}
@@ -0,0 +1,28 @@
"use client"
import { motion } from "framer-motion"
import { cn } from "@/lib/utils"
interface PageHeaderProps {
title: string | React.ReactNode
description?: string
children?: React.ReactNode
className?: string
}
export function PageHeader({ title, description, children, className }: PageHeaderProps) {
return (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
className={cn("flex items-center justify-between pb-6", className)}
>
<div>
<h1 className="text-2xl font-bold tracking-tight border-l-4 border-[#0d9488] pl-4">{title}</h1>
{description && <p className="text-sm text-muted-foreground mt-1">{description}</p>}
</div>
{children && <div className="flex items-center gap-3">{children}</div>}
</motion.div>
)
}
@@ -0,0 +1,113 @@
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}
+41
View File
@@ -0,0 +1,41 @@
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }
+30
View File
@@ -0,0 +1,30 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground shadow",
secondary: "border-transparent bg-secondary text-secondary-foreground",
destructive: "border-transparent bg-destructive text-destructive-foreground shadow",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
}
export { Badge, badgeVariants }
+52
View File
@@ -0,0 +1,52 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+50
View File
@@ -0,0 +1,50 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("rounded-xl border bg-card text-card-foreground shadow-sm", className)}
{...props}
/>
)
)
Card.displayName = "Card"
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
)
)
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("font-semibold leading-none tracking-tight", className)} {...props} />
)
)
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
)
)
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
)
)
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
)
)
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

Some files were not shown because too many files have changed in this diff Show More