Implement localization for API responses and error messages

- Added localization support for API responses in English and Spanish.
- Introduced a middleware to set the API locale based on the Accept-Language header.
- Updated various exception messages and validation responses to use localized strings.
- Created new language files for English and Spanish translations.
- Refactored existing code to replace hardcoded messages with localized strings.
- Added tests to verify localization functionality and response correctness.
This commit is contained in:
2026-07-28 10:19:39 -03:00
parent 754aeebe3a
commit ff9d7728e8
34 changed files with 654 additions and 114 deletions

View File

@@ -24,7 +24,8 @@ class CreateResetPasswordAttemptController extends Controller
);
return response()->json([
'message' => 'Si el email está registrado, recibirás un código para recuperar tu contraseña.',
'code' => 'auth.password_reset_requested',
'message' => __('api.auth.password_reset_requested'),
'status' => ResetPasswordAttempt::STATUS_PENDING,
], 202);
}

View File

@@ -35,7 +35,8 @@ class GoogleTokenExchangeController extends Controller
);
$response = response()->json([
'message' => 'Sesion iniciada correctamente.',
'code' => 'auth.login_success',
'message' => __('api.auth.login_success'),
'token' => $authentication['token'],
'token_type' => 'Bearer',
'user' => UserResource::make($authentication['user']),

View File

@@ -28,7 +28,7 @@ class LoginController extends Controller
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
throw ValidationException::withMessages([
'email' => 'Email o Contraseña incorrectos.',
'email' => __('api.auth.invalid_credentials'),
]);
}
@@ -50,7 +50,8 @@ class LoginController extends Controller
);
$response = response()->json([
'message' => 'Sesion iniciada correctamente.',
'code' => 'auth.login_success',
'message' => __('api.auth.login_success'),
'token' => $token,
'token_type' => 'Bearer',
'user' => UserResource::make($user),

View File

@@ -23,7 +23,8 @@ class LogoutController extends Controller
}
return response()->json([
'message' => 'Sesion cerrada correctamente.',
'code' => 'auth.logout_success',
'message' => __('api.auth.logout_success'),
]);
}
}

View File

@@ -12,15 +12,17 @@ class RegisterController extends Controller
{
public function __construct(
protected RegisterUserService $registerUserService,
) {
}
) {}
public function __invoke(RegisterUserRequest $request): JsonResponse
{
$user = $this->registerUserService->register($request->validated());
return UserResource::make($user)
->additional(['message' => 'Usuario registrado correctamente.'])
->additional([
'code' => 'auth.register_success',
'message' => __('api.auth.register_success'),
])
->response()
->setStatusCode(201);
}

View File

@@ -28,12 +28,13 @@ class ResetPasswordController extends Controller
$data['password'],
)) {
throw ValidationException::withMessages([
'codigo' => 'La solicitud de recuperación es inválida o ya fue utilizada.',
'codigo' => __('api.auth.password_reset_invalid'),
]);
}
return response()->json([
'message' => 'Contraseña modificada correctamente.',
'code' => 'auth.password_updated',
'message' => __('api.auth.password_updated'),
'status' => ResetPasswordAttempt::STATUS_USED,
]);
}

View File

@@ -27,12 +27,13 @@ class ValidateResetPasswordAttemptController extends Controller
$data['codigo'],
)) {
throw ValidationException::withMessages([
'codigo' => 'El código ingresado es inválido.',
'codigo' => __('api.auth.reset_code_invalid'),
]);
}
return response()->json([
'message' => 'Código validado correctamente.',
'code' => 'auth.reset_code_valid',
'message' => __('api.auth.reset_code_valid'),
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
]);
}

View File

