Compare commits

..

9 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
28 changed files with 1334 additions and 53 deletions

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

@@ -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

@@ -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

@@ -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

@@ -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

@@ -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;
@@ -317,6 +318,75 @@ class BootstrapTenantControllerTest extends TestCase
->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?dominio=missing.example&path=%2F');