# WooCommerce to MiniCRM Setup Guide

This guide will help you configure the MiniCRM Bridge to automatically sync your WooCommerce orders to MiniCRM.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Step 1: Get MiniCRM Credentials](#step-1-get-minicrm-credentials)
- [Step 2: Basic Configuration](#step-2-basic-configuration)
- [Step 3: Field Mapping](#step-3-field-mapping-optional)
- [Step 4: EPO Field Mapping](#step-4-epo-field-mapping-optional)
- [Step 5: IP Whitelist Configuration](#step-5-ip-whitelist-configuration)
- [Step 6: Test Your Setup](#step-6-test-your-setup)
- [Verification Checklist](#verification-checklist)
- [Next Steps](#next-steps)

---

## Prerequisites

Before you begin, ensure you have:

1. **WordPress website** with WooCommerce installed and active
2. **MiniCRM account** with API access
3. **Admin access** to your WordPress site
4. **At least one test order** in WooCommerce for testing

---

## Step 1: Get MiniCRM Credentials

You'll need three pieces of information from your MiniCRM account:

### 1.1 System ID

1. Log in to your MiniCRM account
2. Go to **Settings** → **API Settings**
3. Find your **System ID** (numeric value, e.g., `1234`)
4. Copy this number - you'll need it in Step 2

### 1.2 API Key

1. In the same **API Settings** page
2. Generate a new API key if you don't have one
3. Copy the **32-character alphanumeric key** (e.g., `a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6`)
4. **Important**: Store this key securely - you won't be able to see it again

### 1.3 Category ID

1. In MiniCRM, go to **Projects** module
2. Find the category where you want orders to be imported
3. Click on the category and look at the URL:
   ```
   https://r3.minicrm.hu/Project/Index/CategoryId/1234
                                                  ^^^^
                                            This is your Category ID
   ```
4. Copy this category ID number

---

## Step 2: Basic Configuration

Now configure the plugin in WordPress:

### 2.1 Open Settings Page

1. In WordPress admin, go to **MiniCRM Bridge** → **WooCommerce Sync**
2. You'll see the configuration form

### 2.2 Enable Sync

☑️ **Check** "Enable WooCommerce Sync"

### 2.3 Enter MiniCRM Credentials

Fill in the credentials you gathered in Step 1:

| Field | Value | Example |
|-------|-------|---------|
| **System ID** | Your MiniCRM system ID (numeric) | `1234` |
| **API Key** | Your 32-character API key | `a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6` |
| **Category ID** | Category where orders will appear | `5678` |

### 2.4 Configure Module Name

**Folder Name**: Enter a name for the project module in MiniCRM

- This will appear as the folder name in MiniCRM Projects
- Example: `WooCommerce Orders`, `Online Store`, `E-Commerce`
- **Required field** - cannot be empty

### 2.5 Set Language/Locale

**Locale**: Choose the language for sync

- **EN** = English (default)
- **HU** = Hungarian
- **RO** = Romanian

This affects:
- Default field names (e.g., "Shipping" vs "Szállítás")
- Date formats in some cases
- Error messages

### 2.6 Configure Shop ID (Multi-Shop Only)

**Shop ID**: Set to `0` unless you have multiple shops

- **Single shop**: Use `0` (default)
- **Multiple shops**: Use unique numbers `0`, `1`, `2`, etc.
- This prevents product ID collisions between shops
- Valid range: 0-99

**How it works:**
```
Shop 0: Product ID 1001 stays as 1001
Shop 1: Product ID 1001 becomes 100001001
Shop 2: Product ID 1001 becomes 200001001
```

### 2.7 Optional Settings

☑️ **Sync Product Descriptions**: Check if you want full product descriptions in MiniCRM

- Descriptions are truncated to 1024 characters
- Unchecked = only product names sync

**Max Orders to Sync**: Number of orders to sync per project (default: 1000)

- Protects against syncing very large histories
- Recommended: 1000 for most sites
- Increase if you have customers with > 1000 orders

☑️ **Debug Mode**: Check only when troubleshooting issues

- Enables detailed logging
- Creates log entries in `wp-content/debug.log`
- **Disable after troubleshooting** to avoid log bloat

### 2.8 Save Settings

Click **Save Settings**

You should see: ✅ "Settings saved successfully"

If you see an error, check the [TROUBLESHOOTING.md](TROUBLESHOOTING.md) guide.

---

## Step 3: Field Mapping (Optional)

Field mapping allows you to sync additional WooCommerce order data to custom fields in MiniCRM.

### 3.1 Understanding Field Mapping

**Syntax:** One mapping per line in this format:
```
wc_field_name:MiniCRMFieldName
```

**Left side** = WooCommerce field name (without `get_` prefix)
**Right side** = MiniCRM custom field name (must exist in MiniCRM)

### 3.2 Common Field Mappings

Add these to the **WooCommerce Field Mapping** textarea:

```
billing_phone:Phone
billing_company:CompanyName
customer_note:CustomerNote
transaction_id:TransactionID
payment_method_title:PaymentMethod
```

### 3.3 Available WooCommerce Fields

You can map any field from `WC_Order` that has a `get_*` method:

| WooCommerce Field | Description | Example Value |
|-------------------|-------------|---------------|
| `billing_phone` | Customer phone number | `+1-555-0123` |
| `billing_company` | Company name | `Acme Corp` |
| `billing_email` | Customer email | `john@example.com` |
| `customer_note` | Order notes from customer | `Please gift wrap` |
| `transaction_id` | Payment transaction ID | `ch_1A2B3C` |
| `payment_method_title` | Payment method name | `Credit Card` |
| `customer_user_agent` | Browser used for order | `Mozilla/5.0...` |
| `customer_ip_address` | Customer IP | `192.168.1.1` |

### 3.4 Finding Field Names

To find available field names:

1. Check WooCommerce documentation: [WC_Order Class Reference](https://woocommerce.github.io/code-reference/classes/WC-Order.html)
2. Look for methods starting with `get_*`
3. Remove the `get_` prefix and use the rest

**Example:**
Method: `get_billing_phone()`
Field name: `billing_phone`

### 3.5 Create Custom Fields in MiniCRM

**Before mapping**, ensure the MiniCRM field exists:

1. In MiniCRM, go to **Settings** → **Custom Fields**
2. Create fields matching your right-side mapping values:
   - Field Name: `Phone`
   - Field Type: `Text` (or appropriate type)
3. Save the custom field
4. Now you can map to it: `billing_phone:Phone`

### 3.6 Validation

The plugin validates field mappings when you save:

- ❌ Invalid: `invalidfield:Phone` (WooCommerce doesn't have `get_invalidfield()`)
- ✅ Valid: `billing_phone:Phone` (WooCommerce has `get_billing_phone()`)

---

## Step 4: EPO Field Mapping (Optional)

If you use the **WooCommerce Extra Product Options** (EPO) plugin, you can sync custom product fields to MiniCRM.

### 4.1 What are EPO Fields?

EPO (Extra Product Options) are additional fields on products:
- Gift messages
- Custom text engraving
- Delivery instructions
- Color/size variations (if not using WooCommerce variations)

### 4.2 EPO Field Mapping Syntax

Same format as field mapping:
```
EPO Label:MiniCRMFieldName
```

**Left side** = Exact label from EPO field
**Right side** = MiniCRM custom field name

### 4.3 Example EPO Mappings

Add these to the **EPO Field Mapping** textarea:

```
Gift Message:GiftMessage
Engraving Text:EngravingText
Delivery Instructions:DeliveryInstructions
Special Requests:SpecialRequests
```

### 4.4 Finding EPO Labels

1. Edit a product that has EPO fields
2. Look at the field labels in the EPO configuration
3. Use the **exact label** (case-sensitive)

### 4.5 Create MiniCRM Fields

Same as Step 3.5:
1. Create custom fields in MiniCRM
2. Match the names to your EPO mapping right side
3. Save and test

### 4.6 Testing EPO Sync

1. Create a test order with EPO fields filled
2. Sync the order (see Step 6)
3. Check MiniCRM project to verify EPO values appear in custom fields

---

## Step 5: IP Whitelist Configuration

MiniCRM will pull your order feed via a secure URL. You need to whitelist MiniCRM's IP address(es).

### 5.1 Get MiniCRM IP Addresses

Contact MiniCRM support or check their documentation for current IP ranges.

**Example MiniCRM IPs** (verify current IPs with MiniCRM):
```
203.0.113.0/24
198.51.100.50
```

### 5.2 Configure IP Whitelist

In the **WooCommerce Sync** settings page, scroll to **Security Settings**.

**IP Whitelist**: Enter allowed IP addresses or ranges (one per line)

#### Format 1: Single IP Address
```
203.0.113.50
198.51.100.25
```

#### Format 2: CIDR Notation (IP Range)
```
203.0.113.0/24
198.51.100.0/28
```

**CIDR Examples:**
- `203.0.113.0/24` = allows `203.0.113.0` through `203.0.113.255` (256 IPs)
- `198.51.100.0/28` = allows `198.51.100.0` through `198.51.100.15` (16 IPs)

### 5.3 Testing IP Whitelist

After configuration:

1. Save settings
2. Try manual sync (Step 6)
3. If you get "Access Denied" errors, check [TROUBLESHOOTING.md](TROUBLESHOOTING.md) → "Feed Access Denied (403)"

---

## Step 6: Test Your Setup

Now test that everything works!

### 6.1 Create a Test Order

If you don't have one already:

1. Add a product to cart on your WooCommerce site
2. Complete checkout with a test customer
3. Note the order number (e.g., #123)

### 6.2 Manual Sync

On the **WooCommerce Sync** settings page:

1. Scroll to the **Manual Sync** section
2. Click **Load Projects** button
3. You should see a list of customers/projects
4. **Check** the checkbox next to your test project
5. Click **Sync Selected Projects**
6. Wait for the progress bar to complete

### 6.3 Check MiniCRM

1. Log in to MiniCRM
2. Go to **Projects** → Your configured category
3. You should see a new project for the customer
4. Open the project
5. Verify:
   - ✅ Customer name is correct
   - ✅ Order appears with correct status, date, total
   - ✅ Products are listed with quantities and prices
   - ✅ Custom fields are populated (if you configured mappings)
   - ✅ Addresses are correct (billing/shipping)

### 6.4 Test Automatic Sync

1. Create another test order in WooCommerce
2. Wait 5-10 seconds (automatic sync happens on page load completion)
3. Check MiniCRM - new order should appear automatically

---

## Verification Checklist

Use this checklist to ensure everything is configured correctly:

### Basic Configuration
- [ ] "Enable WooCommerce Sync" is checked
- [ ] System ID is numeric and correct
- [ ] API Key is 32 characters
- [ ] Category ID is correct (checked in MiniCRM)
- [ ] Folder Name is filled in
- [ ] Locale is appropriate (EN/HU/RO)
- [ ] Shop ID is correct (0 for single shop)

### Field Mapping (if used)
- [ ] WooCommerce field mappings use correct syntax (`field:Field`)
- [ ] All mapped MiniCRM fields exist in MiniCRM
- [ ] EPO mappings match exact EPO label names
- [ ] Test order shows custom fields in MiniCRM

### Security
- [ ] MiniCRM IP addresses are whitelisted
- [ ] IP whitelist uses correct format (IP or CIDR)
- [ ] Manual sync works (no "Access Denied" errors)

### Testing
- [ ] Manual sync loads projects successfully
- [ ] Manual sync completes without errors
- [ ] Test project appears in MiniCRM
- [ ] All order data is correct in MiniCRM
- [ ] Automatic sync works (new order appears)

### Production Readiness
- [ ] Debug mode is OFF (unchecked)
- [ ] Settings saved successfully
- [ ] No validation errors
- [ ] Checked [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for common issues

---

## Next Steps

### Learn How Sync Works
Read [SYNC-FLOW.md](SYNC-FLOW.md) to understand:
- When automatic sync triggers
- How project IDs are calculated
- What data gets synced
- Security mechanisms (nonces, IP whitelist)

### Troubleshooting
If you encounter issues, check [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for:
- Common error messages
- Debug mode usage
- How to read logs
- Feed URL testing
- Support checklist

### Architecture (Developers)
For developers wanting to extend or modify the integration, see [../README.md](../README.md) for:
- Module architecture
- Design patterns used
- Key classes and responsibilities
- Extension points

---

## Support

If you need help:

1. **Check troubleshooting guide**: [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
2. **Enable debug mode** and check logs (`wp-content/debug.log`)
3. **Verify all credentials** are correct in MiniCRM
4. **Contact MiniCRM support** for API-related issues
5. **Contact plugin developer** with:
   - WordPress version
   - WooCommerce version
   - PHP version
   - Error messages from debug log
   - Steps to reproduce the issue

---

**Setup complete!** Your WooCommerce orders will now sync automatically to MiniCRM. 🎉
