Files
logisticsAPI/app/Support/ApiErrorTranslator.php
Marvin bb1bbc2904 Refactor error handling and enhance API interactions across Filament pages
- Introduced `ApiErrorTranslator` to normalize and translate API error messages, providing clearer feedback in French.
- Updated all Filament pages (Articles, Documents, Divers, Journaux, Tiers, TablesExplorer) to utilize the new error translation mechanism, improving user experience during API interactions.
- Added validation for required fields before API calls, ensuring users receive immediate feedback when mandatory inputs are missing.
- Implemented tracking properties to distinguish between "never searched" and "searched without results," enhancing the user interface.
- Removed the obsolete `$results` property from the Articles page and added a new `$barcode` property to align with API requirements.
- Updated documentation to reflect changes in API behavior and error handling, including new metadata returned by the `art_list` endpoint.
- Added new tests to verify the functionality of the barcode handling and validation logic.
2026-02-23 10:15:17 +01:00

75 lines
2.2 KiB
PHP

<?php
namespace App\Support;
class ApiErrorTranslator
{
/**
* @var array<string, string>
*/
private static array $explanations = [
'search terms are required' => 'Le champ de recherche est obligatoire.',
'invalid api key' => 'La cle API configuree est invalide ou absente.',
'api key is required' => 'La cle API est requise dans les en-tetes de la requete.',
'not found' => "L'element demande n'a pas ete trouve dans la base de donnees.",
'layout not found' => 'La valeur du parametre LAYOUT est inconnue ou invalide.',
'unknown stkid' => "L'identifiant de stock (STKID) fourni est inconnu.",
'invalid date' => 'Le format de date fourni est invalide.',
'thirdid is required' => "L'identifiant du tiers est obligatoire.",
'jnl is required' => 'Le code journal est obligatoire.',
'number is required' => 'Le numero de document est obligatoire.',
'artid is required' => "L'identifiant de l'article est obligatoire.",
];
/**
* Normalise et traduit un message d'erreur API.
*
* Le champ `error` de l'API peut etre null, une chaine ou un tableau.
*/
public static function translate(mixed $error): ?string
{
if ($error === null) {
return null;
}
$message = self::normalize($error);
if ($message === '') {
return null;
}
$explanation = self::findExplanation($message);
if ($explanation !== null) {
return "{$message}\n\nExplication : {$explanation}";
}
return $message;
}
/**
* Normalise une valeur error (string ou array) en chaine lisible.
*/
public static function normalize(mixed $error): string
{
if (is_array($error)) {
return implode(' ', array_map('strval', $error));
}
return (string) $error;
}
private static function findExplanation(string $message): ?string
{
$lower = mb_strtolower($message);
foreach (self::$explanations as $pattern => $explanation) {
if (str_contains($lower, $pattern)) {
return $explanation;
}
}
return null;
}
}