Compare commits

...

20 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
de8da72354 feat(desfile): refactor entry management to use row-based configuration and expand seat options 2026-08-14 13:32:02 -03:00
4be94275f1 feat(migration): implement row and seat swapping logic for desfile tenant 2026-08-14 12:17:40 -03:00
21b0517e6c feat(desfile): implement entry management with image handling and variant synchronization 2026-08-14 11:24:17 -03:00
7fbdc00c64 feat(catalog): add is_enabled field to catalog item attachments 2026-08-14 10:24:11 -03:00
58c7a0f580 fix(catalog): serialize empty selections as an object 2026-08-14 10:15:39 -03:00
a63aea0463 refactor(catalog): return compact ticket selector options 2026-08-14 10:08:58 -03:00
b8251f3b63 fix(catalog): return only matching variant options 2026-08-14 09:57:55 -03:00
a919e9366b refactor(catalog): rely on inventory for variant availability 2026-08-14 09:54:40 -03:00
11dbcb4082 test(catalog): cover partial variant option resolution 2026-08-14 09:43:43 -03:00
ed321d6c6c feat(catalog): resolve options from partial variant selections 2026-08-14 09:43:38 -03:00
63 changed files with 3106 additions and 100 deletions

View File

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

View File

@@ -41,15 +41,18 @@
} }
], ],
"url": { "url": {
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com", "raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
"host": [ "host": [
"{{base_url}}" "{{base_url}}"
], ],
"path": [ "path": [
"api", "api",
"tenants", "tenants",
"bootstrap", "bootstrap"
"acme.com" ],
"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\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; 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; use Illuminate\Support\Str;
#[Fillable([ #[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. * Get the pre-signed temporary S3 URL for this attachment.
*/ */
public function getTemporaryUrl(int $expiresInMinutes = 10): string public function getTemporaryUrl(int $expiresInMinutes = 10): string
{ {
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl( return Storage::disk('s3')->temporaryUrl(
$this->path, $this->path,
now()->addMinutes($expiresInMinutes) 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\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException; use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Symfony\Component\Mime\MimeTypes; use Symfony\Component\Mime\MimeTypes;
@@ -13,6 +15,107 @@ use Throwable;
class AttachmentService 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( public function store(
UploadedFile|string $file, UploadedFile|string $file,
string $path, string $path,
@@ -57,13 +160,30 @@ class AttachmentService
public function delete(Attachment $attachment): void 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) { 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.');
} }
$attachment->delete(); DB::transaction(function () use ($attachment, $croppedAttachments): void {
$attachment->delete();
Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
});
} }
public function copy(Attachment $source, string $path): Attachment public function copy(Attachment $source, string $path): Attachment
@@ -107,6 +227,171 @@ class AttachmentService
return trim($path, '/'); 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 protected function resolveFilename(UploadedFile|string $file, string $key): string
{ {
if ($file instanceof UploadedFile) { if ($file instanceof UploadedFile) {

View File

@@ -2,11 +2,12 @@
## Propósito ## 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 ## Componentes principales
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso. - `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. - `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. - `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento. - `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
@@ -25,5 +26,8 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
## Consideraciones ## Consideraciones
- El directorio no puede quedar vacío después de normalizarlo. - 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. - La eliminación se considera fallida si S3 no confirma el borrado.
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos. - 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 public function __invoke(TenantBootstrapRequest $request): TenantResource
{ {
return TenantResource::make( 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 $hasInvalidDomain = false;
protected bool $hasInvalidPath = false;
public function authorize(): bool public function authorize(): bool
{ {
return true; return true;
@@ -17,13 +19,20 @@ class TenantBootstrapRequest extends FormRequest
protected function prepareForValidation(): void protected function prepareForValidation(): void
{ {
$rawDomain = $this->route('dominio'); $rawDomain = $this->query('dominio', $this->route('dominio'));
$rawPath = $this->query('path', '/');
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain); $normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain) $this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null; && $normalizedDomain === null;
$this->merge(['dominio' => $normalizedDomain]); $this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
$this->merge([
'dominio' => $normalizedDomain,
'path' => $normalizedPath,
]);
} }
/** @return array<string, mixed> */ /** @return array<string, mixed> */
@@ -41,6 +50,17 @@ class TenantBootstrapRequest extends FormRequest
'string', 'string',
'max:255', '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\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantInformationService; use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class TenantBootstrapService class TenantBootstrapService
{ {
public function __construct(protected TenantInformationService $tenantInformationService) {} 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( return $this->tenantInformationService->load(
Tenant::query()->where('dominio', $domain)->firstOrFail(), $tenant,
[ [
'menues' => fn ($query) => $query->whereHas( 'menues' => fn ($query) => $query->whereHas(
'roles', 'roles',

View File

@@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
## Endpoints ## 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`. - Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
## Validación ## 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 ## Dependencias

View File

@@ -3,8 +3,7 @@
use App\Domains\Bootstrap\Controllers\TenantBootstrapController; use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class) Route::get('tenants/bootstrap', TenantBootstrapController::class);
->where('dominio', '.*');
require __DIR__.'/adminapp.php'; require __DIR__.'/adminapp.php';
require __DIR__.'/scanner.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\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -35,19 +34,15 @@ class CartItemResource extends JsonResource
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()), 'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
'catalog_item_id' => $this->catalog_item_id, 'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id, 'variant_id' => $this->variant_id,
'product' => $selectedItem === null ? null : [ 'nombre' => $selectedItem?->getName(),
'nombre' => $selectedItem->getName(), 'imagen' => $imageUrl,
'imagen' => $imageUrl, 'variant' => $this->variant === null ? null : [
'variants' => $this->catalogItem->visibleVariants($this->variant_id) 'id' => $this->variant->id,
->map(fn (Variant $variant): array => [ 'precio' => $this->formatMoney($this->variant->getPrice()),
'id' => $variant->id, 'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
'precio' => $this->formatMoney($variant->getPrice()), ? null
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited : $this->variant->inventory->availableStock(),
? null 'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
])
->values(),
], ],
]; ];
} }

View File

@@ -108,10 +108,6 @@ class CartService
'items.catalogItem.attachments', 'items.catalogItem.attachments',
'items.catalogItem.inventory', 'items.catalogItem.inventory',
'items.catalogItem.itemAttributes.attribute', '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.attachments',
'items.variant.inventory', 'items.variant.inventory',
'items.variant.definitions.itemAttribute.attribute.options', 'items.variant.definitions.itemAttribute.attribute.options',

View File

@@ -25,7 +25,7 @@ Bajo `/tenants/{tenant:codigo}`:
## Contratos ## 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 ## Dependencias y reglas

View File

@@ -2,10 +2,12 @@
namespace App\Domains\Catalog\Controllers; namespace App\Domains\Catalog\Controllers;
use App\Domains\Cart\Services\CartService;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup; use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Requests\CatalogItemDetailRequest; use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
use App\Domains\Catalog\Requests\CategoryPageRequest; use App\Domains\Catalog\Requests\CategoryPageRequest;
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest; use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest; use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
@@ -14,8 +16,10 @@ use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
use App\Domains\Catalog\Resources\CatalogItemDetailResource; use App\Domains\Catalog\Resources\CatalogItemDetailResource;
use App\Domains\Catalog\Resources\CatalogItemResource; use App\Domains\Catalog\Resources\CatalogItemResource;
use App\Domains\Catalog\Resources\CatalogSearchItemResource; use App\Domains\Catalog\Resources\CatalogSearchItemResource;
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Catalog\Services\FeaturedGroupService; use App\Domains\Catalog\Services\FeaturedGroupService;
use App\Domains\Catalog\Services\VariantSelectionService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -110,6 +114,42 @@ class CatalogController extends Controller
); );
} }
public function variantOptions(
CatalogVariantOptionsRequest $request,
Tenant $tenant,
CatalogItem $catalogItem,
VariantSelectionService $variantSelectionService,
CartService $cartService,
): CatalogVariantOptionsResource {
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
$includedVariantId = null;
$cartItemId = $request->validated('cart_item_id');
$selectedValues = $request->validated('selected_values', []);
if ($cartItemId !== null) {
$cartItem = $cartService->show($tenant, $request)
->items
->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,
$selectedValues,
$includedVariantId,
)
);
}
public function store( public function store(
StoreCatalogItemRequest $request, StoreCatalogItemRequest $request,
Tenant $tenant, Tenant $tenant,

View File

@@ -133,6 +133,12 @@ class CatalogItem extends Model
/** @return BelongsToMany<Attachment, $this> */ /** @return BelongsToMany<Attachment, $this> */
public function attachments(): BelongsToMany public function attachments(): BelongsToMany
{
return $this->allAttachments()->wherePivot('is_enabled', true);
}
/** @return BelongsToMany<Attachment, $this> */
public function allAttachments(): BelongsToMany
{ {
return $this->belongsToMany( return $this->belongsToMany(
Attachment::class, Attachment::class,
@@ -140,7 +146,7 @@ class CatalogItem extends Model
'catalog_item_id', 'catalog_item_id',
'attachment_id' 'attachment_id'
) )
->withPivot('orden') ->withPivot(['orden', 'is_enabled'])
->wherePivotNull('variant_id') ->wherePivotNull('variant_id')
->orderByPivot('orden'); ->orderByPivot('orden');
} }

View File

@@ -84,6 +84,12 @@ class Variant extends Model
/** @return BelongsToMany<Attachment, $this> */ /** @return BelongsToMany<Attachment, $this> */
public function attachments(): BelongsToMany public function attachments(): BelongsToMany
{
return $this->allAttachments()->wherePivot('is_enabled', true);
}
/** @return BelongsToMany<Attachment, $this> */
public function allAttachments(): BelongsToMany
{ {
$relation = $this->belongsToMany( $relation = $this->belongsToMany(
Attachment::class, Attachment::class,
@@ -91,7 +97,7 @@ class Variant extends Model
'variant_id', 'variant_id',
'attachment_id' 'attachment_id'
) )
->withPivot('orden') ->withPivot(['orden', 'is_enabled'])
->orderByPivot('orden'); ->orderByPivot('orden');
if ($this->catalog_item_id !== null) { if ($this->catalog_item_id !== null) {

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CatalogVariantOptionsRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, list<string>> */
public function rules(): array
{
return [
'selected_values' => ['sometimes', 'array'],
'selected_values.*' => ['nullable'],
'cart_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
];
}
}

View File

@@ -24,6 +24,10 @@ class CatalogFeaturedItemResource extends JsonResource
return $this->columnWithImageData($catalogItem); return $this->columnWithImageData($catalogItem);
} }
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
return $this->ticketSelectorData($catalogItem);
}
$data = [ $data = [
'id' => $catalogItem->id, 'id' => $catalogItem->id,
'type' => $catalogItem->type->value, 'type' => $catalogItem->type->value,
@@ -48,13 +52,22 @@ class CatalogFeaturedItemResource extends JsonResource
->values(), ->values(),
]; ];
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
$data['image'] = $this->firstImageUrl($catalogItem);
}
return $data; return $data;
} }
/** @return array<string, mixed> */
private function ticketSelectorData(CatalogItem $catalogItem): array
{
return [
'id' => $catalogItem->id,
'type' => $catalogItem->type->value,
'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem),
];
}
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function columnWithImageData(CatalogItem $catalogItem): array private function columnWithImageData(CatalogItem $catalogItem): array
{ {

View File

@@ -0,0 +1,15 @@
<?php
namespace App\Domains\Catalog\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class CatalogVariantOptionsResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return $this->resource;
}
}

View File

@@ -0,0 +1,225 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Support\Collection;
class VariantSelectionService
{
/**
* @param array<string, mixed> $selectedValues
* @return array<string, mixed>
*/
public function options(
CatalogItem $catalogItem,
array $selectedValues,
?int $includedVariantId = null,
): array {
$catalogItem->load([
'itemAttributes.attribute',
'variants' => fn ($query) => $query->orderBy('id'),
'variants.inventory',
'variants.eventDate',
'variants.eventDates',
'variants.definitions' => fn ($query) => $query->orderBy('id'),
'variants.definitions.itemAttribute.attribute.options',
]);
$variants = $catalogItem->visibleVariants($includedVariantId)
->values();
$normalizedSelections = collect($selectedValues)
->mapWithKeys(fn ($value, string $key): array => [$key => $this->normalizeValue($value)])
->filter(fn ($value): bool => $value !== null && $value !== '' && $value !== [])
->all();
$matchingVariants = $variants
->filter(fn (Variant $variant): bool => $this->matches($variant, $normalizedSelections))
->values();
$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
? $matchingVariants->first()
: null;
return [
'variants' => $variants
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
->values()
->all(),
'selectors' => $this->selectors(
$catalogItem,
$variants,
$attributeKeys,
$matchingVariants->isEmpty() ? [] : $normalizedSelections,
),
'selected_values' => (object) ($matchingVariants->isEmpty() ? [] : $normalizedSelections),
'resolved_variant' => $resolvedVariant === null
? null
: $this->variantData($catalogItem, $resolvedVariant),
'valid' => $matchingVariants->isNotEmpty(),
'available_variant_count' => $variants->count(),
'matching_variant_count' => $matchingVariants->count(),
'price_range' => $this->priceRange($catalogItem, $variants),
];
}
/** @param array<string, mixed> $selectedValues */
private function matches(Variant $variant, array $selectedValues): bool
{
$variantValues = $variant->selectionValues();
foreach ($selectedValues as $key => $selectedValue) {
if (! $variantValues->has($key)
|| $this->valueKey($variantValues->get($key)) !== $this->valueKey($selectedValue)) {
return false;
}
}
return true;
}
/** @param Collection<int, Variant> $variants */
private function attributeKeys(CatalogItem $catalogItem, Collection $variants): Collection
{
return $variants
->flatMap(fn (Variant $variant): array => $variant
->selectorOptions($catalogItem->itemAttributes)
->keys()
->all())
->unique()
->values();
}
/**
* @param Collection<int, Variant> $variants
* @param Collection<int, string> $attributeKeys
* @param array<string, mixed> $selectedValues
* @return list<array<string, mixed>>
*/
private function selectors(
CatalogItem $catalogItem,
Collection $variants,
Collection $attributeKeys,
array $selectedValues,
): array {
return $attributeKeys
->map(function (string $key, int $index) use (
$catalogItem,
$variants,
$attributeKeys,
$selectedValues,
): array {
$previousKeys = $attributeKeys->take($index);
$previousSelections = collect($selectedValues)
->only($previousKeys->all())
->all();
$compatibleVariants = $variants
->filter(fn (Variant $variant): bool => $this->matches($variant, $previousSelections));
return [
'key' => $key,
'label' => $this->attributeLabel($catalogItem, $key),
'options' => $this->optionsFor($catalogItem, $compatibleVariants, $key),
'enabled' => $index === 0 || $previousKeys->every(
fn (string $previousKey): bool => array_key_exists($previousKey, $selectedValues),
),
];
})
->values()
->all();
}
/**
* @param Collection<int, Variant> $variants
* @return list<mixed>
*/
private function optionsFor(CatalogItem $catalogItem, Collection $variants, string $key): array
{
$options = [];
$seen = [];
foreach ($variants as $variant) {
$option = $variant->selectorOptions($catalogItem->itemAttributes)->get($key);
if ($option === null || $option === '') {
continue;
}
$optionKey = $this->valueKey($option);
if (isset($seen[$optionKey])) {
continue;
}
$seen[$optionKey] = true;
$options[] = $option;
}
return $options;
}
private function attributeLabel(CatalogItem $catalogItem, string $key): string
{
if ($key === 'event_date') {
return 'Fecha';
}
return $catalogItem->itemAttributes
->first(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo === $key)
?->attribute
?->nombre ?? str($key)->headline()->toString();
}
/** @param Collection<int, Variant> $variants */
private function priceRange(CatalogItem $catalogItem, Collection $variants): array
{
$prices = $variants
->map(fn (Variant $variant): float => $variant->getPrice())
->whenEmpty(fn (Collection $prices): Collection => $prices->push($catalogItem->getPrice()));
return [
'minimum' => number_format((float) $prices->min(), 2, '.', ''),
'maximum' => number_format((float) $prices->max(), 2, '.', ''),
];
}
/** @return array<string, mixed> */
private function variantData(CatalogItem $catalogItem, Variant $variant): array
{
return [
'id' => $variant->id,
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory?->availableStock(),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
];
}
private function normalizeValue(mixed $value): mixed
{
if (is_array($value) && array_key_exists('value', $value)) {
return (string) $value['value'];
}
if (is_array($value)) {
return array_map(fn ($item) => $this->normalizeValue($item), $value);
}
return is_scalar($value) ? (string) $value : null;
}
private function valueKey(mixed $value): string
{
$normalized = $this->normalizeValue($value);
if (is_array($normalized)) {
sort($normalized);
}
return json_encode($normalized, JSON_THROW_ON_ERROR);
}
}

View File

@@ -12,6 +12,7 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
Route::get('categories/{category}', [CatalogController::class, 'category']) Route::get('categories/{category}', [CatalogController::class, 'category'])
->name('categories.show'); ->name('categories.show');
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']); Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
Route::post('catalog-items', [CatalogController::class, 'store']); Route::post('catalog-items', [CatalogController::class, 'store']);
}); });

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Domains\Desfile\Controllers;
use App\Domains\Desfile\Requests\ReplaceEntryImageRequest;
use App\Domains\Desfile\Requests\SyncEntryRowsRequest;
use App\Domains\Desfile\Requests\UpdateEntryImageRequest;
use App\Domains\Desfile\Resources\EntryResource;
use App\Domains\Desfile\Services\EntryService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class EntryController extends Controller
{
public function __construct(private readonly EntryService $entryService) {}
public function show(Request $request): EntryResource
{
return new EntryResource(
$this->entryService->current($request->user()->tenant()->firstOrFail()),
);
}
public function update(SyncEntryRowsRequest $request): EntryResource
{
return new EntryResource($this->entryService->syncRows(
$request->user()->tenant()->firstOrFail(),
$request->validated('rows'),
));
}
public function replaceImage(ReplaceEntryImageRequest $request): JsonResponse
{
return (new EntryResource($this->entryService->replaceImage(
$request->user()->tenant()->firstOrFail(),
$request->file('image'),
$request->boolean('is_enabled', true),
)))->response();
}
public function updateImage(UpdateEntryImageRequest $request): EntryResource
{
return new EntryResource($this->entryService->updateImage(
$request->user()->tenant()->firstOrFail(),
$request->boolean('is_enabled'),
));
}
public function destroyImage(Request $request): Response
{
$this->entryService->deleteImage($request->user()->tenant()->firstOrFail());
return response()->noContent();
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Domains\Desfile\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ReplaceEntryImageRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'image' => ['required', 'image', 'mimes:jpeg,jpg,png,webp', 'max:10240'],
'is_enabled' => ['sometimes', 'boolean'],
];
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace App\Domains\Desfile\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
class SyncEntryRowsRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'rows' => ['required', 'array', 'min:1', 'max:1000'],
'rows.*' => ['required', 'array:type,sector,row,max_seat,price'],
'rows.*.type' => ['required', 'string', 'max:100'],
'rows.*.sector' => ['required', 'string', 'max:100'],
'rows.*.row' => ['required', 'integer', 'between:1,5'],
'rows.*.max_seat' => ['required', 'integer', 'between:1,100'],
'rows.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
];
}
/** @return array<int, callable> */
public function after(): array
{
return [function (Validator $validator): void {
$combinations = [];
foreach ($this->input('rows', []) as $index => $row) {
if (! is_array($row)) {
continue;
}
$combination = collect(['type', 'sector', 'row'])
->map(fn (string $field): string => mb_strtolower(trim((string) ($row[$field] ?? ''))))
->implode('|');
if (isset($combinations[$combination])) {
$validator->errors()->add(
"rows.{$index}",
'La combinación de tipo, sector y fila no puede repetirse.',
);
}
$combinations[$combination] = true;
}
}];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Desfile\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateEntryImageRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'is_enabled' => ['required', 'boolean'],
];
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Domains\Desfile\Resources;
use App\Domains\Catalog\Models\CatalogItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin CatalogItem */
class EntryResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$image = $this->allAttachments->first();
return [
'id' => $this->id,
'rows' => $this->variants
->map(function ($variant): array {
$values = $variant->selectionValues();
return [
'type' => $values->get('tipo'),
'sector' => $values->get('sector'),
'row' => $values->get('fila'),
'seat' => (int) $values->get('asiento'),
'price' => $variant->getPrice(),
];
})
->groupBy(fn (array $variant): string => implode('|', [
mb_strtolower(trim((string) $variant['type'])),
mb_strtolower(trim((string) $variant['sector'])),
mb_strtolower(trim((string) $variant['row'])),
]))
->map(function ($variants): array {
$first = $variants->first();
return [
'type' => $first['type'],
'sector' => $first['sector'],
'row' => $first['row'],
'max_seat' => $variants->max('seat'),
'price' => number_format($first['price'], 2, '.', ''),
];
})
->values(),
'image' => $image === null ? null : [
'key' => $image->key,
'filename' => $image->filename,
'url' => $image->getTemporaryUrl(1440),
'is_enabled' => (bool) $image->pivot->is_enabled,
],
];
}
}

View File

@@ -0,0 +1,302 @@
<?php
namespace App\Domains\Desfile\Services;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Throwable;
class EntryService
{
private const ATTRIBUTE_MAP = [
'type' => 'tipo',
'sector' => 'sector',
'row' => 'fila',
'seat' => 'asiento',
];
private const ROW_ATTRIBUTE_MAP = [
'type' => 'tipo',
'sector' => 'sector',
'row' => 'fila',
];
public function __construct(private readonly AttachmentService $attachmentService) {}
public function current(Tenant $tenant): CatalogItem
{
return $this->entryQuery($tenant)
->with([
'allAttachments',
'itemAttributes.attribute.options',
'variants' => fn ($query) => $query->orderBy('id'),
'variants.inventory',
'variants.definitions.itemAttribute.attribute',
])
->firstOrFail();
}
/**
* @param array<int, array<string, mixed>> $rows
*/
public function syncRows(Tenant $tenant, array $rows): CatalogItem
{
DB::transaction(function () use ($tenant, $rows): void {
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
$itemAttributes = $this->itemAttributes($entry);
$existingVariants = $entry->variants()
->with(['inventory', 'definitions.itemAttribute.attribute'])
->lockForUpdate()
->get();
$existingBySelection = $existingVariants->keyBy(
fn (Variant $variant): string => $this->selectionKey($variant->selectionValues()->all()),
);
$desiredSelections = collect();
foreach (array_values($rows) as $index => $data) {
$rowValues = $this->resolveRowValues($itemAttributes, $data, $index);
foreach (range(1, (int) $data['max_seat']) as $seat) {
$values = [
...$rowValues,
'asiento' => $this->resolveAttributeValue(
$itemAttributes,
'asiento',
(string) $seat,
"rows.{$index}.max_seat",
),
];
$selectionKey = $this->selectionKey($values);
$desiredSelections->put($selectionKey, true);
$variant = $existingBySelection->get($selectionKey);
if ($variant === null) {
$variant = $entry->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 1])->id,
'descripcion' => $this->description($values),
'precio' => $data['price'],
]);
$variant->definitions()->createMany(
collect($values)->map(
fn (string $value, string $code): array => [
'item_attribute_id' => $itemAttributes[$code]->id,
'value' => $value,
],
)->values()->all(),
);
} else {
$variant->update([
'descripcion' => $this->description($values),
'precio' => $data['price'],
]);
}
}
}
foreach ($existingVariants as $variant) {
$selectionKey = $this->selectionKey($variant->selectionValues()->all());
if ($desiredSelections->has($selectionKey)) {
continue;
}
$this->assertVariantCanChangeIdentity($variant, 'rows');
$variant->delete();
}
$minimumPrice = $entry->variants()->min('precio');
if ($minimumPrice !== null) {
$entry->update(['precio' => $minimumPrice]);
}
});
return $this->current($tenant);
}
public function replaceImage(
Tenant $tenant,
UploadedFile $image,
bool $isEnabled,
): CatalogItem {
$attachment = $this->attachmentService->store($image, 'catalog-items');
$previousAttachments = collect();
try {
DB::transaction(function () use ($tenant, $attachment, $isEnabled, &$previousAttachments): void {
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
$previousAttachments = $entry->allAttachments()->get();
$entry->allAttachments()->sync([
$attachment->id => [
'orden' => 0,
'is_enabled' => $isEnabled,
],
]);
});
} catch (Throwable $throwable) {
$this->deleteAttachmentQuietly($attachment);
throw $throwable;
}
$previousAttachments->each(fn (Attachment $previous) => $this->deleteIfUnused($previous));
return $this->current($tenant);
}
public function updateImage(Tenant $tenant, bool $isEnabled): CatalogItem
{
DB::transaction(function () use ($tenant, $isEnabled): void {
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
$entry->allAttachments()->updateExistingPivot($attachment->id, [
'is_enabled' => $isEnabled,
]);
});
return $this->current($tenant);
}
public function deleteImage(Tenant $tenant): void
{
$attachment = DB::transaction(function () use ($tenant): Attachment {
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
$entry->allAttachments()->detach($attachment->id);
return $attachment;
});
$this->deleteIfUnused($attachment);
}
/** @return Collection<string, ItemAttribute> */
private function itemAttributes(CatalogItem $entry): Collection
{
$attributes = $entry->itemAttributes()
->with('attribute.options')
->get()
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute !== null)
->keyBy(fn (ItemAttribute $itemAttribute): string => $itemAttribute->attribute->codigo);
$missing = collect(self::ATTRIBUTE_MAP)->diff($attributes->keys());
if ($missing->isNotEmpty()) {
throw ValidationException::withMessages([
'rows' => [
'Faltan atributos requeridos para las entradas del desfile: '.$missing->implode(', ').'.',
],
]);
}
return $attributes;
}
/**
* @param Collection<string, ItemAttribute> $itemAttributes
* @param array<string, mixed> $data
* @return array<string, string>
*/
private function resolveRowValues(Collection $itemAttributes, array $data, int $index): array
{
$values = [];
foreach (self::ROW_ATTRIBUTE_MAP as $input => $code) {
$values[$code] = $this->resolveAttributeValue(
$itemAttributes,
$code,
(string) $data[$input],
"rows.{$index}.{$input}",
);
}
return $values;
}
/** @param Collection<string, ItemAttribute> $itemAttributes */
private function resolveAttributeValue(
Collection $itemAttributes,
string $code,
string $requestedValue,
string $errorKey,
): string {
$requestedValue = trim($requestedValue);
$option = $itemAttributes[$code]->attribute->options->first(
fn ($candidate): bool => $this->normalize($candidate->value) === $this->normalize($requestedValue),
);
if ($option === null) {
throw ValidationException::withMessages([
$errorKey => ['La opción seleccionada no es válida.'],
]);
}
return $option->value;
}
/** @param array<string, mixed> $values */
private function selectionKey(array $values): string
{
return collect(self::ATTRIBUTE_MAP)
->map(fn (string $code): string => $this->normalize((string) ($values[$code] ?? '')))
->implode('|');
}
private function assertVariantCanChangeIdentity(Variant $variant, string $key): void
{
$inventory = $variant->inventory;
if (($inventory?->reserved_stock ?? 0) > 0 || ($inventory?->sold_units ?? 0) > 0) {
throw ValidationException::withMessages([
$key => [
'No se puede modificar ni eliminar un asiento con ventas o reservas.',
],
]);
}
}
/** @param array<string, string> $values */
private function description(array $values): string
{
return "Sector {$values['sector']} - Fila {$values['fila']} - Asiento {$values['asiento']} - {$values['tipo']}";
}
private function normalize(string $value): string
{
return Str::ascii(mb_strtolower(trim($value)));
}
/** @return Builder<CatalogItem> */
private function entryQuery(Tenant $tenant): Builder
{
return CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('slug', 'entrada');
}
private function deleteIfUnused(Attachment $attachment): void
{
if (DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
return;
}
$this->deleteAttachmentQuietly($attachment);
}
private function deleteAttachmentQuietly(Attachment $attachment): void
{
try {
$this->attachmentService->delete($attachment);
} catch (Throwable $throwable) {
report($throwable);
}
}
}

