# MYSOFT E-Invoice Integration Setup Guide

## Overview

This system integrates with MYSOFT e-document system for creating electronic invoices (e-fatura) and e-receipts (e-adisyon).

## Architecture

### Components

1. **Integration Model** (`app/Models/Integration.php`)

    - Stores MYSOFT credentials and configuration
    - Fields used: `url`, `username`, `password`, `api_key`, `access_token`, `token_expires_at`

2. **MysoftEInvoiceService** (`app/Services/MysoftEInvoiceService.php`)

    - Handles token management
    - Builds invoice documents
    - Communicates with MYSOFT API

3. **MysoftEInvoiceController** (`app/Http/Controllers/MysoftEInvoiceController.php`)

    - RESTful API endpoints
    - Handles requests and responses
    - Creates Eadisyon records

4. **Eadisyon Model** (`app/Models/Eadisyon.php`)
    - Stores created e-invoice records
    - Links to POS sales

## Setup Steps

### 1. Database Migration

Run migration to add MYSOFT fields to integrations table:

```bash
php artisan make:migration add_mysoft_fields_to_integrations_table --table=integrations
```

Migration content:

```php
public function up()
{
    Schema::table('integrations', function (Blueprint $table) {
        $table->string('access_token')->nullable()->after('password');
        $table->timestamp('token_expires_at')->nullable()->after('access_token');
        $table->string('refresh_token')->nullable()->after('token_expires_at');
    });
}

public function down()
{
    Schema::table('integrations', function (Blueprint $table) {
        $table->dropColumn(['access_token', 'token_expires_at', 'refresh_token']);
    });
}
```

Then run:

```bash
php artisan migrate
```

### 2. Configuration

Add to `.env`:

```env
MYSOFT_BASE_URL=https://edocumentapi.mytest.tr/api
MYSOFT_TOKEN_ENDPOINT=https://edocumentapi.mytest.tr/oauth/token
MYSOFT_TOKEN_CACHE_DURATION=82800
MYSOFT_DEFAULT_PREFIX=APP
MYSOFT_LOGGING=true
```

### 3. Create Integration Record

In your database, create an integration record:

```sql
INSERT INTO integrations (
    type, tool, title, url, username, password, api_key,
    is_active, current_team_id, user_id, created_at, updated_at
) VALUES (
    'mysoft', 'mysoft', 'MYSOFT E-Invoice',
    'https://edocumentapi.mytest.tr/api',
    'your-username@example.com',
    'your-password',
    'your-api-key-or-connector-guid',
    1, 1, 1, NOW(), NOW()
);
```

Or use Tinker:

```bash
php artisan tinker
```

```php
\App\Models\Integration::create([
    'type' => 'mysoft',
    'tool' => 'mysoft',
    'title' => 'MYSOFT E-Invoice',
    'url' => 'https://edocumentapi.mytest.tr/api',
    'username' => 'your-username@example.com',
    'password' => 'your-password',
    'api_key' => 'your-api-key',
    'is_active' => true,
    'current_team_id' => 1,
    'user_id' => 1,
]);
```

### 4. Add Routes

Add to `routes/web.php` or `routes/api.php`:

```php
use App\Http\Controllers\MysoftEInvoiceController;

Route::prefix('mysoft')->group(function () {
    Route::get('/', [MysoftEInvoiceController::class, 'index'])->name('mysoft.index');
    Route::post('/test-connection', [MysoftEInvoiceController::class, 'testConnection'])->name('mysoft.test');
    Route::post('/create-invoice', [MysoftEInvoiceController::class, 'createInvoice'])->name('mysoft.create');
    Route::post('/batch-create', [MysoftEInvoiceController::class, 'batchCreateInvoices'])->name('mysoft.batch');
    Route::post('/refresh-token', [MysoftEInvoiceController::class, 'refreshToken'])->name('mysoft.refresh');
});
```

## Usage

### Single Invoice Creation

```javascript
POST /api/mysoft/create-invoice
Content-Type: application/json

{
    "sale_id": 123,
    "integration_id": 1 // Optional, uses active MYSOFT integration if not provided
}
```