@@ -25,7 +25,7 @@ class GoogleAuthService
if (! $tenant || ! $this->isTenantReturnUrl($returnUrl, $tenant)) {
throw ValidationException::withMessages([
'tenant' => 'El tenant o la URL de retorno no son validos.',
'tenant' => __('api.auth.invalid_tenant_or_return_url'),
]);
}
@@ -50,13 +50,13 @@ class GoogleAuthService
$context = Str::isUuid($state) ? Cache::pull("google-oauth-context:{$state}") : null;
if (! is_array($context) || ! isset($context['tenant_codigo'], $context['return_url'])) {
abort(400, 'La solicitud de autenticacion expiro. Intenta nuevamente.');
abort(400, __('api.auth.request_expired'));
}
$tenant = Tenant::query()->where('codigo', $context['tenant_codigo'])->first();
if (! $tenant || ! $this->isTenantReturnUrl($context['return_url'], $tenant)) {
abort(400, 'La URL de retorno no es valida.');
abort(400, __('api.auth.invalid_return_url'));
}
/** @var SocialiteUser $googleUser */
@@ -88,13 +88,13 @@ class GoogleAuthService
if (! $authentication) {
throw ValidationException::withMessages([
'oauth_code' => 'El codigo de autenticacion expiro o ya fue utilizado.',
'oauth_code' => __('api.auth.oauth_code_expired'),
]);
}
if (($authentication['tenant_codigo'] ?? null) !== $tenantCodigo) {
throw ValidationException::withMessages([
'tenant_codigo' => 'El tenant no coincide con la solicitud de autenticacion.',
'tenant_codigo' => __('api.auth.tenant_mismatch'),
]);
}
@@ -112,7 +112,7 @@ class GoogleAuthService
if (! is_string($googleId) || $googleId === '' || ! is_string($email) || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw ValidationException::withMessages([
'google' => 'Google no devolvio una identidad valida.',
'google' => __('api.auth.google_email_required'),
]);
}
@@ -120,7 +120,7 @@ class GoogleAuthService
$emailVerified = $rawUser['email_verified'] ?? $rawUser['verified_email'] ?? false;
if (! in_array($emailVerified, [true, 'true', 1, '1'], true)) {
throw ValidationException::withMessages([
'google' => 'La cuenta de Google debe tener el email verificado.',
'google' => __('api.auth.google_email_unverified'),
]);
}

View File

@@ -36,7 +36,10 @@ class CartController extends Controller
);
$response = CartResource::make($result['cart'])
->additional(['message' => 'Producto agregado al carrito.'])
->additional([
'code' => 'cart.item_added',
'message' => __('api.cart.item_added'),
])
->response();
if ($result['guest_token'] !== null) {
@@ -58,13 +61,19 @@ class CartController extends Controller
$cartItem->getKey(),
(int) $request->validated('cantidad'),
)
)->additional(['message' => 'Cantidad de producto actualizada.']);
)->additional([
'code' => 'cart.quantity_updated',
'message' => __('api.cart.quantity_updated'),
]);
}
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
{
return CartResource::make(
$this->cartService->removeItem($tenant, $request, $cartItem->getKey())
)->additional(['message' => 'Producto eliminado del carrito.']);
)->additional([
'code' => 'cart.item_removed',
'message' => __('api.cart.item_removed'),
]);
}
}

View File

