# SalesHub CRM - Frontend

## Project Overview

SalesHub CRM Frontend is a **Next.js 16** application that provides the user interface for the SalesHub CRM system. It features a modern, responsive design built with **React 19**, **TypeScript**, **shadcn/ui**, and **Tailwind CSS 4**. The application provides comprehensive sales pipeline management, contact/deal tracking, team collaboration, and BANT (Budget, Authority, Need, Timeline) qualification features.

### Architecture

```
saleshub-frontend/
├── src/
│   ├── app/              # Next.js 16 App Router pages
│   ├── components/       # React components (shadcn/ui)
│   ├── api/              # RTK Query + API client
│   ├── store/            # Redux Toolkit state management
│   ├── hooks/            # Custom React hooks
│   ├── lib/              # Utilities (auth, CASL, helpers)
│   ├── types/            # TypeScript type definitions
│   └── proxy.ts          # Next.js middleware for auth
├── public/               # Static assets
├── package.json          # Dependencies and scripts
└── next.config.ts        # Next.js configuration
```

### Tech Stack

| Category | Technology |
|----------|------------|
| **Framework** | Next.js 16 (App Router) |
| **UI Library** | React 19 |
| **Styling** | Tailwind CSS 4 |
| **UI Components** | shadcn/ui, Radix UI |
| **State Management** | Redux Toolkit + Redux Persist |
| **Data Fetching** | RTK Query, SWR |
| **Forms** | React Hook Form + Zod |
| **Charts** | Recharts |
| **Drag & Drop** | @dnd-kit |
| **Auth** | NextAuth.js (JWT strategy) |
| **Authorization** | CASL (role-based permissions) |
| **Notifications** | Sonner, Socket.io |
| **Date Handling** | date-fns, React Day Picker |

## Building and Running

### Prerequisites

- **Node.js** (v20+ recommended)
- **npm** (package manager)
- Running instance of SalesHub Backend API (e.g. `htttp://localhost:3002/v1` — must match `NEXT_PUBLIC_API_URL`)

### Installation

```bash
cd saleshub-frontend

# Install dependencies
npm install
```

### Environment Variables

Create a `.env.local` file in the project root:

```env
NEXTAUTH_URL=http://localhost:3001
NEXTAUTH_SECRET=your-secret-key-here
NEXT_PUBLIC_API_URL=htttp://localhost:3002/v1
```

| Variable | Description |
|----------|-------------|
| `NEXTAUTH_URL` | URL of the Next.js application (dev: 3001, prod: 4001) |
| `NEXTAUTH_SECRET` | Secret key for NextAuth.js JWT signing (min 32 chars) |
| `NEXT_PUBLIC_API_URL` | Backend API base URL (include global prefix, e.g. `.../v1`, no trailing slash) |

### Development

```bash
# Start development server on port 3001
npm run dev
```

