Compare commits

...

10 Commits

Author SHA1 Message Date
e619c51ac9 Refactor attachment cropping functionality to support multiple variants
- Introduced AttachmentCrop model to manage crop variants for attachments.
- Updated Attachment model to remove direct crop fields and establish relationships with AttachmentCrop.
- Modified AttachmentService to handle storing and updating multiple crop variants (desktop and mobile).
- Adjusted validation rules to accommodate new crop structure.
- Updated database migration to create attachment_crops table and migrate existing crop data.
- Refactored tests to ensure compatibility with the new cropping structure and validate multiple crop variants.
- Enhanced documentation to reflect changes in attachment handling and cropping capabilities.
2026-08-18 14:40:22 -03:00
c00b3d609c feat(attachment): update crop data columns to use decimal types and add migration for legacy data 2026-08-18 12:54:53 -03:00
9cfd49f233 feat(attachment): refactor image cropping functionality to use range objects and update related tests 2026-08-18 12:54:47 -03:00
58cc35fd61 feat(attachment): implement deletion of cropped attachments alongside original and update README 2026-08-18 12:20:47 -03:00
460ed528cf feat(attachment): add cropping functionality for images and update metadata storage 2026-08-18 12:04:39 -03:00
1c2f6c4127 refactor(variant-selection): update variant options retrieval to use catalog item's variants and enhance response structure 2026-08-18 10:45:40 -03:00
9e74e21fb5 refactor(catalog): enhance variant options retrieval by restoring canonical values from reserved cart items 2026-08-18 09:27:26 -03:00
7c2880646f refactor(cart): simplify CartItemResource response structure to prioritize selected variant details 2026-08-18 09:05:50 -03:00
4817cb28fe refactor(cart): update CartItemResource to serialize only selected variant and remove unused variant data 2026-08-18 09:02:45 -03:00
c1bfab471c feat(bootstrap): update tenant bootstrap endpoint to accept domain and path as query parameters, enhancing tenant resolution logic 2026-08-14 15:17:24 -03:00
42 changed files with 1678 additions and 90 deletions

View File

@@ -188,15 +188,18 @@
}
],
"url": {
"raw": "{{base_url}}/api/tenants/bootstrap/{{tenant_domain}}",
"raw": "{{base_url}}/api/tenants/bootstrap?dominio={{tenant_domain}}&path={{tenant_path}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"bootstrap",
"{{tenant_domain}}"
"bootstrap"
],
"query": [
{"key": "dominio", "value": "{{tenant_domain}}"},
{"key": "path", "value": "{{tenant_path}}"}
]
}
},
@@ -1402,6 +1405,11 @@
"value": "localhost",
"type": "string"
},
{
"key": "tenant_path",
"value": "/",
"type": "string"
},
{
"key": "tenant_id",
"value": "1",

View File

@@ -41,15 +41,18 @@
}
],
"url": {
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"bootstrap",
"acme.com"
"bootstrap"
],
"query": [
{"key": "dominio", "value": "acme.com"},
{"key": "path", "value": "/"}
]
}
},

View File

@@ -6,6 +6,9 @@ use App\Domains\Attachable\Enums\AttachmentType;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
#[Fillable([
@@ -40,12 +43,34 @@ class Attachment extends Model
];
}
public function cropVariants(): HasMany
{
return $this->hasMany(AttachmentCrop::class);
}
public function desktopCrop(): HasOne
{
return $this->hasOne(AttachmentCrop::class)
->where('variant', AttachmentCrop::DESKTOP);
}
public function mobileCrop(): HasOne
{
return $this->hasOne(AttachmentCrop::class)
->where('variant', AttachmentCrop::MOBILE);
}
public function cropSource(): HasOne
{
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
}
/**
* Get the pre-signed temporary S3 URL for this attachment.
*/
public function getTemporaryUrl(int $expiresInMinutes = 10): string
{
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl(
return Storage::disk('s3')->temporaryUrl(
$this->path,
now()->addMinutes($expiresInMinutes)
);

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Domains\Attachable\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'attachment_id',
'variant',
'crop_horizontal',
'crop_vertical',
'cropped_attachment_id',
])]
class AttachmentCrop extends Model
{
public const DESKTOP = 'desktop';
public const MOBILE = 'mobile';
public const VARIANTS = [self::DESKTOP, self::MOBILE];
protected function casts(): array
{
return [
'attachment_id' => 'integer',
'crop_horizontal' => 'array',
'crop_vertical' => 'array',
'cropped_attachment_id' => 'integer',
];
}
public function attachment(): BelongsTo
{
return $this->belongsTo(Attachment::class);
}
public function croppedAttachment(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'cropped_attachment_id');
}
}

View File

