mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 12:52:09 +01:00
Compare commits
2 Commits
5042a6c016
...
developmen
| Author | SHA1 | Date | |
|---|---|---|---|
| a002d5ef76 | |||
| c4cfe2f389 |
10
.biomeignore
10
.biomeignore
@ -1,10 +0,0 @@
|
|||||||
node_modules/
|
|
||||||
.next/
|
|
||||||
dist/
|
|
||||||
build/
|
|
||||||
coverage/
|
|
||||||
.git/
|
|
||||||
*.min.js
|
|
||||||
public/
|
|
||||||
prisma/migrations/
|
|
||||||
.claude/
|
|
||||||
8
.github/workflows/playwright.yml
vendored
8
.github/workflows/playwright.yml
vendored
@ -14,11 +14,13 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: lts/*
|
node-version: lts/*
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm install -g pnpm && pnpm install
|
run: npm ci
|
||||||
|
- name: Build dashboard
|
||||||
|
run: npm run build
|
||||||
- name: Install Playwright Browsers
|
- name: Install Playwright Browsers
|
||||||
run: pnpm exec playwright install --with-deps
|
run: npx playwright install --with-deps
|
||||||
- name: Run Playwright tests
|
- name: Run Playwright tests
|
||||||
run: pnpm exec playwright test
|
run: npx playwright test
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
if: ${{ !cancelled() }}
|
if: ${{ !cancelled() }}
|
||||||
with:
|
with:
|
||||||
|
|||||||
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,5 +1,3 @@
|
|||||||
*-PROGRESS.md
|
|
||||||
|
|
||||||
# Created by https://www.toptal.com/developers/gitignore/api/node,nextjs,react
|
# Created by https://www.toptal.com/developers/gitignore/api/node,nextjs,react
|
||||||
# Edit at https://www.toptal.com/developers/gitignore?templates=node,nextjs,react
|
# Edit at https://www.toptal.com/developers/gitignore?templates=node,nextjs,react
|
||||||
|
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
npx lint-staged
|
|
||||||
144
CLAUDE.md
144
CLAUDE.md
@ -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
|
|
||||||
@ -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! 🎯
|
|
||||||
54
README.md
54
README.md
@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
A real-time analytics dashboard for monitoring user sessions and interactions with interactive data visualizations and detailed metrics.
|
A real-time analytics dashboard for monitoring user sessions and interactions with interactive data visualizations and detailed metrics.
|
||||||
|
|
||||||
.*%22&replace=%24%3Cversion%3E&logo=nextdotjs&label=Nextjs&color=%23000000>)
|
.*%22&replace=%24%3Cversion%3E&logo=nextdotjs&label=Nextjs&color=%23000000)
|
||||||
.*%22&replace=%24%3Cversion%3E&logo=react&label=React&color=%2361DAFB>)
|
.*%22&replace=%24%3Cversion%3E&logo=react&label=React&color=%2361DAFB)
|
||||||
.*%22&replace=%24%3Cversion%3E&logo=typescript&label=TypeScript&color=%233178C6>)
|
.*%22&replace=%24%3Cversion%3E&logo=typescript&label=TypeScript&color=%233178C6)
|
||||||
.*%22&replace=%24%3Cversion%3E&logo=prisma&label=Prisma&color=%232D3748>)
|
.*%22&replace=%24%3Cversion%3E&logo=prisma&label=Prisma&color=%232D3748)
|
||||||
.*%22&replace=%24%3Cversion%3E&logo=tailwindcss&label=TailwindCSS&color=%2306B6D4>)
|
.*%22&replace=%24%3Cversion%3E&logo=tailwindcss&label=TailwindCSS&color=%2306B6D4)
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@ -31,36 +31,36 @@ A real-time analytics dashboard for monitoring user sessions and interactions wi
|
|||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
- Node.js (LTS version recommended)
|
- Node.js (LTS version recommended)
|
||||||
- pnpm (recommended package manager)
|
- npm or yarn
|
||||||
|
|
||||||
### Installation
|
### Installation
|
||||||
|
|
||||||
1. Clone this repository:
|
1. Clone this repository:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/kjanat/livedash-node.git
|
git clone https://github.com/kjanat/livedash-node.git
|
||||||
cd livedash-node
|
cd livedash-node
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Install dependencies:
|
2. Install dependencies:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm install
|
npm install
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Set up the database:
|
3. Set up the database:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm run prisma:generate
|
npm run prisma:generate
|
||||||
pnpm run prisma:migrate
|
npm run prisma:migrate
|
||||||
pnpm run prisma:seed
|
npm run prisma:seed
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Start the development server:
|
4. Start the development server:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
5. Open your browser and navigate to <http://localhost:3000>
|
5. Open your browser and navigate to <http://localhost:3000>
|
||||||
|
|
||||||
@ -86,12 +86,12 @@ NEXTAUTH_SECRET=your-secret-here
|
|||||||
|
|
||||||
## Available Scripts
|
## Available Scripts
|
||||||
|
|
||||||
- `pnpm run dev`: Start the development server
|
- `npm run dev`: Start the development server
|
||||||
- `pnpm run build`: Build the application for production
|
- `npm run build`: Build the application for production
|
||||||
- `pnpm run start`: Run the production build
|
- `npm run start`: Run the production build
|
||||||
- `pnpm run lint`: Run ESLint
|
- `npm run lint`: Run ESLint
|
||||||
- `pnpm run format`: Format code with Prettier
|
- `npm run format`: Format code with Prettier
|
||||||
- `pnpm run prisma:studio`: Open Prisma Studio to view database
|
- `npm run prisma:studio`: Open Prisma Studio to view database
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
|
|||||||
247
TODO
247
TODO
@ -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
|
|
||||||
@ -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 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,4 +1,4 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { fetchAndParseCsv } from "../../../../lib/csvFetcher";
|
import { fetchAndParseCsv } from "../../../../lib/csvFetcher";
|
||||||
import { processQueuedImports } from "../../../../lib/importProcessor";
|
import { processQueuedImports } from "../../../../lib/importProcessor";
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
@ -37,21 +37,11 @@ export async function POST(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const company = await prisma.company.findUnique({
|
const company = await prisma.company.findUnique({ where: { id: companyId } });
|
||||||
where: { id: companyId },
|
|
||||||
});
|
|
||||||
if (!company) {
|
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(
|
return NextResponse.json(
|
||||||
{
|
{ error: "Company not found" },
|
||||||
error: `Data processing is disabled for ${company.status.toLowerCase()} companies`,
|
{ status: 404 }
|
||||||
companyStatus: company.status,
|
|
||||||
},
|
|
||||||
{ status: 403 }
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -124,12 +114,12 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Immediately process the queued imports to create Session records
|
// Immediately process the queued imports to create Session records
|
||||||
console.log("[Refresh API] Processing queued imports...");
|
console.log('[Refresh API] Processing queued imports...');
|
||||||
await processQueuedImports(100); // Process up to 100 imports immediately
|
await processQueuedImports(100); // Process up to 100 imports immediately
|
||||||
|
|
||||||
// Count how many sessions were created
|
// Count how many sessions were created
|
||||||
const sessionCount = await prisma.session.count({
|
const sessionCount = await prisma.session.count({
|
||||||
where: { companyId: company.id },
|
where: { companyId: company.id }
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
@ -137,7 +127,7 @@ export async function POST(request: NextRequest) {
|
|||||||
imported: importedCount,
|
imported: importedCount,
|
||||||
total: rawSessionData.length,
|
total: rawSessionData.length,
|
||||||
sessions: sessionCount,
|
sessions: sessionCount,
|
||||||
message: `Successfully imported ${importedCount} records and processed them into sessions. Total sessions: ${sessionCount}`,
|
message: `Successfully imported ${importedCount} records and processed them into sessions. Total sessions: ${sessionCount}`
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const error = e instanceof Error ? e.message : "An unknown error occurred";
|
const error = e instanceof Error ? e.message : "An unknown error occurred";
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
import { ProcessingStage } from "@prisma/client";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
import { processUnprocessedSessions } from "../../../../lib/processingScheduler";
|
import { processUnprocessedSessions } from "../../../../lib/processingScheduler";
|
||||||
import { ProcessingStatusManager } from "../../../../lib/processingStatusManager";
|
import { ProcessingStatusManager } from "../../../../lib/processingStatusManager";
|
||||||
|
import { ProcessingStage } from "@prisma/client";
|
||||||
|
|
||||||
interface SessionUser {
|
interface SessionUser {
|
||||||
email: string;
|
email: string;
|
||||||
@ -24,19 +24,7 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
const user = await prisma.user.findUnique({
|
||||||
where: { email: session.user.email },
|
where: { email: session.user.email },
|
||||||
select: {
|
include: { company: true },
|
||||||
id: true,
|
|
||||||
email: true,
|
|
||||||
role: true,
|
|
||||||
companyId: true,
|
|
||||||
company: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
status: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
@ -57,23 +45,18 @@ export async function POST(request: NextRequest) {
|
|||||||
const { batchSize, maxConcurrency } = body;
|
const { batchSize, maxConcurrency } = body;
|
||||||
|
|
||||||
// Validate parameters
|
// Validate parameters
|
||||||
const validatedBatchSize =
|
const validatedBatchSize = batchSize && batchSize > 0 ? parseInt(batchSize) : null;
|
||||||
batchSize && batchSize > 0 ? Number.parseInt(batchSize) : null;
|
const validatedMaxConcurrency = maxConcurrency && maxConcurrency > 0 ? parseInt(maxConcurrency) : 5;
|
||||||
const validatedMaxConcurrency =
|
|
||||||
maxConcurrency && maxConcurrency > 0
|
|
||||||
? Number.parseInt(maxConcurrency)
|
|
||||||
: 5;
|
|
||||||
|
|
||||||
// Check how many sessions need AI processing using the new status system
|
// Check how many sessions need AI processing using the new status system
|
||||||
const sessionsNeedingAI =
|
const sessionsNeedingAI = await ProcessingStatusManager.getSessionsNeedingProcessing(
|
||||||
await ProcessingStatusManager.getSessionsNeedingProcessing(
|
|
||||||
ProcessingStage.AI_ANALYSIS,
|
ProcessingStage.AI_ANALYSIS,
|
||||||
1000 // Get count only
|
1000 // Get count only
|
||||||
);
|
);
|
||||||
|
|
||||||
// Filter to sessions for this company
|
// Filter to sessions for this company
|
||||||
const companySessionsNeedingAI = sessionsNeedingAI.filter(
|
const companySessionsNeedingAI = sessionsNeedingAI.filter(
|
||||||
(statusRecord) => statusRecord.session.companyId === user.companyId
|
statusRecord => statusRecord.session.companyId === user.companyId
|
||||||
);
|
);
|
||||||
|
|
||||||
const unprocessedCount = companySessionsNeedingAI.length;
|
const unprocessedCount = companySessionsNeedingAI.length;
|
||||||
@ -88,21 +71,16 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Start processing (this will run asynchronously)
|
// Start processing (this will run asynchronously)
|
||||||
const _startTime = Date.now();
|
const startTime = Date.now();
|
||||||
|
|
||||||
// Note: We're calling the function but not awaiting it to avoid timeout
|
// Note: We're calling the function but not awaiting it to avoid timeout
|
||||||
// The processing will continue in the background
|
// The processing will continue in the background
|
||||||
processUnprocessedSessions(validatedBatchSize, validatedMaxConcurrency)
|
processUnprocessedSessions(validatedBatchSize, validatedMaxConcurrency)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
console.log(
|
console.log(`[Manual Trigger] Processing completed for company ${user.companyId}`);
|
||||||
`[Manual Trigger] Processing completed for company ${user.companyId}`
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error(
|
console.error(`[Manual Trigger] Processing failed for company ${user.companyId}:`, error);
|
||||||
`[Manual Trigger] Processing failed for company ${user.companyId}:`,
|
|
||||||
error
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
@ -113,6 +91,7 @@ export async function POST(request: NextRequest) {
|
|||||||
maxConcurrency: validatedMaxConcurrency,
|
maxConcurrency: validatedMaxConcurrency,
|
||||||
startedAt: new Date().toISOString(),
|
startedAt: new Date().toISOString(),
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[Manual Trigger] Error:", error);
|
console.error("[Manual Trigger] Error:", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@ -1,5 +1,105 @@
|
|||||||
import NextAuth from "next-auth";
|
import NextAuth, { NextAuthOptions } from "next-auth";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
import CredentialsProvider from "next-auth/providers/credentials";
|
||||||
|
import { prisma } from "../../../../lib/prisma";
|
||||||
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
|
// Define the shape of the JWT token
|
||||||
|
declare module "next-auth/jwt" {
|
||||||
|
interface JWT {
|
||||||
|
companyId: string;
|
||||||
|
role: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define the shape of the session object
|
||||||
|
declare module "next-auth" {
|
||||||
|
interface Session {
|
||||||
|
user: {
|
||||||
|
id?: string;
|
||||||
|
name?: string;
|
||||||
|
email?: string;
|
||||||
|
image?: string;
|
||||||
|
companyId: string;
|
||||||
|
role: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
companyId: string;
|
||||||
|
role: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authOptions: NextAuthOptions = {
|
||||||
|
providers: [
|
||||||
|
CredentialsProvider({
|
||||||
|
name: "Credentials",
|
||||||
|
credentials: {
|
||||||
|
email: { label: "Email", type: "text" },
|
||||||
|
password: { label: "Password", type: "password" },
|
||||||
|
},
|
||||||
|
async authorize(credentials) {
|
||||||
|
if (!credentials?.email || !credentials?.password) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { email: credentials.email },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const valid = await bcrypt.compare(credentials.password, user.password);
|
||||||
|
if (!valid) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
companyId: user.companyId,
|
||||||
|
role: user.role,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
session: {
|
||||||
|
strategy: "jwt",
|
||||||
|
maxAge: 30 * 24 * 60 * 60, // 30 days
|
||||||
|
},
|
||||||
|
cookies: {
|
||||||
|
sessionToken: {
|
||||||
|
name: `next-auth.session-token`,
|
||||||
|
options: {
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
callbacks: {
|
||||||
|
async jwt({ token, user }) {
|
||||||
|
if (user) {
|
||||||
|
token.companyId = user.companyId;
|
||||||
|
token.role = user.role;
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
|
async session({ session, token }) {
|
||||||
|
if (token && session.user) {
|
||||||
|
session.user.companyId = token.companyId;
|
||||||
|
session.user.role = token.role;
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pages: {
|
||||||
|
signIn: "/login",
|
||||||
|
},
|
||||||
|
secret: process.env.NEXTAUTH_SECRET,
|
||||||
|
debug: process.env.NODE_ENV === "development",
|
||||||
|
};
|
||||||
|
|
||||||
const handler = NextAuth(authOptions);
|
const handler = NextAuth(authOptions);
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
|
|
||||||
export async function GET(_request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
if (!session?.user) {
|
if (!session?.user) {
|
||||||
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
|
return NextResponse.json({ error: "Not logged in" }, { status: 401 });
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
|
||||||
import { sessionMetrics } from "../../../../lib/metrics";
|
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
import type { ChatSession } from "../../../../lib/types";
|
import { sessionMetrics } from "../../../../lib/metrics";
|
||||||
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
|
import { ChatSession } from "../../../../lib/types";
|
||||||
|
|
||||||
interface SessionUser {
|
interface SessionUser {
|
||||||
email: string;
|
email: string;
|
||||||
@ -22,18 +22,7 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
const user = await prisma.user.findUnique({
|
const user = await prisma.user.findUnique({
|
||||||
where: { email: session.user.email },
|
where: { email: session.user.email },
|
||||||
select: {
|
include: { company: true },
|
||||||
id: true,
|
|
||||||
companyId: true,
|
|
||||||
company: {
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
csvUrl: true,
|
|
||||||
status: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
@ -46,127 +35,100 @@ export async function GET(request: NextRequest) {
|
|||||||
const endDate = searchParams.get("endDate");
|
const endDate = searchParams.get("endDate");
|
||||||
|
|
||||||
// Build where clause with optional date filtering
|
// Build where clause with optional date filtering
|
||||||
const whereClause: {
|
const whereClause: any = {
|
||||||
companyId: string;
|
|
||||||
startTime?: {
|
|
||||||
gte: Date;
|
|
||||||
lte: Date;
|
|
||||||
};
|
|
||||||
} = {
|
|
||||||
companyId: user.companyId,
|
companyId: user.companyId,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (startDate && endDate) {
|
if (startDate && endDate) {
|
||||||
whereClause.startTime = {
|
whereClause.startTime = {
|
||||||
gte: new Date(startDate),
|
gte: new Date(startDate),
|
||||||
lte: new Date(`${endDate}T23:59:59.999Z`), // Include full end date
|
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({
|
const prismaSessions = await prisma.session.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
select: {
|
include: {
|
||||||
id: true,
|
messages: true, // Include messages for question extraction
|
||||||
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
|
// Convert Prisma sessions to ChatSession[] type for sessionMetrics
|
||||||
const chatSessions: ChatSession[] = prismaSessions.map((ps) => {
|
const chatSessions: ChatSession[] = prismaSessions.map((ps) => ({
|
||||||
// Get questions for this session or empty array
|
id: ps.id, // Map Prisma's id to ChatSession.id
|
||||||
const questions = questionsBySession[ps.id] || [];
|
sessionId: ps.id, // Map Prisma's id to ChatSession.sessionId
|
||||||
|
|
||||||
// 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,
|
companyId: ps.companyId,
|
||||||
startTime: new Date(ps.startTime),
|
startTime: new Date(ps.startTime), // Ensure startTime is a Date object
|
||||||
endTime: ps.endTime ? new Date(ps.endTime) : null,
|
endTime: ps.endTime ? new Date(ps.endTime) : null, // Ensure endTime is a Date object or null
|
||||||
transcriptContent: "",
|
transcriptContent: "", // Session model doesn't have transcriptContent field
|
||||||
createdAt: new Date(ps.createdAt),
|
createdAt: new Date(ps.createdAt), // Map Prisma's createdAt
|
||||||
updatedAt: new Date(ps.createdAt),
|
updatedAt: new Date(ps.createdAt), // Use createdAt for updatedAt as Session model doesn't have updatedAt
|
||||||
category: ps.category || undefined,
|
category: ps.category || undefined,
|
||||||
language: ps.language || undefined,
|
language: ps.language || undefined,
|
||||||
country: ps.country || undefined,
|
country: ps.country || undefined,
|
||||||
ipAddress: ps.ipAddress || undefined,
|
ipAddress: ps.ipAddress || undefined,
|
||||||
sentiment: ps.sentiment === null ? undefined : ps.sentiment,
|
sentiment: ps.sentiment === null ? undefined : ps.sentiment,
|
||||||
messagesSent: ps.messagesSent === null ? undefined : ps.messagesSent,
|
messagesSent: ps.messagesSent === null ? undefined : ps.messagesSent, // Handle null messagesSent
|
||||||
avgResponseTime:
|
avgResponseTime:
|
||||||
ps.avgResponseTime === null ? undefined : ps.avgResponseTime,
|
ps.avgResponseTime === null ? undefined : ps.avgResponseTime,
|
||||||
escalated: ps.escalated || false,
|
escalated: ps.escalated || false,
|
||||||
forwardedHr: ps.forwardedHr || false,
|
forwardedHr: ps.forwardedHr || false,
|
||||||
initialMsg: ps.initialMsg || undefined,
|
initialMsg: ps.initialMsg || undefined,
|
||||||
fullTranscriptUrl: ps.fullTranscriptUrl || undefined,
|
fullTranscriptUrl: ps.fullTranscriptUrl || undefined,
|
||||||
summary: ps.summary || undefined,
|
summary: ps.summary || undefined, // Include summary field
|
||||||
messages: mockMessages, // Use questions as messages for metrics
|
messages: ps.messages || [], // Include messages for question extraction
|
||||||
userId: undefined,
|
// userId is missing in Prisma Session model, assuming it's not strictly needed for metrics or can be null
|
||||||
};
|
userId: undefined, // Or some other default/mapping if available
|
||||||
});
|
}));
|
||||||
|
|
||||||
// Pass company config to metrics
|
// Pass company config to metrics
|
||||||
const companyConfigForMetrics = {
|
const companyConfigForMetrics = {
|
||||||
// Add company-specific configuration here in the future
|
sentimentAlert:
|
||||||
|
user.company.sentimentAlert === null
|
||||||
|
? undefined
|
||||||
|
: user.company.sentimentAlert,
|
||||||
};
|
};
|
||||||
|
|
||||||
const metrics = sessionMetrics(chatSessions, companyConfigForMetrics);
|
const metrics = sessionMetrics(chatSessions, companyConfigForMetrics);
|
||||||
|
|
||||||
// Calculate date range from sessions
|
// Calculate date range from the FILTERED sessions to match what's actually displayed
|
||||||
let dateRange: { minDate: string; maxDate: string } | null = null;
|
let dateRange: { minDate: string; maxDate: string } | null = null;
|
||||||
if (prismaSessions.length > 0) {
|
let availableDataRange: { minDate: string; maxDate: string } | null = null;
|
||||||
const dates = prismaSessions
|
|
||||||
.map((s) => new Date(s.startTime))
|
// Get the full available range for reference
|
||||||
.sort((a, b) => a.getTime() - b.getTime());
|
const allSessions = await prisma.session.findMany({
|
||||||
dateRange = {
|
where: {
|
||||||
minDate: dates[0].toISOString().split("T")[0], // First session date
|
companyId: user.companyId,
|
||||||
maxDate: dates[dates.length - 1].toISOString().split("T")[0], // Last session date
|
},
|
||||||
|
select: {
|
||||||
|
startTime: true,
|
||||||
|
},
|
||||||
|
orderBy: {
|
||||||
|
startTime: 'asc',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (allSessions.length > 0) {
|
||||||
|
availableDataRange = {
|
||||||
|
minDate: allSessions[0].startTime.toISOString().split('T')[0], // First session date
|
||||||
|
maxDate: allSessions[allSessions.length - 1].startTime.toISOString().split('T')[0] // Last session date
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calculate date range from the filtered sessions (what's actually being displayed)
|
||||||
|
if (prismaSessions.length > 0) {
|
||||||
|
const sortedFilteredSessions = prismaSessions.sort((a, b) =>
|
||||||
|
new Date(a.startTime).getTime() - new Date(b.startTime).getTime()
|
||||||
|
);
|
||||||
|
dateRange = {
|
||||||
|
minDate: sortedFilteredSessions[0].startTime.toISOString().split('T')[0],
|
||||||
|
maxDate: sortedFilteredSessions[sortedFilteredSessions.length - 1].startTime.toISOString().split('T')[0]
|
||||||
|
};
|
||||||
|
} else if (availableDataRange) {
|
||||||
|
// If no filtered sessions but we have available data, use the available range
|
||||||
|
dateRange = availableDataRange;
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
metrics,
|
metrics,
|
||||||
csvUrl: user.company.csvUrl,
|
csvUrl: user.company.csvUrl,
|
||||||
|
|||||||
@ -1,9 +1,10 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getServerSession } from "next-auth/next";
|
import { getServerSession } from "next-auth/next";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
|
import { SessionFilterOptions } from "../../../../lib/types";
|
||||||
|
|
||||||
export async function GET(_request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const authSession = await getServerSession(authOptions);
|
const authSession = await getServerSession(authOptions);
|
||||||
|
|
||||||
if (!authSession || !authSession.user?.companyId) {
|
if (!authSession || !authSession.user?.companyId) {
|
||||||
@ -13,41 +14,48 @@ export async function GET(_request: NextRequest) {
|
|||||||
const companyId = authSession.user.companyId;
|
const companyId = authSession.user.companyId;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Use groupBy for better performance with distinct values
|
const categories = await prisma.session.findMany({
|
||||||
const [categoryGroups, languageGroups] = await Promise.all([
|
|
||||||
prisma.session.groupBy({
|
|
||||||
by: ["category"],
|
|
||||||
where: {
|
where: {
|
||||||
companyId,
|
companyId,
|
||||||
category: { not: null },
|
category: {
|
||||||
|
not: null, // Ensure category is not null
|
||||||
|
},
|
||||||
|
},
|
||||||
|
distinct: ["category"],
|
||||||
|
select: {
|
||||||
|
category: true,
|
||||||
},
|
},
|
||||||
orderBy: {
|
orderBy: {
|
||||||
category: "asc",
|
category: "asc",
|
||||||
},
|
},
|
||||||
}),
|
});
|
||||||
prisma.session.groupBy({
|
|
||||||
by: ["language"],
|
const languages = await prisma.session.findMany({
|
||||||
where: {
|
where: {
|
||||||
companyId,
|
companyId,
|
||||||
language: { not: null },
|
language: {
|
||||||
|
not: null, // Ensure language is not null
|
||||||
|
},
|
||||||
|
},
|
||||||
|
distinct: ["language"],
|
||||||
|
select: {
|
||||||
|
language: true,
|
||||||
},
|
},
|
||||||
orderBy: {
|
orderBy: {
|
||||||
language: "asc",
|
language: "asc",
|
||||||
},
|
},
|
||||||
}),
|
});
|
||||||
]);
|
|
||||||
|
|
||||||
const distinctCategories = categoryGroups
|
const distinctCategories = categories
|
||||||
.map((g) => g.category)
|
.map((s) => s.category)
|
||||||
.filter(Boolean) as string[];
|
.filter(Boolean) as string[]; // Filter out any nulls and assert as string[]
|
||||||
|
const distinctLanguages = languages
|
||||||
const distinctLanguages = languageGroups
|
.map((s) => s.language)
|
||||||
.map((g) => g.language)
|
.filter(Boolean) as string[]; // Filter out any nulls and assert as string[]
|
||||||
.filter(Boolean) as string[];
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
categories: distinctCategories,
|
categories: distinctCategories,
|
||||||
languages: distinctLanguages,
|
languages: distinctLanguages
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "../../../../../lib/prisma";
|
import { prisma } from "../../../../../lib/prisma";
|
||||||
import type { ChatSession } from "../../../../../lib/types";
|
import { ChatSession } from "../../../../../lib/types";
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
_request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
{ params }: { params: { id: string } }
|
||||||
) {
|
) {
|
||||||
const { id } = await params;
|
const { id } = params;
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@ -26,7 +26,10 @@ export async function GET(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!prismaSession) {
|
if (!prismaSession) {
|
||||||
return NextResponse.json({ error: "Session not found" }, { status: 404 });
|
return NextResponse.json(
|
||||||
|
{ error: "Session not found" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Map Prisma session object to ChatSession type
|
// Map Prisma session object to ChatSession type
|
||||||
|
|||||||
@ -1,9 +1,13 @@
|
|||||||
import type { Prisma } from "@prisma/client";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { getServerSession } from "next-auth/next";
|
import { getServerSession } from "next-auth/next";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
import type { ChatSession } from "../../../../lib/types";
|
import {
|
||||||
|
ChatSession,
|
||||||
|
SessionApiResponse,
|
||||||
|
SessionQuery,
|
||||||
|
} from "../../../../lib/types";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const authSession = await getServerSession(authOptions);
|
const authSession = await getServerSession(authOptions);
|
||||||
@ -44,7 +48,7 @@ export async function GET(request: NextRequest) {
|
|||||||
// Category Filter
|
// Category Filter
|
||||||
if (category && category.trim() !== "") {
|
if (category && category.trim() !== "") {
|
||||||
// Cast to SessionCategory enum if it's a valid value
|
// Cast to SessionCategory enum if it's a valid value
|
||||||
whereClause.category = category;
|
whereClause.category = category as any;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Language Filter
|
// Language Filter
|
||||||
@ -83,7 +87,9 @@ export async function GET(request: NextRequest) {
|
|||||||
| Prisma.SessionOrderByWithRelationInput[];
|
| Prisma.SessionOrderByWithRelationInput[];
|
||||||
|
|
||||||
const primarySortField =
|
const primarySortField =
|
||||||
sortKey && validSortKeys[sortKey] ? validSortKeys[sortKey] : "startTime"; // Default to startTime field if sortKey is invalid/missing
|
sortKey && validSortKeys[sortKey]
|
||||||
|
? validSortKeys[sortKey]
|
||||||
|
: "startTime"; // Default to startTime field if sortKey is invalid/missing
|
||||||
|
|
||||||
const primarySortOrder =
|
const primarySortOrder =
|
||||||
sortOrder === "asc" || sortOrder === "desc" ? sortOrder : "desc"; // Default to desc order
|
sortOrder === "asc" || sortOrder === "desc" ? sortOrder : "desc"; // Default to desc order
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
@ -18,7 +18,7 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { csvUrl, csvUsername, csvPassword } = body;
|
const { csvUrl, csvUsername, csvPassword, sentimentThreshold } = body;
|
||||||
|
|
||||||
await prisma.company.update({
|
await prisma.company.update({
|
||||||
where: { id: user.companyId },
|
where: { id: user.companyId },
|
||||||
@ -26,7 +26,9 @@ export async function POST(request: NextRequest) {
|
|||||||
csvUrl,
|
csvUrl,
|
||||||
csvUsername,
|
csvUsername,
|
||||||
...(csvPassword ? { csvPassword } : {}),
|
...(csvPassword ? { csvPassword } : {}),
|
||||||
// Remove sentimentAlert field - not in current schema
|
sentimentAlert: sentimentThreshold
|
||||||
|
? parseFloat(sentimentThreshold)
|
||||||
|
: null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
import crypto from "node:crypto";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import bcrypt from "bcryptjs";
|
import crypto from "crypto";
|
||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { authOptions } from "../../../../lib/auth";
|
|
||||||
import { prisma } from "../../../../lib/prisma";
|
import { prisma } from "../../../../lib/prisma";
|
||||||
|
import bcrypt from "bcryptjs";
|
||||||
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||||
|
|
||||||
interface UserBasicInfo {
|
interface UserBasicInfo {
|
||||||
id: string;
|
id: string;
|
||||||
@ -11,7 +11,7 @@ interface UserBasicInfo {
|
|||||||
role: string;
|
role: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET(_request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
if (!session?.user || session.user.role !== "ADMIN") {
|
if (!session?.user || session.user.role !== "ADMIN") {
|
||||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
|
|||||||
@ -1,94 +1,28 @@
|
|||||||
import crypto from "node:crypto";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { prisma } from "../../../lib/prisma";
|
import { prisma } from "../../../lib/prisma";
|
||||||
import { sendEmail } from "../../../lib/sendEmail";
|
import { sendEmail } from "../../../lib/sendEmail";
|
||||||
import { forgotPasswordSchema, validateInput } from "../../../lib/validation";
|
import crypto from "crypto";
|
||||||
|
|
||||||
// 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) {
|
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();
|
const body = await request.json();
|
||||||
|
const { email } = body as { email: string };
|
||||||
// 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 } });
|
const user = await prisma.user.findUnique({ where: { email } });
|
||||||
|
if (!user) {
|
||||||
|
// Always return 200 for privacy (don't reveal if email exists)
|
||||||
|
return NextResponse.json({ success: true }, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
// 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 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
|
const expiry = new Date(Date.now() + 1000 * 60 * 30); // 30 min expiry
|
||||||
|
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
where: { email },
|
where: { email },
|
||||||
data: { resetToken: tokenHash, resetTokenExpiry: expiry },
|
data: { resetToken: token, resetTokenExpiry: expiry },
|
||||||
});
|
});
|
||||||
|
|
||||||
const resetUrl = `${process.env.NEXTAUTH_URL || "http://localhost:3000"}/reset-password?token=${token}`;
|
const resetUrl = `${process.env.NEXTAUTH_URL || "http://localhost:3000"}/reset-password?token=${token}`;
|
||||||
await sendEmail(
|
await sendEmail(email, "Password Reset", `Reset your password: ${resetUrl}`);
|
||||||
email,
|
|
||||||
"Password Reset",
|
|
||||||
`Reset your password: ${resetUrl}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({ success: true }, { status: 200 });
|
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 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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 };
|
|
||||||
@ -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 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -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 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,70 +1,34 @@
|
|||||||
import bcrypt from "bcryptjs";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { prisma } from "../../../lib/prisma";
|
import { prisma } from "../../../lib/prisma";
|
||||||
import { registerSchema, validateInput } from "../../../lib/validation";
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
// In-memory rate limiting (for production, use Redis or similar)
|
interface RegisterRequestBody {
|
||||||
const registrationAttempts = new Map<
|
email: string;
|
||||||
string,
|
password: string;
|
||||||
{ count: number; resetTime: number }
|
company: string;
|
||||||
>();
|
csvUrl?: string;
|
||||||
|
|
||||||
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) {
|
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();
|
const body = await request.json();
|
||||||
|
const { email, password, company, csvUrl } = body as RegisterRequestBody;
|
||||||
|
|
||||||
// Validate input with Zod schema
|
if (!email || !password || !company) {
|
||||||
const validation = validateInput(registerSchema, body);
|
|
||||||
if (!validation.success) {
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
success: false,
|
success: false,
|
||||||
error: "Validation failed",
|
error: "Missing required fields",
|
||||||
details: validation.errors,
|
|
||||||
},
|
},
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { email, password, company } = validation.data;
|
|
||||||
|
|
||||||
// Check if email exists
|
// Check if email exists
|
||||||
const existingUser = await prisma.user.findUnique({
|
const exists = await prisma.user.findUnique({
|
||||||
where: { email },
|
where: { email },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingUser) {
|
if (exists) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
success: false,
|
success: false,
|
||||||
@ -74,63 +38,26 @@ export async function POST(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if company name already exists
|
const newCompany = await prisma.company.create({
|
||||||
const existingCompany = await prisma.company.findFirst({
|
data: { name: company, csvUrl: csvUrl || "" },
|
||||||
where: { name: company },
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingCompany) {
|
const hashed = await bcrypt.hash(password, 10);
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: "Company name already exists",
|
|
||||||
},
|
|
||||||
{ status: 409 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create company and user in a transaction
|
await prisma.user.create({
|
||||||
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: {
|
data: {
|
||||||
email,
|
email,
|
||||||
password: hashedPassword,
|
password: hashed,
|
||||||
companyId: newCompany.id,
|
companyId: newCompany.id,
|
||||||
role: "USER", // Changed from ADMIN - users should be promoted by existing admins
|
role: "ADMIN",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return { company: newCompany, user: newUser };
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: { success: true },
|
||||||
message: "Registration successful",
|
|
||||||
userId: result.user.id,
|
|
||||||
companyId: result.company.id,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{ status: 201 }
|
{ status: 201 }
|
||||||
);
|
);
|
||||||
} catch (error) {
|
|
||||||
console.error("Registration error:", error);
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: "Internal server error",
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,34 +1,29 @@
|
|||||||
import crypto from "node:crypto";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import bcrypt from "bcryptjs";
|
|
||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { prisma } from "../../../lib/prisma";
|
import { prisma } from "../../../lib/prisma";
|
||||||
import { resetPasswordSchema, validateInput } from "../../../lib/validation";
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
const { token, password } = body as { token?: string; password?: string };
|
||||||
|
|
||||||
// Validate input with strong password requirements
|
if (!token || !password) {
|
||||||
const validation = validateInput(resetPasswordSchema, body);
|
|
||||||
if (!validation.success) {
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{ error: "Token and password are required." },
|
||||||
success: false,
|
|
||||||
error: "Validation failed",
|
|
||||||
details: validation.errors,
|
|
||||||
},
|
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { token, password } = validation.data;
|
if (password.length < 8) {
|
||||||
|
return NextResponse.json(
|
||||||
// Hash the token to compare with stored hash
|
{ error: "Password must be at least 8 characters long." },
|
||||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
const user = await prisma.user.findFirst({
|
const user = await prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
resetToken: tokenHash,
|
resetToken: token,
|
||||||
resetTokenExpiry: { gte: new Date() },
|
resetTokenExpiry: { gte: new Date() },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@ -36,38 +31,30 @@ export async function POST(request: NextRequest) {
|
|||||||
if (!user) {
|
if (!user) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
success: false,
|
error: "Invalid or expired token. Please request a new password reset.",
|
||||||
error:
|
|
||||||
"Invalid or expired token. Please request a new password reset.",
|
|
||||||
},
|
},
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hash password with higher rounds for better security
|
const hash = await bcrypt.hash(password, 10);
|
||||||
const hashedPassword = await bcrypt.hash(password, 12);
|
|
||||||
|
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
where: { id: user.id },
|
where: { id: user.id },
|
||||||
data: {
|
data: {
|
||||||
password: hashedPassword,
|
password: hash,
|
||||||
resetToken: null,
|
resetToken: null,
|
||||||
resetTokenExpiry: null,
|
resetTokenExpiry: null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{ message: "Password has been reset successfully." },
|
||||||
success: true,
|
|
||||||
message: "Password has been reset successfully.",
|
|
||||||
},
|
|
||||||
{ status: 200 }
|
{ status: 200 }
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Reset password error:", error);
|
console.error("Reset password error:", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
success: false,
|
|
||||||
error: "An internal server error occurred. Please try again later.",
|
error: "An internal server error occurred. Please try again later.",
|
||||||
},
|
},
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
|
|||||||
@ -1,26 +1,18 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Database, Save, Settings, ShieldX } from "lucide-react";
|
import { useState, useEffect } from "react";
|
||||||
import { useSession } from "next-auth/react";
|
import { useSession } from "next-auth/react";
|
||||||
import { useEffect, useId, useState } from "react";
|
import { Company } from "../../../lib/types";
|
||||||
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";
|
|
||||||
|
|
||||||
export default function CompanySettingsPage() {
|
export default function CompanySettingsPage() {
|
||||||
const csvUrlId = useId();
|
|
||||||
const csvUsernameId = useId();
|
|
||||||
const csvPasswordId = useId();
|
|
||||||
const { data: session, status } = useSession();
|
const { data: session, status } = useSession();
|
||||||
// We store the full company object for future use and updates after save operations
|
// 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
|
// 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 [csvUrl, setCsvUrl] = useState<string>("");
|
||||||
const [csvUsername, setCsvUsername] = useState<string>("");
|
const [csvUsername, setCsvUsername] = useState<string>("");
|
||||||
const [csvPassword, setCsvPassword] = useState<string>("");
|
const [csvPassword, setCsvPassword] = useState<string>("");
|
||||||
|
const [sentimentThreshold, setSentimentThreshold] = useState<string>("");
|
||||||
const [message, setMessage] = useState<string>("");
|
const [message, setMessage] = useState<string>("");
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
@ -34,6 +26,7 @@ export default function CompanySettingsPage() {
|
|||||||
setCompany(data.company);
|
setCompany(data.company);
|
||||||
setCsvUrl(data.company.csvUrl || "");
|
setCsvUrl(data.company.csvUrl || "");
|
||||||
setCsvUsername(data.company.csvUsername || "");
|
setCsvUsername(data.company.csvUsername || "");
|
||||||
|
setSentimentThreshold(data.company.sentimentAlert?.toString() || "");
|
||||||
if (data.company.csvPassword) {
|
if (data.company.csvPassword) {
|
||||||
setCsvPassword(data.company.csvPassword);
|
setCsvPassword(data.company.csvPassword);
|
||||||
}
|
}
|
||||||
@ -58,6 +51,7 @@ export default function CompanySettingsPage() {
|
|||||||
csvUrl,
|
csvUrl,
|
||||||
csvUsername,
|
csvUsername,
|
||||||
csvPassword,
|
csvPassword,
|
||||||
|
sentimentThreshold,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -80,89 +74,49 @@ export default function CompanySettingsPage() {
|
|||||||
|
|
||||||
// Loading state
|
// Loading state
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return <div className="text-center py-10">Loading settings...</div>;
|
||||||
<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>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for ADMIN access
|
// Check for ADMIN access
|
||||||
if (session?.user?.role !== "ADMIN") {
|
if (session?.user?.role !== "ADMIN") {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="text-center py-10 bg-white rounded-xl shadow p-6">
|
||||||
<Card>
|
<h2 className="font-bold text-xl text-red-600 mb-2">Access Denied</h2>
|
||||||
<CardHeader>
|
<p>You don't have permission to view company settings.</p>
|
||||||
<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't have permission to view company settings.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<Card>
|
<div className="bg-white p-6 rounded-xl shadow">
|
||||||
<CardHeader>
|
<h1 className="text-2xl font-bold text-gray-800 mb-6">
|
||||||
<div className="flex items-center gap-3">
|
Company Settings
|
||||||
<Settings className="h-6 w-6" />
|
</h1>
|
||||||
<CardTitle>Company Settings</CardTitle>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-6">
|
|
||||||
{message && (
|
{message && (
|
||||||
<Alert
|
<div
|
||||||
variant={message.includes("Failed") ? "destructive" : "default"}
|
className={`p-4 rounded mb-6 ${message.includes("Failed") ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"}`}
|
||||||
>
|
>
|
||||||
<AlertDescription>{message}</AlertDescription>
|
{message}
|
||||||
</Alert>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<form
|
<form
|
||||||
className="space-y-6"
|
className="grid gap-6"
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
handleSave();
|
handleSave();
|
||||||
}}
|
}}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
>
|
>
|
||||||
<Card>
|
<div className="grid gap-2">
|
||||||
<CardHeader>
|
<label className="font-medium text-gray-700">
|
||||||
<div className="flex items-center gap-2">
|
CSV Data Source URL
|
||||||
<Database className="h-5 w-5" />
|
</label>
|
||||||
<CardTitle className="text-lg">
|
<input
|
||||||
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"
|
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}
|
value={csvUrl}
|
||||||
onChange={(e) => setCsvUrl(e.target.value)}
|
onChange={(e) => setCsvUrl(e.target.value)}
|
||||||
placeholder="https://example.com/data.csv"
|
placeholder="https://example.com/data.csv"
|
||||||
@ -170,11 +124,11 @@ export default function CompanySettingsPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor={csvUsernameId}>CSV Username</Label>
|
<label className="font-medium text-gray-700">CSV Username</label>
|
||||||
<Input
|
<input
|
||||||
id={csvUsernameId}
|
|
||||||
type="text"
|
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}
|
value={csvUsername}
|
||||||
onChange={(e) => setCsvUsername(e.target.value)}
|
onChange={(e) => setCsvUsername(e.target.value)}
|
||||||
placeholder="Username for CSV access (if needed)"
|
placeholder="Username for CSV access (if needed)"
|
||||||
@ -182,32 +136,48 @@ export default function CompanySettingsPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor={csvPasswordId}>CSV Password</Label>
|
<label className="font-medium text-gray-700">CSV Password</label>
|
||||||
<Input
|
<input
|
||||||
id={csvPasswordId}
|
|
||||||
type="password"
|
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}
|
value={csvPassword}
|
||||||
onChange={(e) => setCsvPassword(e.target.value)}
|
onChange={(e) => setCsvPassword(e.target.value)}
|
||||||
placeholder="Password will be updated only if provided"
|
placeholder="Password will be updated only if provided"
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
/>
|
/>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-gray-500">
|
||||||
Leave blank to keep current password
|
Leave blank to keep current password
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
<div className="grid gap-2">
|
||||||
<Button type="submit" className="gap-2">
|
<label className="font-medium text-gray-700">
|
||||||
<Save className="h-4 w-4" />
|
Sentiment Alert Threshold
|
||||||
Save Settings
|
</label>
|
||||||
</Button>
|
<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>
|
</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>
|
</form>
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,12 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { ReactNode, useState, useEffect, useCallback } from "react";
|
||||||
import { useSession } from "next-auth/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";
|
import Sidebar from "../../components/Sidebar";
|
||||||
|
|
||||||
export default function DashboardLayout({ children }: { children: ReactNode }) {
|
export default function DashboardLayout({ children }: { children: ReactNode }) {
|
||||||
const mainContentId = useId();
|
|
||||||
const { status } = useSession();
|
const { status } = useSession();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
@ -58,7 +57,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen bg-background">
|
<div className="flex h-screen bg-gray-100">
|
||||||
<Sidebar
|
<Sidebar
|
||||||
isExpanded={isSidebarExpanded}
|
isExpanded={isSidebarExpanded}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
@ -66,8 +65,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
|
|||||||
onNavigate={collapseSidebar}
|
onNavigate={collapseSidebar}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<main
|
<div
|
||||||
id={mainContentId}
|
|
||||||
className={`flex-1 overflow-auto transition-all duration-300 py-4 pr-4
|
className={`flex-1 overflow-auto transition-all duration-300 py-4 pr-4
|
||||||
${
|
${
|
||||||
isSidebarExpanded
|
isSidebarExpanded
|
||||||
@ -78,7 +76,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
|
|||||||
>
|
>
|
||||||
{/* <div className="w-full mx-auto">{children}</div> */}
|
{/* <div className="w-full mx-auto">{children}</div> */}
|
||||||
<div className="max-w-7xl mx-auto">{children}</div>
|
<div className="max-w-7xl mx-auto">{children}</div>
|
||||||
</main>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,42 +1,44 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import { useEffect, useState, useCallback, useRef } from "react";
|
||||||
CheckCircle,
|
|
||||||
Clock,
|
|
||||||
Euro,
|
|
||||||
Globe,
|
|
||||||
LogOut,
|
|
||||||
MessageCircle,
|
|
||||||
MessageSquare,
|
|
||||||
MoreVertical,
|
|
||||||
RefreshCw,
|
|
||||||
TrendingUp,
|
|
||||||
Users,
|
|
||||||
Zap,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { signOut, useSession } from "next-auth/react";
|
import { signOut, useSession } from "next-auth/react";
|
||||||
import { useCallback, useEffect, useId, useState } from "react";
|
import { useRouter } from "next/navigation";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Company, MetricsResult, WordCloudWord } from "../../../lib/types";
|
||||||
import { Button } from "@/components/ui/button";
|
import MetricCard from "../../../components/ui/metric-card";
|
||||||
|
import ModernLineChart from "../../../components/charts/line-chart";
|
||||||
|
import ModernBarChart from "../../../components/charts/bar-chart";
|
||||||
|
import ModernDonutChart from "../../../components/charts/donut-chart";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/dropdown-menu";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import {
|
||||||
import { formatEnumValue } from "@/lib/format-enums";
|
MessageSquare,
|
||||||
import ModernBarChart from "../../../components/charts/bar-chart";
|
Users,
|
||||||
import ModernDonutChart from "../../../components/charts/donut-chart";
|
Clock,
|
||||||
import ModernLineChart from "../../../components/charts/line-chart";
|
Zap,
|
||||||
|
Euro,
|
||||||
|
TrendingUp,
|
||||||
|
CheckCircle,
|
||||||
|
RefreshCw,
|
||||||
|
LogOut,
|
||||||
|
Calendar,
|
||||||
|
MoreVertical,
|
||||||
|
Globe,
|
||||||
|
MessageCircle,
|
||||||
|
} from "lucide-react";
|
||||||
|
import WordCloud from "../../../components/WordCloud";
|
||||||
import GeographicMap from "../../../components/GeographicMap";
|
import GeographicMap from "../../../components/GeographicMap";
|
||||||
import ResponseTimeDistribution from "../../../components/ResponseTimeDistribution";
|
import ResponseTimeDistribution from "../../../components/ResponseTimeDistribution";
|
||||||
|
import DateRangePicker from "../../../components/DateRangePicker";
|
||||||
import TopQuestionsChart from "../../../components/TopQuestionsChart";
|
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
|
// Safely wrapped component with useSession
|
||||||
function DashboardContent() {
|
function DashboardContent() {
|
||||||
@ -46,14 +48,15 @@ function DashboardContent() {
|
|||||||
const [company, setCompany] = useState<Company | null>(null);
|
const [company, setCompany] = useState<Company | null>(null);
|
||||||
const [loading, setLoading] = useState<boolean>(false);
|
const [loading, setLoading] = useState<boolean>(false);
|
||||||
const [refreshing, setRefreshing] = useState<boolean>(false);
|
const [refreshing, setRefreshing] = useState<boolean>(false);
|
||||||
|
const [dateRange, setDateRange] = useState<{ minDate: string; maxDate: string } | null>(null);
|
||||||
|
const [selectedStartDate, setSelectedStartDate] = useState<string>("");
|
||||||
|
const [selectedEndDate, setSelectedEndDate] = useState<string>("");
|
||||||
const [isInitialLoad, setIsInitialLoad] = useState<boolean>(true);
|
const [isInitialLoad, setIsInitialLoad] = useState<boolean>(true);
|
||||||
|
|
||||||
const refreshStatusId = useId();
|
|
||||||
const isAuditor = session?.user?.role === "AUDITOR";
|
const isAuditor = session?.user?.role === "AUDITOR";
|
||||||
|
|
||||||
// Function to fetch metrics with optional date range
|
// Function to fetch metrics with optional date range
|
||||||
const fetchMetrics = useCallback(
|
const fetchMetrics = async (startDate?: string, endDate?: string, isInitial = false) => {
|
||||||
async (startDate?: string, endDate?: string, isInitial = false) => {
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
let url = "/api/dashboard/metrics";
|
let url = "/api/dashboard/metrics";
|
||||||
@ -67,8 +70,11 @@ function DashboardContent() {
|
|||||||
setMetrics(data.metrics);
|
setMetrics(data.metrics);
|
||||||
setCompany(data.company);
|
setCompany(data.company);
|
||||||
|
|
||||||
// Set initial load flag
|
// Set date range from API response (only on initial load)
|
||||||
if (isInitial) {
|
if (data.dateRange && isInitial) {
|
||||||
|
setDateRange(data.dateRange);
|
||||||
|
setSelectedStartDate(data.dateRange.minDate);
|
||||||
|
setSelectedEndDate(data.dateRange.maxDate);
|
||||||
setIsInitialLoad(false);
|
setIsInitialLoad(false);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -76,9 +82,17 @@ function DashboardContent() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
},
|
};
|
||||||
[]
|
|
||||||
);
|
// Handle date range changes with proper memoization
|
||||||
|
const handleDateRangeChange = useCallback((startDate: string, endDate: string) => {
|
||||||
|
// Only update if dates actually changed to prevent unnecessary API calls
|
||||||
|
if (startDate !== selectedStartDate || endDate !== selectedEndDate) {
|
||||||
|
setSelectedStartDate(startDate);
|
||||||
|
setSelectedEndDate(endDate);
|
||||||
|
fetchMetrics(startDate, endDate);
|
||||||
|
}
|
||||||
|
}, [selectedStartDate, selectedEndDate]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Redirect if not authenticated
|
// Redirect if not authenticated
|
||||||
@ -91,7 +105,7 @@ function DashboardContent() {
|
|||||||
if (status === "authenticated" && isInitialLoad) {
|
if (status === "authenticated" && isInitialLoad) {
|
||||||
fetchMetrics(undefined, undefined, true);
|
fetchMetrics(undefined, undefined, true);
|
||||||
}
|
}
|
||||||
}, [status, router, isInitialLoad, fetchMetrics]);
|
}, [status, router, isInitialLoad]);
|
||||||
|
|
||||||
async function handleRefresh() {
|
async function handleRefresh() {
|
||||||
if (isAuditor) return;
|
if (isAuditor) return;
|
||||||
@ -128,7 +142,7 @@ function DashboardContent() {
|
|||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center min-h-[60vh]">
|
<div className="flex items-center justify-center min-h-[60vh]">
|
||||||
<div className="text-center space-y-4">
|
<div className="text-center space-y-4">
|
||||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto" />
|
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
|
||||||
<p className="text-muted-foreground">Loading session...</p>
|
<p className="text-muted-foreground">Loading session...</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -166,26 +180,9 @@ function DashboardContent() {
|
|||||||
|
|
||||||
{/* Metrics Grid Skeleton */}
|
{/* Metrics Grid Skeleton */}
|
||||||
<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 gap-6">
|
||||||
{Array.from({ length: 8 }, (_, i) => {
|
{Array.from({ length: 8 }).map((_, i) => (
|
||||||
const metricTypes = [
|
<MetricCard key={i} title="" value="" isLoading />
|
||||||
"sessions",
|
))}
|
||||||
"users",
|
|
||||||
"time",
|
|
||||||
"response",
|
|
||||||
"costs",
|
|
||||||
"peak",
|
|
||||||
"resolution",
|
|
||||||
"languages",
|
|
||||||
];
|
|
||||||
return (
|
|
||||||
<MetricCard
|
|
||||||
key={`skeleton-${metricTypes[i] || "metric"}-card-loading`}
|
|
||||||
title=""
|
|
||||||
value=""
|
|
||||||
isLoading
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Charts Skeleton */}
|
{/* Charts Skeleton */}
|
||||||
@ -222,21 +219,9 @@ function DashboardContent() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{ name: "Positive", value: sentimentData.positive, color: "rgb(34, 197, 94)" },
|
||||||
name: "Positive",
|
{ name: "Neutral", value: sentimentData.neutral, color: "rgb(168, 162, 158)" },
|
||||||
value: sentimentData.positive,
|
{ name: "Negative", value: sentimentData.negative, color: "rgb(239, 68, 68)" },
|
||||||
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))",
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -244,10 +229,7 @@ function DashboardContent() {
|
|||||||
if (!metrics?.days) return [];
|
if (!metrics?.days) return [];
|
||||||
|
|
||||||
return Object.entries(metrics.days).map(([date, value]) => ({
|
return Object.entries(metrics.days).map(([date, value]) => ({
|
||||||
date: new Date(date).toLocaleDateString("en-US", {
|
date: new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
}),
|
|
||||||
value: value as number,
|
value: value as number,
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
@ -255,16 +237,10 @@ function DashboardContent() {
|
|||||||
const getCategoriesData = () => {
|
const getCategoriesData = () => {
|
||||||
if (!metrics?.categories) return [];
|
if (!metrics?.categories) return [];
|
||||||
|
|
||||||
return Object.entries(metrics.categories).map(([name, value]) => {
|
return Object.entries(metrics.categories).map(([name, value]) => ({
|
||||||
const formattedName = formatEnumValue(name) || name;
|
name: name.length > 15 ? name.substring(0, 15) + '...' : name,
|
||||||
return {
|
|
||||||
name:
|
|
||||||
formattedName.length > 15
|
|
||||||
? `${formattedName.substring(0, 15)}...`
|
|
||||||
: formattedName,
|
|
||||||
value: value as number,
|
value: value as number,
|
||||||
};
|
}));
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLanguagesData = () => {
|
const getLanguagesData = () => {
|
||||||
@ -308,87 +284,130 @@ function DashboardContent() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
{/* Modern Header */}
|
{/* Apple-Style Unified Header */}
|
||||||
<Card className="border-0 bg-linear-to-r from-primary/5 via-primary/10 to-primary/5">
|
<Card className="border-0 bg-white shadow-sm">
|
||||||
<CardHeader>
|
<CardHeader className="pb-6">
|
||||||
|
<div className="flex flex-col space-y-6">
|
||||||
|
{/* Top row: Company info and actions */}
|
||||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-1">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<h1 className="text-3xl font-bold tracking-tight">
|
<h1 className="text-2xl font-semibold text-gray-900 tracking-tight">{company.name}</h1>
|
||||||
{company.name}
|
<Badge variant="secondary" className="text-xs font-medium bg-gray-100 text-gray-700 border-0">
|
||||||
</h1>
|
|
||||||
<Badge variant="secondary" className="text-xs">
|
|
||||||
Analytics Dashboard
|
Analytics Dashboard
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-muted-foreground">
|
<p className="text-sm text-gray-500">
|
||||||
Last updated{" "}
|
Last updated{" "}
|
||||||
<span className="font-medium">
|
<span className="font-medium text-gray-700">
|
||||||
{new Date(metrics.lastUpdated || Date.now()).toLocaleString()}
|
{new Date(metrics.lastUpdated || Date.now()).toLocaleString()}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-3">
|
||||||
<Button
|
<Button
|
||||||
onClick={handleRefresh}
|
onClick={handleRefresh}
|
||||||
disabled={refreshing || isAuditor}
|
disabled={refreshing || isAuditor}
|
||||||
size="sm"
|
size="sm"
|
||||||
className="gap-2"
|
className="gap-2 bg-blue-600 hover:bg-blue-700 border-0 shadow-sm"
|
||||||
aria-label={
|
|
||||||
refreshing
|
|
||||||
? "Refreshing dashboard data"
|
|
||||||
: "Refresh dashboard data"
|
|
||||||
}
|
|
||||||
aria-describedby={refreshing ? refreshStatusId : undefined}
|
|
||||||
>
|
>
|
||||||
<RefreshCw
|
<RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
|
||||||
className={`h-4 w-4 ${refreshing ? "animate-spin" : ""}`}
|
|
||||||
aria-hidden="true"
|
|
||||||
/>
|
|
||||||
{refreshing ? "Refreshing..." : "Refresh"}
|
{refreshing ? "Refreshing..." : "Refresh"}
|
||||||
</Button>
|
</Button>
|
||||||
{refreshing && (
|
|
||||||
<div
|
|
||||||
id={refreshStatusId}
|
|
||||||
className="sr-only"
|
|
||||||
aria-live="polite"
|
|
||||||
>
|
|
||||||
Dashboard data is being refreshed
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="outline" size="sm" aria-label="Account menu">
|
<Button variant="outline" size="sm" className="border-gray-200 hover:bg-gray-50">
|
||||||
<MoreVertical className="h-4 w-4" aria-hidden="true" />
|
<MoreVertical className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end" className="border-gray-200 shadow-lg">
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem onClick={() => signOut({ callbackUrl: "/login" })}>
|
||||||
onClick={() => signOut({ callbackUrl: "/login" })}
|
<LogOut className="h-4 w-4 mr-2" />
|
||||||
>
|
|
||||||
<LogOut className="h-4 w-4 mr-2" aria-hidden="true" />
|
|
||||||
Sign out
|
Sign out
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Date Range Controls */}
|
||||||
|
{dateRange && (
|
||||||
|
<div className="border-t border-gray-100 pt-6">
|
||||||
|
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Calendar className="h-4 w-4 text-gray-500" />
|
||||||
|
<span className="text-sm font-medium text-gray-700">Date Range:</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<label className="text-sm text-gray-600">From:</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={selectedStartDate}
|
||||||
|
min={dateRange.minDate}
|
||||||
|
max={dateRange.maxDate}
|
||||||
|
onChange={(e) => handleDateRangeChange(e.target.value, selectedEndDate)}
|
||||||
|
className="px-3 py-1.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<label className="text-sm text-gray-600">To:</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={selectedEndDate}
|
||||||
|
min={dateRange.minDate}
|
||||||
|
max={dateRange.maxDate}
|
||||||
|
onChange={(e) => handleDateRangeChange(selectedStartDate, e.target.value)}
|
||||||
|
className="px-3 py-1.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
const endDate = new Date().toISOString().split('T')[0];
|
||||||
|
const startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
|
||||||
|
handleDateRangeChange(startDate, endDate);
|
||||||
|
}}
|
||||||
|
className="text-xs border-gray-200 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
Last 7 days
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
const endDate = new Date().toISOString().split('T')[0];
|
||||||
|
const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
|
||||||
|
handleDateRangeChange(startDate, endDate);
|
||||||
|
}}
|
||||||
|
className="text-xs border-gray-200 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
Last 30 days
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDateRangeChange(dateRange.minDate, dateRange.maxDate)}
|
||||||
|
className="text-xs border-gray-200 hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
All time
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mt-2">
|
||||||
|
Available data: {new Date(dateRange.minDate).toLocaleDateString()} - {new Date(dateRange.maxDate).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Date Range Picker - Temporarily disabled to debug infinite loop */}
|
|
||||||
{/* {dateRange && (
|
|
||||||
<DateRangePicker
|
|
||||||
minDate={dateRange.minDate}
|
|
||||||
maxDate={dateRange.maxDate}
|
|
||||||
onDateRangeChange={handleDateRangeChange}
|
|
||||||
initialStartDate={selectedStartDate}
|
|
||||||
initialEndDate={selectedEndDate}
|
|
||||||
/>
|
|
||||||
)} */}
|
|
||||||
|
|
||||||
{/* Modern Metrics Grid */}
|
{/* 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 gap-6">
|
||||||
<MetricCard
|
<MetricCard
|
||||||
@ -421,6 +440,7 @@ function DashboardContent() {
|
|||||||
value: metrics.avgSessionTimeTrend ?? 0,
|
value: metrics.avgSessionTimeTrend ?? 0,
|
||||||
isPositive: (metrics.avgSessionTimeTrend ?? 0) >= 0,
|
isPositive: (metrics.avgSessionTimeTrend ?? 0) >= 0,
|
||||||
}}
|
}}
|
||||||
|
variant="primary"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MetricCard
|
<MetricCard
|
||||||
@ -436,32 +456,29 @@ function DashboardContent() {
|
|||||||
|
|
||||||
<MetricCard
|
<MetricCard
|
||||||
title="Daily Costs"
|
title="Daily Costs"
|
||||||
value={`€${metrics.avgDailyCosts?.toFixed(4) || "0.0000"}`}
|
value={`€${metrics.avgDailyCosts?.toFixed(4) || '0.0000'}`}
|
||||||
icon={<Euro className="h-5 w-5" />}
|
icon={<Euro className="h-5 w-5" />}
|
||||||
description="Average per day"
|
description="Average per day"
|
||||||
|
variant="warning"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MetricCard
|
<MetricCard
|
||||||
title="Peak Usage"
|
title="Peak Usage"
|
||||||
value={metrics.peakUsageTime || "N/A"}
|
value={metrics.peakUsageTime || 'N/A'}
|
||||||
icon={<TrendingUp className="h-5 w-5" />}
|
icon={<TrendingUp className="h-5 w-5" />}
|
||||||
description="Busiest hour"
|
description="Busiest hour"
|
||||||
|
variant="primary"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MetricCard
|
<MetricCard
|
||||||
title="Resolution Rate"
|
title="Resolution Rate"
|
||||||
value={`${metrics.resolvedChatsPercentage?.toFixed(1) || "0.0"}%`}
|
value={`${metrics.resolvedChatsPercentage?.toFixed(1) || '0.0'}%`}
|
||||||
icon={<CheckCircle className="h-5 w-5" />}
|
icon={<CheckCircle className="h-5 w-5" />}
|
||||||
trend={{
|
trend={{
|
||||||
value: metrics.resolvedChatsPercentage ?? 0,
|
value: metrics.resolvedChatsPercentage ?? 0,
|
||||||
isPositive: (metrics.resolvedChatsPercentage ?? 0) >= 80,
|
isPositive: (metrics.resolvedChatsPercentage ?? 0) >= 80,
|
||||||
}}
|
}}
|
||||||
variant={
|
variant={metrics.resolvedChatsPercentage && metrics.resolvedChatsPercentage >= 80 ? "success" : "warning"}
|
||||||
metrics.resolvedChatsPercentage &&
|
|
||||||
metrics.resolvedChatsPercentage >= 80
|
|
||||||
? "success"
|
|
||||||
: "warning"
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<MetricCard
|
<MetricCard
|
||||||
@ -469,6 +486,7 @@ function DashboardContent() {
|
|||||||
value={Object.keys(metrics.languages || {}).length}
|
value={Object.keys(metrics.languages || {}).length}
|
||||||
icon={<Globe className="h-5 w-5" />}
|
icon={<Globe className="h-5 w-5" />}
|
||||||
description="Languages detected"
|
description="Languages detected"
|
||||||
|
variant="success"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -562,8 +580,8 @@ function DashboardContent() {
|
|||||||
{metrics.totalTokens?.toLocaleString() || 0}
|
{metrics.totalTokens?.toLocaleString() || 0}
|
||||||
</Badge>
|
</Badge>
|
||||||
<Badge variant="outline" className="gap-1">
|
<Badge variant="outline" className="gap-1">
|
||||||
<span className="font-semibold">Total Cost:</span>€
|
<span className="font-semibold">Total Cost:</span>
|
||||||
{metrics.totalTokensEur?.toFixed(4) || 0}
|
€{metrics.totalTokensEur?.toFixed(4) || 0}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,21 +1,22 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { useSession } from "next-auth/react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { FC } from "react";
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
import {
|
import {
|
||||||
ArrowRight,
|
|
||||||
BarChart3,
|
BarChart3,
|
||||||
MessageSquare,
|
MessageSquare,
|
||||||
Settings,
|
Settings,
|
||||||
Shield,
|
|
||||||
TrendingUp,
|
|
||||||
Users,
|
Users,
|
||||||
|
ArrowRight,
|
||||||
|
TrendingUp,
|
||||||
|
Shield,
|
||||||
Zap,
|
Zap,
|
||||||
} from "lucide-react";
|
} 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";
|
|
||||||
|
|
||||||
const DashboardPage: FC = () => {
|
const DashboardPage: FC = () => {
|
||||||
const { data: session, status } = useSession();
|
const { data: session, status } = useSession();
|
||||||
@ -35,13 +36,8 @@ const DashboardPage: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center min-h-[60vh]">
|
<div className="flex items-center justify-center min-h-[60vh]">
|
||||||
<div className="text-center space-y-4">
|
<div className="text-center space-y-4">
|
||||||
<div className="relative">
|
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
|
||||||
<div className="animate-spin rounded-full h-12 w-12 border-2 border-muted border-t-primary mx-auto" />
|
<p className="text-lg text-muted-foreground">Loading dashboard...</p>
|
||||||
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -50,8 +46,7 @@ const DashboardPage: FC = () => {
|
|||||||
const navigationCards = [
|
const navigationCards = [
|
||||||
{
|
{
|
||||||
title: "Analytics Overview",
|
title: "Analytics Overview",
|
||||||
description:
|
description: "View comprehensive metrics, charts, and insights from your chat sessions",
|
||||||
"View comprehensive metrics, charts, and insights from your chat sessions",
|
|
||||||
icon: <BarChart3 className="h-6 w-6" />,
|
icon: <BarChart3 className="h-6 w-6" />,
|
||||||
href: "/dashboard/overview",
|
href: "/dashboard/overview",
|
||||||
variant: "primary" as const,
|
variant: "primary" as const,
|
||||||
@ -59,8 +54,7 @@ const DashboardPage: FC = () => {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Session Browser",
|
title: "Session Browser",
|
||||||
description:
|
description: "Browse, search, and analyze individual conversation sessions",
|
||||||
"Browse, search, and analyze individual conversation sessions",
|
|
||||||
icon: <MessageSquare className="h-6 w-6" />,
|
icon: <MessageSquare className="h-6 w-6" />,
|
||||||
href: "/dashboard/sessions",
|
href: "/dashboard/sessions",
|
||||||
variant: "success" as const,
|
variant: "success" as const,
|
||||||
@ -70,22 +64,16 @@ const DashboardPage: FC = () => {
|
|||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
title: "Company Settings",
|
title: "Company Settings",
|
||||||
description:
|
description: "Configure company settings, integrations, and API connections",
|
||||||
"Configure company settings, integrations, and API connections",
|
|
||||||
icon: <Settings className="h-6 w-6" />,
|
icon: <Settings className="h-6 w-6" />,
|
||||||
href: "/dashboard/company",
|
href: "/dashboard/company",
|
||||||
variant: "warning" as const,
|
variant: "warning" as const,
|
||||||
features: [
|
features: ["API configuration", "Integration settings", "Data management"],
|
||||||
"API configuration",
|
|
||||||
"Integration settings",
|
|
||||||
"Data management",
|
|
||||||
],
|
|
||||||
adminOnly: true,
|
adminOnly: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "User Management",
|
title: "User Management",
|
||||||
description:
|
description: "Invite team members and manage user accounts and permissions",
|
||||||
"Invite team members and manage user accounts and permissions",
|
|
||||||
icon: <Users className="h-6 w-6" />,
|
icon: <Users className="h-6 w-6" />,
|
||||||
href: "/dashboard/users",
|
href: "/dashboard/users",
|
||||||
variant: "default" as const,
|
variant: "default" as const,
|
||||||
@ -125,42 +113,39 @@ const DashboardPage: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
{/* Welcome Header */}
|
{/* 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">
|
<Card className="border-0 bg-linear-to-r from-primary/5 via-primary/10 to-primary/5">
|
||||||
<div className="absolute inset-0 bg-linear-to-br from-primary/5 to-transparent" />
|
<CardHeader>
|
||||||
<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="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
||||||
<div className="space-y-3">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center gap-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">
|
<h1 className="text-3xl font-bold tracking-tight">
|
||||||
Welcome back, {session?.user?.name || "User"}!
|
Welcome back, {session?.user?.name || "User"}!
|
||||||
</h1>
|
</h1>
|
||||||
<Badge
|
<Badge variant="secondary" className="text-xs">
|
||||||
variant="secondary"
|
|
||||||
className="text-xs px-3 py-1 bg-primary/10 text-primary border-primary/20"
|
|
||||||
>
|
|
||||||
{session?.user?.role}
|
{session?.user?.role}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-muted-foreground text-lg">
|
<p className="text-muted-foreground">
|
||||||
Choose a section below to explore your analytics dashboard
|
Choose a section below to explore your analytics dashboard
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3 px-4 py-2 rounded-full bg-muted/50 backdrop-blur-sm">
|
<div className="flex items-center gap-2">
|
||||||
<Shield className="h-4 w-4 text-green-600" />
|
<div className="flex items-center gap-1 text-sm text-muted-foreground">
|
||||||
<span className="text-sm font-medium">Secure Dashboard</span>
|
<Shield className="h-4 w-4" />
|
||||||
</div>
|
Secure Dashboard
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{/* Navigation Cards */}
|
{/* Navigation Cards */}
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||||
{navigationCards.map((card) => (
|
{navigationCards.map((card, index) => (
|
||||||
<Card
|
<Card
|
||||||
key={card.href}
|
key={index}
|
||||||
className={`relative overflow-hidden transition-all duration-300 hover:shadow-2xl hover:-translate-y-1 cursor-pointer group ${getCardClasses(
|
className={`relative overflow-hidden transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5 cursor-pointer ${getCardClasses(
|
||||||
card.variant
|
card.variant
|
||||||
)}`}
|
)}`}
|
||||||
onClick={() => router.push(card.href)}
|
onClick={() => router.push(card.href)}
|
||||||
@ -173,13 +158,11 @@ const DashboardPage: FC = () => {
|
|||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div
|
<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(
|
className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-full border transition-colors ${getIconClasses(
|
||||||
card.variant
|
card.variant
|
||||||
)}`}
|
)}`}
|
||||||
>
|
>
|
||||||
<span className="transition-transform duration-300 group-hover:scale-110">
|
|
||||||
{card.icon}
|
{card.icon}
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className="text-xl font-semibold flex items-center gap-2">
|
<CardTitle className="text-xl font-semibold flex items-center gap-2">
|
||||||
@ -202,12 +185,9 @@ const DashboardPage: FC = () => {
|
|||||||
<CardContent className="relative space-y-4">
|
<CardContent className="relative space-y-4">
|
||||||
{/* Features List */}
|
{/* Features List */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{card.features.map((feature) => (
|
{card.features.map((feature, featureIndex) => (
|
||||||
<div
|
<div key={featureIndex} className="flex items-center gap-2 text-sm">
|
||||||
key={feature}
|
<div className="h-1.5 w-1.5 rounded-full bg-current opacity-60" />
|
||||||
className="flex items-center gap-2 text-sm"
|
|
||||||
>
|
|
||||||
<Zap className="h-3 w-3 text-primary/60" />
|
|
||||||
<span className="text-muted-foreground">{feature}</span>
|
<span className="text-muted-foreground">{feature}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@ -215,7 +195,7 @@ const DashboardPage: FC = () => {
|
|||||||
|
|
||||||
{/* Action Button */}
|
{/* Action Button */}
|
||||||
<Button
|
<Button
|
||||||
className="w-full gap-2 mt-4 group-hover:gap-3 transition-all duration-300"
|
className="w-full gap-2 mt-4"
|
||||||
variant={card.variant === "primary" ? "default" : "outline"}
|
variant={card.variant === "primary" ? "default" : "outline"}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
|||||||
@ -1,27 +1,13 @@
|
|||||||
"use client";
|
"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 { useEffect, useState } from "react";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { useParams, useRouter } from "next/navigation"; // Import useRouter
|
||||||
import { Button } from "@/components/ui/button";
|
import { useSession } from "next-auth/react"; // Import useSession
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|
||||||
import { formatCategory } from "@/lib/format-enums";
|
|
||||||
import MessageViewer from "../../../../components/MessageViewer";
|
|
||||||
import SessionDetails from "../../../../components/SessionDetails";
|
import SessionDetails from "../../../../components/SessionDetails";
|
||||||
import type { ChatSession } from "../../../../lib/types";
|
import TranscriptViewer from "../../../../components/TranscriptViewer";
|
||||||
|
import MessageViewer from "../../../../components/MessageViewer";
|
||||||
|
import { ChatSession } from "../../../../lib/types";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
export default function SessionViewPage() {
|
export default function SessionViewPage() {
|
||||||
const params = useParams();
|
const params = useParams();
|
||||||
@ -71,256 +57,110 @@ export default function SessionViewPage() {
|
|||||||
|
|
||||||
if (status === "loading") {
|
if (status === "loading") {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
|
||||||
<Card>
|
<p className="text-gray-600 text-lg">Loading session...</p>
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
|
||||||
Loading session...
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (status === "unauthenticated") {
|
if (status === "unauthenticated") {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
|
||||||
<Card>
|
<p className="text-gray-600 text-lg">Redirecting to login...</p>
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
|
||||||
Redirecting to login...
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loading && status === "authenticated") {
|
if (loading && status === "authenticated") {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="p-4 md:p-6 flex justify-center items-center min-h-screen">
|
||||||
<Card>
|
<p className="text-gray-600 text-lg">Loading session details...</p>
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
|
||||||
Loading session details...
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="p-4 md:p-6 min-h-screen">
|
||||||
<Card>
|
<p className="text-red-500 text-lg mb-4">Error: {error}</p>
|
||||||
<CardContent className="pt-6">
|
<Link
|
||||||
<div className="text-center py-8">
|
href="/dashboard/sessions"
|
||||||
<AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
|
className="text-sky-600 hover:underline"
|
||||||
<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
|
Back to Sessions List
|
||||||
</Button>
|
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!session) {
|
if (!session) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="p-4 md:p-6 min-h-screen">
|
||||||
<Card>
|
<p className="text-gray-600 text-lg mb-4">Session not found.</p>
|
||||||
<CardContent className="pt-6">
|
<Link
|
||||||
<div className="text-center py-8">
|
href="/dashboard/sessions"
|
||||||
<MessageSquare className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
className="text-sky-600 hover:underline"
|
||||||
<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
|
Back to Sessions List
|
||||||
</Button>
|
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 max-w-6xl mx-auto">
|
<div className="min-h-screen bg-linear-to-br from-slate-50 to-sky-100 p-4 md:p-6">
|
||||||
{/* Header */}
|
<div className="max-w-4xl mx-auto">
|
||||||
<Card>
|
<div className="mb-6">
|
||||||
<CardContent className="pt-6">
|
<Link
|
||||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
href="/dashboard/sessions"
|
||||||
<div className="space-y-2">
|
className="text-sky-700 hover:text-sky-900 hover:underline flex items-center"
|
||||||
<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" />
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
className="h-5 w-5 mr-1"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
fill="currentColor"
|
||||||
|
>
|
||||||
|
<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
|
Back to Sessions List
|
||||||
</Button>
|
|
||||||
</Link>
|
</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>
|
<h1 className="text-3xl font-bold text-gray-800 mb-6">
|
||||||
</div>
|
Session: {session.sessionId || session.id}
|
||||||
<div className="flex flex-wrap gap-2">
|
</h1>
|
||||||
{session.category && (
|
<div className="grid grid-cols-1 gap-6">
|
||||||
<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>
|
<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} />
|
<SessionDetails session={session} />
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Messages */}
|
{/* Show parsed messages if available */}
|
||||||
{session.messages && session.messages.length > 0 && (
|
{session.messages && session.messages.length > 0 && (
|
||||||
<Card>
|
<div>
|
||||||
<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} />
|
<MessageViewer messages={session.messages} />
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Transcript URL */}
|
{/* Show transcript URL if available */}
|
||||||
{session.fullTranscriptUrl && (
|
{session.fullTranscriptUrl && (
|
||||||
<Card>
|
<div className="bg-white p-4 rounded-lg shadow">
|
||||||
<CardHeader>
|
<h3 className="font-bold text-lg mb-3">Source Transcript</h3>
|
||||||
<CardTitle className="flex items-center gap-2">
|
|
||||||
<FileText className="h-5 w-5" />
|
|
||||||
Source Transcript
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<a
|
<a
|
||||||
href={session.fullTranscriptUrl}
|
href={session.fullTranscriptUrl}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
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"
|
className="text-sky-600 hover:underline"
|
||||||
aria-label="Open original transcript in new tab"
|
|
||||||
>
|
>
|
||||||
<ExternalLink className="h-4 w-4" aria-hidden="true" />
|
|
||||||
View Original Transcript
|
View Original Transcript
|
||||||
</a>
|
</a>
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,26 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import { useState, useEffect, useCallback } from "react";
|
||||||
ChevronDown,
|
import { ChatSession } from "../../../lib/types";
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
ChevronUp,
|
|
||||||
Clock,
|
|
||||||
Eye,
|
|
||||||
Filter,
|
|
||||||
Globe,
|
|
||||||
MessageSquare,
|
|
||||||
Search,
|
|
||||||
} from "lucide-react";
|
|
||||||
import Link from "next/link";
|
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
|
// Placeholder for a SessionListItem component to be created later
|
||||||
// For now, we'll display some basic info directly.
|
// 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 [error, setError] = useState<string | null>(null);
|
||||||
const [searchTerm, setSearchTerm] = useState("");
|
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
|
// Filter states
|
||||||
const [filterOptions, setFilterOptions] = useState<FilterOptions>({
|
const [filterOptions, setFilterOptions] = useState<FilterOptions>({
|
||||||
categories: [],
|
categories: [],
|
||||||
@ -76,10 +41,7 @@ export default function SessionsPage() {
|
|||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const [totalPages, setTotalPages] = useState(0);
|
const [totalPages, setTotalPages] = useState(0);
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
|
||||||
const [pageSize, _setPageSize] = useState(10); // Or make this configurable
|
const [pageSize, setPageSize] = useState(10); // Or make this configurable
|
||||||
|
|
||||||
// UI states
|
|
||||||
const [filtersExpanded, setFiltersExpanded] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timerId = setTimeout(() => {
|
const timerId = setTimeout(() => {
|
||||||
@ -158,115 +120,60 @@ export default function SessionsPage() {
|
|||||||
}, [fetchFilterOptions]);
|
}, [fetchFilterOptions]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="p-4 md:p-6">
|
||||||
{/* Page heading for screen readers */}
|
<h1 className="text-2xl font-semibold text-gray-800 mb-6">
|
||||||
<h1 className="sr-only">Sessions Management</h1>
|
Chat Sessions
|
||||||
|
</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>
|
|
||||||
|
|
||||||
{/* Search Input */}
|
{/* Search Input */}
|
||||||
<section aria-labelledby={searchHeadingId}>
|
<div className="mb-4">
|
||||||
<h2 id={searchHeadingId} className="sr-only">
|
<input
|
||||||
Search Sessions
|
type="text"
|
||||||
</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...)"
|
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}
|
value={searchTerm}
|
||||||
onChange={(e) => setSearchTerm(e.target.value)}
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
className="pl-10"
|
|
||||||
aria-label="Search sessions by ID, category, or message content"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Filter and Sort Controls */}
|
{/* Filter and Sort Controls */}
|
||||||
<section aria-labelledby={filtersHeadingId}>
|
<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">
|
||||||
<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 */}
|
{/* Category Filter */}
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor={categoryFilterId}>Category</Label>
|
<label
|
||||||
|
htmlFor="category-filter"
|
||||||
|
className="block text-sm font-medium text-gray-700 mb-1"
|
||||||
|
>
|
||||||
|
Category
|
||||||
|
</label>
|
||||||
<select
|
<select
|
||||||
id={categoryFilterId}
|
id="category-filter"
|
||||||
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"
|
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
|
||||||
value={selectedCategory}
|
value={selectedCategory}
|
||||||
onChange={(e) => setSelectedCategory(e.target.value)}
|
onChange={(e) => setSelectedCategory(e.target.value)}
|
||||||
aria-describedby={categoryHelpId}
|
|
||||||
>
|
>
|
||||||
<option value="">All Categories</option>
|
<option value="">All Categories</option>
|
||||||
{filterOptions.categories.map((cat) => (
|
{filterOptions.categories.map((cat) => (
|
||||||
<option key={cat} value={cat}>
|
<option key={cat} value={cat}>
|
||||||
{formatCategory(cat)}
|
{cat}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
<div id={categoryHelpId} className="sr-only">
|
|
||||||
Filter sessions by category type
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Language Filter */}
|
{/* Language Filter */}
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor={languageFilterId}>Language</Label>
|
<label
|
||||||
|
htmlFor="language-filter"
|
||||||
|
className="block text-sm font-medium text-gray-700 mb-1"
|
||||||
|
>
|
||||||
|
Language
|
||||||
|
</label>
|
||||||
<select
|
<select
|
||||||
id={languageFilterId}
|
id="language-filter"
|
||||||
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"
|
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
|
||||||
value={selectedLanguage}
|
value={selectedLanguage}
|
||||||
onChange={(e) => setSelectedLanguage(e.target.value)}
|
onChange={(e) => setSelectedLanguage(e.target.value)}
|
||||||
aria-describedby={languageHelpId}
|
|
||||||
>
|
>
|
||||||
<option value="">All Languages</option>
|
<option value="">All Languages</option>
|
||||||
{filterOptions.languages.map((lang) => (
|
{filterOptions.languages.map((lang) => (
|
||||||
@ -275,273 +182,166 @@ export default function SessionsPage() {
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
<div id={languageHelpId} className="sr-only">
|
|
||||||
Filter sessions by language
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Start Date Filter */}
|
{/* Start Date Filter */}
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor={startDateFilterId}>Start Date</Label>
|
<label
|
||||||
<Input
|
htmlFor="start-date-filter"
|
||||||
|
className="block text-sm font-medium text-gray-700 mb-1"
|
||||||
|
>
|
||||||
|
Start Date
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
id={startDateFilterId}
|
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}
|
value={startDate}
|
||||||
onChange={(e) => setStartDate(e.target.value)}
|
onChange={(e) => setStartDate(e.target.value)}
|
||||||
aria-describedby={startDateHelpId}
|
|
||||||
/>
|
/>
|
||||||
<div id={startDateHelpId} className="sr-only">
|
|
||||||
Filter sessions from this date onwards
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* End Date Filter */}
|
{/* End Date Filter */}
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor={endDateFilterId}>End Date</Label>
|
<label
|
||||||
<Input
|
htmlFor="end-date-filter"
|
||||||
|
className="block text-sm font-medium text-gray-700 mb-1"
|
||||||
|
>
|
||||||
|
End Date
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
id={endDateFilterId}
|
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}
|
value={endDate}
|
||||||
onChange={(e) => setEndDate(e.target.value)}
|
onChange={(e) => setEndDate(e.target.value)}
|
||||||
aria-describedby={endDateHelpId}
|
|
||||||
/>
|
/>
|
||||||
<div id={endDateHelpId} className="sr-only">
|
|
||||||
Filter sessions up to this date
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sort Key */}
|
{/* Sort Key */}
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor={sortKeyId}>Sort By</Label>
|
<label
|
||||||
|
htmlFor="sort-key"
|
||||||
|
className="block text-sm font-medium text-gray-700 mb-1"
|
||||||
|
>
|
||||||
|
Sort By
|
||||||
|
</label>
|
||||||
<select
|
<select
|
||||||
id={sortKeyId}
|
id="sort-key"
|
||||||
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"
|
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
|
||||||
value={sortKey}
|
value={sortKey}
|
||||||
onChange={(e) => setSortKey(e.target.value)}
|
onChange={(e) => setSortKey(e.target.value)}
|
||||||
aria-describedby={sortKeyHelpId}
|
|
||||||
>
|
>
|
||||||
<option value="startTime">Start Time</option>
|
<option value="startTime">Start Time</option>
|
||||||
<option value="category">Category</option>
|
<option value="category">Category</option>
|
||||||
<option value="language">Language</option>
|
<option value="language">Language</option>
|
||||||
<option value="sentiment">Sentiment</option>
|
<option value="sentiment">Sentiment</option>
|
||||||
<option value="messagesSent">Messages Sent</option>
|
<option value="messagesSent">Messages Sent</option>
|
||||||
<option value="avgResponseTime">
|
<option value="avgResponseTime">Avg. Response Time</option>
|
||||||
Avg. Response Time
|
|
||||||
</option>
|
|
||||||
</select>
|
</select>
|
||||||
<div id={sortKeyHelpId} className="sr-only">
|
|
||||||
Choose field to sort sessions by
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Sort Order */}
|
{/* Sort Order */}
|
||||||
<div className="space-y-2">
|
<div>
|
||||||
<Label htmlFor={sortOrderId}>Order</Label>
|
<label
|
||||||
|
htmlFor="sort-order"
|
||||||
|
className="block text-sm font-medium text-gray-700 mb-1"
|
||||||
|
>
|
||||||
|
Order
|
||||||
|
</label>
|
||||||
<select
|
<select
|
||||||
id={sortOrderId}
|
id="sort-order"
|
||||||
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"
|
className="w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-sky-500 focus:border-sky-500"
|
||||||
value={sortOrder}
|
value={sortOrder}
|
||||||
onChange={(e) =>
|
onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")}
|
||||||
setSortOrder(e.target.value as "asc" | "desc")
|
|
||||||
}
|
|
||||||
aria-describedby={sortOrderHelpId}
|
|
||||||
>
|
>
|
||||||
<option value="desc">Descending</option>
|
<option value="desc">Descending</option>
|
||||||
<option value="asc">Ascending</option>
|
<option value="asc">Ascending</option>
|
||||||
</select>
|
</select>
|
||||||
<div id={sortOrderHelpId} className="sr-only">
|
|
||||||
Choose ascending or descending order
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
</CardContent>
|
|
||||||
)}
|
|
||||||
</Card>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
{/* Results section */}
|
{loading && <p className="text-gray-600">Loading sessions...</p>}
|
||||||
<section aria-labelledby={resultsHeadingId}>
|
{error && <p className="text-red-500">Error: {error}</p>}
|
||||||
<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 && (
|
{!loading && !error && sessions.length === 0 && (
|
||||||
<Card>
|
<p className="text-gray-600">
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
|
||||||
{debouncedSearchTerm
|
{debouncedSearchTerm
|
||||||
? `No sessions found for "${debouncedSearchTerm}".`
|
? `No sessions found for "${debouncedSearchTerm}".`
|
||||||
: "No sessions found."}
|
: "No sessions found."}
|
||||||
</div>
|
</p>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Sessions List */}
|
|
||||||
{!loading && !error && sessions.length > 0 && (
|
{!loading && !error && sessions.length > 0 && (
|
||||||
<ul aria-label="Chat sessions" className="grid gap-4">
|
<div className="space-y-4">
|
||||||
{sessions.map((session) => (
|
{sessions.map((session) => (
|
||||||
<li key={session.id}>
|
<div
|
||||||
<Card className="hover:shadow-md transition-shadow">
|
key={session.id}
|
||||||
<CardContent className="pt-6">
|
className="bg-white p-4 rounded-lg shadow hover:shadow-md transition-shadow"
|
||||||
<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{" "}
|
<h2 className="text-lg font-semibold text-sky-700 mb-1">
|
||||||
{new Date(session.startTime).toLocaleDateString()}
|
Session ID: {session.sessionId || session.id}
|
||||||
</h3>
|
</h2>
|
||||||
<div className="flex items-center gap-3">
|
<p className="text-sm text-gray-500 mb-1">
|
||||||
<Badge
|
Start Time{/* (Local) */}:{" "}
|
||||||
variant="outline"
|
{new Date(session.startTime).toLocaleString()}
|
||||||
className="font-mono text-xs"
|
</p>
|
||||||
>
|
{/* <p className="text-xs text-gray-400 mb-1">
|
||||||
ID
|
Start Time (Raw API): {session.startTime.toString()}
|
||||||
</Badge>
|
</p> */}
|
||||||
<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 && (
|
{session.category && (
|
||||||
<Badge variant="secondary" className="gap-1">
|
<p className="text-sm text-gray-700">
|
||||||
<Filter className="h-3 w-3" aria-hidden="true" />
|
Category:{" "}
|
||||||
{formatCategory(session.category)}
|
<span className="font-medium">{session.category}</span>
|
||||||
</Badge>
|
</p>
|
||||||
)}
|
)}
|
||||||
{session.language && (
|
{session.language && (
|
||||||
<Badge variant="outline" className="gap-1">
|
<p className="text-sm text-gray-700">
|
||||||
<Globe className="h-3 w-3" aria-hidden="true" />
|
Language:{" "}
|
||||||
|
<span className="font-medium">
|
||||||
{session.language.toUpperCase()}
|
{session.language.toUpperCase()}
|
||||||
</Badge>
|
</span>
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{session.summary ? (
|
|
||||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
|
||||||
{session.summary}
|
|
||||||
</p>
|
</p>
|
||||||
) : session.initialMsg ? (
|
|
||||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
|
||||||
{session.initialMsg}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</article>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
)}
|
||||||
|
{session.initialMsg && (
|
||||||
{/* Pagination */}
|
<p className="text-sm text-gray-600 mt-1 truncate">
|
||||||
{totalPages > 0 && (
|
Initial Message: {session.initialMsg}
|
||||||
<Card>
|
</p>
|
||||||
<CardContent className="pt-6">
|
)}
|
||||||
<div className="flex justify-center items-center gap-4">
|
<Link
|
||||||
<Button
|
href={`/dashboard/sessions/${session.id}`}
|
||||||
variant="outline"
|
className="mt-2 text-sm text-sky-600 hover:text-sky-800 hover:underline inline-block"
|
||||||
onClick={() =>
|
>
|
||||||
setCurrentPage((prev) => Math.max(prev - 1, 1))
|
View Details
|
||||||
}
|
</Link>
|
||||||
disabled={currentPage === 1}
|
</div>
|
||||||
className="gap-2"
|
))}
|
||||||
|
</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"
|
||||||
>
|
>
|
||||||
<ChevronLeft className="h-4 w-4" />
|
|
||||||
Previous
|
Previous
|
||||||
</Button>
|
</button>
|
||||||
<span className="text-sm text-muted-foreground">
|
<span className="text-sm text-gray-700">
|
||||||
Page {currentPage} of {totalPages}
|
Page {currentPage} of {totalPages}
|
||||||
</span>
|
</span>
|
||||||
<Button
|
<button
|
||||||
variant="outline"
|
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
|
setCurrentPage((prev) => Math.min(prev + 1, totalPages))
|
||||||
}
|
}
|
||||||
disabled={currentPage === totalPages}
|
disabled={currentPage === totalPages}
|
||||||
className="gap-2"
|
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
|
Next
|
||||||
<ChevronRight className="h-4 w-4" />
|
</button>
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
)}
|
||||||
</section>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import type { Session } from "next-auth";
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import type { Company } from "../../lib/types";
|
import { Company } from "../../lib/types";
|
||||||
|
import { Session } from "next-auth";
|
||||||
|
|
||||||
interface DashboardSettingsProps {
|
interface DashboardSettingsProps {
|
||||||
company: Company;
|
company: Company;
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useState } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import type { UserSession } from "../../lib/types";
|
import { UserSession } from "../../lib/types";
|
||||||
|
|
||||||
interface UserItem {
|
interface UserItem {
|
||||||
id: string;
|
id: string;
|
||||||
@ -56,7 +56,6 @@ export default function UserManagement({ session }: UserManagementProps) {
|
|||||||
<option value="AUDITOR">Auditor</option>
|
<option value="AUDITOR">Auditor</option>
|
||||||
</select>
|
</select>
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
className="bg-blue-600 text-white rounded px-4 py-2 sm:py-0 w-full sm:w-auto"
|
className="bg-blue-600 text-white rounded px-4 py-2 sm:py-0 w-full sm:w-auto"
|
||||||
onClick={inviteUser}
|
onClick={inviteUser}
|
||||||
>
|
>
|
||||||
|
|||||||
@ -1,29 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { AlertCircle, Eye, Shield, UserPlus, Users } from "lucide-react";
|
import { useState, useEffect } from "react";
|
||||||
import { useSession } from "next-auth/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 {
|
interface UserItem {
|
||||||
id: string;
|
id: string;
|
||||||
@ -35,12 +13,17 @@ export default function UserManagementPage() {
|
|||||||
const { data: session, status } = useSession();
|
const { data: session, status } = useSession();
|
||||||
const [users, setUsers] = useState<UserItem[]>([]);
|
const [users, setUsers] = useState<UserItem[]>([]);
|
||||||
const [email, setEmail] = useState<string>("");
|
const [email, setEmail] = useState<string>("");
|
||||||
const [role, setRole] = useState<string>("USER");
|
const [role, setRole] = useState<string>("user");
|
||||||
const [message, setMessage] = useState<string>("");
|
const [message, setMessage] = useState<string>("");
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const emailId = useId();
|
|
||||||
|
|
||||||
const fetchUsers = useCallback(async () => {
|
useEffect(() => {
|
||||||
|
if (status === "authenticated") {
|
||||||
|
fetchUsers();
|
||||||
|
}
|
||||||
|
}, [status]);
|
||||||
|
|
||||||
|
const fetchUsers = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/dashboard/users");
|
const res = await fetch("/api/dashboard/users");
|
||||||
@ -52,19 +35,7 @@ export default function UserManagementPage() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
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() {
|
async function inviteUser() {
|
||||||
setMessage("");
|
setMessage("");
|
||||||
@ -94,180 +65,148 @@ export default function UserManagementPage() {
|
|||||||
|
|
||||||
// Loading state
|
// Loading state
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return <div className="text-center py-10">Loading users...</div>;
|
||||||
<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>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for admin access
|
// Check for admin access
|
||||||
if (session?.user?.role !== "ADMIN") {
|
if (session?.user?.role !== "ADMIN") {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="text-center py-10 bg-white rounded-xl shadow p-6">
|
||||||
<Card>
|
<h2 className="font-bold text-xl text-red-600 mb-2">Access Denied</h2>
|
||||||
<CardContent className="pt-6">
|
<p>You don't have permission to view user management.</p>
|
||||||
<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't have permission to view user management.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6" data-testid="user-management-page">
|
<div className="space-y-6">
|
||||||
{/* Header */}
|
<div className="bg-white p-6 rounded-xl shadow">
|
||||||
<Card>
|
<h1 className="text-2xl font-bold text-gray-800 mb-6">
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center gap-2">
|
|
||||||
<Users className="h-6 w-6" />
|
|
||||||
User Management
|
User Management
|
||||||
</CardTitle>
|
</h1>
|
||||||
</CardHeader>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Message Alert */}
|
|
||||||
{message && (
|
{message && (
|
||||||
<Alert variant={message.includes("Failed") ? "destructive" : "default"}>
|
<div
|
||||||
<AlertDescription>{message}</AlertDescription>
|
className={`p-4 rounded mb-6 ${message.includes("Failed") ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"}`}
|
||||||
</Alert>
|
>
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Invite New User */}
|
<div className="mb-8">
|
||||||
<Card>
|
<h2 className="text-lg font-semibold mb-4">Invite New User</h2>
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center gap-2">
|
|
||||||
<UserPlus className="h-5 w-5" />
|
|
||||||
Invite New User
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<form
|
<form
|
||||||
className="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end"
|
className="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end"
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
inviteUser();
|
inviteUser();
|
||||||
}}
|
}}
|
||||||
autoComplete="off"
|
autoComplete="off" // Disable autofill for the form
|
||||||
data-testid="invite-form"
|
|
||||||
>
|
>
|
||||||
<div className="space-y-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor={emailId}>Email</Label>
|
<label className="font-medium text-gray-700">Email</label>
|
||||||
<Input
|
<input
|
||||||
id={emailId}
|
|
||||||
type="email"
|
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"
|
placeholder="user@example.com"
|
||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
required
|
required
|
||||||
autoComplete="off"
|
autoComplete="off" // Disable autofill for this input
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="role">Role</Label>
|
<label className="font-medium text-gray-700">Role</label>
|
||||||
<Select value={role} onValueChange={setRole}>
|
<select
|
||||||
<SelectTrigger>
|
className="border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500 bg-white"
|
||||||
<SelectValue placeholder="Select role" />
|
value={role}
|
||||||
</SelectTrigger>
|
onChange={(e) => setRole(e.target.value)}
|
||||||
<SelectContent>
|
>
|
||||||
<SelectItem value="USER">User</SelectItem>
|
<option value="user">User</option>
|
||||||
<SelectItem value="ADMIN">Admin</SelectItem>
|
<option value="ADMIN">Admin</option>
|
||||||
<SelectItem value="AUDITOR">Auditor</SelectItem>
|
<option value="AUDITOR">Auditor</option>
|
||||||
</SelectContent>
|
</select>
|
||||||
</Select>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button type="submit" className="gap-2">
|
<button
|
||||||
<UserPlus className="h-4 w-4" />
|
type="submit"
|
||||||
|
className="bg-sky-600 hover:bg-sky-700 text-white py-2 px-4 rounded-lg shadow transition-colors"
|
||||||
|
>
|
||||||
Invite User
|
Invite User
|
||||||
</Button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Current Users */}
|
<div>
|
||||||
<Card>
|
<h2 className="text-lg font-semibold mb-4">Current Users</h2>
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="flex items-center gap-2">
|
|
||||||
<Users className="h-5 w-5" />
|
|
||||||
Current Users ({users?.length || 0})
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<Table>
|
<table className="min-w-full divide-y divide-gray-200">
|
||||||
<TableHeader>
|
<thead className="bg-gray-50">
|
||||||
<TableRow>
|
<tr>
|
||||||
<TableHead>Email</TableHead>
|
<th
|
||||||
<TableHead>Role</TableHead>
|
scope="col"
|
||||||
<TableHead>Actions</TableHead>
|
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||||
</TableRow>
|
>
|
||||||
</TableHeader>
|
Email
|
||||||
<TableBody>
|
</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 ? (
|
{users.length === 0 ? (
|
||||||
<TableRow>
|
<tr>
|
||||||
<TableCell
|
<td
|
||||||
colSpan={3}
|
colSpan={3}
|
||||||
className="text-center text-muted-foreground"
|
className="px-6 py-4 text-center text-sm text-gray-500"
|
||||||
>
|
>
|
||||||
No users found
|
No users found
|
||||||
</TableCell>
|
</td>
|
||||||
</TableRow>
|
</tr>
|
||||||
) : (
|
) : (
|
||||||
users.map((user) => (
|
users.map((user) => (
|
||||||
<TableRow key={user.id}>
|
<tr key={user.id}>
|
||||||
<TableCell className="font-medium">
|
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
|
||||||
{user.email}
|
{user.email}
|
||||||
</TableCell>
|
</td>
|
||||||
<TableCell>
|
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||||
<Badge
|
<span
|
||||||
variant={
|
className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
|
||||||
user.role === "ADMIN"
|
user.role === "ADMIN"
|
||||||
? "default"
|
? "bg-purple-100 text-purple-800"
|
||||||
: user.role === "AUDITOR"
|
: user.role === "AUDITOR"
|
||||||
? "secondary"
|
? "bg-blue-100 text-blue-800"
|
||||||
: "outline"
|
: "bg-green-100 text-green-800"
|
||||||
}
|
}`}
|
||||||
className="gap-1"
|
|
||||||
data-testid="role-badge"
|
|
||||||
>
|
>
|
||||||
{user.role === "ADMIN" && (
|
|
||||||
<Shield className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
{user.role === "AUDITOR" && (
|
|
||||||
<Eye className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
{user.role}
|
{user.role}
|
||||||
</Badge>
|
</span>
|
||||||
</TableCell>
|
</td>
|
||||||
<TableCell>
|
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||||
<span className="text-muted-foreground text-sm">
|
{/* For future: Add actions like edit, delete, etc. */}
|
||||||
|
<span className="text-gray-400">
|
||||||
No actions available
|
No actions available
|
||||||
</span>
|
</span>
|
||||||
</TableCell>
|
</td>
|
||||||
</TableRow>
|
</tr>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</TableBody>
|
</tbody>
|
||||||
</Table>
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
222
app/globals.css
222
app/globals.css
@ -39,161 +39,101 @@
|
|||||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
--color-sidebar-border: var(--sidebar-border);
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
--color-sidebar-ring: var(--sidebar-ring);
|
--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 {
|
:root {
|
||||||
--radius: 0.625rem;
|
--radius: 0.625rem;
|
||||||
--background: oklch(1 0 0);
|
--background: 255 255 255;
|
||||||
--foreground: oklch(0.145 0 0);
|
--foreground: 15 23 42;
|
||||||
--card: oklch(1 0 0);
|
--card: 255 255 255;
|
||||||
--card-foreground: oklch(0.145 0 0);
|
--card-foreground: 15 23 42;
|
||||||
--popover: oklch(1 0 0);
|
--popover: 255 255 255;
|
||||||
--popover-foreground: oklch(0.145 0 0);
|
--popover-foreground: 15 23 42;
|
||||||
--primary: oklch(0.5 0.2 240);
|
--primary: 0 123 255;
|
||||||
--primary-foreground: oklch(0.98 0 0);
|
--primary-foreground: 255 255 255;
|
||||||
--secondary: oklch(0.97 0 0);
|
--secondary: 245 245 245;
|
||||||
--secondary-foreground: oklch(0.205 0 0);
|
--secondary-foreground: 51 51 51;
|
||||||
--muted: oklch(0.97 0 0);
|
--muted: 248 250 252;
|
||||||
--muted-foreground: oklch(0.45 0 0);
|
--muted-foreground: 100 116 139;
|
||||||
--accent: oklch(0.97 0 0);
|
--accent: 245 245 245;
|
||||||
--accent-foreground: oklch(0.15 0 0);
|
--accent-foreground: 51 51 51;
|
||||||
--destructive: oklch(0.55 0.245 27.325);
|
--destructive: 239 68 68;
|
||||||
--border: oklch(0.85 0 0);
|
--border: 229 231 235;
|
||||||
--input: oklch(0.85 0 0);
|
--input: 229 231 235;
|
||||||
--ring: oklch(0.6 0 0);
|
--ring: 0 123 255;
|
||||||
--chart-1: oklch(0.646 0.222 41.116);
|
--chart-1: 0 123 255;
|
||||||
--chart-2: oklch(0.6 0.118 184.704);
|
--chart-2: 255 20 147;
|
||||||
--chart-3: oklch(0.398 0.07 227.392);
|
--chart-3: 50 205 50;
|
||||||
--chart-4: oklch(0.828 0.189 84.429);
|
--chart-4: 138 43 226;
|
||||||
--chart-5: oklch(0.769 0.188 70.08);
|
--chart-5: 255 215 0;
|
||||||
--sidebar: oklch(0.985 0 0);
|
--sidebar: 248 250 252;
|
||||||
--sidebar-foreground: oklch(0.145 0 0);
|
--sidebar-foreground: 15 23 42;
|
||||||
--sidebar-primary: oklch(0.205 0 0);
|
--sidebar-primary: 0 123 255;
|
||||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
--sidebar-primary-foreground: 255 255 255;
|
||||||
--sidebar-accent: oklch(0.97 0 0);
|
--sidebar-accent: 245 245 245;
|
||||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
--sidebar-accent-foreground: 51 51 51;
|
||||||
--sidebar-border: oklch(0.922 0 0);
|
--sidebar-border: 229 231 235;
|
||||||
--sidebar-ring: oklch(0.708 0 0);
|
--sidebar-ring: 0 123 255;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark {
|
.dark {
|
||||||
--background: oklch(0.145 0 0);
|
--background: 15 23 42;
|
||||||
--foreground: oklch(0.985 0 0);
|
--foreground: 248 250 252;
|
||||||
--card: oklch(0.205 0 0);
|
--card: 30 41 59;
|
||||||
--card-foreground: oklch(0.985 0 0);
|
--card-foreground: 248 250 252;
|
||||||
--popover: oklch(0.205 0 0);
|
--popover: 30 41 59;
|
||||||
--popover-foreground: oklch(0.985 0 0);
|
--popover-foreground: 248 250 252;
|
||||||
--primary: oklch(0.7 0.2 240);
|
--primary: 59 130 246;
|
||||||
--primary-foreground: oklch(0.15 0 0);
|
--primary-foreground: 15 23 42;
|
||||||
--secondary: oklch(0.269 0 0);
|
--secondary: 51 65 85;
|
||||||
--secondary-foreground: oklch(0.985 0 0);
|
--secondary-foreground: 248 250 252;
|
||||||
--muted: oklch(0.269 0 0);
|
--muted: 51 65 85;
|
||||||
--muted-foreground: oklch(0.75 0 0);
|
--muted-foreground: 148 163 184;
|
||||||
--accent: oklch(0.269 0 0);
|
--accent: 51 65 85;
|
||||||
--accent-foreground: oklch(0.985 0 0);
|
--accent-foreground: 248 250 252;
|
||||||
--destructive: oklch(0.75 0.191 22.216);
|
--destructive: 248 113 113;
|
||||||
--border: oklch(1 0 0 / 25%);
|
--border: 51 65 85;
|
||||||
--input: oklch(1 0 0 / 30%);
|
--input: 51 65 85;
|
||||||
--ring: oklch(0.75 0 0);
|
--ring: 59 130 246;
|
||||||
--chart-1: oklch(0.488 0.243 264.376);
|
--chart-1: 59 130 246;
|
||||||
--chart-2: oklch(0.696 0.17 162.48);
|
--chart-2: 236 72 153;
|
||||||
--chart-3: oklch(0.769 0.188 70.08);
|
--chart-3: 34 197 94;
|
||||||
--chart-4: oklch(0.627 0.265 303.9);
|
--chart-4: 147 51 234;
|
||||||
--chart-5: oklch(0.645 0.246 16.439);
|
--chart-5: 251 191 36;
|
||||||
--sidebar: oklch(0.205 0 0);
|
--sidebar: 30 41 59;
|
||||||
--sidebar-foreground: oklch(0.985 0 0);
|
--sidebar-foreground: 248 250 252;
|
||||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
--sidebar-primary: 59 130 246;
|
||||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
--sidebar-primary-foreground: 248 250 252;
|
||||||
--sidebar-accent: oklch(0.269 0 0);
|
--sidebar-accent: 51 65 85;
|
||||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
--sidebar-accent-foreground: 248 250 252;
|
||||||
--sidebar-border: oklch(1 0 0 / 10%);
|
--sidebar-border: 51 65 85;
|
||||||
--sidebar-ring: oklch(0.556 0 0);
|
--sidebar-ring: 59 130 246;
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
* {
|
* {
|
||||||
@apply border-border outline-ring/50 selection:bg-primary/30 selection:text-primary-foreground;
|
@apply border-border outline-ring/50;
|
||||||
}
|
}
|
||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground;
|
@apply bg-gray-50 text-gray-900;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Line clamp utility */
|
/* Apple-style scrollbars */
|
||||||
.line-clamp-2 {
|
::-webkit-scrollbar {
|
||||||
display: -webkit-box;
|
width: 8px;
|
||||||
-webkit-line-clamp: 2;
|
height: 8px;
|
||||||
-webkit-box-orient: vertical;
|
}
|
||||||
overflow: hidden;
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: rgba(0, 0, 0, 0.2);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: rgba(0, 0, 0, 0.3);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
128
app/layout.tsx
128
app/layout.tsx
@ -1,79 +1,12 @@
|
|||||||
// Main app layout with basic global style
|
// Main app layout with basic global style
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import type { ReactNode } from "react";
|
import { ReactNode } from "react";
|
||||||
import { Toaster } from "@/components/ui/sonner";
|
|
||||||
import { Providers } from "./providers";
|
import { Providers } from "./providers";
|
||||||
|
|
||||||
export const metadata = {
|
export const metadata = {
|
||||||
title: "LiveDash - AI-Powered Customer Conversation Analytics",
|
title: "LiveDash-Node",
|
||||||
description:
|
description:
|
||||||
"Transform customer conversations into actionable insights with advanced AI sentiment analysis, automated categorization, and real-time analytics. Turn every conversation into competitive intelligence.",
|
"Multi-tenant dashboard system for tracking chat session metrics",
|
||||||
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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
icons: {
|
icons: {
|
||||||
icon: [
|
icon: [
|
||||||
{ url: "/favicon.ico", sizes: "32x32", type: "image/x-icon" },
|
{ url: "/favicon.ico", sizes: "32x32", type: "image/x-icon" },
|
||||||
@ -82,64 +15,13 @@ export const metadata = {
|
|||||||
apple: "/icon-192.svg",
|
apple: "/icon-192.svg",
|
||||||
},
|
},
|
||||||
manifest: "/manifest.json",
|
manifest: "/manifest.json",
|
||||||
other: {
|
|
||||||
"msapplication-TileColor": "#2563eb",
|
|
||||||
"theme-color": "#ffffff",
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
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 (
|
return (
|
||||||
<html lang="en" suppressHydrationWarning>
|
<html lang="en">
|
||||||
<head>
|
<body className="bg-gray-100 min-h-screen font-sans">
|
||||||
<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>
|
|
||||||
<Providers>{children}</Providers>
|
<Providers>{children}</Providers>
|
||||||
<Toaster />
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,270 +1,59 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { BarChart3, Loader2, Shield, Zap } from "lucide-react";
|
import { useState } from "react";
|
||||||
import Image from "next/image";
|
|
||||||
import Link from "next/link";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { signIn } from "next-auth/react";
|
import { signIn } from "next-auth/react";
|
||||||
import { useId, useState } from "react";
|
import { useRouter } from "next/navigation";
|
||||||
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";
|
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const emailId = useId();
|
|
||||||
const emailHelpId = useId();
|
|
||||||
const passwordId = useId();
|
|
||||||
const passwordHelpId = useId();
|
|
||||||
const loadingStatusId = useId();
|
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
async function handleLogin(e: React.FormEvent) {
|
async function handleLogin(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setIsLoading(true);
|
|
||||||
setError("");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await signIn("credentials", {
|
const res = await signIn("credentials", {
|
||||||
email,
|
email,
|
||||||
password,
|
password,
|
||||||
redirect: false,
|
redirect: false,
|
||||||
});
|
});
|
||||||
|
if (res?.ok) router.push("/dashboard");
|
||||||
if (res?.ok) {
|
else setError("Invalid credentials.");
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex">
|
<div className="max-w-md mx-auto mt-24 bg-white rounded-xl p-8 shadow">
|
||||||
{/* Left side - Branding and Features */}
|
<h1 className="text-2xl font-bold mb-6">Login</h1>
|
||||||
<div className="hidden lg:flex lg:flex-1 bg-linear-to-br from-primary/10 via-primary/5 to-background relative overflow-hidden">
|
{error && <div className="text-red-600 mb-3">{error}</div>}
|
||||||
<div className="absolute inset-0 bg-linear-to-br from-primary/5 to-transparent" />
|
<form onSubmit={handleLogin} className="flex flex-col gap-4">
|
||||||
<div className="absolute -top-24 -left-24 h-96 w-96 rounded-full bg-primary/10 blur-3xl" />
|
<input
|
||||||
<div className="absolute -bottom-24 -right-24 h-96 w-96 rounded-full bg-primary/5 blur-3xl" />
|
className="border px-3 py-2 rounded"
|
||||||
|
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* 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"
|
type="email"
|
||||||
placeholder="name@company.com"
|
placeholder="Email"
|
||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
disabled={isLoading}
|
|
||||||
required
|
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">
|
<input
|
||||||
Enter your company email address
|
className="border px-3 py-2 rounded"
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor={passwordId}>Password</Label>
|
|
||||||
<Input
|
|
||||||
id={passwordId}
|
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Enter your password"
|
placeholder="Password"
|
||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
disabled={isLoading}
|
|
||||||
required
|
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">
|
<button className="bg-blue-600 text-white rounded py-2" type="submit">
|
||||||
Enter your account password
|
Login
|
||||||
</div>
|
</button>
|
||||||
</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>
|
</form>
|
||||||
|
<div className="mt-4 text-center">
|
||||||
<div className="mt-6 space-y-4">
|
<a href="/register" className="text-blue-600 underline">
|
||||||
<div className="text-center">
|
Register company
|
||||||
<Link
|
</a>
|
||||||
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'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>
|
||||||
|
<div className="mt-2 text-center">
|
||||||
|
<a href="/forgot-password" className="text-blue-600 underline">
|
||||||
|
Forgot password?
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
471
app/page.tsx
471
app/page.tsx
@ -1,466 +1,9 @@
|
|||||||
"use client";
|
import { getServerSession } from "next-auth";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { authOptions } from "./api/auth/[...nextauth]/route";
|
||||||
|
|
||||||
import {
|
export default async function HomePage() {
|
||||||
ArrowRight,
|
const session = await getServerSession(authOptions);
|
||||||
BarChart3,
|
if (session?.user) redirect("/dashboard");
|
||||||
Brain,
|
else redirect("/login");
|
||||||
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>© 2024 Notso AI. All rights reserved.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</footer>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,18 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { SessionProvider } from "next-auth/react";
|
import { SessionProvider } from "next-auth/react";
|
||||||
import type { ReactNode } from "react";
|
import { ReactNode } from "react";
|
||||||
import { ThemeProvider } from "@/components/theme-provider";
|
|
||||||
|
|
||||||
export function Providers({ children }: { children: ReactNode }) {
|
export function Providers({ children }: { children: ReactNode }) {
|
||||||
// Including error handling and refetch interval for better user experience
|
// Including error handling and refetch interval for better user experience
|
||||||
return (
|
return (
|
||||||
<ThemeProvider
|
|
||||||
attribute="class"
|
|
||||||
defaultTheme="system"
|
|
||||||
enableSystem
|
|
||||||
disableTransitionOnChange
|
|
||||||
>
|
|
||||||
<SessionProvider
|
<SessionProvider
|
||||||
// Re-fetch session every 30 minutes (reduced from 10)
|
// Re-fetch session every 30 minutes (reduced from 10)
|
||||||
refetchInterval={30 * 60}
|
refetchInterval={30 * 60}
|
||||||
@ -20,6 +13,5 @@ export function Providers({ children }: { children: ReactNode }) {
|
|||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</SessionProvider>
|
</SessionProvider>
|
||||||
</ThemeProvider>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
export default function RegisterPage() {
|
export default function RegisterPage() {
|
||||||
const [email, setEmail] = useState<string>("");
|
const [email, setEmail] = useState<string>("");
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { useState, Suspense } from "react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { Suspense, useState } from "react";
|
|
||||||
|
|
||||||
// Component that uses useSearchParams wrapped in Suspense
|
// Component that uses useSearchParams wrapped in Suspense
|
||||||
function ResetPasswordForm() {
|
function ResetPasswordForm() {
|
||||||
|
|||||||
74
biome.json
74
biome.json
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,11 +1,11 @@
|
|||||||
import { PrismaClient } from "@prisma/client";
|
import { PrismaClient } from '@prisma/client';
|
||||||
import { ProcessingStatusManager } from "./lib/processingStatusManager";
|
import { ProcessingStatusManager } from './lib/processingStatusManager';
|
||||||
|
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
async function checkRefactoredPipelineStatus() {
|
async function checkRefactoredPipelineStatus() {
|
||||||
try {
|
try {
|
||||||
console.log("=== REFACTORED PIPELINE STATUS ===\n");
|
console.log('=== REFACTORED PIPELINE STATUS ===\n');
|
||||||
|
|
||||||
// Get pipeline status using the new system
|
// Get pipeline status using the new system
|
||||||
const pipelineStatus = await ProcessingStatusManager.getPipelineStatus();
|
const pipelineStatus = await ProcessingStatusManager.getPipelineStatus();
|
||||||
@ -13,13 +13,7 @@ async function checkRefactoredPipelineStatus() {
|
|||||||
console.log(`Total Sessions: ${pipelineStatus.totalSessions}\n`);
|
console.log(`Total Sessions: ${pipelineStatus.totalSessions}\n`);
|
||||||
|
|
||||||
// Display status for each stage
|
// Display status for each stage
|
||||||
const stages = [
|
const stages = ['CSV_IMPORT', 'TRANSCRIPT_FETCH', 'SESSION_CREATION', 'AI_ANALYSIS', 'QUESTION_EXTRACTION'];
|
||||||
"CSV_IMPORT",
|
|
||||||
"TRANSCRIPT_FETCH",
|
|
||||||
"SESSION_CREATION",
|
|
||||||
"AI_ANALYSIS",
|
|
||||||
"QUESTION_EXTRACTION",
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const stage of stages) {
|
for (const stage of stages) {
|
||||||
console.log(`${stage}:`);
|
console.log(`${stage}:`);
|
||||||
@ -36,11 +30,11 @@ async function checkRefactoredPipelineStatus() {
|
|||||||
console.log(` COMPLETED: ${completed}`);
|
console.log(` COMPLETED: ${completed}`);
|
||||||
console.log(` FAILED: ${failed}`);
|
console.log(` FAILED: ${failed}`);
|
||||||
console.log(` SKIPPED: ${skipped}`);
|
console.log(` SKIPPED: ${skipped}`);
|
||||||
console.log("");
|
console.log('');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show what needs processing
|
// Show what needs processing
|
||||||
console.log("=== WHAT NEEDS PROCESSING ===");
|
console.log('=== WHAT NEEDS PROCESSING ===');
|
||||||
|
|
||||||
for (const stage of stages) {
|
for (const stage of stages) {
|
||||||
const stageData = pipelineStatus.pipeline[stage] || {};
|
const stageData = pipelineStatus.pipeline[stage] || {};
|
||||||
@ -55,36 +49,27 @@ async function checkRefactoredPipelineStatus() {
|
|||||||
// Show failed sessions if any
|
// Show failed sessions if any
|
||||||
const failedSessions = await ProcessingStatusManager.getFailedSessions();
|
const failedSessions = await ProcessingStatusManager.getFailedSessions();
|
||||||
if (failedSessions.length > 0) {
|
if (failedSessions.length > 0) {
|
||||||
console.log("\n=== FAILED SESSIONS ===");
|
console.log('\n=== FAILED SESSIONS ===');
|
||||||
failedSessions.slice(0, 5).forEach((failure) => {
|
failedSessions.slice(0, 5).forEach(failure => {
|
||||||
console.log(
|
console.log(` ${failure.session.import?.externalSessionId || failure.sessionId}: ${failure.stage} - ${failure.errorMessage}`);
|
||||||
` ${failure.session.import?.externalSessionId || failure.sessionId}: ${failure.stage} - ${failure.errorMessage}`
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (failedSessions.length > 5) {
|
if (failedSessions.length > 5) {
|
||||||
console.log(
|
console.log(` ... and ${failedSessions.length - 5} more failed sessions`);
|
||||||
` ... and ${failedSessions.length - 5} more failed sessions`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show sessions ready for AI processing
|
// Show sessions ready for AI processing
|
||||||
const readyForAI =
|
const readyForAI = await ProcessingStatusManager.getSessionsNeedingProcessing('AI_ANALYSIS', 5);
|
||||||
await ProcessingStatusManager.getSessionsNeedingProcessing(
|
|
||||||
"AI_ANALYSIS",
|
|
||||||
5
|
|
||||||
);
|
|
||||||
if (readyForAI.length > 0) {
|
if (readyForAI.length > 0) {
|
||||||
console.log("\n=== SESSIONS READY FOR AI PROCESSING ===");
|
console.log('\n=== SESSIONS READY FOR AI PROCESSING ===');
|
||||||
readyForAI.forEach((status) => {
|
readyForAI.forEach(status => {
|
||||||
console.log(
|
console.log(` ${status.session.import?.externalSessionId || status.sessionId} (created: ${status.session.createdAt})`);
|
||||||
` ${status.session.import?.externalSessionId || status.sessionId} (created: ${status.session.createdAt})`
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error checking pipeline status:", error);
|
console.error('Error checking pipeline status:', error);
|
||||||
} finally {
|
} finally {
|
||||||
await prisma.$disconnect();
|
await prisma.$disconnect();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import Chart from "chart.js/auto";
|
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
import Chart from "chart.js/auto";
|
||||||
import { getLocalizedLanguageName } from "../lib/localization"; // Corrected import path
|
import { getLocalizedLanguageName } from "../lib/localization"; // Corrected import path
|
||||||
|
|
||||||
interface SessionsData {
|
interface SessionsData {
|
||||||
@ -128,9 +128,9 @@ export function SentimentChart({ sentimentData }: SentimentChartProps) {
|
|||||||
sentimentData.negative,
|
sentimentData.negative,
|
||||||
],
|
],
|
||||||
backgroundColor: [
|
backgroundColor: [
|
||||||
"rgba(34, 197, 94, 0.8)", // green
|
"rgba(37, 99, 235, 0.8)", // blue (primary)
|
||||||
"rgba(249, 115, 22, 0.8)", // orange
|
"rgba(107, 114, 128, 0.8)", // gray
|
||||||
"rgba(239, 68, 68, 0.8)", // red
|
"rgba(236, 72, 153, 0.8)", // pink
|
||||||
],
|
],
|
||||||
borderWidth: 1,
|
borderWidth: 1,
|
||||||
},
|
},
|
||||||
@ -196,12 +196,12 @@ export function LanguagePieChart({ languages }: LanguagePieChartProps) {
|
|||||||
{
|
{
|
||||||
data,
|
data,
|
||||||
backgroundColor: [
|
backgroundColor: [
|
||||||
"rgba(59, 130, 246, 0.8)",
|
"rgba(37, 99, 235, 0.8)", // blue (primary)
|
||||||
"rgba(16, 185, 129, 0.8)",
|
"rgba(107, 114, 128, 0.8)", // gray
|
||||||
"rgba(249, 115, 22, 0.8)",
|
"rgba(236, 72, 153, 0.8)", // pink
|
||||||
"rgba(236, 72, 153, 0.8)",
|
"rgba(34, 197, 94, 0.8)", // lime green
|
||||||
"rgba(139, 92, 246, 0.8)",
|
"rgba(168, 85, 247, 0.8)", // purple
|
||||||
"rgba(107, 114, 128, 0.8)",
|
"rgba(251, 191, 36, 0.8)", // yellow
|
||||||
],
|
],
|
||||||
borderWidth: 1,
|
borderWidth: 1,
|
||||||
},
|
},
|
||||||
@ -219,7 +219,7 @@ export function LanguagePieChart({ languages }: LanguagePieChartProps) {
|
|||||||
},
|
},
|
||||||
tooltip: {
|
tooltip: {
|
||||||
callbacks: {
|
callbacks: {
|
||||||
label: (context) => {
|
label: function (context) {
|
||||||
const label = context.label || "";
|
const label = context.label || "";
|
||||||
const value = context.formattedValue || "";
|
const value = context.formattedValue || "";
|
||||||
const index = context.dataIndex;
|
const index = context.dataIndex;
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useId, useState } from "react";
|
import { useState, useEffect, useRef, memo } from "react";
|
||||||
|
|
||||||
interface DateRangePickerProps {
|
interface DateRangePickerProps {
|
||||||
minDate: string;
|
minDate: string;
|
||||||
@ -10,26 +10,36 @@ interface DateRangePickerProps {
|
|||||||
initialEndDate?: string;
|
initialEndDate?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function DateRangePicker({
|
function DateRangePicker({
|
||||||
minDate,
|
minDate,
|
||||||
maxDate,
|
maxDate,
|
||||||
onDateRangeChange,
|
onDateRangeChange,
|
||||||
initialStartDate,
|
initialStartDate,
|
||||||
initialEndDate,
|
initialEndDate,
|
||||||
}: DateRangePickerProps) {
|
}: DateRangePickerProps) {
|
||||||
const startDateId = useId();
|
|
||||||
const endDateId = useId();
|
|
||||||
const [startDate, setStartDate] = useState(initialStartDate || minDate);
|
const [startDate, setStartDate] = useState(initialStartDate || minDate);
|
||||||
const [endDate, setEndDate] = useState(initialEndDate || maxDate);
|
const [endDate, setEndDate] = useState(initialEndDate || maxDate);
|
||||||
|
const isInitializedRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Only notify parent component when dates change, not when the callback changes
|
// Update local state when props change (e.g., when date range is loaded from API)
|
||||||
|
if (initialStartDate && initialStartDate !== startDate) {
|
||||||
|
setStartDate(initialStartDate);
|
||||||
|
}
|
||||||
|
if (initialEndDate && initialEndDate !== endDate) {
|
||||||
|
setEndDate(initialEndDate);
|
||||||
|
}
|
||||||
|
}, [initialStartDate, initialEndDate]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Only notify parent component after initial render and when dates actually change
|
||||||
|
// This prevents the infinite loop by not including onDateRangeChange in dependencies
|
||||||
|
if (isInitializedRef.current) {
|
||||||
onDateRangeChange(startDate, endDate);
|
onDateRangeChange(startDate, endDate);
|
||||||
}, [
|
} else {
|
||||||
startDate,
|
isInitializedRef.current = true;
|
||||||
endDate, // Only notify parent component when dates change, not when the callback changes
|
}
|
||||||
onDateRangeChange,
|
}, [startDate, endDate]);
|
||||||
]);
|
|
||||||
|
|
||||||
const handleStartDateChange = (newStartDate: string) => {
|
const handleStartDateChange = (newStartDate: string) => {
|
||||||
// Ensure start date is not before min date
|
// Ensure start date is not before min date
|
||||||
@ -69,11 +79,10 @@ export default function DateRangePicker({
|
|||||||
const setLast30Days = () => {
|
const setLast30Days = () => {
|
||||||
const thirtyDaysAgo = new Date();
|
const thirtyDaysAgo = new Date();
|
||||||
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
||||||
const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().split("T")[0];
|
const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().split('T')[0];
|
||||||
|
|
||||||
// Use the later of 30 days ago or minDate
|
// Use the later of 30 days ago or minDate
|
||||||
const newStartDate =
|
const newStartDate = thirtyDaysAgoStr > minDate ? thirtyDaysAgoStr : minDate;
|
||||||
thirtyDaysAgoStr > minDate ? thirtyDaysAgoStr : minDate;
|
|
||||||
setStartDate(newStartDate);
|
setStartDate(newStartDate);
|
||||||
setEndDate(maxDate);
|
setEndDate(maxDate);
|
||||||
};
|
};
|
||||||
@ -81,7 +90,7 @@ export default function DateRangePicker({
|
|||||||
const setLast7Days = () => {
|
const setLast7Days = () => {
|
||||||
const sevenDaysAgo = new Date();
|
const sevenDaysAgo = new Date();
|
||||||
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
|
||||||
const sevenDaysAgoStr = sevenDaysAgo.toISOString().split("T")[0];
|
const sevenDaysAgoStr = sevenDaysAgo.toISOString().split('T')[0];
|
||||||
|
|
||||||
// Use the later of 7 days ago or minDate
|
// Use the later of 7 days ago or minDate
|
||||||
const newStartDate = sevenDaysAgoStr > minDate ? sevenDaysAgoStr : minDate;
|
const newStartDate = sevenDaysAgoStr > minDate ? sevenDaysAgoStr : minDate;
|
||||||
@ -93,17 +102,17 @@ export default function DateRangePicker({
|
|||||||
<div className="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
|
<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-4 items-start sm:items-center">
|
||||||
<div className="flex flex-col sm:flex-row gap-3 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:
|
Date Range:
|
||||||
</span>
|
</label>
|
||||||
|
|
||||||
<div className="flex flex-col sm:flex-row gap-2 items-start sm:items-center">
|
<div className="flex flex-col sm:flex-row gap-2 items-start sm:items-center">
|
||||||
<div className="flex items-center gap-2">
|
<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:
|
From:
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id={startDateId}
|
id="start-date"
|
||||||
type="date"
|
type="date"
|
||||||
value={startDate}
|
value={startDate}
|
||||||
min={minDate}
|
min={minDate}
|
||||||
@ -114,11 +123,11 @@ export default function DateRangePicker({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<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:
|
To:
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id={endDateId}
|
id="end-date"
|
||||||
type="date"
|
type="date"
|
||||||
value={endDate}
|
value={endDate}
|
||||||
min={minDate}
|
min={minDate}
|
||||||
@ -132,21 +141,18 @@ export default function DateRangePicker({
|
|||||||
|
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={setLast7Days}
|
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"
|
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
|
Last 7 days
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={setLast30Days}
|
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"
|
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
|
Last 30 days
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={resetToFullRange}
|
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"
|
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"
|
||||||
>
|
>
|
||||||
@ -156,9 +162,11 @@ export default function DateRangePicker({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-2 text-xs text-gray-500">
|
<div className="mt-2 text-xs text-gray-500">
|
||||||
Available data: {new Date(minDate).toLocaleDateString()} -{" "}
|
Available data: {new Date(minDate).toLocaleDateString()} - {new Date(maxDate).toLocaleDateString()}
|
||||||
{new Date(maxDate).toLocaleDateString()}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Export memoized component as default
|
||||||
|
export default memo(DateRangePicker);
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Chart, { type BubbleDataPoint, type Point } from "chart.js/auto";
|
import { useRef, useEffect } from "react";
|
||||||
import { useEffect, useRef } from "react";
|
import Chart, { Point, BubbleDataPoint } from "chart.js/auto";
|
||||||
|
|
||||||
interface DonutChartProps {
|
interface DonutChartProps {
|
||||||
data: {
|
data: {
|
||||||
@ -73,7 +73,7 @@ export default function DonutChart({ data, centerText }: DonutChartProps) {
|
|||||||
},
|
},
|
||||||
tooltip: {
|
tooltip: {
|
||||||
callbacks: {
|
callbacks: {
|
||||||
label: (context) => {
|
label: function (context) {
|
||||||
const label = context.label || "";
|
const label = context.label || "";
|
||||||
const value = context.formattedValue;
|
const value = context.formattedValue;
|
||||||
const total = context.chart.data.datasets[0].data.reduce(
|
const total = context.chart.data.datasets[0].data.reduce(
|
||||||
@ -106,7 +106,7 @@ export default function DonutChart({ data, centerText }: DonutChartProps) {
|
|||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
id: "centerText",
|
id: "centerText",
|
||||||
beforeDraw: (chart: Chart<"doughnut">) => {
|
beforeDraw: function (chart: Chart<"doughnut">) {
|
||||||
const height = chart.height;
|
const height = chart.height;
|
||||||
const ctx = chart.ctx;
|
const ctx = chart.ctx;
|
||||||
ctx.restore();
|
ctx.restore();
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import dynamic from "next/dynamic";
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import dynamic from "next/dynamic";
|
||||||
import "leaflet/dist/leaflet.css";
|
import "leaflet/dist/leaflet.css";
|
||||||
import * as countryCoder from "@rapideditor/country-coder";
|
import * as countryCoder from "@rapideditor/country-coder";
|
||||||
|
|
||||||
@ -48,7 +48,7 @@ const getCountryCoordinates = (): Record<string, [number, number]> => {
|
|||||||
BG: [42.7339, 25.4858],
|
BG: [42.7339, 25.4858],
|
||||||
HR: [45.1, 15.2],
|
HR: [45.1, 15.2],
|
||||||
SK: [48.669, 19.699],
|
SK: [48.669, 19.699],
|
||||||
SI: [46.1512, 14.9955],
|
SI: [46.1512, 14.9955]
|
||||||
};
|
};
|
||||||
// This function now primarily returns fallbacks.
|
// This function now primarily returns fallbacks.
|
||||||
// The actual fetching using @rapideditor/country-coder will be in the component's useEffect.
|
// The actual fetching using @rapideditor/country-coder will be in the component's useEffect.
|
||||||
@ -60,10 +60,10 @@ const DEFAULT_COORDINATES = getCountryCoordinates();
|
|||||||
|
|
||||||
// Dynamically import the Map component to avoid SSR issues
|
// Dynamically import the Map component to avoid SSR issues
|
||||||
// This ensures the component only loads on the client side
|
// This ensures the component only loads on the client side
|
||||||
const CountryMapComponent = dynamic(() => import("./Map"), {
|
const Map = dynamic(() => import("./Map"), {
|
||||||
ssr: false,
|
ssr: false,
|
||||||
loading: () => (
|
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...
|
Loading map...
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
@ -95,7 +95,7 @@ export default function GeographicMap({
|
|||||||
|
|
||||||
if (!countryCoords) {
|
if (!countryCoords) {
|
||||||
const feature = countryCoder.feature(code);
|
const feature = countryCoder.feature(code);
|
||||||
if (feature?.geometry) {
|
if (feature && feature.geometry) {
|
||||||
if (feature.geometry.type === "Point") {
|
if (feature.geometry.type === "Point") {
|
||||||
const [lon, lat] = feature.geometry.coordinates;
|
const [lon, lat] = feature.geometry.coordinates;
|
||||||
countryCoords = [lat, lon]; // Leaflet expects [lat, lon]
|
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
|
// Show loading state during SSR or until client-side rendering takes over
|
||||||
if (!isClient) {
|
if (!isClient) {
|
||||||
return (
|
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...
|
Loading map...
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -160,9 +160,9 @@ export default function GeographicMap({
|
|||||||
return (
|
return (
|
||||||
<div style={{ height: `${height}px`, width: "100%" }} className="relative">
|
<div style={{ height: `${height}px`, width: "100%" }} className="relative">
|
||||||
{countryData.length > 0 ? (
|
{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
|
No geographic data available
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -1,9 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { CircleMarker, MapContainer, TileLayer, Tooltip } from "react-leaflet";
|
import { MapContainer, TileLayer, CircleMarker, Tooltip } from "react-leaflet";
|
||||||
import "leaflet/dist/leaflet.css";
|
import "leaflet/dist/leaflet.css";
|
||||||
import { useTheme } from "next-themes";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { getLocalizedCountryName } from "../lib/localization";
|
import { getLocalizedCountryName } from "../lib/localization";
|
||||||
|
|
||||||
interface CountryData {
|
interface CountryData {
|
||||||
@ -17,30 +15,7 @@ interface MapProps {
|
|||||||
maxCount: number;
|
maxCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const CountryMap = ({ countryData, maxCount }: MapProps) => {
|
const Map = ({ 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
|
|
||||||
? '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>'
|
|
||||||
: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>';
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<MapContainer
|
<MapContainer
|
||||||
center={[30, 0]}
|
center={[30, 0]}
|
||||||
@ -49,28 +24,29 @@ const CountryMap = ({ countryData, maxCount }: MapProps) => {
|
|||||||
scrollWheelZoom={false}
|
scrollWheelZoom={false}
|
||||||
style={{ height: "100%", width: "100%", borderRadius: "0.5rem" }}
|
style={{ height: "100%", width: "100%", borderRadius: "0.5rem" }}
|
||||||
>
|
>
|
||||||
<TileLayer attribution={tileLayerAttribution} url={tileLayerUrl} />
|
<TileLayer
|
||||||
|
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
|
||||||
|
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||||
|
/>
|
||||||
{countryData.map((country) => (
|
{countryData.map((country) => (
|
||||||
<CircleMarker
|
<CircleMarker
|
||||||
key={country.code}
|
key={country.code}
|
||||||
center={country.coordinates}
|
center={country.coordinates}
|
||||||
radius={5 + (country.count / maxCount) * 20}
|
radius={5 + (country.count / maxCount) * 20}
|
||||||
pathOptions={{
|
pathOptions={{
|
||||||
fillColor: "hsl(var(--primary))",
|
fillColor: "#3B82F6",
|
||||||
color: "hsl(var(--primary))",
|
color: "#1E40AF",
|
||||||
weight: 2,
|
weight: 1,
|
||||||
opacity: 0.9,
|
opacity: 0.8,
|
||||||
fillOpacity: 0.6,
|
fillOpacity: 0.6,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<div className="p-2 bg-background border border-border rounded-md shadow-md">
|
<div className="p-1">
|
||||||
<div className="font-medium text-foreground">
|
<div className="font-medium">
|
||||||
{getLocalizedCountryName(country.code)}
|
{getLocalizedCountryName(country.code)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm text-muted-foreground">
|
<div className="text-sm">Sessions: {country.count}</div>
|
||||||
Sessions: {country.count}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</CircleMarker>
|
</CircleMarker>
|
||||||
@ -79,4 +55,4 @@ const CountryMap = ({ countryData, maxCount }: MapProps) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default CountryMap;
|
export default Map;
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { Message } from "../lib/types";
|
import { Message } from "../lib/types";
|
||||||
|
|
||||||
interface MessageViewerProps {
|
interface MessageViewerProps {
|
||||||
messages: Message[];
|
messages: Message[];
|
||||||
@ -49,9 +49,7 @@ export default function MessageViewer({ messages }: MessageViewerProps) {
|
|||||||
{message.role}
|
{message.role}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs opacity-75 ml-2">
|
<span className="text-xs opacity-75 ml-2">
|
||||||
{message.timestamp
|
{message.timestamp ? new Date(message.timestamp).toLocaleTimeString() : 'No timestamp'}
|
||||||
? new Date(message.timestamp).toLocaleTimeString()
|
|
||||||
: "No timestamp"}
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm whitespace-pre-wrap">
|
<div className="text-sm whitespace-pre-wrap">
|
||||||
@ -65,17 +63,13 @@ export default function MessageViewer({ messages }: MessageViewerProps) {
|
|||||||
<div className="mt-4 pt-3 border-t text-sm text-gray-500">
|
<div className="mt-4 pt-3 border-t text-sm text-gray-500">
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span>
|
<span>
|
||||||
First message:{" "}
|
First message: {messages[0].timestamp ? new Date(messages[0].timestamp).toLocaleString() : 'No timestamp'}
|
||||||
{messages[0].timestamp
|
|
||||||
? new Date(messages[0].timestamp).toLocaleString()
|
|
||||||
: "No timestamp"}
|
|
||||||
</span>
|
</span>
|
||||||
<span>
|
<span>
|
||||||
Last message: {(() => {
|
Last message:{" "}
|
||||||
|
{(() => {
|
||||||
const lastMessage = messages[messages.length - 1];
|
const lastMessage = messages[messages.length - 1];
|
||||||
return lastMessage.timestamp
|
return lastMessage.timestamp ? new Date(lastMessage.timestamp).toLocaleString() : 'No timestamp';
|
||||||
? new Date(lastMessage.timestamp).toLocaleString()
|
|
||||||
: "No timestamp";
|
|
||||||
})()}
|
})()}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
88
components/MetricCard.tsx
Normal file
88
components/MetricCard.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,14 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Bar,
|
|
||||||
BarChart,
|
BarChart,
|
||||||
CartesianGrid,
|
Bar,
|
||||||
ReferenceLine,
|
|
||||||
ResponsiveContainer,
|
|
||||||
Tooltip,
|
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
ReferenceLine,
|
||||||
} from "recharts";
|
} from "recharts";
|
||||||
|
|
||||||
interface ResponseTimeDistributionProps {
|
interface ResponseTimeDistributionProps {
|
||||||
@ -17,19 +17,13 @@ interface ResponseTimeDistributionProps {
|
|||||||
targetResponseTime?: number;
|
targetResponseTime?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TooltipProps {
|
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||||
active?: boolean;
|
|
||||||
payload?: Array<{ value: number; payload: { label: string; count: number } }>;
|
|
||||||
label?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
|
|
||||||
if (active && payload && payload.length) {
|
if (active && payload && payload.length) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border bg-background p-3 shadow-md">
|
<div className="rounded-lg border border-gray-200 bg-white p-3 shadow-md">
|
||||||
<p className="text-sm font-medium">{label}</p>
|
<p className="text-sm font-medium text-gray-900">{label}</p>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-gray-600">
|
||||||
<span className="font-medium text-foreground">
|
<span className="font-medium text-gray-900">
|
||||||
{payload[0].value}
|
{payload[0].value}
|
||||||
</span>{" "}
|
</span>{" "}
|
||||||
responses
|
responses
|
||||||
@ -65,20 +59,18 @@ export default function ResponseTimeDistribution({
|
|||||||
|
|
||||||
// Create chart data
|
// Create chart data
|
||||||
const chartData = bins.map((count, i) => {
|
const chartData = bins.map((count, i) => {
|
||||||
let label: string;
|
let label;
|
||||||
if (i === bins.length - 1 && bins.length < maxTime + 1) {
|
if (i === bins.length - 1 && bins.length < maxTime + 1) {
|
||||||
label = `${i}+ sec`;
|
label = `${i}+ sec`;
|
||||||
} else {
|
} else {
|
||||||
label = `${i}-${i + 1} sec`;
|
label = `${i}-${i + 1} sec`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine color based on response time
|
// Determine color based on response time using cohesive palette
|
||||||
let color: string;
|
let color;
|
||||||
if (i <= 2)
|
if (i <= 2) color = "rgb(37, 99, 235)"; // Blue for fast (primary color)
|
||||||
color = "hsl(var(--chart-1))"; // Green for fast
|
else if (i <= 5) color = "rgb(107, 114, 128)"; // Gray for medium
|
||||||
else if (i <= 5)
|
else color = "rgb(236, 72, 153)"; // Pink for slow
|
||||||
color = "hsl(var(--chart-4))"; // Yellow for medium
|
|
||||||
else color = "hsl(var(--chart-3))"; // Red for slow
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
name: label,
|
name: label,
|
||||||
@ -90,32 +82,29 @@ export default function ResponseTimeDistribution({
|
|||||||
return (
|
return (
|
||||||
<div className="h-64">
|
<div className="h-64">
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
<BarChart
|
<BarChart data={chartData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
|
||||||
data={chartData}
|
|
||||||
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
|
|
||||||
>
|
|
||||||
<CartesianGrid
|
<CartesianGrid
|
||||||
strokeDasharray="3 3"
|
strokeDasharray="3 3"
|
||||||
stroke="hsl(var(--border))"
|
stroke="rgb(229, 231, 235)"
|
||||||
strokeOpacity={0.3}
|
strokeOpacity={0.5}
|
||||||
/>
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="name"
|
dataKey="name"
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="rgb(100, 116, 139)"
|
||||||
fontSize={12}
|
fontSize={12}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="rgb(100, 116, 139)"
|
||||||
fontSize={12}
|
fontSize={12}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
label={{
|
label={{
|
||||||
value: "Number of Responses",
|
value: 'Number of Responses',
|
||||||
angle: -90,
|
angle: -90,
|
||||||
position: "insideLeft",
|
position: 'insideLeft',
|
||||||
style: { textAnchor: "middle" },
|
style: { textAnchor: 'middle', fill: 'rgb(100, 116, 139)' }
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Tooltip content={<CustomTooltip />} />
|
<Tooltip content={<CustomTooltip />} />
|
||||||
@ -124,27 +113,26 @@ export default function ResponseTimeDistribution({
|
|||||||
dataKey="value"
|
dataKey="value"
|
||||||
radius={[4, 4, 0, 0]}
|
radius={[4, 4, 0, 0]}
|
||||||
fill="hsl(var(--chart-1))"
|
fill="hsl(var(--chart-1))"
|
||||||
maxBarSize={60}
|
|
||||||
>
|
>
|
||||||
{chartData.map((entry, index) => (
|
{chartData.map((entry, index) => (
|
||||||
<Bar key={`cell-${entry.name}-${index}`} fill={entry.color} />
|
<Bar key={`cell-${index}`} fill={entry.color} />
|
||||||
))}
|
))}
|
||||||
</Bar>
|
</Bar>
|
||||||
|
|
||||||
{/* Average line */}
|
{/* Average line */}
|
||||||
<ReferenceLine
|
<ReferenceLine
|
||||||
x={Math.floor(average)}
|
x={Math.floor(average)}
|
||||||
stroke="hsl(var(--primary))"
|
stroke="rgb(0, 123, 255)"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
strokeDasharray="5 5"
|
strokeDasharray="5 5"
|
||||||
label={{
|
label={{
|
||||||
value: `Avg: ${average.toFixed(1)}s`,
|
value: `Avg: ${average.toFixed(1)}s`,
|
||||||
position: "top" as const,
|
position: "top" as const,
|
||||||
style: {
|
style: {
|
||||||
fill: "hsl(var(--primary))",
|
fill: "rgb(0, 123, 255)",
|
||||||
fontSize: "12px",
|
fontSize: "12px",
|
||||||
fontWeight: "500",
|
fontWeight: "500"
|
||||||
},
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@ -152,17 +140,17 @@ export default function ResponseTimeDistribution({
|
|||||||
{targetResponseTime && (
|
{targetResponseTime && (
|
||||||
<ReferenceLine
|
<ReferenceLine
|
||||||
x={Math.floor(targetResponseTime)}
|
x={Math.floor(targetResponseTime)}
|
||||||
stroke="hsl(var(--chart-2))"
|
stroke="rgb(255, 20, 147)"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
strokeDasharray="3 3"
|
strokeDasharray="3 3"
|
||||||
label={{
|
label={{
|
||||||
value: `Target: ${targetResponseTime}s`,
|
value: `Target: ${targetResponseTime}s`,
|
||||||
position: "top" as const,
|
position: "top" as const,
|
||||||
style: {
|
style: {
|
||||||
fill: "hsl(var(--chart-2))",
|
fill: "rgb(255, 20, 147)",
|
||||||
fontSize: "12px",
|
fontSize: "12px",
|
||||||
fontWeight: "500",
|
fontWeight: "500"
|
||||||
},
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -1,13 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { ExternalLink } from "lucide-react";
|
import { ChatSession } from "../lib/types";
|
||||||
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 LanguageDisplay from "./LanguageDisplay";
|
import LanguageDisplay from "./LanguageDisplay";
|
||||||
|
import CountryDisplay from "./CountryDisplay";
|
||||||
|
|
||||||
interface SessionDetailsProps {
|
interface SessionDetailsProps {
|
||||||
session: ChatSession;
|
session: ChatSession;
|
||||||
@ -17,183 +12,160 @@ interface SessionDetailsProps {
|
|||||||
* Component to display session details with formatted country and language names
|
* Component to display session details with formatted country and language names
|
||||||
*/
|
*/
|
||||||
export default function SessionDetails({ session }: SessionDetailsProps) {
|
export default function SessionDetails({ session }: SessionDetailsProps) {
|
||||||
// Using centralized formatCategory utility
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<div className="bg-white p-4 rounded-lg shadow">
|
||||||
<CardHeader>
|
<h3 className="font-bold text-lg mb-3">Session Details</h3>
|
||||||
<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 className="space-y-3">
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Session ID</p>
|
<span className="text-gray-600">Session ID:</span>
|
||||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">
|
<span className="font-medium font-mono text-sm">{session.id}</span>
|
||||||
{session.id.slice(0, 8)}...
|
|
||||||
</code>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Start Time</p>
|
<span className="text-gray-600">Start Time:</span>
|
||||||
<p className="font-medium">
|
<span className="font-medium">
|
||||||
{new Date(session.startTime).toLocaleString()}
|
{new Date(session.startTime).toLocaleString()}
|
||||||
</p>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{session.endTime && (
|
{session.endTime && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">End Time</p>
|
<span className="text-gray-600">End Time:</span>
|
||||||
<p className="font-medium">
|
<span className="font-medium">
|
||||||
{new Date(session.endTime).toLocaleString()}
|
{new Date(session.endTime).toLocaleString()}
|
||||||
</p>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{session.category && (
|
{session.category && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Category</p>
|
<span className="text-gray-600">Category:</span>
|
||||||
<Badge variant="secondary">
|
<span className="font-medium">{session.category}</span>
|
||||||
{formatCategory(session.category)}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{session.language && (
|
{session.language && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Language</p>
|
<span className="text-gray-600">Language:</span>
|
||||||
<div className="flex items-center gap-2">
|
<span className="font-medium">
|
||||||
<LanguageDisplay languageCode={session.language} />
|
<LanguageDisplay languageCode={session.language} />
|
||||||
<Badge variant="outline" className="text-xs">
|
<span className="text-gray-400 text-xs ml-1">
|
||||||
{session.language.toUpperCase()}
|
({session.language.toUpperCase()})
|
||||||
</Badge>
|
</span>
|
||||||
</div>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{session.country && (
|
{session.country && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Country</p>
|
<span className="text-gray-600">Country:</span>
|
||||||
<div className="flex items-center gap-2">
|
<span className="font-medium">
|
||||||
<CountryDisplay countryCode={session.country} />
|
<CountryDisplay countryCode={session.country} />
|
||||||
<Badge variant="outline" className="text-xs">
|
<span className="text-gray-400 text-xs ml-1">
|
||||||
{session.country}
|
({session.country})
|
||||||
</Badge>
|
</span>
|
||||||
</div>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
|
||||||
{session.sentiment !== null && session.sentiment !== undefined && (
|
{session.sentiment !== null && session.sentiment !== undefined && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Sentiment</p>
|
<span className="text-gray-600">Sentiment:</span>
|
||||||
<Badge
|
<span
|
||||||
variant={
|
className={`font-medium capitalize ${
|
||||||
session.sentiment === "positive"
|
session.sentiment === "POSITIVE"
|
||||||
? "default"
|
? "text-green-500"
|
||||||
: session.sentiment === "negative"
|
: session.sentiment === "NEGATIVE"
|
||||||
? "destructive"
|
? "text-red-500"
|
||||||
: "secondary"
|
: "text-orange-500"
|
||||||
}
|
}`}
|
||||||
>
|
>
|
||||||
{session.sentiment.charAt(0).toUpperCase() +
|
{session.sentiment.toLowerCase()}
|
||||||
session.sentiment.slice(1)}
|
</span>
|
||||||
</Badge>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Messages Sent</p>
|
<span className="text-gray-600">Messages Sent:</span>
|
||||||
<p className="font-medium">{session.messagesSent || 0}</p>
|
<span className="font-medium">{session.messagesSent || 0}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
{session.avgResponseTime !== null &&
|
{session.avgResponseTime !== null &&
|
||||||
session.avgResponseTime !== undefined && (
|
session.avgResponseTime !== undefined && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">
|
<span className="text-gray-600">Avg Response Time:</span>
|
||||||
Avg Response Time
|
<span className="font-medium">
|
||||||
</p>
|
|
||||||
<p className="font-medium">
|
|
||||||
{session.avgResponseTime.toFixed(2)}s
|
{session.avgResponseTime.toFixed(2)}s
|
||||||
</p>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{session.escalated !== null && session.escalated !== undefined && (
|
{session.escalated !== null && session.escalated !== undefined && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">Escalated</p>
|
<span className="text-gray-600">Escalated:</span>
|
||||||
<Badge variant={session.escalated ? "destructive" : "default"}>
|
<span
|
||||||
|
className={`font-medium ${session.escalated ? "text-red-500" : "text-green-500"}`}
|
||||||
|
>
|
||||||
{session.escalated ? "Yes" : "No"}
|
{session.escalated ? "Yes" : "No"}
|
||||||
</Badge>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{session.forwardedHr !== null &&
|
{session.forwardedHr !== null && session.forwardedHr !== undefined && (
|
||||||
session.forwardedHr !== undefined && (
|
<div className="flex justify-between border-b pb-2">
|
||||||
<div>
|
<span className="text-gray-600">Forwarded to HR:</span>
|
||||||
<p className="text-sm text-muted-foreground">
|
<span
|
||||||
Forwarded to HR
|
className={`font-medium ${session.forwardedHr ? "text-amber-500" : "text-green-500"}`}
|
||||||
</p>
|
|
||||||
<Badge
|
|
||||||
variant={session.forwardedHr ? "secondary" : "default"}
|
|
||||||
>
|
>
|
||||||
{session.forwardedHr ? "Yes" : "No"}
|
{session.forwardedHr ? "Yes" : "No"}
|
||||||
</Badge>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{session.ipAddress && (
|
{session.ipAddress && (
|
||||||
<div>
|
<div className="flex justify-between border-b pb-2">
|
||||||
<p className="text-sm text-muted-foreground">IP Address</p>
|
<span className="text-gray-600">IP Address:</span>
|
||||||
<code className="text-sm font-mono bg-muted px-2 py-1 rounded">
|
<span className="font-medium font-mono text-sm">
|
||||||
{session.ipAddress}
|
{session.ipAddress}
|
||||||
</code>
|
</span>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{(session.summary || session.initialMsg) && <Separator />}
|
|
||||||
|
|
||||||
{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">
|
|
||||||
{session.summary}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!session.summary && session.initialMsg && (
|
|
||||||
<div>
|
{session.initialMsg && (
|
||||||
<p className="text-sm text-muted-foreground mb-2">
|
<div className="border-b pb-2">
|
||||||
Initial Message
|
<span className="text-gray-600 block mb-1">Initial Message:</span>
|
||||||
</p>
|
<div className="bg-gray-50 p-2 rounded text-sm italic">
|
||||||
<div className="bg-muted p-3 rounded-md text-sm italic">
|
|
||||||
"{session.initialMsg}"
|
"{session.initialMsg}"
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{session.summary && (
|
||||||
|
<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.fullTranscriptUrl && (
|
{session.fullTranscriptUrl && (
|
||||||
<>
|
<div className="flex justify-between pt-2">
|
||||||
<Separator />
|
<span className="text-gray-600">Transcript:</span>
|
||||||
<div>
|
|
||||||
<a
|
<a
|
||||||
href={session.fullTranscriptUrl}
|
href={session.fullTranscriptUrl}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
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"
|
className="text-blue-500 hover:text-blue-700 underline"
|
||||||
aria-label="Open full transcript in new tab"
|
|
||||||
>
|
>
|
||||||
<ExternalLink className="h-4 w-4" aria-hidden="true" />
|
|
||||||
View Full Transcript
|
View Full Transcript
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,12 +1,10 @@
|
|||||||
"use client";
|
"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 Link from "next/link";
|
||||||
|
import Image from "next/image";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { signOut } from "next-auth/react";
|
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
|
// Icons for the sidebar
|
||||||
const DashboardIcon = () => (
|
const DashboardIcon = () => (
|
||||||
@ -17,7 +15,6 @@ const DashboardIcon = () => (
|
|||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
>
|
>
|
||||||
<title>Dashboard</title>
|
|
||||||
<path
|
<path
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeLinejoin="round"
|
strokeLinejoin="round"
|
||||||
@ -53,7 +50,6 @@ const CompanyIcon = () => (
|
|||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
>
|
>
|
||||||
<title>Company</title>
|
|
||||||
<path
|
<path
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeLinejoin="round"
|
strokeLinejoin="round"
|
||||||
@ -71,7 +67,6 @@ const UsersIcon = () => (
|
|||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
>
|
>
|
||||||
<title>Users</title>
|
|
||||||
<path
|
<path
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeLinejoin="round"
|
strokeLinejoin="round"
|
||||||
@ -89,7 +84,6 @@ const SessionsIcon = () => (
|
|||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
>
|
>
|
||||||
<title>Sessions</title>
|
|
||||||
<path
|
<path
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeLinejoin="round"
|
strokeLinejoin="round"
|
||||||
@ -107,7 +101,6 @@ const LogoutIcon = () => (
|
|||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
>
|
>
|
||||||
<title>Logout</title>
|
|
||||||
<path
|
<path
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeLinejoin="round"
|
strokeLinejoin="round"
|
||||||
@ -125,7 +118,6 @@ const MinimalToggleIcon = ({ isExpanded }: { isExpanded: boolean }) => (
|
|||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
>
|
>
|
||||||
<title>{isExpanded ? "Collapse sidebar" : "Expand sidebar"}</title>
|
|
||||||
{isExpanded ? (
|
{isExpanded ? (
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
|
<path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
|
||||||
) : (
|
) : (
|
||||||
@ -166,8 +158,8 @@ const NavItem: React.FC<NavItemProps> = ({
|
|||||||
href={href}
|
href={href}
|
||||||
className={`relative flex items-center p-3 my-1 rounded-lg transition-all group ${
|
className={`relative flex items-center p-3 my-1 rounded-lg transition-all group ${
|
||||||
isActive
|
isActive
|
||||||
? "bg-primary/10 text-primary font-medium border border-primary/20"
|
? "bg-sky-100 text-sky-800 font-medium"
|
||||||
: "hover:bg-muted text-muted-foreground hover:text-foreground"
|
: "hover:bg-gray-100 text-gray-700 hover:text-gray-900"
|
||||||
}`}
|
}`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (onNavigate) {
|
if (onNavigate) {
|
||||||
@ -183,7 +175,7 @@ const NavItem: React.FC<NavItemProps> = ({
|
|||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
className="fixed ml-6 w-auto p-2 min-w-max rounded-md shadow-md text-xs font-medium
|
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
|
invisible opacity-0 -translate-x-3 transition-all
|
||||||
group-hover:visible group-hover:opacity-100 group-hover:translate-x-0"
|
group-hover:visible group-hover:opacity-100 group-hover:translate-x-0"
|
||||||
>
|
>
|
||||||
@ -199,7 +191,6 @@ export default function Sidebar({
|
|||||||
isMobile = false,
|
isMobile = false,
|
||||||
onNavigate,
|
onNavigate,
|
||||||
}: SidebarProps) {
|
}: SidebarProps) {
|
||||||
const sidebarId = useId();
|
|
||||||
const pathname = usePathname() || "";
|
const pathname = usePathname() || "";
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
@ -211,22 +202,13 @@ export default function Sidebar({
|
|||||||
{/* Backdrop overlay when sidebar is expanded on mobile */}
|
{/* Backdrop overlay when sidebar is expanded on mobile */}
|
||||||
{isExpanded && isMobile && (
|
{isExpanded && isMobile && (
|
||||||
<div
|
<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}
|
onClick={onToggle}
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Escape") {
|
|
||||||
onToggle();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
role="button"
|
|
||||||
tabIndex={0}
|
|
||||||
aria-label="Close sidebar"
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
id={sidebarId}
|
className={`fixed md:relative h-screen bg-white shadow-md transition-all duration-300
|
||||||
className={`fixed md:relative h-screen bg-card border-r border-border shadow-lg transition-all duration-300
|
|
||||||
${
|
${
|
||||||
isExpanded ? (isMobile ? "w-full sm:w-80" : "w-56") : "w-16"
|
isExpanded ? (isMobile ? "w-full sm:w-80" : "w-56") : "w-16"
|
||||||
} flex flex-col overflow-visible z-20`}
|
} flex flex-col overflow-visible z-20`}
|
||||||
@ -236,15 +218,12 @@ export default function Sidebar({
|
|||||||
{!isExpanded && (
|
{!isExpanded && (
|
||||||
<div className="absolute top-1 left-1/2 transform -translate-x-1/2 z-30">
|
<div className="absolute top-1 left-1/2 transform -translate-x-1/2 z-30">
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault(); // Prevent any navigation
|
e.preventDefault(); // Prevent any navigation
|
||||||
onToggle();
|
onToggle();
|
||||||
}}
|
}}
|
||||||
className="p-1.5 rounded-md hover:bg-muted focus:outline-none focus:ring-2 focus:ring-primary transition-colors group"
|
className="p-1.5 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-sky-500 transition-colors group"
|
||||||
aria-label="Expand sidebar"
|
title="Expand sidebar"
|
||||||
aria-expanded={isExpanded}
|
|
||||||
aria-controls={sidebarId}
|
|
||||||
>
|
>
|
||||||
<MinimalToggleIcon isExpanded={isExpanded} />
|
<MinimalToggleIcon isExpanded={isExpanded} />
|
||||||
</button>
|
</button>
|
||||||
@ -269,7 +248,7 @@ export default function Sidebar({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{isExpanded && (
|
{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
|
LiveDash
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@ -278,22 +257,18 @@ export default function Sidebar({
|
|||||||
{isExpanded && (
|
{isExpanded && (
|
||||||
<div className="absolute top-3 right-3 z-30">
|
<div className="absolute top-3 right-3 z-30">
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault(); // Prevent any navigation
|
e.preventDefault(); // Prevent any navigation
|
||||||
onToggle();
|
onToggle();
|
||||||
}}
|
}}
|
||||||
className="p-1.5 rounded-md hover:bg-muted focus:outline-none focus:ring-2 focus:ring-primary transition-colors group"
|
className="p-1.5 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-sky-500 transition-colors group"
|
||||||
aria-label="Collapse sidebar"
|
title="Collapse sidebar"
|
||||||
aria-expanded={isExpanded}
|
|
||||||
aria-controls="main-sidebar"
|
|
||||||
>
|
>
|
||||||
<MinimalToggleIcon isExpanded={isExpanded} />
|
<MinimalToggleIcon isExpanded={isExpanded} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<nav
|
<nav
|
||||||
aria-label="Main navigation"
|
|
||||||
className={`flex-1 py-4 px-2 overflow-y-auto overflow-x-visible ${isExpanded ? "pt-12" : "pt-4"}`}
|
className={`flex-1 py-4 px-2 overflow-y-auto overflow-x-visible ${isExpanded ? "pt-12" : "pt-4"}`}
|
||||||
>
|
>
|
||||||
<NavItem
|
<NavItem
|
||||||
@ -315,7 +290,6 @@ export default function Sidebar({
|
|||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
>
|
>
|
||||||
<title>Analytics Chart</title>
|
|
||||||
<path
|
<path
|
||||||
strokeLinecap="round"
|
strokeLinecap="round"
|
||||||
strokeLinejoin="round"
|
strokeLinejoin="round"
|
||||||
@ -353,24 +327,10 @@ export default function Sidebar({
|
|||||||
onNavigate={onNavigate}
|
onNavigate={onNavigate}
|
||||||
/>
|
/>
|
||||||
</nav>
|
</nav>
|
||||||
<div className="p-4 border-t mt-auto space-y-2">
|
<div className="p-4 border-t mt-auto">
|
||||||
{/* 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 */}
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={handleLogout}
|
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"
|
isExpanded ? "" : "justify-center"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
@ -382,7 +342,7 @@ export default function Sidebar({
|
|||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
className="fixed ml-6 w-auto p-2 min-w-max rounded-md shadow-md text-xs font-medium
|
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
|
invisible opacity-0 -translate-x-3 transition-all
|
||||||
group-hover:visible group-hover:opacity-100 group-hover:translate-x-0"
|
group-hover:visible group-hover:opacity-100 group-hover:translate-x-0"
|
||||||
>
|
>
|
||||||
|
|||||||
@ -1,87 +1,76 @@
|
|||||||
"use client";
|
'use client';
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import React from 'react';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { TopQuestion } from '../lib/types';
|
||||||
import { Separator } from "@/components/ui/separator";
|
|
||||||
import type { TopQuestion } from "../lib/types";
|
|
||||||
|
|
||||||
interface TopQuestionsChartProps {
|
interface TopQuestionsChartProps {
|
||||||
data: TopQuestion[];
|
data: TopQuestion[];
|
||||||
title?: string;
|
title?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function TopQuestionsChart({
|
export default function TopQuestionsChart({ data, title = "Top 5 Asked Questions" }: TopQuestionsChartProps) {
|
||||||
data,
|
|
||||||
title = "Top 5 Asked Questions",
|
|
||||||
}: TopQuestionsChartProps) {
|
|
||||||
if (!data || data.length === 0) {
|
if (!data || data.length === 0) {
|
||||||
return (
|
return (
|
||||||
<Card>
|
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||||
<CardHeader>
|
<h3 className="text-lg font-semibold text-gray-900 mb-6">{title}</h3>
|
||||||
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
|
<div className="text-center py-12 text-gray-500">
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
|
||||||
No questions data available
|
No questions data available
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the maximum count to calculate relative bar widths
|
// Find the maximum count to calculate relative bar widths
|
||||||
const maxCount = Math.max(...data.map((q) => q.count));
|
const maxCount = Math.max(...data.map(q => q.count));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||||
<CardHeader>
|
<h3 className="text-lg font-semibold text-gray-900 mb-6">{title}</h3>
|
||||||
<CardTitle className="text-lg font-semibold">{title}</CardTitle>
|
|
||||||
</CardHeader>
|
<div className="space-y-6">
|
||||||
<CardContent>
|
{data.map((question, index) => {
|
||||||
<div className="space-y-4">
|
const percentage = maxCount > 0 ? (question.count / maxCount) * 100 : 0;
|
||||||
{data.map((question) => {
|
|
||||||
const percentage =
|
|
||||||
maxCount > 0 ? (question.count / maxCount) * 100 : 0;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={question.question} className="relative pl-8">
|
<div key={index} className="group">
|
||||||
{/* Question text */}
|
{/* Rank and Question */}
|
||||||
<div className="flex justify-between items-start mb-2">
|
<div className="flex items-start gap-4 mb-3">
|
||||||
<p className="text-sm font-medium leading-tight pr-4 flex-1 text-foreground">
|
<div className="flex-shrink-0 w-8 h-8 bg-gray-100 text-gray-900 text-sm font-semibold rounded-full flex items-center justify-center">
|
||||||
|
{index + 1}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-sm font-medium text-gray-900 leading-relaxed mb-2">
|
||||||
{question.question}
|
{question.question}
|
||||||
</p>
|
</p>
|
||||||
<Badge variant="secondary" className="whitespace-nowrap">
|
<div className="flex items-center justify-between">
|
||||||
{question.count}
|
<div className="flex-1 mr-4">
|
||||||
</Badge>
|
<div className="w-full bg-gray-100 rounded-full h-2">
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Progress bar */}
|
|
||||||
<div className="w-full bg-muted rounded-full h-2">
|
|
||||||
<div
|
<div
|
||||||
className="bg-primary h-2 rounded-full transition-all duration-300 ease-in-out"
|
className="bg-blue-600 h-2 rounded-full transition-all duration-500 ease-out"
|
||||||
style={{ width: `${percentage}%` }}
|
style={{ width: `${percentage}%` }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
{/* Rank indicator */}
|
<span className="text-sm font-semibold text-gray-900 min-w-0">
|
||||||
<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">
|
{question.count} times
|
||||||
{index + 1}
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Separator className="my-6" />
|
|
||||||
|
|
||||||
{/* Summary */}
|
{/* Summary */}
|
||||||
<div className="flex justify-between text-sm text-muted-foreground">
|
<div className="mt-8 pt-6 border-t border-gray-100">
|
||||||
<span>Total questions analyzed</span>
|
<div className="flex justify-between items-center">
|
||||||
<span className="font-medium text-foreground">
|
<span className="text-sm text-gray-600">Total questions analyzed</span>
|
||||||
|
<span className="text-sm font-semibold text-gray-900">
|
||||||
{data.reduce((sum, q) => sum + q.count, 0)}
|
{data.reduce((sum, q) => sum + q.count, 0)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</div>
|
||||||
</Card>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -26,8 +26,8 @@ function formatTranscript(content: string): React.ReactNode[] {
|
|||||||
|
|
||||||
// Process each line
|
// Process each line
|
||||||
lines.forEach((line) => {
|
lines.forEach((line) => {
|
||||||
const trimmedLine = line.trim();
|
line = line.trim();
|
||||||
if (!trimmedLine) {
|
if (!line) {
|
||||||
// Empty line, ignore
|
// Empty line, ignore
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -51,7 +51,7 @@ function formatTranscript(content: string): React.ReactNode[] {
|
|||||||
{currentMessages.map((msg, i) => (
|
{currentMessages.map((msg, i) => (
|
||||||
// Use ReactMarkdown to render each message part
|
// Use ReactMarkdown to render each message part
|
||||||
<ReactMarkdown
|
<ReactMarkdown
|
||||||
key={`msg-${msg.substring(0, 20).replace(/\s/g, "-")}-${i}`}
|
key={i}
|
||||||
rehypePlugins={[rehypeRaw]} // Add rehypeRaw to plugins
|
rehypePlugins={[rehypeRaw]} // Add rehypeRaw to plugins
|
||||||
components={{
|
components={{
|
||||||
p: "span",
|
p: "span",
|
||||||
@ -74,17 +74,15 @@ function formatTranscript(content: string): React.ReactNode[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set the new current speaker
|
// Set the new current speaker
|
||||||
currentSpeaker = trimmedLine.startsWith("User:") ? "User" : "Assistant";
|
currentSpeaker = line.startsWith("User:") ? "User" : "Assistant";
|
||||||
// Add the content after "User:" or "Assistant:"
|
// Add the content after "User:" or "Assistant:"
|
||||||
const messageContent = trimmedLine
|
const messageContent = line.substring(line.indexOf(":") + 1).trim();
|
||||||
.substring(trimmedLine.indexOf(":") + 1)
|
|
||||||
.trim();
|
|
||||||
if (messageContent) {
|
if (messageContent) {
|
||||||
currentMessages.push(messageContent);
|
currentMessages.push(messageContent);
|
||||||
}
|
}
|
||||||
} else if (currentSpeaker) {
|
} else if (currentSpeaker) {
|
||||||
// This is a continuation of the current speaker's message
|
// 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) => (
|
{currentMessages.map((msg, i) => (
|
||||||
// Use ReactMarkdown to render each message part
|
// Use ReactMarkdown to render each message part
|
||||||
<ReactMarkdown
|
<ReactMarkdown
|
||||||
key={`msg-final-${msg.substring(0, 20).replace(/\s/g, "-")}-${i}`}
|
key={i}
|
||||||
rehypePlugins={[rehypeRaw]} // Add rehypeRaw to plugins
|
rehypePlugins={[rehypeRaw]} // Add rehypeRaw to plugins
|
||||||
components={{
|
components={{
|
||||||
p: "span",
|
p: "span",
|
||||||
@ -159,7 +157,6 @@ export default function TranscriptViewer({
|
|||||||
</a>
|
</a>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
type="button"
|
|
||||||
onClick={() => setShowRaw(!showRaw)}
|
onClick={() => setShowRaw(!showRaw)}
|
||||||
className="text-sm text-sky-600 hover:text-sky-800 hover:underline"
|
className="text-sm text-sky-600 hover:text-sky-800 hover:underline"
|
||||||
title={
|
title={
|
||||||
|
|||||||
@ -48,7 +48,7 @@ export default function WelcomeBanner({ companyName }: WelcomeBannerProps) {
|
|||||||
<div className="bg-white/20 backdrop-blur-sm p-4 rounded-lg">
|
<div className="bg-white/20 backdrop-blur-sm p-4 rounded-lg">
|
||||||
<div className="text-sm opacity-75">Current Status</div>
|
<div className="text-sm opacity-75">Current Status</div>
|
||||||
<div className="text-xl font-semibold flex items-center">
|
<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
|
All Systems Operational
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import cloud, { type Word } from "d3-cloud";
|
import { useRef, useEffect, useState } from "react";
|
||||||
import { select } from "d3-selection";
|
import { select } from "d3-selection";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import cloud, { Word } from "d3-cloud";
|
||||||
|
|
||||||
interface WordCloudProps {
|
interface WordCloudProps {
|
||||||
words: {
|
words: {
|
||||||
|
|||||||
@ -1,25 +1,19 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Bar,
|
|
||||||
BarChart,
|
BarChart,
|
||||||
CartesianGrid,
|
Bar,
|
||||||
Cell,
|
|
||||||
ResponsiveContainer,
|
|
||||||
Tooltip,
|
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Cell,
|
||||||
} from "recharts";
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
interface BarChartData {
|
|
||||||
name: string;
|
|
||||||
value: number;
|
|
||||||
[key: string]: string | number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface BarChartProps {
|
interface BarChartProps {
|
||||||
data: BarChartData[];
|
data: Array<{ name: string; value: number; [key: string]: any }>;
|
||||||
title?: string;
|
title?: string;
|
||||||
dataKey?: string;
|
dataKey?: string;
|
||||||
colors?: string[];
|
colors?: string[];
|
||||||
@ -27,13 +21,7 @@ interface BarChartProps {
|
|||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TooltipProps {
|
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||||
active?: boolean;
|
|
||||||
payload?: Array<{ value: number; name?: string }>;
|
|
||||||
label?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
|
|
||||||
if (active && payload && payload.length) {
|
if (active && payload && payload.length) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border bg-background p-3 shadow-md">
|
<div className="rounded-lg border bg-background p-3 shadow-md">
|
||||||
@ -55,11 +43,11 @@ export default function ModernBarChart({
|
|||||||
title,
|
title,
|
||||||
dataKey = "value",
|
dataKey = "value",
|
||||||
colors = [
|
colors = [
|
||||||
"hsl(var(--chart-1))",
|
"rgb(37, 99, 235)", // Blue (primary)
|
||||||
"hsl(var(--chart-2))",
|
"rgb(107, 114, 128)", // Gray
|
||||||
"hsl(var(--chart-3))",
|
"rgb(236, 72, 153)", // Pink
|
||||||
"hsl(var(--chart-4))",
|
"rgb(34, 197, 94)", // Lime green
|
||||||
"hsl(var(--chart-5))",
|
"rgb(168, 85, 247)", // Purple
|
||||||
],
|
],
|
||||||
height = 300,
|
height = 300,
|
||||||
className,
|
className,
|
||||||
@ -73,18 +61,15 @@ export default function ModernBarChart({
|
|||||||
)}
|
)}
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ResponsiveContainer width="100%" height={height}>
|
<ResponsiveContainer width="100%" height={height}>
|
||||||
<BarChart
|
<BarChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
|
||||||
data={data}
|
|
||||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
|
||||||
>
|
|
||||||
<CartesianGrid
|
<CartesianGrid
|
||||||
strokeDasharray="3 3"
|
strokeDasharray="3 3"
|
||||||
stroke="hsl(var(--border))"
|
stroke="rgb(229, 231, 235)"
|
||||||
strokeOpacity={0.3}
|
strokeOpacity={0.5}
|
||||||
/>
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="name"
|
dataKey="name"
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="rgb(100, 116, 139)"
|
||||||
fontSize={12}
|
fontSize={12}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
@ -93,7 +78,7 @@ export default function ModernBarChart({
|
|||||||
height={80}
|
height={80}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="rgb(100, 116, 139)"
|
||||||
fontSize={12}
|
fontSize={12}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
@ -106,7 +91,7 @@ export default function ModernBarChart({
|
|||||||
>
|
>
|
||||||
{data.map((entry, index) => (
|
{data.map((entry, index) => (
|
||||||
<Cell
|
<Cell
|
||||||
key={`cell-${entry.name}-${index}`}
|
key={`cell-${index}`}
|
||||||
fill={colors[index % colors.length]}
|
fill={colors[index % colors.length]}
|
||||||
className="hover:opacity-80"
|
className="hover:opacity-80"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@ -1,13 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import {
|
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from "recharts";
|
||||||
Cell,
|
|
||||||
Legend,
|
|
||||||
Pie,
|
|
||||||
PieChart,
|
|
||||||
ResponsiveContainer,
|
|
||||||
Tooltip,
|
|
||||||
} from "recharts";
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
interface DonutChartProps {
|
interface DonutChartProps {
|
||||||
@ -22,23 +15,16 @@ interface DonutChartProps {
|
|||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TooltipProps {
|
const CustomTooltip = ({ active, payload }: any) => {
|
||||||
active?: boolean;
|
|
||||||
payload?: Array<{
|
|
||||||
name: string;
|
|
||||||
value: number;
|
|
||||||
payload: { total: number };
|
|
||||||
}>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CustomTooltip = ({ active, payload }: TooltipProps) => {
|
|
||||||
if (active && payload && payload.length) {
|
if (active && payload && payload.length) {
|
||||||
const data = payload[0];
|
const data = payload[0];
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border bg-background p-3 shadow-md">
|
<div className="rounded-lg border bg-background p-3 shadow-md">
|
||||||
<p className="text-sm font-medium">{data.name}</p>
|
<p className="text-sm font-medium">{data.name}</p>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
<span className="font-medium text-foreground">{data.value}</span>{" "}
|
<span className="font-medium text-foreground">
|
||||||
|
{data.value}
|
||||||
|
</span>{" "}
|
||||||
sessions ({((data.value / data.payload.total) * 100).toFixed(1)}%)
|
sessions ({((data.value / data.payload.total) * 100).toFixed(1)}%)
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@ -47,22 +33,11 @@ const CustomTooltip = ({ active, payload }: TooltipProps) => {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
interface LegendProps {
|
const CustomLegend = ({ payload }: any) => {
|
||||||
payload?: Array<{
|
|
||||||
value: string;
|
|
||||||
color: string;
|
|
||||||
type?: string;
|
|
||||||
}>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CustomLegend = ({ payload }: LegendProps) => {
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-wrap justify-center gap-4 mt-4">
|
<div className="flex flex-wrap justify-center gap-4 mt-4">
|
||||||
{payload?.map((entry, index) => (
|
{payload.map((entry: any, index: number) => (
|
||||||
<div
|
<div key={index} className="flex items-center gap-2">
|
||||||
key={`legend-${entry.value}-${index}`}
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className="w-3 h-3 rounded-full"
|
className="w-3 h-3 rounded-full"
|
||||||
style={{ backgroundColor: entry.color }}
|
style={{ backgroundColor: entry.color }}
|
||||||
@ -74,15 +49,7 @@ const CustomLegend = ({ payload }: LegendProps) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
interface CenterLabelProps {
|
const CenterLabel = ({ centerText, total }: any) => {
|
||||||
centerText?: {
|
|
||||||
title: string;
|
|
||||||
value: string | number;
|
|
||||||
};
|
|
||||||
total: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CenterLabel = ({ centerText }: CenterLabelProps) => {
|
|
||||||
if (!centerText) return null;
|
if (!centerText) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -100,17 +67,17 @@ export default function ModernDonutChart({
|
|||||||
title,
|
title,
|
||||||
centerText,
|
centerText,
|
||||||
colors = [
|
colors = [
|
||||||
"hsl(var(--chart-1))",
|
"rgb(37, 99, 235)", // Blue (primary)
|
||||||
"hsl(var(--chart-2))",
|
"rgb(107, 114, 128)", // Gray
|
||||||
"hsl(var(--chart-3))",
|
"rgb(236, 72, 153)", // Pink
|
||||||
"hsl(var(--chart-4))",
|
"rgb(34, 197, 94)", // Lime green
|
||||||
"hsl(var(--chart-5))",
|
"rgb(168, 85, 247)", // Purple
|
||||||
],
|
],
|
||||||
height = 300,
|
height = 300,
|
||||||
className,
|
className,
|
||||||
}: DonutChartProps) {
|
}: DonutChartProps) {
|
||||||
const total = data.reduce((sum, item) => sum + item.value, 0);
|
const total = data.reduce((sum, item) => sum + item.value, 0);
|
||||||
const dataWithTotal = data.map((item) => ({ ...item, total }));
|
const dataWithTotal = data.map(item => ({ ...item, total }));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className={className}>
|
<Card className={className}>
|
||||||
@ -120,11 +87,7 @@ export default function ModernDonutChart({
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
)}
|
)}
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div
|
<div className="relative">
|
||||||
className="relative"
|
|
||||||
role="img"
|
|
||||||
aria-label={`${title || "Chart"} - ${data.length} segments`}
|
|
||||||
>
|
|
||||||
<ResponsiveContainer width="100%" height={height}>
|
<ResponsiveContainer width="100%" height={height}>
|
||||||
<PieChart>
|
<PieChart>
|
||||||
<Pie
|
<Pie
|
||||||
@ -135,20 +98,14 @@ export default function ModernDonutChart({
|
|||||||
outerRadius={100}
|
outerRadius={100}
|
||||||
paddingAngle={2}
|
paddingAngle={2}
|
||||||
dataKey="value"
|
dataKey="value"
|
||||||
className="transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary"
|
className="transition-all duration-200"
|
||||||
tabIndex={0}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === "Enter" || e.key === " ") {
|
|
||||||
e.preventDefault();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{dataWithTotal.map((entry, index) => (
|
{dataWithTotal.map((entry, index) => (
|
||||||
<Cell
|
<Cell
|
||||||
key={`cell-${entry.name}-${index}`}
|
key={`cell-${index}`}
|
||||||
fill={entry.color || colors[index % colors.length]}
|
fill={entry.color || colors[index % colors.length]}
|
||||||
className="hover:opacity-80 cursor-pointer focus:opacity-80"
|
className="hover:opacity-80 cursor-pointer"
|
||||||
stroke="hsl(var(--background))"
|
stroke="white"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,27 +1,20 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useId } from "react";
|
|
||||||
import {
|
import {
|
||||||
Area,
|
|
||||||
AreaChart,
|
|
||||||
CartesianGrid,
|
|
||||||
Line,
|
|
||||||
LineChart,
|
LineChart,
|
||||||
ResponsiveContainer,
|
Line,
|
||||||
Tooltip,
|
|
||||||
XAxis,
|
XAxis,
|
||||||
YAxis,
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
ResponsiveContainer,
|
||||||
|
Area,
|
||||||
|
AreaChart,
|
||||||
} from "recharts";
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
|
||||||
interface LineChartData {
|
|
||||||
date: string;
|
|
||||||
value: number;
|
|
||||||
[key: string]: string | number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface LineChartProps {
|
interface LineChartProps {
|
||||||
data: LineChartData[];
|
data: Array<{ date: string; value: number; [key: string]: any }>;
|
||||||
title?: string;
|
title?: string;
|
||||||
dataKey?: string;
|
dataKey?: string;
|
||||||
color?: string;
|
color?: string;
|
||||||
@ -30,13 +23,7 @@ interface LineChartProps {
|
|||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TooltipProps {
|
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||||
active?: boolean;
|
|
||||||
payload?: Array<{ value: number; name?: string }>;
|
|
||||||
label?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CustomTooltip = ({ active, payload, label }: TooltipProps) => {
|
|
||||||
if (active && payload && payload.length) {
|
if (active && payload && payload.length) {
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border bg-background p-3 shadow-md">
|
<div className="rounded-lg border bg-background p-3 shadow-md">
|
||||||
@ -57,12 +44,11 @@ export default function ModernLineChart({
|
|||||||
data,
|
data,
|
||||||
title,
|
title,
|
||||||
dataKey = "value",
|
dataKey = "value",
|
||||||
color = "hsl(var(--primary))",
|
color = "rgb(37, 99, 235)",
|
||||||
gradient = true,
|
gradient = true,
|
||||||
height = 300,
|
height = 300,
|
||||||
className,
|
className,
|
||||||
}: LineChartProps) {
|
}: LineChartProps) {
|
||||||
const gradientId = useId();
|
|
||||||
const ChartComponent = gradient ? AreaChart : LineChart;
|
const ChartComponent = gradient ? AreaChart : LineChart;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -74,13 +60,10 @@ export default function ModernLineChart({
|
|||||||
)}
|
)}
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ResponsiveContainer width="100%" height={height}>
|
<ResponsiveContainer width="100%" height={height}>
|
||||||
<ChartComponent
|
<ChartComponent data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
|
||||||
data={data}
|
|
||||||
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
|
|
||||||
>
|
|
||||||
<defs>
|
<defs>
|
||||||
{gradient && (
|
{gradient && (
|
||||||
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
|
<linearGradient id="colorGradient" x1="0" y1="0" x2="0" y2="1">
|
||||||
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
|
<stop offset="5%" stopColor={color} stopOpacity={0.3} />
|
||||||
<stop offset="95%" stopColor={color} stopOpacity={0.05} />
|
<stop offset="95%" stopColor={color} stopOpacity={0.05} />
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
@ -88,18 +71,18 @@ export default function ModernLineChart({
|
|||||||
</defs>
|
</defs>
|
||||||
<CartesianGrid
|
<CartesianGrid
|
||||||
strokeDasharray="3 3"
|
strokeDasharray="3 3"
|
||||||
stroke="hsl(var(--border))"
|
stroke="rgb(229, 231, 235)"
|
||||||
strokeOpacity={0.3}
|
strokeOpacity={0.5}
|
||||||
/>
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="date"
|
dataKey="date"
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="rgb(100, 116, 139)"
|
||||||
fontSize={12}
|
fontSize={12}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="rgb(100, 116, 139)"
|
||||||
fontSize={12}
|
fontSize={12}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
@ -112,7 +95,7 @@ export default function ModernLineChart({
|
|||||||
dataKey={dataKey}
|
dataKey={dataKey}
|
||||||
stroke={color}
|
stroke={color}
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
fill={`url(#${gradientId})`}
|
fill="url(#colorGradient)"
|
||||||
dot={{ fill: color, strokeWidth: 2, r: 4 }}
|
dot={{ fill: color, strokeWidth: 2, r: 4 }}
|
||||||
activeDot={{ r: 6, stroke: color, strokeWidth: 2 }}
|
activeDot={{ r: 6, stroke: color, strokeWidth: 2 }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@ -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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -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";
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -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;
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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";
|
|
||||||
@ -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}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -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);
|
|
||||||
@ -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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@ -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>;
|
|
||||||
}
|
|
||||||
@ -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 };
|
|
||||||
@ -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,
|
|
||||||
};
|
|
||||||
@ -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 };
|
|
||||||
@ -1,8 +1,8 @@
|
|||||||
import { Slot } from "@radix-ui/react-slot";
|
import * as React from "react"
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
import type * as React from "react";
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const badgeVariants = cva(
|
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",
|
"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",
|
||||||
@ -23,7 +23,7 @@ const badgeVariants = cva(
|
|||||||
variant: "default",
|
variant: "default",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
)
|
||||||
|
|
||||||
function Badge({
|
function Badge({
|
||||||
className,
|
className,
|
||||||
@ -32,7 +32,7 @@ function Badge({
|
|||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"span"> &
|
}: React.ComponentProps<"span"> &
|
||||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
const Comp = asChild ? Slot : "span";
|
const Comp = asChild ? Slot : "span"
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
@ -40,7 +40,7 @@ function Badge({
|
|||||||
className={cn(badgeVariants({ variant }), className)}
|
className={cn(badgeVariants({ variant }), className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Badge, badgeVariants };
|
export { Badge, badgeVariants }
|
||||||
|
|||||||
@ -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,
|
|
||||||
};
|
|
||||||
@ -1,8 +1,8 @@
|
|||||||
import { Slot } from "@radix-ui/react-slot";
|
import * as React from "react"
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
import { Slot } from "@radix-ui/react-slot"
|
||||||
import type * as React from "react";
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const buttonVariants = cva(
|
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",
|
"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",
|
||||||
@ -33,7 +33,7 @@ const buttonVariants = cva(
|
|||||||
size: "default",
|
size: "default",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
)
|
||||||
|
|
||||||
function Button({
|
function Button({
|
||||||
className,
|
className,
|
||||||
@ -43,9 +43,9 @@ function Button({
|
|||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"button"> &
|
}: React.ComponentProps<"button"> &
|
||||||
VariantProps<typeof buttonVariants> & {
|
VariantProps<typeof buttonVariants> & {
|
||||||
asChild?: boolean;
|
asChild?: boolean
|
||||||
}) {
|
}) {
|
||||||
const Comp = asChild ? Slot : "button";
|
const Comp = asChild ? Slot : "button"
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Comp
|
<Comp
|
||||||
@ -53,7 +53,7 @@ function Button({
|
|||||||
className={cn(buttonVariants({ variant, size, className }))}
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Button, buttonVariants };
|
export { Button, buttonVariants }
|
||||||
|
|||||||
@ -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 };
|
|
||||||
@ -1,18 +1,18 @@
|
|||||||
import type * as React from "react";
|
import * as React from "react"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="card"
|
data-slot="card"
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
"bg-white text-gray-900 flex flex-col gap-6 rounded-2xl border border-gray-100 py-6 shadow-sm",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
@ -25,7 +25,7 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
@ -35,7 +35,7 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
className={cn("leading-none font-semibold", className)}
|
className={cn("leading-none font-semibold", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
@ -45,7 +45,7 @@ function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
className={cn("text-muted-foreground text-sm", className)}
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
@ -58,7 +58,7 @@ function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
@ -68,7 +68,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
className={cn("px-6", className)}
|
className={cn("px-6", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
@ -78,7 +78,7 @@ function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|||||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
@ -89,4 +89,4 @@ export {
|
|||||||
CardAction,
|
CardAction,
|
||||||
CardDescription,
|
CardDescription,
|
||||||
CardContent,
|
CardContent,
|
||||||
};
|
}
|
||||||
|
|||||||
@ -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 };
|
|
||||||
@ -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,
|
|
||||||
};
|
|
||||||
@ -1,135 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import type * as React from "react";
|
|
||||||
import { Drawer as DrawerPrimitive } from "vaul";
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
function Drawer({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
|
||||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerTrigger({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
|
||||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerPortal({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
|
||||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerClose({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
|
||||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerOverlay({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
|
||||||
return (
|
|
||||||
<DrawerPrimitive.Overlay
|
|
||||||
data-slot="drawer-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 DrawerContent({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
|
||||||
return (
|
|
||||||
<DrawerPortal data-slot="drawer-portal">
|
|
||||||
<DrawerOverlay />
|
|
||||||
<DrawerPrimitive.Content
|
|
||||||
data-slot="drawer-content"
|
|
||||||
className={cn(
|
|
||||||
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
|
|
||||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
|
||||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
|
||||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
|
||||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
|
||||||
{children}
|
|
||||||
</DrawerPrimitive.Content>
|
|
||||||
</DrawerPortal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="drawer-header"
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
data-slot="drawer-footer"
|
|
||||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerTitle({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
|
||||||
return (
|
|
||||||
<DrawerPrimitive.Title
|
|
||||||
data-slot="drawer-title"
|
|
||||||
className={cn("text-foreground font-semibold", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DrawerDescription({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
|
||||||
return (
|
|
||||||
<DrawerPrimitive.Description
|
|
||||||
data-slot="drawer-description"
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Drawer,
|
|
||||||
DrawerPortal,
|
|
||||||
DrawerOverlay,
|
|
||||||
DrawerTrigger,
|
|
||||||
DrawerClose,
|
|
||||||
DrawerContent,
|
|
||||||
DrawerHeader,
|
|
||||||
DrawerFooter,
|
|
||||||
DrawerTitle,
|
|
||||||
DrawerDescription,
|
|
||||||
};
|
|
||||||
@ -1,15 +1,15 @@
|
|||||||
"use client";
|
"use client"
|
||||||
|
|
||||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
import * as React from "react"
|
||||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||||
import type * as React from "react";
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
function DropdownMenu({
|
function DropdownMenu({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuPortal({
|
function DropdownMenuPortal({
|
||||||
@ -17,7 +17,7 @@ function DropdownMenuPortal({
|
|||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuTrigger({
|
function DropdownMenuTrigger({
|
||||||
@ -28,7 +28,7 @@ function DropdownMenuTrigger({
|
|||||||
data-slot="dropdown-menu-trigger"
|
data-slot="dropdown-menu-trigger"
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuContent({
|
function DropdownMenuContent({
|
||||||
@ -48,7 +48,7 @@ function DropdownMenuContent({
|
|||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
</DropdownMenuPrimitive.Portal>
|
</DropdownMenuPrimitive.Portal>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuGroup({
|
function DropdownMenuGroup({
|
||||||
@ -56,7 +56,7 @@ function DropdownMenuGroup({
|
|||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuItem({
|
function DropdownMenuItem({
|
||||||
@ -65,8 +65,8 @@ function DropdownMenuItem({
|
|||||||
variant = "default",
|
variant = "default",
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||||
inset?: boolean;
|
inset?: boolean
|
||||||
variant?: "default" | "destructive";
|
variant?: "default" | "destructive"
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Item
|
<DropdownMenuPrimitive.Item
|
||||||
@ -79,7 +79,7 @@ function DropdownMenuItem({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuCheckboxItem({
|
function DropdownMenuCheckboxItem({
|
||||||
@ -105,7 +105,7 @@ function DropdownMenuCheckboxItem({
|
|||||||
</span>
|
</span>
|
||||||
{children}
|
{children}
|
||||||
</DropdownMenuPrimitive.CheckboxItem>
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuRadioGroup({
|
function DropdownMenuRadioGroup({
|
||||||
@ -116,7 +116,7 @@ function DropdownMenuRadioGroup({
|
|||||||
data-slot="dropdown-menu-radio-group"
|
data-slot="dropdown-menu-radio-group"
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuRadioItem({
|
function DropdownMenuRadioItem({
|
||||||
@ -140,7 +140,7 @@ function DropdownMenuRadioItem({
|
|||||||
</span>
|
</span>
|
||||||
{children}
|
{children}
|
||||||
</DropdownMenuPrimitive.RadioItem>
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuLabel({
|
function DropdownMenuLabel({
|
||||||
@ -148,7 +148,7 @@ function DropdownMenuLabel({
|
|||||||
inset,
|
inset,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||||
inset?: boolean;
|
inset?: boolean
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.Label
|
<DropdownMenuPrimitive.Label
|
||||||
@ -160,7 +160,7 @@ function DropdownMenuLabel({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSeparator({
|
function DropdownMenuSeparator({
|
||||||
@ -173,7 +173,7 @@ function DropdownMenuSeparator({
|
|||||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuShortcut({
|
function DropdownMenuShortcut({
|
||||||
@ -189,13 +189,13 @@ function DropdownMenuShortcut({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSub({
|
function DropdownMenuSub({
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSubTrigger({
|
function DropdownMenuSubTrigger({
|
||||||
@ -204,7 +204,7 @@ function DropdownMenuSubTrigger({
|
|||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
inset?: boolean;
|
inset?: boolean
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<DropdownMenuPrimitive.SubTrigger
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
@ -219,7 +219,7 @@ function DropdownMenuSubTrigger({
|
|||||||
{children}
|
{children}
|
||||||
<ChevronRightIcon className="ml-auto size-4" />
|
<ChevronRightIcon className="ml-auto size-4" />
|
||||||
</DropdownMenuPrimitive.SubTrigger>
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DropdownMenuSubContent({
|
function DropdownMenuSubContent({
|
||||||
@ -235,7 +235,7 @@ function DropdownMenuSubContent({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
@ -254,4 +254,4 @@ export {
|
|||||||
DropdownMenuSub,
|
DropdownMenuSub,
|
||||||
DropdownMenuSubTrigger,
|
DropdownMenuSubTrigger,
|
||||||
DropdownMenuSubContent,
|
DropdownMenuSubContent,
|
||||||
};
|
}
|
||||||
|
|||||||
@ -1,24 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
|
|
||||||
|
|
||||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
|
||||||
({ className, type, ...props }, ref) => {
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
type={type}
|
|
||||||
className={cn(
|
|
||||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
ref={ref}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
Input.displayName = "Input";
|
|
||||||
|
|
||||||
export { Input };
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
import * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
const labelVariants = cva(
|
|
||||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
|
||||||
);
|
|
||||||
|
|
||||||
const Label = React.forwardRef<
|
|
||||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
|
||||||
VariantProps<typeof labelVariants>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<LabelPrimitive.Root
|
|
||||||
ref={ref}
|
|
||||||
className={cn(labelVariants(), className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
));
|
|
||||||
Label.displayName = LabelPrimitive.Root.displayName;
|
|
||||||
|
|
||||||
export { Label };
|
|
||||||
@ -1,10 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Minus, TrendingDown, TrendingUp } from "lucide-react";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { TrendingUp, TrendingDown, Minus } from "lucide-react";
|
||||||
|
|
||||||
interface MetricCardProps {
|
interface MetricCardProps {
|
||||||
title: string;
|
title: string;
|
||||||
@ -51,31 +51,20 @@ export default function MetricCard({
|
|||||||
const getVariantClasses = () => {
|
const getVariantClasses = () => {
|
||||||
switch (variant) {
|
switch (variant) {
|
||||||
case "primary":
|
case "primary":
|
||||||
return "border-primary/20 bg-linear-to-br from-primary/5 to-primary/10";
|
return "border border-blue-100 bg-white shadow-sm hover:shadow-md";
|
||||||
case "success":
|
case "success":
|
||||||
return "border-green-200 bg-linear-to-br from-green-50 to-green-100 dark:border-green-800 dark:from-green-950 dark:to-green-900";
|
return "border border-green-100 bg-white shadow-sm hover:shadow-md";
|
||||||
case "warning":
|
case "warning":
|
||||||
return "border-amber-200 bg-linear-to-br from-amber-50 to-amber-100 dark:border-amber-800 dark:from-amber-950 dark:to-amber-900";
|
return "border border-pink-100 bg-white shadow-sm hover:shadow-md";
|
||||||
case "danger":
|
case "danger":
|
||||||
return "border-red-200 bg-linear-to-br from-red-50 to-red-100 dark:border-red-800 dark:from-red-950 dark:to-red-900";
|
return "border border-red-100 bg-white shadow-sm hover:shadow-md";
|
||||||
default:
|
default:
|
||||||
return "border-border bg-linear-to-br from-card to-muted/20";
|
return "border border-gray-100 bg-white shadow-sm hover:shadow-md";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getIconClasses = () => {
|
const getIconClasses = () => {
|
||||||
switch (variant) {
|
return "bg-gray-50 text-gray-900 border-gray-100";
|
||||||
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";
|
|
||||||
case "danger":
|
|
||||||
return "bg-red-100 text-red-600 border-red-200 dark:bg-red-900 dark:text-red-400 dark:border-red-800";
|
|
||||||
default:
|
|
||||||
return "bg-muted text-muted-foreground border-border";
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTrendIcon = () => {
|
const getTrendIcon = () => {
|
||||||
@ -94,43 +83,39 @@ export default function MetricCard({
|
|||||||
|
|
||||||
const getTrendColor = () => {
|
const getTrendColor = () => {
|
||||||
if (!trend || trend.value === 0) return "text-muted-foreground";
|
if (!trend || trend.value === 0) return "text-muted-foreground";
|
||||||
return trend.isPositive !== false
|
return trend.isPositive !== false ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400";
|
||||||
? "text-green-600 dark:text-green-400"
|
|
||||||
: "text-red-600 dark:text-red-400";
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative overflow-hidden transition-all duration-300 hover:shadow-xl hover:-translate-y-1 group",
|
"relative overflow-hidden transition-all duration-200 hover:shadow-lg hover:-translate-y-0.5",
|
||||||
getVariantClasses(),
|
getVariantClasses(),
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{/* 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="pb-3 relative">
|
<CardHeader className="pb-3 relative">
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<p className="text-sm font-medium text-muted-foreground leading-none">
|
<p className="text-sm font-medium text-gray-900 leading-none">
|
||||||
{title}
|
{title}
|
||||||
</p>
|
</p>
|
||||||
{description && (
|
{description && (
|
||||||
<p className="text-xs text-muted-foreground/80">{description}</p>
|
<p className="text-xs text-muted-foreground/80">
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{icon && (
|
{icon && (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex h-10 w-10 shrink-0 items-center justify-center rounded-full border transition-all duration-300 group-hover:scale-110",
|
"flex h-10 w-10 shrink-0 items-center justify-center rounded-full border transition-colors",
|
||||||
getIconClasses()
|
getIconClasses()
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span className="text-lg transition-transform duration-300 group-hover:scale-110">
|
<span className="text-lg">{icon}</span>
|
||||||
{icon}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@ -139,7 +124,7 @@ export default function MetricCard({
|
|||||||
<CardContent className="relative">
|
<CardContent className="relative">
|
||||||
<div className="flex items-end justify-between">
|
<div className="flex items-end justify-between">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<p className="text-3xl font-bold tracking-tight bg-clip-text text-transparent bg-linear-to-r from-foreground to-foreground/80">
|
<p className="text-2xl font-bold tracking-tight text-gray-900">
|
||||||
{value ?? "—"}
|
{value ?? "—"}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|||||||
@ -1,185 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
|
||||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
function Select({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
|
||||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectGroup({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
|
||||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectValue({
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
|
||||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectTrigger({
|
|
||||||
className,
|
|
||||||
size = "default",
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
|
||||||
size?: "sm" | "default";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Trigger
|
|
||||||
data-slot="select-trigger"
|
|
||||||
data-size={size}
|
|
||||||
className={cn(
|
|
||||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<SelectPrimitive.Icon asChild>
|
|
||||||
<ChevronDownIcon className="size-4 opacity-50" />
|
|
||||||
</SelectPrimitive.Icon>
|
|
||||||
</SelectPrimitive.Trigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectContent({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
position = "popper",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Portal>
|
|
||||||
<SelectPrimitive.Content
|
|
||||||
data-slot="select-content"
|
|
||||||
className={cn(
|
|
||||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
|
||||||
position === "popper" &&
|
|
||||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
position={position}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SelectScrollUpButton />
|
|
||||||
<SelectPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"p-1",
|
|
||||||
position === "popper" &&
|
|
||||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</SelectPrimitive.Viewport>
|
|
||||||
<SelectScrollDownButton />
|
|
||||||
</SelectPrimitive.Content>
|
|
||||||
</SelectPrimitive.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectLabel({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Label
|
|
||||||
data-slot="select-label"
|
|
||||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectItem({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Item
|
|
||||||
data-slot="select-item"
|
|
||||||
className={cn(
|
|
||||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
|
||||||
<SelectPrimitive.ItemIndicator>
|
|
||||||
<CheckIcon className="size-4" />
|
|
||||||
</SelectPrimitive.ItemIndicator>
|
|
||||||
</span>
|
|
||||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
|
||||||
</SelectPrimitive.Item>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectSeparator({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Separator
|
|
||||||
data-slot="select-separator"
|
|
||||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectScrollUpButton({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.ScrollUpButton
|
|
||||||
data-slot="select-scroll-up-button"
|
|
||||||
className={cn(
|
|
||||||
"flex cursor-default items-center justify-center py-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronUpIcon className="size-4" />
|
|
||||||
</SelectPrimitive.ScrollUpButton>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectScrollDownButton({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.ScrollDownButton
|
|
||||||
data-slot="select-scroll-down-button"
|
|
||||||
className={cn(
|
|
||||||
"flex cursor-default items-center justify-center py-1",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ChevronDownIcon className="size-4" />
|
|
||||||
</SelectPrimitive.ScrollDownButton>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectGroup,
|
|
||||||
SelectItem,
|
|
||||||
SelectLabel,
|
|
||||||
SelectScrollDownButton,
|
|
||||||
SelectScrollUpButton,
|
|
||||||
SelectSeparator,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
};
|
|
||||||
@ -1,9 +1,9 @@
|
|||||||
"use client";
|
"use client"
|
||||||
|
|
||||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
import * as React from "react"
|
||||||
import type * as React from "react";
|
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
function Separator({
|
function Separator({
|
||||||
className,
|
className,
|
||||||
@ -22,7 +22,7 @@ function Separator({
|
|||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Separator };
|
export { Separator }
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user