Open [http://localhost:3001](http://localhost:3001) in your browser.

### Production

```bash
# Build for production
npm run build

# Start production server on port 4001
npm start
```

### Linting

```bash
# Run ESLint
npm run lint
```

## Key Features

### Core Modules

- **Authentication**: NextAuth.js with credentials provider, JWT sessions, automatic token refresh
- **Authorization**: CASL-based permissions (create, read, update, delete, manage actions on resources)
- **Dashboard**: KPIs, revenue charts, pipeline visualization, leaderboard
- **Deals**: Pipeline-based deal tracking with BANT scoring, drag-and-drop stage management
- **Contacts**: Full contact management with activity tracking
- **Companies**: Company/brand/division management
- **Customers**: Post-won customer management with AM assignment
- **Activities**: Call/Email/Meeting/Note/Deal/Win/Login/Logout logging
- **Pipelines**: Configurable stages with sub-stages, probabilities
- **Teams**: Team structure with team leads and members
- **Users & Roles**: User management, role assignment, permission management
- **Notifications**: Real-time notifications via Socket.io, multi-channel support
- **Reports & Forecasts**: Sales analytics and forecasting

### State Management

**Redux Slices** (`src/store/slices/`):
- `auth-slice`: JWT token management
- `deals-slice`: Deal state with pipeline-based organization
- `team-filter-slice`: Team filtering state
- `edit-stage-slice`, `add-stage-slice`, `stage-name-dialog-slice`: Pipeline stage management

**RTK Query API** (`src/api/rtk/base-api.ts`):
- Base API with automatic JWT token injection
- Response unwrapping (backend wraps responses in `{ success, data }`)
- Tag types for cache invalidation: `Auth`, `User`, `Deals`, `Contacts`, `Activities`, `Customers`, `Dashboard`, `Pipelines`, `BantScores`, etc.

### Authentication Flow

1. User submits credentials to `/login`
2. NextAuth calls backend `/auth/login` endpoint
3. Backend returns JWT access token + user data
4. Token stored in JWT session (not localStorage)
5. Token auto-refreshed every 5 minutes via `jwt` callback
6. Redux store synced via `SyncSessionToRedux` component
7. CASL ability built from user permissions for UI authorization

### Authorization (CASL)

Permissions are defined as `{ action, resource }` pairs:
- **Actions**: `CREATE`, `READ`, `UPDATE`, `DELETE`, `MANAGE`
- **Resources**: `User`, `Role`, `Permission`, `Contact`, `Company`, `Deal`, `Activity`, `Report`, `Dashboard`, `Pipeline`, `Team`, `Customer`

`MANAGE` on a resource grants all CRUD actions. `Admin` role gets full access to everything.

## Development Conventions

### Code Style

- **ESLint**: Configured with `eslint-config-next` (see `eslint.config.mjs`)
- **TypeScript**: Strict mode enabled (see `tsconfig.json`)
- **Prettier**: Integrated with ESLint

### Project Structure

**Pages** (`src/app/`):
```
app/
├── (auth)/           # Auth pages (login, forgot-password, etc.)
├── activities/       # Activities page
├── api/              # API routes (NextAuth)
├── companies/        # Company management
├── contacts/         # Contact management
├── customers/        # Customer management
├── deals/            # Deal/pipeline management
├── forecasts/        # Sales forecasting
├── notifications/    # Notification center
├── permissions/      # Permission management
├── pipeline/         # Pipeline configuration
├── reports/          # Reports and analytics
├── roles/            # Role management
├── settings/         # User settings
├── teams/            # Team management
├── users/            # User management
├── layout.tsx        # Root layout with providers
└── page.tsx          # Dashboard home page
```

**Components** (`src/components/`):
```
components/
├── ui/               # shadcn/ui primitives
├── [module]/         # Feature-specific components
├── providers/        # Context providers (Auth, Store, Ability, Theme)
├── shared/           # Shared components
├── app-shell.tsx     # Main app layout
├── app-sidebar.tsx   # Navigation sidebar
└── app-header.tsx    # Top header bar
```

### Component Patterns

- **shadcn/ui**: All UI components follow shadcn conventions (located in `components/ui/`)
- **Feature components**: Organized by domain (e.g., `components/deals/`, `components/contacts/`)
- **Providers**: Context providers for global state (Auth, Redux, CASL, Theme)
- **Hooks**: Custom hooks in `src/hooks/` (e.g., `use-mobile.ts`, `use-notification-socket.ts`)

### API Client

**`src/api/client.ts`**:
- `apiFetch<T>()`: Generic fetch wrapper with JSON handling, automatic 401 handling
- `getFileUrl()`: Prepend API base URL to relative paths (for images/files)
- `apiBaseUrl`: Backend API base URL from `NEXT_PUBLIC_API_URL` env

### Important Files

| File | Purpose |
|------|---------|
| `src/app/layout.tsx` | Root layout with all providers (Store, Session, Ability, Theme) |
| `src/proxy.ts` | Next.js middleware for auth protection |
| `src/lib/auth.ts` | NextAuth configuration (credentials, JWT callbacks) |
| `src/lib/casl.ts` | CASL ability builder from permissions |
| `src/lib/utils.ts` | Utility functions (`cn()`, stage ID replacement, plain text conversion) |
| `src/store/index.ts` | Redux store configuration with persistence |
| `src/api/rtk/base-api.ts` | RTK Query base API with tag types |
| `src/types/next-auth.d.ts` | NextAuth type augmentation |

## Integration with Backend

The frontend communicates with the NestJS backend API:

- **Base URL**: `htttp://localhost:3002/v1` (configurable via `NEXT_PUBLIC_API_URL`; must include the Nest global prefix)
- **Auth**: JWT Bearer token (automatically injected by RTK Query)
- **Response Format**: Backend wraps responses in `{ success: boolean, data: T }`
- **Error Handling**: 401 responses trigger automatic sign-out and redirect to login

### Backend API Documentation

- **Swagger UI**: `htttp://localhost:3002/v1/docs` (when backend `PORT=3002` and prefix `v1`)
- **Postman Collection**: `saleshub-backend/crm hubspot.postman_collection.json`

## Notes

- **Package Manager**: Uses `npm` (backend uses `pnpm`)
- **Ports**: Dev server `3001`, Production server `4001`
- **React Compiler**: Enabled in `next.config.ts` (`reactCompiler: true`)
- **TypeScript**: Build errors ignored in development (`ignoreBuildErrors: true`)
- **SSL**: Disabled by default (assumes reverse proxy in production)