View File

@@ -1,3 +1,19 @@
<?php <?php
// Desfile tenant routes will be registered here. use App\Domains\Desfile\Controllers\EntryController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant/desfile')
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.entradas'])
->group(function (): void {
Route::get('entries', [EntryController::class, 'show'])
->name('adminapp.desfile.entries.show');
Route::put('entries', [EntryController::class, 'update'])
->name('adminapp.desfile.entries.update');
Route::post('entries/image', [EntryController::class, 'replaceImage'])
->name('adminapp.desfile.entries.image.replace');
Route::patch('entries/image', [EntryController::class, 'updateImage'])
->name('adminapp.desfile.entries.image.update');
Route::delete('entries/image', [EntryController::class, 'destroyImage'])
->name('adminapp.desfile.entries.image.destroy');
});

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 protected function prepareForValidation(): void
{ {
$rawDomain = $this->input('dominio'); $rawDomain = $this->input('dominio');
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain); $normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain) $this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null; && $normalizedDomain === null;

View File

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

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources\AdminApp; namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\WebsiteExtra; use App\Domains\Tenant\Models\WebsiteExtra;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -29,12 +30,44 @@ class WebsiteExtraResource extends JsonResource
fn (Attachment $attachment): string => $attachment->key fn (Attachment $attachment): string => $attachment->key
), ),
'resolved_config' => $this->formatConfig( 'resolved_config' => $this->formatConfig(
$this->resolvedConfig(), $this->resolvedAdminConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440) 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 private function formatConfig(mixed $value, callable $formatAttachment): mixed
{ {
if ($value instanceof Attachment) { if ($value instanceof Attachment) {

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources\AdminApp; namespace App\Domains\Tenant\Resources\AdminApp;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -45,14 +46,53 @@ class WebsiteExtrasResource extends JsonResource
), ),
]), ]),
'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [ 'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
$extra->websiteTypeExtra->codigo => $this->formatConfig( $extra->websiteTypeExtra->codigo => $this->formatResolvedConfig($extra),
$extra->resolvedConfig(),
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
),
]), ]),
]; ];
} }
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 private function formatConfig(mixed $value, callable $formatAttachment): mixed
{ {
if ($value instanceof Attachment) { if ($value instanceof Attachment) {

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Tenant\Resources; namespace App\Domains\Tenant\Resources;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
use App\Domains\Menu\Models\Menu; use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
@@ -98,7 +99,18 @@ class TenantResource extends JsonResource
private function formatExtraConfig(mixed $value): mixed private function formatExtraConfig(mixed $value): mixed
{ {
if ($value instanceof Attachment) { if ($value instanceof Attachment) {
return $value->getTemporaryUrl(1440); $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)) { if (! is_array($value)) {

View File

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

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Services;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService; use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Shared\Rules\CroppedImageOrBase64Rule;
use App\Domains\Shared\Rules\ImageOrBase64Rule; use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteExtra; use App\Domains\Tenant\Models\WebsiteExtra;
@@ -222,9 +223,11 @@ class WebsiteExtraService
$compiled = is_string($rules) ? explode('|', $rules) : $rules; $compiled = is_string($rules) ? explode('|', $rules) : $rules;
return array_map( return array_map(
fn (mixed $rule): mixed => $rule === 'image_or_base64' fn (mixed $rule): mixed => match ($rule) {
? new ImageOrBase64Rule 'image_or_base64' => new ImageOrBase64Rule,
: $rule, 'cropped_image_or_base64' => new CroppedImageOrBase64Rule,
default => $rule,
},
$compiled $compiled
); );
} }
@@ -331,8 +334,11 @@ class WebsiteExtraService
); );
} }
if (is_string($value) && Str::isUuid($value)) { $crops = $this->cropVariants($value);
$attachment = Attachment::query()->where('key', $value)->first(); $image = is_array($value) ? $value['image'] ?? null : $value;
if (is_string($image) && Str::isUuid($image)) {
$attachment = Attachment::query()->where('key', $image)->first();
if (! $attachment) { if (! $attachment) {
throw ValidationException::withMessages([ 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 { } else {
$attachment = $this->attachmentService->store( $attachment = $this->attachmentService->store(
$value, $image,
"tenants/{$tenant->codigo}/extras/{$definition->codigo}" "tenants/{$tenant->codigo}/extras/{$definition->codigo}"
); );
} }
@@ -364,4 +383,37 @@ class WebsiteExtraService
return $attachment->id; 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); 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"], "keywords": ["laravel", "framework"],
"license": "MIT", "license": "MIT",
"require": { "require": {
"ext-gd": "*",
"php": "^8.3", "php": "^8.3",
"barryvdh/laravel-dompdf": "^3.1", "barryvdh/laravel-dompdf": "^3.1",
"endroid/qr-code": "^6.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", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "aa7e98d017dd610946c62579b20c501f", "content-hash": "ce185c60c617846be30ae694f0cf6e9c",
"packages": [ "packages": [
{ {
"name": "aws/aws-crt-php", "name": "aws/aws-crt-php",
@@ -9838,6 +9838,7 @@
"prefer-stable": true, "prefer-stable": true,
"prefer-lowest": false, "prefer-lowest": false,
"platform": { "platform": {
"ext-gd": "*",
"php": "^8.3" "php": "^8.3"
}, },
"platform-dev": {}, "platform-dev": {},

View File

@@ -0,0 +1,22 @@
<?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('catalog_items_attachments', function (Blueprint $table): void {
$table->boolean('is_enabled')->default(true)->after('orden');
});
}
public function down(): void
{
Schema::table('catalog_items_attachments', function (Blueprint $table): void {
$table->dropColumn('is_enabled');
});
}
};

View File

@@ -0,0 +1,128 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
private const TENANT_CODE = 'desfile_pura_tendencia';
public function up(): void
{
$this->swapRowAndSeat(
array_map('strval', range(1, 5)),
array_map('strval', range(1, 17)),
);
}
public function down(): void
{
$this->swapRowAndSeat(
array_map('strval', range(1, 17)),
array_map('strval', range(1, 5)),
);
}
/**
* @param list<string> $rowOptions
* @param list<string> $seatOptions
*/
private function swapRowAndSeat(array $rowOptions, array $seatOptions): void
{
DB::transaction(function () use ($rowOptions, $seatOptions): void {
$entryId = DB::table('catalog_items')
->where('tenant_code', self::TENANT_CODE)
->where('slug', 'entrada')
->value('id');
if ($entryId === null) {
return;
}
$attributes = DB::table('attribute')
->where('tenant_codigo', self::TENANT_CODE)
->whereIn('codigo', ['tipo', 'sector', 'fila', 'asiento'])
->pluck('id', 'codigo');
if (! $attributes->has(['tipo', 'sector', 'fila', 'asiento'])) {
return;
}
$this->replaceOptions((int) $attributes['fila'], $rowOptions);
$this->replaceOptions((int) $attributes['asiento'], $seatOptions);
$itemAttributes = DB::table('item_attributes')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->where('item_attributes.catalog_item_id', $entryId)
->whereIn('attribute.codigo', ['tipo', 'sector', 'fila', 'asiento'])
->pluck('item_attributes.id', 'attribute.codigo');
if (! $itemAttributes->has(['tipo', 'sector', 'fila', 'asiento'])) {
return;
}
foreach (['tipo' => 1, 'sector' => 2, 'fila' => 3, 'asiento' => 4] as $code => $sortOrder) {
DB::table('item_attributes')->where('id', $itemAttributes[$code])->update([
'sort_order' => $sortOrder,
]);
}
$definitions = DB::table('variant_values')
->join('item_attributes', 'item_attributes.id', '=', 'variant_values.item_attribute_id')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->join('variantes', 'variantes.id', '=', 'variant_values.variant_id')
->where('variantes.catalog_item_id', $entryId)
->whereIn('attribute.codigo', ['tipo', 'sector', 'fila', 'asiento'])
->get([
'variant_values.id',
'variant_values.variant_id',
'variant_values.value',
'attribute.codigo',
])
->groupBy('variant_id');
foreach ($definitions as $variantId => $variantDefinitions) {
$values = $variantDefinitions->keyBy('codigo');
$row = $values->get('fila');
$seat = $values->get('asiento');
if ($row === null || $seat === null) {
continue;
}
DB::table('variant_values')->where('id', $row->id)->update(['value' => $seat->value]);
DB::table('variant_values')->where('id', $seat->id)->update(['value' => $row->value]);
$type = $values->get('tipo')?->value;
$sector = $values->get('sector')?->value;
if ($type !== null && $sector !== null) {
DB::table('variantes')->where('id', $variantId)->update([
'descripcion' => "Sector {$sector} - Fila {$seat->value} - Asiento {$row->value} - {$type}",
]);
}
}
});
}
/** @param list<string> $options */
private function replaceOptions(int $attributeId, array $options): void
{
DB::table('attribute_options')->where('attribute_id', $attributeId)->delete();
$now = now();
DB::table('attribute_options')->insert(array_map(
fn (string $option, int $index): array => [
'attribute_id' => $attributeId,
'validity_time_id' => null,
'value' => $option,
'label' => $option,
'sort_order' => $index + 1,
'metadata' => null,
'created_at' => $now,
'updated_at' => $now,
],
$options,
array_keys($options),
));
}
};

View File

@@ -0,0 +1,50 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
private const TENANT_CODE = 'desfile_pura_tendencia';
public function up(): void
{
$this->replaceSeatOptions(100);
}
public function down(): void
{
$this->replaceSeatOptions(17);
}
private function replaceSeatOptions(int $maximum): void
{
$attributeId = DB::table('attribute')
->where('tenant_codigo', self::TENANT_CODE)
->where('codigo', 'asiento')
->value('id');
if ($attributeId === null) {
return;
}
DB::transaction(function () use ($attributeId, $maximum): void {
DB::table('attribute_options')->where('attribute_id', $attributeId)->delete();
$now = now();
DB::table('attribute_options')->insert(array_map(
fn (int $seat): array => [
'attribute_id' => $attributeId,
'validity_time_id' => null,
'value' => (string) $seat,
'label' => (string) $seat,
'sort_order' => $seat,
'metadata' => null,
'created_at' => $now,
'updated_at' => $now,
],
range(1, $maximum),
));
});
}
};

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', 'description_html' => 'nullable|string',
'button_text' => 'nullable|string', 'button_text' => 'nullable|string',
'button_href' => 'nullable|string', 'button_href' => 'nullable|string',
'background_image_id' => 'nullable|image_or_base64', 'background_image_id' => 'nullable|cropped_image_or_base64',
], ],
'transforms' => [ 'transforms' => [
'background_image_id' => [ '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/MailTest/routes/api.php';
require __DIR__.'/../app/Domains/Purchase/routes/api.php'; require __DIR__.'/../app/Domains/Purchase/routes/api.php';
require __DIR__.'/../app/Domains/Sale/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/Tenant/routes/api.php';
require __DIR__.'/../app/Domains/Integration/routes/api.php'; require __DIR__.'/../app/Domains/Integration/routes/api.php';
require __DIR__.'/../app/Domains/Menu/routes/api.php'; require __DIR__.'/../app/Domains/Menu/routes/api.php';
require __DIR__.'/../app/Domains/Ticket/routes/api.php'; require __DIR__.'/../app/Domains/Ticket/routes/api.php';
require __DIR__.'/../app/Domains/Event/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/Forms/routes/api.php';
require __DIR__.'/../app/Domains/Staff/routes/api.php'; require __DIR__.'/../app/Domains/Staff/routes/api.php';
require __DIR__.'/../app/Domains/FiestaFutbolInfantil/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\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException; use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Attachable\Services\AttachmentService; use App\Domains\Attachable\Services\AttachmentService;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile; 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 public function test_it_deletes_from_s3_before_removing_the_database_record(): void
{ {
Storage::fake('s3'); 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') ->assertCookie('guest_token')
->assertJsonPath('data.items.0.catalog_item_id', $item->id) ->assertJsonPath('data.items.0.catalog_item_id', $item->id)
->assertJsonPath('data.items.0.variant_id', null) ->assertJsonPath('data.items.0.variant_id', null)
->assertJsonPath('data.items.0.variant', null)
->assertJsonPath('data.items.0.cantidad', 2) ->assertJsonPath('data.items.0.cantidad', 2)
->assertJsonPath('data.items.0.precio_unitario', '49.90') ->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'); ->assertJsonPath('data.subtotal', '99.80');
$guestTokenCookie = $response->getCookie('guest_token', false); $guestTokenCookie = $response->getCookie('guest_token', false);
@@ -276,11 +279,6 @@ class CartControllerTest extends TestCase
'inventory_id' => $secondInventory->id, 'inventory_id' => $secondInventory->id,
'precio' => '20.00', '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', [ $createResponse = $this->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
'variant_id' => $firstVariant->id, 'variant_id' => $firstVariant->id,
@@ -301,11 +299,10 @@ class CartControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.items.0.variant_id', $secondVariant->id) ->assertJsonPath('data.items.0.variant_id', $secondVariant->id)
->assertJsonPath('data.items.0.precio_unitario', '20.00') ->assertJsonPath('data.items.0.precio_unitario', '20.00')
->assertJsonCount(2, 'data.items.0.product.variants') ->assertJsonPath('data.items.0.variant.id', $secondVariant->id)
->assertJsonPath('data.items.0.product.variants.0.id', $firstVariant->id) ->assertJsonPath('data.items.0.variant.precio', '20.00')
->assertJsonPath('data.items.0.product.variants.1.id', $secondVariant->id) ->assertJsonPath('data.items.0.variant.stock_tecnico', 0)
->assertJsonPath('data.items.0.product.variants.1.stock_tecnico', 0) ->assertJsonMissingPath('data.items.0.product');
->assertJsonMissing(['id' => $unavailableVariant->id, 'stock_tecnico' => 0]);
$this->assertDatabaseHas('inventories', [ $this->assertDatabaseHas('inventories', [
'id' => $firstVariant->inventory_id, 'id' => $firstVariant->inventory_id,

View File

@@ -264,7 +264,8 @@ class CatalogControllerTest extends TestCase
->assertJsonPath('0.layout', ProductLayout::TicketSelector->value) ->assertJsonPath('0.layout', ProductLayout::TicketSelector->value)
->assertJsonPath('0.group_layout', GroupLayout::Single->value) ->assertJsonPath('0.group_layout', GroupLayout::Single->value)
->assertJsonCount(1, '0.items') ->assertJsonCount(1, '0.items')
->assertJsonPath('0.items.0.nombre', 'Primera entrada'); ->assertJsonPath('0.items.0.nombre', 'Primera entrada')
->assertJsonMissingPath('0.items.0.variants');
} }
public function test_groups_can_source_items_from_a_category_or_the_entire_catalog(): void public function test_groups_can_source_items_from_a_category_or_the_entire_catalog(): void

View File

@@ -62,6 +62,7 @@ class CatalogItemControllerTest extends TestCase
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
'variant_id' => $variant->id, 'variant_id' => $variant->id,
'orden' => 0, 'orden' => 0,
'is_enabled' => true,
]); ]);
} }

View File

@@ -4,6 +4,8 @@ namespace Tests\Feature\Catalog;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; 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\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Attribute; use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
@@ -296,6 +298,122 @@ class CatalogItemDetailControllerTest extends TestCase
->assertJsonPath('data.attributes.0.show_in_selector', false); ->assertJsonPath('data.attributes.0.show_in_selector', false);
} }
public function test_it_resolves_available_variant_options_from_partial_selections(): void
{
$tenant = $this->createTenant('variant-options');
$item = $this->createItem($tenant, '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,
]);
$first = $this->createVariant($item, 1, 0);
$second = $this->createVariant($item, 1, 0);
$third = $this->createVariant($item, 1, 0);
foreach ([[$first, 'A', '1'], [$second, 'A', '2'], [$third, 'B', '3']] as [$variant, $sectorValue, $seatValue]) {
$variant->definitions()->createMany([
['item_attribute_id' => $itemSector->id, 'value' => $sectorValue],
['item_attribute_id' => $itemSeat->id, 'value' => $seatValue],
]);
}
$this->postJson(
"/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}/variant-options",
[
'selected_values' => ['sector' => 'A'],
],
)
->assertOk()
->assertJsonPath('data.valid', true)
->assertJsonPath('data.resolved_variant', null)
->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')
->assertJsonCount(2, 'data.selectors.1.options')
->assertJsonPath('data.selectors.1.options.0.value', '1')
->assertJsonPath('data.available_variant_count', 3)
->assertJsonPath('data.matching_variant_count', 2);
$this->postJson(
"/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}/variant-options",
['selected_values' => ['sector' => 'A', 'seat' => '1']],
)
->assertOk()
->assertJsonPath('data.resolved_variant.id', $first->id)
->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( private function createItem(
Tenant $tenant, Tenant $tenant,
string $name, string $name,

View File

@@ -104,6 +104,7 @@ class CatalogSchemaTest extends TestCase
'catalog_item_id', 'catalog_item_id',
'attachment_id', 'attachment_id',
'orden', 'orden',
'is_enabled',
], Schema::getColumnListing('catalog_items_attachments')); ], Schema::getColumnListing('catalog_items_attachments'));
} }
@@ -170,12 +171,14 @@ class CatalogSchemaTest extends TestCase
'variant_id' => null, 'variant_id' => null,
'attachment_id' => $itemAttachment->id, 'attachment_id' => $itemAttachment->id,
'orden' => 2, 'orden' => 2,
'is_enabled' => true,
]); ]);
$this->assertDatabaseHas('catalog_items_attachments', [ $this->assertDatabaseHas('catalog_items_attachments', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
'variant_id' => $variant->id, 'variant_id' => $variant->id,
'attachment_id' => $variantAttachment->id, 'attachment_id' => $variantAttachment->id,
'orden' => 3, 'orden' => 3,
'is_enabled' => true,
]); ]);
} }

