# n8n-nodes-sahabat-xpert

Sahabat Xpert - Multi-platform business automation node for n8n workflow automation.

## Description

This package provides a powerful n8n node for Sahabat Xpert multi-service business automation with comprehensive integration capabilities:

### Sahabat Xpert Node

A unified node supporting 4 major business services:

#### 🛒 E-commerce Operations (Bizapp)
- **Get Product List:** Retrieve product catalogs with SKU filtering
- **Submit Order:** Process orders with customer data and product items

#### 💳 Payment Processing
- **Process Payment:** Handle payment transactions *(Coming Soon)*
- **Refund Payment:** Process payment refunds *(Coming Soon)*
- **Check Payment Status:** Monitor payment transaction status *(Coming Soon)*

#### 🚚 Shipping Management
- **Create Shipment:** Generate new shipping orders *(Coming Soon)*
- **Track Shipment:** Monitor shipment status and location *(Coming Soon)*
- **Get Shipping Rates:** Calculate shipping costs and delivery options *(Coming Soon)*

#### 👥 CRM Integration
- **Create Contact:** Add new contacts to CRM system *(Coming Soon)*
- **Update Contact:** Modify existing contact information *(Coming Soon)*
- **Get Contact:** Retrieve contact details and history *(Coming Soon)*

## Installation

### Community Nodes (Recommended)

1. Go to **Settings > Community Nodes** in your n8n instance
2. Click **Install a community node**
3. Enter: `n8n-nodes-sahabat-xpert`
4. Click **Install**

### Manual Installation

```bash
# In your n8n root directory
npm install n8n-nodes-sahabat-xpert
```

### Development Installation

```bash
# Clone this repository
git clone https://github.com/nmhafiz/n8n-nodes-sahabat-xpert.git
cd n8n-nodes-sahabat-xpert

# Install dependencies
npm install

# Build the nodes
npm run build

# Link to your n8n installation
npm link
cd /path/to/your/n8n
npm link n8n-nodes-sahabat-xpert
```

## Node Operations

This package provides one unified node with multiple service operations:

### Sahabat Xpert Node

#### 🛒 E-commerce Service (Bizapp)

**Get Product List Operation:**
- Retrieve all available products from Bizapp API
- Filter products by SKU pattern
- Include/exclude stock information
- Returns comprehensive product details (SKU, name, description, price, stock)

**Submit Order Operation:**
- Submit orders with complete customer information
- Support multiple products per order
- Automatic formatting for phone numbers, emails, and addresses
- Auto-generated order IDs and price formatting
- Real-time order processing

#### 💳 Payment Service *(Coming Soon)*

**Process Payment:** Execute payment transactions with gateway integration
**Refund Payment:** Handle payment reversals and refund processing
**Check Payment Status:** Monitor and verify payment transaction states

#### 🚚 Shipping Service *(Coming Soon)*

**Create Shipment:** Generate shipping orders with carrier integration
**Track Shipment:** Real-time shipment tracking and status updates
**Get Shipping Rates:** Calculate shipping costs and delivery timeframes

#### 👥 CRM Service *(Coming Soon)*

**Create Contact:** Add new customer contacts to CRM system
**Update Contact:** Modify existing contact information and preferences
**Get Contact:** Retrieve detailed contact profiles and interaction history

## Configuration

### Credentials Setup

1. Create new credentials of type **Sahabat Xpert Credentials**
2. Select the appropriate **Service Type** based on your needs:
   - **Bizapp E-commerce:** For e-commerce operations ✅ *Available*
   - **Payment Gateway:** For payment processing services 🚧 *Coming Soon*
   - **Shipping API:** For shipping and logistics operations 🚧 *Coming Soon*
   - **CRM System:** For customer relationship management 🚧 *Coming Soon*

3. Enter the corresponding credentials based on your selected service type:

#### For Bizapp E-commerce: ✅ *Available*
- **Bizapp Secret Key:** Your Bizapp API authentication key

#### For Payment Gateway: 🚧 *Coming Soon*
- **Payment API Key:** Your payment gateway API key
- **Payment API Secret:** Optional API secret for enhanced security

#### For Shipping API: 🚧 *Coming Soon*
- **Shipping API Token:** Access token for shipping service authentication

#### For CRM System: 🚧 *Coming Soon*
- **CRM Access Token:** Access token for CRM system
- **CRM Base URL:** Base URL for your CRM system (optional)

### Usage Examples

#### 🛒 E-commerce Operations