@@ -79,7 +79,7 @@ class Cart extends Model
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
'cantidad' => 'La cantidad debe ser mayor a cero.',
'cantidad' => __('api.cart.positive_quantity'),
]);
}
@@ -91,7 +91,7 @@ class Cart extends Model
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
'cantidad' => "Stock insuficiente para el producto solicitado. Maximo disponible: {$availableQuantity}.",
'cantidad' => __('api.cart.insufficient_stock', ['max' => $availableQuantity]),
]);
}
@@ -123,7 +123,7 @@ class Cart extends Model
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
'cantidad' => 'La cantidad debe ser mayor a cero.',
'cantidad' => __('api.cart.positive_quantity'),
]);
}
@@ -146,7 +146,7 @@ class Cart extends Model
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad;
throw ValidationException::withMessages([
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
'cantidad' => __('api.cart.max_quantity', ['max' => $maxAvailable]),
]);
}
@@ -209,13 +209,13 @@ class Cart extends Model
if ($catalogItem->isBundle()) {
if ($variantId !== null) {
throw ValidationException::withMessages([
'variant_id' => 'Un bundle no admite una variante.',
'variant_id' => __('api.cart.bundle_variant_forbidden'),
]);
}
if (! $catalogItem->bundleComponents()->exists()) {
throw ValidationException::withMessages([
'catalog_item_id' => 'El bundle no tiene componentes.',
'catalog_item_id' => __('api.cart.empty_bundle'),
]);
}
@@ -225,7 +225,7 @@ class Cart extends Model
if ($variantId === null) {
if ($catalogItem->inventory_id === null) {
throw ValidationException::withMessages([
'variant_id' => 'Debe seleccionar una variante para este ítem.',
'variant_id' => __('api.cart.variant_required'),
]);
}

View File

@@ -45,7 +45,7 @@ class CatalogService
} else {
if (array_key_exists('components', $data)) {
throw ValidationException::withMessages([
'components' => ['Un item standard no puede tener componentes.'],
'components' => [__('api.catalog.standard_with_components')],
]);
}
@@ -265,7 +265,7 @@ class CatalogService
if (isset($seen[$key])) {
throw ValidationException::withMessages([
"components.{$index}" => ['El componente esta duplicado.'],
"components.{$index}" => [__('api.catalog.duplicate_component')],
]);
}
$seen[$key] = true;
@@ -278,7 +278,7 @@ class CatalogService
if ($componentItem === null) {
throw ValidationException::withMessages([
"components.{$index}.catalog_item_id" => [
'El item no pertenece al tenant del bundle.',
__('api.catalog.component_wrong_tenant'),
],
]);
}
@@ -286,7 +286,7 @@ class CatalogService
if ($componentItem->is($bundle) || $componentItem->type !== CatalogItemType::Standard) {
throw ValidationException::withMessages([
"components.{$index}.catalog_item_id" => [
'El componente debe ser un item standard distinto del bundle.',
__('api.catalog.invalid_component'),
],
]);
}
@@ -295,7 +295,7 @@ class CatalogService
if ($hasVariants && $variantId === null) {
throw ValidationException::withMessages([
"components.{$index}.variant_id" => [
'Debe seleccionar una variante para este componente.',
__('api.catalog.component_variant_required'),
],
]);
}
@@ -303,7 +303,7 @@ class CatalogService
if (! $hasVariants && $variantId !== null) {
throw ValidationException::withMessages([
"components.{$index}.variant_id" => [
'El componente con inventario directo no admite una variante.',
__('api.catalog.component_variant_forbidden'),
],
]);
}
@@ -311,7 +311,7 @@ class CatalogService
if ($variantId !== null && ! $componentItem->variants()->whereKey($variantId)->exists()) {
throw ValidationException::withMessages([
"components.{$index}.variant_id" => [
'La variante no pertenece al componente indicado.',
__('api.catalog.component_variant_invalid'),
],
]);
}
@@ -333,7 +333,7 @@ class CatalogService
{
if ($components === []) {
throw ValidationException::withMessages([
'components' => ['Un bundle debe tener al menos un componente.'],
'components' => [__('api.catalog.bundle_component_required')],
]);
}
@@ -348,7 +348,7 @@ class CatalogService
] as $field) {
if (array_key_exists($field, $data)) {
throw ValidationException::withMessages([
$field => ["{$field} no se admite para un bundle."],
$field => [__('api.catalog.bundle_field_forbidden', ['field' => $field])],
]);
}
}
@@ -376,7 +376,7 @@ class CatalogService
if ($attachment === null) {
throw ValidationException::withMessages([
$validationKey => ['El attachment indicado no existe.'],
$validationKey => [__('api.catalog.attachment_not_found')],
]);
}
@@ -408,7 +408,7 @@ class CatalogService
if ($attribute === null) {
throw ValidationException::withMessages([
'attribute_codes' => [
"El atributo {$attributeCode} no existe para el tenant del ítem.",
__('api.catalog.attribute_not_found', ['attribute' => $attributeCode]),
],
]);
}
@@ -442,7 +442,7 @@ class CatalogService
) {
throw ValidationException::withMessages([
"variants.{$index}.inventory" => [
'inventory_id, reserved_stock y sold_units son administrados internamente.',
__('api.catalog.managed_inventory_fields'),
],
]);
}
@@ -463,7 +463,7 @@ class CatalogService
if ($itemAttribute === null) {
throw ValidationException::withMessages([
"variants.{$index}.values.{$attributeCode}" => [
'El atributo no pertenece al ítem de catálogo.',
__('api.catalog.attribute_not_on_item'),
],
]);
}
@@ -489,7 +489,7 @@ class CatalogService
) {
throw ValidationException::withMessages([
"variants.{$index}.maximum_use_date" => [
'La fecha maxima efectiva debe ser posterior o igual a la fecha minima efectiva.',
__('api.catalog.invalid_effective_date_range'),
],
]);
}
@@ -508,7 +508,7 @@ class CatalogService
if ($hasVariants && $variants === []) {
throw ValidationException::withMessages([
'variants' => [
'Un ítem con attribute_codes debe tener variantes.',
__('api.catalog.variants_required'),
],
]);
}
@@ -516,7 +516,7 @@ class CatalogService
if (! $hasVariants && $variants !== []) {
throw ValidationException::withMessages([
'variants' => [
'Un ítem sin attribute_codes no puede tener variantes.',
__('api.catalog.variants_forbidden'),
],
]);
}
@@ -524,7 +524,7 @@ class CatalogService
if ($hasVariants && $hasDirectStock) {
throw ValidationException::withMessages([
'real_stock' => [
'Un ítem con variantes no puede tener inventario directo.',
__('api.catalog.direct_inventory_forbidden'),
],
]);
}
@@ -536,7 +536,7 @@ class CatalogService
) {
throw ValidationException::withMessages([
'inventory' => [
'inventory_id, reserved_stock y sold_units son administrados internamente.',
__('api.catalog.managed_inventory_fields'),
],
]);
}

