3 Commits

Author SHA1 Message Date
fd55b30398 shit 2025-06-26 22:43:22 +02:00
8774a1f155 feat: Refactor sentiment handling and enhance processing logic for session data 2025-06-26 21:14:24 +02:00
653d70022b Broken shit 2025-06-26 21:00:19 +02:00
223 changed files with 16070 additions and 32723 deletions

View File

@ -1,10 +0,0 @@
node_modules/
.next/
dist/
build/
coverage/
.git/
*.min.js
public/
prisma/migrations/
.claude/

View File

@ -1 +0,0 @@
Use pnpm to manage this project, not npm!

View File

@ -2,25 +2,12 @@
# This file ensures NextAuth always has necessary environment variables in development
# NextAuth.js configuration
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="this_is_a_fixed_secret_for_development_only"
NODE_ENV="development"
NEXTAUTH_URL=http://192.168.1.2:3000
NEXTAUTH_SECRET=this_is_a_fixed_secret_for_development_only
NODE_ENV=development
# OpenAI API key for session processing
# Add your API key here: OPENAI_API_KEY=sk-...
OPENAI_API_KEY="your_openai_api_key_here"
OPENAI_API_KEY=your_openai_api_key_here
# Database connection - already configured in your prisma/schema.prisma
# Scheduler Configuration
SCHEDULER_ENABLED="false" # Enable/disable all schedulers (false for dev, true for production)
CSV_IMPORT_INTERVAL="*/15 * * * *" # Cron expression for CSV imports (every 15 minutes)
IMPORT_PROCESSING_INTERVAL="*/5 * * * *" # Cron expression for processing imports to sessions (every 5 minutes)
IMPORT_PROCESSING_BATCH_SIZE="50" # Number of imports to process at once
SESSION_PROCESSING_INTERVAL="0 * * * *" # Cron expression for AI session processing (every hour)
SESSION_PROCESSING_BATCH_SIZE="0" # 0 = unlimited sessions, >0 = specific limit
SESSION_PROCESSING_CONCURRENCY="5" # How many sessions to process in parallel
# Postgres Database Configuration
DATABASE_URL_TEST="postgresql://"
DATABASE_URL="postgresql://"

View File

@ -1,29 +0,0 @@
# Copy this file to .env.local and configure as needed
# NextAuth.js configuration
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="your_secret_key_here"
NODE_ENV="development"
# OpenAI API key for session processing
OPENAI_API_KEY="your_openai_api_key_here"
# Scheduler Configuration
SCHEDULER_ENABLED="true" # Set to false to disable all schedulers during development
CSV_IMPORT_INTERVAL="*/15 * * * *" # Every 15 minutes (cron format)
IMPORT_PROCESSING_INTERVAL="*/5 * * * *" # Every 5 minutes (cron format) - converts imports to sessions
IMPORT_PROCESSING_BATCH_SIZE="50" # Number of imports to process at once
SESSION_PROCESSING_INTERVAL="0 * * * *" # Every hour (cron format) - AI processing
SESSION_PROCESSING_BATCH_SIZE="0" # 0 = process all sessions, >0 = limit number
SESSION_PROCESSING_CONCURRENCY="5" # Number of sessions to process in parallel
# Postgres Database Configuration
DATABASE_URL_TEST="postgresql://"
DATABASE_URL="postgresql://"
# Example configurations:
# - For development (no schedulers): SCHEDULER_ENABLED=false
# - For testing (every 5 minutes): CSV_IMPORT_INTERVAL=*/5 * * * *
# - For faster import processing: IMPORT_PROCESSING_INTERVAL=*/2 * * * *
# - For limited processing: SESSION_PROCESSING_BATCH_SIZE=10
# - For high concurrency: SESSION_PROCESSING_CONCURRENCY=10

20
.gemini/settings.json Normal file
View File

@ -0,0 +1,20 @@
{
"mcpServers": {
"sqlite": {
"command": "uvx",
"args": [
"mcp-server-sqlite",
"--db-path",
"./prisma/dev.db"
]
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"D:\\Notso\\Product\\Vibe-coding\\livedash-node"
]
}
}
}

View File