Response:

```json
{
    "success": true,
    "message": "E-invoice created successfully",
    "data": {
        "ettn": "b0743d52-4641-4406-b13d-294badc203b4",
        "docNo": "APP2026000000019",
        "prefix": "APP"
    }
}
```

### Batch Invoice Creation

```javascript
POST /api/mysoft/batch-create
Content-Type: application/json

{
    "sales": [
        {"sale_id": 123},
        {"sale_id": 124},
        {"sale_id": 125}
    ],
    "integration_id": 1
}
```

### Test Connection

```javascript
POST /api/mysoft/test-connection
Content-Type: application/json

{
    "integration_id": 1
}
```

### Refresh Token Manually

```javascript
POST /api/mysoft/refresh-token
Content-Type: application/json

{
    "integration_id": 1
}
```

## Token Management

### Automatic Token Handling

The service automatically:

1. Checks cache for valid token
2. Uses cached token if valid
3. Fetches new token if expired or missing
4. Caches token for 23 hours

### Token Storage

-   Tokens are cached using Laravel Cache
-   Cache key: `mysoft_token_{integration_id}`
-   Cache duration: 23 hours (82800 seconds)
-   Can optionally store in database via `access_token` field

## Data Mapping

### Supplier Data

Update `buildSupplierData()` method in service with your company information:

```php
protected function buildSupplierData(): array
{
    return [
        'agentAccountName' => $this->integration->title ?? config('app.name'),
        'agentNumber' => $this->integration->account_id ?? '',
        'city' => ['name' => 'BURSA'],
        'country' => ['code' => 'TR', 'name' => 'TÜRKİYE'],
        // ... update with actual address
    ];
}
```

### Customer Data

Maps from PosSale/Customer model fields:

| MYSOFT Field | Source Field                       |
| ------------ | ---------------------------------- |
| vknTckn      | tax_number / identification_number |
| accountName  | name / company_name                |
| telephone1   | phone                              |
| email1       | email                              |
| cityName     | city                               |
| postalCode   | postal_code                        |

## Error Handling

### Common Errors

1. **Token Expired**

    - Automatically refreshed
    - Check logs for details

2. **Invalid Credentials**

    - Verify username/password in integration record
    - Check MYSOFT portal access

3. **Schema Validation Errors**
    - Review MYSOFT documentation
    - Check required fields in JSON

### Logging

All operations are logged to Laravel log:

```bash
tail -f storage/logs/laravel.log | grep MYSOFT
```

Log entries include:

-   Token acquisition
-   Invoice creation success/failure
-   API errors

## Testing

### Test Mode

Use MYSOFT test environment:

```env
MYSOFT_BASE_URL=https://edocumentapi.mytest.tr/api
MYSOFT_TOKEN_ENDPOINT=https://edocumentapi.mytest.tr/oauth/token
```

### Production Mode

Update to production URLs:

```env
MYSOFT_BASE_URL=https://edocumentapi.mysoft.com.tr/api
MYSOFT_TOKEN_ENDPOINT=https://edocumentapi.mysoft.com.tr/oauth/token
```

## Monitoring

### Dashboard Integration

View integration status:

```
GET /mysoft
```

Shows:

-   Active integrations
-   Last token refresh
-   Recent invoice creations

### Database Records

Check `eadisyon` table for:

-   Created invoices
-   Status codes
-   Response data

## Troubleshooting

### Token Issues

1. Clear cache:

```bash
php artisan cache:clear
```

2. Manually refresh token via API

3. Check credentials in database

### Connection Issues

1. Test endpoint accessibility:

```bash
curl https://edocumentapi.mytest.tr/oauth/token
```

2. Check firewall/proxy settings

3. Verify SSL certificates

## Security Notes

-   Store credentials securely
-   Use HTTPS in production
-   Rotate API keys periodically
-   Monitor for unauthorized access
-   Log all integration activities

## Support

For MYSOFT-specific issues:

-   Documentation: https://mysoft.com.tr/docs
-   Support: support@mysoft.com.tr

For integration issues:

-   Check Laravel logs
-   Review Eadisyon records
-   Test with sample data first