View File

@@ -6,28 +6,26 @@ use App\Domains\Integration\Requests\TelepagosWebhookRequest;
use App\Domains\Integration\Services\TelepagosWebhookService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class TelepagosWebhookController extends Controller
{
/**
* Handle the incoming Telepagos webhook.
*
* @param TelepagosWebhookRequest $request
* @param string $tenantCodigo
* @param TelepagosWebhookService $service
* @return JsonResponse
*/
public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
{
try {
$cashinId = $request->validated('id');
$service->handleWebhook($tenantCodigo, $cashinId);
return response()->json(['status' => 'success']);
} catch (\Exception $e) {
return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500);
return response()->json([
'status' => 'error',
'code' => 'integration.webhook_failed',
'message' => __('api.integration.webhook_failed'),
], 500);
}
}
}

View File

@@ -24,9 +24,12 @@ class TenantIntegrationController extends Controller
public function show(string $tenantCode, string $integrationCode)
{
$integration = $this->tenantIntegrationService->getTenantIntegration($tenantCode, $integrationCode);
if (!$integration) {
return response()->json(['message' => 'Integration not configured for this tenant'], 404);
if (! $integration) {
return response()->json([
'code' => 'integration.not_configured',
'message' => __('api.integration.not_configured'),
], 404);
}
return response()->json($integration);
@@ -35,7 +38,7 @@ class TenantIntegrationController extends Controller
public function store(StoreTenantIntegrationRequest $request, string $tenantCode, string $integrationCode)
{
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
try {
$this->tenantIntegrationService->updateOrCreateIntegration(
$tenantCode,
@@ -44,11 +47,13 @@ class TenantIntegrationController extends Controller
);
return response()->json([
'message' => 'integration configured correctly',
'code' => 'integration.configured',
'message' => __('api.integration.configured'),
]);
} catch (\Exception $e) {
return response()->json([
'message' => 'Error validando la configuración: ' . $e->getMessage()
'code' => 'integration.validation_failed',
'message' => __('api.integration.validation_failed', ['error' => $e->getMessage()]),
], 400);
}
}

View File

@@ -20,9 +20,9 @@ class StoreTenantIntegrationRequest extends FormRequest
$integrationCode = $this->route('integration_code');
$this->integrationModel = Integration::where('integration_code', $integrationCode)->first();
if (!$this->integrationModel) {
if (! $this->integrationModel) {
throw ValidationException::withMessages([
'integration_code' => 'Integration not found.'
'integration_code' => __('api.integration.not_configured'),
]);
}
}
@@ -34,7 +34,7 @@ class StoreTenantIntegrationRequest extends FormRequest
// Dynamic validation rules based on the integration data schema
if ($this->integrationModel && $this->integrationModel->integration_data_schema) {
foreach ($this->integrationModel->integration_data_schema as $field => $rule) {
$rules['integration_data.' . $field] = $rule;
$rules['integration_data.'.$field] = $rule;
}
}

View File

@@ -24,7 +24,8 @@ class MailTestService
);
return [
'message' => 'Correo de prueba enviado correctamente.',
'code' => 'mail.test_sent',
'message' => __('api.mail.test_sent'),
'recipient' => $recipient,
'tenant_code' => $tenant->codigo,
'mailer' => $mailService->mailerName(),

View File

@@ -48,7 +48,7 @@ class Menu extends Model
&& empty($menu->static_content_schema)
) {
throw ValidationException::withMessages([
'static_content_schema' => 'El schema es obligatorio para los menús estáticos.',
'static_content_schema' => __('api.menu.schema_required'),
]);
}
});

