# WhatsApp Gateway - Self-Hosted

## Project Overview
Self-hosted WhatsApp Gateway dengan Node.js dan whatsapp-web.js untuk multi-number management, chatbot capabilities, dan customer service automation.

## Current State
Production-ready MVP dengan fitur lengkap untuk WhatsApp automation dan management.

## Tech Stack
- **Backend**: Node.js 20, Express.js
- **WhatsApp Integration**: whatsapp-web.js (self-hosted, tanpa API eksternal)
- **Database**: PostgreSQL dengan Sequelize ORM
- **Real-time**: Socket.io untuk live updates
- **Frontend**: Vanilla JavaScript dengan Bootstrap 5

## Key Features Implemented
1. ✅ Multi WhatsApp number management (private per user/number)
2. ✅ QR Code authentication untuk setiap session
3. ✅ Keyword-based auto-responder dengan customizable templates
4. ✅ REST API endpoints untuk external integrations
5. ✅ Web dashboard untuk monitoring dan management
6. ✅ Message history dan logging per session
7. ✅ Real-time updates menggunakan Socket.io
8. ✅ AI-ready framework (placeholder untuk OpenAI/Gemini)
9. ✅ Contact management dan synchronization
10. ✅ Broadcast messaging capability

## Project Structure
```
├── src/
│   ├── server.js              # Main application entry point
│   ├── config/
│   │   └── database.js        # Database configuration
│   ├── models/                # Sequelize models
│   │   ├── Session.js         # WhatsApp session model
│   │   ├── Message.js         # Message history model
│   │   ├── Contact.js         # Contact management model
│   │   ├── AutoReply.js       # Auto-reply rules model
│   │   └── index.js           # Model exports
│   ├── routes/                # API routes
│   │   ├── sessions.js        # Session management endpoints
│   │   ├── messages.js        # Messaging endpoints
│   │   ├── contacts.js        # Contact endpoints
│   │   └── autoReply.js       # Auto-reply management endpoints
│   └── services/
│       └── WhatsAppService.js # WhatsApp client management
├── public/                    # Frontend files
│   ├── index.html            # Main dashboard
│   ├── css/
│   │   └── style.css         # Custom styles
│   └── js/
│       └── app.js            # Frontend JavaScript
├── package.json              # Dependencies
└── README.md                 # Documentation
```

## Database Schema
- **Sessions**: Menyimpan WhatsApp session info (sessionId, name, phoneNumber, status, qrCode)
- **Messages**: Message history (from, to, body, type, direction, timestamp)
- **Contacts**: Contact information per session
- **AutoReply**: Auto-reply rules dengan keyword matching

## API Endpoints

### Session Management
- `POST /api/sessions/create` - Create new WhatsApp session
- `GET /api/sessions` - Get all sessions
- `GET /api/sessions/:sessionId` - Get specific session
- `DELETE /api/sessions/:sessionId` - Delete session

### Messaging
- `POST /api/messages/send` - Send single message
- `POST /api/messages/broadcast` - Broadcast to multiple contacts
- `GET /api/messages/:sessionId` - Get message history
- `GET /api/messages/:sessionId/chat/:contactId` - Get chat with specific contact

### Auto-Reply
- `POST /api/auto-reply/rules` - Create auto-reply rule
- `GET /api/auto-reply/rules/:sessionId` - Get all rules for session
- `PUT /api/auto-reply/rules/:ruleId` - Update rule
- `DELETE /api/auto-reply/rules/:ruleId` - Delete rule

### Contacts
- `GET /api/contacts/:sessionId` - Get all contacts for session

## Environment Configuration
- `PORT`: Server port (default: 5000)
- `API_KEY`: API authentication key (auto-generated on first run jika belum ada)
- `DATABASE_URL`: PostgreSQL connection string (auto-configured)
- `SESSION_SECRET`: Session encryption secret
- `OPENAI_API_KEY`: (Optional) For AI responses
- `GEMINI_API_KEY`: (Optional) For AI responses

## Auto-Generated Features
- **API Key**: Jika `API_KEY` tidak di-set, sistem akan auto-generate saat first run
  - Generated key: 64-character secure hex string
  - Automatically saved to `.env` file
  - Displayed in console pada startup

## How to Use

### 1. Create WhatsApp Session
1. Buka dashboard
2. Klik "Create New Session"
3. Masukkan Session ID dan Name
4. Scan QR code yang muncul dengan WhatsApp mobile app
5. Tunggu hingga status menjadi "connected"

### 2. Send Messages
1. Pilih tab "Messages"
2. Pilih session yang sudah connected
3. Masukkan phone number tujuan (format: country code + number, e.g., 628123456789)
4. Ketik message dan klik Send

### 3. Setup Auto-Reply
1. Pilih tab "Auto-Replies"
2. Klik "Add Rule"
3. Pilih session, masukkan keyword dan response
4. Pilih match type (exact, contains, startsWith, regex)
5. Set priority (lebih tinggi = diproses lebih dulu)

### 4. API Integration
Gunakan API endpoints untuk integrasi dengan sistem lain. Semua responses dalam format JSON.

## Recent Changes
- **November 13, 2025**: Initial project creation
  - Implemented complete WhatsApp Gateway system
  - Multi-number support dengan session isolation
  - Keyword-based auto-responder
  - Web dashboard dengan real-time updates
  - Complete REST API untuk external integrations
  - AI-ready framework untuk future enhancements

## Notes
- WhatsApp sessions disimpan di folder `.wwebjs_auth/` (per session)
- Session data persisten di PostgreSQL database
- Real-time updates menggunakan Socket.io
- Support multiple concurrent WhatsApp numbers
- Each session isolated dan independent

## Future Enhancements
- Full AI integration dengan OpenAI/Gemini
- Advanced analytics dan reporting
- Message queue untuk high-volume messaging
- Multi-user access dengan role-based permissions
- Webhook system untuk advanced integrations
- Contact segmentation dan tagging
- Scheduled message broadcasting
