# PosCloud API Integration - Customer Transactions

## Overview

This integration enables creating customer transactions through the PosCloud (Bulut Adisyon) API. All write operations for customer transactions are performed exclusively via the PosCloud API, while read operations continue to use the remote database.

## Architecture

### Write Operations (API-Only)
- **New Transaction Creation** → PosCloud API
- **Deferred Sale Collection** → PosCloud API
- **No local fallback** - If API fails, no record is created

### Read Operations (Database)
- **Balance Calculation** → Remote Database (`PosCustomerTransactions` model)
- **Transaction List** → Remote Database
- **Deferred Sales** → Remote Database (`PosSale` model)

## Configuration

### 1. Environment Variables

Add to `.env`:

```env
# PosCloud API Configuration (optional - defaults are set)
POSCLOUD_PROD_URL=https://api.bulutadisyon.com
POSCLOUD_DEV_URL=https://dev.api.bulutadisyon.com
POSCLOUD_BETA_URL=https://beta.api.bulutadisyon.com
```

### 2. Integration Record

Create an Integration record in the database:

```php
Integration::create([
    'slug' => 'bulutadisyon',
    'title' => 'PosCloud Integration',
    'account_id' => YOUR_COMPANY_ID, // Must match session('selected_pos_service_id')
    'api_key' => 'YOUR_POSCLOUD_API_KEY', // From PosCloud dashboard
    'is_active' => true,
    'type' => 'pos',
]);
```

## Implementation Details

### Service: `PosCloudService`

Location: `app/Services/PosCloudService.php`

**Key Features:**
- Automatic environment detection (dev/staging/prod)
- API key retrieval from Integration model
- Date format conversion (Laravel → PosCloud format: `DD.MM.YYYY HH:mm`)
- Comprehensive error handling and logging
- 30-second HTTP timeout

**Main Method:**
```php
createCustomerTransaction(
    int $customerId,
    float $amount,
    string $direction,  // 'collection' or 'payment'
    int $paymentType,
    array $optionalFields = []
): array
```

**Returns:**
```php
[
    'success' => bool,
    'message' => string,
    'data' => mixed|null,
    'error_code' => string|null  // Only on error
]
```

### Livewire Component: `CustomerTransactions`

Location: `app/Livewire/CustomerTransactions.php`

**Modified Methods:**

1. **`addTransaction()`** - Manual transaction creation
   - Validates input
   - Calls PosCloud API
   - If API succeeds → Refresh data from remote DB
   - If API fails → Show error, no record created

2. **`collectSale()`** - Deferred sale collection
   - Same flow as `addTransaction()`
   - Uses direction: 'collection'
   - Description includes sale reference

## Workflow

### Successful Transaction Creation

```
User fills form
    ↓
Livewire validates
    ↓
PosCloudService.createCustomerTransaction()
    ↓
HTTP POST → https://api.bulutadisyon.com/api/customer-transactions
    ↓
PosCloud Backend:
  - Creates transaction in PosCloud DB
  - Syncs to your remote database
    ↓
API returns success (200 + success:true)
    ↓
Component calls refreshData()
    ↓
Remote DB queried for updated list
    ↓
UI updates with new transaction
    ↓
Success message shown
```

### Failed Transaction

```
User fills form
    ↓
Livewire validates
    ↓
PosCloudService.createCustomerTransaction()
    ↓
HTTP POST fails OR API returns error
    ↓
Error logged to storage/logs/laravel.log
    ↓
Error message shown to user
    ↓
NO record created anywhere
    ↓
Modal stays open (user can retry)
```

## Error Handling

### Types of Errors

1. **Missing API Key**
   - Message: "PosCloud API anahtarı yapılandırılmamış"
   - Action: Check Integration record

2. **Connection Error**
   - Message: "PosCloud API'ye bağlanılamadı"
   - Action: Check internet connection

3. **API Validation Error**
   - Message: From PosCloud API response
   - Action: Fix input data

4. **Unexpected Error**
   - Message: Exception details
   - Action: Check logs

### Logging

All API calls are logged to `storage/logs/laravel.log`:

```
[INFO] PosCloud API: Transaction oluşturuluyor
[INFO] PosCloud API: Transaction başarıyla oluşturuldu
[WARNING] PosCloud API: Transaction oluşturma başarısız
[ERROR] PosCloud API: Bağlantı hatası
```

## Payment Type Mapping

| ID | Name          | Description        |
|----|---------------|--------------------|
| 1  | Cash          | Nakit              |
| 2  | Credit Card   | Kredi Kartı        |
| 3  | Ticket        | Ticket/Yemek Çeki  |
| 4  | Online        | Online Ödeme       |

## Testing

### Manual API Test

```bash
curl -X POST "https://dev.api.bulutadisyon.com/api/customer-transactions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
      "customer_id": 45,
      "amount": 150.00,
      "direction": "collection",
      "payment_type": 1,
      "paid_at": "13.05.2026 14:30",
      "description": "Test transaction"
  }'
```

### Expected Success Response

```json
{
    "data": {
        "transaction_id": 1205,
        "customer_id": 45,
        "amount": 150.00,
        "direction": "collection",
        "payment_type": 1,
        "paid_at": "2026-05-13 14:30:00",
        "description": "Test transaction",
        "balance_after": 500.00
    },
    "success": true,
    "errorCode": null,
    "message": "Transaction created successfully."
}
```

### UI Testing Checklist

- [ ] Create manual transaction (success case)
- [ ] Create manual transaction (API failure case)
- [ ] Collect deferred sale (success case)
- [ ] Collect deferred sale (API failure case)
- [ ] Verify balance updates correctly
- [ ] Verify transaction list refreshes
- [ ] Test with invalid API key
- [ ] Test with network disconnection
- [ ] Verify error messages are user-friendly

## Troubleshooting

### Issue: "API key not configured"

**Solution:**
1. Check Integration table for record with `slug='bulutadisyon'`
2. Verify `api_key` field is populated
3. Verify `is_active = true`
4. Verify `account_id` matches `session('selected_pos_service_id')`

### Issue: "Invalid API key"

**Solution:**
1. Regenerate API key in PosCloud dashboard
2. Update Integration record
3. Clear application cache: `php artisan cache:clear`

### Issue: "Connection timeout"

**Solution:**
1. Check server internet connectivity
2. Verify firewall allows outbound HTTPS to PosCloud domains
3. Check if PosCloud API is experiencing downtime

### Issue: Transaction not appearing after success

**Solution:**
1. Check if `refreshData()` is being called
2. Verify remote database connection is working
3. Check if PosCloud backend synced to your remote DB
4. Manually query remote DB to verify record exists

## Important Notes

1. **No Local Fallback**: Unlike some integrations, there is NO local database write if the API fails. The operation is atomic - either it succeeds completely or not at all.

2. **Remote Database**: The `PosCustomerTransactions` model uses the `mysql-remote` connection. After successful API call, we query this remote database to get updated data.

3. **PosCloud Responsibility**: When the API returns success, PosCloud's backend is responsible for writing to both their database AND your remote database. We don't do any direct database writes.

4. **Direction Parameter**: All manual transactions and collections use `direction='collection'` (money coming IN from customer).

5. **Date Format**: The service automatically converts Laravel datetime format to PosCloud's expected format (`DD.MM.YYYY HH:mm`).

## Future Enhancements

- [ ] Add retry mechanism with exponential backoff
- [ ] Implement background job queue for better UX
- [ ] Add transaction reconciliation feature
- [ ] Support for bulk transaction creation
- [ ] Webhook support for real-time sync confirmation