View File

@@ -42,7 +42,10 @@ class CatalogSearchTest extends TestCase
->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value) ->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value)
->assertJsonPath('data.search_items_per_page', 24); ->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() ->assertOk()
->assertJsonPath('data.search_product_layout', ProductLayout::Row->value) ->assertJsonPath('data.search_product_layout', ProductLayout::Row->value)
->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value) ->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value)

View File

@@ -0,0 +1,280 @@
<?php
namespace Tests\Feature\Desfile;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Enums\InventorySubject;
use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Menu\Models\Menu;
use App\Domains\Shared\Enums\FieldType;
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;
class EntryControllerTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seed(AuthorizationSeeder::class);
WebsiteType::query()->create([
'codigo' => 'onticket',
'nombre' => 'OnTicket',
]);
}
public function test_it_returns_row_configs_and_expands_them_into_seat_variants(): void
{
[$tenant, $entry] = $this->configuredEntry();
$existing = $this->createVariant($entry, 'NORMAL', 'A', '1', '1', 100000);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$this->getJson('/api/v1/adminapp/tenant/desfile/entries')
->assertOk()
->assertJsonPath('data.id', $entry->id)
->assertJsonPath('data.rows.0.type', 'NORMAL')
->assertJsonPath('data.rows.0.row', '1')
->assertJsonPath('data.rows.0.max_seat', 1)
->assertJsonPath('data.rows.0.price', '100000.00');
$response = $this->putJson('/api/v1/adminapp/tenant/desfile/entries', [
'rows' => [
[
'type' => 'NORMAL',
'sector' => 'A',
'row' => '1',
'max_seat' => 2,
'price' => 120000,
],
[
'type' => 'VIP + LUNCH',
'sector' => 'B',
'row' => '2',
'max_seat' => 3,
'price' => 250000,
],
],
]);
$response
->assertOk()
->assertJsonCount(2, 'data.rows')
->assertJsonPath('data.rows.0.max_seat', 2)
->assertJsonPath('data.rows.0.price', '120000.00')
->assertJsonPath('data.rows.1.max_seat', 3)
->assertJsonPath('data.rows.1.type', 'VIP + LUNCH');
$this->assertDatabaseCount('variantes', 5);
$this->assertDatabaseHas('catalog_items', [
'id' => $entry->id,
'precio' => 120000,
]);
$this->assertSame('120000.00', $existing->fresh()->precio);
$this->assertSame(2, $entry->variants()->where('precio', 120000)->count());
$this->assertSame(3, $entry->variants()->where('precio', 250000)->count());
$this->assertSame(5, Inventory::query()->where('real_stock', 1)->count());
}
public function test_it_replaces_and_toggles_the_entry_image(): void
{
Storage::fake('s3');
[$tenant, $entry] = $this->configuredEntry();
$oldImage = Attachment::query()->create([
'path' => 'catalog-items/old.png',
'filename' => 'old.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
'extension' => 'png',
'size' => 10,
]);
Storage::disk('s3')->put($oldImage->path, 'old');
$entry->allAttachments()->attach($oldImage->id, ['orden' => 0]);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$this->post('/api/v1/adminapp/tenant/desfile/entries/image', [
'image' => UploadedFile::fake()->image('plano.png'),
'is_enabled' => false,
], ['Accept' => 'application/json'])
->assertOk()
->assertJsonPath('data.image.filename', 'plano.png')
->assertJsonPath('data.image.is_enabled', false);
$this->assertDatabaseMissing('attachments', ['id' => $oldImage->id]);
$this->assertCount(0, $entry->fresh()->attachments);
$this->assertCount(1, $entry->fresh()->allAttachments);
$this->patchJson('/api/v1/adminapp/tenant/desfile/entries/image', [
'is_enabled' => true,
])
->assertOk()
->assertJsonPath('data.image.is_enabled', true);
$this->assertCount(1, $entry->fresh()->attachments);
}
public function test_it_rejects_duplicate_rows(): void
{
[$tenant] = $this->configuredEntry();
Sanctum::actingAs($this->createAdminAppUser($tenant));
$payload = [
'rows' => [
$this->rowPayload('NORMAL', 'A', '1', 10, 100),
$this->rowPayload('normal', 'A', '1', 20, 200),
],
];
$this->putJson('/api/v1/adminapp/tenant/desfile/entries', $payload)
->assertUnprocessable()
->assertJsonValidationErrors('rows.1');
}
public function test_it_rejects_rows_and_seat_quantities_outside_the_configured_ranges(): void
{
[$tenant] = $this->configuredEntry();
Sanctum::actingAs($this->createAdminAppUser($tenant));
$this->putJson('/api/v1/adminapp/tenant/desfile/entries', [
'rows' => [
$this->rowPayload('NORMAL', 'A', '6', 1, 100),
$this->rowPayload('NORMAL', 'A', '1', 101, 100),
],
])
->assertUnprocessable()
->assertJsonValidationErrors(['rows.0.row', 'rows.1.max_seat']);
}
public function test_it_cannot_reduce_the_maximum_below_a_reserved_seat(): void
{
[$tenant, $entry] = $this->configuredEntry();
$reserved = $this->createVariant($entry, 'NORMAL', 'A', '1', '3', 100);
$reserved->inventory()->update(['reserved_stock' => 1]);
Sanctum::actingAs($this->createAdminAppUser($tenant));
$this->putJson('/api/v1/adminapp/tenant/desfile/entries', [
'rows' => [$this->rowPayload('NORMAL', 'A', '1', 2, 100)],
])
->assertUnprocessable()
->assertJsonValidationErrors('rows');
$this->assertDatabaseHas('variantes', ['id' => $reserved->id, 'deleted_at' => null]);
}
/** @return array{Tenant, CatalogItem} */
private function configuredEntry(string $tenantCode = 'desfile_pura_tendencia'): array
{
$tenant = Tenant::query()->create([
'codigo' => $tenantCode,
'nombre' => 'Desfile',
'dominio' => "{$tenantCode}.test",
'website_type_code' => 'onticket',
]);
$menu = Menu::query()->firstOrCreate(
['code' => 'adminapp.desfile.entradas'],
['label' => 'Entradas', 'route' => '/admin/desfile/entradas'],
);
$tenant->menues()->attach($menu->code);
$entry = CatalogItem::query()->create([
'tenant_code' => $tenant->codigo,
'slug' => 'entrada',
'nombre' => 'Entrada',
'precio' => 0,
'inventory_policy' => InventoryPolicy::Tracked,
'inventory_subject' => InventorySubject::Seat,
'has_tickets' => true,
]);
foreach ([
'tipo' => ['VIP + LUNCH', 'NORMAL'],
'sector' => ['A', 'B', 'C', 'D'],
'fila' => array_map('strval', range(1, 5)),
'asiento' => array_map('strval', range(1, 100)),
] as $code => $options) {
$attribute = Attribute::query()->create([
'tenant_codigo' => $tenant->codigo,
'codigo' => $code,
'nombre' => ucfirst($code),
'type' => FieldType::Select,
'is_required' => true,
]);
foreach ($options as $order => $option) {
$attribute->options()->create([
'value' => $option,
'label' => $option,
'sort_order' => $order + 1,
]);
}
$entry->itemAttributes()->create([
'attribute_id' => $attribute->id,
'sort_order' => $entry->itemAttributes()->count() + 1,
]);
}
return [$tenant, $entry];
}
private function createVariant(
CatalogItem $entry,
string $type,
string $sector,
string $row,
string $seat,
int $price,
): Variant {
$variant = $entry->variants()->create([
'inventory_id' => Inventory::query()->create(['real_stock' => 1])->id,
'precio' => $price,
]);
$itemAttributes = $entry->itemAttributes()->with('attribute')->get()->keyBy(
fn (ItemAttribute $itemAttribute): string => $itemAttribute->attribute->codigo,
);
foreach (compact('type', 'sector', 'row', 'seat') as $input => $value) {
$code = ['type' => 'tipo', 'sector' => 'sector', 'row' => 'fila', 'seat' => 'asiento'][$input];
$variant->definitions()->create([
'item_attribute_id' => $itemAttributes[$code]->id,
'value' => $value,
]);
}
return $variant;
}
/** @return array<string, mixed> */
private function rowPayload(
string $type,
string $sector,
string $row,
int $maxSeat,
int $price,
): array {
return [
...compact('type', 'sector', 'row', 'price'),
'max_seat' => $maxSeat,
];
}
private function createAdminAppUser(Tenant $tenant): User
{
return User::factory()->create([
'rol_codigo' => RoleCode::AdminApp->value,
'tenant_codigo' => $tenant->codigo,
]);
}
}

