# MYSOFT E-Invoice Integration - Setup Instructions

## ✅ Completed Steps

-   [x] Service implementation (MysoftEInvoiceService.php)
-   [x] Controller implementation (MysoftEInvoiceController.php)
-   [x] Console command for testing (TestMysoftIntegration.php)
-   [x] Configuration file (config/mysoft.php)
-   [x] Migration file created and executed
-   [x] Routes added to api.php
-   [x] Environment variables added to .env.example
-   [x] Blade view for dashboard (resources/views/mysoft/index.blade.php)
-   [x] Documentation files created

## 📋 Remaining Setup Steps

### 1. Add MYSOFT Configuration to .env

Copy these lines to your `.env` file:

```env
# MYSOFT Settings - TEST Environment (default)
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
```

**For production, change to:**

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

### 2. Create MYSOFT Integration Record

#### Option A: Using Tinker (Recommended)

```bash
php artisan tinker
```

Then paste this code:

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

Exit tinker with `exit`

#### Option B: Using SQL

```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-portal-username@example.com',  -- Change this!
    'your-portal-password',              -- Change this!
    'your-connector-guid-or-api-key',    -- Change this!
    1,
    1,
    1,
    NOW(),
    NOW()
);
```

### 3. Update Supplier Information

Edit `app/Services/MysoftEInvoiceService.php` and update the `buildSupplierData()` method with your actual company information:

```php
protected function buildSupplierData(): array
{
    return [
        'agentAccountName' => 'YOUR COMPANY NAME',
        'agentNumber' => 'YOUR TAX ID OR MERSIS',
        'city' => ['name' => 'YOUR CITY'],
        'country' => ['code' => 'TR', 'name' => 'TÜRKİYE'],
        'citySubdivision' => 'Your District',
        'telephone1' => '+90XXXXXXXXXX',
        'email1' => 'info@yourcompany.com',
        'fax1' => '+90XXXXXXXXXX',
        'postalCode' => 'XXXXX',
        'room' => '',
        'streetName' => 'Your Street',
        'blockName' => '',
        'buildingName' => '',
        'buildingNumber' => '',
        'region' => 'Your Region',
        'district' => 'Your District',
    ];
}
```

### 4. Test the Integration

Run the test command:

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

This will:

-   Display your integration configuration
-   Test token acquisition
-   Test API connection
-   Test invoice document structure building

### 5. Access the Dashboard (Optional)

If you want to use the web interface:

1. Make sure you're logged into the application
2. Navigate to `/mysoft` in your browser
3. You'll see:
    - List of active MYSOFT integrations
    - Test connection button
    - Create e-invoice form

### 6. Test Creating an E-Invoice

#### Via API (using Postman or similar):

```http
POST /api/mysoft/create-invoice
Content-Type: application/json
Authorization: Bearer {your-token}

{
    "sale_id": 1
}
```

#### Via Command Line:

You can create a test sale or use an existing one.

#### Via Dashboard:

1. Go to `/mysoft`
2. Enter a POS Sale ID
3. Click "Create E-Invoice"

## 🎯 Usage Examples

### Single Invoice Creation

```javascript
POST /api/mysoft/create-invoice
{
    "sale_id": 123
}
```

Response:

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

### Batch Invoice Creation

```javascript
POST /api/mysoft/batch-create
{
    "sales": [
        {"sale_id": 123},
        {"sale_id": 124},
        {"sale_id": 125}
    ]
}
```

### Test Connection

```javascript
POST /api/mysoft/test-connection
{
    "integration_id": 1
}
```

### Refresh Token

```javascript
POST /api/mysoft/refresh-token
{
    "integration_id": 1
}
```

## 📊 Monitoring

### View Recent E-Invoices

```sql
SELECT document_no, ettn, status, sent_at, created_at
FROM eadisyon
ORDER BY created_at DESC
LIMIT 10;
```

### Check Integration Status

```sql
SELECT id, title, is_active, access_token, token_expires_at
FROM integrations
WHERE type = 'mysoft';
```

### View Logs

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

## 🐛 Troubleshooting

### No Active Integration Found

Make sure you created the integration record and it's active:

```sql
UPDATE integrations SET is_active = 1 WHERE type = 'mysoft';
```

### Token Issues

Clear cache and refresh:

```bash
php artisan cache:clear
php artisan mysoft:test
```

### Connection Failed

1. Check if credentials are correct
2. Verify internet connection
3. Test endpoint accessibility:

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

## 📝 Important Notes

1. **Token Management**: Tokens are automatically cached for 23 hours
2. **Automatic Retry**: Failed requests retry 3 times by default
3. **Logging**: All operations are logged to `storage/logs/laravel.log`
4. **Eadisyon Records**: Created automatically when invoices are sent
5. **Production URLs**: Remember to update URLs from test to production when going live

## 🚀 Production Deployment

When ready for production:

1. Update `.env`:

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

2. Update integration URL in database:

```sql
UPDATE integrations
SET url = 'https://edocumentapi.mysoft.com.tr/api'
WHERE type = 'mysoft';
```

3. Test connection:

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

## 📚 Documentation Files

-   **Setup Guide**: `MYSOFT_INTEGRATION_SETUP.md`
-   **Implementation Summary**: `MYSOFT_IMPLEMENTATION_SUMMARY.md`
-   **Quick Reference**: `MYSOFT_QUICK_REFERENCE.md`
-   **This File**: `README_MYSOFT_SETUP.md`

## ✅ Checklist

Before going live, ensure:

-   [ ] Migration executed
-   [ ] Integration record created
-   [ ] Supplier data customized
-   [ ] Test passed (`php artisan mysoft:test`)
-   [ ] At least one test invoice created successfully
-   [ ] Production URLs configured (when ready)
-   [ ] Monitoring set up
-   [ ] Team trained on usage

---

**Need Help?**

Check the detailed documentation files or run:

```bash
php artisan mysoft:test --help
```
