# WhatsApp CRM API - Project Structure

## Quick Start

```bash
cd c:\Users\HP\Documents\whatsappcrm
npm install
npm start
```

Visit: `http://localhost:3000/api/docs`

---

## Project Structure

```
whatsappcrm/
├── src/                          # Source code
│   ├── index.js                 # Main server file
│   ├── database.js              # SQLite database setup
│   ├── auth.js                  # Authentication logic
│   ├── whatsapp.js              # WhatsApp Web integration
│   └── routes/
│       ├── auth.js              # /api/auth endpoints
│       ├── messages.js          # /api/messages endpoints
│       ├── contacts.js          # /api/contacts endpoints
│       └── templates.js         # /api/templates endpoints
│
├── data/                        # Database files (auto-created)
│   └── whatsapp.db             # SQLite database
│
├── sessions/                    # WhatsApp sessions (auto-created)
│   └── Client/                 # Session authentication data
│
├── logs/                        # Log files (auto-created)
│
├── package.json                # Dependencies
├── .env                        # Environment variables
├── .gitignore                  # Git ignore rules
│
├── client.js                   # API client library
├── example.js                  # Usage examples
│
├── README.md                   # Main documentation
├── GUIDE.md                    # Complete implementation guide
├── TESTING.md                  # API testing guide
└── PROJECT.md                  # This file
```

---

## Key Files Explained

### 1. **src/index.js** - Main Server
- Express server setup
- Middleware configuration (CORS, body-parser)
- Route initialization
- Database initialization
- Health check and documentation endpoints

### 2. **src/database.js** - Database Layer
- SQLite initialization
- Table creation (Sessions, Messages, Contacts, Templates)
- Query execution helpers

### 3. **src/auth.js** - Authentication
- Session creation
- API key generation and validation
- Session management

### 4. **src/whatsapp.js** - WhatsApp Integration
- WhatsApp Web client initialization
- QR code generation
- Message sending/receiving
- Contact management
- Event handling

### 5. **src/routes/** - API Endpoints

#### auth.js
- `POST /api/auth/init` - Initialize new session
- `GET /api/auth/:sessionId/qr` - Get QR code
- `GET /api/auth/:sessionId/status` - Check status

#### messages.js
- `POST /api/messages/:sessionId/send` - Send message
- `GET /api/messages/:sessionId/list` - List all messages
- `GET /api/messages/:sessionId/conversation/:phone` - Get conversation

#### contacts.js
- `POST /api/contacts/:sessionId` - Add contact
- `GET /api/contacts/:sessionId` - List contacts
- `GET /api/contacts/:sessionId/:phone` - Get contact details
- `PUT /api/contacts/:sessionId/:id` - Update contact
- `DELETE /api/contacts/:sessionId/:id` - Delete contact

#### templates.js
- `POST /api/templates/:sessionId` - Create template
- `GET /api/templates/:sessionId` - List templates
- `GET /api/templates/:sessionId/:id` - Get template
- `PUT /api/templates/:sessionId/:id` - Update template
- `POST /api/templates/:sessionId/:id/render` - Render with variables
- `DELETE /api/templates/:sessionId/:id` - Delete template

### 6. **client.js** - JavaScript Client Library
Ready-to-use client for Node.js applications:
- `new WhatsAppCRMClient(baseUrl, apiKey, sessionId)`
- Methods for all API operations
- Automatic authentication waiting

### 7. **example.js** - Complete Example
Shows full workflow:
1. Session initialization
2. QR code scanning
3. Message sending
4. Template creation
5. Contact management

---

## Database Schema

### Sessions
```
id (UUID, PK)
phone_number (TEXT, UNIQUE)
api_key (TEXT, UNIQUE)
qr_code (TEXT)
status (TEXT: pending|authenticated|disconnected)
created_at (DATETIME)
updated_at (DATETIME)
```

### Messages
```
id (TEXT, PK)
session_id (TEXT, FK)
from_phone (TEXT)
to_phone (TEXT)
message_text (TEXT)
message_type (TEXT)
direction (TEXT: incoming|outgoing)
timestamp (DATETIME)
read_status (INTEGER)
media_url (TEXT)
```

### Contacts
```
id (UUID, PK)
session_id (TEXT, FK)
phone (TEXT, UNIQUE)
name (TEXT)
avatar (TEXT)
created_at (DATETIME)
```

### Templates
```
id (UUID, PK)
session_id (TEXT, FK)
name (TEXT)
content (TEXT with {{variables}})
variables (JSON)
created_at (DATETIME)
```

---

## Environment Variables

```env
PORT=3000                           # Server port
NODE_ENV=development|production     # Environment
API_KEY=your_secret_key            # Default API key (override in .env)
DATABASE_PATH=./data/whatsapp.db   # Database file location
SESSION_PATH=./sessions            # WhatsApp session storage
LOG_PATH=./logs                    # Log file location
```

---

## Installation & Setup

### Prerequisites
- Node.js 14+
- npm 6+
- Windows/Mac/Linux

### Installation Steps

1. **Navigate to project**
```bash
cd c:\Users\HP\Documents\whatsappcrm
```

2. **Install dependencies**
```bash
npm install
```

3. **Configure environment** (optional)
Edit `.env` if needed

4. **Start server**
```bash
npm start
# or for development
npm run dev
```

5. **Access API**
- API: http://localhost:3000/api
- Docs: http://localhost:3000/api/docs
- Health: http://localhost:3000/health

---

## Authentication Flow

1. **POST /api/auth/init**
   - Returns: sessionId + apiKey