View File

@@ -31,6 +31,16 @@ class CreateDesfilePuraTendenciaTenantTest extends TestCase
); );
$migration->up(); $migration->up();
$rowAndSeatMigration = require database_path(
'migrations/2026_08_14_030000_swap_desfile_row_and_seat_semantics.php'
);
$rowAndSeatMigration->up();
$seatOptionsMigration = require database_path(
'migrations/2026_08_14_040000_expand_desfile_seat_options.php'
);
$seatOptionsMigration->up();
$footerBackgroundMigration = require database_path( $footerBackgroundMigration = require database_path(
'migrations/2026_08_12_060000_set_desfile_footer_background_image.php' 'migrations/2026_08_12_060000_set_desfile_footer_background_image.php'
); );
@@ -186,13 +196,22 @@ class CreateDesfilePuraTendenciaTenantTest extends TestCase
$this->assertSame([ $this->assertSame([
'tipo' => ['VIP + LUNCH', 'NORMAL'], 'tipo' => ['VIP + LUNCH', 'NORMAL'],
'sector' => ['A', 'B', 'C', 'D'], 'sector' => ['A', 'B', 'C', 'D'],
'fila' => array_map('strval', range(1, 17)), 'fila' => array_map('strval', range(1, 5)),
'asiento' => array_map('strval', range(1, 5)), 'asiento' => array_map('strval', range(1, 100)),
], $attributes->map(fn (object $attribute): array => DB::table('attribute_options') ], $attributes->map(fn (object $attribute): array => DB::table('attribute_options')
->where('attribute_id', $attribute->id) ->where('attribute_id', $attribute->id)
->orderBy('sort_order') ->orderBy('sort_order')
->pluck('value') ->pluck('value')
->all())->all()); ->all())->all());
$this->assertSame(
['tipo', 'sector', 'fila', 'asiento'],
DB::table('item_attributes')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->where('item_attributes.catalog_item_id', $catalogItem->id)
->orderBy('item_attributes.sort_order')
->pluck('attribute.codigo')
->all(),
);
$variants = DB::table('variantes')->where('catalog_item_id', $catalogItem->id); $variants = DB::table('variantes')->where('catalog_item_id', $catalogItem->id);
@@ -210,6 +229,11 @@ class CreateDesfilePuraTendenciaTenantTest extends TestCase
->where('reserved_stock', 0) ->where('reserved_stock', 0)
->where('sold_units', 0) ->where('sold_units', 0)
->count()); ->count());
$this->assertDatabaseHas('variantes', [
'catalog_item_id' => $catalogItem->id,
'descripcion' => 'Sector A - Fila 1 - Asiento 17 - VIP + LUNCH',
'precio' => 250000,
]);
foreach ([ foreach ([
250000 => 34, 250000 => 34,
@@ -228,15 +252,15 @@ class CreateDesfilePuraTendenciaTenantTest extends TestCase
$this->assertSame(0, $this->variantCountForSelection($catalogItem->id, [ $this->assertSame(0, $this->variantCountForSelection($catalogItem->id, [
'sector' => ['B', 'D'], 'sector' => ['B', 'D'],
'fila' => ['17'], 'asiento' => ['17'],
])); ]));
$this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [ $this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [
'tipo' => ['VIP + LUNCH'], 'tipo' => ['VIP + LUNCH'],
'asiento' => ['1'], 'fila' => ['1'],
])); ]));
$this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [ $this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [
'tipo' => ['NORMAL'], 'tipo' => ['NORMAL'],
'asiento' => ['5'], 'fila' => ['5'],
])); ]));
} }

