# Z.CRM - API Documentation
## مجموعة أتمتة - توثيق واجهة برمجة التطبيقات

Base URL: `http://localhost:5000/api/v1`

## Authentication

All API endpoints (except `/auth/login` and `/auth/register`) require authentication via JWT token.

### Headers

```
Authorization: Bearer <access_token>
Content-Type: application/json
```

### Authentication Endpoints

#### Login
```http
POST /auth/login
```

**Request Body:**
```json
{
  "email": "gm@atmata.com",
  "password": "Admin@123"
}
```

**Response:**
```json
{
  "success": true,
  "message": "تم تسجيل الدخول بنجاح - Login successful",
  "data": {
    "user": {
      "id": "uuid",
      "email": "gm@atmata.com",
      "employee": { ... }
    },
    "accessToken": "jwt_token",
    "refreshToken": "refresh_token",
    "expiresIn": "7d"
  }
}
```

#### Refresh Token
```http
POST /auth/refresh
```

#### Get Current User
```http
GET /auth/me
```

#### Logout
```http
POST /auth/logout
```

---

## Module 1: Contact Management

### Contacts

#### List All Contacts
```http
GET /contacts?page=1&pageSize=20&search=&type=&status=
```

**Query Parameters:**
- `page` (number): Page number
- `pageSize` (number): Items per page
- `search` (string): Search term
- `type` (string): INDIVIDUAL, COMPANY, HOLDING, GOVERNMENT
- `status` (string): ACTIVE, INACTIVE, ARCHIVED, BLOCKED
- `category` (string): Category ID
- `source` (string): Source type
- `rating` (number): 1-5
- `createdFrom` (date): Filter from date
- `createdTo` (date): Filter to date

**Response:**
```json
{
  "success": true,
  "data": [...],
  "pagination": {
    "total": 100,
    "page": 1,
    "pageSize": 20,
    "totalPages": 5
  }
}
```

#### Get Contact by ID
```http
GET /contacts/:id
```

**Response includes:**
- Basic contact info
- Categories
- Parent/children (hierarchy)
- Relationships
- Activities (last 20)
- Deals (last 10)
- Notes
- Attachments

#### Create Contact
```http
POST /contacts
```

**Request Body:**
```json
{
  "type": "COMPANY",
  "name": "ABC Corporation",
  "nameAr": "شركة ABC",
  "email": "contact@abc.com",
  "phone": "+966112345678",
  "mobile": "+966501234567",
  "companyName": "ABC Corporation",
  "taxNumber": "123456789",
  "commercialRegister": "1010123456",
  "address": "123 King Fahd Road",
  "city": "Riyadh",
  "country": "Saudi Arabia",
  "source": "EXHIBITION",
  "categories": ["category-uuid-1"],
  "tags": ["VIP", "Tech"],
  "customFields": {}
}
```

#### Update Contact
```http
PUT /contacts/:id
```

#### Archive Contact
```http
POST /contacts/:id/archive
```

**Request Body:**
```json
{
  "reason": "سبب الأرشفة"
}
```

#### Delete Contact (Hard Delete - GM Only)
```http
DELETE /contacts/:id
```

**Request Body:**
```json
{
  "reason": "سبب الحذف النهائي"
}
```

#### Merge Contacts
```http
POST /contacts/merge
```

**Request Body:**
```json
{
  "sourceId": "uuid",
  "targetId": "uuid",
  "reason": "سبب الدمج"
}
```

#### Add Relationship
```http
POST /contacts/:id/relationships
```

**Request Body:**
```json
{
  "toContactId": "uuid",
  "type": "REPRESENTATIVE",
  "startDate": "2024-01-01"
}
```

#### Get Contact History
```http
GET /contacts/:id/history
```

---

## Module 2: CRM

### Deals

#### List All Deals
```http
GET /crm/deals?page=1&pageSize=20&structure=B2B&stage=OPEN&status=ACTIVE&ownerId=&fiscalYear=2024
```

#### Get Deal by ID
```http
GET /crm/deals/:id
```

**Response includes:**
- Deal info
- Contact info
- Owner info
- Pipeline & stages
- Quotes (all versions)
- Cost sheets
- Activities (last 20)
- Notes
- Attachments
- Contracts
- Invoices

#### Create Deal
```http
POST /crm/deals
```

**Request Body:**
```json
{
  "name": "ABC Corp - ERP System",
  "contactId": "uuid",
  "structure": "B2B",
  "pipelineId": "uuid",
  "stage": "OPEN",
  "estimatedValue": 500000,
  "probability": 70,
  "expectedCloseDate": "2024-06-30",
  "ownerId": "uuid",
  "fiscalYear": 2024
}
```

#### Update Deal
```http
PUT /crm/deals/:id
```

#### Update Deal Stage
```http
PATCH /crm/deals/:id/stage
```

**Request Body:**
```json
{
  "stage": "NEGOTIATION"
}
```

#### Win Deal
```http
POST /crm/deals/:id/win
```

**Request Body:**
```json
{
  "actualValue": 480000,
  "wonReason": "Competitive pricing and good proposal"
}
```

