# Z.CRM - Installation Guide
## نظام إدارة علاقات العملاء - دليل التثبيت

This guide will help you set up the Z.CRM system on your local machine or server.

## Prerequisites

### Required Software
- **Node.js**: v18+ ([Download](https://nodejs.org/))
- **PostgreSQL**: v14+ ([Download](https://www.postgresql.org/download/))
- **npm or yarn**: Latest version

### System Requirements
- **OS**: macOS, Linux, or Windows
- **RAM**: Minimum 4GB (8GB recommended)
- **Disk Space**: 2GB free space

## Installation Steps

### 1. Clone or Extract the Project

```bash
cd /Users/talalsharabi/z_crm
```

### 2. Install Dependencies

```bash
# Install root dependencies
npm install

# Install backend dependencies
cd backend
npm install

# Install frontend dependencies
cd ../frontend
npm install
```

### 3. Database Setup

#### Create PostgreSQL Database

```bash
# Login to PostgreSQL
psql -U postgres

# Create database
CREATE DATABASE z_crm;

# Create user (optional)
CREATE USER z_crm_user WITH PASSWORD 'your_secure_password';
GRANT ALL PRIVILEGES ON DATABASE z_crm TO z_crm_user;

# Exit
\q
```

#### Configure Database Connection

```bash
cd backend

# Copy environment example
cp .env.example .env

# Edit .env file with your database credentials
# DATABASE_URL="postgresql://username:password@localhost:5432/z_crm?schema=public"
```

**Important Environment Variables:**

```env
# Server
NODE_ENV=development
PORT=5000

# Database
DATABASE_URL="postgresql://postgres:password@localhost:5432/z_crm?schema=public"

# JWT Secret (CHANGE THIS!)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production-z-crm-2024

# CORS
CORS_ORIGIN=http://localhost:3000
```

### 4. Run Database Migrations

```bash
# Still in backend directory
npx prisma generate
npx prisma migrate dev
```

### 5. Seed Database with Sample Data

```bash
npm run prisma:seed
```

This will create:
- 3 departments (Sales, IT, HR)
- 3 positions with permissions
- 3 employees
- 3 user accounts
- Sample data for categories, pipelines, and warehouses

**Default Login Credentials:**

| Role | Email | Password | Access Level |
|------|-------|----------|--------------|
| General Manager | gm@atmata.com | Admin@123 | Full Access |
| Sales Manager | sales.manager@atmata.com | Admin@123 | Contacts & CRM |
| Sales Rep | sales.rep@atmata.com | Admin@123 | Basic Access |

### 6. Configure Frontend

```bash
cd ../frontend

# Create .env.local file
echo "NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1" > .env.local
```

## Running the Application

### Option 1: Run All Services Together (Recommended)

From the project root directory:

```bash
npm run dev
```

This will start:
- Backend API on `http://localhost:5000`
- Frontend on `http://localhost:3000`

### Option 2: Run Services Separately

**Terminal 1 - Backend:**

```bash
cd backend
npm run dev
```

**Terminal 2 - Frontend:**

```bash
cd frontend
npm run dev
```

## Verify Installation

1. **Check Backend API:**
   ```bash
   curl http://localhost:5000/health
   ```
   Expected response: `{"status":"ok"}`

2. **Check Frontend:**
   Open browser: `http://localhost:3000`

3. **Test Login:**
   - Go to `http://localhost:3000/login` (when implemented)
   - Login with: `gm@atmata.com` / `Admin@123`

## Database Management Tools

### Prisma Studio (GUI for Database)

```bash
cd backend
npm run prisma:studio
```

Opens at: `http://localhost:5555`

### Database Backup

```bash
pg_dump -U postgres z_crm > backup.sql
```

### Database Restore

```bash
psql -U postgres z_crm < backup.sql
```

## Production Deployment

### 1. Build Applications

```bash
# Build backend
cd backend
npm run build

# Build frontend
cd ../frontend
npm run build
```

### 2. Environment Variables for Production

```env
NODE_ENV=production
DATABASE_URL="postgresql://user:password@your-db-host:5432/z_crm"
JWT_SECRET="your-super-secure-production-secret-with-at-least-32-characters"
CORS_ORIGIN="https://your-domain.com"
```

### 3. Start Production Server

```bash
# Backend
cd backend
npm start

# Frontend
cd frontend
npm start
```

## Troubleshooting

### Database Connection Issues

```bash
# Check PostgreSQL is running
pg_isready

# Check connection string
psql "postgresql://username:password@localhost:5432/z_crm"
```

### Port Already in Use

```bash
# Find process using port 5000
lsof -ti:5000 | xargs kill -9

# Find process using port 3000
lsof -ti:3000 | xargs kill -9
```

### Reset Database

```bash
cd backend
npx prisma migrate reset
npm run prisma:seed
```

### Clear Node Modules

```bash
rm -rf node_modules package-lock.json
npm install
```

## System Architecture

```
z_crm/
├── backend/           # Express API (Port 5000)
│   ├── src/
│   │   ├── modules/   # 6 Modules
│   │   ├── shared/    # Middleware, utils
│   │   └── config/    # Configuration
│   └── prisma/        # Database schema & migrations
│
├── frontend/          # Next.js App (Port 3000)
│   └── src/
│       ├── app/       # Pages & layouts
│       ├── components/# React components
│       └── lib/       # API client & utilities
│
└── docs/             # Documentation
```

## Next Steps

After successful installation:

1. ✅ Login with default credentials
2. ✅ Explore the 6 modules
3. ✅ Create your first contact
4. ✅ Set up your organization structure in HR
5. ✅ Configure permissions for your team
6. ✅ Start managing your business!

## Support & Documentation

- **Full Documentation**: See `README.md`
- **API Documentation**: `http://localhost:5000/api/v1` (when running)
- **Module Specifications**: See original Arabic specifications

## Security Checklist for Production

- [ ] Change all default passwords
- [ ] Update JWT_SECRET with strong random string
- [ ] Enable HTTPS/SSL
- [ ] Configure firewall rules
- [ ] Set up database backups
- [ ] Enable audit logging
- [ ] Review and restrict permissions
- [ ] Set up monitoring and alerts

---

**Z.CRM © 2024 - نظام إدارة علاقات العملاء**