View File

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

View File

@@ -2,12 +2,16 @@
namespace Tests\Feature\Tenant; 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\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode; use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType; use App\Domains\Tenant\Models\WebsiteType;
use Database\Seeders\AuthorizationSeeder; use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Laravel\Sanctum\Sanctum; use Laravel\Sanctum\Sanctum;
use Tests\TestCase; 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 public function test_update_returns_not_found_for_an_unsupported_extra_code(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');

View File

@@ -4,6 +4,7 @@ namespace Tests\Feature\Tenant;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Authorization\Enums\RoleCode; use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role; use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
@@ -74,7 +75,7 @@ class BootstrapTenantControllerTest extends TestCase
'display_cart' => false, 'display_cart' => false,
]); ]);
$response = $this->getJson('/api/tenants/bootstrap/acme.com'); $response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$response $response
->assertOk() ->assertOk()
@@ -117,9 +118,9 @@ class BootstrapTenantControllerTest extends TestCase
'dominio' => 'acme.com', '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 $response
->assertOk() ->assertOk()
@@ -127,6 +128,62 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonPath('data.dominio', 'acme.com'); ->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 public function test_it_resolves_browser_branding_from_the_tenant_before_the_website_type(): void
{ {
$typeFavicon = Attachment::query()->create([ $typeFavicon = Attachment::query()->create([
@@ -153,7 +210,7 @@ class BootstrapTenantControllerTest extends TestCase
'website_type_code' => $websiteType->codigo, '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 $typeResponse
->assertOk() ->assertOk()
@@ -165,7 +222,7 @@ class BootstrapTenantControllerTest extends TestCase
'favicon_id' => $tenantFavicon->id, 'favicon_id' => $tenantFavicon->id,
]); ]);
$tenantResponse = $this->getJson('/api/tenants/bootstrap/acme.com'); $tenantResponse = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$tenantResponse $tenantResponse
->assertOk() ->assertOk()
@@ -177,7 +234,7 @@ class BootstrapTenantControllerTest extends TestCase
{ {
$this->createTenant(); $this->createTenant();
$this->getJson('/api/tenants/bootstrap/acme.com') $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk() ->assertOk()
->assertJsonPath('data.site_title', 'ShopitFront') ->assertJsonPath('data.site_title', 'ShopitFront')
->assertJsonPath('data.favicon', null); ->assertJsonPath('data.favicon', null);
@@ -210,7 +267,7 @@ class BootstrapTenantControllerTest extends TestCase
'nombre' => 'Global', 'nombre' => 'Global',
]); ]);
$this->getJson('/api/tenants/bootstrap/acme.com') $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk() ->assertOk()
->assertJsonCount(1, 'data.categories') ->assertJsonCount(1, 'data.categories')
->assertJsonPath('data.categories.0.nombre', 'Remeras') ->assertJsonPath('data.categories.0.nombre', 'Remeras')
@@ -254,16 +311,85 @@ class BootstrapTenantControllerTest extends TestCase
'is_enabled' => false, 'is_enabled' => false,
]); ]);
$this->getJson('/api/tenants/bootstrap/acme.com') $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk() ->assertOk()
->assertJsonMissingPath('data.website_type') ->assertJsonMissingPath('data.website_type')
->assertJsonPath('data.extras.contact.phone', '+54 341 555 0101') ->assertJsonPath('data.extras.contact.phone', '+54 341 555 0101')
->assertJsonMissingPath('data.extras.banner'); ->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 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(); $response->assertNotFound();
} }
@@ -317,7 +443,7 @@ class BootstrapTenantControllerTest extends TestCase
$dynamicChild->code, $dynamicChild->code,
]); ]);
$response = $this->getJson('/api/tenants/bootstrap/acme.com'); $response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');
$response $response
->assertOk() ->assertOk()
@@ -375,7 +501,7 @@ class BootstrapTenantControllerTest extends TestCase
$userRole->menus()->sync([$userMenu->code]); $userRole->menus()->sync([$userMenu->code]);
$adminRole->menus()->sync([$adminMenu->code]); $adminRole->menus()->sync([$adminMenu->code]);
$this->getJson('/api/tenants/bootstrap/acme.com') $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk() ->assertOk()
->assertJsonPath('data.menues.0.code', 'account') ->assertJsonPath('data.menues.0.code', 'account')
->assertJsonMissing(['code' => 'admin.catalog']); ->assertJsonMissing(['code' => 'admin.catalog']);
@@ -416,7 +542,7 @@ class BootstrapTenantControllerTest extends TestCase
$tenant->menues()->sync($menuCodes); $tenant->menues()->sync($menuCodes);
$userRole->menus()->sync($menuCodes); $userRole->menus()->sync($menuCodes);
$this->getJson('/api/tenants/bootstrap/acme.com') $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
->assertOk() ->assertOk()
->assertJsonPath('data.menues.0.code', 'tree') ->assertJsonPath('data.menues.0.code', 'tree')
->assertJsonPath('data.menues.1.code', 'zeta') ->assertJsonPath('data.menues.1.code', 'zeta')
@@ -424,14 +550,14 @@ class BootstrapTenantControllerTest extends TestCase
->assertJsonPath('data.menues.0.submenues.1.code', 'tree.fox'); ->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=='; $base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
$firstResponse = $this->postJson('/api/tenants', [ $firstResponse = $this->postJson('/api/tenants', [
'codigo' => 'acme', 'codigo' => 'acme',
'nombre' => 'Acme', 'nombre' => 'Acme',
'dominio' => 'https://ACME.com/path', 'dominio' => 'https://ACME.com/puratendencia/',
'primary_color' => '#111111', 'primary_color' => '#111111',
'secondary_color' => '#222222', 'secondary_color' => '#222222',
'danger_color' => '#333333', 'danger_color' => '#333333',
@@ -444,7 +570,7 @@ class BootstrapTenantControllerTest extends TestCase
$firstResponse $firstResponse
->assertCreated() ->assertCreated()
->assertJsonPath('data.dominio', 'acme.com') ->assertJsonPath('data.dominio', 'acme.com/puratendencia')
->assertJsonPath('data.primary_color', '#111111') ->assertJsonPath('data.primary_color', '#111111')
->assertJsonPath('data.secondary_color', '#222222') ->assertJsonPath('data.secondary_color', '#222222')
->assertJsonPath('data.danger_color', '#333333') ->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=') 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', [ $secondResponse = $this->postJson('/api/tenants', [
'codigo' => 'globex', 'codigo' => 'globex',
'nombre' => 'Globex', 'nombre' => 'Globex',
'dominio' => 'acme.com', 'dominio' => 'acme.com/puratendencia',
'primary_color' => '#111111', 'primary_color' => '#111111',
'secondary_color' => '#222222', 'secondary_color' => '#222222',
'danger_color' => '#333333', 'danger_color' => '#333333',
@@ -534,7 +678,7 @@ class BootstrapTenantControllerTest extends TestCase
$successfulResponse = $this->putJson("/api/tenants/{$tenant->codigo}", [ $successfulResponse = $this->putJson("/api/tenants/{$tenant->codigo}", [
'codigo' => 'acme', 'codigo' => 'acme',
'nombre' => 'Acme Updated', 'nombre' => 'Acme Updated',
'dominio' => 'https://ACME.com:443/admin', 'dominio' => 'https://ACME.com:443/',
'primary_color' => '#555555', 'primary_color' => '#555555',
'secondary_color' => '#666666', 'secondary_color' => '#666666',
'danger_color' => '#777777', 'danger_color' => '#777777',
@@ -582,7 +726,7 @@ class BootstrapTenantControllerTest extends TestCase
$failingResponse = $this->putJson("/api/tenants/{$otherTenant->codigo}", [ $failingResponse = $this->putJson("/api/tenants/{$otherTenant->codigo}", [
'codigo' => 'globex', 'codigo' => 'globex',
'nombre' => 'Globex', 'nombre' => 'Globex',
'dominio' => 'https://ACME.com/storefront', 'dominio' => 'https://ACME.com/',
]); ]);
$failingResponse $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',
));
}
}