**Get Product List:**
```json
{
  "service": "ecommerce",
  "ecommerceOperation": "getProductList",
  "skuFilter": "PROD",
  "includeStock": true
}
```

**Submit Order:**
```json
{
  "service": "ecommerce",
  "ecommerceOperation": "submitOrder",
  "customerName": "John Doe",
  "customerAddress": "123 Main St, City, State 12345",
  "customerPhone": "+1234567890",
  "customerEmail": "john@example.com",
  "totalPrice": 99.99,
  "products": {
    "productValues": [
      {
        "sku": "PROD001",
        "quantity": 2
      },
      {
        "sku": "PROD002",
        "quantity": 1
      }
    ]
  }
}
```

#### 💳 Payment Operations *(Coming Soon)*

**Process Payment:** *(Preview - Implementation in progress)*
```json
{
  "service": "payment",
  "paymentOperation": "processPayment",
  "amount": 99.99,
  "currency": "MYR",
  "paymentMethod": "credit_card"
}
```

#### 🚚 Shipping Operations *(Coming Soon)*

**Create Shipment:** *(Preview - Implementation in progress)*
```json
{
  "service": "shipping",
  "shippingOperation": "createShipment",
  "recipientName": "John Doe",
  "recipientAddress": "123 Main St, City, State 12345",
  "packageWeight": 2.5
}
```

#### 👥 CRM Operations *(Coming Soon)*

**Create Contact:** *(Preview - Implementation in progress)*
```json
{
  "service": "crm",
  "crmOperation": "createContact",
  "contactName": "John Doe",
  "contactEmail": "john@example.com",
  "contactPhone": "+1234567890"
}
```

## API Compatibility

This package is designed to work with multiple service APIs that support:

### 🛒 E-commerce APIs (Bizapp) ✅ *Fully Implemented*
- RESTful endpoints with JSON communication
- Secret key authentication
- Product catalog and order management

### 💳 Payment Gateway APIs 🚧 *Coming Soon*
- Secure payment processing protocols
- API key/secret authentication
- Transaction management and status tracking

### 🚚 Shipping Service APIs 🚧 *Coming Soon*
- Carrier integration protocols
- Token-based authentication
- Shipment creation and tracking

### 👥 CRM System APIs 🚧 *Coming Soon*
- Customer data management
- OAuth or token authentication
- Contact lifecycle management

## Error Handling

All service operations include comprehensive error handling:

### Common Error Handling
- Network timeouts (30 seconds)
- Invalid response formats
- Authentication failures
- Missing required parameters
- Service-specific validation errors

### Service-Specific Error Handling

#### 🛒 E-commerce (Bizapp)
- INVALIDKEY errors with auto-correction suggestions
- Product SKU validation
- Order format validation

#### 💳 Payment Processing
- Payment gateway connection errors
- Transaction validation failures
- Currency and amount format errors

#### 🚚 Shipping Management
- Carrier API connectivity issues
- Address validation errors
- Package specification errors

#### 👥 CRM Integration
- Contact data validation
- Duplicate contact handling
- CRM system connectivity errors

## Development