2. **GET /api/auth/:sessionId/qr**
   - Returns: QR code image
   - User scans with WhatsApp mobile

3. **GET /api/auth/:sessionId/status**
   - Returns: Authentication status
   - Status changes to "authenticated" after QR scan

4. **Use API**
   - Add header: `X-API-Key: your_api_key`
   - Use sessionId in URL paths

---

## API Endpoints Summary

### Authentication (Public)
```
POST   /api/auth/init
GET    /api/auth/:sessionId/qr
GET    /api/auth/:sessionId/status
```

### Messages (Protected)
```
POST   /api/messages/:sessionId/send
GET    /api/messages/:sessionId/list
GET    /api/messages/:sessionId/conversation/:phone
```

### Contacts (Protected)
```
POST   /api/contacts/:sessionId
GET    /api/contacts/:sessionId
GET    /api/contacts/:sessionId/:phone
PUT    /api/contacts/:sessionId/:id
DELETE /api/contacts/:sessionId/:id
```

### Templates (Protected)
```
POST   /api/templates/:sessionId
GET    /api/templates/:sessionId
GET    /api/templates/:sessionId/:id
PUT    /api/templates/:sessionId/:id
POST   /api/templates/:sessionId/:id/render
DELETE /api/templates/:sessionId/:id
```

---

## Documentation Files

### README.md
- Feature overview
- Quick start guide
- API endpoint list
- Database schema
- Error handling
- Security notes

### GUIDE.md
- System architecture
- Detailed installation
- Configuration options
- Complete API reference
- Authentication flow
- Usage examples (JavaScript, cURL, Python)
- Advanced features
- Deployment instructions

### TESTING.md
- Test sequences for all endpoints
- Expected responses
- Postman collection setup
- Error scenarios
- Performance testing examples

### example.js
- Complete working example
- Demonstrates all features
- Ready to run

### client.js
- Reusable JavaScript client
- Can be imported in Node.js projects
- Clean API interface

---

## Usage Examples

### Initialize & Send Message

```javascript
const WhatsAppCRMClient = require('./client');

async function example() {
  const client = new WhatsAppCRMClient('http://localhost:3000');
  
  // Initialize
  const session = await client.initSession();
  console.log('Session:', session.sessionId);
  console.log('API Key:', session.apiKey);
  
  // Wait for QR scan
  await client.waitForAuthentication();
  console.log('✓ Authenticated');
  
  // Send message
  await client.sendMessage('919876543210', 'Hello!');
  
  // Get contacts
  const contacts = await client.getContacts();
  console.log('Contacts:', contacts.contacts);
}

example();
```

### Using cURL

```bash
# Initialize
curl -X POST http://localhost:3000/api/auth/init

# Get QR
curl http://localhost:3000/api/auth/SESSION_ID/qr

# Send message
curl -X POST http://localhost:3000/api/messages/SESSION_ID/send \
  -H "X-API-Key: API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"phone": "919876543210", "message": "Hello!"}'
```

---

## Features

✅ **QR Code Authentication**
- Secure WhatsApp Web login
- No credentials stored
- Session-based management

✅ **Message Management**
- Send messages via API
- Receive incoming messages
- Message history storage
- Conversation view

✅ **Contact Management**
- Add/update/delete contacts
- Contact list management
- Search and filtering

✅ **Message Templates**
- Create reusable templates
- Variable substitution ({{name}}, etc.)
- Template rendering API

✅ **API Key System**
- Unique key per session
- Secure request authentication
- Easy revocation

✅ **Database**
- SQLite for local storage
- Session persistence
- Message history
- Contact information

✅ **Real-time Updates**
- Instant message receiving
- Automatic contact sync
- Live status updates

---

## Deployment Options

### Local Development
```bash
npm run dev
```

### Production with PM2
```bash
pm2 start src/index.js --name "whatsapp-crm"
```

### Docker
```bash
docker build -t whatsapp-crm-api .
docker run -p 3000:3000 whatsapp-crm-api
```

### Nginx Reverse Proxy
```nginx
location / {
    proxy_pass http://localhost:3000;
}
```

---

## Troubleshooting

| Issue | Solution |
|-------|----------|
| QR not loading | Wait 10-15 seconds, check logs |
| 401 errors | Verify X-API-Key header |
| Port in use | Change PORT in .env |
| Database locked | Ensure only one instance |
| Messages not receiving | Check session authenticated |

---

## Security Best Practices

1. Change API key in .env
2. Use HTTPS in production
3. Implement rate limiting
4. Secure database permissions
5. Validate all inputs
6. Use firewall rules
7. Rotate keys regularly
8. Monitor access logs

---

## Performance Tips

1. Add database indexes
2. Implement caching (Redis)
3. Use connection pooling
4. Load balance multiple instances
5. Queue async operations
6. Monitor resource usage

---

## Next Steps

1. **Read Documentation**
   - Start with README.md
   - Review GUIDE.md for details
   - Check TESTING.md for API testing

2. **Install & Run**
   - `npm install`
   - `npm start`
   - Test endpoints

3. **Integrate**
   - Use client.js in your CRM
   - Build UI/UX on top
   - Add custom business logic

4. **Deploy**
   - Configure production .env
   - Setup database backup
   - Use reverse proxy
   - Monitor and maintain

---

## Support & Issues

- Check logs in `logs/` directory
- Review error messages carefully
- Consult TESTING.md for examples
- Verify environment setup
- Test with cURL first

---

## License

ISC

---

## Contact

For issues or questions, refer to the documentation files included in this project.