View File

@@ -23,7 +23,7 @@ class StoreTenantMenuRequest extends FormRequest
if (! $this->menuModel) {
throw ValidationException::withMessages([
'menu_code' => 'El menú indicado no existe.',
'menu_code' => __('api.menu.not_found'),
]);
}
}

View File

@@ -135,7 +135,7 @@ class PurchaseController extends Controller
if ($updated === 0) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer available for payment.',
'purchase' => __('api.purchase.not_available_for_payment'),
]);
}
@@ -159,8 +159,14 @@ class PurchaseController extends Controller
],
]);
} catch (\Exception $e) {
Log::error('Unable to retrieve TelePagos account information.', [
'purchase_id' => $compra->id,
'exception' => $e,
]);
return response()->json([
'message' => 'Error getting account info: '.$e->getMessage(),
'code' => 'integration.account_info_failed',
'message' => __('api.integration.account_info_failed'),
], 500);
}
}
@@ -182,8 +188,14 @@ class PurchaseController extends Controller
'qr_code' => $qrResponse['qr_code'] ?? '',
]);
} catch (\Exception $e) {
Log::error('Unable to generate TelePagos QR code.', [
'purchase_id' => $compra->id,
'exception' => $e,
]);
return response()->json([
'message' => 'Error generating QR: '.$e->getMessage(),
'code' => 'integration.qr_generation_failed',
'message' => __('api.integration.qr_generation_failed'),
], 500);
}
@@ -197,7 +209,8 @@ class PurchaseController extends Controller
}
return response()->json([
'message' => 'Invalid payment method.',
'code' => 'integration.invalid_payment_method',
'message' => __('api.integration.invalid_payment_method'),
], 400);
}
@@ -222,7 +235,7 @@ class PurchaseController extends Controller
protected function resolveScopedPurchase(Tenant $tenant, int $userId, Purchase $purchase): Purchase
{
if ($purchase->tenant_codigo !== $tenant->codigo || $purchase->user_id !== $userId) {
throw new NotFoundHttpException('Purchase not found for tenant.');
throw new NotFoundHttpException(__('api.errors.not_found'));
}
return $purchase;

View File

@@ -41,7 +41,7 @@ class CheckoutService
if ($cartId === null) {
throw ValidationException::withMessages([
'cart_id' => 'A cart or direct item is required.',
'cart_id' => __('api.purchase.source_required'),
]);
}
@@ -64,7 +64,7 @@ class CheckoutService
if ($purchase->payment_method === null) {
throw ValidationException::withMessages([
'payment_method' => 'The purchase payment method must be selected before finalizing.',
'payment_method' => __('api.purchase.payment_method_required'),
]);
}
@@ -102,7 +102,7 @@ class CheckoutService
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer editable.',
'purchase' => __('api.purchase.not_editable'),
]);
}
@@ -128,7 +128,7 @@ class CheckoutService
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer editable.',
'purchase' => __('api.purchase.not_editable'),
]);
}
@@ -144,7 +144,7 @@ class CheckoutService
if ($purchaseItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'item' => 'The purchase item is no longer editable.',
'item' => __('api.purchase.item_not_editable'),
]);
}
@@ -162,7 +162,7 @@ class CheckoutService
}
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'quantity' => 'No hay suficiente stock disponible.',
'quantity' => __('api.purchase.insufficient_stock'),
]);
}
@@ -197,7 +197,7 @@ class CheckoutService
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
throw ValidationException::withMessages([
'purchase' => 'The purchase is no longer editable.',
'purchase' => __('api.purchase.not_editable'),
]);
}
@@ -233,7 +233,7 @@ class CheckoutService
Purchase::STATUS_EXPIRED,
], true)) {
throw ValidationException::withMessages([
'purchase' => 'A cancelled, rejected or expired purchase cannot be confirmed.',
'purchase' => __('api.purchase.cannot_confirm'),
]);
}
@@ -249,7 +249,7 @@ class CheckoutService
$this->catalogInventoryService->commit($selection, (int) $item->cantidad);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'items' => 'The purchase has an inconsistent stock reservation.',
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
@@ -306,7 +306,7 @@ class CheckoutService
}
throw ValidationException::withMessages([
'purchase' => 'A paid purchase cannot be cancelled.',
'purchase' => __('api.purchase.paid_cannot_cancel'),
]);
}
@@ -339,7 +339,7 @@ class CheckoutService
$this->catalogInventoryService->release($selection, (int) $item->cantidad);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'items' => 'The purchase has an inconsistent stock reservation.',
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
}
@@ -375,7 +375,7 @@ class CheckoutService
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
'direct_item.cantidad' => "Stock insuficiente. Maximo disponible: {$availableQuantity}.",
'direct_item.cantidad' => __('api.purchase.direct_item_max_stock', ['max' => $availableQuantity]),
]);
}
@@ -383,7 +383,7 @@ class CheckoutService
$this->catalogInventoryService->reserve($selection, $quantity);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'direct_item.cantidad' => 'No hay suficiente stock disponible.',
'direct_item.cantidad' => __('api.purchase.insufficient_stock'),
]);
}
@@ -416,7 +416,7 @@ class CheckoutService
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart does not contain items.',
'cart_id' => __('api.purchase.empty_cart'),
]);
}
@@ -596,13 +596,13 @@ class CheckoutService
foreach ($cartItems as $item) {
if ($item->selectedItem() === null) {
throw ValidationException::withMessages([
'cart_id' => 'One or more catalog items could not be loaded.',
'cart_id' => __('api.purchase.catalog_item_missing'),
]);
}
if ($item->catalogItem?->tenant_code !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more catalog items do not belong to the tenant.',
'cart_id' => __('api.purchase.catalog_item_wrong_tenant'),
]);
}
}
@@ -621,7 +621,7 @@ class CheckoutService
if ($cart->status !== 'active') {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart is no longer active.',
'cart_id' => __('api.purchase.inactive_cart'),
]);
}
@@ -682,13 +682,13 @@ class CheckoutService
if ($catalogItem->isBundle()) {
if ($variantId !== null) {
throw ValidationException::withMessages([
'direct_item.variant_id' => 'Un bundle no admite una variante.',
'direct_item.variant_id' => __('api.cart.bundle_variant_forbidden'),
]);
}
if (! $catalogItem->bundleComponents()->exists()) {
throw ValidationException::withMessages([
'direct_item.catalog_item_id' => 'El bundle no tiene componentes.',
'direct_item.catalog_item_id' => __('api.cart.empty_bundle'),
]);
}
@@ -698,7 +698,7 @@ class CheckoutService
if ($variantId === null) {
if ($catalogItem->inventory_id === null) {
throw ValidationException::withMessages([
'direct_item.variant_id' => 'Debe seleccionar una variante para este item.',
'direct_item.variant_id' => __('api.cart.variant_required'),
]);
}

View File

@@ -225,7 +225,7 @@ class TenantService
if ($attachment === null) {
throw ValidationException::withMessages([
"main_carousel_images.{$order}" => [
'La imagen indicada no existe o no es un attachment de tipo imagen.',
__('api.tenant.invalid_carousel_image'),
],
]);
}

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Ticket\Controllers;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Requests\DownloadTicketsPdfRequest;
use App\Domains\Ticket\Resources\TicketResource;
@@ -37,11 +38,9 @@ class TicketController extends Controller
->orderByDesc('id')
->get();
abort_if(
$tickets->count() !== count($ticketIds),
404,
'Uno o más tickets no están disponibles.'
);
if ($tickets->count() !== count($ticketIds)) {
throw new TicketNotAvailableException(__('api.ticket.not_available'));
}
return $this->ticketPdfService->download($tenant, $tickets);
}

View File

@@ -11,22 +11,22 @@ class TicketGenerationException extends RuntimeException
{
public static function invalidQuantity(): self
{
return new self('La cantidad de tickets a generar debe ser mayor a cero.');
return new self(__('api.ticket.positive_quantity'));
}
public static function emptyBundle(CatalogItem $bundle): self
{
return new self("El bundle {$bundle->id} no tiene componentes.");
return new self(__('api.ticket.empty_bundle', ['bundle' => $bundle->id]));
}
public static function ticketsDisabled(CatalogItem $catalogItem): self
{
return new self("El producto {$catalogItem->id} no tiene tickets habilitados.");
return new self(__('api.ticket.disabled', ['product' => $catalogItem->id]));
}
public static function maximumUseDateReached(CatalogItem $catalogItem): self
{
return new self("El producto {$catalogItem->id} alcanzó su fecha máxima de uso.");
return new self(__('api.ticket.expired', ['product' => $catalogItem->id]));
}
public static function variantNotFound(
@@ -34,17 +34,20 @@ class TicketGenerationException extends RuntimeException
int $variantId,
): self {
return new self(
"La variante {$variantId} no pertenece al producto {$catalogItem->id}.",
__('api.ticket.invalid_variant', [
'variant' => $variantId,
'product' => $catalogItem->id,
]),
);
}
public static function purchaseWithoutUser(Purchase $purchase): self
{
return new self("La compra {$purchase->id} no tiene un usuario asociado.");
return new self(__('api.ticket.purchase_without_user', ['purchase' => $purchase->id]));
}
public static function catalogItemNotFound(PurchaseItem $purchaseItem): self
{
return new self("No se encontró el producto de la línea de compra {$purchaseItem->id}.");
return new self(__('api.ticket.product_not_found', ['purchase_item' => $purchaseItem->id]));
}
}

View File

@@ -0,0 +1,7 @@
<?php
namespace App\Domains\Ticket\Exceptions;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class TicketNotAvailableException extends NotFoundHttpException {}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response;
class SetApiLocale
{
public function handle(Request $request, Closure $next): Response
{
if (! $request->is('api/*')) {
return $next($request);
}
$supportedLocales = config('app.supported_locales', ['es', 'en']);
$acceptLanguage = $request->header('Accept-Language');
$locale = is_string($acceptLanguage) && $acceptLanguage !== ''
? $request->getPreferredLanguage($supportedLocales)
: null;
$locale ??= config('app.locale', 'es');
App::setLocale($locale);
$response = $next($request);
$response->headers->set('Content-Language', $locale);
$response->setVary('Accept-Language', false);
return $response;
}
}