@@ -5,7 +5,9 @@ namespace App\Domains\Attachable\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Mime\MimeTypes;
@@ -13,6 +15,107 @@ use Throwable;
class AttachmentService
{
/**
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
*/
public function storeCroppedImageVariants(
UploadedFile|string $image,
string $path,
array $crops,
): Attachment {
$crops = $this->validateCropVariants($crops);
$storedPaths = [];
try {
return DB::transaction(function () use (
$image,
$path,
$crops,
&$storedPaths,
): Attachment {
$original = $this->store($image, $path);
$storedPaths[] = $original->path;
$contents = $this->imageContents($image);
foreach ($crops as $variant => $crop) {
$cropped = $this->storeCropVariant($contents, $path, $crop);
$storedPaths[] = $cropped->path;
$original->cropVariants()->create([
'variant' => $variant,
'crop_horizontal' => $crop['crop_horizontal'],
'crop_vertical' => $crop['crop_vertical'],
'cropped_attachment_id' => $cropped->id,
]);
}
return $original->load('cropVariants.croppedAttachment');
});
} catch (Throwable $throwable) {
if ($storedPaths !== []) {
Storage::disk('s3')->delete(array_values(array_unique($storedPaths)));
}
throw $throwable;
}
}
/**
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
*/
public function updateImageCropVariants(
Attachment $original,
array $crops,
): Attachment {
if ($original->type !== AttachmentType::Image) {
throw new AttachmentStorageException('Only image attachments can be cropped.');
}
$crops = $this->validateCropVariants($crops);
$contents = Storage::disk('s3')->get($original->path);
if (! is_string($contents) || $contents === '') {
throw new AttachmentStorageException('The original image could not be read from the s3 disk.');
}
$directory = trim(str_replace('\\', '/', dirname($original->path)), './');
$directory = $directory !== '' ? $directory : 'attachments';
$previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
$storedCrops = [];
try {
foreach ($crops as $variant => $crop) {
$storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
}
DB::transaction(function () use ($original, $crops, $storedCrops): void {
foreach ($crops as $variant => $crop) {
$original->cropVariants()->updateOrCreate(
['variant' => $variant],
[
'crop_horizontal' => $crop['crop_horizontal'],
'crop_vertical' => $crop['crop_vertical'],
'cropped_attachment_id' => $storedCrops[$variant]->id,
]
);
}
});
} catch (Throwable $throwable) {
foreach ($storedCrops as $storedCrop) {
$this->delete($storedCrop);
}
throw $throwable;
}
foreach ($previousCrops as $previousCrop) {
if ($previousCrop->croppedAttachment !== null) {
$this->delete($previousCrop->croppedAttachment);
}
}
return $original->refresh()->load('cropVariants.croppedAttachment');
}
public function store(
UploadedFile|string $file,
string $path,
@@ -57,13 +160,30 @@ class AttachmentService
public function delete(Attachment $attachment): void
{
$deleted = Storage::disk('s3')->delete($attachment->path);
$croppedAttachments = $attachment->cropVariants()
->with('croppedAttachment')
->get()
->pluck('croppedAttachment')
->filter();
$paths = $croppedAttachments
->pluck('path')
->prepend($attachment->path)
->filter()
->unique()
->values()
->all();
$deleted = Storage::disk('s3')->delete(
count($paths) === 1 ? $paths[0] : $paths
);
if (! $deleted) {
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.');
}
DB::transaction(function () use ($attachment, $croppedAttachments): void {
$attachment->delete();
Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
});
}
public function copy(Attachment $source, string $path): Attachment
@@ -107,6 +227,171 @@ class AttachmentService
return trim($path, '/');
}
/**
* @param array<string, array{crop_horizontal?: mixed, crop_vertical?: mixed}> $crops
* @return array<string, array{crop_horizontal: array{start_percentage: float, end_percentage: float}, crop_vertical: array{start_percentage: float, end_percentage: float}}>
*/
protected function validateCropVariants(array $crops): array
{
$validated = [];
foreach (AttachmentCrop::VARIANTS as $variant) {
$crop = $crops[$variant] ?? null;
if (! is_array($crop)) {
throw new AttachmentStorageException("The {$variant} crop is required.");
}
$horizontal = $crop['crop_horizontal'] ?? null;
$vertical = $crop['crop_vertical'] ?? null;
if (! is_array($horizontal) || ! is_array($vertical)) {
throw new AttachmentStorageException(
"The {$variant} crop must contain crop_horizontal and crop_vertical ranges."
);
}
$validated[$variant] = [
'crop_horizontal' => $this->validateCropRange($horizontal, "{$variant} horizontal"),
'crop_vertical' => $this->validateCropRange($vertical, "{$variant} vertical"),
];
}
return $validated;
}
/**
* @param array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>} $crop
*/
protected function storeCropVariant(string $contents, string $path, array $crop): Attachment
{
$croppedContents = $this->cropImage(
$contents,
$crop['crop_horizontal'],
$crop['crop_vertical'],
);
return $this->store(
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
$path,
);
}
/**
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range
* @return array{start_percentage: float, end_percentage: float}
*/
protected function validateCropRange(array $range, string $axis): array
{
$start = $range['start_percentage'] ?? null;
$end = $range['end_percentage'] ?? null;
if (! is_numeric($start) || ! is_numeric($end)) {
throw new AttachmentStorageException(
"The {$axis} crop range must contain numeric start_percentage and end_percentage values."
);
}
$start = (float) $start;
$end = (float) $end;
if (! is_finite($start) || ! is_finite($end) || $start < 0 || $end > 100 || $start >= $end) {
throw new AttachmentStorageException(
"The {$axis} crop range must satisfy 0 <= start_percentage < end_percentage <= 100."
);
}
return [
'start_percentage' => $start,
'end_percentage' => $end,
];
}
protected function imageContents(UploadedFile|string $image): string
{
if (is_string($image)) {
return $this->decodeBase64File($image)['data'];
}
$contents = file_get_contents($image->getRealPath());
if (! is_string($contents) || $contents === '') {
throw new AttachmentStorageException('The image content cannot be empty.');
}
return $contents;
}
/**
* @return array{contents: string, mime_type: string}
*/
protected function cropImage(
string $contents,
array $cropHorizontal,
array $cropVertical,
): array {
$source = @imagecreatefromstring($contents);
if ($source === false) {
throw new AttachmentStorageException('The attachment must contain a valid image.');
}
$width = imagesx($source);
$height = imagesy($source);
$x = min($width - 1, (int) floor($width * $cropHorizontal['start_percentage'] / 100));
$right = min($width, (int) ceil($width * $cropHorizontal['end_percentage'] / 100));
$y = min($height - 1, (int) floor($height * $cropVertical['start_percentage'] / 100));
$bottom = min($height, (int) ceil($height * $cropVertical['end_percentage'] / 100));
$cropped = imagecrop($source, [
'x' => $x,
'y' => $y,
'width' => $right - $x,
'height' => $bottom - $y,
]);
if ($cropped === false) {
throw new AttachmentStorageException('The image could not be cropped.');
}
return $this->encodeImage($cropped, $contents);
}
/**
* @return array{contents: string, mime_type: string}
*/
protected function encodeImage(\GdImage $image, string $originalContents): array
{
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($originalContents);
$mimeType = is_string($mimeType) ? strtolower($mimeType) : '';
ob_start();
try {
$encoded = match ($mimeType) {
'image/jpeg' => imagejpeg($image, null, 90),
'image/gif' => imagegif($image),
'image/webp' => imagewebp($image, null, 90),
'image/avif' => function_exists('imageavif') && imageavif($image, null, 90),
default => imagepng($image),
};
$output = ob_get_contents();
} finally {
ob_end_clean();
}
if (! $encoded || ! is_string($output) || $output === '') {
throw new AttachmentStorageException('The cropped image could not be encoded.');
}
return [
'contents' => $output,
'mime_type' => match ($mimeType) {
'image/jpeg', 'image/gif', 'image/webp', 'image/avif' => $mimeType,
default => 'image/png',
},
];
}
protected function resolveFilename(UploadedFile|string $file, string $key): string
{
if ($file instanceof UploadedFile) {

View File

@@ -2,11 +2,12 @@
## Propósito
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única.
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con variantes recortadas para desktop y mobile.
## Componentes principales
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
- `Models/AttachmentCrop.php`: relaciona un original con su crop desktop o mobile y la imagen generada.
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
@@ -25,5 +26,8 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
## Consideraciones
- El directorio no puede quedar vacío después de normalizarlo.
- Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`.
- `attachment_crops` guarda una fila por variante con los rangos horizontal/vertical y el attachment procesado.
- Al eliminar el original mediante el servicio también se eliminan todas sus variantes recortadas.
- La eliminación se considera fallida si S3 no confirma el borrado.
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.

View File

@@ -14,7 +14,10 @@ class TenantBootstrapController extends Controller
public function __invoke(TenantBootstrapRequest $request): TenantResource
{
return TenantResource::make(
$this->bootstrapService->get((string) $request->validated('dominio'))
$this->bootstrapService->get(
(string) $request->validated('dominio'),
(string) $request->validated('path'),
)
);
}
}

View File

@@ -10,6 +10,8 @@ class TenantBootstrapRequest extends FormRequest
{
protected bool $hasInvalidDomain = false;
protected bool $hasInvalidPath = false;
public function authorize(): bool
{
return true;
@@ -17,13 +19,20 @@ class TenantBootstrapRequest extends FormRequest
protected function prepareForValidation(): void
{
$rawDomain = $this->route('dominio');
$rawDomain = $this->query('dominio', $this->route('dominio'));
$rawPath = $this->query('path', '/');
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null;
$this->merge(['dominio' => $normalizedDomain]);
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
$this->merge([
'dominio' => $normalizedDomain,
'path' => $normalizedPath,
]);
}
/** @return array<string, mixed> */
@@ -41,6 +50,17 @@ class TenantBootstrapRequest extends FormRequest
'string',
'max:255',
],
'path' => [
'bail',
function (string $attribute, mixed $value, Closure $fail): void {
if ($this->hasInvalidPath) {
$fail("The {$attribute} field must contain a valid URL path.");
}
},
'required',
'string',
'max:2048',
],
];
}
}

View File

@@ -5,15 +5,31 @@ namespace App\Domains\Bootstrap\Services;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class TenantBootstrapService
{
public function __construct(protected TenantInformationService $tenantInformationService) {}
public function get(string $domain): Tenant
public function get(string $domain, string $path = '/'): Tenant
{
$candidateKeys = TenantDomainNormalizer::tenantKeyCandidates($domain, $path);
$tenantsByDomain = Tenant::query()
->whereIn('dominio', $candidateKeys)
->get()
->keyBy('dominio');
$tenant = collect($candidateKeys)
->map(fn (string $candidate): ?Tenant => $tenantsByDomain->get($candidate))
->first(fn (?Tenant $candidate): bool => $candidate !== null);
if (! $tenant instanceof Tenant) {
throw (new ModelNotFoundException)->setModel(Tenant::class);
}
return $this->tenantInformationService->load(
Tenant::query()->where('dominio', $domain)->firstOrFail(),
$tenant,
[
'menues' => fn ($query) => $query->whereHas(
'roles',

View File

@@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
## Endpoints
- `GET /tenants/bootstrap/{dominio}`: bootstrap público de la tienda.
- `GET /tenants/bootstrap?dominio={hostname}&path={path}`: bootstrap público de la tienda. Resuelve la clave de tenant más específica que sea prefijo completo del path y usa el dominio raíz como fallback.
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
## Validación
`TenantBootstrapRequest` valida el dominio recibido. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
## Dependencias

View File

@@ -3,8 +3,7 @@
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
use Illuminate\Support\Facades\Route;
Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class)
->where('dominio', '.*');
Route::get('tenants/bootstrap', TenantBootstrapController::class);
require __DIR__.'/adminapp.php';
require __DIR__.'/scanner.php';

View File

@@ -4,7 +4,6 @@ namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -35,19 +34,15 @@ class CartItemResource extends JsonResource
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id,
'product' => $selectedItem === null ? null : [
'nombre' => $selectedItem->getName(),
'nombre' => $selectedItem?->getName(),
'imagen' => $imageUrl,
'variants' => $this->catalogItem->visibleVariants($this->variant_id)
->map(fn (Variant $variant): array => [
'id' => $variant->id,
'precio' => $this->formatMoney($variant->getPrice()),
'variant' => $this->variant === null ? null : [
'id' => $this->variant->id,
'precio' => $this->formatMoney($this->variant->getPrice()),
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
])
->values(),
: $this->variant->inventory->availableStock(),
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
],
];
}

View File

@@ -108,10 +108,6 @@ class CartService
'items.catalogItem.attachments',
'items.catalogItem.inventory',
'items.catalogItem.itemAttributes.attribute',
'items.catalogItem.variants.inventory',
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
'items.catalogItem.variants.eventDates',
'items.catalogItem.variants.eventDate',
'items.variant.attachments',
'items.variant.inventory',
'items.variant.definitions.itemAttribute.attribute.options',

View File

@@ -25,7 +25,7 @@ Bajo `/tenants/{tenant:codigo}`:
## Contratos
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública. Cada ítem expone `nombre`, `imagen` y `precio_unitario` en la raíz, priorizando la variante seleccionada y usando el catálogo base como respaldo. La variante seleccionada se serializa en `variant`; las variantes alternativas no forman parte de la respuesta del carrito.
## Dependencias y reglas

View File

@@ -125,6 +125,7 @@ class CatalogController extends Controller
$includedVariantId = null;
$cartItemId = $request->validated('cart_item_id');
$selectedValues = $request->validated('selected_values', []);
if ($cartItemId !== null) {
$cartItem = $cartService->show($tenant, $request)
@@ -132,12 +133,18 @@ class CatalogController extends Controller
->firstWhere('id', (int) $cartItemId);
abort_unless($cartItem?->catalog_item_id === $catalogItem->id, 404);
$includedVariantId = $cartItem->variant_id;
if ($selectedValues === [] && $cartItem->variant !== null) {
$selectedValues = $cartItem->variant
->selectorOptions($catalogItem->itemAttributes)
->all();
}
}
return CatalogVariantOptionsResource::make(
$variantSelectionService->options(
$catalogItem,
$request->validated('selected_values', []),
$selectedValues,
$includedVariantId,
)
);

View File

@@ -38,7 +38,7 @@ class VariantSelectionService
$matchingVariants = $variants
->filter(fn (Variant $variant): bool => $this->matches($variant, $normalizedSelections))
->values();
$attributeKeys = $this->attributeKeys($catalogItem, $variants);
$attributeKeys = $this->attributeKeys($catalogItem, $catalogItem->variants->values());
$isComplete = $attributeKeys->isNotEmpty()
&& $attributeKeys->every(fn (string $key): bool => array_key_exists($key, $normalizedSelections));
$resolvedVariant = $isComplete && $matchingVariants->count() === 1
@@ -46,6 +46,10 @@ class VariantSelectionService
: null;
return [
'variants' => $variants
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
->values()
->all(),
'selectors' => $this->selectors(
$catalogItem,
$variants,

View File

@@ -0,0 +1,86 @@
<?php
namespace App\Domains\Shared\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class CroppedImageOrBase64Rule implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_array($value)) {
(new ImageOrBase64Rule)->validate($attribute, $value, $fail);
return;
}
if (! array_key_exists('image', $value)) {
$fail('The :attribute.image field is required.');
return;
}
$valid = true;
(new ImageOrBase64Rule)->validate(
"{$attribute}.image",
$value['image'],
function (string $message) use ($fail, &$valid): void {
$valid = false;
$fail($message);
}
);
if (! $valid) {
return;
}
if (isset($value['crops']) && is_array($value['crops'])) {
foreach (['desktop', 'mobile'] as $variant) {
$crop = $value['crops'][$variant] ?? null;
if (! is_array($crop)) {
$fail("The :attribute.crops.{$variant} field must be an object.");
continue;
}
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_horizontal', $crop, $fail);
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_vertical', $crop, $fail);
}
return;
}
// Backwards compatibility with the original single-crop payload.
$this->validateRange($attribute, 'crop_horizontal', $value, $fail);
$this->validateRange($attribute, 'crop_vertical', $value, $fail);
}
private function validateRange(string $attribute, string $axis, array $value, Closure $fail): void
{
$range = $value[$axis] ?? null;
if (! is_array($range)) {
$fail("The :attribute.{$axis} field must be an object.");
return;
}
$start = $range['start_percentage'] ?? null;
$end = $range['end_percentage'] ?? null;
if (
! is_numeric($start)
|| ! is_numeric($end)
|| (float) $start < 0
|| (float) $end > 100
|| (float) $start >= (float) $end
) {
$fail(
"The :attribute.{$axis} field must satisfy "
.'0 <= start_percentage < end_percentage <= 100.'
);
}
}
}

View File

@@ -23,7 +23,7 @@ class StoreTenantRequest extends FormRequest
protected function prepareForValidation(): void
{
$rawDomain = $this->input('dominio');
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
$normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null;

View File

@@ -24,7 +24,7 @@ class UpdateTenantRequest extends FormRequest
{
if ($this->has('dominio')) {
$rawDomain = $this->input('dominio');
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
$normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null;

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\WebsiteExtra;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -29,12 +30,44 @@ class WebsiteExtraResource extends JsonResource
fn (Attachment $attachment): string => $attachment->key
),
'resolved_config' => $this->formatConfig(
$this->resolvedConfig(),
$this->resolvedAdminConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
];
}
private function resolvedAdminConfig(): mixed
{
$config = $this->resolvedConfig();
if (
$this->websiteTypeExtra->codigo !== 'heroConfig'
|| ! is_array($config)
|| ! ($config['background_image_id'] ?? null) instanceof Attachment
) {
return $config;
}
$attachment = $config['background_image_id'];
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
$crops = $attachment->cropVariants->keyBy('variant');
$config['background_image_id'] = [
'url' => $attachment->getTemporaryUrl(1440),
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
function (string $variant) use ($crops, $fullRange): array {
$crop = $crops->get($variant);
return [$variant => [
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
]];
}
)->all(),
];
return $config;
}
private function formatConfig(mixed $value, callable $formatAttachment): mixed
{
if ($value instanceof Attachment) {

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -45,14 +46,53 @@ class WebsiteExtrasResource extends JsonResource
),
]),
'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->codigo => $this->formatConfig(
$extra->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
$extra->websiteTypeExtra->codigo => $this->formatResolvedConfig($extra),
]),
];
}
private function formatResolvedConfig(mixed $extra): mixed
{
$config = $extra->resolvedConfig();
if (
$extra->websiteTypeExtra->codigo === 'heroConfig'
&& is_array($config)
&& ($config['background_image_id'] ?? null) instanceof Attachment
) {
$attachment = $config['background_image_id'];
$config['background_image_id'] = $this->formatHeroAttachment($attachment);
}
return $this->formatConfig(
$config,
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
);
}
/**
* @return array{url: string, crops: array<string, array<string, array<string, float>>>}
*/
private function formatHeroAttachment(Attachment $attachment): array
{
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
$crops = $attachment->cropVariants->keyBy('variant');
return [
'url' => $attachment->getTemporaryUrl(1440),
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
function (string $variant) use ($crops, $fullRange): array {
$crop = $crops->get($variant);
return [$variant => [
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
]];
}
)->all(),
];
}
private function formatConfig(mixed $value, callable $formatAttachment): mixed
{
if ($value instanceof Attachment) {

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Catalog\Models\Category;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
@@ -98,9 +99,20 @@ class TenantResource extends JsonResource
private function formatExtraConfig(mixed $value): mixed
{
if ($value instanceof Attachment) {
$crops = $value->cropVariants->keyBy('variant');
$desktop = $crops->get(AttachmentCrop::DESKTOP)?->croppedAttachment ?? $value;
$mobile = $crops->get(AttachmentCrop::MOBILE)?->croppedAttachment ?? $desktop;
if ($crops->isEmpty()) {
return $value->getTemporaryUrl(1440);
}
return [
'desktop' => $desktop->getTemporaryUrl(1440),
'mobile' => $mobile->getTemporaryUrl(1440),
];
}
if (! is_array($value)) {
return $value;
}

View File

@@ -81,6 +81,7 @@ class TenantInformationService
$attachments = Attachment::query()
->whereIn('id', $attachmentIds)
->with('cropVariants.croppedAttachment')
->get()
->keyBy('id');

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Shared\Rules\CroppedImageOrBase64Rule;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteExtra;
@@ -222,9 +223,11 @@ class WebsiteExtraService
$compiled = is_string($rules) ? explode('|', $rules) : $rules;
return array_map(
fn (mixed $rule): mixed => $rule === 'image_or_base64'
? new ImageOrBase64Rule
: $rule,
fn (mixed $rule): mixed => match ($rule) {
'image_or_base64' => new ImageOrBase64Rule,
'cropped_image_or_base64' => new CroppedImageOrBase64Rule,
default => $rule,
},
$compiled
);
}
@@ -331,8 +334,11 @@ class WebsiteExtraService
);
}
if (is_string($value) && Str::isUuid($value)) {
$attachment = Attachment::query()->where('key', $value)->first();
$crops = $this->cropVariants($value);
$image = is_array($value) ? $value['image'] ?? null : $value;
if (is_string($image) && Str::isUuid($image)) {
$attachment = Attachment::query()->where('key', $image)->first();
if (! $attachment) {
throw ValidationException::withMessages([
@@ -341,9 +347,22 @@ class WebsiteExtraService
],
]);
}
if ($crops !== null) {
$attachment = $this->attachmentService->updateImageCropVariants(
$attachment,
$crops,
);
}
} elseif ($crops !== null) {
$attachment = $this->attachmentService->storeCroppedImageVariants(
$image,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}",
$crops,
);
} else {
$attachment = $this->attachmentService->store(
$value,
$image,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}"
);
}
@@ -364,4 +383,37 @@ class WebsiteExtraService
return $attachment->id;
}
/**
* Normalize the current variants payload and the original single-crop contract.
*
* @return array<string, array<string, mixed>>|null
*/
private function cropVariants(mixed $value): ?array
{
if (! is_array($value)) {
return null;
}
if (isset($value['crops']) && is_array($value['crops'])) {
return $value['crops'];
}
$horizontal = $value['crop_horizontal'] ?? null;
$vertical = $value['crop_vertical'] ?? null;
if (! is_array($horizontal) || ! is_array($vertical)) {
return null;
}
$crop = [
'crop_horizontal' => $horizontal,
'crop_vertical' => $vertical,
];
return [
'desktop' => $crop,
'mobile' => $crop,
];
}
}

View File

@@ -33,4 +33,90 @@ class TenantDomainNormalizer
return strtolower($host);
}
public static function normalizeTenantKey(mixed $domain, mixed $path = null): ?string
{
$host = self::normalize($domain);
if ($host === null) {
return null;
}
if ($path === null && is_string($domain)) {
$decodedDomain = trim(urldecode($domain));
$candidate = str_contains($decodedDomain, '://')
? $decodedDomain
: "//{$decodedDomain}";
$path = parse_url($candidate, PHP_URL_PATH) ?: '/';
}
$normalizedPath = self::normalizePath($path);
if ($normalizedPath === null) {
return null;
}
return $host.($normalizedPath === '/' ? '' : $normalizedPath);
}
public static function normalizePath(mixed $path): ?string
{
if (! is_string($path)) {
return null;
}
$path = trim($path);
if ($path === '' || $path === '/') {
return '/';
}
$path = parse_url(str_starts_with($path, '/') ? $path : "/{$path}", PHP_URL_PATH);
if (! is_string($path)) {
return null;
}
$path = preg_replace('#/+#', '/', $path);
if (! is_string($path)) {
return null;
}
$segments = array_filter(explode('/', $path), static fn (string $segment): bool => $segment !== '');
foreach ($segments as $segment) {
if ($segment === '.' || $segment === '..') {
return null;
}
}
return '/'.implode('/', $segments);
}
/** @return list<string> */
public static function tenantKeyCandidates(mixed $domain, mixed $path): array
{
$host = self::normalize($domain);
$normalizedPath = self::normalizePath($path);
if ($host === null || $normalizedPath === null) {
return [];
}
$segments = array_values(array_filter(
explode('/', $normalizedPath),
static fn (string $segment): bool => $segment !== '',
));
$candidates = [];
while ($segments !== []) {
$candidates[] = $host.'/'.implode('/', $segments);
array_pop($segments);
}
$candidates[] = $host;
return $candidates;
}
}

View File

@@ -6,6 +6,7 @@
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"ext-gd": "*",
"php": "^8.3",
"barryvdh/laravel-dompdf": "^3.1",
"endroid/qr-code": "^6.1",

3
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "aa7e98d017dd610946c62579b20c501f",
"content-hash": "ce185c60c617846be30ae694f0cf6e9c",
"packages": [
{
"name": "aws/aws-crt-php",
@@ -9838,6 +9838,7 @@
"prefer-stable": true,
"prefer-lowest": false,
"platform": {
"ext-gd": "*",
"php": "^8.3"
},
"platform-dev": {},

View File

@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('attachments', function (Blueprint $table): void {
$table->decimal('crop_horizontal_start_percent', 7, 4)->nullable()->after('size');
$table->decimal('crop_vertical_start_percent', 7, 4)->nullable()->after('crop_horizontal_start_percent');
$table->foreignId('cropped_attachment_id')
->nullable()
->unique()
->after('crop_vertical_start_percent')
->constrained('attachments')
->nullOnDelete();
});
}
public function down(): void
{
Schema::table('attachments', function (Blueprint $table): void {
$table->dropForeign(['cropped_attachment_id']);
$table->dropColumn([
'cropped_attachment_id',
'crop_horizontal_start_percent',
'crop_vertical_start_percent',
]);
});
}
};

View File

@@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
$this->replaceRule('nullable|image_or_base64', 'nullable|cropped_image_or_base64');
}
public function down(): void
{
$this->replaceRule('nullable|cropped_image_or_base64', 'nullable|image_or_base64');
}
private function replaceRule(string $from, string $to): void
{
DB::table('website_type_extras')
->where('codigo', 'heroConfig')
->orderBy('id')
->each(function (object $definition) use ($from, $to): void {
$schema = json_decode((string) $definition->config_schema, true);
if (! is_array($schema)) {
return;
}
$currentRule = $schema['request_rules']['background_image_id'] ?? null;
if ($currentRule !== $from) {
return;
}
$schema['request_rules']['background_image_id'] = $to;
DB::table('website_type_extras')
->where('id', $definition->id)
->update(['config_schema' => json_encode($schema)]);
});
}
};

View File

@@ -0,0 +1,108 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasColumn('attachments', 'crop_horizontal')) {
Schema::table('attachments', function (Blueprint $table): void {
$table->json('crop_horizontal')->nullable()->after('size');
});
}
if (! Schema::hasColumn('attachments', 'crop_vertical')) {
Schema::table('attachments', function (Blueprint $table): void {
$table->json('crop_vertical')->nullable()->after('crop_horizontal');
});
}
$hasLegacyHorizontal = Schema::hasColumn('attachments', 'crop_horizontal_start_percent');
$hasLegacyVertical = Schema::hasColumn('attachments', 'crop_vertical_start_percent');
if ($hasLegacyHorizontal || $hasLegacyVertical) {
$columns = array_values(array_filter([
'id',
$hasLegacyHorizontal ? 'crop_horizontal_start_percent' : null,
$hasLegacyVertical ? 'crop_vertical_start_percent' : null,
]));
DB::table('attachments')
->select($columns)
->orderBy('id')
->chunkById(100, function ($attachments) use ($hasLegacyHorizontal, $hasLegacyVertical): void {
foreach ($attachments as $attachment) {
$updates = [];
if ($hasLegacyHorizontal && $attachment->crop_horizontal_start_percent !== null) {
$updates['crop_horizontal'] = json_encode([
'start_percentage' => (float) $attachment->crop_horizontal_start_percent,
'end_percentage' => 100,
]);
}
if ($hasLegacyVertical && $attachment->crop_vertical_start_percent !== null) {
$updates['crop_vertical'] = json_encode([
'start_percentage' => (float) $attachment->crop_vertical_start_percent,
'end_percentage' => 100,
]);
}
if ($updates !== []) {
DB::table('attachments')->where('id', $attachment->id)->update($updates);
}
}
});
Schema::table('attachments', function (Blueprint $table) use ($hasLegacyHorizontal, $hasLegacyVertical): void {
if ($hasLegacyHorizontal) {
$table->dropColumn('crop_horizontal_start_percent');
}
if ($hasLegacyVertical) {
$table->dropColumn('crop_vertical_start_percent');
}
});
}
}
public function down(): void
{
if (! Schema::hasColumn('attachments', 'crop_horizontal_start_percent')) {
Schema::table('attachments', function (Blueprint $table): void {
$table->decimal('crop_horizontal_start_percent', 7, 4)->nullable()->after('size');
});
}
if (! Schema::hasColumn('attachments', 'crop_vertical_start_percent')) {
Schema::table('attachments', function (Blueprint $table): void {
$table->decimal('crop_vertical_start_percent', 7, 4)
->nullable()
->after('crop_horizontal_start_percent');
});
}
DB::table('attachments')
->select(['id', 'crop_horizontal', 'crop_vertical'])
->orderBy('id')
->chunkById(100, function ($attachments): void {
foreach ($attachments as $attachment) {
$horizontal = json_decode($attachment->crop_horizontal ?? '', true);
$vertical = json_decode($attachment->crop_vertical ?? '', true);
DB::table('attachments')->where('id', $attachment->id)->update([
'crop_horizontal_start_percent' => $horizontal['start_percentage'] ?? null,
'crop_vertical_start_percent' => $vertical['start_percentage'] ?? null,
]);
}
});
Schema::table('attachments', function (Blueprint $table): void {
$table->dropColumn(['crop_horizontal', 'crop_vertical']);
});
}
};

View File

@@ -0,0 +1,91 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('attachment_crops')) {
Schema::create('attachment_crops', function (Blueprint $table): void {
$table->id();
$table->foreignId('attachment_id')->constrained('attachments')->cascadeOnDelete();
$table->string('variant', 20);
$table->json('crop_horizontal');
$table->json('crop_vertical');
$table->foreignId('cropped_attachment_id')
->unique()
->constrained('attachments')
->cascadeOnDelete();
$table->timestamps();
$table->unique(['attachment_id', 'variant']);
});
}
if (Schema::hasColumn('attachments', 'cropped_attachment_id')) {
DB::table('attachments')
->whereNotNull('cropped_attachment_id')
->orderBy('id')
->chunkById(100, function ($attachments): void {
foreach ($attachments as $attachment) {
DB::table('attachment_crops')->updateOrInsert(
['attachment_id' => $attachment->id, 'variant' => 'desktop'],
[
'crop_horizontal' => $attachment->crop_horizontal
?? json_encode(['start_percentage' => 0, 'end_percentage' => 100]),
'crop_vertical' => $attachment->crop_vertical
?? json_encode(['start_percentage' => 0, 'end_percentage' => 100]),
'cropped_attachment_id' => $attachment->cropped_attachment_id,
'created_at' => now(),
'updated_at' => now(),
]
);
}
});
Schema::table('attachments', function (Blueprint $table): void {
$table->dropForeign(['cropped_attachment_id']);
$table->dropColumn([
'crop_horizontal',
'crop_vertical',
'cropped_attachment_id',
]);
});
}
}
public function down(): void
{
Schema::table('attachments', function (Blueprint $table): void {
$table->json('crop_horizontal')->nullable()->after('size');
$table->json('crop_vertical')->nullable()->after('crop_horizontal');
$table->foreignId('cropped_attachment_id')
->nullable()
->unique()
->after('crop_vertical')
->constrained('attachments')
->nullOnDelete();
});
DB::table('attachment_crops')
->where('variant', 'desktop')
->orderBy('id')
->chunkById(100, function ($crops): void {
foreach ($crops as $crop) {
DB::table('attachments')
->where('id', $crop->attachment_id)
->update([
'crop_horizontal' => $crop->crop_horizontal,
'crop_vertical' => $crop->crop_vertical,
'cropped_attachment_id' => $crop->cropped_attachment_id,
]);
}
});
Schema::dropIfExists('attachment_crops');
}
};

View File

@@ -86,7 +86,7 @@ class WebsiteTypeSeeder extends Seeder
'description_html' => 'nullable|string',
'button_text' => 'nullable|string',
'button_href' => 'nullable|string',
'background_image_id' => 'nullable|image_or_base64',
'background_image_id' => 'nullable|cropped_image_or_base64',
],
'transforms' => [
'background_image_id' => [

View File

@@ -7,12 +7,12 @@ require __DIR__.'/../app/Domains/StorageTest/routes/api.php';
require __DIR__.'/../app/Domains/MailTest/routes/api.php';
require __DIR__.'/../app/Domains/Purchase/routes/api.php';
require __DIR__.'/../app/Domains/Sale/routes/api.php';
require __DIR__.'/../app/Domains/Bootstrap/routes/api.php';
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
require __DIR__.'/../app/Domains/Integration/routes/api.php';
require __DIR__.'/../app/Domains/Menu/routes/api.php';
require __DIR__.'/../app/Domains/Ticket/routes/api.php';
require __DIR__.'/../app/Domains/Event/routes/api.php';
require __DIR__.'/../app/Domains/Bootstrap/routes/api.php';
require __DIR__.'/../app/Domains/Forms/routes/api.php';
require __DIR__.'/../app/Domains/Staff/routes/api.php';
require __DIR__.'/../app/Domains/FiestaFutbolInfantil/routes/api.php';

View File

@@ -5,6 +5,7 @@ namespace Tests\Feature\Attachable;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Attachable\Services\AttachmentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
@@ -70,6 +71,163 @@ class AttachmentTest extends TestCase
}
}
public function test_it_stores_an_original_image_and_its_crop(): void
{
Storage::fake('s3');
$original = app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.jpg', 200, 100),
'attachments/acme',
[
'desktop' => [
'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
],
'mobile' => [
'crop_horizontal' => ['start_percentage' => 20, 'end_percentage' => 80],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
],
);
$desktopCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
$mobileCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::MOBILE);
$cropped = $desktopCrop->croppedAttachment;
$this->assertNotNull($cropped);
$this->assertEquals(
['start_percentage' => 25.0, 'end_percentage' => 75.0],
$desktopCrop->crop_horizontal,
);
$this->assertEquals(
['start_percentage' => 10.0, 'end_percentage' => 85.0],
$desktopCrop->crop_vertical,
);
$this->assertTrue($cropped->cropSource->attachment->is($original));
$this->assertDatabaseCount('attachments', 3);
$this->assertDatabaseCount('attachment_crops', 2);
$this->assertDatabaseHas('attachment_crops', [
'attachment_id' => $original->id,
'variant' => AttachmentCrop::DESKTOP,
'cropped_attachment_id' => $cropped->id,
]);
Storage::disk('s3')->assertExists($original->path);
Storage::disk('s3')->assertExists($cropped->path);
Storage::disk('s3')->assertExists($mobileCrop->croppedAttachment->path);
$croppedSize = getimagesizefromstring(Storage::disk('s3')->get($cropped->path));
$this->assertIsArray($croppedSize);
$this->assertSame(100, $croppedSize[0]);
$this->assertSame(75, $croppedSize[1]);
}
public function test_it_rejects_invalid_crop_percentages_without_storing_files(): void
{
Storage::fake('s3');
try {
app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.png'),
'attachments/acme',
[
'desktop' => [
'crop_horizontal' => ['start_percentage' => 75, 'end_percentage' => 25],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
'mobile' => [
'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
],
);
$this->fail('Expected an AttachmentStorageException to be thrown.');
} catch (AttachmentStorageException) {
$this->assertDatabaseCount('attachments', 0);
$this->assertSame([], Storage::disk('s3')->allFiles());
}
}
public function test_it_rolls_back_the_original_when_the_file_is_not_a_valid_image(): void
{
Storage::fake('s3');
try {
app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->createWithContent('invalid.png', 'not-an-image'),
'attachments/acme',
$this->fullCropVariants(),
);
$this->fail('Expected an AttachmentStorageException to be thrown.');
} catch (AttachmentStorageException) {
$this->assertDatabaseCount('attachments', 0);
$this->assertSame([], Storage::disk('s3')->allFiles());
}
}
public function test_it_deletes_the_crop_together_with_its_original(): void
{
Storage::fake('s3');
$original = app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.png'),
'attachments/acme',
$this->fullCropVariants(),
);
$cropped = $original->cropVariants->pluck('croppedAttachment');
app(AttachmentService::class)->delete($original);
$this->assertDatabaseCount('attachments', 0);
Storage::disk('s3')->assertMissing($original->path);
foreach ($cropped as $variant) {
Storage::disk('s3')->assertMissing($variant->path);
}
}
public function test_it_replaces_the_crop_of_an_existing_image(): void
{
Storage::fake('s3');
$original = app(AttachmentService::class)->storeCroppedImageVariants(
UploadedFile::fake()->image('product.jpg', 200, 100),
'attachments/acme',
$this->fullCropVariants(),
);
$previousCrops = $original->cropVariants->pluck('croppedAttachment');
$updated = app(AttachmentService::class)->updateImageCropVariants(
$original,
[
'desktop' => [
'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
],
'mobile' => [
'crop_horizontal' => ['start_percentage' => 30, 'end_percentage' => 70],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
],
],
);
foreach ($previousCrops as $previousCrop) {
$this->assertDatabaseMissing('attachments', ['id' => $previousCrop->id]);
Storage::disk('s3')->assertMissing($previousCrop->path);
}
$desktop = $updated->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
$croppedSize = getimagesizefromstring(
Storage::disk('s3')->get($desktop->croppedAttachment->path)
);
$this->assertIsArray($croppedSize);
$this->assertSame(100, $croppedSize[0]);
$this->assertSame(75, $croppedSize[1]);
}
public function test_it_deletes_from_s3_before_removing_the_database_record(): void
{
Storage::fake('s3');
@@ -126,4 +284,14 @@ class AttachmentTest extends TestCase
]);
}
}
private function fullCropVariants(): array
{
$crop = [
'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
];
return ['desktop' => $crop, 'mobile' => $crop];
}
}

View File

@@ -49,9 +49,12 @@ class CartControllerTest extends TestCase
->assertCookie('guest_token')
->assertJsonPath('data.items.0.catalog_item_id', $item->id)
->assertJsonPath('data.items.0.variant_id', null)
->assertJsonPath('data.items.0.variant', null)
->assertJsonPath('data.items.0.cantidad', 2)
->assertJsonPath('data.items.0.precio_unitario', '49.90')
->assertJsonPath('data.items.0.product.nombre', 'Item acme')
->assertJsonPath('data.items.0.nombre', 'Item acme')
->assertJsonPath('data.items.0.imagen', null)
->assertJsonMissingPath('data.items.0.product')
->assertJsonPath('data.subtotal', '99.80');
$guestTokenCookie = $response->getCookie('guest_token', false);
@@ -276,11 +279,6 @@ class CartControllerTest extends TestCase
'inventory_id' => $secondInventory->id,
'precio' => '20.00',
]);
$unavailableInventory = Inventory::query()->create(['real_stock' => 0]);
$unavailableVariant = $item->variants()->create([
'inventory_id' => $unavailableInventory->id,
'precio' => '25.00',
]);
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $item->id,
'variant_id' => $firstVariant->id,
@@ -301,11 +299,10 @@ class CartControllerTest extends TestCase
->assertOk()
->assertJsonPath('data.items.0.variant_id', $secondVariant->id)
->assertJsonPath('data.items.0.precio_unitario', '20.00')
->assertJsonCount(2, 'data.items.0.product.variants')
->assertJsonPath('data.items.0.product.variants.0.id', $firstVariant->id)
->assertJsonPath('data.items.0.product.variants.1.id', $secondVariant->id)
->assertJsonPath('data.items.0.product.variants.1.stock_tecnico', 0)
->assertJsonMissing(['id' => $unavailableVariant->id, 'stock_tecnico' => 0]);
->assertJsonPath('data.items.0.variant.id', $secondVariant->id)
->assertJsonPath('data.items.0.variant.precio', '20.00')
->assertJsonPath('data.items.0.variant.stock_tecnico', 0)
->assertJsonMissingPath('data.items.0.product');
$this->assertDatabaseHas('inventories', [
'id' => $firstVariant->inventory_id,

View File

@@ -4,6 +4,8 @@ namespace Tests\Feature\Catalog;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem;
@@ -340,7 +342,10 @@ class CatalogItemDetailControllerTest extends TestCase
->assertOk()
->assertJsonPath('data.valid', true)
->assertJsonPath('data.resolved_variant', null)
->assertJsonMissingPath('data.variants')
->assertJsonCount(3, 'data.variants')
->assertJsonPath('data.variants.0.id', $first->id)
->assertJsonPath('data.variants.0.values.sector.value', 'A')
->assertJsonPath('data.variants.0.values.seat.value', '1')
->assertJsonCount(2, 'data.selectors')
->assertJsonPath('data.selectors.0.key', 'sector')
->assertJsonCount(2, 'data.selectors.0.options')
@@ -358,6 +363,57 @@ class CatalogItemDetailControllerTest extends TestCase
->assertJsonPath('data.resolved_variant.values.sector.value', 'A');
}
public function test_variant_options_restore_canonical_values_from_the_reserved_cart_item(): void
{
$tenant = $this->createTenant('reserved-variant-options');
$item = $this->createItem($tenant, 'Reserved numbered entry');
$sector = Attribute::query()->create([
'tenant_codigo' => $tenant->codigo,
'codigo' => 'sector',
'nombre' => 'Sector',
'type' => FieldType::Select,
]);
$seat = Attribute::query()->create([
'tenant_codigo' => $tenant->codigo,
'codigo' => 'seat',
'nombre' => 'Seat',
'type' => FieldType::Select,
]);
$itemSector = $item->itemAttributes()->create([
'attribute_id' => $sector->id,
'sort_order' => 0,
]);
$itemSeat = $item->itemAttributes()->create([
'attribute_id' => $seat->id,
'sort_order' => 1,
]);
$variant = $this->createVariant($item, 1, 0);
$variant->definitions()->createMany([
['item_attribute_id' => $itemSector->id, 'value' => 'VIP'],
['item_attribute_id' => $itemSeat->id, 'value' => 'A-12'],
]);
$user = User::factory()->create();
$cart = Cart::query()->create([
'tenant_codigo' => $tenant->codigo,
'user_id' => $user->id,
'status' => 'active',
]);
$cartItem = $cart->addItem($item->id, $variant->id, 1);
$this->actingAs($user, 'sanctum')
->postJson(
"/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}/variant-options",
[
'selected_values' => [],
'cart_item_id' => $cartItem->id,
],
)
->assertOk()
->assertJsonPath('data.selected_values.sector', 'VIP')
->assertJsonPath('data.selected_values.seat', 'A-12')
->assertJsonPath('data.resolved_variant.id', $variant->id);
}
private function createItem(
Tenant $tenant,
string $name,

View File

@@ -42,7 +42,10 @@ class CatalogSearchTest extends TestCase
->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value)
->assertJsonPath('data.search_items_per_page', 24);
$this->getJson("/api/tenants/bootstrap/{$tenant->dominio}")
$this->getJson('/api/tenants/bootstrap?'.http_build_query([
'dominio' => $tenant->dominio,
'path' => '/',
]))
->assertOk()
->assertJsonPath('data.search_product_layout', ProductLayout::Row->value)
->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value)

View File

@@ -92,7 +92,7 @@ class WebsiteTypeSeederTest extends TestCase
'description_html' => 'nullable|string',
'button_text' => 'nullable|string',
'button_href' => 'nullable|string',
'background_image_id' => 'nullable|image_or_base64',
'background_image_id' => 'nullable|cropped_image_or_base64',
],
'transforms' => [
'background_image_id' => [

View File

@@ -2,12 +2,16 @@
namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
@@ -217,6 +221,131 @@ class AdminAppWebsiteExtraControllerTest extends TestCase
);
}
public function test_adminapp_user_stores_a_cropped_banner_and_receives_original_edit_data(): void
{
Storage::fake('s3');
$this->websiteType->extras()->create([
'codigo' => 'heroConfig',
'nombre' => 'Banner principal',
'descripcion' => 'Configuración del banner principal.',
'is_required' => false,
'config_schema' => [
'request_rules' => [
'$' => 'required|array',
'background_image_id' => 'nullable|cropped_image_or_base64',
],
'transforms' => [
'background_image_id' => [
'handler' => 'attachment',
'attachment_type' => 'image',
],
],
],
]);
$tenant = $this->createTenant('acme');
$file = UploadedFile::fake()->image('banner.jpg', 200, 100);
$image = 'data:image/jpeg;base64,'.base64_encode((string) file_get_contents($file->getRealPath()));
Sanctum::actingAs($this->createAdminAppUser($tenant));
$response = $this->putJson('/api/v1/adminapp/tenant/website-extras/heroConfig', [
'config' => [
'background_image_id' => [
'image' => $image,
'crops' => [
'desktop' => [
'crop_horizontal' => [
'start_percentage' => 25,
'end_percentage' => 75,
],
'crop_vertical' => [
'start_percentage' => 10,
'end_percentage' => 85,
],
],
'mobile' => [
'crop_horizontal' => [
'start_percentage' => 30,
'end_percentage' => 70,
],
'crop_vertical' => [
'start_percentage' => 0,
'end_percentage' => 100,
],
],
],
],
],
])->assertOk();
$original = Attachment::query()->whereHas('cropVariants')->sole();
$response
->assertJsonPath('data.extras.heroConfig.background_image_id', $original->key)
->assertJsonPath(
'data.resolved_extras.heroConfig.background_image_id.crops.desktop.crop_horizontal.start_percentage',
25
)
->assertJsonPath(
'data.resolved_extras.heroConfig.background_image_id.crops.mobile.crop_vertical.end_percentage',
100
);
$this->assertStringContainsString(
$original->key,
$response->json('data.resolved_extras.heroConfig.background_image_id.url')
);
$this->assertDatabaseCount('attachments', 3);
$this->assertDatabaseCount('attachment_crops', 2);
$previousCropIds = $original->cropVariants()->pluck('cropped_attachment_id');
$this->putJson('/api/v1/adminapp/tenant/website-extras/heroConfig', [
'config' => [
'background_image_id' => [
'image' => $original->key,
'crops' => [
'desktop' => [
'crop_horizontal' => [
'start_percentage' => 10,
'end_percentage' => 90,
],
'crop_vertical' => [
'start_percentage' => 20,
'end_percentage' => 80,
],
],
'mobile' => [
'crop_horizontal' => [
'start_percentage' => 35,
'end_percentage' => 65,
],
'crop_vertical' => [
'start_percentage' => 0,
'end_percentage' => 100,
],
],
],
],
],
])
->assertOk()
->assertJsonPath(
'data.resolved_extras.heroConfig.background_image_id.crops.desktop.crop_horizontal.start_percentage',
10
);
$newCropIds = $original->cropVariants()->pluck('cropped_attachment_id');
$this->assertEmpty($previousCropIds->intersect($newCropIds));
foreach ($previousCropIds as $previousCropId) {
$this->assertDatabaseMissing('attachments', ['id' => $previousCropId]);
}
$this->assertDatabaseCount('attachments', 3);
$this->assertDatabaseHas('attachment_crops', [
'attachment_id' => $original->id,
'variant' => AttachmentCrop::MOBILE,
]);
}
public function test_update_returns_not_found_for_an_unsupported_extra_code(): void
{
$tenant = $this->createTenant('acme');

View File

@@ -4,6 +4,7 @@ namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category;
@@ -74,7 +75,7 @@ class BootstrapTenantControllerTest extends TestCase
'display_cart' => false,
]);
$response = $this->getJson('/api/tenants/bootstrap/acme.com');
$response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$response
->assertOk()
@@ -117,9 +118,9 @@ class BootstrapTenantControllerTest extends TestCase
'dominio' => 'acme.com',
]);
$encodedDomain = urlencode('https://ACME.com:8080/path?foo=bar#frag');
$encodedDomain = urlencode('https://ACME.com:8080');
$response = $this->getJson("/api/tenants/bootstrap/{$encodedDomain}");
$response = $this->getJson("/api/tenants/bootstrap?dominio={$encodedDomain}&path=%2F");
$response
->assertOk()
@@ -127,6 +128,62 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonPath('data.dominio', 'acme.com');
}
public function test_it_resolves_the_longest_tenant_prefix_for_deep_links(): void
{
$this->createTenant([
'codigo' => 'qa-root',
'nombre' => 'QA Root',
'dominio' => 'qa.onticket.com.ar',
]);
$this->createTenant([
'codigo' => 'pura-tendencia',
'nombre' => 'Pura Tendencia',
'dominio' => 'qa.onticket.com.ar/puratendencia',
]);
$this->createTenant([
'codigo' => 'pura-tendencia-vip',
'nombre' => 'Pura Tendencia VIP',
'dominio' => 'qa.onticket.com.ar/puratendencia/vip',
]);
$this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fpuratendencia%2Fproductos%2F123')
->assertOk()
->assertJsonPath('data.codigo', 'pura-tendencia')
->assertJsonPath('data.dominio', 'qa.onticket.com.ar/puratendencia');
$this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fpuratendencia%2Fvip%2Fproductos%2F123')
->assertOk()
->assertJsonPath('data.codigo', 'pura-tendencia-vip')
->assertJsonPath('data.dominio', 'qa.onticket.com.ar/puratendencia/vip');
}
public function test_it_uses_the_root_tenant_for_spa_paths_without_a_tenant_prefix(): void
{
$this->createTenant([
'codigo' => 'qa-root',
'nombre' => 'QA Root',
'dominio' => 'qa.onticket.com.ar',
]);
$this->createTenant([
'codigo' => 'sonder',
'nombre' => 'Sonder',
'dominio' => 'qa.onticket.com.ar/sonder',
]);
$this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fproducto%2F123')
->assertOk()
->assertJsonPath('data.codigo', 'qa-root');
$this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fsonder-shop%2Fproducto%2F123')
->assertOk()
->assertJsonPath('data.codigo', 'qa-root');
}
public function test_the_legacy_bootstrap_route_is_not_available(): void
{
$this->getJson('/api/tenants/bootstrap/acme.com')->assertNotFound();
}
public function test_it_resolves_browser_branding_from_the_tenant_before_the_website_type(): void
{
$typeFavicon = Attachment::query()->create([
@@ -153,7 +210,7 @@ class BootstrapTenantControllerTest extends TestCase
'website_type_code' => $websiteType->codigo,
]);
$typeResponse = $this->getJson('/api/tenants/bootstrap/acme.com');
$typeResponse = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$typeResponse
->assertOk()
@@ -165,7 +222,7 @@ class BootstrapTenantControllerTest extends TestCase
'favicon_id' => $tenantFavicon->id,
]);
$tenantResponse = $this->getJson('/api/tenants/bootstrap/acme.com');
$tenantResponse = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$tenantResponse
->assertOk()
@@ -177,7 +234,7 @@ class BootstrapTenantControllerTest extends TestCase
{
$this->createTenant();
$this->getJson('/api/tenants/bootstrap/acme.com')
$this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk()
->assertJsonPath('data.site_title', 'ShopitFront')
->assertJsonPath('data.favicon', null);
@@ -210,7 +267,7 @@ class BootstrapTenantControllerTest extends TestCase
'nombre' => 'Global',
]);
$this->getJson('/api/tenants/bootstrap/acme.com')
$this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk()
->assertJsonCount(1, 'data.categories')
->assertJsonPath('data.categories.0.nombre', 'Remeras')
@@ -254,16 +311,85 @@ class BootstrapTenantControllerTest extends TestCase
'is_enabled' => false,
]);
$this->getJson('/api/tenants/bootstrap/acme.com')
$this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk()
->assertJsonMissingPath('data.website_type')
->assertJsonPath('data.extras.contact.phone', '+54 341 555 0101')
->assertJsonMissingPath('data.extras.banner');
}
public function test_the_bootstrap_returns_only_the_cropped_banner_url(): void
{
Storage::fake('s3');
$tenant = $this->createTenant();
$websiteType = WebsiteType::query()->create([
'codigo' => 'event-store',
'nombre' => 'Eventos',
]);
$tenant->update(['website_type_code' => $websiteType->codigo]);
$heroDefinition = $websiteType->extras()->create([
'codigo' => 'heroConfig',
'nombre' => 'Banner',
'config_schema' => [
'transforms' => [
'background_image_id' => [
'handler' => 'attachment',
'attachment_type' => 'image',
],
],
],
]);
$desktop = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => 'tenants/acme/desktop.jpg',
'filename' => 'desktop.jpg',
'type' => AttachmentType::Image,
'mime_type' => 'image/jpeg',
'extension' => 'jpg',
]);
$mobile = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => 'tenants/acme/mobile.jpg',
'filename' => 'mobile.jpg',
'type' => AttachmentType::Image,
'mime_type' => 'image/jpeg',
'extension' => 'jpg',
]);
$original = Attachment::query()->create([
'key' => (string) Str::uuid(),
'path' => 'tenants/acme/original.jpg',
'filename' => 'original.jpg',
'type' => AttachmentType::Image,
'mime_type' => 'image/jpeg',
'extension' => 'jpg',
]);
foreach ([AttachmentCrop::DESKTOP => $desktop, AttachmentCrop::MOBILE => $mobile] as $variant => $crop) {
$original->cropVariants()->create([
'variant' => $variant,
'crop_horizontal' => ['start_percentage' => 10, 'end_percentage' => 90],
'crop_vertical' => ['start_percentage' => 20, 'end_percentage' => 80],
'cropped_attachment_id' => $crop->id,
]);
}
$tenant->websiteExtras()->create([
'website_type_extra_id' => $heroDefinition->id,
'config' => ['background_image_id' => $original->id],
'is_enabled' => true,
]);
$response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk()
->assertJsonMissingPath('data.extras.heroConfig.crop_horizontal')
->assertJsonMissingPath('data.extras.heroConfig.crop_vertical');
$response
->assertJsonPath('data.extras.heroConfig.background_image_id.desktop', fn (string $url): bool => str_contains($url, 'desktop.jpg'))
->assertJsonPath('data.extras.heroConfig.background_image_id.mobile', fn (string $url): bool => str_contains($url, 'mobile.jpg'));
}
public function test_it_returns_not_found_when_the_domain_does_not_exist(): void
{
$response = $this->getJson('/api/tenants/bootstrap/missing.example');
$response = $this->getJson('/api/tenants/bootstrap?dominio=missing.example&path=%2F');
$response->assertNotFound();
}
@@ -317,7 +443,7 @@ class BootstrapTenantControllerTest extends TestCase
$dynamicChild->code,
]);
$response = $this->getJson('/api/tenants/bootstrap/acme.com');
$response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$response
->assertOk()
@@ -375,7 +501,7 @@ class BootstrapTenantControllerTest extends TestCase
$userRole->menus()->sync([$userMenu->code]);
$adminRole->menus()->sync([$adminMenu->code]);
$this->getJson('/api/tenants/bootstrap/acme.com')
$this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk()
->assertJsonPath('data.menues.0.code', 'account')
->assertJsonMissing(['code' => 'admin.catalog']);
@@ -416,7 +542,7 @@ class BootstrapTenantControllerTest extends TestCase
$tenant->menues()->sync($menuCodes);
$userRole->menus()->sync($menuCodes);
$this->getJson('/api/tenants/bootstrap/acme.com')
$this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk()
->assertJsonPath('data.menues.0.code', 'tree')
->assertJsonPath('data.menues.1.code', 'zeta')
@@ -424,14 +550,14 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonPath('data.menues.0.submenues.1.code', 'tree.fox');
}
public function test_it_rejects_duplicate_domains_after_normalization_when_storing(): void
public function test_it_allows_different_domain_paths_and_rejects_duplicate_tenant_keys(): void
{
$base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
$firstResponse = $this->postJson('/api/tenants', [
'codigo' => 'acme',
'nombre' => 'Acme',
'dominio' => 'https://ACME.com/path',
'dominio' => 'https://ACME.com/puratendencia/',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
@@ -444,7 +570,7 @@ class BootstrapTenantControllerTest extends TestCase
$firstResponse
->assertCreated()
->assertJsonPath('data.dominio', 'acme.com')
->assertJsonPath('data.dominio', 'acme.com/puratendencia')
->assertJsonPath('data.primary_color', '#111111')
->assertJsonPath('data.secondary_color', '#222222')
->assertJsonPath('data.danger_color', '#333333')
@@ -480,10 +606,28 @@ class BootstrapTenantControllerTest extends TestCase
str_contains($footerUrl, 'Expires=') || str_contains($footerUrl, 'expiration=') || str_contains($footerUrl, 'X-Amz-Expires=')
);
$differentPathResponse = $this->postJson('/api/tenants', [
'codigo' => 'pura-tendencia',
'nombre' => 'Pura Tendencia',
'dominio' => 'acme.com/sonder',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
'success_color' => '#555555',
'header_bg_color' => '#444444',
'footer_bg_color' => '#444444',
'header_logo' => $base64Image,
'footer_logo' => $base64Image,
]);
$differentPathResponse
->assertCreated()
->assertJsonPath('data.dominio', 'acme.com/sonder');
$secondResponse = $this->postJson('/api/tenants', [
'codigo' => 'globex',
'nombre' => 'Globex',
'dominio' => 'acme.com',
'dominio' => 'acme.com/puratendencia',
'primary_color' => '#111111',
'secondary_color' => '#222222',
'danger_color' => '#333333',
@@ -534,7 +678,7 @@ class BootstrapTenantControllerTest extends TestCase
$successfulResponse = $this->putJson("/api/tenants/{$tenant->codigo}", [
'codigo' => 'acme',
'nombre' => 'Acme Updated',
'dominio' => 'https://ACME.com:443/admin',
'dominio' => 'https://ACME.com:443/',
'primary_color' => '#555555',
'secondary_color' => '#666666',
'danger_color' => '#777777',
@@ -582,7 +726,7 @@ class BootstrapTenantControllerTest extends TestCase
$failingResponse = $this->putJson("/api/tenants/{$otherTenant->codigo}", [
'codigo' => 'globex',
'nombre' => 'Globex',
'dominio' => 'https://ACME.com/storefront',
'dominio' => 'https://ACME.com/',
]);
$failingResponse

View File

@@ -0,0 +1,19 @@
<?php
namespace Tests\Feature\Tenant;
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
use Illuminate\Http\Request;
use Tests\TestCase;
class TenantBootstrapRouteTest extends TestCase
{
public function test_the_static_bootstrap_route_takes_precedence_over_the_tenant_resource(): void
{
$route = app('router')->getRoutes()->match(
Request::create('/api/tenants/bootstrap', 'GET')
);
$this->assertSame(TenantBootstrapController::class, $route->getActionName());
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Tests\Unit\Tenant;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class TenantDomainNormalizerTest extends TestCase
{
#[DataProvider('tenantKeys')]
public function test_it_normalizes_a_hostname_and_path_as_a_single_tenant_key(
string $domain,
?string $path,
string $expected,
): void {
$this->assertSame(
$expected,
TenantDomainNormalizer::normalizeTenantKey($domain, $path),
);
}
/** @return iterable<string, array{string, ?string, string}> */
public static function tenantKeys(): iterable
{
yield 'pura tendencia' => [
'QA.ONTICKET.COM.AR',
'/puratendencia',
'qa.onticket.com.ar/puratendencia',
];
yield 'sonder with trailing slash' => [
'qa.onticket.com.ar',
'/sonder/',
'qa.onticket.com.ar/sonder',
];
yield 'root tenant' => [
'fnfi.onticket.com.ar',
'/',
'fnfi.onticket.com.ar',
];
yield 'full tenant URL when storing' => [
'https://QA.ONTICKET.COM.AR/puratendencia/',
null,
'qa.onticket.com.ar/puratendencia',
];
}
public function test_it_builds_tenant_key_candidates_from_the_longest_path_to_the_root(): void
{
$this->assertSame([
'qa.onticket.com.ar/puratendencia/vip/productos/123',
'qa.onticket.com.ar/puratendencia/vip/productos',
'qa.onticket.com.ar/puratendencia/vip',
'qa.onticket.com.ar/puratendencia',
'qa.onticket.com.ar',
], TenantDomainNormalizer::tenantKeyCandidates(
'QA.ONTICKET.COM.AR',
'/puratendencia/vip/productos/123?ref=home',
));
}
public function test_tenant_key_candidates_only_include_complete_path_segments(): void
{
$this->assertSame([
'qa.onticket.com.ar/sonder-shop/productos',
'qa.onticket.com.ar/sonder-shop',
'qa.onticket.com.ar',
], TenantDomainNormalizer::tenantKeyCandidates(
'qa.onticket.com.ar',
'/sonder-shop/productos',
));
}
}