```bash
# Install dependencies
npm install

# Build for development
npm run dev

# Build for production
npm run build

# Run linting
npm run lint

# Format code
npm run format
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Troubleshooting

### Common Issues

#### 1. Service-Specific Authentication Errors

**Problem:** Getting authentication errors for different services

**Solutions:**

**For Bizapp E-commerce (INVALIDKEY Error):**
1. **Check Credential Configuration:**
   ```
   Service Type: Bizapp E-commerce
   Bizapp Secret Key: your-secret-key-here
   ```

2. **Verify Secret Key Format:**
   - Enter your secret key without the `-` prefix
   - The system will automatically add `-` if needed
   - Example: If your key is `abc123`, enter `abc123` (not `-abc123`)

**For Payment Gateway:**
1. Verify API Key and Secret are correct
2. Check if payment gateway service is active
3. Ensure proper currency and amount formats

**For Shipping API:**
1. Validate shipping API token
2. Check carrier service availability
3. Verify address format requirements

**For CRM System:**
1. Confirm CRM access token is valid
2. Check CRM base URL configuration
3. Verify contact data format requirements

**General Solutions:**
3. **Test Credentials:**
   - Click "Test" button in credential settings
   - Ensure you get a successful response

4. **Reinstall Node (if issue persists):**
   ```
   1. Go to Settings > Community Nodes
   2. Uninstall n8n-nodes-sahabat-xpert
   3. Restart n8n
   4. Reinstall n8n-nodes-sahabat-xpert
   5. Reconfigure credentials
   ```

#### 2. Node Not Loading

**Problem:** Node doesn't appear in n8n after installation

**Solutions:**
- Restart n8n service/container
- Clear browser cache
- Check n8n logs for installation errors
- Verify node is installed: `npm list n8n-nodes-sahabat-xpert`

#### 3. Credential Test Fails

**Problem:** Credential test returns error

**Solutions:**
- Verify internet connection
- Check if API endpoint is accessible
- Ensure secret key is valid and active
- Contact API provider if key is expired

#### 4. Empty Product List

**Problem:** Get Product List returns empty array

**Solutions:**
- Verify your account has products configured
- Check if SKU filter is too restrictive
- Test with empty SKU filter first
- Verify API permissions for your account

### Best Practices

#### General Practices
1. **Always test credentials after setup for each service type**
2. **Monitor n8n logs for detailed error messages**
3. **Keep all API keys and tokens secure - never share them**
4. **Update to latest version regularly**
5. **Use appropriate service types for different operations**

#### Service-Specific Best Practices

**🛒 E-commerce (Bizapp):**
- Use exact SKU values from Get Product List operation
- Test with small orders before processing bulk orders
- Validate customer data format before submission

**💳 Payment Processing:**
- Always verify payment amounts and currency
- Implement proper error handling for failed transactions
- Test in sandbox mode before going live

**🚚 Shipping Management:**
- Validate shipping addresses before creating shipments
- Monitor shipment status regularly
- Keep tracking information updated

**👥 CRM Integration:**
- Avoid creating duplicate contacts
- Maintain consistent contact data format
- Regular data synchronization between systems

### Getting Help

If you're still experiencing issues:

1. **Check n8n logs:**
   ```bash
   # Docker
   docker logs n8n-container-name
   
   # PM2
   pm2 logs n8n
   
   # Direct installation
   Check ~/.n8n/logs/
   ```

2. **Test API directly:**
   ```bash
   curl "https://woo.bizapp.my/v2/getproductlist/-YOUR-SECRET-KEY"
   ```

3. **Verify node version:**
   ```bash
   npm list n8n-nodes-sahabat-xpert
   ```



## Support

For issues and questions:
- Create an issue on GitHub
- Check the n8n community forum
- Review the documentation
- Test API endpoints directly for debugging

## Changelog
### v1.4.3 (Latest)

- 🐛 **CRITICAL FIX**: Fixed submit order validation bug
- ✅ Now properly checks Bizapp API response status field
- ❌ Throws error when Bizapp returns failure status
- 📊 Added bizapp_order_id and bizapp_status to response
- 🔍 Enhanced error reporting for failed order submissions

### v1.4.2

- 🏷️ **Penambahan label "Coming Soon"** untuk fitur yang belum diimplementasikan (Payment, Shipping, CRM)
- 📋 **Klarifikasi status implementasi** - E-commerce sepenuhnya fungsional
- 📖 **Peningkatan dokumentasi** dengan indikator status fitur
- 🎯 **Manajemen ekspektasi pengguna** yang lebih baik

### v1.4.1

- 🔧 **Perbaikan minor** dan optimisasi kode
- ✅ **Verifikasi lengkap** semua fungsi telah diuji
- 📦 **Build yang lebih stabil** dengan dependencies terbaru

### v1.4.0

- 🧹 **Menghapus semua fungsi telemetry** untuk privasi maksimal
- 🔒 **Tidak ada pelacakan** - node sepenuhnya bersih dari tracking
- ⚡ **Performa lebih baik** tanpa overhead telemetry
- 🛡️ **Privasi terjamin** - tidak ada data yang dikirim ke server eksternal

### v1.3.0
- ✅ Menambahkan panduan pemecahan masalah yang komprehensif
- 🔧 Solusi untuk kesalahan `INVALIDKEY` dan masalah umum
- 📖 Instruksi instalasi ulang untuk mengatasi masalah cache
- 🐛 Tips debugging dan praktik terbaik manajemen kredensial
- 📚 Panduan lengkap untuk mendapatkan bantuan dan dukungan

### v1.2.9
- 🔧 Perbaikan masalah kompatibilitas kredensial
- 📖 Peningkatan dokumentasi dan contoh penggunaan
- 🐛 Bug fixes untuk stabilitas yang lebih baik

### v1.0.0
- 🎉 Rilis pertama dengan dukungan Bizapp API
- ✅ Operasi Get Product List dan Submit Order
- 🔐 Sistem kredensial yang aman
- 📖 Dokumentasi lengkap dan contoh penggunaan