# MYSOFT E-Invoice Integration - Implementation Summary

## Files Created/Modified

### New Files

1. **app/Services/MysoftEInvoiceService.php**

    - Main service for MYSOFT integration
    - Token management (automatic caching, refresh)
    - Invoice document building
    - API communication
    - Error handling and logging

2. **app/Http/Controllers/MysoftEInvoiceController.php**

    - RESTful API controller
    - Endpoints for:
        - Single invoice creation
        - Batch invoice creation
        - Connection testing
        - Token refresh
    - Integration with Eadisyon model

3. **app/Console/Commands/TestMysoftIntegration.php**

    - CLI command for testing integration
    - Tests token acquisition, connection, and document building
    - Usage: `php artisan mysoft:test`

4. **config/mysoft.php**

    - Configuration file for MYSOFT settings
    - Environment variable overrides
    - Retry settings and defaults

5. **MYSOFT_INTEGRATION_SETUP.md**
    - Complete setup documentation
    - Usage examples
    - Troubleshooting guide

### Modified Files

1. **app/Models/Integration.php**
    - Added MYSOFT-specific fields:
        - `access_token`
        - `token_expires_at`
        - `refresh_token`
    - Note: Uses existing `url` field for endpoint URL (as requested)

## Key Features

### 1. Token Management

-   **Automatic**: Tokens are automatically fetched and cached
-   **Cache Duration**: 23 hours (82800 seconds)
-   **Storage**: Laravel cache + optional database storage
-   **Refresh**: Automatic on expiration or manual via API

### 2. Invoice Creation

-   **Single**: Create invoice for one sale at a time
-   **Batch**: Process multiple sales in one request
-   **Auto-mapping**: Maps PosSale data to MYSOFT format
-   **Logging**: All operations logged for audit trail

### 3. Data Mapping

#### Supplier Information

Uses integration settings and company configuration:

-   Company name from integration title
-   Address (needs customization in service)
-   Contact information

#### Customer Information

Maps from PosSale/Customer:

-   Tax ID → vknTckn
-   Name → accountName
-   Address fields → street, city, postal code
-   Contact → phone, email

#### Line Items

From PosSale orders:

-   Product name → itemName
-   Quantity → quantity
-   Price → unitPrice
-   VAT → amtVat, vatRate

### 4. Error Handling

-   Try-catch blocks on all API calls
-   Detailed error logging
-   User-friendly error messages
-   Graceful failure handling

## API Endpoints

### Base URL

```
/api/mysoft/
```

### Available Routes

1. **Test Connection**

    ```
    POST /test-connection
    Body: { "integration_id": 1 }
    ```

2. **Create Single Invoice**

    ```
    POST /create-invoice
    Body: { "sale_id": 123, "integration_id": 1 }
    ```

3. **Batch Create Invoices**

    ```
    POST /batch-create
    Body: { "sales": [{"sale_id": 123}, ...], "integration_id": 1 }
    ```

4. **Refresh Token**

    ```
    POST /refresh-token
    Body: { "integration_id": 1 }
    ```

5. **View Integrations**
    ```
    GET /
    ```

## Database Changes

### Integration Model Fields

```php
[
    'type' => 'mysoft',
    'tool' => 'mysoft',
    'url' => 'https://edocumentapi.mytest.tr/api', // Endpoint URL
    'username' => 'portal-username',
    'password' => 'portal-password',
    'api_key' => 'connector-guid-or-api-key',
    'access_token' => 'cached-access-token',
    'token_expires_at' => '2026-03-12 14:40:00',
    'refresh_token' => 'refresh-token-for-renewal',
]
```

### Eadisyon Records

Created automatically when invoices are sent:

-   Stores ETTN (universally unique tracking number)
-   Document number
-   Response data
-   Status and timestamps

## Configuration

### Environment Variables (.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
MYSOFT_RETRY_COUNT=3
MYSOFT_RETRY_DELAY=1000
```

### Config File (config/mysoft.php)

Provides defaults and environment variable mapping for all MYSOFT settings.

## Testing

### Command Line

```bash
# Test with default active integration
php artisan mysoft:test