@ -14,11 +14,13 @@ jobs:
with:
node-version: lts/*
- name: Install dependencies
run: npm install -g pnpm && pnpm install
run: npm ci
- name: Build dashboard
run: npm run build
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps
run: npx playwright install --with-deps
- name: Run Playwright tests
run: pnpm exec playwright test
run: npx playwright test
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:

6
.gitignore vendored
View File

@ -1,5 +1,3 @@
*-PROGRESS.md
# Created by https://www.toptal.com/developers/gitignore/api/node,nextjs,react
# Edit at https://www.toptal.com/developers/gitignore?templates=node,nextjs,react
@ -263,7 +261,3 @@ Thumbs.db
/playwright-report/
/blob-report/
/playwright/.cache/
# OpenAI API request samples
sample-openai-request.json
admin-user.txt

View File

@ -1 +0,0 @@
npx lint-staged

144
CLAUDE.md
View File

@ -1,144 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Development Commands
**Core Development:**
- `pnpm dev` - Start development server (runs custom server.ts with schedulers)
- `pnpm dev:next-only` - Start Next.js only with Turbopack (no schedulers)
- `pnpm build` - Build production application
- `pnpm start` - Run production server
**Code Quality:**
- `pnpm lint` - Run ESLint
- `pnpm lint:fix` - Fix ESLint issues automatically
- `pnpm format` - Format code with Prettier
- `pnpm format:check` - Check formatting without fixing
**Database:**
- `pnpm prisma:generate` - Generate Prisma client
- `pnpm prisma:migrate` - Run database migrations
- `pnpm prisma:push` - Push schema changes to database
- `pnpm prisma:push:force` - Force reset database and push schema
- `pnpm prisma:seed` - Seed database with initial data
- `pnpm prisma:studio` - Open Prisma Studio database viewer
**Testing:**
- `pnpm test` - Run both Vitest and Playwright tests concurrently
- `pnpm test:vitest` - Run Vitest tests only
- `pnpm test:vitest:watch` - Run Vitest in watch mode
- `pnpm test:vitest:coverage` - Run Vitest with coverage report
- `pnpm test:coverage` - Run all tests with coverage
**Markdown:**
- `pnpm lint:md` - Lint Markdown files
- `pnpm lint:md:fix` - Fix Markdown linting issues
## Architecture Overview
**LiveDash-Node** is a real-time analytics dashboard for monitoring user sessions with AI-powered analysis and processing pipeline.
### Tech Stack
- **Frontend:** Next.js 15 + React 19 + TailwindCSS 4
- **Backend:** Next.js API Routes + Custom Node.js server
- **Database:** PostgreSQL with Prisma ORM
- **Authentication:** NextAuth.js
- **AI Processing:** OpenAI API integration
- **Visualization:** D3.js, React Leaflet, Recharts
- **Scheduling:** Node-cron for background processing
### Key Architecture Components
**1. Multi-Stage Processing Pipeline**
The system processes user sessions through distinct stages tracked in `SessionProcessingStatus`:
- `CSV_IMPORT` - Import raw CSV data into `SessionImport`
- `TRANSCRIPT_FETCH` - Fetch transcript content from URLs
- `SESSION_CREATION` - Create normalized `Session` and `Message` records
- `AI_ANALYSIS` - AI processing for sentiment, categorization, summaries
- `QUESTION_EXTRACTION` - Extract questions from conversations
**2. Database Architecture**
- **Multi-tenant design** with `Company` as root entity
- **Dual storage pattern**: Raw CSV data in `SessionImport`, processed data in `Session`
- **1-to-1 relationship** between `SessionImport` and `Session` via `importId`
- **Message parsing** into individual `Message` records with order tracking
- **AI cost tracking** via `AIProcessingRequest` with detailed token usage
- **Flexible AI model management** through `AIModel`, `AIModelPricing`, and `CompanyAIModel`
**3. Custom Server Architecture**
- `server.ts` - Custom Next.js server with configurable scheduler initialization
- Three main schedulers: CSV import, import processing, and session processing
- Environment-based configuration via `lib/env.ts`
**4. Key Processing Libraries**
- `lib/scheduler.ts` - CSV import scheduling
- `lib/importProcessor.ts` - Raw data to Session conversion
- `lib/processingScheduler.ts` - AI analysis pipeline
- `lib/transcriptFetcher.ts` - External transcript fetching
- `lib/transcriptParser.ts` - Message parsing from transcripts
### Development Environment
**Environment Configuration:**
Environment variables are managed through `lib/env.ts` with .env.local file support:
- Database: PostgreSQL via `DATABASE_URL` and `DATABASE_URL_DIRECT`
- Authentication: `NEXTAUTH_SECRET`, `NEXTAUTH_URL`
- AI Processing: `OPENAI_API_KEY`
- Schedulers: `SCHEDULER_ENABLED`, various interval configurations
**Key Files to Understand:**
- `prisma/schema.prisma` - Complete database schema with enums and relationships
- `server.ts` - Custom server entry point
- `lib/env.ts` - Environment variable management and validation
- `app/` - Next.js App Router structure
**Testing:**
- Uses Vitest for unit testing
- Playwright for E2E testing
- Test files in `tests/` directory
### Important Notes
**Scheduler System:**
- Schedulers are optional and controlled by `SCHEDULER_ENABLED` environment variable
- Use `pnpm dev:next-only` to run without schedulers for pure frontend development
- Three separate schedulers handle different pipeline stages:
- CSV Import Scheduler (`lib/scheduler.ts`)
- Import Processing Scheduler (`lib/importProcessor.ts`)
- Session Processing Scheduler (`lib/processingScheduler.ts`)
**Database Migrations:**
- Always run `pnpm prisma:generate` after schema changes
- Use `pnpm prisma:migrate` for production-ready migrations
- Use `pnpm prisma:push` for development schema changes
- Database uses PostgreSQL with Prisma's driver adapter for connection pooling
**AI Processing:**
- All AI requests are tracked for cost analysis
- Support for multiple AI models per company
- Time-based pricing management for accurate cost calculation
- Processing stages can be retried on failure with retry count tracking
**Code Quality Standards:**
- Run `pnpm lint` and `pnpm format:check` before committing
- TypeScript with ES modules (type: "module" in package.json)
- React 19 with Next.js 15 App Router
- TailwindCSS 4 for styling

View File

@ -1,91 +0,0 @@
# 🚨 Database Connection Issues - Fixes Applied
## Issues Identified
From your logs:
```
Can't reach database server at `ep-tiny-math-a2zsshve-pooler.eu-central-1.aws.neon.tech:5432`
[NODE-CRON] [WARN] missed execution! Possible blocking IO or high CPU
```
## Root Causes
1. **Multiple PrismaClient instances** across schedulers
2. **No connection retry logic** for temporary failures
3. **No connection pooling optimization** for Neon
4. **Aggressive scheduler intervals** overwhelming database
## Fixes Applied ✅
### 1. Connection Retry Logic (`lib/database-retry.ts`)
- **Automatic retry** for connection errors
- **Exponential backoff** (1s → 2s → 4s → 10s max)
- **Smart error detection** (only retry connection issues)
- **Configurable retry attempts** (default: 3 retries)
### 2. Enhanced Schedulers
- **Import Processor**: Added retry wrapper around main processing
- **Session Processor**: Added retry wrapper around AI processing
- **Graceful degradation** when database is temporarily unavailable
### 3. Singleton Pattern Enforced
- **All schedulers now use** `import { prisma } from "./prisma.js"`
- **No more separate** `new PrismaClient()` instances
- **Shared connection pool** across all operations
### 4. Neon-Specific Optimizations
- **Connection limit guidance**: 15 connections (below Neon's 20 limit)
- **Extended timeouts**: 30s for cold start handling
- **SSL mode requirements**: `sslmode=require` for Neon
- **Application naming**: For better monitoring
## Immediate Actions Needed
### 1. Update Environment Variables
```bash
# Add to .env.local
USE_ENHANCED_POOLING=true
DATABASE_CONNECTION_LIMIT=15
DATABASE_POOL_TIMEOUT=30
# Update your DATABASE_URL to include:
DATABASE_URL="postgresql://user:pass@ep-tiny-math-a2zsshve-pooler.eu-central-1.aws.neon.tech:5432/db?sslmode=require&connection_limit=15&pool_timeout=30"
```
### 2. Reduce Scheduler Frequency (Optional)
```bash
# Less aggressive intervals
CSV_IMPORT_INTERVAL="*/30 * * * *" # Every 30 min (was 15)
IMPORT_PROCESSING_INTERVAL="*/10 * * * *" # Every 10 min (was 5)
SESSION_PROCESSING_INTERVAL="0 */2 * * *" # Every 2 hours (was 1)
```
### 3. Run Configuration Check
```bash
pnpm db:check
```
## Expected Results
**Connection Stability**: Automatic retry on temporary failures
**Resource Efficiency**: Single shared connection pool
**Neon Optimization**: Proper connection limits and timeouts
**Monitoring**: Health check endpoint for visibility
**Graceful Degradation**: Schedulers won't crash on DB issues
## Monitoring
- **Health Endpoint**: `/api/admin/database-health`
- **Connection Logs**: Enhanced logging for pool events
- **Retry Logs**: Detailed retry attempt logging
- **Error Classification**: Retryable vs non-retryable errors
## Files Modified
- `lib/database-retry.ts` - New retry utilities
- `lib/importProcessor.ts` - Added retry wrapper
- `lib/processingScheduler.ts` - Added retry wrapper
- `docs/neon-database-optimization.md` - Neon-specific guide
- `scripts/check-database-config.ts` - Configuration checker
The connection issues should be significantly reduced with these fixes! 🎯

47
GEMINI.md Normal file
View File

@ -0,0 +1,47 @@
# Project Overview
This project is a Next.js application with a Node.js backend, designed to provide a live dashboard for data visualization and session management.
## Setup
To set up the project, follow these steps:
1. **Install Dependencies:**
```bash
npm install
```
2. **Environment Variables:**
Create a `.env` file based on `.env.example` and fill in the necessary environment variables.
3. **Database Setup:**
Run database migrations:
```bash
npx prisma migrate dev
```
Seed the database (optional):
```bash
npx prisma db seed
```
4. **Run Development Server:**
```bash
npm run dev
```
## Common Commands
- **Run Tests:**
```bash
npm test
```
- **Run Linter:**
```bash
npm run lint
```
- **Build Project:**
```bash
npm run build
```

View File

@ -31,7 +31,7 @@ A real-time analytics dashboard for monitoring user sessions and interactions wi
### Prerequisites
- Node.js (LTS version recommended)
- pnpm (recommended package manager)
- npm or yarn
### Installation
@ -45,21 +45,21 @@ cd livedash-node
2. Install dependencies:
```bash
pnpm install
npm install
```
3. Set up the database:
```bash
pnpm run prisma:generate
pnpm run prisma:migrate
pnpm run prisma:seed
npm run prisma:generate
npm run prisma:migrate
npm run prisma:seed
```
4. Start the development server:
```bash
pnpm run dev
npm run dev
```
5. Open your browser and navigate to <http://localhost:3000>
@ -86,12 +86,12 @@ NEXTAUTH_SECRET=your-secret-here
## Available Scripts
- `pnpm run dev`: Start the development server
- `pnpm run build`: Build the application for production
- `pnpm run start`: Run the production build
- `pnpm run lint`: Run ESLint
- `pnpm run format`: Format code with Prettier
- `pnpm run prisma:studio`: Open Prisma Studio to view database
- `npm run dev`: Start the development server
- `npm run build`: Build the application for production
- `npm run start`: Run the production build
- `npm run lint`: Run ESLint
- `npm run format`: Format code with Prettier
- `npm run prisma:studio`: Open Prisma Studio to view database
## Contributing

247
TODO
View File

@ -1,247 +0,0 @@
# TODO - LiveDash Architecture Evolution & Improvements
## 🚀 CRITICAL PRIORITY - Architectural Refactoring
### Phase 1: Service Decomposition & Platform Management (Weeks 1-4)
- [x] **Create Platform Management Layer** (80% Complete)
- [x] Add Organization/PlatformUser models to Prisma schema
- [x] Implement super-admin authentication system (/platform/login)
- [x] Build platform dashboard for Notso AI team (/platform/dashboard)
- [x] Add company creation workflows
- [x] Add basic platform API endpoints with tests
- [x] Create stunning SaaS landing page with modern design
- [x] Add company editing/management workflows
- [x] Create company suspension/activation UI features
- [x] Add proper SEO metadata and OpenGraph tags
- [x] Add user management within companies from platform
- [ ] Add AI model management UI
- [ ] Add cost tracking/quotas UI
- [ ] **Extract Data Ingestion Service (Golang)**
- [ ] Create new Golang service for CSV processing
- [ ] Implement concurrent CSV downloading & parsing
- [ ] Add transcript fetching with rate limiting
- [ ] Set up Redis message queues (BullMQ/RabbitMQ)
- [ ] Migrate lib/scheduler.ts and lib/csvFetcher.ts logic
- [ ] **Implement tRPC Infrastructure**
- [ ] Add tRPC to existing Next.js app
- [ ] Create type-safe API procedures for frontend
- [ ] Implement inter-service communication protocols
- [ ] Add proper error handling and validation
### Phase 2: AI Service Separation & Compliance (Weeks 5-8)
- [ ] **Extract AI Processing Service**
- [ ] Separate lib/processingScheduler.ts into standalone service
- [ ] Implement async AI processing with queues
- [ ] Add per-company AI cost tracking and quotas
- [ ] Create AI model management per company
- [ ] Add retry logic and failure handling
- [ ] **GDPR & ISO 27001 Compliance Foundation**
- [ ] Implement data isolation boundaries between services
- [ ] Add audit logging for all data processing
- [ ] Create data retention policies per company
- [ ] Add consent management for data processing
- [ ] Implement data export/deletion workflows (Right to be Forgotten)
### Phase 3: Performance & Monitoring (Weeks 9-12)
- [ ] **Monitoring & Observability**
- [ ] Add distributed tracing across services (Jaeger/Zipkin)
- [ ] Implement health checks for all services
- [ ] Create cross-service metrics dashboard
- [ ] Add alerting for service failures and SLA breaches
- [ ] Monitor AI processing costs and quotas
- [ ] **Database Optimization**
- [ ] Implement connection pooling per service
- [ ] Add read replicas for dashboard queries
- [ ] Create database sharding strategy for multi-tenancy
- [ ] Optimize queries with proper indexing
## High Priority
### PR #20 Feedback Actions (Code Review)
- [ ] **Fix Environment Variable Testing**
- [ ] Replace process.env access with proper environment mocking in tests
- [ ] Update existing tests to avoid direct environment variable dependencies
- [ ] Add environment validation tests for critical config values
- [ ] **Enforce Zero Accessibility Violations**
- [ ] Set Playwright accessibility tests to fail on any violations (not just warn)
- [ ] Add accessibility regression tests for all major components
- [ ] Implement accessibility checklist for new components
- [ ] **Improve Error Handling with Custom Error Classes**
- [ ] Create custom error classes for different error types (ValidationError, AuthError, etc.)
- [ ] Replace generic Error throws with specific error classes
- [ ] Add proper error logging and monitoring integration
- [ ] **Refactor Long className Strings**
- [ ] Extract complex className combinations into utility functions
- [ ] Consider using cn() utility from utils for cleaner class composition
- [ ] Break down overly complex className props into semantic components
- [ ] **Add Dark Mode Accessibility Tests**
- [ ] Create comprehensive test suite for dark mode color contrast
- [ ] Verify focus indicators work properly in both light and dark modes
- [ ] Test screen reader compatibility with theme switching
- [ ] **Fix Platform Login Authentication Issue**
- [ ] NEXTAUTH_SECRET was using placeholder value (FIXED)
- [ ] Investigate platform cookie path restrictions in /platform auth
- [ ] Test platform login flow end-to-end after fixes
### Testing & Quality Assurance
- [ ] Add comprehensive test coverage for API endpoints (currently minimal)
- [ ] Implement integration tests for the data processing pipeline
- [ ] Add unit tests for validation schemas and authentication logic
- [ ] Create E2E tests for critical user flows (registration, login, dashboard)
### Error Handling & Monitoring
- [ ] Implement global error boundaries for React components
- [ ] Add structured logging with correlation IDs for request tracing
- [ ] Set up error monitoring and alerting (e.g., Sentry integration)
- [ ] Add proper error pages for 404, 500, and other HTTP status codes
### Performance Optimization
- [ ] Implement database query optimization and indexing strategy
- [ ] Add caching layer for frequently accessed data (Redis/in-memory)
- [ ] Optimize React components with proper memoization
- [ ] Implement lazy loading for dashboard components and charts
## Medium Priority
### Security Enhancements
- [ ] Add CSRF protection for state-changing operations
- [ ] Implement session timeout and refresh token mechanism
- [ ] Add API rate limiting with Redis-backed storage (replace in-memory)
- [ ] Implement role-based access control (RBAC) for different user types
- [ ] Add audit logging for sensitive operations
### Code Quality & Maintenance
- [ ] Resolve remaining ESLint warnings and type issues
- [ ] Standardize chart library usage (currently mixing Chart.js and other libraries)
- [ ] Add proper TypeScript strict mode configuration
- [ ] Implement consistent API response formats across all endpoints
### Database & Schema
- [ ] Add database connection pooling configuration
- [ ] Implement proper database migrations for production deployment
- [ ] Add data retention policies for session data
- [ ] Consider database partitioning for large-scale data
### User Experience
- [ ] Add loading states and skeleton components throughout the application
- [ ] Implement proper form validation feedback and error messages
- [ ] Add pagination for large data sets in dashboard tables
- [ ] Implement real-time notifications for processing status updates
## Low Priority
### Documentation & Development
- [ ] Add API documentation (OpenAPI/Swagger)
- [ ] Create deployment guides for different environments
- [ ] Add contributing guidelines and code review checklist
- [ ] Implement development environment setup automation
### Feature Enhancements
- [ ] Add data export functionality (CSV, PDF reports)
- [ ] Implement dashboard customization and user preferences
- [ ] Add multi-language support (i18n)
- [ ] Create admin panel for system configuration
### Infrastructure & DevOps
- [ ] Add Docker configuration for containerized deployment
- [ ] Implement CI/CD pipeline with automated testing
- [ ] Add environment-specific configuration management
- [ ] Set up monitoring and health check endpoints
### Analytics & Insights
- [ ] Add more detailed analytics and reporting features
- [ ] Implement A/B testing framework for UI improvements
- [ ] Add user behavior tracking and analytics
- [ ] Create automated report generation and scheduling
## Completed ✅
- [x] Fix duplicate MetricCard components
- [x] Add input validation schema with Zod
- [x] Strengthen password requirements (12+ chars, complexity)
- [x] Fix schema drift - create missing migrations
- [x] Add rate limiting to authentication endpoints
- [x] Update README.md to use pnpm instead of npm
- [x] Implement platform authentication and basic dashboard
- [x] Add platform API endpoints for company management
- [x] Write tests for platform features (auth, dashboard, API)
## 📊 Test Coverage Status (< 30% Overall)
### ✅ Features WITH Tests:
- User Authentication (regular users)
- User Management UI & API
- Basic database connectivity
- Transcript Fetcher
- Input validation
- Environment configuration
- Format enums
- Accessibility features
- Keyboard navigation
- Platform authentication (NEW)
- Platform dashboard (NEW)
- Platform API endpoints (NEW)
### ❌ Features WITHOUT Tests (Critical Gaps):
- **Data Processing Pipeline** (0 tests)
- CSV import scheduler
- Import processor
- Processing scheduler
- AI processing functionality
- Transcript parser
- **Most API Endpoints** (0 tests)
- Dashboard endpoints
- Session management
- Admin endpoints
- Password reset flow
- **Custom Server** (0 tests)
- **Dashboard Features** (0 tests)
- Charts and visualizations
- Session details
- Company settings
- **AI Integration** (0 tests)
- **Real-time Features** (0 tests)
- **E2E Tests** (only examples exist)
## 🏛️ Architectural Decisions & Rationale
### Service Technology Choices
- **Dashboard Service**: Next.js + tRPC (existing, proven stack)
- **Data Ingestion Service**: Golang (high-performance CSV processing, concurrency)
- **AI Processing Service**: Node.js/Python (existing AI integrations, async processing)
- **Message Queue**: Redis + BullMQ (Node.js ecosystem compatibility)
- **Database**: PostgreSQL (existing, excellent for multi-tenancy)
### Why Golang for Data Ingestion?
- **Performance**: 10-100x faster CSV processing than Node.js
- **Concurrency**: Native goroutines for parallel transcript fetching
- **Memory Efficiency**: Lower memory footprint for large CSV files
- **Deployment**: Single binary deployment, excellent for containers
- **Team Growth**: Easy to hire Golang developers for data processing
### Migration Strategy
1. **Keep existing working system** while building new services
2. **Feature flagging** to gradually migrate companies to new processing
3. **Dual-write approach** during transition period
4. **Zero-downtime migration** with careful rollback plans
### Compliance Benefits
- **Data Isolation**: Each service has limited database access
- **Audit Trail**: All inter-service communication logged
- **Data Retention**: Automated per-company data lifecycle
- **Security Boundaries**: DMZ for ingestion, private network for processing
## Notes
- **CRITICAL**: Architectural refactoring must be priority #1 for scalability
- **Platform Management**: Notso AI needs self-service customer onboarding
- **Compliance First**: GDPR/ISO 27001 requirements drive service boundaries
- **Performance**: Current monolith blocks on CSV/AI processing
- **Technology Evolution**: Golang for data processing, tRPC for type safety

78
TODO.md Normal file
View File

@ -0,0 +1,78 @@
# TODO.md
# Refactor!!!
> Based on my analysis of the codebase, here is a plan with recommendations for improving the project. The focus is on enhancing standardization, abstraction, user experience, and visual
> design.
## High-Level Recommendations
The project has a solid foundation, but it could be significantly improved by focusing on three key areas:
1. Adopt a UI Component Library: While Tailwind CSS is excellent for styling, using a component library like ShadCN/UI or Headless UI would provide pre-built, accessible, and visually
consistent components, saving development time and improving the user experience.
2. Refactor for Next.js App Router: The project currently uses a mix of the pages and app directories. Migrating fully to the App Router would simplify the project structure, improve
performance, and align with the latest Next.js features.
3. Enhance User Experience: Implementing consistent loading and error states, improving responsiveness, and providing better user feedback would make the application more robust and
user-friendly.
## Detailed Improvement Plan
Here is a phased plan to implement these recommendations:
### Phase 1: Foundational Improvements (Standardization & Abstraction)
This phase focuses on cleaning up the codebase, standardizing the project structure, and improving the abstraction of core functionalities.
1. Standardize Project Structure:
- [x] Unify Server File: Consolidated server.js, server.mjs, and server.ts into a single server.ts file to remove redundancy. ✅
- [x] Migrate to App Router: All API routes moved from `pages/api` to `app/api`. ✅
- [x] Standardize Naming Conventions: All files and components already follow a consistent naming convention (e.g., PascalCase for components, kebab-case for files). ✅
2. Introduce a UI Component Library:
- Integrate ShadCN/UI: Add ShadCN/UI to the project to leverage its extensive library of accessible and customizable components.
- Replace Custom Components: Gradually replace custom-built components in the components/ directory with their ShadCN/UI equivalents. This will improve visual consistency and reduce
maintenance overhead.
3. Refactor Core Logic:
- Centralize Data Fetching: Create a dedicated module (e.g., lib/data-service.ts) to handle all data fetching logic, abstracting away the details of using Prisma and external APIs.
- Isolate Business Logic: Ensure that business logic (e.g., session processing, metric calculation) is separated from the API routes and UI components.
### Phase 2: UX and Visual Enhancements
This phase focuses on improving the user-facing aspects of the application.
1. Implement Comprehensive Loading and Error States:
- Skeleton Loaders: Use skeleton loaders for dashboard components to provide a better loading experience.
- Global Error Handling: Implement a global error handling strategy to catch and display user-friendly error messages for API failures or other unexpected issues.
2. Redesign the Dashboard:
- Improve Information Hierarchy: Reorganize the dashboard to present the most important information first.
- Enhance Visual Appeal: Use the new component library to create a more modern and visually appealing design with a consistent color palette and typography.
- Improve Chart Interactivity: Add features like tooltips, zooming, and filtering to the charts to make them more interactive and informative.
3. Ensure Full Responsiveness:
- Mobile-First Approach: Review and update all pages and components to ensure they are fully responsive and usable on a wide range of devices.
### Phase 3: Advanced Topics (Security, Performance, and Documentation)
This phase focuses on long-term improvements to the project's stability, performance, and maintainability.
1. Conduct a Security Review:
- Input Validation: Ensure that all user inputs are properly validated on both the client and server sides.
- Dependency Audit: Regularly audit dependencies for known vulnerabilities.
2. Optimize Performance:
- Code Splitting: Leverage Next.js's automatic code splitting to reduce initial load times.
- Caching: Implement caching strategies for frequently accessed data to reduce database load and improve API response times.
3. Expand Documentation:
- API Documentation: Create detailed documentation for all API endpoints.
- Component Library: Document the usage and props of all reusable components.
- Update `AGENTS.md`: Keep the AGENTS.md file up-to-date with any architectural changes.

View File

@ -1,89 +0,0 @@
// Database connection health monitoring endpoint
import { type NextRequest, NextResponse } from "next/server";
import { checkDatabaseConnection, prisma } from "@/lib/prisma";
export async function GET(request: NextRequest) {
try {
// Check if user has admin access (you may want to add proper auth here)
const authHeader = request.headers.get("authorization");
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Basic database connectivity check
const isConnected = await checkDatabaseConnection();
if (!isConnected) {
return NextResponse.json(
{
status: "unhealthy",
database: {
connected: false,
error: "Database connection failed",
},
timestamp: new Date().toISOString(),
},
{ status: 503 }
);
}
// Get basic metrics
const metrics = await Promise.allSettled([
// Count total sessions
prisma.session.count(),
// Count processing status records
prisma.sessionProcessingStatus.count(),
// Count recent AI requests
prisma.aIProcessingRequest.count({
where: {
createdAt: {
gte: new Date(Date.now() - 24 * 60 * 60 * 1000), // Last 24 hours
},
},
}),
]);
const [sessionsResult, statusResult, aiRequestsResult] = metrics;
return NextResponse.json({
status: "healthy",
database: {
connected: true,
connectionType:
process.env.USE_ENHANCED_POOLING === "true"
? "enhanced_pooling"
: "standard",
},
metrics: {
totalSessions:
sessionsResult.status === "fulfilled"
? sessionsResult.value
: "error",
processingRecords:
statusResult.status === "fulfilled" ? statusResult.value : "error",
recentAIRequests:
aiRequestsResult.status === "fulfilled"
? aiRequestsResult.value
: "error",
},
environment: {
nodeEnv: process.env.NODE_ENV,
enhancedPooling: process.env.USE_ENHANCED_POOLING === "true",
connectionLimit: process.env.DATABASE_CONNECTION_LIMIT || "default",
poolTimeout: process.env.DATABASE_POOL_TIMEOUT || "default",
},
timestamp: new Date().toISOString(),
});
} catch (error) {
console.error("Database health check failed:", error);
return NextResponse.json(
{
status: "error",
error: error instanceof Error ? error.message : "Unknown error",
timestamp: new Date().toISOString(),
},
{ status: 500 }
);
}
}

View File

@ -1,146 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
import { fetchAndParseCsv } from "../../../../lib/csvFetcher";
import { processQueuedImports } from "../../../../lib/importProcessor";
import { prisma } from "../../../../lib/prisma";
export async function POST(request: NextRequest) {
try {
const body = await request.json();
let { companyId } = body;
if (!companyId) {
// Try to get user from prisma based on session cookie
try {
const session = await prisma.session.findFirst({
orderBy: { createdAt: "desc" },
where: {
/* Add session check criteria here */
},
});
if (session) {
companyId = session.companyId;
}
} catch (error) {
// Log error for server-side debugging
const errorMessage =
error instanceof Error ? error.message : String(error);
// Use a server-side logging approach instead of console
process.stderr.write(`Error fetching session: ${errorMessage}\n`);
}
}
if (!companyId) {
return NextResponse.json(
{ error: "Company ID is required" },
{ status: 400 }
);
}
const company = await prisma.company.findUnique({
where: { id: companyId },
});
if (!company) {
return NextResponse.json({ error: "Company not found" }, { status: 404 });
}
// Check if company is active and can process data
if (company.status !== "ACTIVE") {
return NextResponse.json(
{
error: `Data processing is disabled for ${company.status.toLowerCase()} companies`,
companyStatus: company.status,
},
{ status: 403 }
);
}
const rawSessionData = await fetchAndParseCsv(
company.csvUrl,
company.csvUsername as string | undefined,
company.csvPassword as string | undefined
);
let importedCount = 0;
// Create SessionImport records for new data
for (const rawSession of rawSessionData) {
try {
// Use upsert to handle duplicates gracefully
await prisma.sessionImport.upsert({
where: {
companyId_externalSessionId: {
companyId: company.id,
externalSessionId: rawSession.externalSessionId,
},
},
update: {
// Update existing record with latest data
startTimeRaw: rawSession.startTimeRaw,
endTimeRaw: rawSession.endTimeRaw,
ipAddress: rawSession.ipAddress,
countryCode: rawSession.countryCode,
language: rawSession.language,
messagesSent: rawSession.messagesSent,
sentimentRaw: rawSession.sentimentRaw,
escalatedRaw: rawSession.escalatedRaw,
forwardedHrRaw: rawSession.forwardedHrRaw,
fullTranscriptUrl: rawSession.fullTranscriptUrl,
avgResponseTimeSeconds: rawSession.avgResponseTimeSeconds,
tokens: rawSession.tokens,
tokensEur: rawSession.tokensEur,
category: rawSession.category,
initialMessage: rawSession.initialMessage,
// Status tracking now handled by ProcessingStatusManager
},
create: {
companyId: company.id,
externalSessionId: rawSession.externalSessionId,
startTimeRaw: rawSession.startTimeRaw,
endTimeRaw: rawSession.endTimeRaw,
ipAddress: rawSession.ipAddress,
countryCode: rawSession.countryCode,
language: rawSession.language,
messagesSent: rawSession.messagesSent,
sentimentRaw: rawSession.sentimentRaw,
escalatedRaw: rawSession.escalatedRaw,
forwardedHrRaw: rawSession.forwardedHrRaw,
fullTranscriptUrl: rawSession.fullTranscriptUrl,
avgResponseTimeSeconds: rawSession.avgResponseTimeSeconds,
tokens: rawSession.tokens,
tokensEur: rawSession.tokensEur,
category: rawSession.category,
initialMessage: rawSession.initialMessage,
// Status tracking now handled by ProcessingStatusManager
},
});
importedCount++;
} catch (error) {
// Log individual session import errors but continue processing
process.stderr.write(
`Failed to import session ${rawSession.externalSessionId}: ${error}\n`
);
}
}
// Immediately process the queued imports to create Session records
console.log("[Refresh API] Processing queued imports...");
await processQueuedImports(100); // Process up to 100 imports immediately
// Count how many sessions were created
const sessionCount = await prisma.session.count({
where: { companyId: company.id },
});
return NextResponse.json({
ok: true,
imported: importedCount,
total: rawSessionData.length,
sessions: sessionCount,
message: `Successfully imported ${importedCount} records and processed them into sessions. Total sessions: ${sessionCount}`,
});
} catch (e) {
const error = e instanceof Error ? e.message : "An unknown error occurred";
return NextResponse.json({ error }, { status: 500 });
}
}

View File

@ -1,126 +0,0 @@
import { ProcessingStage } from "@prisma/client";
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/auth";
import { prisma } from "../../../../lib/prisma";
import { processUnprocessedSessions } from "../../../../lib/processingScheduler";
import { ProcessingStatusManager } from "../../../../lib/processingStatusManager";
interface SessionUser {
email: string;
name?: string;
}
interface SessionData {
user: SessionUser;
}
export async function POST(request: NextRequest) {
const session = (await getServerSession(authOptions)) as SessionData | null;
if (!session?.user) {
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
select: {
id: true,
email: true,
role: true,
companyId: true,
company: {
select: {
id: true,
name: true,
status: true,
},
},
},
});
if (!user) {
return NextResponse.json({ error: "No user found" }, { status: 401 });
}
// Check if user has ADMIN role
if (user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Admin access required" },
{ status: 403 }
);
}
try {
// Get optional parameters from request body
const body = await request.json();
const { batchSize, maxConcurrency } = body;
// Validate parameters
const validatedBatchSize =
batchSize && batchSize > 0 ? Number.parseInt(batchSize) : null;
const validatedMaxConcurrency =
maxConcurrency && maxConcurrency > 0
? Number.parseInt(maxConcurrency)
: 5;
// Check how many sessions need AI processing using the new status system
const sessionsNeedingAI =
await ProcessingStatusManager.getSessionsNeedingProcessing(
ProcessingStage.AI_ANALYSIS,
1000 // Get count only
);
// Filter to sessions for this company
const companySessionsNeedingAI = sessionsNeedingAI.filter(
(statusRecord) => statusRecord.session.companyId === user.companyId
);
const unprocessedCount = companySessionsNeedingAI.length;
if (unprocessedCount === 0) {
return NextResponse.json({
success: true,
message: "No sessions requiring AI processing found",
unprocessedCount: 0,
processedCount: 0,
});
}
// Start processing (this will run asynchronously)
const _startTime = Date.now();
// Note: We're calling the function but not awaiting it to avoid timeout
// The processing will continue in the background
processUnprocessedSessions(validatedBatchSize, validatedMaxConcurrency)
.then(() => {
console.log(
`[Manual Trigger] Processing completed for company ${user.companyId}`
);
})
.catch((error) => {
console.error(
`[Manual Trigger] Processing failed for company ${user.companyId}:`,
error
);
});
return NextResponse.json({
success: true,
message: `Started processing ${unprocessedCount} unprocessed sessions`,
unprocessedCount,
batchSize: validatedBatchSize || unprocessedCount,
maxConcurrency: validatedMaxConcurrency,
startedAt: new Date().toISOString(),
});
} catch (error) {
console.error("[Manual Trigger] Error:", error);
return NextResponse.json(
{
error: "Failed to trigger processing",
details: error instanceof Error ? error.message : String(error),
},
{ status: 500 }
);
}
}

View File

@ -1,6 +0,0 @@
import NextAuth from "next-auth";
import { authOptions } from "../../../../lib/auth";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View File

@ -1,51 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/auth";
import { prisma } from "../../../../lib/prisma";
export async function GET(_request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return NextResponse.json({ error: "No user" }, { status: 401 });
}
// Get company data
const company = await prisma.company.findUnique({
where: { id: user.companyId },
});
return NextResponse.json({ company });
}
export async function POST(request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return NextResponse.json({ error: "No user" }, { status: 401 });
}
const body = await request.json();
const { csvUrl } = body;
await prisma.company.update({
where: { id: user.companyId },
data: { csvUrl },
});
return NextResponse.json({ ok: true });
}

View File

@ -1,176 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/auth";
import { sessionMetrics } from "../../../../lib/metrics";
import { prisma } from "../../../../lib/prisma";
import type { ChatSession } from "../../../../lib/types";
interface SessionUser {
email: string;
name?: string;
}
interface SessionData {
user: SessionUser;
}
export async function GET(request: NextRequest) {
const session = (await getServerSession(authOptions)) as SessionData | null;
if (!session?.user) {
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
select: {
id: true,
companyId: true,
company: {
select: {
id: true,
name: true,
csvUrl: true,
status: true,
},
},
},
});
if (!user) {
return NextResponse.json({ error: "No user" }, { status: 401 });
}
// Get date range from query parameters
const { searchParams } = new URL(request.url);
const startDate = searchParams.get("startDate");
const endDate = searchParams.get("endDate");
// Build where clause with optional date filtering
const whereClause: {
companyId: string;
startTime?: {
gte: Date;
lte: Date;
};
} = {
companyId: user.companyId,
};
if (startDate && endDate) {
whereClause.startTime = {
gte: new Date(startDate),
lte: new Date(`${endDate}T23:59:59.999Z`), // Include full end date
};
}
// Fetch sessions without messages first for better performance
const prismaSessions = await prisma.session.findMany({
where: whereClause,
select: {
id: true,
companyId: true,
startTime: true,
endTime: true,
createdAt: true,
category: true,
language: true,
country: true,
ipAddress: true,
sentiment: true,
messagesSent: true,
avgResponseTime: true,
escalated: true,
forwardedHr: true,
initialMsg: true,
fullTranscriptUrl: true,
summary: true,
},
});
// Batch fetch questions for all sessions at once if needed for metrics
const sessionIds = prismaSessions.map((s) => s.id);
const sessionQuestions = await prisma.sessionQuestion.findMany({
where: { sessionId: { in: sessionIds } },
include: { question: true },
orderBy: { order: "asc" },
});
// Group questions by session
const questionsBySession = sessionQuestions.reduce(
(acc, sq) => {
if (!acc[sq.sessionId]) acc[sq.sessionId] = [];
acc[sq.sessionId].push(sq.question.content);
return acc;
},
{} as Record<string, string[]>
);
// Convert Prisma sessions to ChatSession[] type for sessionMetrics
const chatSessions: ChatSession[] = prismaSessions.map((ps) => {
// Get questions for this session or empty array
const questions = questionsBySession[ps.id] || [];
// Convert questions to mock messages for backward compatibility
const mockMessages = questions.map((q, index) => ({
id: `question-${index}`,
sessionId: ps.id,
timestamp: ps.createdAt,
role: "User",
content: q,
order: index,
createdAt: ps.createdAt,
}));
return {
id: ps.id,
sessionId: ps.id,
companyId: ps.companyId,
startTime: new Date(ps.startTime),
endTime: ps.endTime ? new Date(ps.endTime) : null,
transcriptContent: "",
createdAt: new Date(ps.createdAt),
updatedAt: new Date(ps.createdAt),
category: ps.category || undefined,
language: ps.language || undefined,
country: ps.country || undefined,
ipAddress: ps.ipAddress || undefined,
sentiment: ps.sentiment === null ? undefined : ps.sentiment,
messagesSent: ps.messagesSent === null ? undefined : ps.messagesSent,
avgResponseTime:
ps.avgResponseTime === null ? undefined : ps.avgResponseTime,
escalated: ps.escalated || false,
forwardedHr: ps.forwardedHr || false,
initialMsg: ps.initialMsg || undefined,
fullTranscriptUrl: ps.fullTranscriptUrl || undefined,
summary: ps.summary || undefined,
messages: mockMessages, // Use questions as messages for metrics
userId: undefined,
};
});
// Pass company config to metrics
const companyConfigForMetrics = {
// Add company-specific configuration here in the future
};
const metrics = sessionMetrics(chatSessions, companyConfigForMetrics);
// Calculate date range from sessions
let dateRange: { minDate: string; maxDate: string } | null = null;
if (prismaSessions.length > 0) {
const dates = prismaSessions
.map((s) => new Date(s.startTime))
.sort((a, b) => a.getTime() - b.getTime());
dateRange = {
minDate: dates[0].toISOString().split("T")[0], // First session date
maxDate: dates[dates.length - 1].toISOString().split("T")[0], // Last session date
};
}
return NextResponse.json({
metrics,
csvUrl: user.company.csvUrl,
company: user.company,
dateRange,
});
}

View File

@ -1,63 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../../../lib/auth";
import { prisma } from "../../../../lib/prisma";
export async function GET(_request: NextRequest) {
const authSession = await getServerSession(authOptions);
if (!authSession || !authSession.user?.companyId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const companyId = authSession.user.companyId;
try {
// Use groupBy for better performance with distinct values
const [categoryGroups, languageGroups] = await Promise.all([
prisma.session.groupBy({
by: ["category"],
where: {
companyId,
category: { not: null },
},
orderBy: {
category: "asc",
},
}),
prisma.session.groupBy({
by: ["language"],
where: {
companyId,
language: { not: null },
},
orderBy: {
language: "asc",
},
}),
]);
const distinctCategories = categoryGroups
.map((g) => g.category)
.filter(Boolean) as string[];
const distinctLanguages = languageGroups
.map((g) => g.language)
.filter(Boolean) as string[];
return NextResponse.json({
categories: distinctCategories,
languages: distinctLanguages,
});
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
return NextResponse.json(
{
error: "Failed to fetch filter options",
details: errorMessage,
},
{ status: 500 }
);
}
}

View File

@ -1,82 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "../../../../../lib/prisma";
import type { ChatSession } from "../../../../../lib/types";
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
if (!id) {
return NextResponse.json(
{ error: "Session ID is required" },
{ status: 400 }
);
}
try {
const prismaSession = await prisma.session.findUnique({
where: { id },
include: {
messages: {
orderBy: { order: "asc" },
},
},
});
if (!prismaSession) {
return NextResponse.json({ error: "Session not found" }, { status: 404 });
}
// Map Prisma session object to ChatSession type
const session: ChatSession = {
// Spread prismaSession to include all its properties
...prismaSession,
// Override properties that need conversion or specific mapping
id: prismaSession.id, // ChatSession.id from Prisma.Session.id
sessionId: prismaSession.id, // ChatSession.sessionId from Prisma.Session.id
startTime: new Date(prismaSession.startTime),
endTime: prismaSession.endTime ? new Date(prismaSession.endTime) : null,
createdAt: new Date(prismaSession.createdAt),
// Prisma.Session does not have an `updatedAt` field. We'll use `createdAt` as a fallback.
// Or, if your business logic implies an update timestamp elsewhere, use that.
updatedAt: new Date(prismaSession.createdAt), // Fallback to createdAt
// Prisma.Session does not have a `userId` field.
userId: null, // Explicitly set to null or map if available from another source
// Ensure nullable fields from Prisma are correctly mapped to ChatSession's optional or nullable fields
category: prismaSession.category ?? null,
language: prismaSession.language ?? null,
country: prismaSession.country ?? null,
ipAddress: prismaSession.ipAddress ?? null,
sentiment: prismaSession.sentiment ?? null,
messagesSent: prismaSession.messagesSent ?? undefined, // Use undefined if ChatSession expects number | undefined
avgResponseTime: prismaSession.avgResponseTime ?? null,
escalated: prismaSession.escalated ?? undefined,
forwardedHr: prismaSession.forwardedHr ?? undefined,
initialMsg: prismaSession.initialMsg ?? undefined,
fullTranscriptUrl: prismaSession.fullTranscriptUrl ?? null,
summary: prismaSession.summary ?? null, // New field
transcriptContent: null, // Not available in Session model
messages:
prismaSession.messages?.map((msg) => ({
id: msg.id,
sessionId: msg.sessionId,
timestamp: msg.timestamp ? new Date(msg.timestamp) : new Date(),
role: msg.role,
content: msg.content,
order: msg.order,
createdAt: new Date(msg.createdAt),
})) ?? [], // New field - parsed messages
};
return NextResponse.json({ session });
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
return NextResponse.json(
{ error: "Failed to fetch session", details: errorMessage },
{ status: 500 }
);
}
}

View File

@ -1,143 +0,0 @@
import type { Prisma } from "@prisma/client";
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../../../lib/auth";
import { prisma } from "../../../../lib/prisma";
import type { ChatSession } from "../../../../lib/types";
export async function GET(request: NextRequest) {
const authSession = await getServerSession(authOptions);
if (!authSession || !authSession.user?.companyId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const companyId = authSession.user.companyId;
const { searchParams } = new URL(request.url);
const searchTerm = searchParams.get("searchTerm");
const category = searchParams.get("category");
const language = searchParams.get("language");
const startDate = searchParams.get("startDate");
const endDate = searchParams.get("endDate");
const sortKey = searchParams.get("sortKey");
const sortOrder = searchParams.get("sortOrder");
const queryPage = searchParams.get("page");
const queryPageSize = searchParams.get("pageSize");
const page = Number(queryPage) || 1;
const pageSize = Number(queryPageSize) || 10;
try {
const whereClause: Prisma.SessionWhereInput = { companyId };
// Search Term
if (searchTerm && searchTerm.trim() !== "") {
const searchConditions = [
{ id: { contains: searchTerm } },
{ initialMsg: { contains: searchTerm } },
{ summary: { contains: searchTerm } },
];
whereClause.OR = searchConditions;
}
// Category Filter
if (category && category.trim() !== "") {
// Cast to SessionCategory enum if it's a valid value
whereClause.category = category;
}
// Language Filter
if (language && language.trim() !== "") {
whereClause.language = language;
}
// Date Range Filter
if (startDate) {
whereClause.startTime = {
...((whereClause.startTime as object) || {}),
gte: new Date(startDate),
};
}
if (endDate) {
const inclusiveEndDate = new Date(endDate);
inclusiveEndDate.setDate(inclusiveEndDate.getDate() + 1);
whereClause.startTime = {
...((whereClause.startTime as object) || {}),
lt: inclusiveEndDate,
};
}
// Sorting
const validSortKeys: { [key: string]: string } = {
startTime: "startTime",
category: "category",
language: "language",
sentiment: "sentiment",
messagesSent: "messagesSent",
avgResponseTime: "avgResponseTime",
};
let orderByCondition:
| Prisma.SessionOrderByWithRelationInput
| Prisma.SessionOrderByWithRelationInput[];
const primarySortField =
sortKey && validSortKeys[sortKey] ? validSortKeys[sortKey] : "startTime"; // Default to startTime field if sortKey is invalid/missing
const primarySortOrder =
sortOrder === "asc" || sortOrder === "desc" ? sortOrder : "desc"; // Default to desc order
if (primarySortField === "startTime") {
// If sorting by startTime, it's the only sort criteria
orderByCondition = { [primarySortField]: primarySortOrder };
} else {
// If sorting by another field, use startTime: "desc" as secondary sort
orderByCondition = [
{ [primarySortField]: primarySortOrder },
{ startTime: "desc" },
];
}
const prismaSessions = await prisma.session.findMany({
where: whereClause,
orderBy: orderByCondition,
skip: (page - 1) * pageSize,
take: pageSize,
});
const totalSessions = await prisma.session.count({ where: whereClause });
const sessions: ChatSession[] = prismaSessions.map((ps) => ({
id: ps.id,
sessionId: ps.id,
companyId: ps.companyId,
startTime: new Date(ps.startTime),
endTime: ps.endTime ? new Date(ps.endTime) : null,
createdAt: new Date(ps.createdAt),
updatedAt: new Date(ps.createdAt),
userId: null,
category: ps.category ?? null,
language: ps.language ?? null,
country: ps.country ?? null,
ipAddress: ps.ipAddress ?? null,
sentiment: ps.sentiment ?? null,
messagesSent: ps.messagesSent ?? undefined,
avgResponseTime: ps.avgResponseTime ?? null,
escalated: ps.escalated ?? undefined,
forwardedHr: ps.forwardedHr ?? undefined,
initialMsg: ps.initialMsg ?? undefined,
fullTranscriptUrl: ps.fullTranscriptUrl ?? null,
transcriptContent: null, // Transcript content is now fetched from fullTranscriptUrl when needed
}));
return NextResponse.json({ sessions, totalSessions });
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
return NextResponse.json(
{ error: "Failed to fetch sessions", details: errorMessage },
{ status: 500 }
);
}
}

View File

@ -1,34 +0,0 @@
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/auth";
import { prisma } from "../../../../lib/prisma";
export async function POST(request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return NextResponse.json({ error: "No user" }, { status: 401 });
}
const body = await request.json();
const { csvUrl, csvUsername, csvPassword } = body;
await prisma.company.update({
where: { id: user.companyId },
data: {
csvUrl,
csvUsername,
...(csvPassword ? { csvPassword } : {}),
// Remove sentimentAlert field - not in current schema
},
});
return NextResponse.json({ ok: true });
}

View File

@ -1,80 +0,0 @@
import crypto from "node:crypto";
import bcrypt from "bcryptjs";
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/auth";
import { prisma } from "../../../../lib/prisma";
interface UserBasicInfo {
id: string;
email: string;
role: string;
}
export async function GET(_request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return NextResponse.json({ error: "No user" }, { status: 401 });
}
const users = await prisma.user.findMany({
where: { companyId: user.companyId },
});
const mappedUsers: UserBasicInfo[] = users.map((u) => ({
id: u.id,
email: u.email,
role: u.role,
}));
return NextResponse.json({ users: mappedUsers });
}
export async function POST(request: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email as string },
});
if (!user) {
return NextResponse.json({ error: "No user" }, { status: 401 });
}
const body = await request.json();
const { email, role } = body;
if (!email || !role) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}
const exists = await prisma.user.findUnique({ where: { email } });
if (exists) {
return NextResponse.json({ error: "Email exists" }, { status: 409 });
}
const tempPassword = crypto.randomBytes(12).toString("base64").slice(0, 12); // secure random initial password
await prisma.user.create({
data: {
email,
password: await bcrypt.hash(tempPassword, 10),
companyId: user.companyId,
role,
},
});
// TODO: Email user their temp password (stub, for demo) - Implement a robust and secure email sending mechanism. Consider using a transactional email service.
return NextResponse.json({ ok: true, tempPassword });
}

View File

@ -1,94 +0,0 @@
import crypto from "node:crypto";
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { sendEmail } from "../../../lib/sendEmail";
import { forgotPasswordSchema, validateInput } from "../../../lib/validation";
// In-memory rate limiting for password reset requests
const resetAttempts = new Map<string, { count: number; resetTime: number }>();
function checkRateLimit(ip: string): boolean {
const now = Date.now();
const attempts = resetAttempts.get(ip);
if (!attempts || now > attempts.resetTime) {
resetAttempts.set(ip, { count: 1, resetTime: now + 15 * 60 * 1000 }); // 15 minute window
return true;
}
if (attempts.count >= 5) {
// Max 5 reset requests per 15 minutes per IP
return false;
}
attempts.count++;
return true;
}
export async function POST(request: NextRequest) {
try {
// Rate limiting check
const ip =
request.headers.get("x-forwarded-for") ||
request.headers.get("x-real-ip") ||
"unknown";
if (!checkRateLimit(ip)) {
return NextResponse.json(
{
success: false,
error: "Too many password reset attempts. Please try again later.",
},
{ status: 429 }
);
}
const body = await request.json();
// Validate input
const validation = validateInput(forgotPasswordSchema, body);
if (!validation.success) {
return NextResponse.json(
{
success: false,
error: "Invalid email format",
},
{ status: 400 }
);
}
const { email } = validation.data;
const user = await prisma.user.findUnique({ where: { email } });
// Always return success for privacy (don't reveal if email exists)
// But only send email if user exists
if (user) {
const token = crypto.randomBytes(32).toString("hex");
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
const expiry = new Date(Date.now() + 1000 * 60 * 30); // 30 min expiry
await prisma.user.update({
where: { email },
data: { resetToken: tokenHash, resetTokenExpiry: expiry },
});
const resetUrl = `${process.env.NEXTAUTH_URL || "http://localhost:3000"}/reset-password?token=${token}`;
await sendEmail(
email,
"Password Reset",
`Reset your password: ${resetUrl}`
);
}
return NextResponse.json({ success: true }, { status: 200 });
} catch (error) {
console.error("Forgot password error:", error);
return NextResponse.json(
{
success: false,
error: "Internal server error",
},
{ status: 500 }
);
}
}

View File

@ -1,6 +0,0 @@
import NextAuth from "next-auth";
import { platformAuthOptions } from "../../../../../lib/platform-auth";
const handler = NextAuth(platformAuthOptions);
export { handler as GET, handler as POST };

View File

@ -1,163 +0,0 @@
import { CompanyStatus } from "@prisma/client";
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { platformAuthOptions } from "../../../../../lib/platform-auth";
import { prisma } from "../../../../../lib/prisma";
interface PlatformSession {
user: {
id?: string;
name?: string;
email?: string;
isPlatformUser?: boolean;
platformRole?: string;
};
}
// GET /api/platform/companies/[id] - Get company details
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = (await getServerSession(
platformAuthOptions
)) as PlatformSession | null;
if (!session?.user?.isPlatformUser) {
return NextResponse.json(
{ error: "Platform access required" },
{ status: 401 }
);
}
const { id } = await params;
const company = await prisma.company.findUnique({
where: { id },
include: {
users: {
select: {
id: true,
name: true,
email: true,
role: true,
createdAt: true,
updatedAt: true,
invitedBy: true,
invitedAt: true,
},
},
_count: {
select: {
sessions: true,
imports: true,
},
},
},
});
if (!company) {
return NextResponse.json({ error: "Company not found" }, { status: 404 });
}
return NextResponse.json(company);
} catch (error) {
console.error("Platform company details error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
// PATCH /api/platform/companies/[id] - Update company
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getServerSession(platformAuthOptions);
if (
!session?.user?.isPlatformUser ||
session.user.platformRole === "SUPPORT"
) {
return NextResponse.json(
{ error: "Admin access required" },
{ status: 403 }
);
}
const { id } = await params;
const body = await request.json();
const { name, email, maxUsers, csvUrl, csvUsername, csvPassword, status } =
body;
const updateData: {
name?: string;
email?: string;
maxUsers?: number;
csvUrl?: string;
csvUsername?: string;
csvPassword?: string;
status?: CompanyStatus;
} = {};
if (name !== undefined) updateData.name = name;
if (email !== undefined) updateData.email = email;
if (maxUsers !== undefined) updateData.maxUsers = maxUsers;
if (csvUrl !== undefined) updateData.csvUrl = csvUrl;
if (csvUsername !== undefined) updateData.csvUsername = csvUsername;
if (csvPassword !== undefined) updateData.csvPassword = csvPassword;
if (status !== undefined) updateData.status = status;
const company = await prisma.company.update({
where: { id },
data: updateData,
});
return NextResponse.json({ company });
} catch (error) {
console.error("Platform company update error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
// DELETE /api/platform/companies/[id] - Delete company (archives instead)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getServerSession(platformAuthOptions);
if (
!session?.user?.isPlatformUser ||
session.user.platformRole !== "SUPER_ADMIN"
) {
return NextResponse.json(
{ error: "Super admin access required" },
{ status: 403 }
);
}
const { id } = await params;
// Archive instead of delete to preserve data integrity
const company = await prisma.company.update({
where: { id },
data: { status: CompanyStatus.ARCHIVED },
});
return NextResponse.json({ company });
} catch (error) {
console.error("Platform company archive error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}

View File

@ -1,151 +0,0 @@
import { hash } from "bcryptjs";
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { platformAuthOptions } from "../../../../../../lib/platform-auth";
import { prisma } from "../../../../../../lib/prisma";
// POST /api/platform/companies/[id]/users - Invite user to company
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getServerSession(platformAuthOptions);
if (
!session?.user?.isPlatformUser ||
session.user.platformRole === "SUPPORT"
) {
return NextResponse.json(
{ error: "Admin access required" },
{ status: 403 }
);
}
const { id: companyId } = await params;
const body = await request.json();
const { name, email, role = "USER" } = body;
if (!name || !email) {
return NextResponse.json(
{ error: "Name and email are required" },
{ status: 400 }
);
}
// Check if company exists
const company = await prisma.company.findUnique({
where: { id: companyId },
include: { _count: { select: { users: true } } },
});
if (!company) {
return NextResponse.json({ error: "Company not found" }, { status: 404 });
}
// Check if user limit would be exceeded
if (company._count.users >= company.maxUsers) {
return NextResponse.json(
{ error: "Company has reached maximum user limit" },
{ status: 400 }
);
}
// Check if user already exists in this company
const existingUser = await prisma.user.findFirst({
where: {
email,
companyId,
},
});
if (existingUser) {
return NextResponse.json(
{ error: "User already exists in this company" },
{ status: 400 }
);
}
// Generate a temporary password (in a real app, you'd send an invitation email)
const tempPassword = `temp${Math.random().toString(36).slice(-8)}`;
const hashedPassword = await hash(tempPassword, 10);
// Create the user
const user = await prisma.user.create({
data: {
name,
email,
password: hashedPassword,
role,
companyId,
invitedBy: session.user.email,
invitedAt: new Date(),
},
select: {
id: true,
name: true,
email: true,
role: true,
createdAt: true,
invitedBy: true,
invitedAt: true,
},
});
// In a real application, you would send an email with login credentials
// For now, we'll return the temporary password
return NextResponse.json({
user,
tempPassword, // Remove this in production and send via email
message:
"User invited successfully. In production, credentials would be sent via email.",
});
} catch (error) {
console.error("Platform user invitation error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
// GET /api/platform/companies/[id]/users - Get company users
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getServerSession(platformAuthOptions);
if (!session?.user?.isPlatformUser) {
return NextResponse.json(
{ error: "Platform access required" },
{ status: 401 }
);
}
const { id: companyId } = await params;
const users = await prisma.user.findMany({
where: { companyId },
select: {
id: true,
name: true,
email: true,
role: true,
createdAt: true,
invitedBy: true,
invitedAt: true,
},
orderBy: { createdAt: "desc" },
});
return NextResponse.json({ users });
} catch (error) {
console.error("Platform users list error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}

View File

@ -1,187 +0,0 @@
import type { CompanyStatus } from "@prisma/client";
import { type NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { platformAuthOptions } from "../../../../lib/platform-auth";
import { prisma } from "../../../../lib/prisma";
// GET /api/platform/companies - List all companies
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(platformAuthOptions);
if (!session?.user?.isPlatformUser) {
return NextResponse.json(
{ error: "Platform access required" },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const status = searchParams.get("status") as CompanyStatus | null;
const search = searchParams.get("search");
const page = Number.parseInt(searchParams.get("page") || "1");
const limit = Number.parseInt(searchParams.get("limit") || "20");
const offset = (page - 1) * limit;
const where: {
status?: CompanyStatus;
name?: {
contains: string;
mode: "insensitive";
};
} = {};
if (status) where.status = status;
if (search) {
where.name = {
contains: search,
mode: "insensitive",
};
}
const [companies, total] = await Promise.all([
prisma.company.findMany({
where,
select: {
id: true,
name: true,
status: true,
createdAt: true,
updatedAt: true,
maxUsers: true,
_count: {
select: {
sessions: true,
imports: true,
users: true,
},
},
},
orderBy: { createdAt: "desc" },
skip: offset,
take: limit,
}),
prisma.company.count({ where }),
]);
return NextResponse.json({
companies,
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit),
},
});
} catch (error) {
console.error("Platform companies list error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
// POST /api/platform/companies - Create new company
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(platformAuthOptions);
if (
!session?.user?.isPlatformUser ||
session.user.platformRole === "SUPPORT"
) {
return NextResponse.json(
{ error: "Admin access required" },
{ status: 403 }
);
}
const body = await request.json();
const {
name,
csvUrl,
csvUsername,
csvPassword,
adminEmail,
adminName,
adminPassword,
maxUsers = 10,
status = "TRIAL",
} = body;
if (!name || !csvUrl) {
return NextResponse.json(
{ error: "Name and CSV URL required" },
{ status: 400 }
);
}
if (!adminEmail || !adminName) {
return NextResponse.json(
{ error: "Admin email and name required" },
{ status: 400 }
);
}
// Generate password if not provided
const finalAdminPassword =
adminPassword || `Temp${Math.random().toString(36).slice(2, 8)}!`;
// Hash the admin password
const bcrypt = await import("bcryptjs");
const hashedPassword = await bcrypt.hash(finalAdminPassword, 12);
// Create company and admin user in a transaction
const result = await prisma.$transaction(async (tx) => {
// Create the company
const company = await tx.company.create({
data: {
name,
csvUrl,
csvUsername: csvUsername || null,
csvPassword: csvPassword || null,
maxUsers,
status,
},
});
// Create the admin user
const adminUser = await tx.user.create({
data: {
email: adminEmail,
password: hashedPassword,
name: adminName,
role: "ADMIN",
companyId: company.id,
invitedBy: session.user.email || "platform",
invitedAt: new Date(),
},
});
return {
company,
adminUser,
generatedPassword: adminPassword ? null : finalAdminPassword,
};
});
return NextResponse.json(
{
company: result.company,
adminUser: {
email: result.adminUser.email,
name: result.adminUser.name,
role: result.adminUser.role,
},
generatedPassword: result.generatedPassword,
},
{ status: 201 }
);
} catch (error) {
console.error("Platform company creation error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}

View File

@ -1,136 +0,0 @@
import bcrypt from "bcryptjs";
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { registerSchema, validateInput } from "../../../lib/validation";
// In-memory rate limiting (for production, use Redis or similar)
const registrationAttempts = new Map<
string,
{ count: number; resetTime: number }
>();
function checkRateLimit(ip: string): boolean {
const now = Date.now();
const attempts = registrationAttempts.get(ip);
if (!attempts || now > attempts.resetTime) {
registrationAttempts.set(ip, { count: 1, resetTime: now + 60 * 60 * 1000 }); // 1 hour window
return true;
}
if (attempts.count >= 3) {
// Max 3 registrations per hour per IP
return false;
}
attempts.count++;
return true;
}
export async function POST(request: NextRequest) {
try {
// Rate limiting check
const ip =
request.ip || request.headers.get("x-forwarded-for") || "unknown";
if (!checkRateLimit(ip)) {
return NextResponse.json(
{
success: false,
error: "Too many registration attempts. Please try again later.",
},
{ status: 429 }
);
}
const body = await request.json();
// Validate input with Zod schema
const validation = validateInput(registerSchema, body);
if (!validation.success) {
return NextResponse.json(
{
success: false,
error: "Validation failed",
details: validation.errors,
},
{ status: 400 }
);
}
const { email, password, company } = validation.data;
// Check if email exists
const existingUser = await prisma.user.findUnique({
where: { email },
});
if (existingUser) {
return NextResponse.json(
{
success: false,
error: "Email already exists",
},
{ status: 409 }
);
}
// Check if company name already exists
const existingCompany = await prisma.company.findFirst({
where: { name: company },
});
if (existingCompany) {
return NextResponse.json(
{
success: false,
error: "Company name already exists",
},
{ status: 409 }
);
}
// Create company and user in a transaction
const result = await prisma.$transaction(async (tx) => {
const newCompany = await tx.company.create({
data: {
name: company,
csvUrl: "", // Empty by default, can be set later in settings
},
});
const hashedPassword = await bcrypt.hash(password, 12); // Increased rounds for better security
const newUser = await tx.user.create({
data: {
email,
password: hashedPassword,
companyId: newCompany.id,
role: "USER", // Changed from ADMIN - users should be promoted by existing admins
},
});
return { company: newCompany, user: newUser };
});
return NextResponse.json(
{
success: true,
data: {
message: "Registration successful",
userId: result.user.id,
companyId: result.company.id,
},
},
{ status: 201 }
);
} catch (error) {
console.error("Registration error:", error);
return NextResponse.json(
{
success: false,
error: "Internal server error",
},
{ status: 500 }
);
}
}

View File

@ -1,76 +0,0 @@
import crypto from "node:crypto";
import bcrypt from "bcryptjs";
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "../../../lib/prisma";
import { resetPasswordSchema, validateInput } from "../../../lib/validation";
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// Validate input with strong password requirements
const validation = validateInput(resetPasswordSchema, body);
if (!validation.success) {
return NextResponse.json(
{
success: false,
error: "Validation failed",
details: validation.errors,
},
{ status: 400 }
);
}
const { token, password } = validation.data;
// Hash the token to compare with stored hash
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
const user = await prisma.user.findFirst({
where: {
resetToken: tokenHash,
resetTokenExpiry: { gte: new Date() },
},
});
if (!user) {
return NextResponse.json(
{
success: false,
error:
"Invalid or expired token. Please request a new password reset.",
},
{ status: 400 }
);
}
// Hash password with higher rounds for better security
const hashedPassword = await bcrypt.hash(password, 12);
await prisma.user.update({
where: { id: user.id },
data: {
password: hashedPassword,
resetToken: null,
resetTokenExpiry: null,
},
});
return NextResponse.json(
{
success: true,
message: "Password has been reset successfully.",
},
{ status: 200 }
);
} catch (error) {
console.error("Reset password error:", error);
return NextResponse.json(
{
success: false,
error: "An internal server error occurred. Please try again later.",
},
{ status: 500 }
);
}
}

View File

@ -1,26 +1,18 @@
"use client";
import { Database, Save, Settings, ShieldX } from "lucide-react";
import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useEffect, useId, useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import type { Company } from "../../../lib/types";
import { Company } from "../../../lib/types";
export default function CompanySettingsPage() {
const csvUrlId = useId();
const csvUsernameId = useId();
const csvPasswordId = useId();
const { data: session, status } = useSession();
// We store the full company object for future use and updates after save operations
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const [_company, setCompany] = useState<Company | null>(null);
const [company, setCompany] = useState<Company | null>(null);
const [csvUrl, setCsvUrl] = useState<string>("");
const [csvUsername, setCsvUsername] = useState<string>("");
const [csvPassword, setCsvPassword] = useState<string>("");
const [sentimentThreshold, setSentimentThreshold] = useState<string>("");
const [message, setMessage] = useState<string>("");
const [loading, setLoading] = useState(true);
@ -34,6 +26,7 @@ export default function CompanySettingsPage() {
setCompany(data.company);
setCsvUrl(data.company.csvUrl || "");
setCsvUsername(data.company.csvUsername || "");
setSentimentThreshold(data.company.sentimentAlert?.toString() || "");
if (data.company.csvPassword) {
setCsvPassword(data.company.csvPassword);
}
@ -58,6 +51,7 @@ export default function CompanySettingsPage() {
csvUrl,
csvUsername,
csvPassword,
sentimentThreshold,
}),
});
@ -80,134 +74,110 @@ export default function CompanySettingsPage() {
// Loading state
if (loading) {
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center gap-3">
<Settings className="h-6 w-6" />
<CardTitle>Company Settings</CardTitle>
</div>
</CardHeader>
<CardContent>
<div className="text-center py-8 text-muted-foreground">
Loading settings...
</div>
</CardContent>
</Card>
</div>
);
return <div className="text-center py-10">Loading settings...</div>;
}
// Check for ADMIN access
if (session?.user?.role !== "ADMIN") {
// Check for admin access
if (session?.user?.role !== "admin") {
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center gap-3">
<ShieldX className="h-6 w-6 text-destructive" />
<CardTitle className="text-destructive">Access Denied</CardTitle>
</div>
</CardHeader>
<CardContent>
<div className="text-center py-8">
<p className="text-muted-foreground">
You don&apos;t have permission to view company settings.
</p>
</div>
</CardContent>
</Card>
<div className="text-center py-10 bg-white rounded-xl shadow p-6">
<h2 className="font-bold text-xl text-red-600 mb-2">Access Denied</h2>
<p>You don&apos;t have permission to view company settings.</p>
</div>
);
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center gap-3">
<Settings className="h-6 w-6" />
<CardTitle>Company Settings</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-6">
{message && (
<Alert
variant={message.includes("Failed") ? "destructive" : "default"}
>
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
<div className="bg-white p-6 rounded-xl shadow">
<h1 className="text-2xl font-bold text-gray-800 mb-6">
Company Settings
</h1>
<form
className="space-y-6"
onSubmit={(e) => {
e.preventDefault();
handleSave();
}}
autoComplete="off"
{message && (
<div
className={`p-4 rounded mb-6 ${message.includes("Failed") ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"}`}
>
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Database className="h-5 w-5" />
<CardTitle className="text-lg">
Data Source Configuration
</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor={csvUrlId}>CSV Data Source URL</Label>
<Input
id={csvUrlId}
type="text"
value={csvUrl}
onChange={(e) => setCsvUrl(e.target.value)}
placeholder="https://example.com/data.csv"
autoComplete="off"
/>
</div>
{message}
</div>
)}
<div className="space-y-2">
<Label htmlFor={csvUsernameId}>CSV Username</Label>
<Input
id={csvUsernameId}
type="text"
value={csvUsername}
onChange={(e) => setCsvUsername(e.target.value)}
placeholder="Username for CSV access (if needed)"
autoComplete="off"
/>
</div>
<form
className="grid gap-6"
onSubmit={(e) => {
e.preventDefault();
handleSave();
}}
autoComplete="off"
>
<div className="grid gap-2">
<label className="font-medium text-gray-700">
CSV Data Source URL
</label>
<input
type="text"
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500"
value={csvUrl}
onChange={(e) => setCsvUrl(e.target.value)}
placeholder="https://example.com/data.csv"
autoComplete="off"
/>
</div>
<div className="space-y-2">
<Label htmlFor={csvPasswordId}>CSV Password</Label>
<Input
id={csvPasswordId}
type="password"
value={csvPassword}
onChange={(e) => setCsvPassword(e.target.value)}
placeholder="Password will be updated only if provided"
autoComplete="new-password"
/>
<p className="text-sm text-muted-foreground">
Leave blank to keep current password
</p>
</div>
</CardContent>
</Card>
<div className="grid gap-2">
<label className="font-medium text-gray-700">CSV Username</label>
<input
type="text"
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500"
value={csvUsername}
onChange={(e) => setCsvUsername(e.target.value)}
placeholder="Username for CSV access (if needed)"
autoComplete="off"
/>
</div>
<div className="flex justify-end">
<Button type="submit" className="gap-2">
<Save className="h-4 w-4" />
Save Settings
</Button>
</div>
</form>
</CardContent>
</Card>
<div className="grid gap-2">
<label className="font-medium text-gray-700">CSV Password</label>
<input
type="password"
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500"
value={csvPassword}
onChange={(e) => setCsvPassword(e.target.value)}
placeholder="Password will be updated only if provided"
autoComplete="new-password"
/>
<p className="text-sm text-gray-500">
Leave blank to keep current password
</p>
</div>
<div className="grid gap-2">
<label className="font-medium text-gray-700">
Sentiment Alert Threshold
</label>
<input
type="number"
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500"
value={sentimentThreshold}
onChange={(e) => setSentimentThreshold(e.target.value)}
placeholder="Threshold value (0-100)"
min="0"
max="100"
autoComplete="off"
/>
<p className="text-sm text-gray-500">
Percentage of negative sentiment sessions to trigger alert (0-100)
</p>
</div>
<button
type="submit"
className="bg-sky-600 hover:bg-sky-700 text-white py-2 px-4 rounded-lg shadow transition-colors w-full sm:w-auto"
>
Save Settings
</button>
</form>
</div>
</div>
);
}