#### Lose Deal
```http
POST /crm/deals/:id/lose
```

**Request Body:**
```json
{
  "lostReason": "Client chose competitor"
}
```

### Quotes

#### Get Quotes for Deal
```http
GET /crm/deals/:dealId/quotes
```

#### Get Quote by ID
```http
GET /crm/quotes/:id
```

#### Create Quote
```http
POST /crm/quotes
```

**Request Body:**
```json
{
  "dealId": "uuid",
  "items": [
    {
      "description": "Software License",
      "quantity": 10,
      "unitPrice": 5000,
      "total": 50000
    }
  ],
  "subtotal": 50000,
  "taxRate": 15,
  "taxAmount": 7500,
  "total": 57500,
  "validUntil": "2024-03-31",
  "paymentTerms": "Net 30",
  "deliveryTerms": "On-site installation",
  "notes": "Special offer for Q1 2024"
}
```

#### Approve Quote
```http
POST /crm/quotes/:id/approve
```

#### Send Quote
```http
POST /crm/quotes/:id/send
```

---

## Module 3: Inventory & Assets

### Products
```http
GET    /inventory/products
POST   /inventory/products
PUT    /inventory/products/:id
DELETE /inventory/products/:id
```

### Warehouses
```http
GET    /inventory/warehouses
POST   /inventory/warehouses
GET    /inventory/warehouses/:id
```

### Inventory Items
```http
GET /inventory/items?warehouseId=&productId=
```

### Assets
```http
GET    /inventory/assets
POST   /inventory/assets
GET    /inventory/assets/:id
PUT    /inventory/assets/:id
```

---

## Module 4: Projects & Tasks

### Projects
```http
GET    /projects/projects
POST   /projects/projects
GET    /projects/projects/:id
PUT    /projects/projects/:id
DELETE /projects/projects/:id
```

### Tasks
```http
GET    /projects/tasks?projectId=&assignedToId=&status=
POST   /projects/tasks
GET    /projects/tasks/:id
PUT    /projects/tasks/:id
DELETE /projects/tasks/:id
```

**Task Statuses:**
- TODO
- IN_PROGRESS
- REVIEW
- COMPLETED
- CANCELLED

---

## Module 5: HR Management

### Employees
```http
GET    /hr/employees?departmentId=&status=
POST   /hr/employees
GET    /hr/employees/:id
PUT    /hr/employees/:id
POST   /hr/employees/:id/terminate
```

### Attendance
```http
GET  /hr/attendance/:employeeId?month=1&year=2024
POST /hr/attendance
```

### Leaves
```http
GET  /hr/leaves
POST /hr/leaves
POST /hr/leaves/:id/approve
POST /hr/leaves/:id/reject
```

### Salaries
```http
POST /hr/salaries/process
GET  /hr/salaries?employeeId=&month=&year=
```

---

## Module 6: Marketing

### Campaigns
```http
GET    /marketing/campaigns?type=EMAIL&status=RUNNING
POST   /marketing/campaigns
GET    /marketing/campaigns/:id
PUT    /marketing/campaigns/:id
POST   /marketing/campaigns/:id/approve
POST   /marketing/campaigns/:id/launch
GET    /marketing/campaigns/:id/stats
```

**Campaign Types:**
- EMAIL
- WHATSAPP
- SOCIAL
- EXHIBITION
- MULTI_CHANNEL

**Campaign Statuses:**
- DRAFT
- PENDING_APPROVAL
- APPROVED
- SCHEDULED
- RUNNING
- COMPLETED
- CANCELLED

---

## Common Response Format

### Success Response
```json
{
  "success": true,
  "message": "Operation completed successfully",
  "data": { ... }
}
```

### Paginated Response
```json
{
  "success": true,
  "data": [...],
  "pagination": {
    "total": 100,
    "page": 1,
    "pageSize": 20,
    "totalPages": 5
  }
}
```

### Error Response
```json
{
  "success": false,
  "message": "Error message in Arabic and English",
  "error": "ERROR_CODE"
}
```

## Error Codes

| Code | HTTP Status | Description |
|------|-------------|-------------|
| UNAUTHORIZED | 401 | Missing or invalid token |
| FORBIDDEN | 403 | Insufficient permissions |
| NOT_FOUND | 404 | Resource not found |
| VALIDATION_ERROR | 400 | Invalid input data |
| DUPLICATE_RECORD | 409 | Duplicate entry |
| INTERNAL_ERROR | 500 | Server error |

## Permissions System

Each endpoint requires specific permissions based on:
- **Module**: contacts, crm, inventory, etc.
- **Resource**: contacts, deals, products, etc.
- **Action**: create, read, update, delete, approve, etc.

Permissions are managed through the HR module and assigned to positions.

## Rate Limiting

- **Window**: 15 minutes
- **Max Requests**: 100 per window
- Headers included in response:
  - `X-RateLimit-Limit`
  - `X-RateLimit-Remaining`
  - `X-RateLimit-Reset`

---

**For complete module-specific API documentation, see the source code in `/backend/src/modules/`**

