Files
logisticsAPI/app/Services/LogisticsService.php
Marvin 4aef33f270 Implement robust error handling and configuration for Logistics API interactions
- Introduced `LogisticsApiException` to handle connection and request errors with user-friendly messages in French.
- Updated `LogisticsService` to include configurable timeout, connection timeout, retry attempts, and sleep duration for retries.
- Enhanced error handling in Filament pages to catch `LogisticsApiException` and provide clear feedback to users.
- Updated `.env` and `config/logistics.php` to support new configuration options.
- Added logging for failed API requests in `api_request_logs`.
- Created comprehensive API documentation for Logistics endpoints.
2026-02-20 10:06:04 +01:00

219 lines
6.4 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\LogisticsApiException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
class LogisticsService
{
private string $baseUrl;
private string $apiKey;
private string $folder;
private int $timeout;
private int $connectTimeout;
private int $retryTimes;
private int $retrySleepMs;
public function __construct()
{
$this->baseUrl = rtrim(config('logistics.base_url'), '/');
$this->apiKey = config('logistics.api_key');
$this->folder = config('logistics.folder');
$this->timeout = config('logistics.timeout', 30);
$this->connectTimeout = config('logistics.connect_timeout', 10);
$this->retryTimes = config('logistics.retry.times', 3);
$this->retrySleepMs = config('logistics.retry.sleep_ms', 500);
}
public function tablesList(): array
{
return $this->post('tables_list');
}
public function columnList(string $table): array
{
return $this->post("column_list/{$table}");
}
/**
* @param array{select?: string, results?: int, search?: string, barcode?: string} $params
*/
public function artList(array $params = []): array
{
return $this->post('art_list', $params);
}
public function artGetStock(string $artId): array
{
return $this->post('art_getstk', ['ARTID' => $artId]);
}
/**
* @param array{select?: string, results?: int, TYPE: string} $params
*/
public function jnlList(array $params = []): array
{
return $this->post('jnl_list', $params);
}
/**
* @param array{select?: string, thirdid?: string} $params
*/
public function documentList(array $params = []): array
{
return $this->post('document_list', $params);
}
public function documentDetail(string $jnl, string $number): array
{
return $this->post('document_detail', [
'jnl' => $jnl,
'number' => $number,
]);
}
/**
* @param array{ThirdId: string, Date: string, Artid: array, Qty: array, Saleprice: array, JNL: string, Discount?: array, Vatid?: array, Vatpc?: array, Attachments?: array} $params
*/
public function documentAdd(array $params): array
{
return $this->post('document_add', $params);
}
/**
* @param array{number: string, Thirdid?: string, Artid?: array, Qty?: array, Saleprice?: array, JNL: string, Attachments?: array} $params
*/
public function documentMod(array $params): array
{
return $this->post('document_mod', $params);
}
public function documentGetStatusList(string $jnl): array
{
return $this->post('Document_GetStatusList', ['jnl' => $jnl]);
}
/**
* @param array{ARTID: string, QTY: string, JNL: string, THIRDID: string, DATE: string} $params
*/
public function documentGetUnitPriceAndVat(array $params): array
{
return $this->post('Document_GetUnitPriceAndVat', $params);
}
public function documentGetDueDate(string $payDelay, string $date): array
{
return $this->post('Document_GetDueDate', [
'paydelay' => $payDelay,
'date' => $date,
]);
}
public function documentGetAttachListThumbnail(string $jnl, string $number): array
{
return $this->post('Document_GetAttachListThumbnail', [
'JNL' => $jnl,
'NUMBER' => $number,
]);
}
/**
* @param array{select?: string, results?: int, search: string} $params
*/
public function thirdList(array $params = []): array
{
return $this->post('third_list', $params);
}
public function thirdGetArtHistory(string $thirdId): array
{
return $this->post('third_GetArtHistory', ['thirdid' => $thirdId]);
}
public function getSerialNumber(): array
{
return $this->post('getserialnumber');
}
/**
* @param array{code: string} $params
*/
public function codesList(array $params): array
{
return $this->post('codes_list', $params);
}
/**
* @return array{data: mixed, metadata: array, error: mixed}
*
* @throws LogisticsApiException
*/
private function post(string $endpoint, array $params = []): array
{
$url = "{$this->baseUrl}/{$this->folder}/{$endpoint}";
try {
$response = Http::withHeaders([
'X-API-KEY' => $this->apiKey,
])
->timeout($this->timeout)
->connectTimeout($this->connectTimeout)
->retry($this->retryTimes, $this->retrySleepMs, fn (\Exception $e) => $e instanceof ConnectionException)
->post($url, $params);
$this->logRequest($endpoint, $params, $response);
return $response->json() ?? [
'data' => null,
'metadata' => ['rowcount' => 0, 'issuccess' => false],
'error' => 'Empty response from API',
];
} catch (ConnectionException $e) {
$this->logFailedRequest($endpoint, $params, $e);
throw LogisticsApiException::connectionTimeout($endpoint, $params, $e);
} catch (\Throwable $e) {
$this->logFailedRequest($endpoint, $params, $e);
throw LogisticsApiException::requestFailed($endpoint, $params, $e);
}
}
private function logRequest(string $endpoint, array $params, Response $response): void
{
$body = $response->body();
$isValidJson = json_decode($body) !== null || $body === 'null';
DB::table('api_request_logs')->insert([
'endpoint' => $endpoint,
'parameters' => json_encode($params),
'response_status' => $response->status(),
'response_data' => $isValidJson ? $body : json_encode(['raw' => $body]),
'created_at' => now(),
'updated_at' => now(),
]);
}
private function logFailedRequest(string $endpoint, array $params, \Throwable $exception): void
{
DB::table('api_request_logs')->insert([
'endpoint' => $endpoint,
'parameters' => json_encode($params),
'response_status' => 0,
'response_data' => json_encode(['error' => $exception->getMessage()]),
'created_at' => now(),
'updated_at' => now(),
]);
}
}