View File

@ -1,12 +1,11 @@
"use client";
import { useRouter } from "next/navigation";
import { ReactNode, useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { type ReactNode, useCallback, useEffect, useId, useState } from "react";
import { useRouter } from "next/navigation";
import Sidebar from "../../components/Sidebar";
export default function DashboardLayout({ children }: { children: ReactNode }) {
const mainContentId = useId();
const { status } = useSession();
const router = useRouter();
@ -58,7 +57,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
}
return (
<div className="flex h-screen bg-background">
<div className="flex h-screen bg-gray-100">
<Sidebar
isExpanded={isSidebarExpanded}
isMobile={isMobile}
@ -66,8 +65,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
onNavigate={collapseSidebar}
/>
<main
id={mainContentId}
<div
className={`flex-1 overflow-auto transition-all duration-300 py-4 pr-4
${
isSidebarExpanded
@ -78,7 +76,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
>
{/* <div className="w-full mx-auto">{children}</div> */}
<div className="max-w-7xl mx-auto">{children}</div>
</main>
</div>
</div>
);
}

View File

@ -1,59 +1,44 @@
"use client";
import {
CheckCircle,
Clock,
Euro,
Globe,
LogOut,
MessageCircle,
MessageSquare,
MoreVertical,
RefreshCw,
TrendingUp,
Users,
Zap,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState, useCallback } from "react";
import { signOut, useSession } from "next-auth/react";
import { useCallback, useEffect, useId, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useRouter } from "next/navigation";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Skeleton } from "@/components/ui/skeleton";
import { formatEnumValue } from "@/lib/format-enums";
import ModernBarChart from "../../../components/charts/bar-chart";
import ModernDonutChart from "../../../components/charts/donut-chart";
import ModernLineChart from "../../../components/charts/line-chart";
SessionsLineChart,
CategoriesBarChart,
LanguagePieChart,
TokenUsageChart,
} from "../../../components/Charts";
import { Company, MetricsResult, WordCloudWord } from "../../../lib/types";
import MetricCard from "../../../components/MetricCard";
import DonutChart from "../../../components/DonutChart";
import WordCloud from "../../../components/WordCloud";
import GeographicMap from "../../../components/GeographicMap";
import ResponseTimeDistribution from "../../../components/ResponseTimeDistribution";
import WelcomeBanner from "../../../components/WelcomeBanner";
import DateRangePicker from "../../../components/DateRangePicker";
import TopQuestionsChart from "../../../components/TopQuestionsChart";
import MetricCard from "../../../components/ui/metric-card";
import WordCloud from "../../../components/WordCloud";
import type { Company, MetricsResult, WordCloudWord } from "../../../lib/types";
// Safely wrapped component with useSession
function DashboardContent() {
const { data: session, status } = useSession();
const router = useRouter();
const { data: session, status } = useSession(); // Add status from useSession
const router = useRouter(); // Initialize useRouter
const [metrics, setMetrics] = useState<MetricsResult | null>(null);
const [company, setCompany] = useState<Company | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const [, setLoading] = useState<boolean>(false);
const [refreshing, setRefreshing] = useState<boolean>(false);
const [isInitialLoad, setIsInitialLoad] = useState<boolean>(true);
const [dateRange, setDateRange] = useState<{
minDate: string;
maxDate: string;
} | null>(null);
const [selectedStartDate, setSelectedStartDate] = useState<string>("");
const [selectedEndDate, setSelectedEndDate] = useState<string>("");
const refreshStatusId = useId();
const isAuditor = session?.user?.role === "AUDITOR";
const isAuditor = session?.user?.role === "auditor";
// Function to fetch metrics with optional date range
const fetchMetrics = useCallback(
async (startDate?: string, endDate?: string, isInitial = false) => {
async (startDate?: string, endDate?: string) => {
setLoading(true);
try {
let url = "/api/dashboard/metrics";
@ -67,9 +52,11 @@ function DashboardContent() {
setMetrics(data.metrics);
setCompany(data.company);
// Set initial load flag
if (isInitial) {
setIsInitialLoad(false);
// Set date range from API response (only on initial load)
if (data.dateRange && !dateRange) {
setDateRange(data.dateRange);
setSelectedStartDate(data.dateRange.minDate);
setSelectedEndDate(data.dateRange.maxDate);
}
} catch (error) {
console.error("Error fetching metrics:", error);
@ -77,27 +64,38 @@ function DashboardContent() {
setLoading(false);
}
},
[]
[dateRange]
);
// Handle date range changes
const handleDateRangeChange = useCallback(
(startDate: string, endDate: string) => {
setSelectedStartDate(startDate);
setSelectedEndDate(endDate);
fetchMetrics(startDate, endDate);
},
[fetchMetrics]
);
useEffect(() => {
// Redirect if not authenticated
if (status === "unauthenticated") {
router.push("/login");
return;
return; // Stop further execution in this effect
}
// Fetch metrics and company on mount if authenticated
if (status === "authenticated" && isInitialLoad) {
fetchMetrics(undefined, undefined, true);
if (status === "authenticated") {
fetchMetrics();
}
}, [status, router, isInitialLoad, fetchMetrics]);
}, [status, router, fetchMetrics]); // Add fetchMetrics to dependency array
async function handleRefresh() {
if (isAuditor) return;
if (isAuditor) return; // Prevent auditors from refreshing
try {
setRefreshing(true);
// Make sure we have a company ID to send
if (!company?.id) {
setRefreshing(false);
alert("Cannot refresh: Company ID is missing");
@ -111,6 +109,7 @@ function DashboardContent() {
});
if (res.ok) {
// Refetch metrics
const metricsRes = await fetch("/api/dashboard/metrics");
const data = await metricsRes.json();
setMetrics(data.metrics);
@ -123,167 +122,70 @@ function DashboardContent() {
}
}
// Calculate sentiment distribution
const getSentimentData = () => {
if (!metrics) return { positive: 0, neutral: 0, negative: 0 };
if (
metrics.sentimentPositiveCount !== undefined &&
metrics.sentimentNeutralCount !== undefined &&
metrics.sentimentNegativeCount !== undefined
) {
return {
positive: metrics.sentimentPositiveCount,
neutral: metrics.sentimentNeutralCount,
negative: metrics.sentimentNegativeCount,
};
}
const total = metrics.totalSessions || 1;
return {
positive: Math.round(total * 0.6),
neutral: Math.round(total * 0.3),
negative: Math.round(total * 0.1),
};
};
// Prepare token usage data
const getTokenData = () => {
if (!metrics || !metrics.tokensByDay) {
return { labels: [], values: [], costs: [] };
}
const days = Object.keys(metrics.tokensByDay).sort();
const labels = days.slice(-7);
const values = labels.map((day) => metrics.tokensByDay?.[day] || 0);
const costs = labels.map((day) => metrics.tokensCostByDay?.[day] || 0);
return { labels, values, costs };
};
// Show loading state while session status is being determined
if (status === "loading") {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="text-center space-y-4">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto" />
<p className="text-muted-foreground">Loading session...</p>
</div>
</div>
);
return <div className="text-center py-10">Loading session...</div>;
}
// If unauthenticated and not redirected yet (should be handled by useEffect, but as a fallback)
if (status === "unauthenticated") {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="text-center">
<p className="text-muted-foreground">Redirecting to login...</p>
</div>
</div>
);
return <div className="text-center py-10">Redirecting to login...</div>;
}
if (loading || !metrics || !company) {
return (
<div className="space-y-8">
{/* Header Skeleton */}
<Card>
<CardHeader>
<div className="flex justify-between items-start">
<div className="space-y-2">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-4 w-64" />
</div>
<div className="flex gap-2">
<Skeleton className="h-10 w-24" />
<Skeleton className="h-10 w-20" />
</div>
</div>
</CardHeader>
</Card>
{/* Metrics Grid Skeleton */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
{Array.from({ length: 8 }, (_, i) => {
const metricTypes = [
"sessions",
"users",
"time",
"response",
"costs",
"peak",
"resolution",
"languages",
];
return (
<MetricCard
key={`skeleton-${metricTypes[i] || "metric"}-card-loading`}
title=""
value=""
isLoading
/>
);
})}
</div>
{/* Charts Skeleton */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<Card className="lg:col-span-2">
<CardHeader>
<Skeleton className="h-6 w-32" />
</CardHeader>
<CardContent>
<Skeleton className="h-64 w-full" />
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-6 w-32" />
</CardHeader>
<CardContent>
<Skeleton className="h-64 w-full" />
</CardContent>
</Card>
</div>
</div>
);
if (!metrics || !company) {
return <div className="text-center py-10">Loading dashboard...</div>;
}
// Data preparation functions
const getSentimentData = () => {
if (!metrics) return [];
const sentimentData = {
positive: metrics.sentimentPositiveCount ?? 0,
neutral: metrics.sentimentNeutralCount ?? 0,
negative: metrics.sentimentNegativeCount ?? 0,
};
return [
{
name: "Positive",
value: sentimentData.positive,
color: "hsl(var(--chart-1))",
},
{
name: "Neutral",
value: sentimentData.neutral,
color: "hsl(var(--chart-2))",
},
{
name: "Negative",
value: sentimentData.negative,
color: "hsl(var(--chart-3))",
},
];
};
const getSessionsOverTimeData = () => {
if (!metrics?.days) return [];
return Object.entries(metrics.days).map(([date, value]) => ({
date: new Date(date).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
}),
value: value as number,
}));
};
const getCategoriesData = () => {
if (!metrics?.categories) return [];
return Object.entries(metrics.categories).map(([name, value]) => {
const formattedName = formatEnumValue(name) || name;
return {
name:
formattedName.length > 15
? `${formattedName.substring(0, 15)}...`
: formattedName,
value: value as number,
};
});
};
const getLanguagesData = () => {
if (!metrics?.languages) return [];
return Object.entries(metrics.languages).map(([name, value]) => ({
name,
value: value as number,
}));
};
// Function to prepare word cloud data from metrics.wordCloudData
const getWordCloudData = (): WordCloudWord[] => {
if (!metrics?.wordCloudData) return [];
if (!metrics || !metrics.wordCloudData) return [];
return metrics.wordCloudData;
};
// Function to prepare country data for the map using actual metrics
const getCountryData = () => {
if (!metrics?.countries) return {};
return Object.entries(metrics.countries).reduce(
if (!metrics || !metrics.countries) return {};
// Convert the countries object from metrics to the format expected by GeographicMap
const result = Object.entries(metrics.countries).reduce(
(acc, [code, count]) => {
if (code && count) {
acc[code] = count;
@ -292,8 +194,11 @@ function DashboardContent() {
},
{} as Record<string, number>
);
return result;
};
// Function to prepare response time distribution data
const getResponseTimeData = () => {
const avgTime = metrics.avgResponseTime || 1.5;
const simulatedData: number[] = [];
@ -308,78 +213,62 @@ function DashboardContent() {
return (
<div className="space-y-8">
{/* Modern Header */}
<Card className="border-0 bg-linear-to-r from-primary/5 via-primary/10 to-primary/5">
<CardHeader>
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div className="space-y-2">
<div className="flex items-center gap-3">
<h1 className="text-3xl font-bold tracking-tight">
{company.name}
</h1>
<Badge variant="secondary" className="text-xs">
Analytics Dashboard
</Badge>
</div>
<p className="text-muted-foreground">
Last updated{" "}
<span className="font-medium">
{new Date(metrics.lastUpdated || Date.now()).toLocaleString()}
</span>
</p>
</div>
<div className="flex items-center gap-2">
<Button
onClick={handleRefresh}
disabled={refreshing || isAuditor}
size="sm"
className="gap-2"
aria-label={
refreshing
? "Refreshing dashboard data"
: "Refresh dashboard data"
}
aria-describedby={refreshing ? refreshStatusId : undefined}
>
<RefreshCw
className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`}
aria-hidden="true"
/>
{refreshing ? "Refreshing..." : "Refresh"}
</Button>
{refreshing && (
<div
id={refreshStatusId}
className="sr-only"
aria-live="polite"
<WelcomeBanner companyName={company.name} />
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center bg-white p-6 rounded-2xl shadow-lg ring-1 ring-slate-200/50">
<div>
<h1 className="text-3xl font-bold text-slate-800">{company.name}</h1>
<p className="text-slate-500 mt-1">
Dashboard updated{" "}
<span className="font-medium text-slate-600">
{new Date(metrics.lastUpdated || Date.now()).toLocaleString()}
</span>
</p>
</div>
<div className="flex items-center gap-3 mt-4 sm:mt-0">
<button
className="bg-sky-600 text-white py-2 px-5 rounded-lg shadow hover:bg-sky-700 transition-colors disabled:opacity-60 disabled:cursor-not-allowed flex items-center text-sm font-medium"
onClick={handleRefresh}
disabled={refreshing || isAuditor}
>
{refreshing ? (
<>
<svg
className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
Dashboard data is being refreshed
</div>
)}
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
Refreshing...
</>
) : (
"Refresh Data"
)}
</button>
<button
className="bg-slate-100 text-slate-700 py-2 px-5 rounded-lg shadow hover:bg-slate-200 transition-colors flex items-center text-sm font-medium"
onClick={() => signOut({ callbackUrl: "/login" })}
>
Sign out
</button>
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" aria-label="Account menu">
<MoreVertical className="h-4 w-4" aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => signOut({ callbackUrl: "/login" })}
>
<LogOut className="h-4 w-4 mr-2" aria-hidden="true" />
Sign out
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</CardHeader>
</Card>
{/* Date Range Picker - Temporarily disabled to debug infinite loop */}
{/* {dateRange && (
{/* Date Range Picker */}
{dateRange && (
<DateRangePicker
minDate={dateRange.minDate}
maxDate={dateRange.maxDate}
@ -387,197 +276,268 @@ function DashboardContent() {
initialStartDate={selectedStartDate}
initialEndDate={selectedEndDate}
/>
)} */}
)}
{/* Modern Metrics Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-7 gap-4">
<MetricCard
title="Total Sessions"
value={metrics.totalSessions?.toLocaleString()}
icon={<MessageSquare className="h-5 w-5" />}
value={metrics.totalSessions}
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"
/>
</svg>
}
trend={{
value: metrics.sessionTrend ?? 0,
isPositive: (metrics.sessionTrend ?? 0) >= 0,
}}
variant="primary"
/>
<MetricCard
title="Unique Users"
value={metrics.uniqueUsers?.toLocaleString()}
icon={<Users className="h-5 w-5" />}
value={metrics.uniqueUsers}
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
/>
</svg>
}
trend={{
value: metrics.usersTrend ?? 0,
isPositive: (metrics.usersTrend ?? 0) >= 0,
}}
variant="success"
/>
<MetricCard
title="Avg. Session Time"
value={`${Math.round(metrics.avgSessionLength || 0)}s`}
icon={<Clock className="h-5 w-5" />}
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
trend={{
value: metrics.avgSessionTimeTrend ?? 0,
isPositive: (metrics.avgSessionTimeTrend ?? 0) >= 0,
}}
/>
<MetricCard
title="Avg. Response Time"
value={`${metrics.avgResponseTime?.toFixed(1) || 0}s`}
icon={<Zap className="h-5 w-5" />}
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M13 10V3L4 14h7v7l9-11h-7z"
/>
</svg>
}
trend={{
value: metrics.avgResponseTimeTrend ?? 0,
isPositive: (metrics.avgResponseTimeTrend ?? 0) <= 0,
isPositive: (metrics.avgResponseTimeTrend ?? 0) <= 0, // Lower response time is better
}}
variant="warning"
/>
<MetricCard
title="Daily Costs"
title="Avg. Daily Costs"
value={`${metrics.avgDailyCosts?.toFixed(4) || "0.0000"}`}
icon={<Euro className="h-5 w-5" />}
description="Average per day"
/>
<MetricCard
title="Peak Usage"
value={metrics.peakUsageTime || "N/A"}
icon={<TrendingUp className="h-5 w-5" />}
description="Busiest hour"
/>
<MetricCard
title="Resolution Rate"
value={`${metrics.resolvedChatsPercentage?.toFixed(1) || "0.0"}%`}
icon={<CheckCircle className="h-5 w-5" />}
trend={{
value: metrics.resolvedChatsPercentage ?? 0,
isPositive: (metrics.resolvedChatsPercentage ?? 0) >= 80,
}}
variant={
metrics.resolvedChatsPercentage &&
metrics.resolvedChatsPercentage >= 80
? "success"
: "warning"
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
/>
<MetricCard
title="Active Languages"
value={Object.keys(metrics.languages || {}).length}
icon={<Globe className="h-5 w-5" />}
description="Languages detected"
title="Peak Usage Time"
value={metrics.peakUsageTime || "N/A"}
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
/>
</svg>
}
/>
</div>
{/* Charts Section */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<ModernLineChart
data={getSessionsOverTimeData()}
title="Sessions Over Time"
className="lg:col-span-2"
height={350}
/>
<ModernDonutChart
data={getSentimentData()}
title="Conversation Sentiment"
centerText={{
title: "Total",
value: metrics.totalSessions || 0,
<MetricCard
title="Resolved Chats"
value={`${metrics.resolvedChatsPercentage?.toFixed(1) || "0.0"}%`}
icon={
<svg
className="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="1"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
trend={{
value: metrics.resolvedChatsPercentage ?? 0,
isPositive: (metrics.resolvedChatsPercentage ?? 0) >= 80, // 80%+ resolution rate is good
}}
height={350}
/>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<ModernBarChart
data={getCategoriesData()}
title="Sessions by Category"
height={350}
/>
<ModernDonutChart
data={getLanguagesData()}
title="Languages Used"
height={350}
/>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="bg-white p-6 rounded-xl shadow lg:col-span-2">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Sessions Over Time
</h3>
<SessionsLineChart sessionsPerDay={metrics.days} />
</div>
<div className="bg-white p-6 rounded-xl shadow">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Conversation Sentiment
</h3>
<DonutChart
data={{
labels: ["Positive", "Neutral", "Negative"],
values: [
getSentimentData().positive,
getSentimentData().neutral,
getSentimentData().negative,
],
colors: ["#1cad7c", "#a1a1a1", "#dc2626"],
}}
centerText={{
title: "Total",
value: metrics.totalSessions,
}}
/>
</div>
</div>
{/* Geographic and Topics Section */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Globe className="h-5 w-5" />
Geographic Distribution
</CardTitle>
</CardHeader>
<CardContent>
<GeographicMap countries={getCountryData()} />
</CardContent>
</Card>
<div className="bg-white p-6 rounded-xl shadow">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Sessions by Category
</h3>
<CategoriesBarChart categories={metrics.categories || {}} />
</div>
<div className="bg-white p-6 rounded-xl shadow">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Languages Used
</h3>
<LanguagePieChart languages={metrics.languages || {}} />
</div>
</div>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MessageCircle className="h-5 w-5" />
Common Topics
</CardTitle>
</CardHeader>
<CardContent>
<div className="h-[300px]">
<WordCloud words={getWordCloudData()} width={500} height={300} />
</div>
</CardContent>
</Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-white p-6 rounded-xl shadow">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Geographic Distribution
</h3>
<GeographicMap countries={getCountryData()} />
</div>
<div className="bg-white p-6 rounded-xl shadow">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Common Topics
</h3>
<div className="h-[300px]">
<WordCloud words={getWordCloudData()} width={500} height={400} />
</div>
</div>
</div>
{/* Top Questions Chart */}
<TopQuestionsChart data={metrics.topQuestions || []} />
{/* Response Time Distribution */}
<Card>
<CardHeader>
<CardTitle>Response Time Distribution</CardTitle>
</CardHeader>
<CardContent>
<ResponseTimeDistribution
data={getResponseTimeData()}
average={metrics.avgResponseTime || 0}
/>
</CardContent>
</Card>
{/* Token Usage Summary */}
<Card>
<CardHeader>
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<CardTitle>AI Usage & Costs</CardTitle>
<div className="flex flex-wrap gap-2">
<Badge variant="outline" className="gap-1">
<span className="font-semibold">Total Tokens:</span>
{metrics.totalTokens?.toLocaleString() || 0}
</Badge>
<Badge variant="outline" className="gap-1">
<span className="font-semibold">Total Cost:</span>
{metrics.totalTokensEur?.toFixed(4) || 0}
</Badge>
<div className="bg-white p-6 rounded-xl shadow">
<h3 className="font-bold text-lg text-gray-800 mb-4">
Response Time Distribution
</h3>
<ResponseTimeDistribution
data={getResponseTimeData()}
average={metrics.avgResponseTime || 0}
/>
</div>
<div className="bg-white p-6 rounded-xl shadow">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 mb-4">
<h3 className="font-bold text-lg text-gray-800">
Token Usage & Costs
</h3>
<div className="flex flex-col sm:flex-row gap-2 sm:gap-4 w-full sm:w-auto">
<div className="text-sm bg-blue-50 text-blue-700 px-3 py-1 rounded-full flex items-center">
<span className="font-semibold mr-1">Total Tokens:</span>
{metrics.totalTokens?.toLocaleString() || 0}
</div>
<div className="text-sm bg-green-50 text-green-700 px-3 py-1 rounded-full flex items-center">
<span className="font-semibold mr-1">Total Cost:</span>
{metrics.totalTokensEur?.toFixed(4) || 0}
</div>
</div>
</CardHeader>
<CardContent>
<div className="text-center py-8 text-muted-foreground">
<p>Token usage chart will be implemented with historical data</p>
</div>
</CardContent>
</Card>
</div>
<TokenUsageChart tokenData={getTokenData()} />
</div>
</div>
);
}
// Our exported component
export default function DashboardPage() {
return <DashboardContent />;
}

View File

@ -1,21 +1,9 @@
"use client";
import {
ArrowRight,
BarChart3,
MessageSquare,
Settings,
Shield,
TrendingUp,
Users,
Zap,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { type FC, useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { FC } from "react";
const DashboardPage: FC = () => {
const { data: session, status } = useSession();
@ -33,244 +21,82 @@ const DashboardPage: FC = () => {
if (loading) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="text-center space-y-4">
<div className="relative">
<div className="animate-spin rounded-full h-12 w-12 border-2 border-muted border-t-primary mx-auto" />
<div className="absolute inset-0 animate-ping rounded-full h-12 w-12 border border-primary opacity-20 mx-auto" />
</div>
<p className="text-lg text-muted-foreground animate-pulse">
Loading dashboard...
</p>
<div className="flex items-center justify-center min-h-[40vh]">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-sky-500 mx-auto mb-4"></div>
<p className="text-lg text-gray-600">Loading dashboard...</p>
</div>
</div>
);
}
const navigationCards = [
{
title: "Analytics Overview",
description:
"View comprehensive metrics, charts, and insights from your chat sessions",
icon: <BarChart3 className="h-6 w-6" />,
href: "/dashboard/overview",
variant: "primary" as const,
features: ["Real-time metrics", "Interactive charts", "Trend analysis"],
},
{
title: "Session Browser",
description:
"Browse, search, and analyze individual conversation sessions",
icon: <MessageSquare className="h-6 w-6" />,
href: "/dashboard/sessions",
variant: "success" as const,
features: ["Session search", "Conversation details", "Export data"],
},
...(session?.user?.role === "ADMIN"
? [
{
title: "Company Settings",
description:
"Configure company settings, integrations, and API connections",
icon: <Settings className="h-6 w-6" />,
href: "/dashboard/company",
variant: "warning" as const,
features: [
"API configuration",
"Integration settings",
"Data management",
],
adminOnly: true,
},
{
title: "User Management",
description:
"Invite team members and manage user accounts and permissions",
icon: <Users className="h-6 w-6" />,
href: "/dashboard/users",
variant: "default" as const,
features: ["User invitations", "Role management", "Access control"],
adminOnly: true,
},
]
: []),
];
const getCardClasses = (variant: string) => {
switch (variant) {
case "primary":
return "border-primary/20 bg-linear-to-br from-primary/5 to-primary/10 hover:from-primary/10 hover:to-primary/15";
case "success":
return "border-green-200 bg-linear-to-br from-green-50 to-green-100 hover:from-green-100 hover:to-green-150 dark:border-green-800 dark:from-green-950 dark:to-green-900";
case "warning":
return "border-amber-200 bg-linear-to-br from-amber-50 to-amber-100 hover:from-amber-100 hover:to-amber-150 dark:border-amber-800 dark:from-amber-950 dark:to-amber-900";
default:
return "border-border bg-linear-to-br from-card to-muted/20 hover:from-muted/30 hover:to-muted/40";
}
};
const getIconClasses = (variant: string) => {
switch (variant) {
case "primary":
return "bg-primary/10 text-primary border-primary/20";
case "success":
return "bg-green-100 text-green-600 border-green-200 dark:bg-green-900 dark:text-green-400 dark:border-green-800";
case "warning":
return "bg-amber-100 text-amber-600 border-amber-200 dark:bg-amber-900 dark:text-amber-400 dark:border-amber-800";
default:
return "bg-muted text-muted-foreground border-border";
}
};
return (
<div className="space-y-8">
{/* Welcome Header */}
<div className="relative overflow-hidden rounded-xl bg-linear-to-r from-primary/10 via-primary/5 to-transparent p-8 border border-primary/10">
<div className="absolute inset-0 bg-linear-to-br from-primary/5 to-transparent" />
<div className="absolute -top-24 -right-24 h-64 w-64 rounded-full bg-primary/10 blur-3xl" />
<div className="relative">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div className="space-y-3">
<div className="flex items-center gap-3">
<h1 className="text-4xl font-bold tracking-tight bg-clip-text text-transparent bg-linear-to-r from-foreground to-foreground/70">
Welcome back, {session?.user?.name || "User"}!
</h1>
<Badge
variant="secondary"
className="text-xs px-3 py-1 bg-primary/10 text-primary border-primary/20"
>
{session?.user?.role}
</Badge>
</div>
<p className="text-muted-foreground text-lg">
Choose a section below to explore your analytics dashboard
</p>
</div>
<div className="space-y-6">
<div className="bg-white rounded-xl shadow p-6">
<h1 className="text-2xl font-bold mb-4">Dashboard</h1>
<div className="flex items-center gap-3 px-4 py-2 rounded-full bg-muted/50 backdrop-blur-sm">
<Shield className="h-4 w-4 text-green-600" />
<span className="text-sm font-medium">Secure Dashboard</span>
</div>
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
<div className="bg-gradient-to-br from-sky-50 to-sky-100 p-6 rounded-xl shadow-sm hover:shadow-md transition-shadow">
<h2 className="text-lg font-semibold text-sky-700">Analytics</h2>
<p className="text-gray-600 mt-2 mb-4">
View your chat session metrics and analytics
</p>
<button
onClick={() => router.push("/dashboard/overview")}
className="bg-sky-500 hover:bg-sky-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
>
View Analytics
</button>
</div>
<div className="bg-gradient-to-br from-emerald-50 to-emerald-100 p-6 rounded-xl shadow-sm hover:shadow-md transition-shadow">
<h2 className="text-lg font-semibold text-emerald-700">Sessions</h2>
<p className="text-gray-600 mt-2 mb-4">
Browse and analyze conversation sessions
</p>
<button
onClick={() => router.push("/dashboard/sessions")}
className="bg-emerald-500 hover:bg-emerald-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
>
View Sessions
</button>
</div>
{session?.user?.role === "admin" && (
<div className="bg-gradient-to-br from-purple-50 to-purple-100 p-6 rounded-xl shadow-sm hover:shadow-md transition-shadow">
<h2 className="text-lg font-semibold text-purple-700">
Company Settings
</h2>
<p className="text-gray-600 mt-2 mb-4">
Configure company settings and integrations
</p>
<button
onClick={() => router.push("/dashboard/company")}
className="bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
>
Manage Settings
</button>
</div>
)}
{session?.user?.role === "admin" && (
<div className="bg-gradient-to-br from-amber-50 to-amber-100 p-6 rounded-xl shadow-sm hover:shadow-md transition-shadow">
<h2 className="text-lg font-semibold text-amber-700">
User Management
</h2>
<p className="text-gray-600 mt-2 mb-4">
Invite and manage user accounts
</p>
<button
onClick={() => router.push("/dashboard/users")}
className="bg-amber-500 hover:bg-amber-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
>
Manage Users
</button>
</div>
)}
</div>
</div>
{/* Navigation Cards */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{navigationCards.map((card) => (
<Card
key={card.href}
className={`relative overflow-hidden transition-all duration-300 hover:shadow-2xl hover:-translate-y-1 cursor-pointer group ${getCardClasses(
card.variant
)}`}
onClick={() => router.push(card.href)}
>
{/* Subtle gradient overlay */}
<div className="absolute inset-0 bg-linear-to-br from-white/50 to-transparent dark:from-white/5 pointer-events-none" />
<CardHeader className="relative">
<div className="flex items-start justify-between">
<div className="space-y-3">
<div className="flex items-center gap-3">
<div
className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-full border transition-all duration-300 group-hover:scale-110 ${getIconClasses(
card.variant
)}`}
>
<span className="transition-transform duration-300 group-hover:scale-110">
{card.icon}
</span>
</div>
<div>
<CardTitle className="text-xl font-semibold flex items-center gap-2">
{card.title}
{card.adminOnly && (
<Badge variant="outline" className="text-xs">
Admin
</Badge>
)}
</CardTitle>
</div>
</div>
<p className="text-muted-foreground leading-relaxed">
{card.description}
</p>
</div>
</div>
</CardHeader>
<CardContent className="relative space-y-4">
{/* Features List */}
<div className="space-y-2">
{card.features.map((feature) => (
<div
key={feature}
className="flex items-center gap-2 text-sm"
>
<Zap className="h-3 w-3 text-primary/60" />
<span className="text-muted-foreground">{feature}</span>
</div>
))}
</div>
{/* Action Button */}
<Button
className="w-full gap-2 mt-4 group-hover:gap-3 transition-all duration-300"
variant={card.variant === "primary" ? "default" : "outline"}
onClick={(e) => {
e.stopPropagation();
router.push(card.href);
}}
>
<span>
{card.title === "Analytics Overview" && "View Analytics"}
{card.title === "Session Browser" && "Browse Sessions"}
{card.title === "Company Settings" && "Manage Settings"}
{card.title === "User Management" && "Manage Users"}
</span>
<ArrowRight className="h-4 w-4" />
</Button>
</CardContent>
</Card>
))}
</div>
{/* Quick Stats */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="h-5 w-5" />
Quick Stats
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
<div className="text-center space-y-2">
<div className="flex items-center justify-center gap-2">
<Zap className="h-5 w-5 text-primary" />
<span className="text-2xl font-bold">Real-time</span>
</div>
<p className="text-sm text-muted-foreground">Data updates</p>
</div>
<div className="text-center space-y-2">
<div className="flex items-center justify-center gap-2">
<Shield className="h-5 w-5 text-green-600" />
<span className="text-2xl font-bold">Secure</span>
</div>
<p className="text-sm text-muted-foreground">Data protection</p>
</div>
<div className="text-center space-y-2">
<div className="flex items-center justify-center gap-2">
<BarChart3 className="h-5 w-5 text-blue-600" />
<span className="text-2xl font-bold">Advanced</span>
</div>
<p className="text-sm text-muted-foreground">Analytics</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
};

View File

@ -1,27 +1,13 @@
"use client";
import {
Activity,
AlertCircle,
ArrowLeft,
Clock,
ExternalLink,
FileText,
Globe,
MessageSquare,
User,
} from "lucide-react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatCategory } from "@/lib/format-enums";
import MessageViewer from "../../../../components/MessageViewer";
import { useParams, useRouter } from "next/navigation"; // Import useRouter
import { useSession } from "next-auth/react"; // Import useSession
import SessionDetails from "../../../../components/SessionDetails";
import type { ChatSession } from "../../../../lib/types";
import MessageViewer from "../../../../components/MessageViewer";
import { ChatSession } from "../../../../lib/types";
import Link from "next/link";
export default function SessionViewPage() {
const params = useParams();
@ -71,256 +57,110 @@ export default function SessionViewPage() {
if (status === "loading") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Loading session...
</div>
</CardContent>
</Card>
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
<p className="text-gray-600 text-lg">Loading session...</p>
</div>
);
}
if (status === "unauthenticated") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Redirecting to login...
</div>
</CardContent>
</Card>
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
<p className="text-gray-600 text-lg">Redirecting to login...</p>
</div>
);
}
if (loading && status === "authenticated") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Loading session details...
</div>
</CardContent>
</Card>
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
<p className="text-gray-600 text-lg">Loading session details...</p>
</div>
);
}
if (error) {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
<p className="text-destructive text-lg mb-4">Error: {error}</p>
<Link href="/dashboard/sessions">
<Button variant="outline" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Sessions List
</Button>
</Link>
</div>
</CardContent>
</Card>
<div className="p-4 md:p-6 min-h-screen">
<p className="text-red-500 text-lg mb-4">Error: {error}</p>
<Link
href="/dashboard/sessions"
className="text-sky-600 hover:underline"
>
Back to Sessions List
</Link>
</div>
);
}
if (!session) {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<MessageSquare className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
<p className="text-muted-foreground text-lg mb-4">
Session not found.
</p>
<Link href="/dashboard/sessions">
<Button variant="outline" className="gap-2">
<ArrowLeft className="h-4 w-4" />
Back to Sessions List
</Button>
</Link>
</div>
</CardContent>
</Card>
<div className="p-4 md:p-6 min-h-screen">
<p className="text-gray-600 text-lg mb-4">Session not found.</p>
<Link
href="/dashboard/sessions"
className="text-sky-600 hover:underline"
>
Back to Sessions List
</Link>
</div>
);
}
return (
<div className="space-y-6 max-w-6xl mx-auto">
{/* Header */}
<Card>
<CardContent className="pt-6">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div className="space-y-2">
<Link href="/dashboard/sessions">
<Button
variant="ghost"
className="gap-2 p-0 h-auto focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
aria-label="Return to sessions list"
>
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
Back to Sessions List
</Button>
</Link>
<div className="space-y-2">
<h1 className="text-3xl font-bold">Session Details</h1>
<div className="flex items-center gap-3">
<Badge variant="outline" className="font-mono text-xs">
ID
</Badge>
<code className="text-sm text-muted-foreground font-mono">
{(session.sessionId || session.id).slice(0, 8)}...
</code>
</div>
</div>
</div>
<div className="flex flex-wrap gap-2">
{session.category && (
<Badge variant="secondary" className="gap-1">
<Activity className="h-3 w-3" />
{formatCategory(session.category)}
</Badge>
)}
{session.language && (
<Badge variant="outline" className="gap-1">
<Globe className="h-3 w-3" />
{session.language.toUpperCase()}
</Badge>
)}
{session.sentiment && (
<Badge
variant={
session.sentiment === "positive"
? "default"
: session.sentiment === "negative"
? "destructive"
: "secondary"
}
className="gap-1"
>
{session.sentiment.charAt(0).toUpperCase() +
session.sentiment.slice(1)}
</Badge>
)}
</div>
</div>
</CardContent>
</Card>
{/* Session Overview */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Clock className="h-8 w-8 text-blue-500" />
<div>
<p className="text-sm text-muted-foreground">Start Time</p>
<p className="font-semibold">
{new Date(session.startTime).toLocaleString()}
</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<MessageSquare className="h-8 w-8 text-green-500" />
<div>
<p className="text-sm text-muted-foreground">Messages</p>
<p className="font-semibold">{session.messages?.length || 0}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<User className="h-8 w-8 text-purple-500" />
<div>
<p className="text-sm text-muted-foreground">User ID</p>
<p className="font-semibold truncate">
{session.userId || "N/A"}
</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<Activity className="h-8 w-8 text-orange-500" />
<div>
<p className="text-sm text-muted-foreground">Duration</p>
<p className="font-semibold">
{session.endTime && session.startTime
? `${Math.round(
(new Date(session.endTime).getTime() -
new Date(session.startTime).getTime()) /
60000
)} min`
: "N/A"}
</p>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Session Details */}
<SessionDetails session={session} />
{/* Messages */}
{session.messages && session.messages.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MessageSquare className="h-5 w-5" />
Conversation ({session.messages.length} messages)
</CardTitle>
</CardHeader>
<CardContent>
<MessageViewer messages={session.messages} />
</CardContent>
</Card>
)}
{/* Transcript URL */}
{session.fullTranscriptUrl && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileText className="h-5 w-5" />
Source Transcript
</CardTitle>
</CardHeader>
<CardContent>
<a
href={session.fullTranscriptUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 rounded-sm"
aria-label="Open original transcript in new tab"
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-sky-100 p-4 md:p-6">
<div className="max-w-4xl mx-auto">
<div className="mb-6">
<Link
href="/dashboard/sessions"
className="text-sky-700 hover:text-sky-900 hover:underline flex items-center"
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-5 w-5 mr-1"
viewBox="0 0 20 20"
fill="currentColor"
>
<ExternalLink className="h-4 w-4" aria-hidden="true" />
View Original Transcript
</a>
</CardContent>
</Card>
)}
<path
fillRule="evenodd"
d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
clipRule="evenodd"
/>
</svg>
Back to Sessions List
</Link>
</div>
<h1 className="text-3xl font-bold text-gray-800 mb-6">
Session: {session.sessionId || session.id}
</h1>
<div className="grid grid-cols-1 gap-6">
<div>
<SessionDetails session={session} />
</div>
{/* Show parsed messages if available */}
{session.messages && session.messages.length > 0 && (
<div>
<MessageViewer messages={session.messages} />
</div>
)}
{/* Show transcript URL if available */}
{session.fullTranscriptUrl && (
<div className="bg-white p-4 rounded-lg shadow">
<h3 className="font-bold text-lg mb-3">Source Transcript</h3>
<a
href={session.fullTranscriptUrl}
target="_blank"
rel="noopener noreferrer"
className="text-sky-600 hover:underline"
>
View Original Transcript
</a>
</div>
)}
</div>
</div>
</div>
);
}

View File

@ -1,26 +1,8 @@
"use client";
import {
ChevronDown,
ChevronLeft,
ChevronRight,
ChevronUp,
Clock,
Eye,
Filter,
Globe,
MessageSquare,
Search,
} from "lucide-react";
import { useState, useEffect, useCallback } from "react";
import { ChatSession } from "../../../lib/types";
import Link from "next/link";
import { useCallback, useEffect, useId, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { formatCategory } from "@/lib/format-enums";
import type { ChatSession } from "../../../lib/types";
// Placeholder for a SessionListItem component to be created later
// For now, we'll display some basic info directly.
@ -38,23 +20,6 @@ export default function SessionsPage() {
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState("");
const searchHeadingId = useId();
const filtersHeadingId = useId();
const filterContentId = useId();
const categoryFilterId = useId();
const categoryHelpId = useId();
const languageFilterId = useId();
const languageHelpId = useId();
const sortOrderId = useId();
const sortOrderHelpId = useId();
const resultsHeadingId = useId();
const startDateFilterId = useId();
const startDateHelpId = useId();
const endDateFilterId = useId();
const endDateHelpId = useId();
const sortKeyId = useId();
const sortKeyHelpId = useId();
// Filter states
const [filterOptions, setFilterOptions] = useState<FilterOptions>({
categories: [],
@ -76,10 +41,7 @@ export default function SessionsPage() {
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const [pageSize, _setPageSize] = useState(10); // Or make this configurable
// UI states
const [filtersExpanded, setFiltersExpanded] = useState(false);
const [pageSize, setPageSize] = useState(10); // Or make this configurable
useEffect(() => {
const timerId = setTimeout(() => {
@ -158,390 +120,228 @@ export default function SessionsPage() {
}, [fetchFilterOptions]);
return (
<div className="space-y-6">
{/* Page heading for screen readers */}
<h1 className="sr-only">Sessions Management</h1>
{/* Header */}
<Card>
<CardHeader>
<div className="flex items-center gap-3">
<MessageSquare className="h-6 w-6" />
<CardTitle as="h2">Chat Sessions</CardTitle>
</div>
</CardHeader>
</Card>
<div className="p-4 md:p-6">
<h1 className="text-2xl font-semibold text-gray-800 mb-6">
Chat Sessions
</h1>
{/* Search Input */}
<section aria-labelledby={searchHeadingId}>
<h2 id={searchHeadingId} className="sr-only">
Search Sessions
</h2>
<Card>
<CardContent className="pt-6">
<div className="relative">
<Search
className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"
aria-hidden="true"
/>
<Input
placeholder="Search sessions (ID, category, initial message...)"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
aria-label="Search sessions by ID, category, or message content"
/>
</div>
</CardContent>
</Card>
</section>
<div className="mb-4">
<input
type="text"
placeholder="Search sessions (ID, category, initial message...)"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
{/* Filter and Sort Controls */}
<section aria-labelledby={filtersHeadingId}>
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Filter className="h-5 w-5" aria-hidden="true" />
<CardTitle as="h2" id={filtersHeadingId} className="text-lg">
Filters & Sorting
</CardTitle>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => setFiltersExpanded(!filtersExpanded)}
className="gap-2"
aria-expanded={filtersExpanded}
aria-controls={filterContentId}
>
{filtersExpanded ? (
<>
<ChevronUp className="h-4 w-4" />
Hide
</>
) : (
<>
<ChevronDown className="h-4 w-4" />
Show
</>
)}
</Button>
</div>
</CardHeader>
{filtersExpanded && (
<CardContent id={filterContentId}>
<fieldset>
<legend className="sr-only">
Session Filters and Sorting Options
</legend>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
{/* Category Filter */}
<div className="space-y-2">
<Label htmlFor={categoryFilterId}>Category</Label>
<select
id={categoryFilterId}
className="w-full h-10 px-3 py-2 text-sm rounded-md border border-input bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
value={selectedCategory}
onChange={(e) => setSelectedCategory(e.target.value)}
aria-describedby={categoryHelpId}
>
<option value="">All Categories</option>
{filterOptions.categories.map((cat) => (
<option key={cat} value={cat}>
{formatCategory(cat)}
</option>
))}
</select>
<div id={categoryHelpId} className="sr-only">
Filter sessions by category type
</div>
</div>
{/* Language Filter */}
<div className="space-y-2">
<Label htmlFor={languageFilterId}>Language</Label>
<select
id={languageFilterId}
className="w-full h-10 px-3 py-2 text-sm rounded-md border border-input bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
value={selectedLanguage}
onChange={(e) => setSelectedLanguage(e.target.value)}
aria-describedby={languageHelpId}
>
<option value="">All Languages</option>
{filterOptions.languages.map((lang) => (
<option key={lang} value={lang}>
{lang.toUpperCase()}
</option>
))}
</select>
<div id={languageHelpId} className="sr-only">
Filter sessions by language
</div>
</div>
{/* Start Date Filter */}
<div className="space-y-2">
<Label htmlFor={startDateFilterId}>Start Date</Label>
<Input
type="date"
id={startDateFilterId}
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
aria-describedby={startDateHelpId}
/>
<div id={startDateHelpId} className="sr-only">
Filter sessions from this date onwards
</div>
</div>
{/* End Date Filter */}
<div className="space-y-2">
<Label htmlFor={endDateFilterId}>End Date</Label>
<Input
type="date"
id={endDateFilterId}
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
aria-describedby={endDateHelpId}
/>
<div id={endDateHelpId} className="sr-only">
Filter sessions up to this date
</div>
</div>
{/* Sort Key */}
<div className="space-y-2">
<Label htmlFor={sortKeyId}>Sort By</Label>
<select
id={sortKeyId}
className="w-full h-10 px-3 py-2 text-sm rounded-md border border-input bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
value={sortKey}
onChange={(e) => setSortKey(e.target.value)}
aria-describedby={sortKeyHelpId}
>
<option value="startTime">Start Time</option>
<option value="category">Category</option>
<option value="language">Language</option>
<option value="sentiment">Sentiment</option>
<option value="messagesSent">Messages Sent</option>
<option value="avgResponseTime">
Avg. Response Time
</option>
</select>
<div id={sortKeyHelpId} className="sr-only">
Choose field to sort sessions by
</div>
</div>
{/* Sort Order */}
<div className="space-y-2">
<Label htmlFor={sortOrderId}>Order</Label>
<select
id={sortOrderId}
className="w-full h-10 px-3 py-2 text-sm rounded-md border border-input bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
value={sortOrder}
onChange={(e) =>
setSortOrder(e.target.value as "asc" | "desc")
}
aria-describedby={sortOrderHelpId}
>
<option value="desc">Descending</option>
<option value="asc">Ascending</option>
</select>
<div id={sortOrderHelpId} className="sr-only">
Choose ascending or descending order
</div>
</div>
</div>
</fieldset>
</CardContent>
)}
</Card>
</section>
{/* Results section */}
<section aria-labelledby={resultsHeadingId}>
<h2 id={resultsHeadingId} className="sr-only">
Session Results
</h2>
{/* Live region for screen reader announcements */}
<output aria-live="polite" className="sr-only">
{loading && "Loading sessions..."}
{error && `Error loading sessions: ${error}`}
{!loading &&
!error &&
sessions.length > 0 &&
`Found ${sessions.length} sessions`}
{!loading && !error && sessions.length === 0 && "No sessions found"}
</output>
{/* Loading State */}
{loading && (
<Card>
<CardContent className="pt-6">
<div
className="text-center py-8 text-muted-foreground"
aria-hidden="true"
>
Loading sessions...
</div>
</CardContent>
</Card>
)}
{/* Error State */}
{error && (
<Card>
<CardContent className="pt-6">
<div
className="text-center py-8 text-destructive"
role="alert"
aria-hidden="true"
>
Error: {error}
</div>
</CardContent>
</Card>
)}
{/* Empty State */}
{!loading && !error && sessions.length === 0 && (
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
{debouncedSearchTerm
? `No sessions found for "${debouncedSearchTerm}".`
: "No sessions found."}
</div>
</CardContent>
</Card>
)}
{/* Sessions List */}
{!loading && !error && sessions.length > 0 && (
<ul aria-label="Chat sessions" className="grid gap-4">
{sessions.map((session) => (
<li key={session.id}>
<Card className="hover:shadow-md transition-shadow">
<CardContent className="pt-6">
<article aria-labelledby={`session-${session.id}-title`}>
<header className="flex justify-between items-start mb-4">
<div className="space-y-2 flex-1">
<h3
id={`session-${session.id}-title`}
className="sr-only"
>
Session {session.sessionId || session.id} from{" "}
{new Date(session.startTime).toLocaleDateString()}
</h3>
<div className="flex items-center gap-3">
<Badge
variant="outline"
className="font-mono text-xs"
>
ID
</Badge>
<code className="text-sm text-muted-foreground font-mono truncate max-w-24">
{session.sessionId || session.id}
</code>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="text-xs">
<Clock
className="h-3 w-3 mr-1"
aria-hidden="true"
/>
{new Date(session.startTime).toLocaleDateString()}
</Badge>
<span className="text-xs text-muted-foreground">
{new Date(session.startTime).toLocaleTimeString()}
</span>
</div>
</div>
<Link href={`/dashboard/sessions/${session.id}`}>
<Button
variant="outline"
size="sm"
className="gap-2"
aria-label={`View details for session ${session.sessionId || session.id}`}
>
<Eye className="h-4 w-4" aria-hidden="true" />
<span className="hidden sm:inline">
View Details
</span>
</Button>
</Link>
</header>
<div className="flex flex-wrap gap-2 mb-3">
{session.category && (
<Badge variant="secondary" className="gap-1">
<Filter className="h-3 w-3" aria-hidden="true" />
{formatCategory(session.category)}
</Badge>
)}
{session.language && (
<Badge variant="outline" className="gap-1">
<Globe className="h-3 w-3" aria-hidden="true" />
{session.language.toUpperCase()}
</Badge>
)}
</div>
{session.summary ? (
<p className="text-sm text-muted-foreground line-clamp-2">
{session.summary}
</p>
) : session.initialMsg ? (
<p className="text-sm text-muted-foreground line-clamp-2">
{session.initialMsg}
</p>
) : null}
</article>
</CardContent>
</Card>
</li>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 p-4 bg-gray-50 rounded-lg shadow">
{/* Category Filter */}
<div>
<label
htmlFor="category-filter"
className="block text-sm font-medium text-gray-700 mb-1"
>
Category
</label>
<select
id="category-filter"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={selectedCategory}
onChange={(e) => setSelectedCategory(e.target.value)}
>
<option value="">All Categories</option>
{filterOptions.categories.map((cat) => (
<option key={cat} value={cat}>
{cat}
</option>
))}
</ul>
)}
</select>
</div>
{/* Pagination */}
{totalPages > 0 && (
<Card>
<CardContent className="pt-6">
<div className="flex justify-center items-center gap-4">
<Button
variant="outline"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
disabled={currentPage === 1}
className="gap-2"
>
<ChevronLeft className="h-4 w-4" />
Previous
</Button>
<span className="text-sm text-muted-foreground">
Page {currentPage} of {totalPages}
</span>
<Button
variant="outline"
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
disabled={currentPage === totalPages}
className="gap-2"
>
Next
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
)}
</section>
{/* Language Filter */}
<div>
<label
htmlFor="language-filter"
className="block text-sm font-medium text-gray-700 mb-1"
>
Language
</label>
<select
id="language-filter"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={selectedLanguage}
onChange={(e) => setSelectedLanguage(e.target.value)}
>
<option value="">All Languages</option>
{filterOptions.languages.map((lang) => (
<option key={lang} value={lang}>
{lang.toUpperCase()}
</option>
))}
</select>
</div>
{/* Start Date Filter */}
<div>
<label
htmlFor="start-date-filter"
className="block text-sm font-medium text-gray-700 mb-1"
>
Start Date
</label>
<input
type="date"
id="start-date-filter"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
</div>
{/* End Date Filter */}
<div>
<label
htmlFor="end-date-filter"
className="block text-sm font-medium text-gray-700 mb-1"
>
End Date
</label>
<input
type="date"
id="end-date-filter"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</div>
{/* Sort Key */}
<div>
<label
htmlFor="sort-key"
className="block text-sm font-medium text-gray-700 mb-1"
>
Sort By
</label>
<select
id="sort-key"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={sortKey}
onChange={(e) => setSortKey(e.target.value)}
>
<option value="startTime">Start Time</option>
<option value="category">Category</option>
<option value="language">Language</option>
<option value="sentiment">Sentiment</option>
<option value="messagesSent">Messages Sent</option>
<option value="avgResponseTime">Avg. Response Time</option>
</select>
</div>
{/* Sort Order */}
<div>
<label
htmlFor="sort-order"
className="block text-sm font-medium text-gray-700 mb-1"
>
Order
</label>
<select
id="sort-order"
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
value={sortOrder}
onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")}
>
<option value="desc">Descending</option>
<option value="asc">Ascending</option>
</select>
</div>
</div>
{loading && <p className="text-gray-600">Loading sessions...</p>}
{error && <p className="text-red-500">Error: {error}</p>}
{!loading && !error && sessions.length === 0 && (
<p className="text-gray-600">
{debouncedSearchTerm
? `No sessions found for "${debouncedSearchTerm}".`
: "No sessions found."}
</p>
)}
{!loading && !error && sessions.length > 0 && (
<div className="space-y-4">
{sessions.map((session) => (
<div
key={session.id}
className="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow"
>
<h2 className="text-lg font-semibold text-sky-700 mb-1">
Session ID: {session.sessionId || session.id}
</h2>
<p className="text-sm text-gray-500 mb-1">
Start Time{/* (Local) */}:{" "}
{new Date(session.startTime).toLocaleString()}
</p>
{/* <p className="text-xs text-gray-400 mb-1">
Start Time (Raw API): {session.startTime.toString()}
</p> */}
{session.category && (
<p className="text-sm text-gray-700">
Category:{" "}
<span className="font-medium">{session.category}</span>
</p>
)}
{session.language && (
<p className="text-sm text-gray-700">
Language:{" "}
<span className="font-medium">
{session.language.toUpperCase()}
</span>
</p>
)}
{session.initialMsg && (
<p className="text-sm text-gray-600 mt-1 truncate">
Initial Message: {session.initialMsg}
</p>
)}
<Link
href={`/dashboard/sessions/${session.id}`}
className="mt-2 text-sm text-sky-600 hover:text-sky-800 hover:underline inline-block"
>
View Details
</Link>
</div>
))}
</div>
)}
{totalPages > 0 && (
<div className="mt-6 flex justify-center items-center space-x-2">
<button
onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
disabled={currentPage === 1}
className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
>
Previous
</button>
<span className="text-sm text-gray-700">
Page {currentPage} of {totalPages}
</span>
<button
onClick={() =>
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
}
disabled={currentPage === totalPages}
className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
>
Next
</button>
</div>
)}
</div>
);
}

View File

@ -1,7 +1,7 @@
"use client";
import type { Session } from "next-auth";
import { useState } from "react";
import type { Company } from "../../lib/types";
import { Company } from "../../lib/types";
import { Session } from "next-auth";
interface DashboardSettingsProps {
company: Company;
@ -37,7 +37,7 @@ export default function DashboardSettings({
else setMessage("Failed.");
}
if (session.user.role !== "ADMIN") return null;
if (session.user.role !== "admin") return null;
return (
<div className="bg-white p-6 rounded-xl shadow mb-6">

View File

@ -1,6 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import type { UserSession } from "../../lib/types";
import { useState, useEffect } from "react";
import { UserSession } from "../../lib/types";
interface UserItem {
id: string;
@ -34,7 +34,7 @@ export default function UserManagement({ session }: UserManagementProps) {
else setMsg("Failed.");
}
if (session.user.role !== "ADMIN") return null;
if (session.user.role !== "admin") return null;
return (
<div className="bg-white p-6 rounded-xl shadow mb-6">
@ -52,11 +52,10 @@ export default function UserManagement({ session }: UserManagementProps) {
onChange={(e) => setRole(e.target.value)}
>
<option value="user">User</option>
<option value="ADMIN">Admin</option>
<option value="AUDITOR">Auditor</option>
<option value="admin">Admin</option>
<option value="auditor">Auditor</option>
</select>
<button
type="button"
className="bg-blue-600 text-white rounded px-4 py-2 sm:py-0 w-full sm:w-auto"
onClick={inviteUser}
>

View File

@ -1,29 +1,7 @@
"use client";
import { AlertCircle, Eye, Shield, UserPlus, Users } from "lucide-react";
import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useCallback, useEffect, useId, useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
interface UserItem {
id: string;
@ -35,12 +13,17 @@ export default function UserManagementPage() {
const { data: session, status } = useSession();
const [users, setUsers] = useState<UserItem[]>([]);
const [email, setEmail] = useState<string>("");
const [role, setRole] = useState<string>("USER");
const [role, setRole] = useState<string>("user");
const [message, setMessage] = useState<string>("");
const [loading, setLoading] = useState(true);
const emailId = useId();
const fetchUsers = useCallback(async () => {
useEffect(() => {
if (status === "authenticated") {
fetchUsers();
}
}, [status]);
const fetchUsers = async () => {
setLoading(true);
try {
const res = await fetch("/api/dashboard/users");
@ -52,19 +35,7 @@ export default function UserManagementPage() {
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (status === "authenticated") {
if (session?.user?.role === "ADMIN") {
fetchUsers();
} else {
setLoading(false); // Stop loading for non-admin users
}
} else if (status === "unauthenticated") {
setLoading(false);
}
}, [status, session?.user?.role, fetchUsers]);
};
async function inviteUser() {
setMessage("");
@ -94,180 +65,148 @@ export default function UserManagementPage() {
// Loading state
if (loading) {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8 text-muted-foreground">
Loading users...
</div>
</CardContent>
</Card>
</div>
);
return <div className="text-center py-10">Loading users...</div>;
}
// Check for admin access
if (session?.user?.role !== "ADMIN") {
if (session?.user?.role !== "admin") {
return (
<div className="space-y-6">
<Card>
<CardContent className="pt-6">
<div className="text-center py-8">
<AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
<h2 className="font-bold text-xl text-destructive mb-2">
Access Denied
</h2>
<p className="text-muted-foreground">
You don&apos;t have permission to view user management.
</p>
</div>
</CardContent>
</Card>
<div className="text-center py-10 bg-white rounded-xl shadow p-6">
<h2 className="font-bold text-xl text-red-600 mb-2">Access Denied</h2>
<p>You don&apos;t have permission to view user management.</p>
</div>
);
}
return (
<div className="space-y-6" data-testid="user-management-page">
{/* Header */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="h-6 w-6" />
User Management
</CardTitle>
</CardHeader>
</Card>
<div className="space-y-6">
<div className="bg-white p-6 rounded-xl shadow">
<h1 className="text-2xl font-bold text-gray-800 mb-6">
User Management
</h1>
{/* Message Alert */}
{message && (
<Alert variant={message.includes("Failed") ? "destructive" : "default"}>
<AlertDescription>{message}</AlertDescription>
</Alert>
)}
{message && (
<div
className={`p-4 rounded mb-6 ${message.includes("Failed") ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"}`}
>
{message}
</div>
)}
{/* Invite New User */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<UserPlus className="h-5 w-5" />
Invite New User
</CardTitle>
</CardHeader>
<CardContent>
<div className="mb-8">
<h2 className="text-lg font-semibold mb-4">Invite New User</h2>
<form
className="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end"
onSubmit={(e) => {
e.preventDefault();
inviteUser();
}}
autoComplete="off"
data-testid="invite-form"
autoComplete="off" // Disable autofill for the form
>
<div className="space-y-2">
<Label htmlFor={emailId}>Email</Label>
<Input
id={emailId}
<div className="grid gap-2">
<label className="font-medium text-gray-700">Email</label>
<input
type="email"
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500"
placeholder="user@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoComplete="off"
autoComplete="off" // Disable autofill for this input
/>
</div>
<div className="space-y-2">
<Label htmlFor="role">Role</Label>
<Select value={role} onValueChange={setRole}>
<SelectTrigger>
<SelectValue placeholder="Select role" />
</SelectTrigger>
<SelectContent>
<SelectItem value="USER">User</SelectItem>
<SelectItem value="ADMIN">Admin</SelectItem>
<SelectItem value="AUDITOR">Auditor</SelectItem>
</SelectContent>
</Select>
<div className="grid gap-2">
<label className="font-medium text-gray-700">Role</label>
<select
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500 bg-white"
value={role}
onChange={(e) => setRole(e.target.value)}
>
<option value="user">User</option>
<option value="admin">Admin</option>
<option value="auditor">Auditor</option>
</select>
</div>
<Button type="submit" className="gap-2">
<UserPlus className="h-4 w-4" />
<button
type="submit"
className="bg-sky-600 hover:bg-sky-700 text-white py-2 px-4 rounded-lg shadow transition-colors"
>
Invite User
</Button>
</button>
</form>
</CardContent>
</Card>
</div>
{/* Current Users */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="h-5 w-5" />
Current Users ({users?.length || 0})
</CardTitle>
</CardHeader>
<CardContent>
<div>
<h2 className="text-lg font-semibold mb-4">Current Users</h2>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Role</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Email
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Role
</th>
<th
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{users.length === 0 ? (
<TableRow>
<TableCell
<tr>
<td
colSpan={3}
className="text-center text-muted-foreground"
className="px-6 py-4 text-center text-sm text-gray-500"
>
No users found
</TableCell>
</TableRow>
</td>
</tr>
) : (
users.map((user) => (
<TableRow key={user.id}>
<TableCell className="font-medium">
<tr key={user.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{user.email}
</TableCell>
<TableCell>
<Badge
variant={
user.role === "ADMIN"
? "default"
: user.role === "AUDITOR"
? "secondary"
: "outline"
}
className="gap-1"
data-testid="role-badge"
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<span
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.role === "admin"
? "bg-purple-100 text-purple-800"
: user.role === "auditor"
? "bg-blue-100 text-blue-800"
: "bg-green-100 text-green-800"
}`}
>
{user.role === "ADMIN" && (
<Shield className="h-3 w-3" />
)}
{user.role === "AUDITOR" && (
<Eye className="h-3 w-3" />
)}
{user.role}
</Badge>
</TableCell>
<TableCell>
<span className="text-muted-foreground text-sm">
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{/* For future: Add actions like edit, delete, etc. */}
<span className="text-gray-400">
No actions available
</span>
</TableCell>
</TableRow>
</td>
</tr>
))
)}
</TableBody>
</Table>
</tbody>
</table>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
);
}

View File

@ -39,77 +39,6 @@
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--animate-shine: shine var(--duration) infinite linear;
@keyframes shine {
0% {
background-position: 0% 0%;
}
50% {
background-position: 100% 100%;
}
to {
background-position: 0% 0%;
}
}
--animate-meteor: meteor 5s linear infinite;
@keyframes meteor {
0% {
transform: rotate(var(--angle)) translateX(0);
opacity: 1;
}
70% {
opacity: 1;
}
100% {
transform: rotate(var(--angle)) translateX(-500px);
opacity: 0;
}
}
--animate-background-position-spin: background-position-spin 3000ms infinite
alternate;
@keyframes background-position-spin {
0% {
background-position: top center;
}
100% {
background-position: bottom center;
}
}
--animate-aurora: aurora 8s ease-in-out infinite alternate;
@keyframes aurora {
0% {
background-position: 0% 50%;
transform: rotate(-5deg) scale(0.9);
}
25% {
background-position: 50% 100%;
transform: rotate(5deg) scale(1.1);
}
50% {
background-position: 100% 50%;
transform: rotate(-3deg) scale(0.95);
}
75% {
background-position: 50% 0%;
transform: rotate(3deg) scale(1.05);
}
100% {
background-position: 0% 50%;
transform: rotate(-5deg) scale(0.9);
}
}
--animate-shiny-text: shiny-text 8s infinite;
@keyframes shiny-text {
0%,
90%,
100% {
background-position: calc(-100% - var(--shiny-width)) 0;
}
30%,
60% {
background-position: calc(100% + var(--shiny-width)) 0;
}
}
}
:root {
@ -120,18 +49,18 @@
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.5 0.2 240);
--primary-foreground: oklch(0.98 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.45 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.15 0 0);
--destructive: oklch(0.55 0.245 27.325);
--border: oklch(0.85 0 0);
--input: oklch(0.85 0 0);
--ring: oklch(0.6 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
@ -154,18 +83,18 @@
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.7 0.2 240);
--primary-foreground: oklch(0.15 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.75 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.75 0.191 22.216);
--border: oklch(1 0 0 / 25%);
--input: oklch(1 0 0 / 30%);
--ring: oklch(0.75 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
@ -183,17 +112,9 @@
@layer base {
* {
@apply border-border outline-ring/50 selection:bg-primary/30 selection:text-primary-foreground;
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
/* Line clamp utility */
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
}

View File

@ -1,79 +1,12 @@
// Main app layout with basic global style
import "./globals.css";
import type { ReactNode } from "react";
import { Toaster } from "@/components/ui/sonner";
import { ReactNode } from "react";
import { Providers } from "./providers";
export const metadata = {
title: "LiveDash - AI-Powered Customer Conversation Analytics",
title: "LiveDash-Node",
description:
"Transform customer conversations into actionable insights with advanced AI sentiment analysis, automated categorization, and real-time analytics. Turn every conversation into competitive intelligence.",
keywords: [
"customer analytics",
"AI sentiment analysis",
"conversation intelligence",
"customer support analytics",
"chat analytics",
"customer insights",
"conversation analytics",
"customer experience analytics",
"sentiment tracking",
"AI customer intelligence",
"automated categorization",
"real-time analytics",
"customer conversation dashboard",
],
authors: [{ name: "Notso AI" }],
creator: "Notso AI",
publisher: "Notso AI",
formatDetection: {
email: false,
address: false,
telephone: false,
},
metadataBase: new URL(
process.env.NEXTAUTH_URL || "https://livedash.notso.ai"
),
alternates: {
canonical: "/",
},
openGraph: {
title: "LiveDash - AI-Powered Customer Conversation Analytics",
description:
"Transform customer conversations into actionable insights with advanced AI sentiment analysis, automated categorization, and real-time analytics. Turn every conversation into competitive intelligence.",
type: "website",
siteName: "LiveDash",
url: "/",
locale: "en_US",
images: [
{
url: "/og-image.png",
width: 1200,
height: 630,
alt: "LiveDash - AI-Powered Customer Conversation Analytics Platform",
},
],
},
twitter: {
card: "summary_large_image",
title: "LiveDash - AI-Powered Customer Conversation Analytics",
description:
"Transform customer conversations into actionable insights with advanced AI sentiment analysis, automated categorization, and real-time analytics.",
creator: "@notsoai",
site: "@notsoai",
images: ["/og-image.png"],
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
"max-video-preview": -1,
"max-image-preview": "large",
"max-snippet": -1,
},
},
"Multi-tenant dashboard system for tracking chat session metrics",
icons: {
icon: [
{ url: "/favicon.ico", sizes: "32x32", type: "image/x-icon" },
@ -82,64 +15,13 @@ export const metadata = {
apple: "/icon-192.svg",
},
manifest: "/manifest.json",
other: {
"msapplication-TileColor": "#2563eb",
"theme-color": "#ffffff",
},
};
export default function RootLayout({ children }: { children: ReactNode }) {
const jsonLd = {
"@context": "https://schema.org",
"@type": "SoftwareApplication",
name: "LiveDash",
description:
"Transform customer conversations into actionable insights with advanced AI sentiment analysis, automated categorization, and real-time analytics.",
url: process.env.NEXTAUTH_URL || "https://livedash.notso.ai",
author: {
"@type": "Organization",
name: "Notso AI",
},
applicationCategory: "Business Analytics Software",
operatingSystem: "Web Browser",
offers: {
"@type": "Offer",
category: "SaaS",
},
aggregateRating: {
"@type": "AggregateRating",
ratingValue: "4.8",
ratingCount: "150",
},
featureList: [
"AI-powered sentiment analysis",
"Automated conversation categorization",
"Real-time analytics dashboard",
"Multi-language support",
"Custom AI model integration",
"Enterprise-grade security",
],
};
return (
<html lang="en" suppressHydrationWarning>
<head>
<script
type="application/ld+json"
// biome-ignore lint/security/noDangerouslySetInnerHtml: Safe use for JSON-LD structured data
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
</head>
<body className="bg-background text-foreground min-h-screen font-sans antialiased">
{/* Skip navigation link for keyboard users */}
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-50 focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded focus:outline-none focus:ring-2 focus:ring-ring"
>
Skip to main content
</a>
<html lang="en">
<body className="bg-gray-100 min-h-screen font-sans">
<Providers>{children}</Providers>
<Toaster />
</body>
</html>
);

View File

@ -1,270 +1,59 @@
"use client";
import { BarChart3, Loader2, Shield, Zap } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { signIn } from "next-auth/react";
import { useId, useState } from "react";
import { toast } from "sonner";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ThemeToggle } from "@/components/ui/theme-toggle";
import { useRouter } from "next/navigation";
export default function LoginPage() {
const emailId = useId();
const emailHelpId = useId();
const passwordId = useId();
const passwordHelpId = useId();
const loadingStatusId = useId();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
async function handleLogin(e: React.FormEvent) {
e.preventDefault();
setIsLoading(true);
setError("");
try {
const res = await signIn("credentials", {
email,
password,
redirect: false,
});
if (res?.ok) {
toast.success("Login successful! Redirecting...");
router.push("/dashboard");
} else {
setError("Invalid email or password. Please try again.");
toast.error("Login failed. Please check your credentials.");
}
} catch {
setError("An error occurred. Please try again.");
toast.error("An unexpected error occurred.");
} finally {
setIsLoading(false);
}
const res = await signIn("credentials", {
email,
password,
redirect: false,
});
if (res?.ok) router.push("/dashboard");
else setError("Invalid credentials.");
}
return (
<div className="min-h-screen flex">
{/* Left side - Branding and Features */}
<div className="hidden lg:flex lg:flex-1 bg-linear-to-br from-primary/10 via-primary/5 to-background relative overflow-hidden">
<div className="absolute inset-0 bg-linear-to-br from-primary/5 to-transparent" />
<div className="absolute -top-24 -left-24 h-96 w-96 rounded-full bg-primary/10 blur-3xl" />
<div className="absolute -bottom-24 -right-24 h-96 w-96 rounded-full bg-primary/5 blur-3xl" />
<div className="relative flex flex-col justify-center px-12 py-24">
<div className="max-w-md">
<Link href="/" className="flex items-center gap-3 mb-8">
<div className="relative w-12 h-12">
<Image
src="/favicon.svg"
alt="LiveDash Logo"
fill
className="object-contain"
/>
</div>
<span className="text-2xl font-bold text-primary">LiveDash</span>
</Link>
<h1 className="text-4xl font-bold tracking-tight mb-6">
Welcome back to your analytics dashboard
</h1>
<p className="text-xl text-muted-foreground mb-8">
Monitor, analyze, and optimize your customer conversations with
AI-powered insights.
</p>
<div className="space-y-4">
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-primary/10 text-primary">
<BarChart3 className="h-5 w-5" />
</div>
<span className="text-muted-foreground">
Real-time analytics and insights
</span>
</div>
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-green-500/10 text-green-600">
<Shield className="h-5 w-5" />
</div>
<span className="text-muted-foreground">
Enterprise-grade security
</span>
</div>
<div className="flex items-center gap-3">
<div className="p-2 rounded-lg bg-blue-500/10 text-blue-600">
<Zap className="h-5 w-5" />
</div>
<span className="text-muted-foreground">
AI-powered conversation analysis
</span>
</div>
</div>
</div>
</div>
<div className="max-w-md mx-auto mt-24 bg-white rounded-xl p-8 shadow">
<h1 className="text-2xl font-bold mb-6">Login</h1>
{error && <div className="text-red-600 mb-3">{error}</div>}
<form onSubmit={handleLogin} className="flex flex-col gap-4">
<input
className="border px-3 py-2 rounded"
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
className="border px-3 py-2 rounded"
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button className="bg-blue-600 text-white rounded py-2" type="submit">
Login
</button>
</form>
<div className="mt-4 text-center">
<a href="/register" className="text-blue-600 underline">
Register company
</a>
</div>
{/* Right side - Login Form */}
<div className="flex-1 flex flex-col justify-center px-8 py-12 lg:px-12">
<div className="absolute top-4 right-4">
<ThemeToggle />
</div>
<div className="mx-auto w-full max-w-sm">
{/* Mobile logo */}
<div className="lg:hidden flex justify-center mb-8">
<Link href="/" className="flex items-center gap-3">
<div className="relative w-10 h-10">
<Image
src="/favicon.svg"
alt="LiveDash Logo"
fill
className="object-contain"
/>
</div>
<span className="text-xl font-bold text-primary">LiveDash</span>
</Link>
</div>
<Card className="border-border/50 shadow-xl">
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-bold">Sign in</CardTitle>
<CardDescription>
Enter your email and password to access your dashboard
</CardDescription>
</CardHeader>
<CardContent>
{/* Live region for screen reader announcements */}
<output aria-live="polite" className="sr-only">
{isLoading && "Signing in, please wait..."}
{error && `Error: ${error}`}
</output>
{error && (
<Alert variant="destructive" className="mb-6" role="alert">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<form onSubmit={handleLogin} className="space-y-4" noValidate>
<div className="space-y-2">
<Label htmlFor={emailId}>Email</Label>
<Input
id={emailId}
type="email"
placeholder="name@company.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isLoading}
required
aria-describedby={emailHelpId}
aria-invalid={!!error}
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20"
/>
<div id={emailHelpId} className="sr-only">
Enter your company email address
</div>
</div>
<div className="space-y-2">
<Label htmlFor={passwordId}>Password</Label>
<Input
id={passwordId}
type="password"
placeholder="Enter your password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={isLoading}
required
aria-describedby={passwordHelpId}
aria-invalid={!!error}
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20"
/>
<div id={passwordHelpId} className="sr-only">
Enter your account password
</div>
</div>
<Button
type="submit"
className="w-full mt-6 h-11 bg-linear-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 transition-all duration-200"
disabled={isLoading || !email || !password}
aria-describedby={isLoading ? "loading-status" : undefined}
>
{isLoading ? (
<>
<Loader2
className="mr-2 h-4 w-4 animate-spin"
aria-hidden="true"
/>
Signing in...
</>
) : (
"Sign in"
)}
</Button>
{isLoading && (
<div
id={loadingStatusId}
className="sr-only"
aria-live="polite"
>
Authentication in progress, please wait
</div>
)}
</form>
<div className="mt-6 space-y-4">
<div className="text-center">
<Link
href="/register"
className="text-sm text-primary hover:underline transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 rounded-sm"
>
Don&apos;t have a company account? Register here
</Link>
</div>
<div className="text-center">
<Link
href="/forgot-password"
className="text-sm text-muted-foreground hover:text-foreground transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 rounded-sm"
>
Forgot your password?
</Link>
</div>
</div>
</CardContent>
</Card>
<p className="mt-8 text-center text-xs text-muted-foreground">
By signing in, you agree to our{" "}
<Link
href="/terms"
className="text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 rounded-sm"
>
Terms of Service
</Link>{" "}
and{" "}
<Link
href="/privacy"
className="text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 rounded-sm"
>
Privacy Policy
</Link>
</p>
</div>
<div className="mt-2 text-center">
<a href="/forgot-password" className="text-blue-600 underline">
Forgot password?
</a>
</div>
</div>
);

View File

@ -1,466 +1,9 @@
"use client";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { authOptions } from "./api/auth/[...nextauth]/route";
import {
ArrowRight,
BarChart3,
Brain,
Globe,
MessageCircle,
Shield,
Sparkles,
TrendingUp,
Zap,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
export default function LandingPage() {
const { data: session, status } = useSession();
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (session?.user) {
router.push("/dashboard");
}
}, [session, router]);
const handleGetStarted = () => {
setIsLoading(true);
router.push("/login");
};
const handleRequestDemo = () => {
// For now, redirect to contact - can be enhanced later
window.open("mailto:demo@notso.ai?subject=LiveDash Demo Request", "_blank");
};
if (status === "loading") {
return (
<div className="flex items-center justify-center min-h-screen">
Loading...
</div>
);
}
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900">
{/* Header */}
<header className="relative z-50 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-b">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-6">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-gradient-to-br from-blue-600 to-purple-600 rounded-lg flex items-center justify-center">
<BarChart3 className="w-6 h-6 text-white" />
</div>
<span className="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
LiveDash
</span>
</div>
<div className="flex items-center gap-4">
<Button variant="ghost" onClick={handleRequestDemo}>
Request Demo
</Button>
<Button onClick={handleGetStarted} disabled={isLoading}>
Get Started
<ArrowRight className="w-4 h-4 ml-2" />
</Button>
</div>
</div>
</div>
</header>
{/* Hero Section */}
<section className="relative py-20 lg:py-32">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center">
<Badge className="mb-8 bg-gradient-to-r from-blue-100 to-purple-100 text-blue-800 dark:from-blue-900 dark:to-purple-900 dark:text-blue-200">
<Sparkles className="w-4 h-4 mr-2" />
AI-Powered Analytics Platform
</Badge>
<h1 className="text-5xl lg:text-7xl font-bold mb-8 bg-gradient-to-r from-gray-900 via-blue-800 to-purple-800 dark:from-white dark:via-blue-200 dark:to-purple-200 bg-clip-text text-transparent leading-tight">
Transform Customer
<br />
Conversations into
<br />
<span className="bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
Actionable Insights
</span>
</h1>
<p className="text-xl lg:text-2xl text-gray-600 dark:text-gray-300 mb-12 max-w-4xl mx-auto leading-relaxed">
LiveDash analyzes your customer support conversations with
advanced AI to deliver real-time sentiment analysis, automated
categorization, and powerful analytics that drive better business
decisions.
</p>
<div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
<Button
size="lg"
className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white px-8 py-4 text-lg"
onClick={handleGetStarted}
disabled={isLoading}
>
Start Free Trial
<ArrowRight className="w-5 h-5 ml-2" />
</Button>
<Button
size="lg"
variant="outline"
className="px-8 py-4 text-lg"
onClick={handleRequestDemo}
>
Watch Demo
</Button>
</div>
</div>
</div>
</section>
{/* Features Section */}
<section className="py-20 bg-white/50 dark:bg-gray-800/50">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center mb-16">
<h2 className="text-4xl font-bold mb-6 text-gray-900 dark:text-white">
Powerful Features for Modern Teams
</h2>
<p className="text-xl text-gray-600 dark:text-gray-300 max-w-2xl mx-auto">
Everything you need to understand and optimize your customer
interactions
</p>
</div>
<div className="max-w-4xl mx-auto space-y-8">
{/* Feature Stack */}
<div className="relative">
{/* Connection Lines */}
<div className="absolute left-1/2 top-0 bottom-0 w-px bg-gradient-to-b from-blue-200 via-purple-200 to-transparent dark:from-blue-800 dark:via-purple-800 transform -translate-x-1/2 z-0" />
{/* Feature Cards */}
<div className="space-y-16 relative z-10">
{/* AI Sentiment Analysis */}
<div className="flex items-center gap-8 group">
<div className="flex-1 text-right">
<div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 group-hover:shadow-xl transition-all duration-300 group-hover:scale-105">
<h3 className="text-2xl font-bold mb-3 text-gray-900 dark:text-white">
AI Sentiment Analysis
</h3>
<p className="text-gray-600 dark:text-gray-300 text-lg">
Automatically analyze customer emotions and satisfaction
levels across all conversations with 99.9% accuracy
</p>
</div>
</div>
<div className="w-16 h-16 bg-gradient-to-br from-blue-500 to-blue-600 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-6 transition-all duration-300">
<Brain className="w-8 h-8 text-white" />
</div>
<div className="flex-1" />
</div>
{/* Smart Categorization */}
<div className="flex items-center gap-8 group">
<div className="flex-1" />
<div className="w-16 h-16 bg-gradient-to-br from-purple-500 to-purple-600 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-6 transition-all duration-300">
<MessageCircle className="w-8 h-8 text-white" />
</div>
<div className="flex-1">
<div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 group-hover:shadow-xl transition-all duration-300 group-hover:scale-105">
<h3 className="text-2xl font-bold mb-3 text-gray-900 dark:text-white">
Smart Categorization
</h3>
<p className="text-gray-600 dark:text-gray-300 text-lg">
Intelligently categorize conversations by topic,
urgency, and department automatically using advanced ML
</p>
</div>
</div>
</div>
{/* Real-time Analytics */}
<div className="flex items-center gap-8 group">
<div className="flex-1 text-right">
<div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 group-hover:shadow-xl transition-all duration-300 group-hover:scale-105">
<h3 className="text-2xl font-bold mb-3 text-gray-900 dark:text-white">
Real-time Analytics
</h3>
<p className="text-gray-600 dark:text-gray-300 text-lg">
Get instant insights with beautiful dashboards and
real-time performance metrics that update live
</p>
</div>
</div>
<div className="w-16 h-16 bg-gradient-to-br from-green-500 to-green-600 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-6 transition-all duration-300">
<TrendingUp className="w-8 h-8 text-white" />
</div>
<div className="flex-1" />
</div>
{/* Enterprise Security */}
<div className="flex items-center gap-8 group">
<div className="flex-1" />
<div className="w-16 h-16 bg-gradient-to-br from-orange-500 to-orange-600 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-6 transition-all duration-300">
<Shield className="w-8 h-8 text-white" />
</div>
<div className="flex-1">
<div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 group-hover:shadow-xl transition-all duration-300 group-hover:scale-105">
<h3 className="text-2xl font-bold mb-3 text-gray-900 dark:text-white">
Enterprise Security
</h3>
<p className="text-gray-600 dark:text-gray-300 text-lg">
Bank-grade security with GDPR compliance, SOC 2
certification, and end-to-end encryption
</p>
</div>
</div>
</div>
{/* Lightning Fast */}
<div className="flex items-center gap-8 group">
<div className="flex-1 text-right">
<div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 group-hover:shadow-xl transition-all duration-300 group-hover:scale-105">
<h3 className="text-2xl font-bold mb-3 text-gray-900 dark:text-white">
Lightning Fast
</h3>
<p className="text-gray-600 dark:text-gray-300 text-lg">
Process thousands of conversations in seconds with our
optimized AI pipeline and global CDN
</p>
</div>
</div>
<div className="w-16 h-16 bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-6 transition-all duration-300">
<Zap className="w-8 h-8 text-white" />
</div>
<div className="flex-1" />
</div>
{/* Global Scale */}
<div className="flex items-center gap-8 group">
<div className="flex-1" />
<div className="w-16 h-16 bg-gradient-to-br from-indigo-500 to-indigo-600 rounded-2xl flex items-center justify-center shadow-lg group-hover:scale-110 group-hover:rotate-6 transition-all duration-300">
<Globe className="w-8 h-8 text-white" />
</div>
<div className="flex-1">
<div className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg border border-gray-100 dark:border-gray-700 group-hover:shadow-xl transition-all duration-300 group-hover:scale-105">
<h3 className="text-2xl font-bold mb-3 text-gray-900 dark:text-white">
Global Scale
</h3>
<p className="text-gray-600 dark:text-gray-300 text-lg">
Multi-language support with global infrastructure for
teams worldwide, serving 50+ countries
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
{/* Social Proof */}
<section className="py-20">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
<h2 className="text-3xl font-bold mb-12 text-gray-900 dark:text-white">
Trusted by Growing Companies
</h2>
<div className="grid md:grid-cols-3 gap-8 mb-16">
<div className="text-center">
<div className="text-4xl font-bold text-blue-600 mb-2">
10,000+
</div>
<div className="text-gray-600 dark:text-gray-300">
Conversations Analyzed Daily
</div>
</div>
<div className="text-center">
<div className="text-4xl font-bold text-purple-600 mb-2">
99.9%
</div>
<div className="text-gray-600 dark:text-gray-300">
Accuracy Rate
</div>
</div>
<div className="text-center">
<div className="text-4xl font-bold text-green-600 mb-2">50+</div>
<div className="text-gray-600 dark:text-gray-300">
Enterprise Customers
</div>
</div>
</div>
</div>
</section>
{/* CTA Section */}
<section className="py-20 bg-gradient-to-r from-blue-600 to-purple-600">
<div className="max-w-4xl mx-auto text-center px-4 sm:px-6 lg:px-8">
<h2 className="text-4xl lg:text-5xl font-bold text-white mb-6">
Ready to Transform Your Customer Insights?
</h2>
<p className="text-xl text-blue-100 mb-8 max-w-2xl mx-auto">
Join thousands of teams already using LiveDash to make data-driven
decisions and improve customer satisfaction.
</p>
<div className="flex flex-col sm:flex-row gap-4 justify-center">
<Button
size="lg"
className="bg-white text-blue-600 hover:bg-gray-100 px-8 py-4 text-lg font-semibold"
onClick={handleGetStarted}
disabled={isLoading}
>
Start Free Trial
<ArrowRight className="w-5 h-5 ml-2" />
</Button>
<Button
size="lg"
variant="outline"
className="border-white text-white hover:bg-white/10 px-8 py-4 text-lg"
onClick={handleRequestDemo}
>
Schedule Demo
</Button>
</div>
</div>
</section>
{/* Footer */}
<footer className="bg-gray-900 text-white py-12">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="grid md:grid-cols-4 gap-8">
<div>
<div className="flex items-center gap-3 mb-4">
<div className="w-8 h-8 bg-gradient-to-br from-blue-600 to-purple-600 rounded-lg flex items-center justify-center">
<BarChart3 className="w-5 h-5 text-white" />
</div>
<span className="text-xl font-bold">LiveDash</span>
</div>
<p className="text-gray-400">
AI-powered customer conversation analytics for modern teams.
</p>
</div>
<div>
<h3 className="font-semibold mb-4">Product</h3>
<ul className="space-y-2 text-gray-400">
<li>
<a
href="/features"
className="hover:text-white transition-colors"
>
Features
</a>
</li>
<li>
<a
href="/pricing"
className="hover:text-white transition-colors"
>
Pricing
</a>
</li>
<li>
<a href="/api" className="hover:text-white transition-colors">
API
</a>
</li>
<li>
<a
href="/integrations"
className="hover:text-white transition-colors"
>
Integrations
</a>
</li>
</ul>
</div>
<div>
<h3 className="font-semibold mb-4">Company</h3>
<ul className="space-y-2 text-gray-400">
<li>
<a
href="/about"
className="hover:text-white transition-colors"
>
About
</a>
</li>
<li>
<a
href="/blog"
className="hover:text-white transition-colors"
>
Blog
</a>
</li>
<li>
<a
href="/careers"
className="hover:text-white transition-colors"
>
Careers
</a>
</li>
<li>
<a
href="/contact"
className="hover:text-white transition-colors"
>
Contact
</a>
</li>
</ul>
</div>
<div>
<h3 className="font-semibold mb-4">Support</h3>
<ul className="space-y-2 text-gray-400">
<li>
<a
href="/docs"
className="hover:text-white transition-colors"
>
Documentation
</a>
</li>
<li>
<a
href="/help"
className="hover:text-white transition-colors"
>
Help Center
</a>
</li>
<li>
<a
href="/privacy"
className="hover:text-white transition-colors"
>
Privacy
</a>
</li>
<li>
<a
href="/terms"
className="hover:text-white transition-colors"
>
Terms
</a>
</li>
</ul>
</div>
</div>
<div className="border-t border-gray-800 mt-12 pt-8 text-center text-gray-400">
<p>&copy; 2024 Notso AI. All rights reserved.</p>
</div>
</div>
</footer>
</div>
);
export default async function HomePage() {
const session = await getServerSession(authOptions);
if (session?.user) redirect("/dashboard");
else redirect("/login");
}

View File

@ -1,806 +0,0 @@
"use client";
import {
Activity,
ArrowLeft,
Calendar,
Database,
Mail,
Save,
UserPlus,
Users,
} from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { useCallback, useEffect, useId, useState } from "react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
interface User {
id: string;
name: string;
email: string;
role: string;
createdAt: string;
invitedBy: string | null;
invitedAt: string | null;
}
interface Company {
id: string;
name: string;
email: string;
status: string;
maxUsers: number;
createdAt: string;
updatedAt: string;
users: User[];
_count: {
sessions: number;
imports: number;
};
}
export default function CompanyManagement() {
const { data: session, status } = useSession();
const router = useRouter();
const params = useParams();
const { toast } = useToast();
const companyNameFieldId = useId();
const companyEmailFieldId = useId();
const maxUsersFieldId = useId();
const inviteNameFieldId = useId();
const inviteEmailFieldId = useId();
const fetchCompany = useCallback(async () => {
try {
const response = await fetch(`/api/platform/companies/${params.id}`);
if (response.ok) {
const data = await response.json();
setCompany(data);
const companyData = {
name: data.name,
email: data.email,
status: data.status,
maxUsers: data.maxUsers,
};
setEditData(companyData);
setOriginalData(companyData);
} else {
toast({
title: "Error",
description: "Failed to load company data",
variant: "destructive",
});
}
} catch (error) {
console.error("Failed to fetch company:", error);
toast({
title: "Error",
description: "Failed to load company data",
variant: "destructive",
});
} finally {
setIsLoading(false);
}
}, [params.id, toast]);
const [company, setCompany] = useState<Company | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [editData, setEditData] = useState<Partial<Company>>({});
const [originalData, setOriginalData] = useState<Partial<Company>>({});
const [showInviteUser, setShowInviteUser] = useState(false);
const [inviteData, setInviteData] = useState({
name: "",
email: "",
role: "USER",
});
const [showUnsavedChangesDialog, setShowUnsavedChangesDialog] =
useState(false);
const [pendingNavigation, setPendingNavigation] = useState<string | null>(
null
);
// Function to check if data has been modified
const hasUnsavedChanges = useCallback(() => {
// Normalize data for comparison (handle null/undefined/empty string equivalence)
const normalizeValue = (value: string | number | null | undefined) => {
if (value === null || value === undefined || value === "") {
return "";
}
return value;
};
const normalizedEditData = {
name: normalizeValue(editData.name),
email: normalizeValue(editData.email),
status: normalizeValue(editData.status),
maxUsers: editData.maxUsers || 0,
};
const normalizedOriginalData = {
name: normalizeValue(originalData.name),
email: normalizeValue(originalData.email),
status: normalizeValue(originalData.status),
maxUsers: originalData.maxUsers || 0,
};
return (
JSON.stringify(normalizedEditData) !==
JSON.stringify(normalizedOriginalData)
);
}, [editData, originalData]);
// Handle navigation protection - must be at top level
const handleNavigation = useCallback(
(url: string) => {
// Allow navigation within the same company (different tabs, etc.)
if (url.includes(`/platform/companies/${params.id}`)) {
router.push(url);
return;
}
// If there are unsaved changes, show confirmation dialog
if (hasUnsavedChanges()) {
setPendingNavigation(url);
setShowUnsavedChangesDialog(true);
} else {
router.push(url);
}
},
[router, params.id, hasUnsavedChanges]
);
useEffect(() => {
if (status === "loading") return;
if (!session?.user?.isPlatformUser) {
router.push("/platform/login");
return;
}
fetchCompany();
}, [session, status, router, fetchCompany]);
const handleSave = async () => {
setIsSaving(true);
try {
const response = await fetch(`/api/platform/companies/${params.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(editData),
});
if (response.ok) {
const updatedCompany = await response.json();
setCompany(updatedCompany);
const companyData = {
name: updatedCompany.name,
email: updatedCompany.email,
status: updatedCompany.status,
maxUsers: updatedCompany.maxUsers,
};
setOriginalData(companyData);
toast({
title: "Success",
description: "Company updated successfully",
});
} else {
throw new Error("Failed to update company");
}
} catch (_error) {
toast({
title: "Error",
description: "Failed to update company",
variant: "destructive",
});
} finally {
setIsSaving(false);
}
};
const handleStatusChange = async (newStatus: string) => {
const statusAction = newStatus === "SUSPENDED" ? "suspend" : "activate";
try {
const response = await fetch(`/api/platform/companies/${params.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status: newStatus }),
});
if (response.ok) {
setCompany((prev) => (prev ? { ...prev, status: newStatus } : null));
setEditData((prev) => ({ ...prev, status: newStatus }));
toast({
title: "Success",
description: `Company ${statusAction}d successfully`,
});
} else {
throw new Error(`Failed to ${statusAction} company`);
}
} catch (_error) {
toast({
title: "Error",
description: `Failed to ${statusAction} company`,
variant: "destructive",
});
}
};
const confirmNavigation = () => {
if (pendingNavigation) {
router.push(pendingNavigation);
setPendingNavigation(null);
}
setShowUnsavedChangesDialog(false);
};
const cancelNavigation = () => {
setPendingNavigation(null);
setShowUnsavedChangesDialog(false);
};
// Protect against browser back/forward and other navigation
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (hasUnsavedChanges()) {
e.preventDefault();
e.returnValue = "";
}
};
const handlePopState = (e: PopStateEvent) => {
if (hasUnsavedChanges()) {
const confirmLeave = window.confirm(
"You have unsaved changes. Are you sure you want to leave this page?"
);
if (!confirmLeave) {
// Push the current state back to prevent navigation
window.history.pushState(null, "", window.location.href);
e.preventDefault();
}
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
window.addEventListener("popstate", handlePopState);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
window.removeEventListener("popstate", handlePopState);
};
}, [hasUnsavedChanges]);
const handleInviteUser = async () => {
try {
const response = await fetch(
`/api/platform/companies/${params.id}/users`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(inviteData),
}
);
if (response.ok) {
setShowInviteUser(false);
setInviteData({ name: "", email: "", role: "USER" });
fetchCompany(); // Refresh company data
toast({
title: "Success",
description: "User invited successfully",
});
} else {
throw new Error("Failed to invite user");
}
} catch (_error) {
toast({
title: "Error",
description: "Failed to invite user",
variant: "destructive",
});
}
};
const getStatusBadgeVariant = (status: string) => {
switch (status) {
case "ACTIVE":
return "default";
case "TRIAL":
return "secondary";
case "SUSPENDED":
return "destructive";
case "ARCHIVED":
return "outline";
default:
return "default";
}
};
if (status === "loading" || isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">Loading company details...</div>
</div>
);
}
if (!session?.user?.isPlatformUser || !company) {
return null;
}
const canEdit = session.user.platformRole === "SUPER_ADMIN";
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="border-b bg-white dark:bg-gray-800">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-6">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="sm"
onClick={() => handleNavigation("/platform/dashboard")}
>
<ArrowLeft className="w-4 h-4 mr-2" />
Back to Dashboard
</Button>
<div>
<div className="flex items-center gap-3">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
{company.name}
</h1>
<Badge variant={getStatusBadgeVariant(company.status)}>
{company.status}
</Badge>
</div>
<p className="text-sm text-gray-500 dark:text-gray-400">
Company Management
</p>
</div>
</div>
<div className="flex gap-2">
{canEdit && (
<Button
variant="outline"
size="sm"
onClick={() => setShowInviteUser(true)}
>
<UserPlus className="w-4 h-4 mr-2" />
Invite User
</Button>
)}
</div>
</div>
</div>
</div>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<Tabs defaultValue="overview" className="space-y-6">
<TabsList>
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="users">Users</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
<TabsTrigger value="analytics">Analytics</TabsTrigger>
</TabsList>
<TabsContent value="overview" className="space-y-6">
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Total Users
</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{company.users.length}
</div>
<p className="text-xs text-muted-foreground">
of {company.maxUsers} maximum
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Total Sessions
</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{company._count.sessions}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Data Imports
</CardTitle>
<Activity className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{company._count.imports}
</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Created</CardTitle>
<Calendar className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-sm font-bold">
{new Date(company.createdAt).toLocaleDateString()}
</div>
</CardContent>
</Card>
</div>
{/* Company Info */}
<Card>
<CardHeader>
<CardTitle>Company Information</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Label htmlFor={companyNameFieldId}>Company Name</Label>
<Input
id={companyNameFieldId}
value={editData.name || ""}
onChange={(e) =>
setEditData((prev) => ({
...prev,
name: e.target.value,
}))
}
disabled={!canEdit}
/>
</div>
<div>
<Label htmlFor={companyEmailFieldId}>Contact Email</Label>
<Input
id={companyEmailFieldId}
type="email"
value={editData.email || ""}
onChange={(e) =>
setEditData((prev) => ({
...prev,
email: e.target.value,
}))
}
disabled={!canEdit}
/>
</div>
<div>
<Label htmlFor={maxUsersFieldId}>Max Users</Label>
<Input
id={maxUsersFieldId}
type="number"
value={editData.maxUsers || 0}
onChange={(e) =>
setEditData((prev) => ({
...prev,
maxUsers: Number.parseInt(e.target.value),
}))
}
disabled={!canEdit}
/>
</div>
<div>
<Label htmlFor="status">Status</Label>
<Select
value={editData.status}
onValueChange={(value) =>
setEditData((prev) => ({ ...prev, status: value }))
}
disabled={!canEdit}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ACTIVE">Active</SelectItem>
<SelectItem value="TRIAL">Trial</SelectItem>
<SelectItem value="SUSPENDED">Suspended</SelectItem>
<SelectItem value="ARCHIVED">Archived</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{canEdit && hasUnsavedChanges() && (
<div className="flex gap-2 pt-4 border-t">
<Button
variant="outline"
onClick={() => {
setEditData(originalData);
}}
>
Cancel Changes
</Button>
<Button onClick={handleSave} disabled={isSaving}>
<Save className="w-4 h-4 mr-2" />
{isSaving ? "Saving..." : "Save Changes"}
</Button>
</div>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="users" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<span className="flex items-center gap-2">
<Users className="w-5 h-5" />
Users ({company.users.length})
</span>
{canEdit && (
<Button size="sm" onClick={() => setShowInviteUser(true)}>
<UserPlus className="w-4 h-4 mr-2" />
Invite User
</Button>
)}
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{company.users.map((user) => (
<div
key={user.id}
className="flex items-center justify-between p-4 border rounded-lg"
>
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
<span className="text-sm font-medium text-blue-600 dark:text-blue-300">
{user.name?.charAt(0) ||
user.email.charAt(0).toUpperCase()}
</span>
</div>
<div>
<div className="font-medium">
{user.name || "No name"}
</div>
<div className="text-sm text-muted-foreground">
{user.email}
</div>
</div>
</div>
<div className="flex items-center gap-4">
<Badge variant="outline">{user.role}</Badge>
<div className="text-sm text-muted-foreground">
Joined {new Date(user.createdAt).toLocaleDateString()}
</div>
</div>
</div>
))}
{company.users.length === 0 && (
<div className="text-center py-8 text-muted-foreground">
No users found. Invite the first user to get started.
</div>
)}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="settings" className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-red-600 dark:text-red-400">
Danger Zone
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{canEdit && (
<>
<div className="flex items-center justify-between p-4 border border-red-200 dark:border-red-800 rounded-lg">
<div>
<h3 className="font-medium">Suspend Company</h3>
<p className="text-sm text-muted-foreground">
Temporarily disable access to this company
</p>
</div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
disabled={company.status === "SUSPENDED"}
>
{company.status === "SUSPENDED"
? "Already Suspended"
: "Suspend"}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Suspend Company</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to suspend this company?
This will disable access for all users.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => handleStatusChange("SUSPENDED")}
>
Suspend
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
{company.status === "SUSPENDED" && (
<div className="flex items-center justify-between p-4 border border-green-200 dark:border-green-800 rounded-lg">
<div>
<h3 className="font-medium">Reactivate Company</h3>
<p className="text-sm text-muted-foreground">
Restore access to this company
</p>
</div>
<Button
variant="default"
onClick={() => handleStatusChange("ACTIVE")}
>
Reactivate
</Button>
</div>
)}
</>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="analytics" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Analytics</CardTitle>
</CardHeader>
<CardContent>
<div className="text-center py-8 text-muted-foreground">
Analytics dashboard coming soon...
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
{/* Invite User Dialog */}
{showInviteUser && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<Card className="w-full max-w-md mx-4">
<CardHeader>
<CardTitle>Invite User</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label htmlFor={inviteNameFieldId}>Name</Label>
<Input
id={inviteNameFieldId}
value={inviteData.name}
onChange={(e) =>
setInviteData((prev) => ({ ...prev, name: e.target.value }))
}
placeholder="User's full name"
/>
</div>
<div>
<Label htmlFor={inviteEmailFieldId}>Email</Label>
<Input
id={inviteEmailFieldId}
type="email"
value={inviteData.email}
onChange={(e) =>
setInviteData((prev) => ({
...prev,
email: e.target.value,
}))
}
placeholder="user@example.com"
/>
</div>
<div>
<Label htmlFor="inviteRole">Role</Label>
<Select
value={inviteData.role}
onValueChange={(value) =>
setInviteData((prev) => ({ ...prev, role: value }))
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="USER">User</SelectItem>
<SelectItem value="ADMIN">Admin</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex gap-2 pt-4">
<Button
variant="outline"
onClick={() => setShowInviteUser(false)}
className="flex-1"
>
Cancel
</Button>
<Button
onClick={handleInviteUser}
className="flex-1"
disabled={!inviteData.email || !inviteData.name}
>
<Mail className="w-4 h-4 mr-2" />
Send Invite
</Button>
</div>
</CardContent>
</Card>
</div>
)}
{/* Unsaved Changes Dialog */}
<AlertDialog
open={showUnsavedChangesDialog}
onOpenChange={setShowUnsavedChangesDialog}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Unsaved Changes</AlertDialogTitle>
<AlertDialogDescription>
You have unsaved changes that will be lost if you leave this page.
Are you sure you want to continue?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={cancelNavigation}>
Stay on Page
</AlertDialogCancel>
<AlertDialogAction onClick={confirmNavigation}>
Leave Without Saving
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@ -1,670 +0,0 @@
"use client";
import {
Activity,
BarChart3,
Building2,
Check,
Copy,
Database,
Plus,
Search,
Settings,
Users,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useId, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ThemeToggle } from "@/components/ui/theme-toggle";
import { useToast } from "@/hooks/use-toast";
interface Company {
id: string;
name: string;
status: string;
createdAt: string;
_count: {
users: number;
sessions: number;
imports: number;
};
}
interface DashboardData {
companies: Company[];
pagination: {
total: number;
pages: number;
};
}
interface PlatformSession {
user: {
id: string;
email: string;
name?: string;
isPlatformUser: boolean;
platformRole: string;
};
}
// Custom hook for platform session
function usePlatformSession() {
const [session, setSession] = useState<PlatformSession | null>(null);
const [status, setStatus] = useState<
"loading" | "authenticated" | "unauthenticated"
>("loading");
useEffect(() => {
const fetchSession = async () => {
try {
const response = await fetch("/api/platform/auth/session");
const sessionData = await response.json();
if (sessionData?.user?.isPlatformUser) {
setSession(sessionData);
setStatus("authenticated");
} else {
setSession(null);
setStatus("unauthenticated");
}
} catch (error) {
console.error("Platform session fetch error:", error);
setSession(null);
setStatus("unauthenticated");
}
};
fetchSession();
}, []);
return { data: session, status };
}
export default function PlatformDashboard() {
const { data: session, status } = usePlatformSession();
const router = useRouter();
const { toast } = useToast();
const [dashboardData, setDashboardData] = useState<DashboardData | null>(
null
);
const [isLoading, setIsLoading] = useState(true);
const [showAddCompany, setShowAddCompany] = useState(false);
const [isCreating, setIsCreating] = useState(false);
const [copiedEmail, setCopiedEmail] = useState(false);
const [copiedPassword, setCopiedPassword] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [newCompanyData, setNewCompanyData] = useState({
name: "",
csvUrl: "",
csvUsername: "",
csvPassword: "",
adminEmail: "",
adminName: "",
adminPassword: "",
maxUsers: 10,
});
const companyNameId = useId();
const csvUrlId = useId();
const csvUsernameId = useId();
const csvPasswordId = useId();
const adminNameId = useId();
const adminEmailId = useId();
const adminPasswordId = useId();
const maxUsersId = useId();
const fetchDashboardData = useCallback(async () => {
try {
const response = await fetch("/api/platform/companies");
if (response.ok) {
const data = await response.json();
setDashboardData(data);
}
} catch (error) {
console.error("Failed to fetch dashboard data:", error);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
if (status === "loading") return;
if (status === "unauthenticated" || !session?.user?.isPlatformUser) {
router.push("/platform/login");
return;
}
fetchDashboardData();
}, [session, status, router, fetchDashboardData]);
const copyToClipboard = async (text: string, type: "email" | "password") => {
try {
await navigator.clipboard.writeText(text);
if (type === "email") {
setCopiedEmail(true);
setTimeout(() => setCopiedEmail(false), 2000);
} else {
setCopiedPassword(true);
setTimeout(() => setCopiedPassword(false), 2000);
}
} catch (err) {
console.error("Failed to copy: ", err);
}
};
const getFilteredCompanies = () => {
if (!dashboardData?.companies) return [];
return dashboardData.companies.filter((company) =>
company.name.toLowerCase().includes(searchTerm.toLowerCase())
);
};
const handleCreateCompany = async () => {
if (
!newCompanyData.name ||
!newCompanyData.csvUrl ||
!newCompanyData.adminEmail ||
!newCompanyData.adminName
) {
toast({
title: "Error",
description: "Please fill in all required fields",
variant: "destructive",
});
return;
}
setIsCreating(true);
try {
const response = await fetch("/api/platform/companies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newCompanyData),
});
if (response.ok) {
const result = await response.json();
setShowAddCompany(false);
const companyName = newCompanyData.name;
setNewCompanyData({
name: "",
csvUrl: "",
csvUsername: "",
csvPassword: "",
adminEmail: "",
adminName: "",
adminPassword: "",
maxUsers: 10,
});
fetchDashboardData(); // Refresh the list
// Show success message with copyable credentials
if (result.generatedPassword) {
toast({
title: "Company Created Successfully!",
description: (
<div className="space-y-3">
<p className="font-medium">
Company "{companyName}" has been created.
</p>
<div className="space-y-2">
<div className="flex items-center justify-between bg-muted p-2 rounded">
<div className="flex-1">
<p className="text-xs text-muted-foreground">
Admin Email:
</p>
<p className="font-mono text-sm">
{result.adminUser.email}
</p>
</div>
<Button
size="sm"
variant="ghost"
onClick={() =>
copyToClipboard(result.adminUser.email, "email")
}
className="h-8 w-8 p-0"
>
{copiedEmail ? (
<Check className="h-3 w-3" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
<div className="flex items-center justify-between bg-muted p-2 rounded">
<div className="flex-1">
<p className="text-xs text-muted-foreground">
Admin Password:
</p>
<p className="font-mono text-sm">
{result.generatedPassword}
</p>
</div>
<Button
size="sm"
variant="ghost"
onClick={() =>
copyToClipboard(result.generatedPassword, "password")
}
className="h-8 w-8 p-0"
>
{copiedPassword ? (
<Check className="h-3 w-3" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
</div>
</div>
),
duration: 15000, // Longer duration for credentials
});
} else {
toast({
title: "Success",
description: `Company "${companyName}" created successfully`,
});
}
} else {
const error = await response.json();
throw new Error(error.error || "Failed to create company");
}
} catch (error) {
toast({
title: "Error",
description:
error instanceof Error ? error.message : "Failed to create company",
variant: "destructive",
});
} finally {
setIsCreating(false);
}
};
const getStatusBadgeVariant = (status: string) => {
switch (status) {
case "ACTIVE":
return "default";
case "TRIAL":
return "secondary";
case "SUSPENDED":
return "destructive";
case "ARCHIVED":
return "outline";
default:
return "default";
}
};
if (status === "loading" || isLoading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="text-center">Loading platform dashboard...</div>
</div>
);
}
if (status === "unauthenticated" || !session?.user?.isPlatformUser) {
return null;
}
const filteredCompanies = getFilteredCompanies();
const totalCompanies = dashboardData?.pagination?.total || 0;
const totalUsers =
dashboardData?.companies?.reduce(
(sum, company) => sum + company._count.users,
0
) || 0;
const totalSessions =
dashboardData?.companies?.reduce(
(sum, company) => sum + company._count.sessions,
0
) || 0;
return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
<div className="border-b bg-white dark:bg-gray-800">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-6">
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">
Platform Dashboard
</h1>
<p className="text-sm text-gray-500 dark:text-gray-400">
Welcome back, {session.user.name || session.user.email}
</p>
</div>
<div className="flex gap-4 items-center">
<ThemeToggle />
{/* Search Filter */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
<Input
placeholder="Search companies..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10 w-64"
/>
</div>
<Button variant="outline" size="sm">
<Settings className="w-4 h-4 mr-2" />
Settings
</Button>
</div>
</div>
</div>
</div>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Total Companies
</CardTitle>
<Building2 className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalCompanies}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Users</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalUsers}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Total Sessions
</CardTitle>
<Database className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalSessions}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">
Active Companies
</CardTitle>
<Activity className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{dashboardData?.companies?.filter((c) => c.status === "ACTIVE")
.length || 0}
</div>
</CardContent>
</Card>
</div>
{/* Companies List */}
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Building2 className="w-5 h-5" />
Companies
{searchTerm && (
<Badge variant="secondary" className="ml-2">
{filteredCompanies.length} of {totalCompanies} shown
</Badge>
)}
</div>
<div className="flex items-center gap-2">
{searchTerm && (
<Badge variant="outline" className="text-xs">
Search: "{searchTerm}"
</Badge>
)}
<Dialog open={showAddCompany} onOpenChange={setShowAddCompany}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="w-4 h-4 mr-2" />
Add Company
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Add New Company</DialogTitle>
<DialogDescription>
Create a new company and invite the first administrator.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="space-y-2">
<Label htmlFor={companyNameId}>Company Name *</Label>
<Input
id={companyNameId}
value={newCompanyData.name}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
name: e.target.value,
}))
}
placeholder="Acme Corporation"
/>
</div>
<div className="space-y-2">
<Label htmlFor={csvUrlId}>CSV Data URL *</Label>
<Input
id={csvUrlId}
value={newCompanyData.csvUrl}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
csvUrl: e.target.value,
}))
}
placeholder="https://api.company.com/sessions.csv"
/>
</div>
<div className="space-y-2">
<Label htmlFor={csvUsernameId}>CSV Auth Username</Label>
<Input
id={csvUsernameId}
value={newCompanyData.csvUsername}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
csvUsername: e.target.value,
}))
}
placeholder="Optional HTTP auth username"
/>
</div>
<div className="space-y-2">
<Label htmlFor={csvPasswordId}>CSV Auth Password</Label>
<Input
id={csvPasswordId}
type="password"
value={newCompanyData.csvPassword}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
csvPassword: e.target.value,
}))
}
placeholder="Optional HTTP auth password"
/>
</div>
<div className="space-y-2">
<Label htmlFor={adminNameId}>Admin Name *</Label>
<Input
id={adminNameId}
value={newCompanyData.adminName}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
adminName: e.target.value,
}))
}
placeholder="John Doe"
/>
</div>
<div className="space-y-2">
<Label htmlFor={adminEmailId}>Admin Email *</Label>
<Input
id={adminEmailId}
type="email"
value={newCompanyData.adminEmail}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
adminEmail: e.target.value,
}))
}
placeholder="admin@acme.com"
/>
</div>
<div className="space-y-2">
<Label htmlFor={adminPasswordId}>Admin Password</Label>
<Input
id={adminPasswordId}
type="password"
value={newCompanyData.adminPassword}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
adminPassword: e.target.value,
}))
}
placeholder="Leave empty to auto-generate"
/>
</div>
<div className="space-y-2">
<Label htmlFor={maxUsersId}>Max Users</Label>
<Input
id={maxUsersId}
type="number"
value={newCompanyData.maxUsers}
onChange={(e) =>
setNewCompanyData((prev) => ({
...prev,
maxUsers: Number.parseInt(e.target.value) || 10,
}))
}
min="1"
max="1000"
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => setShowAddCompany(false)}
>
Cancel
</Button>
<Button
onClick={handleCreateCompany}
disabled={isCreating}
>
{isCreating ? "Creating..." : "Create Company"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{filteredCompanies.map((company) => (
<div
key={company.id}
className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
>
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<h3 className="font-semibold">{company.name}</h3>
<Badge variant={getStatusBadgeVariant(company.status)}>
{company.status}
</Badge>
</div>
<div className="flex items-center gap-6 text-sm text-muted-foreground">
<span>{company._count.users} users</span>
<span>{company._count.sessions} sessions</span>
<span>{company._count.imports} imports</span>
<span>
Created{" "}
{new Date(company.createdAt).toLocaleDateString()}
</span>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm">
<BarChart3 className="w-4 h-4 mr-2" />
Analytics
</Button>
<Button
variant="outline"
size="sm"
onClick={() =>
router.push(`/platform/companies/${company.id}`)
}
>
<Settings className="w-4 h-4 mr-2" />
Manage
</Button>
</div>
</div>
))}
{!filteredCompanies.length && (
<div className="text-center py-8 text-muted-foreground">
{searchTerm ? (
<div className="space-y-2">
<p>No companies match "{searchTerm}".</p>
<Button
variant="link"
onClick={() => setSearchTerm("")}
className="text-sm"
>
Clear search to see all companies
</Button>
</div>
) : (
"No companies found. Create your first company to get started."
)}
</div>
)}
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@ -1,25 +0,0 @@
"use client";
import { SessionProvider } from "next-auth/react";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/toaster";
export default function PlatformLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<SessionProvider basePath="/api/platform/auth">
{children}
<Toaster />
</SessionProvider>
</ThemeProvider>
);
}

View File

@ -1,102 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
import { useId, useState } from "react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ThemeToggle } from "@/components/ui/theme-toggle";
export default function PlatformLoginPage() {
const emailId = useId();
const passwordId = useId();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const router = useRouter();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setError("");
try {
const result = await signIn("credentials", {
email,
password,
redirect: false,
callbackUrl: "/platform/dashboard",
});
if (result?.error) {
setError("Invalid credentials");
} else if (result?.ok) {
// Login successful, redirect to dashboard
router.push("/platform/dashboard");
}
} catch (_error) {
setError("An error occurred during login");
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 relative">
<div className="absolute top-4 right-4">
<ThemeToggle />
</div>
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<CardTitle className="text-2xl font-bold">Platform Login</CardTitle>
<p className="text-muted-foreground">
Sign in to the Notso AI platform management dashboard
</p>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor={emailId}>Email</Label>
<Input
id={emailId}
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
disabled={isLoading}
autoComplete="email"
/>
</div>
<div className="space-y-2">
<Label htmlFor={passwordId}>Password</Label>
<Input
id={passwordId}
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
disabled={isLoading}
autoComplete="current-password"
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Signing in..." : "Sign In"}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}

View File

@ -1,23 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function PlatformIndexPage() {
const router = useRouter();
useEffect(() => {
// Redirect to platform dashboard
router.replace("/platform/dashboard");
}, [router]);
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
Redirecting to platform dashboard...
</p>
</div>
</div>
);
}

View File

@ -1,25 +1,17 @@
"use client";
import { SessionProvider } from "next-auth/react";
import type { ReactNode } from "react";
import { ThemeProvider } from "@/components/theme-provider";
import { ReactNode } from "react";
export function Providers({ children }: { children: ReactNode }) {
// Including error handling and refetch interval for better user experience
return (
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
<SessionProvider
// Re-fetch session every 10 minutes
refetchInterval={10 * 60}
refetchOnWindowFocus={true}
>
<SessionProvider
// Re-fetch session every 30 minutes (reduced from 10)
refetchInterval={30 * 60}
refetchOnWindowFocus={false}
>
{children}
</SessionProvider>
</ThemeProvider>
{children}
</SessionProvider>
);
}

View File

@ -1,13 +1,13 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function RegisterPage() {
const [email, setEmail] = useState<string>("");
const [company, setCompany] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [csvUrl, setCsvUrl] = useState<string>("");
const [role, setRole] = useState<string>("ADMIN"); // Default to ADMIN for company registration
const [role, setRole] = useState<string>("admin"); // Default to admin for company registration
const [error, setError] = useState<string>("");
const router = useRouter();
@ -66,7 +66,7 @@ export default function RegisterPage() {
>
<option value="admin">Admin</option>
<option value="user">User</option>
<option value="AUDITOR">Auditor</option>
<option value="auditor">Auditor</option>
</select>
<button className="bg-blue-600 text-white rounded py-2" type="submit">
Register & Continue

View File

@ -1,6 +1,6 @@
"use client";
import { useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
// Component that uses useSearchParams wrapped in Suspense
function ResetPasswordForm() {

View File

@ -1,74 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"correctness": {
"noUnusedVariables": "error",
"noUnusedImports": "error"
},
"style": {
"useConst": "error",
"useTemplate": "error",
"noParameterAssign": "error",
"useAsConstAssertion": "error",
"useDefaultParameterLast": "error",
"useEnumInitializers": "error",
"useSelfClosingElements": "error",
"useSingleVarDeclarator": "error",
"noUnusedTemplateLiteral": "error",
"useNumberNamespace": "error",
"noInferrableTypes": "error",
"noUselessElse": "error"
},
"suspicious": {
"noExplicitAny": "warn",
"noArrayIndexKey": "warn"
},
"complexity": {
"noForEach": "off",
"noExcessiveCognitiveComplexity": {
"level": "error",
"options": { "maxAllowedComplexity": 15 }
}
}
}
},
"formatter": {
"enabled": true,
"formatWithErrors": false,
"indentStyle": "space",
"indentWidth": 2,
"lineEnding": "lf",
"lineWidth": 80
},
"javascript": {
"formatter": {
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"trailingCommas": "es5",
"semicolons": "always",
"arrowParentheses": "always",
"bracketSpacing": true,
"bracketSameLine": false,
"quoteStyle": "double"
}
},
"json": {
"formatter": {
"enabled": true
}
},
"files": {
"includes": [
"app/**",
"lib/**",
"components/**",
"*.ts",
"*.tsx",
"*.js",
"*.jsx"
]
}
}

View File

@ -1,93 +0,0 @@
import { PrismaClient } from "@prisma/client";
import { ProcessingStatusManager } from "./lib/processingStatusManager";
const prisma = new PrismaClient();
async function checkRefactoredPipelineStatus() {
try {
console.log("=== REFACTORED PIPELINE STATUS ===\n");
// Get pipeline status using the new system
const pipelineStatus = await ProcessingStatusManager.getPipelineStatus();
console.log(`Total Sessions: ${pipelineStatus.totalSessions}\n`);
// Display status for each stage
const stages = [
"CSV_IMPORT",
"TRANSCRIPT_FETCH",
"SESSION_CREATION",
"AI_ANALYSIS",
"QUESTION_EXTRACTION",
];
for (const stage of stages) {
console.log(`${stage}:`);
const stageData = pipelineStatus.pipeline[stage] || {};
const pending = stageData.PENDING || 0;
const inProgress = stageData.IN_PROGRESS || 0;
const completed = stageData.COMPLETED || 0;
const failed = stageData.FAILED || 0;
const skipped = stageData.SKIPPED || 0;
console.log(` PENDING: ${pending}`);
console.log(` IN_PROGRESS: ${inProgress}`);
console.log(` COMPLETED: ${completed}`);
console.log(` FAILED: ${failed}`);
console.log(` SKIPPED: ${skipped}`);
console.log("");
}
// Show what needs processing
console.log("=== WHAT NEEDS PROCESSING ===");
for (const stage of stages) {
const stageData = pipelineStatus.pipeline[stage] || {};
const pending = stageData.PENDING || 0;
const failed = stageData.FAILED || 0;
if (pending > 0 || failed > 0) {
console.log(`${stage}: ${pending} pending, ${failed} failed`);
}
}
// Show failed sessions if any
const failedSessions = await ProcessingStatusManager.getFailedSessions();
if (failedSessions.length > 0) {
console.log("\n=== FAILED SESSIONS ===");
failedSessions.slice(0, 5).forEach((failure) => {
console.log(
` ${failure.session.import?.externalSessionId || failure.sessionId}: ${failure.stage} - ${failure.errorMessage}`
);
});
if (failedSessions.length > 5) {
console.log(
` ... and ${failedSessions.length - 5} more failed sessions`
);
}
}
// Show sessions ready for AI processing
const readyForAI =
await ProcessingStatusManager.getSessionsNeedingProcessing(
"AI_ANALYSIS",
5
);
if (readyForAI.length > 0) {
console.log("\n=== SESSIONS READY FOR AI PROCESSING ===");
readyForAI.forEach((status) => {
console.log(
` ${status.session.import?.externalSessionId || status.sessionId} (created: ${status.session.createdAt})`
);
});
}
} catch (error) {
console.error("Error checking pipeline status:", error);
} finally {
await prisma.$disconnect();
}
}
checkRefactoredPipelineStatus();

View File

@ -4,7 +4,7 @@
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"config": "tailwind.config.js",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
@ -18,4 +18,4 @@
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
}

View File

@ -1,6 +1,6 @@
"use client";
import Chart from "chart.js/auto";
import { useEffect, useRef } from "react";
import Chart from "chart.js/auto";
import { getLocalizedLanguageName } from "../lib/localization"; // Corrected import path
interface SessionsData {
@ -219,7 +219,7 @@ export function LanguagePieChart({ languages }: LanguagePieChartProps) {
},
tooltip: {
callbacks: {
label: (context) => {
label: function (context) {
const label = context.label || "";
const value = context.formattedValue || "";
const index = context.dataIndex;

View File

@ -1,6 +1,6 @@
"use client";
import { useEffect, useId, useState } from "react";
import { useState, useEffect } from "react";
interface DateRangePickerProps {
minDate: string;
@ -17,19 +17,13 @@ export default function DateRangePicker({
initialStartDate,
initialEndDate,
}: DateRangePickerProps) {
const startDateId = useId();
const endDateId = useId();
const [startDate, setStartDate] = useState(initialStartDate || minDate);
const [endDate, setEndDate] = useState(initialEndDate || maxDate);
useEffect(() => {
// Only notify parent component when dates change, not when the callback changes
// Notify parent component when dates change
onDateRangeChange(startDate, endDate);
}, [
startDate,
endDate, // Only notify parent component when dates change, not when the callback changes
onDateRangeChange,
]);
}, [startDate, endDate, onDateRangeChange]);
const handleStartDateChange = (newStartDate: string) => {
// Ensure start date is not before min date
@ -93,17 +87,17 @@ export default function DateRangePicker({
<div className="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
<div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center">
<div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center">
<span className="text-sm font-medium text-gray-700 whitespace-nowrap">
<label className="text-sm font-medium text-gray-700 whitespace-nowrap">
Date Range:
</span>
</label>
<div className="flex flex-col sm:flex-row gap-2 items-start sm:items-center">
<div className="flex items-center gap-2">
<label htmlFor={startDateId} className="text-sm text-gray-600">
<label htmlFor="start-date" className="text-sm text-gray-600">
From:
</label>
<input
id={startDateId}
id="start-date"
type="date"
value={startDate}
min={minDate}
@ -114,11 +108,11 @@ export default function DateRangePicker({
</div>
<div className="flex items-center gap-2">
<label htmlFor={endDateId} className="text-sm text-gray-600">
<label htmlFor="end-date" className="text-sm text-gray-600">
To:
</label>
<input
id={endDateId}
id="end-date"
type="date"
value={endDate}
min={minDate}
@ -132,21 +126,18 @@ export default function DateRangePicker({
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={setLast7Days}
className="px-3 py-1.5 text-xs font-medium text-sky-600 bg-sky-50 border border-sky-200 rounded-md hover:bg-sky-100 transition-colors"
>
Last 7 days
</button>
<button
type="button"
onClick={setLast30Days}
className="px-3 py-1.5 text-xs font-medium text-sky-600 bg-sky-50 border border-sky-200 rounded-md hover:bg-sky-100 transition-colors"
>
Last 30 days
</button>
<button
type="button"
onClick={resetToFullRange}
className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 transition-colors"
>

View File

@ -1,7 +1,7 @@
"use client";
import Chart, { type BubbleDataPoint, type Point } from "chart.js/auto";
import { useEffect, useRef } from "react";
import { useRef, useEffect } from "react";
import Chart, { Point, BubbleDataPoint } from "chart.js/auto";
interface DonutChartProps {
data: {
@ -73,7 +73,7 @@ export default function DonutChart({ data, centerText }: DonutChartProps) {
},
tooltip: {
callbacks: {
label: (context) => {
label: function (context) {
const label = context.label || "";
const value = context.formattedValue;
const total = context.chart.data.datasets[0].data.reduce(
@ -106,7 +106,7 @@ export default function DonutChart({ data, centerText }: DonutChartProps) {
? [
{
id: "centerText",
beforeDraw: (chart: Chart<"doughnut">) => {
beforeDraw: function (chart: Chart<"doughnut">) {
const height = chart.height;
const ctx = chart.ctx;
ctx.restore();

View File

@ -1,7 +1,7 @@
"use client";
import dynamic from "next/dynamic";
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import "leaflet/dist/leaflet.css";
import * as countryCoder from "@rapideditor/country-coder";
@ -60,10 +60,10 @@ const DEFAULT_COORDINATES = getCountryCoordinates();
// Dynamically import the Map component to avoid SSR issues
// This ensures the component only loads on the client side
const CountryMapComponent = dynamic(() => import("./Map"), {
const Map = dynamic(() => import("./Map"), {
ssr: false,
loading: () => (
<div className="h-full w-full bg-muted flex items-center justify-center text-muted-foreground">
<div className="h-full w-full bg-gray-100 flex items-center justify-center">
Loading map...
</div>
),
@ -95,7 +95,7 @@ export default function GeographicMap({
if (!countryCoords) {
const feature = countryCoder.feature(code);
if (feature?.geometry) {
if (feature && feature.geometry) {
if (feature.geometry.type === "Point") {
const [lon, lat] = feature.geometry.coordinates;
countryCoords = [lat, lon]; // Leaflet expects [lat, lon]
@ -151,7 +151,7 @@ export default function GeographicMap({
// Show loading state during SSR or until client-side rendering takes over
if (!isClient) {
return (
<div className="h-full w-full bg-muted flex items-center justify-center text-muted-foreground">
<div className="h-full w-full bg-gray-100 flex items-center justify-center">
Loading map...
</div>
);
@ -160,9 +160,9 @@ export default function GeographicMap({
return (
<div style={{ height: `${height}px`, width: "100%" }} className="relative">
{countryData.length > 0 ? (
<CountryMapComponent countryData={countryData} maxCount={maxCount} />
<Map countryData={countryData} maxCount={maxCount} />
) : (
<div className="h-full w-full bg-muted flex items-center justify-center text-muted-foreground">
<div className="h-full w-full bg-gray-100 flex items-center justify-center text-gray-500">
No geographic data available
</div>
)}

View File

@ -1,9 +1,7 @@
"use client";
import { CircleMarker, MapContainer, TileLayer, Tooltip } from "react-leaflet";
import { MapContainer, TileLayer, CircleMarker, Tooltip } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";
import { getLocalizedCountryName } from "../lib/localization";
interface CountryData {
@ -17,30 +15,7 @@ interface MapProps {
maxCount: number;
}
const CountryMap = ({ countryData, maxCount }: MapProps) => {
const { theme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
// Don't render until mounted to avoid hydration mismatch
if (!mounted) {
return <div className="h-full w-full bg-muted animate-pulse rounded-lg" />;
}
const isDark = theme === "dark";
// Use different tile layers based on theme
const tileLayerUrl = isDark
? "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
: "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png";
const tileLayerAttribution = isDark
? '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>';
const Map = ({ countryData, maxCount }: MapProps) => {
return (
<MapContainer
center={[30, 0]}
@ -49,28 +24,29 @@ const CountryMap = ({ countryData, maxCount }: MapProps) => {
scrollWheelZoom={false}
style={{ height: "100%", width: "100%", borderRadius: "0.5rem" }}
>
<TileLayer attribution={tileLayerAttribution} url={tileLayerUrl} />
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{countryData.map((country) => (
<CircleMarker
key={country.code}
center={country.coordinates}
radius={5 + (country.count / maxCount) * 20}
pathOptions={{
fillColor: "hsl(var(--primary))",
color: "hsl(var(--primary))",
weight: 2,
opacity: 0.9,
fillColor: "#3B82F6",
color: "#1E40AF",
weight: 1,
opacity: 0.8,
fillOpacity: 0.6,
}}
>
<Tooltip>
<div className="p-2 bg-background border border-border rounded-md shadow-md">
<div className="font-medium text-foreground">
<div className="p-1">
<div className="font-medium">
{getLocalizedCountryName(country.code)}
</div>
<div className="text-sm text-muted-foreground">
Sessions: {country.count}
</div>
<div className="text-sm">Sessions: {country.count}</div>
</div>
</Tooltip>
</CircleMarker>
@ -79,4 +55,4 @@ const CountryMap = ({ countryData, maxCount }: MapProps) => {
);
};
export default CountryMap;
export default Map;

View File

@ -1,6 +1,6 @@
"use client";
import type { Message } from "../lib/types";
import { Message } from "../lib/types";
interface MessageViewerProps {
messages: Message[];
@ -49,9 +49,7 @@ export default function MessageViewer({ messages }: MessageViewerProps) {
{message.role}
</span>
<span className="text-xs opacity-75 ml-2">
{message.timestamp
? new Date(message.timestamp).toLocaleTimeString()
: "No timestamp"}
{new Date(message.timestamp).toLocaleTimeString()}
</span>
</div>
<div className="text-sm whitespace-pre-wrap">
@ -65,18 +63,11 @@ export default function MessageViewer({ messages }: MessageViewerProps) {
<div className="mt-4 pt-3 border-t text-sm text-gray-500">
<div className="flex justify-between">
<span>
First message:{" "}
{messages[0].timestamp
? new Date(messages[0].timestamp).toLocaleString()
: "No timestamp"}
First message: {new Date(messages[0].timestamp).toLocaleString()}
</span>
<span>
Last message: {(() => {
const lastMessage = messages[messages.length - 1];
return lastMessage.timestamp
? new Date(lastMessage.timestamp).toLocaleString()
: "No timestamp";
})()}
Last message:{" "}
{new Date(messages[messages.length - 1].timestamp).toLocaleString()}
</span>
</div>
</div>

88
components/MetricCard.tsx Normal file
View File

@ -0,0 +1,88 @@
"use client";
interface MetricCardProps {
title: string;
value: string | number | null | undefined;
description?: string;
icon?: React.ReactNode;
trend?: {
value: number;
label?: string;
isPositive?: boolean;
};
variant?: "default" | "primary" | "success" | "warning" | "danger";
}
export default function MetricCard({
title,
value,
description,
icon,
trend,
variant = "default",
}: MetricCardProps) {
// Determine background and text colors based on variant
const getVariantClasses = () => {
switch (variant) {
case "primary":
return "bg-blue-50 border-blue-200";
case "success":
return "bg-green-50 border-green-200";
case "warning":
return "bg-amber-50 border-amber-200";
case "danger":
return "bg-red-50 border-red-200";
default:
return "bg-white border-gray-200";
}
};
const getIconClasses = () => {
switch (variant) {
case "primary":
return "bg-blue-100 text-blue-600";
case "success":
return "bg-green-100 text-green-600";
case "warning":
return "bg-amber-100 text-amber-600";
case "danger":
return "bg-red-100 text-red-600";
default:
return "bg-gray-100 text-gray-600";
}
};
return (
<div className={`rounded-xl border shadow-sm p-6 ${getVariantClasses()}`}>
<div className="flex items-start justify-between">
<div>
<p className="text-sm font-medium text-gray-500">{title}</p>
<div className="mt-2 flex items-baseline">
<p className="text-2xl font-semibold">{value ?? "-"}</p>
{trend && (
<span
className={`ml-2 text-sm font-medium ${
trend.isPositive !== false ? "text-green-600" : "text-red-600"
}`}
>
{trend.isPositive !== false ? "↑" : "↓"}{" "}
{Math.abs(trend.value).toFixed(1)}%
</span>
)}
</div>
{description && (
<p className="mt-1 text-xs text-gray-500">{description}</p>
)}
</div>
{icon && (
<div
className={`flex h-12 w-12 rounded-full ${getIconClasses()} items-center justify-center`}
>
<span className="text-xl">{icon}</span>
</div>
)}
</div>
</div>
);
}

View File

@ -1,15 +1,10 @@
"use client";
import {
Bar,
BarChart,
CartesianGrid,
ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { useRef, useEffect } from "react";
import Chart from "chart.js/auto";
import annotationPlugin from "chartjs-plugin-annotation";
Chart.register(annotationPlugin);
interface ResponseTimeDistributionProps {
data: number[];
@ -17,157 +12,114 @@ interface ResponseTimeDistributionProps {
targetResponseTime?: number;
}
interface TooltipProps {
active?: boolean;
payload?: Array<{ value: number; payload: { label: string; count: number } }>;
label?: string;
}
const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
if (active && payload && payload.length) {
return (
<div className="rounded-lg border bg-background p-3 shadow-md">
<p className="text-sm font-medium">{label}</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
{payload[0].value}
</span>{" "}
responses
</p>
</div>
);
}
return null;
};
export default function ResponseTimeDistribution({
data,
average,
targetResponseTime,
}: ResponseTimeDistributionProps) {
if (!data || !data.length) {
return (
<div className="flex items-center justify-center h-64 text-muted-foreground">
No response time data available
</div>
);
}
const ref = useRef<HTMLCanvasElement | null>(null);
// Create bins for the histogram (0-1s, 1-2s, 2-3s, etc.)
const maxTime = Math.ceil(Math.max(...data));
const bins = Array(Math.min(maxTime + 1, 10)).fill(0);
useEffect(() => {
if (!ref.current || !data || !data.length) return;
// Count responses in each bin
data.forEach((time) => {
const binIndex = Math.min(Math.floor(time), bins.length - 1);
bins[binIndex]++;
});
const ctx = ref.current.getContext("2d");
if (!ctx) return;
// Create chart data
const chartData = bins.map((count, i) => {
let label: string;
if (i === bins.length - 1 && bins.length < maxTime + 1) {
label = `${i}+ sec`;
} else {
label = `${i}-${i + 1} sec`;
}
// Create bins for the histogram (0-1s, 1-2s, 2-3s, etc.)
const maxTime = Math.ceil(Math.max(...data));
const bins = Array(Math.min(maxTime + 1, 10)).fill(0);
// Determine color based on response time
let color: string;
if (i <= 2)
color = "hsl(var(--chart-1))"; // Green for fast
else if (i <= 5)
color = "hsl(var(--chart-4))"; // Yellow for medium
else color = "hsl(var(--chart-3))"; // Red for slow
// Count responses in each bin
data.forEach((time) => {
const binIndex = Math.min(Math.floor(time), bins.length - 1);
bins[binIndex]++;
});
return {
name: label,
value: count,
color,
};
});
// Create labels for each bin
const labels = bins.map((_, i) => {
if (i === bins.length - 1 && bins.length < maxTime + 1) {
return `${i}+ seconds`;
}
return `${i}-${i + 1} seconds`;
});
return (
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={chartData}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="hsl(var(--border))"
strokeOpacity={0.3}
/>
<XAxis
dataKey="name"
stroke="hsl(var(--muted-foreground))"
fontSize={12}
tickLine={false}
axisLine={false}
/>
<YAxis
stroke="hsl(var(--muted-foreground))"
fontSize={12}
tickLine={false}
axisLine={false}
label={{
value: "Number of Responses",
angle: -90,
position: "insideLeft",
style: { textAnchor: "middle" },
}}
/>
<Tooltip content={<CustomTooltip />} />
<Bar
dataKey="value"
radius={[4, 4, 0, 0]}
fill="hsl(var(--chart-1))"
maxBarSize={60}
>
{chartData.map((entry, index) => (
<Bar key={`cell-${entry.name}-${index}`} fill={entry.color} />
))}
</Bar>
{/* Average line */}
<ReferenceLine
x={Math.floor(average)}
stroke="hsl(var(--primary))"
strokeWidth={2}
strokeDasharray="5 5"
label={{
value: `Avg: ${average.toFixed(1)}s`,
position: "top" as const,
style: {
fill: "hsl(var(--primary))",
fontSize: "12px",
fontWeight: "500",
},
}}
/>
{/* Target line (if provided) */}
{targetResponseTime && (
<ReferenceLine
x={Math.floor(targetResponseTime)}
stroke="hsl(var(--chart-2))"
strokeWidth={2}
strokeDasharray="3 3"
label={{
value: `Target: ${targetResponseTime}s`,
position: "top" as const,
style: {
fill: "hsl(var(--chart-2))",
fontSize: "12px",
fontWeight: "500",
const chart = new Chart(ctx, {
type: "bar",
data: {
labels,
datasets: [
{
label: "Responses",
data: bins,
backgroundColor: bins.map((_, i) => {
// Green for fast, yellow for medium, red for slow
if (i <= 2) return "rgba(34, 197, 94, 0.7)"; // Green
if (i <= 5) return "rgba(250, 204, 21, 0.7)"; // Yellow
return "rgba(239, 68, 68, 0.7)"; // Red
}),
borderWidth: 1,
},
],
},
options: {
responsive: true,
plugins: {
legend: { display: false },
annotation: {
annotations: {
averageLine: {
type: "line",
yMin: 0,
yMax: Math.max(...bins),
xMin: average,
xMax: average,
borderColor: "rgba(75, 192, 192, 1)",
borderWidth: 2,
label: {
display: true,
content: "Avg: " + average.toFixed(1) + "s",
position: "start",
},
}}
/>
)}
</BarChart>
</ResponsiveContainer>
</div>
);
},
targetLine: targetResponseTime
? {
type: "line",
yMin: 0,
yMax: Math.max(...bins),
xMin: targetResponseTime,
xMax: targetResponseTime,
borderColor: "rgba(75, 192, 192, 0.7)",
borderWidth: 2,
label: {
display: true,
content: "Target",
position: "end",
},
}
: undefined,
},
},
},
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: "Number of Responses",
},
},
x: {
title: {
display: true,
text: "Response Time",
},
},
},
},
});
return () => chart.destroy();
}, [data, average, targetResponseTime]);
return <canvas ref={ref} height={180} />;
}

View File

@ -1,13 +1,8 @@
"use client";
import { ExternalLink } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { formatCategory } from "@/lib/format-enums";
import type { ChatSession } from "../lib/types";
import CountryDisplay from "./CountryDisplay";
import { ChatSession } from "../lib/types";
import LanguageDisplay from "./LanguageDisplay";
import CountryDisplay from "./CountryDisplay";
interface SessionDetailsProps {
session: ChatSession;
@ -17,183 +12,229 @@ interface SessionDetailsProps {
* Component to display session details with formatted country and language names
*/
export default function SessionDetails({ session }: SessionDetailsProps) {
// Using centralized formatCategory utility
return (
<Card>
<CardHeader>
<CardTitle>Session Information</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-3">
<div>
<p className="text-sm text-muted-foreground">Session ID</p>
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">
{session.id.slice(0, 8)}...
</code>
</div>
<div>
<p className="text-sm text-muted-foreground">Start Time</p>
<p className="font-medium">
{new Date(session.startTime).toLocaleString()}
</p>
</div>
{session.endTime && (
<div>
<p className="text-sm text-muted-foreground">End Time</p>
<p className="font-medium">
{new Date(session.endTime).toLocaleString()}
</p>
</div>
)}
{session.category && (
<div>
<p className="text-sm text-muted-foreground">Category</p>
<Badge variant="secondary">
{formatCategory(session.category)}
</Badge>
</div>
)}
{session.language && (
<div>
<p className="text-sm text-muted-foreground">Language</p>
<div className="flex items-center gap-2">
<LanguageDisplay languageCode={session.language} />
<Badge variant="outline" className="text-xs">
{session.language.toUpperCase()}
</Badge>
</div>
</div>
)}
{session.country && (
<div>
<p className="text-sm text-muted-foreground">Country</p>
<div className="flex items-center gap-2">
<CountryDisplay countryCode={session.country} />
<Badge variant="outline" className="text-xs">
{session.country}
</Badge>
</div>
</div>
)}
</div>
<div className="space-y-3">
{session.sentiment !== null && session.sentiment !== undefined && (
<div>
<p className="text-sm text-muted-foreground">Sentiment</p>
<Badge
variant={
session.sentiment === "positive"
? "default"
: session.sentiment === "negative"
? "destructive"
: "secondary"
}
>
{session.sentiment.charAt(0).toUpperCase() +
session.sentiment.slice(1)}
</Badge>
</div>
)}
<div>
<p className="text-sm text-muted-foreground">Messages Sent</p>
<p className="font-medium">{session.messagesSent || 0}</p>
</div>
{session.avgResponseTime !== null &&
session.avgResponseTime !== undefined && (
<div>
<p className="text-sm text-muted-foreground">
Avg Response Time
</p>
<p className="font-medium">
{session.avgResponseTime.toFixed(2)}s
</p>
</div>
)}
{session.escalated !== null && session.escalated !== undefined && (
<div>
<p className="text-sm text-muted-foreground">Escalated</p>
<Badge variant={session.escalated ? "destructive" : "default"}>
{session.escalated ? "Yes" : "No"}
</Badge>
</div>
)}
{session.forwardedHr !== null &&
session.forwardedHr !== undefined && (
<div>
<p className="text-sm text-muted-foreground">
Forwarded to HR
</p>
<Badge
variant={session.forwardedHr ? "secondary" : "default"}
>
{session.forwardedHr ? "Yes" : "No"}
</Badge>
</div>
)}
{session.ipAddress && (
<div>
<p className="text-sm text-muted-foreground">IP Address</p>
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">
{session.ipAddress}
</code>
</div>
)}
</div>
<div className="bg-white p-4 rounded-lg shadow">
<h3 className="font-bold text-lg mb-3">Session Details</h3>
<div className="space-y-3">
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Session ID:</span>
<span className="font-medium font-mono text-sm">{session.id}</span>
</div>
{(session.summary || session.initialMsg) && <Separator />}
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Start Time:</span>
<span className="font-medium">
{new Date(session.startTime).toLocaleString()}
</span>
</div>
{session.endTime && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">End Time:</span>
<span className="font-medium">
{new Date(session.endTime).toLocaleString()}
</span>
</div>
)}
{session.category && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Category:</span>
<span className="font-medium">{session.category}</span>
</div>
)}
{session.language && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Language:</span>
<span className="font-medium">
<LanguageDisplay languageCode={session.language} />
<span className="text-gray-400 text-xs ml-1">
({session.language.toUpperCase()})
</span>
</span>
</div>
)}
{session.country && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Country:</span>
<span className="font-medium">
<CountryDisplay countryCode={session.country} />
<span className="text-gray-400 text-xs ml-1">
({session.country})
</span>
</span>
</div>
)}
{session.sentiment !== null && session.sentiment !== undefined && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Sentiment Score:</span>
<span
className={`font-medium ${
session.sentiment > 0.3
? "text-green-500"
: session.sentiment < -0.3
? "text-red-500"
: "text-orange-500"
}`}
>
{session.sentiment > 0.3
? "Positive"
: session.sentiment < -0.3
? "Negative"
: "Neutral"}{" "}
({session.sentiment.toFixed(2)})
</span>
</div>
)}
{session.sentimentCategory && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">AI Sentiment:</span>
<span
className={`font-medium capitalize ${
session.sentimentCategory === "positive"
? "text-green-500"
: session.sentimentCategory === "negative"
? "text-red-500"
: "text-orange-500"
}`}
>
{session.sentimentCategory}
</span>
</div>
)}
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Messages Sent:</span>
<span className="font-medium">{session.messagesSent || 0}</span>
</div>
{typeof session.tokens === "number" && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Tokens:</span>
<span className="font-medium">{session.tokens}</span>
</div>
)}
{typeof session.tokensEur === "number" && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Cost:</span>
<span className="font-medium">{session.tokensEur.toFixed(4)}</span>
</div>
)}
{session.avgResponseTime !== null &&
session.avgResponseTime !== undefined && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Avg Response Time:</span>
<span className="font-medium">
{session.avgResponseTime.toFixed(2)}s
</span>
</div>
)}
{session.escalated !== null && session.escalated !== undefined && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Escalated:</span>
<span
className={`font-medium ${session.escalated ? "text-red-500" : "text-green-500"}`}
>
{session.escalated ? "Yes" : "No"}
</span>
</div>
)}
{session.forwardedHr !== null && session.forwardedHr !== undefined && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">Forwarded to HR:</span>
<span
className={`font-medium ${session.forwardedHr ? "text-amber-500" : "text-green-500"}`}
>
{session.forwardedHr ? "Yes" : "No"}
</span>
</div>
)}
{session.ipAddress && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">IP Address:</span>
<span className="font-medium font-mono text-sm">
{session.ipAddress}
</span>
</div>
)}
{session.processed !== null && session.processed !== undefined && (
<div className="flex justify-between border-b pb-2">
<span className="text-gray-600">AI Processed:</span>
<span
className={`font-medium ${session.processed ? "text-green-500" : "text-gray-500"}`}
>
{session.processed ? "Yes" : "No"}
</span>
</div>
)}
{session.initialMsg && (
<div className="border-b pb-2">
<span className="text-gray-600 block mb-1">Initial Message:</span>
<div className="bg-gray-50 p-2 rounded text-sm italic">
"{session.initialMsg}"
</div>
</div>
)}
{session.summary && (
<div>
<p className="text-sm text-muted-foreground mb-2">AI Summary</p>
<div className="bg-muted p-3 rounded-md text-sm">
<div className="border-b pb-2">
<span className="text-gray-600 block mb-1">AI Summary:</span>
<div className="bg-blue-50 p-2 rounded text-sm">
{session.summary}
</div>
</div>
)}
{!session.summary && session.initialMsg && (
<div>
<p className="text-sm text-muted-foreground mb-2">
Initial Message
</p>
<div className="bg-muted p-3 rounded-md text-sm italic">
&quot;{session.initialMsg}&quot;
{session.questions && (
<div className="border-b pb-2">
<span className="text-gray-600 block mb-1">Questions Asked:</span>
<div className="bg-yellow-50 p-2 rounded text-sm">
{(() => {
try {
const questions = JSON.parse(session.questions);
if (Array.isArray(questions) && questions.length > 0) {
return (
<ul className="list-disc list-inside space-y-1">
{questions.map((question: string, index: number) => (
<li key={index}>{question}</li>
))}
</ul>
);
}
return "No questions identified";
} catch {
return session.questions;
}
})()}
</div>
</div>
)}
{session.fullTranscriptUrl && (
<>
<Separator />
<div>
<a
href={session.fullTranscriptUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 text-primary hover:underline focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 rounded-sm"
aria-label="Open full transcript in new tab"
>
<ExternalLink className="h-4 w-4" aria-hidden="true" />
View Full Transcript
</a>
</div>
</>
<div className="flex justify-between pt-2">
<span className="text-gray-600">Transcript:</span>
<a
href={session.fullTranscriptUrl}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:text-blue-700 underline"
>
View Full Transcript
</a>
</div>
)}
</CardContent>
</Card>
</div>
</div>
);
}

View File

@ -1,12 +1,10 @@
"use client";
import Image from "next/image";
import React from "react"; // No hooks needed since state is now managed by parent
import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { signOut } from "next-auth/react";
import type React from "react"; // No hooks needed since state is now managed by parent
import { useId } from "react";
import { SimpleThemeToggle } from "@/components/ui/theme-toggle";
// Icons for the sidebar
const DashboardIcon = () => (
@ -17,7 +15,6 @@ const DashboardIcon = () => (
viewBox="0 0 24 24"
stroke="currentColor"
>
<title>Dashboard</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
@ -53,7 +50,6 @@ const CompanyIcon = () => (
viewBox="0 0 24 24"
stroke="currentColor"
>
<title>Company</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
@ -71,7 +67,6 @@ const UsersIcon = () => (
viewBox="0 0 24 24"
stroke="currentColor"
>
<title>Users</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
@ -89,7 +84,6 @@ const SessionsIcon = () => (
viewBox="0 0 24 24"
stroke="currentColor"
>
<title>Sessions</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
@ -107,7 +101,6 @@ const LogoutIcon = () => (
viewBox="0 0 24 24"
stroke="currentColor"
>
<title>Logout</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
@ -125,7 +118,6 @@ const MinimalToggleIcon = ({ isExpanded }: { isExpanded: boolean }) => (
stroke="currentColor"
strokeWidth={2}
>
<title>{isExpanded ? "Collapse sidebar" : "Expand sidebar"}</title>
{isExpanded ? (
<path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
) : (
@ -166,8 +158,8 @@ const NavItem: React.FC<NavItemProps> = ({
href={href}
className={`relative flex items-center p-3 my-1 rounded-lg transition-all group ${
isActive
? "bg-primary/10 text-primary font-medium border border-primary/20"
: "hover:bg-muted text-muted-foreground hover:text-foreground"
? "bg-sky-100 text-sky-800 font-medium"
: "hover:bg-gray-100 text-gray-700 hover:text-gray-900"
}`}
onClick={() => {
if (onNavigate) {
@ -175,7 +167,7 @@ const NavItem: React.FC<NavItemProps> = ({
}
}}
>
<span className={`shrink-0 ${isExpanded ? "mr-3" : "mx-auto"}`}>
<span className={`flex-shrink-0 ${isExpanded ? "mr-3" : "mx-auto"}`}>
{icon}
</span>
{isExpanded ? (
@ -183,7 +175,7 @@ const NavItem: React.FC<NavItemProps> = ({
) : (
<div
className="fixed ml-6 w-auto p-2 min-w-max rounded-md shadow-md text-xs font-medium
text-popover-foreground bg-popover border border-border z-50
text-white bg-gray-800 z-50
invisible opacity-0 -translate-x-3 transition-all
group-hover:visible group-hover:opacity-100 group-hover:translate-x-0"
>
@ -199,7 +191,6 @@ export default function Sidebar({
isMobile = false,
onNavigate,
}: SidebarProps) {
const sidebarId = useId();
const pathname = usePathname() || "";
const handleLogout = () => {
@ -211,22 +202,13 @@ export default function Sidebar({
{/* Backdrop overlay when sidebar is expanded on mobile */}
{isExpanded && isMobile && (
<div
className="fixed inset-0 bg-black/50 backdrop-blur-sm z-10 transition-all duration-300"
className="fixed inset-0 bg-gray-900 bg-opacity-50 z-10 transition-opacity duration-300"
onClick={onToggle}
onKeyDown={(e) => {
if (e.key === "Escape") {
onToggle();
}
}}
role="button"
tabIndex={0}
aria-label="Close sidebar"
/>
)}
<div
id={sidebarId}
className={`fixed md:relative h-screen bg-card border-r border-border shadow-lg transition-all duration-300
className={`fixed md:relative h-screen bg-white shadow-md transition-all duration-300
${
isExpanded ? (isMobile ? "w-full sm:w-80" : "w-56") : "w-16"
} flex flex-col overflow-visible z-20`}
@ -236,15 +218,12 @@ export default function Sidebar({
{!isExpanded && (
<div className="absolute top-1 left-1/2 transform -translate-x-1/2 z-30">
<button
type="button"
onClick={(e) => {
e.preventDefault(); // Prevent any navigation
onToggle();
}}
className="p-1.5 rounded-md hover:bg-muted focus:outline-none focus:ring-2 focus:ring-primary transition-colors group"
aria-label="Expand sidebar"
aria-expanded={isExpanded}
aria-controls={sidebarId}
className="p-1.5 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-sky-500 transition-colors group"
title="Expand sidebar"
>
<MinimalToggleIcon isExpanded={isExpanded} />
</button>
@ -269,7 +248,7 @@ export default function Sidebar({
/>
</div>
{isExpanded && (
<span className="text-lg font-bold text-primary mt-1 transition-opacity duration-300">
<span className="text-lg font-bold text-sky-700 mt-1 transition-opacity duration-300">
LiveDash
</span>
)}
@ -278,22 +257,18 @@ export default function Sidebar({
{isExpanded && (
<div className="absolute top-3 right-3 z-30">
<button
type="button"
onClick={(e) => {
e.preventDefault(); // Prevent any navigation
onToggle();
}}
className="p-1.5 rounded-md hover:bg-muted focus:outline-none focus:ring-2 focus:ring-primary transition-colors group"
aria-label="Collapse sidebar"
aria-expanded={isExpanded}
aria-controls="main-sidebar"
className="p-1.5 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-sky-500 transition-colors group"
title="Collapse sidebar"
>
<MinimalToggleIcon isExpanded={isExpanded} />
</button>
</div>
)}
<nav
aria-label="Main navigation"
className={`flex-1 py-4 px-2 overflow-y-auto overflow-x-visible ${isExpanded ? "pt-12" : "pt-4"}`}
>
<NavItem
@ -315,7 +290,6 @@ export default function Sidebar({
viewBox="0 0 24 24"
stroke="currentColor"
>
<title>Analytics Chart</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
@ -353,28 +327,14 @@ export default function Sidebar({
onNavigate={onNavigate}
/>
</nav>
<div className="p-4 border-t mt-auto space-y-2">
{/* Theme Toggle */}
<div
className={`flex items-center ${isExpanded ? "justify-between" : "justify-center"}`}
>
{isExpanded && (
<span className="text-sm font-medium text-muted-foreground">
Theme
</span>
)}
<SimpleThemeToggle />
</div>
{/* Logout Button */}
<div className="p-4 border-t mt-auto">
<button
type="button"
onClick={handleLogout}
className={`relative flex items-center p-3 w-full rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-all group ${
className={`relative flex items-center p-3 w-full rounded-lg text-gray-700 hover:bg-gray-100 hover:text-gray-900 transition-all group ${
isExpanded ? "" : "justify-center"
}`}
>
<span className={`shrink-0 ${isExpanded ? "mr-3" : ""}`}>
<span className={`flex-shrink-0 ${isExpanded ? "mr-3" : ""}`}>
<LogoutIcon />
</span>
{isExpanded ? (
@ -382,7 +342,7 @@ export default function Sidebar({
) : (
<div
className="fixed ml-6 w-auto p-2 min-w-max rounded-md shadow-md text-xs font-medium
text-popover-foreground bg-popover border border-border z-50
text-white bg-gray-800 z-50
invisible opacity-0 -translate-x-3 transition-all
group-hover:visible group-hover:opacity-100 group-hover:translate-x-0"
>

View File

@ -1,9 +1,7 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import type { TopQuestion } from "../lib/types";
import React from "react";
import { TopQuestion } from "../lib/types";
interface TopQuestionsChartProps {
data: TopQuestion[];
@ -16,16 +14,12 @@ export default function TopQuestionsChart({
}: TopQuestionsChartProps) {
if (!data || data.length === 0) {
return (
<Card>
<CardHeader>
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
</CardHeader>
<CardContent>
<div className="text-center py-8 text-muted-foreground">
No questions data available
</div>
</CardContent>
</Card>
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<h3 className="text-lg font-semibold text-gray-900 mb-4">{title}</h3>
<div className="text-center py-8 text-gray-500">
No questions data available
</div>
</div>
);
}
@ -33,55 +27,52 @@ export default function TopQuestionsChart({
const maxCount = Math.max(...data.map((q) => q.count));
return (
<Card>
<CardHeader>
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{data.map((question) => {
const percentage =
maxCount > 0 ? (question.count / maxCount) * 100 : 0;
<div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
<h3 className="text-lg font-semibold text-gray-900 mb-4">{title}</h3>
return (
<div key={question.question} className="relative pl-8">
{/* Question text */}
<div className="flex justify-between items-start mb-2">
<p className="text-sm font-medium leading-tight pr-4 flex-1 text-foreground">
{question.question}
</p>
<Badge variant="secondary" className="whitespace-nowrap">
{question.count}
</Badge>
</div>
<div className="space-y-4">
{data.map((question, index) => {
const percentage =
maxCount > 0 ? (question.count / maxCount) * 100 : 0;
{/* Progress bar */}
<div className="w-full bg-muted rounded-full h-2">
<div
className="bg-primary h-2 rounded-full transition-all duration-300 ease-in-out"
style={{ width: `${percentage}%` }}
/>
</div>
{/* Rank indicator */}
<div className="absolute -left-1 top-0 w-6 h-6 bg-primary text-primary-foreground text-xs font-bold rounded-full flex items-center justify-center">
{index + 1}
</div>
return (
<div key={index} className="relative">
{/* Question text */}
<div className="flex justify-between items-start mb-2">
<p className="text-sm text-gray-700 font-medium leading-tight pr-4 flex-1">
{question.question}
</p>
<span className="text-sm font-semibold text-gray-900 bg-gray-100 px-2 py-1 rounded-md whitespace-nowrap">
{question.count}
</span>
</div>
);
})}
</div>
<Separator className="my-6" />
{/* Progress bar */}
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className="bg-blue-600 h-2 rounded-full transition-all duration-300 ease-in-out"
style={{ width: `${percentage}%` }}
/>
</div>
{/* Summary */}
<div className="flex justify-between text-sm text-muted-foreground">
{/* Rank indicator */}
<div className="absolute -left-2 top-0 w-6 h-6 bg-blue-600 text-white text-xs font-bold rounded-full flex items-center justify-center">
{index + 1}
</div>
</div>
);
})}
</div>
{/* Summary */}
<div className="mt-6 pt-4 border-t border-gray-200">
<div className="flex justify-between text-sm text-gray-600">
<span>Total questions analyzed</span>
<span className="font-medium text-foreground">
<span className="font-medium">
{data.reduce((sum, q) => sum + q.count, 0)}
</span>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@ -26,8 +26,8 @@ function formatTranscript(content: string): React.ReactNode[] {
// Process each line
lines.forEach((line) => {
const trimmedLine = line.trim();
if (!trimmedLine) {
line = line.trim();
if (!line) {
// Empty line, ignore
return;
}
@ -51,7 +51,7 @@ function formatTranscript(content: string): React.ReactNode[] {
{currentMessages.map((msg, i) => (
// Use ReactMarkdown to render each message part
<ReactMarkdown
key={`msg-${msg.substring(0, 20).replace(/\s/g, "-")}-${i}`}
key={i}
rehypePlugins={[rehypeRaw]} // Add rehypeRaw to plugins
components={{
p: "span",
@ -74,17 +74,15 @@ function formatTranscript(content: string): React.ReactNode[] {
}
// Set the new current speaker
currentSpeaker = trimmedLine.startsWith("User:") ? "User" : "Assistant";
currentSpeaker = line.startsWith("User:") ? "User" : "Assistant";
// Add the content after "User:" or "Assistant:"
const messageContent = trimmedLine
.substring(trimmedLine.indexOf(":") + 1)
.trim();
const messageContent = line.substring(line.indexOf(":") + 1).trim();
if (messageContent) {
currentMessages.push(messageContent);
}
} else if (currentSpeaker) {
// This is a continuation of the current speaker's message
currentMessages.push(trimmedLine);
currentMessages.push(line);
}
});
@ -105,7 +103,7 @@ function formatTranscript(content: string): React.ReactNode[] {
{currentMessages.map((msg, i) => (
// Use ReactMarkdown to render each message part
<ReactMarkdown
key={`msg-final-${msg.substring(0, 20).replace(/\s/g, "-")}-${i}`}
key={i}
rehypePlugins={[rehypeRaw]} // Add rehypeRaw to plugins
components={{
p: "span",
@ -159,7 +157,6 @@ export default function TranscriptViewer({
</a>
)}
<button
type="button"
onClick={() => setShowRaw(!showRaw)}
className="text-sm text-sky-600 hover:text-sky-800 hover:underline"
title={

View File

@ -22,7 +22,7 @@ export default function WelcomeBanner({ companyName }: WelcomeBannerProps) {
}
return (
<div className="bg-linear-to-r from-blue-600 to-indigo-700 text-white p-6 rounded-xl shadow-lg mb-8">
<div className="bg-gradient-to-r from-blue-600 to-indigo-700 text-white p-6 rounded-xl shadow-lg mb-8">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold">
@ -48,7 +48,7 @@ export default function WelcomeBanner({ companyName }: WelcomeBannerProps) {
<div className="bg-white/20 backdrop-blur-sm p-4 rounded-lg">
<div className="text-sm opacity-75">Current Status</div>
<div className="text-xl font-semibold flex items-center">
<span className="inline-block w-2 h-2 bg-green-400 rounded-full mr-2" />
<span className="inline-block w-2 h-2 bg-green-400 rounded-full mr-2"></span>
All Systems Operational
</div>
</div>

View File

@ -1,8 +1,8 @@
"use client";
import cloud, { type Word } from "d3-cloud";
import { useRef, useEffect, useState } from "react";
import { select } from "d3-selection";
import { useEffect, useRef, useState } from "react";
import cloud, { Word } from "d3-cloud";
interface WordCloudProps {
words: {

View File

@ -1,120 +0,0 @@
"use client";
import {
Bar,
BarChart,
CartesianGrid,
Cell,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
interface BarChartData {
name: string;
value: number;
[key: string]: string | number;
}
interface BarChartProps {
data: BarChartData[];
title?: string;
dataKey?: string;
colors?: string[];
height?: number;
className?: string;
}
interface TooltipProps {
active?: boolean;
payload?: Array<{ value: number; name?: string }>;
label?: string;
}
const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
if (active && payload && payload.length) {
return (
<div className="rounded-lg border bg-background p-3 shadow-md">
<p className="text-sm font-medium">{label}</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
{payload[0].value}
</span>{" "}
sessions
</p>
</div>
);
}
return null;
};
export default function ModernBarChart({
data,
title,
dataKey = "value",
colors = [
"hsl(var(--chart-1))",
"hsl(var(--chart-2))",
"hsl(var(--chart-3))",
"hsl(var(--chart-4))",
"hsl(var(--chart-5))",
],
height = 300,
className,
}: BarChartProps) {
return (
<Card className={className}>
{title && (
<CardHeader>
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
</CardHeader>
)}
<CardContent>
<ResponsiveContainer width="100%" height={height}>
<BarChart
data={data}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="hsl(var(--border))"
strokeOpacity={0.3}
/>
<XAxis
dataKey="name"
stroke="hsl(var(--muted-foreground))"
fontSize={12}
tickLine={false}
axisLine={false}
angle={-45}
textAnchor="end"
height={80}
/>
<YAxis
stroke="hsl(var(--muted-foreground))"
fontSize={12}
tickLine={false}
axisLine={false}
/>
<Tooltip content={<CustomTooltip />} />
<Bar
dataKey={dataKey}
radius={[4, 4, 0, 0]}
className="transition-all duration-200"
>
{data.map((entry, index) => (
<Cell
key={`cell-${entry.name}-${index}`}
fill={colors[index % colors.length]}
className="hover:opacity-80"
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@ -1,165 +0,0 @@
"use client";
import {
Cell,
Legend,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
interface DonutChartProps {
data: Array<{ name: string; value: number; color?: string }>;
title?: string;
centerText?: {
title: string;
value: string | number;
};
colors?: string[];
height?: number;
className?: string;
}
interface TooltipProps {
active?: boolean;
payload?: Array<{
name: string;
value: number;
payload: { total: number };
}>;
}
const CustomTooltip = ({ active, payload }: TooltipProps) => {
if (active && payload && payload.length) {
const data = payload[0];
return (
<div className="rounded-lg border bg-background p-3 shadow-md">
<p className="text-sm font-medium">{data.name}</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">{data.value}</span>{" "}
sessions ({((data.value / data.payload.total) * 100).toFixed(1)}%)
</p>
</div>
);
}
return null;
};
interface LegendProps {
payload?: Array<{
value: string;
color: string;
type?: string;
}>;
}
const CustomLegend = ({ payload }: LegendProps) => {
return (
<div className="flex flex-wrap justify-center gap-4 mt-4">
{payload?.map((entry, index) => (
<div
key={`legend-${entry.value}-${index}`}
className="flex items-center gap-2"
>
<div
className="w-3 h-3 rounded-full"
style={{ backgroundColor: entry.color }}
/>
<span className="text-sm text-muted-foreground">{entry.value}</span>
</div>
))}
</div>
);
};
interface CenterLabelProps {
centerText?: {
title: string;
value: string | number;
};
total: number;
}
const CenterLabel = ({ centerText }: CenterLabelProps) => {
if (!centerText) return null;
return (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="text-center">
<p className="text-2xl font-bold">{centerText.value}</p>
<p className="text-sm text-muted-foreground">{centerText.title}</p>
</div>
</div>
);
};
export default function ModernDonutChart({
data,
title,
centerText,
colors = [
"hsl(var(--chart-1))",
"hsl(var(--chart-2))",
"hsl(var(--chart-3))",
"hsl(var(--chart-4))",
"hsl(var(--chart-5))",
],
height = 300,
className,
}: DonutChartProps) {
const total = data.reduce((sum, item) => sum + item.value, 0);
const dataWithTotal = data.map((item) => ({ ...item, total }));
return (
<Card className={className}>
{title && (
<CardHeader>
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
</CardHeader>
)}
<CardContent>
<div
className="relative"
role="img"
aria-label={`${title || "Chart"} - ${data.length} segments`}
>
<ResponsiveContainer width="100%" height={height}>
<PieChart>
<Pie
data={dataWithTotal}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
paddingAngle={2}
dataKey="value"
className="transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
}
}}
>
{dataWithTotal.map((entry, index) => (
<Cell
key={`cell-${entry.name}-${index}`}
fill={entry.color || colors[index % colors.length]}
className="hover:opacity-80 cursor-pointer focus:opacity-80"
stroke="hsl(var(--background))"
strokeWidth={2}
/>
))}
</Pie>
<Tooltip content={<CustomTooltip />} />
<Legend content={<CustomLegend />} />
</PieChart>
</ResponsiveContainer>
<CenterLabel centerText={centerText} total={total} />
</div>
</CardContent>
</Card>
);
}

View File

@ -1,134 +0,0 @@
"use client";
import { useId } from "react";
import {
Area,
AreaChart,
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
interface LineChartData {
date: string;
value: number;
[key: string]: string | number;
}
interface LineChartProps {
data: LineChartData[];
title?: string;
dataKey?: string;
color?: string;
gradient?: boolean;
height?: number;
className?: string;
}
interface TooltipProps {
active?: boolean;
payload?: Array<{ value: number; name?: string }>;
label?: string;
}
const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
if (active && payload && payload.length) {
return (
<div className="rounded-lg border bg-background p-3 shadow-md">
<p className="text-sm font-medium">{label}</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
{payload[0].value}
</span>{" "}
sessions
</p>
</div>
);
}
return null;
};
export default function ModernLineChart({
data,
title,
dataKey = "value",
color = "hsl(var(--primary))",
gradient = true,
height = 300,
className,
}: LineChartProps) {
const gradientId = useId();
const ChartComponent = gradient ? AreaChart : LineChart;
return (
<Card className={className}>
{title && (
<CardHeader>
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
</CardHeader>
)}
<CardContent>
<ResponsiveContainer width="100%" height={height}>
<ChartComponent
data={data}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<defs>
{gradient && (
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
<stop offset="95%" stopColor={color} stopOpacity={0.05} />
</linearGradient>
)}
</defs>
<CartesianGrid
strokeDasharray="3 3"
stroke="hsl(var(--border))"
strokeOpacity={0.3}
/>
<XAxis
dataKey="date"
stroke="hsl(var(--muted-foreground))"
fontSize={12}
tickLine={false}
axisLine={false}
/>
<YAxis
stroke="hsl(var(--muted-foreground))"
fontSize={12}
tickLine={false}
axisLine={false}
/>
<Tooltip content={<CustomTooltip />} />
{gradient ? (
<Area
type="monotone"
dataKey={dataKey}
stroke={color}
strokeWidth={2}
fill={`url(#${gradientId})`}
dot={{ fill: color, strokeWidth: 2, r: 4 }}
activeDot={{ r: 6, stroke: color, strokeWidth: 2 }}
/>
) : (
<Line
type="monotone"
dataKey={dataKey}
stroke={color}
strokeWidth={2}
dot={{ fill: color, strokeWidth: 2, r: 4 }}
activeDot={{ r: 6, stroke: color, strokeWidth: 2 }}
/>
)}
</ChartComponent>
</ResponsiveContainer>
</CardContent>
</Card>
);
}

View File

@ -1,185 +0,0 @@
"use client";
import { motion } from "motion/react";
import { type RefObject, useEffect, useId, useState } from "react";
import { cn } from "@/lib/utils";
export interface AnimatedBeamProps {
className?: string;
containerRef: RefObject<HTMLElement | null>; // Container ref
fromRef: RefObject<HTMLElement | null>;
toRef: RefObject<HTMLElement | null>;
curvature?: number;
reverse?: boolean;
pathColor?: string;
pathWidth?: number;
pathOpacity?: number;
gradientStartColor?: string;
gradientStopColor?: string;
delay?: number;
duration?: number;
startXOffset?: number;
startYOffset?: number;
endXOffset?: number;
endYOffset?: number;
}
export const AnimatedBeam: React.FC<AnimatedBeamProps> = ({
className,
containerRef,
fromRef,
toRef,
curvature = 0,
reverse = false, // Include the reverse prop
duration = Math.random() * 3 + 4,
delay = 0,
pathColor = "gray",
pathWidth = 2,
pathOpacity = 0.2,
gradientStartColor = "#ffaa40",
gradientStopColor = "#9c40ff",
startXOffset = 0,
startYOffset = 0,
endXOffset = 0,
endYOffset = 0,
}) => {
const id = useId();
const [pathD, setPathD] = useState("");
const [svgDimensions, setSvgDimensions] = useState({ width: 0, height: 0 });
// Calculate the gradient coordinates based on the reverse prop
const gradientCoordinates = reverse
? {
x1: ["90%", "-10%"],
x2: ["100%", "0%"],
y1: ["0%", "0%"],
y2: ["0%", "0%"],
}
: {
x1: ["10%", "110%"],
x2: ["0%", "100%"],
y1: ["0%", "0%"],
y2: ["0%", "0%"],
};
useEffect(() => {
const updatePath = () => {
if (containerRef.current && fromRef.current && toRef.current) {
const containerRect = containerRef.current.getBoundingClientRect();
const rectA = fromRef.current.getBoundingClientRect();
const rectB = toRef.current.getBoundingClientRect();
const svgWidth = containerRect.width;
const svgHeight = containerRect.height;
setSvgDimensions({ width: svgWidth, height: svgHeight });
const startX =
rectA.left - containerRect.left + rectA.width / 2 + startXOffset;
const startY =
rectA.top - containerRect.top + rectA.height / 2 + startYOffset;
const endX =
rectB.left - containerRect.left + rectB.width / 2 + endXOffset;
const endY =
rectB.top - containerRect.top + rectB.height / 2 + endYOffset;
const controlY = startY - curvature;
const d = `M ${startX},${startY} Q ${
(startX + endX) / 2
},${controlY} ${endX},${endY}`;
setPathD(d);
}
};
// Initialize ResizeObserver
const resizeObserver = new ResizeObserver((entries) => {
// For all entries, recalculate the path
for (const _entry of entries) {
updatePath();
}
});
// Observe the container element
if (containerRef.current) {
resizeObserver.observe(containerRef.current);
}
// Call the updatePath initially to set the initial path
updatePath();
// Clean up the observer on component unmount
return () => {
resizeObserver.disconnect();
};
}, [
containerRef,
fromRef,
toRef,
curvature,
startXOffset,
startYOffset,
endXOffset,
endYOffset,
]);
return (
<svg
fill="none"
width={svgDimensions.width}
height={svgDimensions.height}
xmlns="http://www.w3.org/2000/svg"
className={cn(
"pointer-events-none absolute left-0 top-0 transform-gpu stroke-2",
className
)}
viewBox={`0 0 ${svgDimensions.width} ${svgDimensions.height}`}
>
<title>Animated connection beam</title>
<path
d={pathD}
stroke={pathColor}
strokeWidth={pathWidth}
strokeOpacity={pathOpacity}
strokeLinecap="round"
/>
<path
d={pathD}
strokeWidth={pathWidth}
stroke={`url(#${id})`}
strokeOpacity="1"
strokeLinecap="round"
/>
<defs>
<motion.linearGradient
className="transform-gpu"
id={id}
gradientUnits={"userSpaceOnUse"}
initial={{
x1: "0%",
x2: "0%",
y1: "0%",
y2: "0%",
}}
animate={{
x1: gradientCoordinates.x1,
x2: gradientCoordinates.x2,
y1: gradientCoordinates.y1,
y2: gradientCoordinates.y2,
}}
transition={{
delay,
duration,
ease: [0.16, 1, 0.3, 1], // https://easings.net/#easeOutExpo
repeat: Number.POSITIVE_INFINITY,
repeatDelay: 0,
}}
>
<stop stopColor={gradientStartColor} stopOpacity="0" />
<stop stopColor={gradientStartColor} />
<stop offset="32.5%" stopColor={gradientStopColor} />
<stop offset="100%" stopColor={gradientStopColor} stopOpacity="0" />
</motion.linearGradient>
</defs>
</svg>
);
};

View File

@ -1,109 +0,0 @@
import { cn } from "@/lib/utils";
interface AnimatedCircularProgressBarProps {
max: number;
value: number;
min: number;
gaugePrimaryColor: string;
gaugeSecondaryColor: string;
className?: string;
}
export function AnimatedCircularProgressBar({
max = 100,
min = 0,
value = 0,
gaugePrimaryColor,
gaugeSecondaryColor,
className,
}: AnimatedCircularProgressBarProps) {
const circumference = 2 * Math.PI * 45;
const percentPx = circumference / 100;
const currentPercent = Math.round(((value - min) / (max - min)) * 100);
return (
<div
className={cn("relative size-40 text-2xl font-semibold", className)}
style={
{
"--circle-size": "100px",
"--circumference": circumference,
"--percent-to-px": `${percentPx}px`,
"--gap-percent": "5",
"--offset-factor": "0",
"--transition-length": "1s",
"--transition-step": "200ms",
"--delay": "0s",
"--percent-to-deg": "3.6deg",
transform: "translateZ(0)",
} as React.CSSProperties
}
>
<svg
fill="none"
className="size-full"
strokeWidth="2"
viewBox="0 0 100 100"
>
<title>Circular progress indicator</title>
{currentPercent <= 90 && currentPercent >= 0 && (
<circle
cx="50"
cy="50"
r="45"
strokeWidth="10"
strokeDashoffset="0"
strokeLinecap="round"
strokeLinejoin="round"
className=" opacity-100"
style={
{
stroke: gaugeSecondaryColor,
"--stroke-percent": 90 - currentPercent,
"--offset-factor-secondary": "calc(1 - var(--offset-factor))",
strokeDasharray:
"calc(var(--stroke-percent) * var(--percent-to-px)) var(--circumference)",
transform:
"rotate(calc(1turn - 90deg - (var(--gap-percent) * var(--percent-to-deg) * var(--offset-factor-secondary)))) scaleY(-1)",
transition: "all var(--transition-length) ease var(--delay)",
transformOrigin:
"calc(var(--circle-size) / 2) calc(var(--circle-size) / 2)",
} as React.CSSProperties
}
/>
)}
<circle
cx="50"
cy="50"
r="45"
strokeWidth="10"
strokeDashoffset="0"
strokeLinecap="round"
strokeLinejoin="round"
className="opacity-100"
style={
{
stroke: gaugePrimaryColor,
"--stroke-percent": currentPercent,
strokeDasharray:
"calc(var(--stroke-percent) * var(--percent-to-px)) var(--circumference)",
transition:
"var(--transition-length) ease var(--delay),stroke var(--transition-length) ease var(--delay)",
transitionProperty: "stroke-dasharray,transform",
transform:
"rotate(calc(-90deg + var(--gap-percent) * var(--offset-factor) * var(--percent-to-deg)))",
transformOrigin:
"calc(var(--circle-size) / 2) calc(var(--circle-size) / 2)",
} as React.CSSProperties
}
/>
</svg>
<span
data-current-value={currentPercent}
className="duration-[var(--transition-length)] delay-[var(--delay)] absolute inset-0 m-auto size-fit ease-linear animate-in fade-in"
>
{currentPercent}
</span>
</div>
);
}

View File

@ -1,39 +0,0 @@
import type { ComponentPropsWithoutRef, CSSProperties, FC } from "react";
import { cn } from "@/lib/utils";
export interface AnimatedShinyTextProps
extends ComponentPropsWithoutRef<"span"> {
shimmerWidth?: number;
}
export const AnimatedShinyText: FC<AnimatedShinyTextProps> = ({
children,
className,
shimmerWidth = 100,
...props
}) => {
return (
<span
style={
{
"--shiny-width": `${shimmerWidth}px`,
} as CSSProperties
}
className={cn(
"mx-auto max-w-md text-neutral-600/70 dark:text-neutral-400/70",
// Shine effect
"animate-shiny-text bg-clip-text bg-no-repeat [background-position:0_0] [background-size:var(--shiny-width)_100%] [transition:background-position_1s_cubic-bezier(.6,.6,0,1)_infinite]",
// Shine gradient
"bg-gradient-to-r from-transparent via-black/80 via-50% to-transparent dark:via-white/80",
className
)}
{...props}
>
{children}
</span>
);
};

View File

@ -1,44 +0,0 @@
"use client";
import type React from "react";
import { memo } from "react";
interface AuroraTextProps {
children: React.ReactNode;
className?: string;
colors?: string[];
speed?: number;
}
export const AuroraText = memo(
({
children,
className = "",
colors = ["#FF0080", "#7928CA", "#0070F3", "#38bdf8"],
speed = 1,
}: AuroraTextProps) => {
const gradientStyle = {
backgroundImage: `linear-gradient(135deg, ${colors.join(", ")}, ${
colors[0]
})`,
WebkitBackgroundClip: "text",
WebkitTextFillColor: "transparent",
animationDuration: `${10 / speed}s`,
};
return (
<span className={`relative inline-block ${className}`}>
<span className="sr-only">{children}</span>
<span
className="relative animate-aurora bg-[length:200%_auto] bg-clip-text text-transparent"
style={gradientStyle}
aria-hidden="true"
>
{children}
</span>
</span>
);
}
);
AuroraText.displayName = "AuroraText";

View File

@ -1,81 +0,0 @@
"use client";
import {
AnimatePresence,
type MotionProps,
motion,
type UseInViewOptions,
useInView,
type Variants,
} from "motion/react";
import { useRef } from "react";
type MarginType = UseInViewOptions["margin"];
interface BlurFadeProps extends MotionProps {
children: React.ReactNode;
className?: string;
variant?: {
hidden: { y: number };
visible: { y: number };
};
duration?: number;
delay?: number;
offset?: number;
direction?: "up" | "down" | "left" | "right";
inView?: boolean;
inViewMargin?: MarginType;
blur?: string;
}
export function BlurFade({
children,
className,
variant,
duration = 0.4,
delay = 0,
offset = 6,
direction = "down",
inView = false,
inViewMargin = "-50px",
blur = "6px",
...props
}: BlurFadeProps) {
const ref = useRef(null);
const inViewResult = useInView(ref, { once: true, margin: inViewMargin });
const isInView = !inView || inViewResult;
const defaultVariants: Variants = {
hidden: {
[direction === "left" || direction === "right" ? "x" : "y"]:
direction === "right" || direction === "down" ? -offset : offset,
opacity: 0,
filter: `blur(${blur})`,
},
visible: {
[direction === "left" || direction === "right" ? "x" : "y"]: 0,
opacity: 1,
filter: "blur(0px)",
},
};
const combinedVariants = variant || defaultVariants;
return (
<AnimatePresence>
<motion.div
ref={ref}
initial="hidden"
animate={isInView ? "visible" : "hidden"}
exit="hidden"
variants={combinedVariants}
transition={{
delay: 0.04 + delay,
duration,
ease: "easeOut",
}}
className={className}
{...props}
>
{children}
</motion.div>
</AnimatePresence>
);
}

View File

@ -1,106 +0,0 @@
"use client";
import { type MotionStyle, motion, type Transition } from "motion/react";
import { cn } from "@/lib/utils";
interface BorderBeamProps {
/**
* The size of the border beam.
*/
size?: number;
/**
* The duration of the border beam.
*/
duration?: number;
/**
* The delay of the border beam.
*/
delay?: number;
/**
* The color of the border beam from.
*/
colorFrom?: string;
/**
* The color of the border beam to.
*/
colorTo?: string;
/**
* The motion transition of the border beam.
*/
transition?: Transition;
/**
* The class name of the border beam.
*/
className?: string;
/**
* The style of the border beam.
*/
style?: React.CSSProperties;
/**
* Whether to reverse the animation direction.
*/
reverse?: boolean;
/**
* The initial offset position (0-100).
*/
initialOffset?: number;
/**
* The border width of the beam.
*/
borderWidth?: number;
}
export const BorderBeam = ({
className,
size = 50,
delay = 0,
duration = 6,
colorFrom = "#ffaa40",
colorTo = "#9c40ff",
transition,
style,
reverse = false,
initialOffset = 0,
borderWidth = 1,
}: BorderBeamProps) => {
return (
<div
className="pointer-events-none absolute inset-0 rounded-[inherit] border-transparent [mask-clip:padding-box,border-box] [mask-composite:intersect] [mask-image:linear-gradient(transparent,transparent),linear-gradient(#000,#000)] border-(length:--border-beam-width)"
style={
{
"--border-beam-width": `${borderWidth}px`,
} as React.CSSProperties
}
>
<motion.div
className={cn(
"absolute aspect-square",
"bg-gradient-to-l from-[var(--color-from)] via-[var(--color-to)] to-transparent",
className
)}
style={
{
width: size,
offsetPath: `rect(0 auto auto 0 round ${size}px)`,
"--color-from": colorFrom,
"--color-to": colorTo,
...style,
} as MotionStyle
}
initial={{ offsetDistance: `${initialOffset}%` }}
animate={{
offsetDistance: reverse
? [`${100 - initialOffset}%`, `${-initialOffset}%`]
: [`${initialOffset}%`, `${100 + initialOffset}%`],
}}
transition={{
repeat: Number.POSITIVE_INFINITY,
ease: "linear",
duration,
delay: -delay,
...transition,
}}
/>
</div>
);
};

View File

@ -1,150 +0,0 @@
"use client";
import type {
GlobalOptions as ConfettiGlobalOptions,
CreateTypes as ConfettiInstance,
Options as ConfettiOptions,
} from "canvas-confetti";
import confetti from "canvas-confetti";
import type React from "react";
import type { ReactNode } from "react";
import {
createContext,
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
} from "react";
import { Button, type ButtonProps } from "@/components/ui/button";
type Api = {
fire: (options?: ConfettiOptions) => void;
};
type Props = React.ComponentPropsWithRef<"canvas"> & {
options?: ConfettiOptions;
globalOptions?: ConfettiGlobalOptions;
manualstart?: boolean;
children?: ReactNode;
};
export type ConfettiRef = Api | null;
const ConfettiContext = createContext<Api>({} as Api);
// Define component first
const ConfettiComponent = forwardRef<ConfettiRef, Props>((props, ref) => {
const {
options,
globalOptions = { resize: true, useWorker: true },
manualstart = false,
children,
...rest
} = props;
const instanceRef = useRef<ConfettiInstance | null>(null);
const canvasRef = useCallback(
(node: HTMLCanvasElement) => {
if (node !== null) {
if (instanceRef.current) return;
instanceRef.current = confetti.create(node, {
...globalOptions,
resize: true,
});
} else {
if (instanceRef.current) {
instanceRef.current.reset();
instanceRef.current = null;
}
}
},
[globalOptions]
);
const fire = useCallback(
async (opts = {}) => {
try {
await instanceRef.current?.({ ...options, ...opts });
} catch (error) {
console.error("Confetti error:", error);
}
},
[options]
);
const api = useMemo(
() => ({
fire,
}),
[fire]
);
useImperativeHandle(ref, () => api, [api]);
useEffect(() => {
if (!manualstart) {
(async () => {
try {
await fire();
} catch (error) {
console.error("Confetti effect error:", error);
}
})();
}
}, [manualstart, fire]);
return (
<ConfettiContext.Provider value={api}>
<canvas ref={canvasRef} {...rest} />
{children}
</ConfettiContext.Provider>
);
});
// Set display name immediately
ConfettiComponent.displayName = "Confetti";
// Export as Confetti
export const Confetti = ConfettiComponent;
interface ConfettiButtonProps extends ButtonProps {
options?: ConfettiOptions &
ConfettiGlobalOptions & { canvas?: HTMLCanvasElement };
children?: React.ReactNode;
}
const ConfettiButtonComponent = ({
options,
children,
...props
}: ConfettiButtonProps) => {
const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {
try {
const rect = event.currentTarget.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
await confetti({
...options,
origin: {
x: x / window.innerWidth,
y: y / window.innerHeight,
},
});
} catch (error) {
console.error("Confetti button error:", error);
}
};
return (
<Button onClick={handleClick} {...props}>
{children}
</Button>
);
};
ConfettiButtonComponent.displayName = "ConfettiButton";
export const ConfettiButton = ConfettiButtonComponent;

View File

@ -1,109 +0,0 @@
"use client";
import { motion, useMotionTemplate, useMotionValue } from "motion/react";
import type React from "react";
import { useCallback, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
interface MagicCardProps {
children?: React.ReactNode;
className?: string;
gradientSize?: number;
gradientColor?: string;
gradientOpacity?: number;
gradientFrom?: string;
gradientTo?: string;
}
export function MagicCard({
children,
className,
gradientSize = 200,
gradientColor = "#262626",
gradientOpacity = 0.8,
gradientFrom = "#9E7AFF",
gradientTo = "#FE8BBB",
}: MagicCardProps) {
const cardRef = useRef<HTMLDivElement>(null);
const mouseX = useMotionValue(-gradientSize);
const mouseY = useMotionValue(-gradientSize);
const handleMouseMove = useCallback(
(e: MouseEvent) => {
if (cardRef.current) {
const { left, top } = cardRef.current.getBoundingClientRect();
const clientX = e.clientX;
const clientY = e.clientY;
mouseX.set(clientX - left);
mouseY.set(clientY - top);
}
},
[mouseX, mouseY]
);
const handleMouseOut = useCallback(
(e: MouseEvent) => {
if (!e.relatedTarget) {
document.removeEventListener("mousemove", handleMouseMove);
mouseX.set(-gradientSize);
mouseY.set(-gradientSize);
}
},
[handleMouseMove, mouseX, gradientSize, mouseY]
);
const handleMouseEnter = useCallback(() => {
document.addEventListener("mousemove", handleMouseMove);
mouseX.set(-gradientSize);
mouseY.set(-gradientSize);
}, [handleMouseMove, mouseX, gradientSize, mouseY]);
useEffect(() => {
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseout", handleMouseOut);
document.addEventListener("mouseenter", handleMouseEnter);
return () => {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseout", handleMouseOut);
document.removeEventListener("mouseenter", handleMouseEnter);
};
}, [handleMouseEnter, handleMouseMove, handleMouseOut]);
useEffect(() => {
mouseX.set(-gradientSize);
mouseY.set(-gradientSize);
}, [gradientSize, mouseX, mouseY]);
return (
<div
ref={cardRef}
className={cn("group relative rounded-[inherit]", className)}
>
<motion.div
className="pointer-events-none absolute inset-0 rounded-[inherit] bg-border duration-300 group-hover:opacity-100"
style={{
background: useMotionTemplate`
radial-gradient(${gradientSize}px circle at ${mouseX}px ${mouseY}px,
${gradientFrom},
${gradientTo},
var(--border) 100%
)
`,
}}
/>
<div className="absolute inset-px rounded-[inherit] bg-background" />
<motion.div
className="pointer-events-none absolute inset-px rounded-[inherit] opacity-0 transition-opacity duration-300 group-hover:opacity-100"
style={{
background: useMotionTemplate`
radial-gradient(${gradientSize}px circle at ${mouseX}px ${mouseY}px, ${gradientColor}, transparent 100%)
`,
opacity: gradientOpacity,
}}
/>
<div className="relative">{children}</div>
</div>
);
}

View File

@ -1,61 +0,0 @@
"use client";
import type React from "react";
import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
interface MeteorsProps {
number?: number;
minDelay?: number;
maxDelay?: number;
minDuration?: number;
maxDuration?: number;
angle?: number;
className?: string;
}
export const Meteors = ({
number = 20,
minDelay = 0.2,
maxDelay = 1.2,
minDuration = 2,
maxDuration = 10,
angle = 215,
className,
}: MeteorsProps) => {
const [meteorStyles, setMeteorStyles] = useState<Array<React.CSSProperties>>(
[]
);
useEffect(() => {
const styles = [...new Array(number)].map(() => ({
"--angle": `${-angle}deg`,
top: "-5%",
left: `calc(0% + ${Math.floor(Math.random() * window.innerWidth)}px)`,
animationDelay: `${Math.random() * (maxDelay - minDelay) + minDelay}s`,
animationDuration:
Math.floor(Math.random() * (maxDuration - minDuration) + minDuration) +
"s",
}));
setMeteorStyles(styles);
}, [number, minDelay, maxDelay, minDuration, maxDuration, angle]);
return (
<>
{[...meteorStyles].map((style, idx) => (
// Meteor Head
<span
key={`meteor-${style.left}-${style.animationDelay}-${idx}`}
style={{ ...style }}
className={cn(
"pointer-events-none absolute size-0.5 rotate-[var(--angle)] animate-meteor rounded-full bg-zinc-500 shadow-[0_0_0_1px_#ffffff10]",
className
)}
>
{/* Meteor Tail */}
<div className="pointer-events-none absolute top-1/2 -z-10 h-px w-[50px] -translate-y-1/2 bg-gradient-to-r from-zinc-500 to-transparent" />
</span>
))}
</>
);
};

View File

@ -1,155 +0,0 @@
"use client";
import {
type CSSProperties,
type ReactElement,
type ReactNode,
useEffect,
useRef,
useState,
} from "react";
import { cn } from "@/lib/utils";
interface NeonColorsProps {
firstColor: string;
secondColor: string;
}
interface NeonGradientCardProps {
/**
* @default <div />
* @type ReactElement
* @description
* The component to be rendered as the card
* */
as?: ReactElement;
/**
* @default ""
* @type string
* @description
* The className of the card
*/
className?: string;
/**
* @default ""
* @type ReactNode
* @description
* The children of the card
* */
children?: ReactNode;
/**
* @default 5
* @type number
* @description
* The size of the border in pixels
* */
borderSize?: number;
/**
* @default 20
* @type number
* @description
* The size of the radius in pixels
* */
borderRadius?: number;
/**
* @default "{ firstColor: '#ff00aa', secondColor: '#00FFF1' }"
* @type string
* @description
* The colors of the neon gradient
* */
neonColors?: NeonColorsProps;
// Allow additional HTML div properties
style?: CSSProperties;
id?: string;
onClick?: () => void;
onMouseEnter?: () => void;
onMouseLeave?: () => void;
"data-testid"?: string;
}
export const NeonGradientCard: React.FC<NeonGradientCardProps> = ({
className,
children,
borderSize = 2,
borderRadius = 20,
neonColors = {
firstColor: "#ff00aa",
secondColor: "#00FFF1",
},
...props
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
const updateDimensions = () => {
if (containerRef.current) {
const { offsetWidth, offsetHeight } = containerRef.current;
setDimensions({ width: offsetWidth, height: offsetHeight });
}
};
updateDimensions();
window.addEventListener("resize", updateDimensions);
return () => {
window.removeEventListener("resize", updateDimensions);
};
}, []);
useEffect(() => {
if (containerRef.current) {
const { offsetWidth, offsetHeight } = containerRef.current;
setDimensions({ width: offsetWidth, height: offsetHeight });
}
}, []);
return (
<div
ref={containerRef}
style={
{
"--border-size": `${borderSize}px`,
"--border-radius": `${borderRadius}px`,
"--neon-first-color": neonColors.firstColor,
"--neon-second-color": neonColors.secondColor,
"--card-width": `${dimensions.width}px`,
"--card-height": `${dimensions.height}px`,
"--card-content-radius": `${borderRadius - borderSize}px`,
"--pseudo-element-background-image": `linear-gradient(0deg, ${neonColors.firstColor}, ${neonColors.secondColor})`,
"--pseudo-element-width": `${dimensions.width + borderSize * 2}px`,
"--pseudo-element-height": `${dimensions.height + borderSize * 2}px`,
"--after-blur": `${dimensions.width / 3}px`,
} as CSSProperties
}
className={cn(
"relative z-10 size-full rounded-[var(--border-radius)]",
className
)}
{...props}
>
<div
className={cn(
"relative size-full min-h-[inherit] rounded-[var(--card-content-radius)] bg-gray-100 p-6",
"before:absolute before:-left-[var(--border-size)] before:-top-[var(--border-size)] before:-z-10 before:block",
"before:h-[var(--pseudo-element-height)] before:w-[var(--pseudo-element-width)] before:rounded-[var(--border-radius)] before:content-['']",
"before:bg-[linear-gradient(0deg,var(--neon-first-color),var(--neon-second-color))] before:bg-[length:100%_200%]",
"before:animate-background-position-spin",
"after:absolute after:-left-[var(--border-size)] after:-top-[var(--border-size)] after:-z-10 after:block",
"after:h-[var(--pseudo-element-height)] after:w-[var(--pseudo-element-width)] after:rounded-[var(--border-radius)] after:blur-[var(--after-blur)] after:content-['']",
"after:bg-[linear-gradient(0deg,var(--neon-first-color),var(--neon-second-color))] after:bg-[length:100%_200%] after:opacity-80",
"after:animate-background-position-spin",
"dark:bg-neutral-900"
)}
>
{children}
</div>
</div>
);
};

View File

@ -1,67 +0,0 @@
"use client";
import { useInView, useMotionValue, useSpring } from "motion/react";
import { type ComponentPropsWithoutRef, useEffect, useRef } from "react";
import { cn } from "@/lib/utils";
interface NumberTickerProps extends ComponentPropsWithoutRef<"span"> {
value: number;
startValue?: number;
direction?: "up" | "down";
delay?: number;
decimalPlaces?: number;
}
export function NumberTicker({
value,
startValue = 0,
direction = "up",
delay = 0,
className,
decimalPlaces = 0,
...props
}: NumberTickerProps) {
const ref = useRef<HTMLSpanElement>(null);
const motionValue = useMotionValue(direction === "down" ? value : startValue);
const springValue = useSpring(motionValue, {
damping: 60,
stiffness: 100,
});
const isInView = useInView(ref, { once: true, margin: "0px" });
useEffect(() => {
if (isInView) {
const timer = setTimeout(() => {
motionValue.set(direction === "down" ? startValue : value);
}, delay * 1000);
return () => clearTimeout(timer);
}
}, [motionValue, isInView, delay, value, direction, startValue]);
useEffect(
() =>
springValue.on("change", (latest) => {
if (ref.current) {
ref.current.textContent = Intl.NumberFormat("en-US", {
minimumFractionDigits: decimalPlaces,
maximumFractionDigits: decimalPlaces,
}).format(Number(latest.toFixed(decimalPlaces)));
}
}),
[springValue, decimalPlaces]
);
return (
<span
ref={ref}
className={cn(
"inline-block tabular-nums tracking-wider text-black dark:text-white",
className
)}
{...props}
>
{startValue}
</span>
);
}

View File

@ -1,121 +0,0 @@
"use client";
import {
AnimatePresence,
type HTMLMotionProps,
motion,
useMotionValue,
} from "motion/react";
import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
interface PointerProps extends Omit<HTMLMotionProps<"div">, "ref"> {
children?: React.ReactNode;
}
/**
* A custom pointer component that displays an animated cursor.
* Add this as a child to any component to enable a custom pointer when hovering.
* You can pass custom children to render as the pointer.
*
* @component
* @param {PointerProps} props - The component props
*/
export function Pointer({
className,
style,
children,
...props
}: PointerProps): JSX.Element {
const x = useMotionValue(0);
const y = useMotionValue(0);
const [isActive, setIsActive] = useState<boolean>(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (typeof window !== "undefined" && containerRef.current) {
// Get the parent element directly from the ref
const parentElement = containerRef.current.parentElement;
if (parentElement) {
// Add cursor-none to parent
parentElement.style.cursor = "none";
// Add event listeners to parent
const handleMouseMove = (e: MouseEvent) => {
x.set(e.clientX);
y.set(e.clientY);
};
const handleMouseEnter = () => {
setIsActive(true);
};
const handleMouseLeave = () => {
setIsActive(false);
};
parentElement.addEventListener("mousemove", handleMouseMove);
parentElement.addEventListener("mouseenter", handleMouseEnter);
parentElement.addEventListener("mouseleave", handleMouseLeave);
return () => {
parentElement.style.cursor = "";
parentElement.removeEventListener("mousemove", handleMouseMove);
parentElement.removeEventListener("mouseenter", handleMouseEnter);
parentElement.removeEventListener("mouseleave", handleMouseLeave);
};
}
}
}, [x, y]);
return (
<>
<div ref={containerRef} />
<AnimatePresence>
{isActive && (
<motion.div
className="transform-[translate(-50%,-50%)] pointer-events-none fixed z-50"
style={{
top: y,
left: x,
...style,
}}
initial={{
scale: 0,
opacity: 0,
}}
animate={{
scale: 1,
opacity: 1,
}}
exit={{
scale: 0,
opacity: 0,
}}
{...props}
>
{children || (
<svg
stroke="currentColor"
fill="currentColor"
strokeWidth="1"
viewBox="0 0 16 16"
height="24"
width="24"
xmlns="http://www.w3.org/2000/svg"
className={cn(
"rotate-[-70deg] stroke-white text-black",
className
)}
>
<title>Mouse pointer</title>
<path d="M14.082 2.182a.5.5 0 0 1 .103.557L8.528 15.467a.5.5 0 0 1-.917-.007L5.57 10.694.803 8.652a.5.5 0 0 1-.006-.916l12.728-5.657a.5.5 0 0 1 .556.103z" />
</svg>
)}
</motion.div>
)}
</AnimatePresence>
</>
);
}

View File

@ -1,33 +0,0 @@
"use client";
import { type MotionProps, motion, useScroll } from "motion/react";
import React from "react";
import { cn } from "@/lib/utils";
interface ScrollProgressProps
extends Omit<React.HTMLAttributes<HTMLElement>, keyof MotionProps> {
className?: string;
}
export const ScrollProgress = React.forwardRef<
HTMLDivElement,
ScrollProgressProps
>(({ className, ...props }, ref) => {
const { scrollYProgress } = useScroll();
return (
<motion.div
ref={ref}
className={cn(
"fixed inset-x-0 top-0 z-50 h-px origin-left bg-gradient-to-r from-[#A97CF8] via-[#F38CB8] to-[#FDCC92]",
className
)}
style={{
scaleX: scrollYProgress,
}}
{...props}
/>
);
});
ScrollProgress.displayName = "ScrollProgress";

View File

@ -1,64 +0,0 @@
"use client";
import type * as React from "react";
import { cn } from "@/lib/utils";
interface ShineBorderProps extends React.HTMLAttributes<HTMLDivElement> {
/**
* Width of the border in pixels
* @default 1
*/
borderWidth?: number;
/**
* Duration of the animation in seconds
* @default 14
*/
duration?: number;
/**
* Color of the border, can be a single color or an array of colors
* @default "#000000"
*/
shineColor?: string | string[];
}
/**
* Shine Border
*
* An animated background border effect component with configurable properties.
*/
export function ShineBorder({
borderWidth = 1,
duration = 14,
shineColor = "#000000",
className,
style,
...props
}: ShineBorderProps) {
return (
<div
style={
{
"--border-width": `${borderWidth}px`,
"--duration": `${duration}s`,
backgroundImage: `radial-gradient(transparent,transparent, ${
Array.isArray(shineColor) ? shineColor.join(",") : shineColor
},transparent,transparent)`,
backgroundSize: "300% 300%",
mask: "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)",
WebkitMask:
"linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)",
WebkitMaskComposite: "xor",
maskComposite: "exclude",
padding: "var(--border-width)",
...style,
} as React.CSSProperties
}
className={cn(
"pointer-events-none absolute inset-0 size-full rounded-[inherit] will-change-[background-position] motion-safe:animate-shine",
className
)}
{...props}
/>
);
}

View File

@ -1,414 +0,0 @@
"use client";
import {
AnimatePresence,
type MotionProps,
motion,
type Variants,
} from "motion/react";
import { type ElementType, memo } from "react";
import { cn } from "@/lib/utils";
type AnimationType = "text" | "word" | "character" | "line";
type AnimationVariant =
| "fadeIn"
| "blurIn"
| "blurInUp"
| "blurInDown"
| "slideUp"
| "slideDown"
| "slideLeft"
| "slideRight"
| "scaleUp"
| "scaleDown";
interface TextAnimateProps extends MotionProps {
/**
* The text content to animate
*/
children: string;
/**
* The class name to be applied to the component
*/
className?: string;
/**
* The class name to be applied to each segment
*/
segmentClassName?: string;
/**
* The delay before the animation starts
*/
delay?: number;
/**
* The duration of the animation
*/
duration?: number;
/**
* Custom motion variants for the animation
*/
variants?: Variants;
/**
* The element type to render
*/
as?: ElementType;
/**
* How to split the text ("text", "word", "character")
*/
by?: AnimationType;
/**
* Whether to start animation when component enters viewport
*/
startOnView?: boolean;
/**
* Whether to animate only once
*/
once?: boolean;
/**
* The animation preset to use
*/
animation?: AnimationVariant;
}
const staggerTimings: Record<AnimationType, number> = {
text: 0.06,
word: 0.05,
character: 0.03,
line: 0.06,
};
const defaultContainerVariants = {
hidden: { opacity: 1 },
show: {
opacity: 1,
transition: {
delayChildren: 0,
staggerChildren: 0.05,
},
},
exit: {
opacity: 0,
transition: {
staggerChildren: 0.05,
staggerDirection: -1,
},
},
};
const defaultItemVariants: Variants = {
hidden: { opacity: 0 },
show: {
opacity: 1,
},
exit: {
opacity: 0,
},
};
const defaultItemAnimationVariants: Record<
AnimationVariant,
{ container: Variants; item: Variants }
> = {
fadeIn: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, y: 20 },
show: {
opacity: 1,
y: 0,
transition: {
duration: 0.3,
},
},
exit: {
opacity: 0,
y: 20,
transition: { duration: 0.3 },
},
},
},
blurIn: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, filter: "blur(10px)" },
show: {
opacity: 1,
filter: "blur(0px)",
transition: {
duration: 0.3,
},
},
exit: {
opacity: 0,
filter: "blur(10px)",
transition: { duration: 0.3 },
},
},
},
blurInUp: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, filter: "blur(10px)", y: 20 },
show: {
opacity: 1,
filter: "blur(0px)",
y: 0,
transition: {
y: { duration: 0.3 },
opacity: { duration: 0.4 },
filter: { duration: 0.3 },
},
},
exit: {
opacity: 0,
filter: "blur(10px)",
y: 20,
transition: {
y: { duration: 0.3 },
opacity: { duration: 0.4 },
filter: { duration: 0.3 },
},
},
},
},
blurInDown: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, filter: "blur(10px)", y: -20 },
show: {
opacity: 1,
filter: "blur(0px)",
y: 0,
transition: {
y: { duration: 0.3 },
opacity: { duration: 0.4 },
filter: { duration: 0.3 },
},
},
},
},
slideUp: {
container: defaultContainerVariants,
item: {
hidden: { y: 20, opacity: 0 },
show: {
y: 0,
opacity: 1,
transition: {
duration: 0.3,
},
},
exit: {
y: -20,
opacity: 0,
transition: {
duration: 0.3,
},
},
},
},
slideDown: {
container: defaultContainerVariants,
item: {
hidden: { y: -20, opacity: 0 },
show: {
y: 0,
opacity: 1,
transition: { duration: 0.3 },
},
exit: {
y: 20,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
slideLeft: {
container: defaultContainerVariants,
item: {
hidden: { x: 20, opacity: 0 },
show: {
x: 0,
opacity: 1,
transition: { duration: 0.3 },
},
exit: {
x: -20,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
slideRight: {
container: defaultContainerVariants,
item: {
hidden: { x: -20, opacity: 0 },
show: {
x: 0,
opacity: 1,
transition: { duration: 0.3 },
},
exit: {
x: 20,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
scaleUp: {
container: defaultContainerVariants,
item: {
hidden: { scale: 0.5, opacity: 0 },
show: {
scale: 1,
opacity: 1,
transition: {
duration: 0.3,
scale: {
type: "spring",
damping: 15,
stiffness: 300,
},
},
},
exit: {
scale: 0.5,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
scaleDown: {
container: defaultContainerVariants,
item: {
hidden: { scale: 1.5, opacity: 0 },
show: {
scale: 1,
opacity: 1,
transition: {
duration: 0.3,
scale: {
type: "spring",
damping: 15,
stiffness: 300,
},
},
},
exit: {
scale: 1.5,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
};
const TextAnimateBase = ({
children,
delay = 0,
duration = 0.3,
variants,
className,
segmentClassName,
as: Component = "p",
startOnView = true,
once = false,
by = "word",
animation = "fadeIn",
...props
}: TextAnimateProps) => {
const MotionComponent = motion.create(Component);
let segments: string[] = [];
switch (by) {
case "word":
segments = children.split(/(\s+)/);
break;
case "character":
segments = children.split("");
break;
case "line":
segments = children.split("\n");
break;
default:
segments = [children];
break;
}
const finalVariants = variants
? {
container: {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
opacity: { duration: 0.01, delay },
delayChildren: delay,
staggerChildren: duration / segments.length,
},
},
exit: {
opacity: 0,
transition: {
staggerChildren: duration / segments.length,
staggerDirection: -1,
},
},
},
item: variants,
}
: animation
? {
container: {
...defaultItemAnimationVariants[animation].container,
show: {
...defaultItemAnimationVariants[animation].container.show,
transition: {
delayChildren: delay,
staggerChildren: duration / segments.length,
},
},
exit: {
...defaultItemAnimationVariants[animation].container.exit,
transition: {
staggerChildren: duration / segments.length,
staggerDirection: -1,
},
},
},
item: defaultItemAnimationVariants[animation].item,
}
: { container: defaultContainerVariants, item: defaultItemVariants };
return (
<AnimatePresence mode="popLayout">
<MotionComponent
variants={finalVariants.container as Variants}
initial="hidden"
whileInView={startOnView ? "show" : undefined}
animate={startOnView ? undefined : "show"}
exit="exit"
className={cn("whitespace-pre-wrap", className)}
viewport={{ once }}
{...props}
>
{segments.map((segment, i) => (
<motion.span
key={`${by}-${segment.replace(/\s/g, "_")}-${i}-${segment.length}`}
variants={finalVariants.item}
custom={i * staggerTimings[by]}
className={cn(
by === "line" ? "block" : "inline-block whitespace-pre",
by === "character" && "",
segmentClassName
)}
>
{segment}
</motion.span>
))}
</MotionComponent>
</AnimatePresence>
);
};
// Export the memoized version
export const TextAnimate = memo(TextAnimateBase);

View File

@ -1,85 +0,0 @@
"use client";
import {
type MotionValue,
motion,
useScroll,
useTransform,
} from "motion/react";
import {
type ComponentPropsWithoutRef,
type FC,
type ReactNode,
useRef,
} from "react";
import { cn } from "@/lib/utils";
export interface TextRevealProps extends ComponentPropsWithoutRef<"div"> {
children: string;
}
export const TextReveal: FC<TextRevealProps> = ({ children, className }) => {
const targetRef = useRef<HTMLDivElement | null>(null);
const { scrollYProgress } = useScroll({
target: targetRef,
});
if (typeof children !== "string") {
throw new Error("TextReveal: children must be a string");
}
const words = children.split(" ");
return (
<div ref={targetRef} className={cn("relative z-0 h-[200vh]", className)}>
<div
className={
"sticky top-0 mx-auto flex h-[50%] max-w-4xl items-center bg-transparent px-[1rem] py-[5rem]"
}
>
<span
ref={targetRef}
className={
"flex flex-wrap p-5 text-2xl font-bold text-black/20 dark:text-white/20 md:p-8 md:text-3xl lg:p-10 lg:text-4xl xl:text-5xl"
}
>
{words.map((word, i) => {
const start = i / words.length;
const end = start + 1 / words.length;
return (
<Word
key={`word-${word}-${i}-${start}`}
progress={scrollYProgress}
range={[start, end]}
>
{word}
</Word>
);
})}
</span>
</div>
</div>
);
};
interface WordProps {
children: ReactNode;
progress: MotionValue<number>;
range: [number, number];
}
const Word: FC<WordProps> = ({ children, progress, range }) => {
const opacity = useTransform(progress, range, [0, 1]);
return (
<span className="xl:lg-3 relative mx-1 lg:mx-1.5">
<span className="absolute opacity-30">{children}</span>
<motion.span
style={{ opacity: opacity }}
className={"text-black dark:text-white"}
>
{children}
</motion.span>
</span>
);
};

View File

@ -1,8 +0,0 @@
"use client";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import type { ThemeProviderProps } from "next-themes/dist/types";
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

View File

@ -1,66 +0,0 @@
"use client";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDownIcon } from "lucide-react";
import type * as React from "react";
import { cn } from "@/lib/utils";
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
);
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
);
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
);
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

View File

@ -1,156 +0,0 @@
"use client";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import type * as React from "react";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
);
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
);
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@ -1,59 +0,0 @@
import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };

View File

@ -1,46 +0,0 @@
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span";
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

@ -1,110 +0,0 @@
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import type * as React from "react";
import { cn } from "@/lib/utils";
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />;
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
className
)}
{...props}
/>
);
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-item"
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
);
}
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "a";
return (
<Comp
data-slot="breadcrumb-link"
className={cn("hover:text-foreground transition-colors", className)}
{...props}
/>
);
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
tabIndex={0}
className={cn("text-foreground font-normal", className)}
{...props}
/>
);
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
);
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">More</span>
</span>
);
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};

View File

@ -1,59 +0,0 @@
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
);
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };

View File

@ -1,240 +0,0 @@
"use client";
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react";
import * as React from "react";
import {
type DayButton,
DayPicker,
getDefaultClassNames,
} from "react-day-picker";
import { Button, buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
interface CalendarRootProps {
className?: string;
rootRef?: React.Ref<HTMLDivElement>;
[key: string]: unknown;
}
const CalendarRoot = ({ className, rootRef, ...props }: CalendarRootProps) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
);
};
interface CalendarChevronProps {
className?: string;
orientation: "left" | "right" | "up" | "down";
[key: string]: unknown;
}
const CalendarChevron = ({
className,
orientation,
...props
}: CalendarChevronProps) => {
if (orientation === "left") {
return <ChevronLeftIcon className={cn("size-4", className)} {...props} />;
}
if (orientation === "right") {
return <ChevronRightIcon className={cn("size-4", className)} {...props} />;
}
if (orientation === "up") {
return (
<ChevronDownIcon
className={cn("size-4 rotate-180", className)}
{...props}
/>
);
}
return <ChevronDownIcon className={cn("size-4", className)} {...props} />;
};
interface CalendarWeekNumberProps {
children: React.ReactNode;
[key: string]: unknown;
}
const CalendarWeekNumber = ({
children,
...props
}: CalendarWeekNumberProps) => {
return (
<td {...props}>
<div className="flex size-9 items-center justify-center p-0 text-sm">
{children}
</div>
</td>
);
};
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
}) {
const defaultClassNames = getDefaultClassNames();
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next
),
month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
defaultClassNames.dropdown_root
),
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-(--cell-size)",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number
),
day: cn(
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: CalendarRoot,
Chevron: CalendarChevron,
DayButton: CalendarDayButton,
WeekNumber: CalendarWeekNumber,
...components,
}}
{...props}
/>
);
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]);
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
);
}
export { Calendar, CalendarDayButton };

View File

@ -1,92 +0,0 @@
import type * as React from "react";
import { cn } from "@/lib/utils";
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
};

View File

@ -1,33 +0,0 @@
"use client";
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
);
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
);
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent };

View File

@ -1,143 +0,0 @@
"use client";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import type * as React from "react";
import { cn } from "@/lib/utils";
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background 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 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
);
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};

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