# Test specific integration
php artisan mysoft:test --integration=1
```

### API Testing

Use Postman or similar tool to test endpoints (see API Endpoints section).

### Logging

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

## Setup Checklist

-   [ ] Run migration to add MYSOFT fields to integrations table
-   [ ] Add environment variables to .env
-   [ ] Publish config: `php artisan vendor:publish --provider="..."` (if needed)
-   [ ] Create integration record in database
-   [ ] Add routes to routes/web.php or api.php
-   [ ] Test connection: `php artisan mysoft:test`
-   [ ] Update supplier data in service (company address, etc.)
-   [ ] Test with sample sale data
-   [ ] Configure production URLs when ready

## Customization Points

### 1. Supplier Data

Update `buildSupplierData()` in MysoftEInvoiceService.php with actual company information.

### 2. Customer Mapping

Modify `buildCustomerData()` if your customer model has different field names.

### 3. Totals Calculation

Adjust `buildTotals()` based on how your PosSale model stores amounts.

### 4. Line Items

Customize `buildLineItems()` for your specific order structure.

### 5. Prefix/Document Numbering

Change default prefix in config or build logic per integration settings.

## Security Considerations

1. **Credentials Storage**

    - Stored in database (encrypted recommended)
    - Use environment variables for sensitive data
    - Limit database access

2. **Token Security**

    - Cached securely in Laravel cache
    - Not exposed in responses
    - Automatically rotated

3. **API Security**

    - Use HTTPS in production
    - Implement authentication middleware
    - Log all access attempts

4. **Data Privacy**
    - Customer data handled per regulations
    - Audit trail maintained
    - Access controls recommended

## Next Steps

1. **Run Migration**

    ```bash
    php artisan make:migration add_mysoft_fields_to_integrations_table
    # Edit migration file
    php artisan migrate
    ```

2. **Add Routes**
   Add to routes/api.php or web.php

3. **Create Integration Record**
   Via tinker or SQL

4. **Test Integration**

    ```bash
    php artisan mysoft:test
    ```

5. **Customize Supplier Data**
   Update service with company details

6. **Deploy to Production**
    - Update URLs to production
    - Configure SSL
    - Set up monitoring

## Support & Resources

-   **Setup Guide**: MYSOFT_INTEGRATION_SETUP.md
-   **Token Docs**: resources/eadisyon/mysoft/token-alma.md
-   **Sample JSON**: resources/eadisyon/mysoft/eadisyon-ornek.json
-   **MYSOFT Docs**: https://mysoft.com.tr/docs

## Architecture Diagram

```
┌─────────────┐      ┌──────────────────┐      ┌─────────────┐
│   Client    │─────▶│  MysoftController│─────▶│ MysoftService│
│ (Frontend/  │      │                  │      │              │
│  API)       │◀─────│                  │◀─────│              │
└─────────────┘      └──────────────────┘      └──────┬──────┘
                                                       │
                    ┌──────────────────────────────────┼──────────┐
                    │                                  │          │
                    ▼                                  ▼          ▼
            ┌──────────────┐                  ┌────────────┐ ┌─────────┐
            │ Integration  │                  │   Cache    │ │ MYSOFT  │
            │    Model     │                  │  (Tokens)  │ │   API   │
            └──────────────┘                  └────────────┘ └─────────┘
                    │
                    ▼
            ┌──────────────┐
            │   Eadisyon   │
            │    Model     │
            └──────────────┘
```

## Implementation Status

✅ Service layer implementation  
✅ Controller with CRUD operations  
✅ Token management system  
✅ Data mapping and transformation  
✅ Error handling and logging  
✅ Test command  
✅ Configuration files  
✅ Documentation

⏳ Migration (to be run)  
⏳ Routes (to be added)  
⏳ Supplier data customization (manual step)  
⏳ Production deployment (future step)
