Compare commits
21 Commits
bfdaf1c38b
...
tenant/des
| Author | SHA1 | Date | |
|---|---|---|---|
| e619c51ac9 | |||
| c00b3d609c | |||
| 9cfd49f233 | |||
| 58cc35fd61 | |||
| 460ed528cf | |||
| 1c2f6c4127 | |||
| 9e74e21fb5 | |||
| 7c2880646f | |||
| 4817cb28fe | |||
| c1bfab471c | |||
| de8da72354 | |||
| 4be94275f1 | |||
| 21b0517e6c | |||
| 7fbdc00c64 | |||
| 58c7a0f580 | |||
| a63aea0463 | |||
| b8251f3b63 | |||
| a919e9366b | |||
| 11dbcb4082 | |||
| ed321d6c6c | |||
| 573d4fe5e6 |
@@ -188,15 +188,18 @@
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap/{{tenant_domain}}",
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio={{tenant_domain}}&path={{tenant_path}}",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"bootstrap",
|
||||
"{{tenant_domain}}"
|
||||
"bootstrap"
|
||||
],
|
||||
"query": [
|
||||
{"key": "dominio", "value": "{{tenant_domain}}"},
|
||||
{"key": "path", "value": "{{tenant_path}}"}
|
||||
]
|
||||
}
|
||||
},
|
||||
@@ -1402,6 +1405,11 @@
|
||||
"value": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "tenant_path",
|
||||
"value": "/",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "tenant_id",
|
||||
"value": "1",
|
||||
|
||||
@@ -41,15 +41,18 @@
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"bootstrap",
|
||||
"acme.com"
|
||||
"bootstrap"
|
||||
],
|
||||
"query": [
|
||||
{"key": "dominio", "value": "acme.com"},
|
||||
{"key": "path", "value": "/"}
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,6 +6,9 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
@@ -40,12 +43,34 @@ class Attachment extends Model
|
||||
];
|
||||
}
|
||||
|
||||
public function cropVariants(): HasMany
|
||||
{
|
||||
return $this->hasMany(AttachmentCrop::class);
|
||||
}
|
||||
|
||||
public function desktopCrop(): HasOne
|
||||
{
|
||||
return $this->hasOne(AttachmentCrop::class)
|
||||
->where('variant', AttachmentCrop::DESKTOP);
|
||||
}
|
||||
|
||||
public function mobileCrop(): HasOne
|
||||
{
|
||||
return $this->hasOne(AttachmentCrop::class)
|
||||
->where('variant', AttachmentCrop::MOBILE);
|
||||
}
|
||||
|
||||
public function cropSource(): HasOne
|
||||
{
|
||||
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the pre-signed temporary S3 URL for this attachment.
|
||||
*/
|
||||
public function getTemporaryUrl(int $expiresInMinutes = 10): string
|
||||
{
|
||||
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl(
|
||||
return Storage::disk('s3')->temporaryUrl(
|
||||
$this->path,
|
||||
now()->addMinutes($expiresInMinutes)
|
||||
);
|
||||
|
||||
43
app/Domains/Attachable/Models/AttachmentCrop.php
Normal file
43
app/Domains/Attachable/Models/AttachmentCrop.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ namespace App\Domains\Attachable\Services;
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Mime\MimeTypes;
|
||||
@@ -13,6 +15,107 @@ use Throwable;
|
||||
|
||||
class AttachmentService
|
||||
{
|
||||
/**
|
||||
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
||||
*/
|
||||
public function storeCroppedImageVariants(
|
||||
UploadedFile|string $image,
|
||||
string $path,
|
||||
array $crops,
|
||||
): Attachment {
|
||||
$crops = $this->validateCropVariants($crops);
|
||||
$storedPaths = [];
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use (
|
||||
$image,
|
||||
$path,
|
||||
$crops,
|
||||
&$storedPaths,
|
||||
): Attachment {
|
||||
$original = $this->store($image, $path);
|
||||
$storedPaths[] = $original->path;
|
||||
$contents = $this->imageContents($image);
|
||||
|
||||
foreach ($crops as $variant => $crop) {
|
||||
$cropped = $this->storeCropVariant($contents, $path, $crop);
|
||||
$storedPaths[] = $cropped->path;
|
||||
$original->cropVariants()->create([
|
||||
'variant' => $variant,
|
||||
'crop_horizontal' => $crop['crop_horizontal'],
|
||||
'crop_vertical' => $crop['crop_vertical'],
|
||||
'cropped_attachment_id' => $cropped->id,
|
||||
]);
|
||||
}
|
||||
|
||||
return $original->load('cropVariants.croppedAttachment');
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
if ($storedPaths !== []) {
|
||||
Storage::disk('s3')->delete(array_values(array_unique($storedPaths)));
|
||||
}
|
||||
|
||||
throw $throwable;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
||||
*/
|
||||
public function updateImageCropVariants(
|
||||
Attachment $original,
|
||||
array $crops,
|
||||
): Attachment {
|
||||
if ($original->type !== AttachmentType::Image) {
|
||||
throw new AttachmentStorageException('Only image attachments can be cropped.');
|
||||
}
|
||||
|
||||
$crops = $this->validateCropVariants($crops);
|
||||
$contents = Storage::disk('s3')->get($original->path);
|
||||
|
||||
if (! is_string($contents) || $contents === '') {
|
||||
throw new AttachmentStorageException('The original image could not be read from the s3 disk.');
|
||||
}
|
||||
|
||||
$directory = trim(str_replace('\\', '/', dirname($original->path)), './');
|
||||
$directory = $directory !== '' ? $directory : 'attachments';
|
||||
$previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
|
||||
$storedCrops = [];
|
||||
|
||||
try {
|
||||
foreach ($crops as $variant => $crop) {
|
||||
$storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($original, $crops, $storedCrops): void {
|
||||
foreach ($crops as $variant => $crop) {
|
||||
$original->cropVariants()->updateOrCreate(
|
||||
['variant' => $variant],
|
||||
[
|
||||
'crop_horizontal' => $crop['crop_horizontal'],
|
||||
'crop_vertical' => $crop['crop_vertical'],
|
||||
'cropped_attachment_id' => $storedCrops[$variant]->id,
|
||||
]
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
foreach ($storedCrops as $storedCrop) {
|
||||
$this->delete($storedCrop);
|
||||
}
|
||||
|
||||
throw $throwable;
|
||||
}
|
||||
|
||||
foreach ($previousCrops as $previousCrop) {
|
||||
if ($previousCrop->croppedAttachment !== null) {
|
||||
$this->delete($previousCrop->croppedAttachment);
|
||||
}
|
||||
}
|
||||
|
||||
return $original->refresh()->load('cropVariants.croppedAttachment');
|
||||
}
|
||||
|
||||
public function store(
|
||||
UploadedFile|string $file,
|
||||
string $path,
|
||||
@@ -57,13 +160,30 @@ class AttachmentService
|
||||
|
||||
public function delete(Attachment $attachment): void
|
||||
{
|
||||
$deleted = Storage::disk('s3')->delete($attachment->path);
|
||||
$croppedAttachments = $attachment->cropVariants()
|
||||
->with('croppedAttachment')
|
||||
->get()
|
||||
->pluck('croppedAttachment')
|
||||
->filter();
|
||||
$paths = $croppedAttachments
|
||||
->pluck('path')
|
||||
->prepend($attachment->path)
|
||||
->filter()
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
$deleted = Storage::disk('s3')->delete(
|
||||
count($paths) === 1 ? $paths[0] : $paths
|
||||
);
|
||||
|
||||
if (! $deleted) {
|
||||
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
|
||||
throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.');
|
||||
}
|
||||
|
||||
$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
|
||||
@@ -107,6 +227,171 @@ class AttachmentService
|
||||
return trim($path, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{crop_horizontal?: mixed, crop_vertical?: mixed}> $crops
|
||||
* @return array<string, array{crop_horizontal: array{start_percentage: float, end_percentage: float}, crop_vertical: array{start_percentage: float, end_percentage: float}}>
|
||||
*/
|
||||
protected function validateCropVariants(array $crops): array
|
||||
{
|
||||
$validated = [];
|
||||
|
||||
foreach (AttachmentCrop::VARIANTS as $variant) {
|
||||
$crop = $crops[$variant] ?? null;
|
||||
|
||||
if (! is_array($crop)) {
|
||||
throw new AttachmentStorageException("The {$variant} crop is required.");
|
||||
}
|
||||
|
||||
$horizontal = $crop['crop_horizontal'] ?? null;
|
||||
$vertical = $crop['crop_vertical'] ?? null;
|
||||
|
||||
if (! is_array($horizontal) || ! is_array($vertical)) {
|
||||
throw new AttachmentStorageException(
|
||||
"The {$variant} crop must contain crop_horizontal and crop_vertical ranges."
|
||||
);
|
||||
}
|
||||
|
||||
$validated[$variant] = [
|
||||
'crop_horizontal' => $this->validateCropRange($horizontal, "{$variant} horizontal"),
|
||||
'crop_vertical' => $this->validateCropRange($vertical, "{$variant} vertical"),
|
||||
];
|
||||
}
|
||||
|
||||
return $validated;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>} $crop
|
||||
*/
|
||||
protected function storeCropVariant(string $contents, string $path, array $crop): Attachment
|
||||
{
|
||||
$croppedContents = $this->cropImage(
|
||||
$contents,
|
||||
$crop['crop_horizontal'],
|
||||
$crop['crop_vertical'],
|
||||
);
|
||||
|
||||
return $this->store(
|
||||
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
|
||||
$path,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range
|
||||
* @return array{start_percentage: float, end_percentage: float}
|
||||
*/
|
||||
protected function validateCropRange(array $range, string $axis): array
|
||||
{
|
||||
$start = $range['start_percentage'] ?? null;
|
||||
$end = $range['end_percentage'] ?? null;
|
||||
|
||||
if (! is_numeric($start) || ! is_numeric($end)) {
|
||||
throw new AttachmentStorageException(
|
||||
"The {$axis} crop range must contain numeric start_percentage and end_percentage values."
|
||||
);
|
||||
}
|
||||
|
||||
$start = (float) $start;
|
||||
$end = (float) $end;
|
||||
|
||||
if (! is_finite($start) || ! is_finite($end) || $start < 0 || $end > 100 || $start >= $end) {
|
||||
throw new AttachmentStorageException(
|
||||
"The {$axis} crop range must satisfy 0 <= start_percentage < end_percentage <= 100."
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'start_percentage' => $start,
|
||||
'end_percentage' => $end,
|
||||
];
|
||||
}
|
||||
|
||||
protected function imageContents(UploadedFile|string $image): string
|
||||
{
|
||||
if (is_string($image)) {
|
||||
return $this->decodeBase64File($image)['data'];
|
||||
}
|
||||
|
||||
$contents = file_get_contents($image->getRealPath());
|
||||
|
||||
if (! is_string($contents) || $contents === '') {
|
||||
throw new AttachmentStorageException('The image content cannot be empty.');
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string, mime_type: string}
|
||||
*/
|
||||
protected function cropImage(
|
||||
string $contents,
|
||||
array $cropHorizontal,
|
||||
array $cropVertical,
|
||||
): array {
|
||||
$source = @imagecreatefromstring($contents);
|
||||
|
||||
if ($source === false) {
|
||||
throw new AttachmentStorageException('The attachment must contain a valid image.');
|
||||
}
|
||||
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
$x = min($width - 1, (int) floor($width * $cropHorizontal['start_percentage'] / 100));
|
||||
$right = min($width, (int) ceil($width * $cropHorizontal['end_percentage'] / 100));
|
||||
$y = min($height - 1, (int) floor($height * $cropVertical['start_percentage'] / 100));
|
||||
$bottom = min($height, (int) ceil($height * $cropVertical['end_percentage'] / 100));
|
||||
$cropped = imagecrop($source, [
|
||||
'x' => $x,
|
||||
'y' => $y,
|
||||
'width' => $right - $x,
|
||||
'height' => $bottom - $y,
|
||||
]);
|
||||
|
||||
if ($cropped === false) {
|
||||
throw new AttachmentStorageException('The image could not be cropped.');
|
||||
}
|
||||
|
||||
return $this->encodeImage($cropped, $contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string, mime_type: string}
|
||||
*/
|
||||
protected function encodeImage(\GdImage $image, string $originalContents): array
|
||||
{
|
||||
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($originalContents);
|
||||
$mimeType = is_string($mimeType) ? strtolower($mimeType) : '';
|
||||
|
||||
ob_start();
|
||||
|
||||
try {
|
||||
$encoded = match ($mimeType) {
|
||||
'image/jpeg' => imagejpeg($image, null, 90),
|
||||
'image/gif' => imagegif($image),
|
||||
'image/webp' => imagewebp($image, null, 90),
|
||||
'image/avif' => function_exists('imageavif') && imageavif($image, null, 90),
|
||||
default => imagepng($image),
|
||||
};
|
||||
$output = ob_get_contents();
|
||||
} finally {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
if (! $encoded || ! is_string($output) || $output === '') {
|
||||
throw new AttachmentStorageException('The cropped image could not be encoded.');
|
||||
}
|
||||
|
||||
return [
|
||||
'contents' => $output,
|
||||
'mime_type' => match ($mimeType) {
|
||||
'image/jpeg', 'image/gif', 'image/webp', 'image/avif' => $mimeType,
|
||||
default => 'image/png',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
||||
{
|
||||
if ($file instanceof UploadedFile) {
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
## Propósito
|
||||
|
||||
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única.
|
||||
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con variantes recortadas para desktop y mobile.
|
||||
|
||||
## Componentes principales
|
||||
|
||||
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
|
||||
- `Models/AttachmentCrop.php`: relaciona un original con su crop desktop o mobile y la imagen generada.
|
||||
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
|
||||
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
|
||||
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
|
||||
@@ -25,5 +26,8 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
|
||||
## Consideraciones
|
||||
|
||||
- El directorio no puede quedar vacío después de normalizarlo.
|
||||
- Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`.
|
||||
- `attachment_crops` guarda una fila por variante con los rangos horizontal/vertical y el attachment procesado.
|
||||
- Al eliminar el original mediante el servicio también se eliminan todas sus variantes recortadas.
|
||||
- La eliminación se considera fallida si S3 no confirma el borrado.
|
||||
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.
|
||||
|
||||
@@ -14,7 +14,10 @@ class TenantBootstrapController extends Controller
|
||||
public function __invoke(TenantBootstrapRequest $request): TenantResource
|
||||
{
|
||||
return TenantResource::make(
|
||||
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||
$this->bootstrapService->get(
|
||||
(string) $request->validated('dominio'),
|
||||
(string) $request->validated('path'),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ class TenantBootstrapRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidPath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -17,13 +19,20 @@ class TenantBootstrapRequest extends FormRequest
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->route('dominio');
|
||||
$rawDomain = $this->query('dominio', $this->route('dominio'));
|
||||
$rawPath = $this->query('path', '/');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
|
||||
$this->merge(['dominio' => $normalizedDomain]);
|
||||
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
'path' => $normalizedPath,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
@@ -41,6 +50,17 @@ class TenantBootstrapRequest extends FormRequest
|
||||
'string',
|
||||
'max:255',
|
||||
],
|
||||
'path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidPath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:2048',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,31 @@ namespace App\Domains\Bootstrap\Services;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Services\TenantInformationService;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
|
||||
class TenantBootstrapService
|
||||
{
|
||||
public function __construct(protected TenantInformationService $tenantInformationService) {}
|
||||
|
||||
public function get(string $domain): Tenant
|
||||
public function get(string $domain, string $path = '/'): Tenant
|
||||
{
|
||||
$candidateKeys = TenantDomainNormalizer::tenantKeyCandidates($domain, $path);
|
||||
$tenantsByDomain = Tenant::query()
|
||||
->whereIn('dominio', $candidateKeys)
|
||||
->get()
|
||||
->keyBy('dominio');
|
||||
|
||||
$tenant = collect($candidateKeys)
|
||||
->map(fn (string $candidate): ?Tenant => $tenantsByDomain->get($candidate))
|
||||
->first(fn (?Tenant $candidate): bool => $candidate !== null);
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
throw (new ModelNotFoundException)->setModel(Tenant::class);
|
||||
}
|
||||
|
||||
return $this->tenantInformationService->load(
|
||||
Tenant::query()->where('dominio', $domain)->firstOrFail(),
|
||||
$tenant,
|
||||
[
|
||||
'menues' => fn ($query) => $query->whereHas(
|
||||
'roles',
|
||||
|
||||
@@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `GET /tenants/bootstrap/{dominio}`: bootstrap público de la tienda.
|
||||
- `GET /tenants/bootstrap?dominio={hostname}&path={path}`: bootstrap público de la tienda. Resuelve la clave de tenant más específica que sea prefijo completo del path y usa el dominio raíz como fallback.
|
||||
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
|
||||
|
||||
## Validación
|
||||
|
||||
`TenantBootstrapRequest` valida el dominio recibido. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||
|
||||
## Dependencias
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class)
|
||||
->where('dominio', '.*');
|
||||
Route::get('tenants/bootstrap', TenantBootstrapController::class);
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
require __DIR__.'/scanner.php';
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -35,19 +34,15 @@ class CartItemResource extends JsonResource
|
||||
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
||||
'catalog_item_id' => $this->catalog_item_id,
|
||||
'variant_id' => $this->variant_id,
|
||||
'product' => $selectedItem === null ? null : [
|
||||
'nombre' => $selectedItem->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variants' => $this->catalogItem->visibleVariants($this->variant_id)
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
'precio' => $this->formatMoney($variant->getPrice()),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
'nombre' => $selectedItem?->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variant' => $this->variant === null ? null : [
|
||||
'id' => $this->variant->id,
|
||||
'precio' => $this->formatMoney($this->variant->getPrice()),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $this->variant->inventory->availableStock(),
|
||||
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -108,10 +108,6 @@ class CartService
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.catalogItem.itemAttributes.attribute',
|
||||
'items.catalogItem.variants.inventory',
|
||||
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'items.catalogItem.variants.eventDates',
|
||||
'items.catalogItem.variants.eventDate',
|
||||
'items.variant.attachments',
|
||||
'items.variant.inventory',
|
||||
'items.variant.definitions.itemAttribute.attribute.options',
|
||||
|
||||
@@ -25,7 +25,7 @@ Bajo `/tenants/{tenant:codigo}`:
|
||||
|
||||
## Contratos
|
||||
|
||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
|
||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública. Cada ítem expone `nombre`, `imagen` y `precio_unitario` en la raíz, priorizando la variante seleccionada y usando el catálogo base como respaldo. La variante seleccionada se serializa en `variant`; las variantes alternativas no forman parte de la respuesta del carrito.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Cart\Services\CartService;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
||||
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
|
||||
use App\Domains\Catalog\Requests\CategoryPageRequest;
|
||||
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
||||
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\CatalogItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
||||
use App\Domains\Catalog\Services\VariantSelectionService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
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(
|
||||
StoreCatalogItemRequest $request,
|
||||
Tenant $tenant,
|
||||
|
||||
@@ -8,9 +8,7 @@ use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -18,6 +16,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
@@ -34,12 +33,10 @@ use Illuminate\Support\Collection;
|
||||
'inventory_subject',
|
||||
'max_units_per_user',
|
||||
'has_tickets',
|
||||
'ticket_generation_policy',
|
||||
'validity_time_id',
|
||||
])]
|
||||
class CatalogItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -50,7 +47,6 @@ class CatalogItem extends Model
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'inventory_subject' => InventorySubject::Product->value,
|
||||
'has_tickets' => false,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::PerEventDate->value,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -65,8 +61,6 @@ class CatalogItem extends Model
|
||||
'inventory_subject' => InventorySubject::class,
|
||||
'max_units_per_user' => 'integer',
|
||||
'has_tickets' => 'boolean',
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::class,
|
||||
'validity_time_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -118,12 +112,6 @@ class CatalogItem extends Model
|
||||
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<ValidityTime, $this> */
|
||||
public function validityTime(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ValidityTime::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attribute, $this> */
|
||||
public function attributes(): BelongsToMany
|
||||
{
|
||||
@@ -145,6 +133,12 @@ class CatalogItem extends Model
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Attachment::class,
|
||||
@@ -152,7 +146,7 @@ class CatalogItem extends Model
|
||||
'catalog_item_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->wherePivotNull('variant_id')
|
||||
->orderByPivot('orden');
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Lang;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -24,7 +25,7 @@ use Illuminate\Support\Str;
|
||||
])]
|
||||
class Variant extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -43,7 +44,7 @@ class Variant extends Model
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class);
|
||||
return $this->belongsTo(CatalogItem::class)->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
@@ -83,6 +84,12 @@ class Variant extends Model
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
$relation = $this->belongsToMany(
|
||||
Attachment::class,
|
||||
@@ -90,7 +97,7 @@ class Variant extends Model
|
||||
'variant_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->orderByPivot('orden');
|
||||
|
||||
if ($this->catalog_item_id !== null) {
|
||||
|
||||
@@ -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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -58,8 +57,6 @@ class StoreCatalogItemRequest extends FormRequest
|
||||
'inventory_subject' => ['sometimes', Rule::enum(InventorySubject::class)],
|
||||
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||
'ticket_generation_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(TicketGenerationPolicy::class)],
|
||||
'validity_time_id' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'integer', Rule::exists('validity_times', 'id')],
|
||||
'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
|
||||
'inventory_id' => ['prohibited'],
|
||||
'reserved_stock' => ['prohibited'],
|
||||
|
||||
@@ -7,7 +7,6 @@ use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -25,15 +24,16 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
return $this->columnWithImageData($catalogItem);
|
||||
}
|
||||
|
||||
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||
return $this->ticketSelectorData($catalogItem);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
|
||||
'validity_time_id' => $catalogItem->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||
'stock_tecnico' => $catalogItem->availableStock(),
|
||||
'variants' => $catalogItem->visibleVariants()
|
||||
->map(fn (Variant $variant): array => [
|
||||
@@ -52,13 +52,22 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
->values(),
|
||||
];
|
||||
|
||||
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||
$data['image'] = $this->firstImageUrl($catalogItem);
|
||||
}
|
||||
|
||||
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> */
|
||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||
{
|
||||
@@ -67,9 +76,6 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'precio' => $catalogItem->precio,
|
||||
'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
|
||||
'validity_time_id' => $catalogItem->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||
'image' => $this->firstImageUrl($catalogItem),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -36,11 +36,6 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => $this->validityTime === null
|
||||
? null
|
||||
: ValidityTimeResource::make($this->validityTime),
|
||||
'attributes' => $this->attributesData(),
|
||||
'stock_tecnico' => $this->when(
|
||||
$selectedVariant === null,
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -26,12 +25,6 @@ class CatalogItemResource extends JsonResource
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => $this->whenLoaded(
|
||||
'validityTime',
|
||||
fn () => ValidityTimeResource::make($this->validityTime),
|
||||
),
|
||||
'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
|
||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
|
||||
@@ -5,7 +5,6 @@ namespace App\Domains\Catalog\Resources;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -26,9 +25,6 @@ class CatalogSearchItemResource extends JsonResource
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($this->validityTime),
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'stock_tecnico' => $this->availableStock(),
|
||||
'variants' => $this->visibleVariants()
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -160,7 +160,6 @@ class CatalogService
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
@@ -180,7 +179,6 @@ class CatalogService
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute.options.validityTime',
|
||||
'itemAttributes.attribute.eventDates.validityTime',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
@@ -241,7 +239,6 @@ class CatalogService
|
||||
->with([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
@@ -277,7 +274,6 @@ class CatalogService
|
||||
->with([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
@@ -294,32 +290,8 @@ class CatalogService
|
||||
public function delete(CatalogItem $catalogItem): void
|
||||
{
|
||||
DB::transaction(function () use ($catalogItem): void {
|
||||
$catalogItem->load([
|
||||
'attachments',
|
||||
'variants.attachments',
|
||||
]);
|
||||
|
||||
$attachments = $catalogItem->attachments
|
||||
->merge($catalogItem->variants->flatMap->attachments)
|
||||
->unique('id');
|
||||
$inventoryIds = collect([$catalogItem->inventory_id])
|
||||
->merge($catalogItem->variants->pluck('inventory_id'))
|
||||
->filter()
|
||||
->unique();
|
||||
|
||||
$catalogItem->attachments()->detach();
|
||||
foreach ($catalogItem->variants as $variant) {
|
||||
$variant->attachments()->detach();
|
||||
}
|
||||
|
||||
$catalogItem->variants()->delete();
|
||||
$catalogItem->delete();
|
||||
Inventory::query()->whereKey($inventoryIds)->delete();
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
$this->attachmentService->delete($attachment);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -327,32 +299,19 @@ class CatalogService
|
||||
{
|
||||
DB::transaction(function () use ($variant): void {
|
||||
$variant = Variant::query()
|
||||
->with('attachments')
|
||||
->lockForUpdate()
|
||||
->findOrFail($variant->getKey());
|
||||
$catalogItem = CatalogItem::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($variant->catalog_item_id);
|
||||
$attachments = $variant->attachments;
|
||||
$inventoryId = $variant->inventory_id;
|
||||
|
||||
$variant->attachments()->detach();
|
||||
$variant->delete();
|
||||
Inventory::query()->whereKey($inventoryId)->delete();
|
||||
|
||||
$minimumPrice = $catalogItem->variants()->min('precio');
|
||||
|
||||
if ($minimumPrice === null) {
|
||||
if (! $catalogItem->variants()->exists()) {
|
||||
$this->delete($catalogItem);
|
||||
} else {
|
||||
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) {
|
||||
$catalogItem->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
$this->attachmentService->delete($attachment);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -457,8 +416,6 @@ class CatalogService
|
||||
'attribute_codes',
|
||||
'variants',
|
||||
'has_tickets',
|
||||
'ticket_generation_policy',
|
||||
'validity_time_id',
|
||||
] as $field) {
|
||||
if (array_key_exists($field, $data)) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -731,16 +688,6 @@ class CatalogService
|
||||
]);
|
||||
}
|
||||
|
||||
$validityTimeIds = $resolvedOptions
|
||||
->pluck('validity_time_id')
|
||||
->filter()
|
||||
->unique();
|
||||
if ($validityTimeIds->count() > 1) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [__('api.catalog.incompatible_validity_windows')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $resolvedOptions->pluck('value')->all();
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ class FeaturedGroupService
|
||||
->with([
|
||||
'inventory',
|
||||
'attachments',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
|
||||
225
app/Domains/Catalog/Services/VariantSelectionService.php
Normal file
225
app/Domains/Catalog/Services/VariantSelectionService.php
Normal 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);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::get('categories/{category}', [CatalogController::class, 'category'])
|
||||
->name('categories.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']);
|
||||
});
|
||||
|
||||
|
||||
57
app/Domains/Desfile/Controllers/EntryController.php
Normal file
57
app/Domains/Desfile/Controllers/EntryController.php
Normal 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();
|
||||
}
|
||||
}
|
||||
22
app/Domains/Desfile/Requests/ReplaceEntryImageRequest.php
Normal file
22
app/Domains/Desfile/Requests/ReplaceEntryImageRequest.php
Normal 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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
55
app/Domains/Desfile/Requests/SyncEntryRowsRequest.php
Normal file
55
app/Domains/Desfile/Requests/SyncEntryRowsRequest.php
Normal 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;
|
||||
}
|
||||
}];
|
||||
}
|
||||
}
|
||||
21
app/Domains/Desfile/Requests/UpdateEntryImageRequest.php
Normal file
21
app/Domains/Desfile/Requests/UpdateEntryImageRequest.php
Normal 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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
56
app/Domains/Desfile/Resources/EntryResource.php
Normal file
56
app/Domains/Desfile/Resources/EntryResource.php
Normal 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,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
302
app/Domains/Desfile/Services/EntryService.php
Normal file
302
app/Domains/Desfile/Services/EntryService.php
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,19 @@
|
||||
<?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');
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ class EventDate extends Model
|
||||
$eventDate->syncTenantDateText();
|
||||
ValidityTime::query()
|
||||
->whereKey($eventDate->validity_time_id)
|
||||
->whereDoesntHave('ticketValidityGroups')
|
||||
->delete();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Event\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class EventService
|
||||
{
|
||||
@@ -60,7 +61,19 @@ class EventService
|
||||
}
|
||||
}
|
||||
|
||||
$existingDates->slice(count($dates))->each->delete();
|
||||
$datesToDelete = $existingDates->slice(count($dates));
|
||||
|
||||
if ($datesToDelete->contains(fn ($eventDate): bool => $eventDate
|
||||
->selectedByVariants()
|
||||
->whereHas('sourceTickets')
|
||||
->exists()
|
||||
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
|
||||
throw ValidationException::withMessages([
|
||||
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$datesToDelete->each->delete();
|
||||
$tenant->unsetRelation('eventDates');
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -126,18 +125,21 @@ class AccommodationService
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Alojamientos',
|
||||
]);
|
||||
$accommodation = CatalogItem::query()
|
||||
$accommodation = CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'alojamiento')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($accommodation !== null) {
|
||||
if ($accommodation->trashed()) {
|
||||
$accommodation->restore();
|
||||
}
|
||||
|
||||
$accommodation->update([
|
||||
'category_id' => $category->id,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
return $accommodation;
|
||||
@@ -152,7 +154,6 @@ class AccommodationService
|
||||
'precio' => collect($variants)->min('price') ?? 0,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -63,7 +62,6 @@ class EntryService
|
||||
'category_id' => $category->id,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'attribute_codes' => ['event_date'],
|
||||
'multi_select_attribute_codes' => ['event_date'],
|
||||
@@ -135,7 +133,6 @@ class EntryService
|
||||
'category_id' => $category->id,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
]);
|
||||
$variant->update([
|
||||
@@ -163,7 +160,7 @@ class EntryService
|
||||
|
||||
while (
|
||||
in_array($slug, $reservedSlugs, true)
|
||||
|| CatalogItem::query()
|
||||
|| CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', $slug)
|
||||
->exists()
|
||||
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -137,18 +136,21 @@ class FoodService
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Comidas',
|
||||
]);
|
||||
$food = CatalogItem::query()
|
||||
$food = CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($food !== null) {
|
||||
if ($food->trashed()) {
|
||||
$food->restore();
|
||||
}
|
||||
|
||||
$food->update([
|
||||
'category_id' => $category->id,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
return $food;
|
||||
@@ -163,7 +165,6 @@ class FoodService
|
||||
'precio' => collect($variants)->min('price') ?? 0,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -75,7 +74,6 @@ class MerchandiseService
|
||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
$itemAttributes = $this->itemAttributes($item, $attributes);
|
||||
@@ -200,7 +198,6 @@ class MerchandiseService
|
||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
@@ -414,7 +411,7 @@ class MerchandiseService
|
||||
|
||||
while (
|
||||
in_array($slug, $reservedSlugs, true)
|
||||
|| CatalogItem::query()
|
||||
|| CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', $slug)
|
||||
->exists()
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -104,6 +105,7 @@ class NotificationMailService
|
||||
->where('tenant_code', $purchase->tenant_codigo)
|
||||
->where('user_id', $purchase->user_id)
|
||||
->whereKey($ticketIds)
|
||||
->with(TicketPresentationResolver::RELATIONS)
|
||||
->get();
|
||||
|
||||
if ($tickets->isEmpty()) {
|
||||
|
||||
@@ -7,6 +7,8 @@ use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -58,7 +60,7 @@ class AdminAppSaleService
|
||||
{
|
||||
return $this->findForTenant($tenant, $saleId)
|
||||
->tickets()
|
||||
->with('validityGroups.validityTimes')
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
86
app/Domains/Shared/Rules/CroppedImageOrBase64Rule.php
Normal file
86
app/Domains/Shared/Rules/CroppedImageOrBase64Rule.php
Normal 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.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ class StoreTenantRequest extends FormRequest
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->input('dominio');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
|
||||
@@ -24,7 +24,7 @@ class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
if ($this->has('dominio')) {
|
||||
$rawDomain = $this->input('dominio');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Tenant\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Tenant\Models\WebsiteExtra;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
@@ -29,12 +30,44 @@ class WebsiteExtraResource extends JsonResource
|
||||
fn (Attachment $attachment): string => $attachment->key
|
||||
),
|
||||
'resolved_config' => $this->formatConfig(
|
||||
$this->resolvedConfig(),
|
||||
$this->resolvedAdminConfig(),
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
private function resolvedAdminConfig(): mixed
|
||||
{
|
||||
$config = $this->resolvedConfig();
|
||||
|
||||
if (
|
||||
$this->websiteTypeExtra->codigo !== 'heroConfig'
|
||||
|| ! is_array($config)
|
||||
|| ! ($config['background_image_id'] ?? null) instanceof Attachment
|
||||
) {
|
||||
return $config;
|
||||
}
|
||||
|
||||
$attachment = $config['background_image_id'];
|
||||
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
|
||||
$crops = $attachment->cropVariants->keyBy('variant');
|
||||
$config['background_image_id'] = [
|
||||
'url' => $attachment->getTemporaryUrl(1440),
|
||||
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
|
||||
function (string $variant) use ($crops, $fullRange): array {
|
||||
$crop = $crops->get($variant);
|
||||
|
||||
return [$variant => [
|
||||
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
|
||||
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
|
||||
]];
|
||||
}
|
||||
)->all(),
|
||||
];
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
private function formatConfig(mixed $value, callable $formatAttachment): mixed
|
||||
{
|
||||
if ($value instanceof Attachment) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Tenant\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
@@ -45,14 +46,53 @@ class WebsiteExtrasResource extends JsonResource
|
||||
),
|
||||
]),
|
||||
'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
|
||||
$extra->websiteTypeExtra->codigo => $this->formatConfig(
|
||||
$extra->resolvedConfig(),
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
),
|
||||
$extra->websiteTypeExtra->codigo => $this->formatResolvedConfig($extra),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
private function formatResolvedConfig(mixed $extra): mixed
|
||||
{
|
||||
$config = $extra->resolvedConfig();
|
||||
|
||||
if (
|
||||
$extra->websiteTypeExtra->codigo === 'heroConfig'
|
||||
&& is_array($config)
|
||||
&& ($config['background_image_id'] ?? null) instanceof Attachment
|
||||
) {
|
||||
$attachment = $config['background_image_id'];
|
||||
$config['background_image_id'] = $this->formatHeroAttachment($attachment);
|
||||
}
|
||||
|
||||
return $this->formatConfig(
|
||||
$config,
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string, crops: array<string, array<string, array<string, float>>>}
|
||||
*/
|
||||
private function formatHeroAttachment(Attachment $attachment): array
|
||||
{
|
||||
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
|
||||
$crops = $attachment->cropVariants->keyBy('variant');
|
||||
|
||||
return [
|
||||
'url' => $attachment->getTemporaryUrl(1440),
|
||||
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
|
||||
function (string $variant) use ($crops, $fullRange): array {
|
||||
$crop = $crops->get($variant);
|
||||
|
||||
return [$variant => [
|
||||
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
|
||||
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
|
||||
]];
|
||||
}
|
||||
)->all(),
|
||||
];
|
||||
}
|
||||
|
||||
private function formatConfig(mixed $value, callable $formatAttachment): mixed
|
||||
{
|
||||
if ($value instanceof Attachment) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Tenant\Resources;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -98,7 +99,18 @@ class TenantResource extends JsonResource
|
||||
private function formatExtraConfig(mixed $value): mixed
|
||||
{
|
||||
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)) {
|
||||
|
||||
@@ -81,6 +81,7 @@ class TenantInformationService
|
||||
|
||||
$attachments = Attachment::query()
|
||||
->whereIn('id', $attachmentIds)
|
||||
->with('cropVariants.croppedAttachment')
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Services;
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
use App\Domains\Shared\Rules\CroppedImageOrBase64Rule;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Models\WebsiteExtra;
|
||||
@@ -222,9 +223,11 @@ class WebsiteExtraService
|
||||
$compiled = is_string($rules) ? explode('|', $rules) : $rules;
|
||||
|
||||
return array_map(
|
||||
fn (mixed $rule): mixed => $rule === 'image_or_base64'
|
||||
? new ImageOrBase64Rule
|
||||
: $rule,
|
||||
fn (mixed $rule): mixed => match ($rule) {
|
||||
'image_or_base64' => new ImageOrBase64Rule,
|
||||
'cropped_image_or_base64' => new CroppedImageOrBase64Rule,
|
||||
default => $rule,
|
||||
},
|
||||
$compiled
|
||||
);
|
||||
}
|
||||
@@ -331,8 +334,11 @@ class WebsiteExtraService
|
||||
);
|
||||
}
|
||||
|
||||
if (is_string($value) && Str::isUuid($value)) {
|
||||
$attachment = Attachment::query()->where('key', $value)->first();
|
||||
$crops = $this->cropVariants($value);
|
||||
$image = is_array($value) ? $value['image'] ?? null : $value;
|
||||
|
||||
if (is_string($image) && Str::isUuid($image)) {
|
||||
$attachment = Attachment::query()->where('key', $image)->first();
|
||||
|
||||
if (! $attachment) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -341,9 +347,22 @@ class WebsiteExtraService
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($crops !== null) {
|
||||
$attachment = $this->attachmentService->updateImageCropVariants(
|
||||
$attachment,
|
||||
$crops,
|
||||
);
|
||||
}
|
||||
} elseif ($crops !== null) {
|
||||
$attachment = $this->attachmentService->storeCroppedImageVariants(
|
||||
$image,
|
||||
"tenants/{$tenant->codigo}/extras/{$definition->codigo}",
|
||||
$crops,
|
||||
);
|
||||
} else {
|
||||
$attachment = $this->attachmentService->store(
|
||||
$value,
|
||||
$image,
|
||||
"tenants/{$tenant->codigo}/extras/{$definition->codigo}"
|
||||
);
|
||||
}
|
||||
@@ -364,4 +383,37 @@ class WebsiteExtraService
|
||||
|
||||
return $attachment->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the current variants payload and the original single-crop contract.
|
||||
*
|
||||
* @return array<string, array<string, mixed>>|null
|
||||
*/
|
||||
private function cropVariants(mixed $value): ?array
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($value['crops']) && is_array($value['crops'])) {
|
||||
return $value['crops'];
|
||||
}
|
||||
|
||||
$horizontal = $value['crop_horizontal'] ?? null;
|
||||
$vertical = $value['crop_vertical'] ?? null;
|
||||
|
||||
if (! is_array($horizontal) || ! is_array($vertical)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$crop = [
|
||||
'crop_horizontal' => $horizontal,
|
||||
'crop_vertical' => $vertical,
|
||||
];
|
||||
|
||||
return [
|
||||
'desktop' => $crop,
|
||||
'mobile' => $crop,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,4 +33,90 @@ class TenantDomainNormalizer
|
||||
|
||||
return strtolower($host);
|
||||
}
|
||||
|
||||
public static function normalizeTenantKey(mixed $domain, mixed $path = null): ?string
|
||||
{
|
||||
$host = self::normalize($domain);
|
||||
|
||||
if ($host === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($path === null && is_string($domain)) {
|
||||
$decodedDomain = trim(urldecode($domain));
|
||||
$candidate = str_contains($decodedDomain, '://')
|
||||
? $decodedDomain
|
||||
: "//{$decodedDomain}";
|
||||
$path = parse_url($candidate, PHP_URL_PATH) ?: '/';
|
||||
}
|
||||
|
||||
$normalizedPath = self::normalizePath($path);
|
||||
|
||||
if ($normalizedPath === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $host.($normalizedPath === '/' ? '' : $normalizedPath);
|
||||
}
|
||||
|
||||
public static function normalizePath(mixed $path): ?string
|
||||
{
|
||||
if (! is_string($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = trim($path);
|
||||
|
||||
if ($path === '' || $path === '/') {
|
||||
return '/';
|
||||
}
|
||||
|
||||
$path = parse_url(str_starts_with($path, '/') ? $path : "/{$path}", PHP_URL_PATH);
|
||||
|
||||
if (! is_string($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = preg_replace('#/+#', '/', $path);
|
||||
|
||||
if (! is_string($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$segments = array_filter(explode('/', $path), static fn (string $segment): bool => $segment !== '');
|
||||
|
||||
foreach ($segments as $segment) {
|
||||
if ($segment === '.' || $segment === '..') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return '/'.implode('/', $segments);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function tenantKeyCandidates(mixed $domain, mixed $path): array
|
||||
{
|
||||
$host = self::normalize($domain);
|
||||
$normalizedPath = self::normalizePath($path);
|
||||
|
||||
if ($host === null || $normalizedPath === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$segments = array_values(array_filter(
|
||||
explode('/', $normalizedPath),
|
||||
static fn (string $segment): bool => $segment !== '',
|
||||
));
|
||||
$candidates = [];
|
||||
|
||||
while ($segments !== []) {
|
||||
$candidates[] = $host.'/'.implode('/', $segments);
|
||||
array_pop($segments);
|
||||
}
|
||||
|
||||
$candidates[] = $host;
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Requests\DownloadTicketsPdfRequest;
|
||||
use App\Domains\Ticket\Resources\TicketResource;
|
||||
use App\Domains\Ticket\Services\TicketPdfService;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -22,7 +24,7 @@ class TicketController extends Controller
|
||||
$tickets = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('user_id', $request->user()->getKey())
|
||||
->with('validityGroups.validityTimes', 'sourceVariant.eventDate', 'sourceVariant.catalogItem')
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
@@ -36,7 +38,7 @@ class TicketController extends Controller
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('user_id', $request->user()->getKey())
|
||||
->whereIn('id', $ticketIds)
|
||||
->with('validityGroups.validityTimes', 'sourceVariant.eventDate', 'sourceVariant.catalogItem')
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Enums;
|
||||
|
||||
enum TicketGenerationPolicy: string
|
||||
{
|
||||
case PerEventDate = 'per_event_date';
|
||||
case OnePerUnit = 'one_per_unit';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Ticket\Exceptions;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use RuntimeException;
|
||||
@@ -24,9 +25,9 @@ class TicketGenerationException extends RuntimeException
|
||||
return new self(__('api.ticket.disabled', ['product' => $catalogItem->id]));
|
||||
}
|
||||
|
||||
public static function ambiguousValidityTime(CatalogItem $catalogItem): self
|
||||
public static function invalidValidityConfiguration(CatalogItem $catalogItem, Variant $variant): self
|
||||
{
|
||||
return new self("Catalog item {$catalogItem->id} resolves more than one validity time.");
|
||||
return new self("Variant {$variant->id} from catalog item {$catalogItem->id} has an invalid validity configuration.");
|
||||
}
|
||||
|
||||
public static function variantNotFound(
|
||||
|
||||
@@ -7,20 +7,20 @@ use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Services\ResolvedTicketValidity;
|
||||
use App\Domains\Ticket\Services\ResolvedValidityGroup;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'ticket',
|
||||
'name',
|
||||
'description',
|
||||
'source_purchase_id',
|
||||
'source_catalog_item_id',
|
||||
'source_variant_id',
|
||||
@@ -32,6 +32,8 @@ class Ticket extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
private ?ResolvedTicketValidity $resolvedValidity = null;
|
||||
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
@@ -41,6 +43,8 @@ class Ticket extends Model
|
||||
public $timestamps = false;
|
||||
|
||||
protected $appends = [
|
||||
'name',
|
||||
'description',
|
||||
'is_valid',
|
||||
'is_expired',
|
||||
'is_used',
|
||||
@@ -86,19 +90,13 @@ class Ticket extends Model
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function sourceCatalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id');
|
||||
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Variant, $this> */
|
||||
public function sourceVariant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Variant::class, 'source_variant_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TicketValidityGroup, $this> */
|
||||
public function validityGroups(): HasMany
|
||||
{
|
||||
return $this->hasMany(TicketValidityGroup::class);
|
||||
return $this->belongsTo(Variant::class, 'source_variant_id')->withTrashed();
|
||||
}
|
||||
|
||||
public function isValid(): bool
|
||||
@@ -107,12 +105,7 @@ class Ticket extends Model
|
||||
return false;
|
||||
}
|
||||
|
||||
$validityGroups = $this->resolvedValidityGroups();
|
||||
|
||||
return $validityGroups->isEmpty()
|
||||
|| $validityGroups->contains(
|
||||
fn (TicketValidityGroup $group): bool => $group->isValid()
|
||||
);
|
||||
return $this->resolvedValidity()->isValid();
|
||||
}
|
||||
|
||||
public function getIsValidAttribute(): bool
|
||||
@@ -122,13 +115,7 @@ class Ticket extends Model
|
||||
|
||||
public function getIsExpiredAttribute(): bool
|
||||
{
|
||||
$validityGroups = $this->resolvedValidityGroups();
|
||||
|
||||
return $this->used_at === null
|
||||
&& $validityGroups->isNotEmpty()
|
||||
&& $validityGroups->every(
|
||||
fn (TicketValidityGroup $group): bool => $group->isExpired()
|
||||
);
|
||||
return $this->used_at === null && $this->resolvedValidity()->isExpired();
|
||||
}
|
||||
|
||||
public function getIsUsedAttribute(): bool
|
||||
@@ -149,52 +136,34 @@ class Ticket extends Model
|
||||
return self::STATUS_ACTIVE;
|
||||
}
|
||||
|
||||
public function getNameAttribute(): string
|
||||
{
|
||||
return app(TicketPresentationResolver::class)->name($this);
|
||||
}
|
||||
|
||||
public function getDescriptionAttribute(): string
|
||||
{
|
||||
return app(TicketPresentationResolver::class)->description($this);
|
||||
}
|
||||
|
||||
public function getEffectiveStartsAt(): ?CarbonInterface
|
||||
{
|
||||
return $this->resolvedValidityGroups()
|
||||
->map(fn (TicketValidityGroup $group): ?CarbonInterface => $group->effectiveStartsAt())
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
return $this->resolvedValidity()->effectiveStartsAt();
|
||||
}
|
||||
|
||||
public function getEffectiveExpiresAt(): ?CarbonInterface
|
||||
{
|
||||
return $this->resolvedValidityGroups()
|
||||
->map(fn (TicketValidityGroup $group): ?CarbonInterface => $group->effectiveExpiresAt())
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
return $this->resolvedValidity()->effectiveExpiresAt();
|
||||
}
|
||||
|
||||
/** @return Collection<int, ValidityTime> */
|
||||
public function allValidityTimes(): Collection
|
||||
/** @return Collection<int, ResolvedValidityGroup> */
|
||||
public function resolvedValidityGroups(): Collection
|
||||
{
|
||||
return $this->resolvedValidityGroups()
|
||||
->flatMap(fn (TicketValidityGroup $group): EloquentCollection => $group->resolvedValidityTimes())
|
||||
->unique(
|
||||
fn (ValidityTime $validityTime): int => $validityTime->getKey()
|
||||
?? spl_object_id($validityTime)
|
||||
)
|
||||
->values();
|
||||
return $this->resolvedValidity()->groups;
|
||||
}
|
||||
|
||||
/** @return EloquentCollection<int, TicketValidityGroup> */
|
||||
public function resolvedValidityGroups(): EloquentCollection
|
||||
public function resolvedValidity(): ResolvedTicketValidity
|
||||
{
|
||||
if ($this->relationLoaded('validityGroups')) {
|
||||
return $this->getRelation('validityGroups');
|
||||
}
|
||||
|
||||
if (! $this->exists) {
|
||||
return new EloquentCollection;
|
||||
}
|
||||
|
||||
$validityGroups = $this->validityGroups()
|
||||
->with('validityTimes')
|
||||
->get();
|
||||
$this->setRelation('validityGroups', $validityGroups);
|
||||
|
||||
return $validityGroups;
|
||||
return $this->resolvedValidity ??= app(TicketValidityResolver::class)->resolveTicket($this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
#[Fillable(['ticket_id'])]
|
||||
class TicketValidityGroup extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
/** @return BelongsTo<Ticket, $this> */
|
||||
public function ticket(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Ticket::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<ValidityTime, $this> */
|
||||
public function validityTimes(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
ValidityTime::class,
|
||||
'ticket_validity_group_times',
|
||||
'ticket_validity_group_id',
|
||||
'validity_time_id',
|
||||
);
|
||||
}
|
||||
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$validityTimes = $this->resolvedValidityTimes();
|
||||
|
||||
return $validityTimes->isNotEmpty()
|
||||
&& $validityTimes->every(
|
||||
fn (ValidityTime $validityTime): bool => $validityTime->isValid($at)
|
||||
);
|
||||
}
|
||||
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $expiresAt !== null && $expiresAt->lessThanOrEqualTo($at);
|
||||
}
|
||||
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->resolvedValidityTimes()
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->startsAt($anchor))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->resolvedValidityTimes()
|
||||
->map(function (ValidityTime $validityTime) use ($anchor): ?CarbonInterface {
|
||||
$startsAt = $validityTime->startsAt($anchor);
|
||||
$expiresAt = $validityTime->expiresAt($anchor);
|
||||
|
||||
if (
|
||||
$startsAt !== null
|
||||
&& $expiresAt !== null
|
||||
&& $expiresAt->lessThanOrEqualTo($startsAt)
|
||||
) {
|
||||
return $expiresAt->addDay();
|
||||
}
|
||||
|
||||
return $expiresAt;
|
||||
})
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/** @return EloquentCollection<int, ValidityTime> */
|
||||
public function resolvedValidityTimes(): EloquentCollection
|
||||
{
|
||||
if ($this->relationLoaded('validityTimes')) {
|
||||
return $this->getRelation('validityTimes');
|
||||
}
|
||||
|
||||
if (! $this->exists) {
|
||||
return new EloquentCollection;
|
||||
}
|
||||
|
||||
$validityTimes = $this->validityTimes()->get();
|
||||
$this->setRelation('validityTimes', $validityTimes);
|
||||
|
||||
return $validityTimes;
|
||||
}
|
||||
|
||||
private function dateAnchor(): ?CarbonInterface
|
||||
{
|
||||
return $this->resolvedValidityTimes()
|
||||
->filter(fn (ValidityTime $validityTime): bool => $validityTime->type === ValidityTimeType::FixedWindow)
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->fixed_starts_at)
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\AttributeOption;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -11,7 +10,6 @@ use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
@@ -35,12 +33,6 @@ class ValidityTime extends Model
|
||||
];
|
||||
}
|
||||
|
||||
/** @return HasMany<CatalogItem, $this> */
|
||||
public function catalogItems(): HasMany
|
||||
{
|
||||
return $this->hasMany(CatalogItem::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<AttributeOption, $this> */
|
||||
public function attributeOptions(): HasMany
|
||||
{
|
||||
@@ -53,17 +45,6 @@ class ValidityTime extends Model
|
||||
return $this->hasOne(EventDate::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<TicketValidityGroup, $this> */
|
||||
public function ticketValidityGroups(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
TicketValidityGroup::class,
|
||||
'ticket_validity_group_times',
|
||||
'validity_time_id',
|
||||
'ticket_validity_group_id',
|
||||
);
|
||||
}
|
||||
|
||||
public function startsAt(
|
||||
?CarbonInterface $at = null,
|
||||
): ?CarbonInterface {
|
||||
|
||||
@@ -22,10 +22,6 @@ class TicketResource extends JsonResource
|
||||
'category' => $this->sourceCatalogItem?->category?->nombre,
|
||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||
'source_variant_id' => $this->source_variant_id,
|
||||
'validity_times' => ValidityTimeResource::collection($this->allValidityTimes()),
|
||||
'validity_groups' => TicketValidityGroupResource::collection(
|
||||
$this->resolvedValidityGroups()
|
||||
),
|
||||
'starts_at' => $this->getEffectiveStartsAt(),
|
||||
'expires_at' => $this->getEffectiveExpiresAt(),
|
||||
'used_at' => $this->used_at,
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources;
|
||||
|
||||
use App\Domains\Ticket\Models\TicketValidityGroup;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin TicketValidityGroup */
|
||||
class TicketValidityGroupResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'validity_times' => ValidityTimeResource::collection($this->resolvedValidityTimes()),
|
||||
'starts_at' => $this->effectiveStartsAt(),
|
||||
'expires_at' => $this->effectiveExpiresAt(),
|
||||
'is_valid' => $this->isValid(),
|
||||
'is_expired' => $this->isExpired(),
|
||||
];
|
||||
}
|
||||
}
|
||||
77
app/Domains/Ticket/Services/ResolvedTicketValidity.php
Normal file
77
app/Domains/Ticket/Services/ResolvedTicketValidity.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Resultado completo de resolver la vigencia de un ticket.
|
||||
*
|
||||
* Cada ResolvedValidityGroup contiene condiciones AND. Entre los grupos se
|
||||
* aplica OR, por lo que alcanza con que uno de ellos esté activo.
|
||||
*/
|
||||
final readonly class ResolvedTicketValidity
|
||||
{
|
||||
/** @param Collection<int, ResolvedValidityGroup> $groups */
|
||||
public function __construct(
|
||||
public Collection $groups,
|
||||
public bool $isResolvable = true,
|
||||
public bool $isUnrestricted = false,
|
||||
) {}
|
||||
|
||||
/** No existe ninguna restricción temporal configurada. */
|
||||
public static function unrestricted(): self
|
||||
{
|
||||
return new self(collect(), isUnrestricted: true);
|
||||
}
|
||||
|
||||
/** La configuración fuente está incompleta o es inconsistente. */
|
||||
public static function unresolvable(): self
|
||||
{
|
||||
return new self(collect(), isResolvable: false);
|
||||
}
|
||||
|
||||
/** Es válido cuando no tiene restricciones o algún grupo OR está activo. */
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
if (! $this->isResolvable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isUnrestricted || $this->groups->contains(
|
||||
fn (ResolvedValidityGroup $group): bool => $group->isValid($at)
|
||||
);
|
||||
}
|
||||
|
||||
/** Sólo está vencido cuando todos los grupos OR ya vencieron. */
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
return $this->isResolvable
|
||||
&& ! $this->isUnrestricted
|
||||
&& $this->groups->isNotEmpty()
|
||||
&& $this->groups->every(
|
||||
fn (ResolvedValidityGroup $group): bool => $group->isExpired($at)
|
||||
);
|
||||
}
|
||||
|
||||
/** Inicio más temprano de todas las alternativas, usado como resumen. */
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
return $this->groups
|
||||
->map(fn (ResolvedValidityGroup $group): ?CarbonInterface => $group->effectiveStartsAt($at))
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/** Vencimiento más tardío de todas las alternativas, usado como resumen. */
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
return $this->groups
|
||||
->map(fn (ResolvedValidityGroup $group): ?CarbonInterface => $group->effectiveExpiresAt($at))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
97
app/Domains/Ticket/Services/ResolvedValidityGroup.php
Normal file
97
app/Domains/Ticket/Services/ResolvedValidityGroup.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Representa una intersección de vigencias: todos los ValidityTime del grupo
|
||||
* deben cumplirse simultáneamente (AND).
|
||||
*
|
||||
* Ejemplo: [fecha del evento, horario de almuerzo] significa que el ticket
|
||||
* solamente es válido durante la intersección de ambas ventanas.
|
||||
*/
|
||||
final readonly class ResolvedValidityGroup
|
||||
{
|
||||
/** @param Collection<int, ValidityTime> $validityTimes */
|
||||
public function __construct(public Collection $validityTimes) {}
|
||||
|
||||
/** Comprueba si el instante pertenece a la intersección efectiva del grupo. */
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$startsAt = $this->effectiveStartsAt($at);
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $this->validityTimes->isNotEmpty()
|
||||
&& ($startsAt === null || $startsAt->lessThanOrEqualTo($at))
|
||||
&& ($expiresAt === null || $expiresAt->greaterThan($at));
|
||||
}
|
||||
|
||||
/** Un grupo vence cuando termina su intersección efectiva. */
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $expiresAt !== null && $expiresAt->lessThanOrEqualTo($at);
|
||||
}
|
||||
|
||||
/**
|
||||
* En un AND, la intersección comienza en el inicio más tardío.
|
||||
* Por ejemplo, fecha 00:00 + horario 12:00 comienza a las 12:00.
|
||||
*/
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->validityTimes
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->startsAt($anchor))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* En un AND, la intersección termina en el vencimiento más temprano.
|
||||
* Los horarios cuyo fin no supera al inicio se interpretan como nocturnos.
|
||||
*/
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->validityTimes
|
||||
->map(function (ValidityTime $validityTime) use ($anchor): ?CarbonInterface {
|
||||
$startsAt = $validityTime->startsAt($anchor);
|
||||
$expiresAt = $validityTime->expiresAt($anchor);
|
||||
|
||||
if ($startsAt !== null && $expiresAt !== null && $expiresAt->lessThanOrEqualTo($startsAt)) {
|
||||
return $expiresAt->addDay();
|
||||
}
|
||||
|
||||
return $expiresAt;
|
||||
})
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Usa la fecha de un fixed_window como ancla para convertir ventanas que
|
||||
* sólo contienen horas (time_window) en instantes concretos.
|
||||
*/
|
||||
private function dateAnchor(): ?CarbonInterface
|
||||
{
|
||||
return $this->validityTimes
|
||||
->filter(fn (ValidityTime $validityTime): bool => $validityTime->type === ValidityTimeType::FixedWindow)
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->fixed_starts_at)
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,8 @@ class ScannerTicketService
|
||||
private function relations(): array
|
||||
{
|
||||
return [
|
||||
'validityGroups.validityTimes',
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
'sourceCatalogItem.category',
|
||||
'sourceVariant.eventDate',
|
||||
'sourceVariant.catalogItem',
|
||||
|
||||
@@ -5,19 +5,16 @@ namespace App\Domains\Ticket\Services;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use App\Domains\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\TicketValidityGroup;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class TicketGeneratorService
|
||||
{
|
||||
public function __construct(private readonly TicketValidityResolver $validityResolver) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
@@ -45,19 +42,9 @@ class TicketGeneratorService
|
||||
): Ticket {
|
||||
$item = $target['catalog_item'];
|
||||
$variant = $target['variant'];
|
||||
$eventDate = $target['event_date'];
|
||||
$validityGroups = $this->buildTicketValidityGroups(
|
||||
$item,
|
||||
$variant,
|
||||
$eventDate,
|
||||
$this->resolveValidityTime($item, $variant),
|
||||
);
|
||||
|
||||
$ticket = Ticket::query()->create([
|
||||
'tenant_code' => $item->tenant_code,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'name' => $this->ticketName($item, $variant, $eventDate),
|
||||
'description' => (string) ($item->descripcion ?? ''),
|
||||
'source_purchase_id' => $sourcePurchaseId,
|
||||
'source_catalog_item_id' => $item->getKey(),
|
||||
'source_variant_id' => $variant?->getKey(),
|
||||
@@ -65,31 +52,12 @@ class TicketGeneratorService
|
||||
'user_id' => $user->getKey(),
|
||||
]);
|
||||
|
||||
$groups = $validityGroups->map(function (Collection $validityTimes) use ($ticket): TicketValidityGroup {
|
||||
$group = $ticket->validityGroups()->create();
|
||||
$group->validityTimes()->attach(
|
||||
$validityTimes
|
||||
->map(fn (ValidityTime $validityTime): int => $validityTime->getKey())
|
||||
->all()
|
||||
);
|
||||
$group->setRelation(
|
||||
'validityTimes',
|
||||
new EloquentCollection($validityTimes->all()),
|
||||
);
|
||||
|
||||
return $group;
|
||||
});
|
||||
|
||||
$ticket->setRelation('validityGroups', new EloquentCollection($groups->all()));
|
||||
|
||||
return $ticket;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null, event_date: EventDate|null}>
|
||||
*/
|
||||
/** @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> */
|
||||
private function resolveTargets(
|
||||
CatalogItem $catalogItem,
|
||||
int $quantity,
|
||||
@@ -126,9 +94,7 @@ class TicketGeneratorService
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null, event_date: EventDate|null}>
|
||||
*/
|
||||
/** @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> */
|
||||
private function targetsForVariant(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
@@ -138,36 +104,18 @@ class TicketGeneratorService
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => null,
|
||||
'event_date' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->loadMissing(['eventDates.validityTime', 'eventDate.validityTime']);
|
||||
$selectedEventDates = $variant->selectedEventDates();
|
||||
|
||||
if ($catalogItem->ticket_generation_policy === TicketGenerationPolicy::OnePerUnit) {
|
||||
$eventDate = $selectedEventDates->count() === 1
|
||||
? $selectedEventDates->first()
|
||||
: null;
|
||||
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
'event_date' => $eventDate,
|
||||
]);
|
||||
if (! $this->validityResolver->resolveVariant($variant)->isResolvable) {
|
||||
throw TicketGenerationException::invalidValidityConfiguration($catalogItem, $variant);
|
||||
}
|
||||
|
||||
$eventDates = $selectedEventDates->isEmpty()
|
||||
? collect([null])
|
||||
: $selectedEventDates;
|
||||
|
||||
return Collection::times($quantity)
|
||||
->flatMap(fn () => $eventDates->map(fn (?EventDate $eventDate): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
'event_date' => $eventDate,
|
||||
]))
|
||||
->values();
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveVariant(
|
||||
@@ -201,112 +149,5 @@ class TicketGeneratorService
|
||||
if (! $catalogItem->has_tickets) {
|
||||
throw TicketGenerationException::ticketsDisabled($catalogItem);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function resolveValidityTime(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
): ?ValidityTime {
|
||||
if ($catalogItem->validity_time_id !== null) {
|
||||
return $catalogItem->validityTime;
|
||||
}
|
||||
|
||||
if ($variant === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$variant->loadMissing('definitions.itemAttribute.attribute.options.validityTime');
|
||||
|
||||
$validityTimes = $variant->definitions
|
||||
->map(function ($definition): ?ValidityTime {
|
||||
$option = $definition->itemAttribute?->attribute?->options
|
||||
->firstWhere('value', $definition->value);
|
||||
|
||||
return $option?->validityTime;
|
||||
})
|
||||
->filter()
|
||||
->unique(fn (ValidityTime $validityTime): int => $validityTime->getKey())
|
||||
->values();
|
||||
|
||||
if ($validityTimes->count() > 1) {
|
||||
throw TicketGenerationException::ambiguousValidityTime($catalogItem);
|
||||
}
|
||||
|
||||
return $validityTimes->first();
|
||||
}
|
||||
|
||||
private function ticketName(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
?EventDate $eventDate,
|
||||
): string {
|
||||
if ($variant === null) {
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
$options = $variant->selectionOptions();
|
||||
|
||||
if ($eventDate !== null) {
|
||||
$options->put('event_date', [
|
||||
'value' => (string) $eventDate->getKey(),
|
||||
'label' => $eventDate->date->format('d/m/Y'),
|
||||
]);
|
||||
}
|
||||
|
||||
$properties = $options
|
||||
->flatMap(function (array $option): array {
|
||||
if (array_is_list($option)) {
|
||||
return collect($option)
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->all();
|
||||
}
|
||||
|
||||
$label = $option['label'] ?? null;
|
||||
|
||||
return is_string($label) && $label !== '' ? [$label] : [];
|
||||
})
|
||||
->values();
|
||||
|
||||
if ($properties->isEmpty()) {
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
return $catalogItem->nombre.' ('.$properties->implode(', ').')';
|
||||
}
|
||||
|
||||
/** @return Collection<int, Collection<int, ValidityTime>> */
|
||||
private function buildTicketValidityGroups(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
?EventDate $eventDate,
|
||||
?ValidityTime $validityTime,
|
||||
): Collection {
|
||||
$eventDates = collect([$eventDate]);
|
||||
|
||||
if (
|
||||
$catalogItem->ticket_generation_policy === TicketGenerationPolicy::OnePerUnit
|
||||
&& $variant !== null
|
||||
) {
|
||||
$variant->loadMissing(['eventDates.validityTime', 'eventDate.validityTime']);
|
||||
$selectedEventDates = $variant->selectedEventDates();
|
||||
|
||||
if ($selectedEventDates->isNotEmpty()) {
|
||||
$eventDates = $selectedEventDates;
|
||||
}
|
||||
}
|
||||
|
||||
return $eventDates
|
||||
->map(function (?EventDate $date) use ($validityTime): Collection {
|
||||
$date?->loadMissing('validityTime');
|
||||
|
||||
return collect([$date?->validityTime, $validityTime])
|
||||
->filter()
|
||||
->unique(fn (ValidityTime $time): int => $time->getKey())
|
||||
->values();
|
||||
})
|
||||
->filter(fn (Collection $group): bool => $group->isNotEmpty())
|
||||
->values();
|
||||
}
|
||||
}
|
||||
|
||||
60
app/Domains/Ticket/Services/TicketPresentationResolver.php
Normal file
60
app/Domains/Ticket/Services/TicketPresentationResolver.php
Normal file
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
|
||||
class TicketPresentationResolver
|
||||
{
|
||||
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceCatalogItem',
|
||||
'sourceVariant.catalogItem.itemAttributes.attribute.options',
|
||||
'sourceVariant.definitions.itemAttribute.attribute.options',
|
||||
'sourceVariant.eventDates',
|
||||
'sourceVariant.eventDate',
|
||||
];
|
||||
|
||||
public function name(Ticket $ticket): string
|
||||
{
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
$catalogItem = $ticket->sourceCatalogItem;
|
||||
|
||||
if ($catalogItem === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$variant = $ticket->sourceVariant;
|
||||
if ($variant === null) {
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
$properties = $variant->selectionOptions()
|
||||
->flatMap(function (array $option): array {
|
||||
if (array_is_list($option)) {
|
||||
return collect($option)
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->all();
|
||||
}
|
||||
|
||||
$label = $option['label'] ?? null;
|
||||
|
||||
return is_string($label) && $label !== '' ? [$label] : [];
|
||||
})
|
||||
->values();
|
||||
|
||||
return $properties->isEmpty()
|
||||
? $catalogItem->nombre
|
||||
: $catalogItem->nombre.' ('.$properties->implode(', ').')';
|
||||
}
|
||||
|
||||
public function description(Ticket $ticket): string
|
||||
{
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
|
||||
return (string) ($ticket->sourceVariant?->getDescription()
|
||||
?? $ticket->sourceCatalogItem?->descripcion
|
||||
?? '');
|
||||
}
|
||||
}
|
||||
134
app/Domains/Ticket/Services/TicketValidityResolver.php
Normal file
134
app/Domains/Ticket/Services/TicketValidityResolver.php
Normal file
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Models\VariantDefinition;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Deriva la expresión temporal de un ticket desde su variante.
|
||||
*
|
||||
* Las selecciones alternativas de una misma dimensión (varias fechas u opciones
|
||||
* multiselección) se interpretan como OR. Las dimensiones diferentes se combinan
|
||||
* mediante AND usando un producto cartesiano.
|
||||
*/
|
||||
class TicketValidityResolver
|
||||
{
|
||||
/** Relaciones necesarias para resolver tickets sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceVariant.eventDates.validityTime',
|
||||
'sourceVariant.eventDate.validityTime',
|
||||
'sourceVariant.definitions.itemAttribute.attribute.options.validityTime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Resuelve la variante fuente del ticket. Un ticket creado legítimamente sin
|
||||
* variante es irrestricto; una referencia esperada pero rota es irresoluble.
|
||||
*/
|
||||
public function resolveTicket(Ticket $ticket): ResolvedTicketValidity
|
||||
{
|
||||
if ($ticket->source_variant_id === null) {
|
||||
return ResolvedTicketValidity::unrestricted();
|
||||
}
|
||||
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
|
||||
if ($ticket->sourceVariant === null) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
return $this->resolveVariant($ticket->sourceVariant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convierte las fechas y definiciones temporales de la variante en grupos
|
||||
* normalizados: AND dentro de cada grupo y OR entre grupos.
|
||||
*/
|
||||
public function resolveVariant(Variant $variant): ResolvedTicketValidity
|
||||
{
|
||||
$variant->loadMissing([
|
||||
'eventDates.validityTime',
|
||||
'eventDate.validityTime',
|
||||
'definitions.itemAttribute.attribute.options.validityTime',
|
||||
]);
|
||||
|
||||
$dimensions = collect();
|
||||
$eventDates = $variant->selectedEventDates();
|
||||
|
||||
if ($eventDates->contains(fn ($eventDate): bool => $eventDate->validityTime === null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if ($eventDates->isNotEmpty()) {
|
||||
// Todas las fechas pertenecen a una misma dimensión alternativa:
|
||||
// fecha 1 OR fecha 2 OR fecha 3.
|
||||
$dimensions->push(
|
||||
$eventDates->map(fn ($eventDate): Collection => collect([$eventDate->validityTime]))
|
||||
);
|
||||
}
|
||||
|
||||
foreach ($variant->definitions->groupBy('item_attribute_id') as $definitions) {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attribute = $itemAttribute?->attribute;
|
||||
|
||||
if ($itemAttribute === null || $attribute === null) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if (! $attribute->type->supportsOptions() || $attribute->type->usesDynamicOptions()) {
|
||||
// Texto, números y demás atributos no temporales no restringen
|
||||
// la vigencia. EventDate se procesó arriba mediante su relación.
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $itemAttribute->allow_multi_select && $definitions->count() > 1) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
$alternatives = $definitions->map(function (VariantDefinition $definition) use ($attribute): ?Collection {
|
||||
$option = $attribute->options->firstWhere('value', $definition->value);
|
||||
|
||||
if ($option === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collect([$option->validityTime])->filter()->values();
|
||||
});
|
||||
|
||||
if ($alternatives->contains(null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if ($alternatives->contains(fn (Collection $alternative): bool => $alternative->isNotEmpty())) {
|
||||
// Las opciones elegidas del mismo atributo son alternativas OR.
|
||||
$dimensions->push($alternatives->values());
|
||||
}
|
||||
}
|
||||
|
||||
if ($dimensions->isEmpty()) {
|
||||
return ResolvedTicketValidity::unrestricted();
|
||||
}
|
||||
|
||||
$groups = collect([collect()]);
|
||||
|
||||
foreach ($dimensions as $alternatives) {
|
||||
// El producto cartesiano agrega cada dimensión como una condición
|
||||
// AND y conserva sus opciones internas como alternativas OR.
|
||||
$groups = $groups->flatMap(
|
||||
fn (Collection $group): Collection => $alternatives->map(
|
||||
fn (Collection $alternative): Collection => $group
|
||||
->merge($alternative)
|
||||
->unique(fn (ValidityTime $time): int => $time->getKey() ?? spl_object_id($time))
|
||||
->values()
|
||||
)
|
||||
)->values();
|
||||
}
|
||||
|
||||
return new ResolvedTicketValidity(
|
||||
$groups->map(fn (Collection $times): ResolvedValidityGroup => new ResolvedValidityGroup($times))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,15 @@ Genera, valida, consulta y exporta entradas asociadas a compras pagadas de produ
|
||||
|
||||
## Modelo
|
||||
|
||||
- `Ticket`: pertenece a tenant y usuario, conserva referencias a compra, producto, variante, validez y usuario escáner.
|
||||
- `ValidityTime`: define ventanas absolutas o relativas de vigencia para productos, opciones y tickets.
|
||||
- `Ticket`: pertenece a tenant y usuario, y conserva referencias a compra, producto, variante y usuario escáner.
|
||||
- El nombre y la descripción se calculan dinámicamente desde el producto y la variante; los tickets no
|
||||
persisten una copia de esos textos.
|
||||
- `ValidityTime`: define ventanas absolutas o relativas de vigencia para fechas de evento y opciones de atributos.
|
||||
- `ValidityTimeType`: enum de estrategias de vigencia.
|
||||
|
||||
El modelo calcula si un ticket está vigente, vencido o usado, y resuelve sus fechas efectivas de inicio y fin.
|
||||
`TicketValidityResolver` deriva la vigencia desde la variante asociada. Las alternativas de un mismo atributo
|
||||
se combinan con OR y las dimensiones diferentes se combinan con AND. El modelo calcula si un ticket está
|
||||
vigente, vencido o usado, y resuelve sus fechas efectivas de inicio y fin sin persistir vigencias en el ticket.
|
||||
|
||||
## Flujo de generación
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"keywords": ["laravel", "framework"],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"ext-gd": "*",
|
||||
"php": "^8.3",
|
||||
"barryvdh/laravel-dompdf": "^3.1",
|
||||
"endroid/qr-code": "^6.1",
|
||||
|
||||
3
composer.lock
generated
3
composer.lock
generated
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "aa7e98d017dd610946c62579b20c501f",
|
||||
"content-hash": "ce185c60c617846be30ae694f0cf6e9c",
|
||||
"packages": [
|
||||
{
|
||||
"name": "aws/aws-crt-php",
|
||||
@@ -9838,6 +9838,7 @@
|
||||
"prefer-stable": true,
|
||||
"prefer-lowest": false,
|
||||
"platform": {
|
||||
"ext-gd": "*",
|
||||
"php": "^8.3"
|
||||
},
|
||||
"platform-dev": {},
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -11,15 +10,15 @@ return new class extends Migration
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('catalog_items', function (Blueprint $table): void {
|
||||
$table->enum('ticket_generation_policy', TicketGenerationPolicy::values())
|
||||
->default(TicketGenerationPolicy::PerEventDate->value)
|
||||
$table->enum('ticket_generation_policy', ['per_event_date', 'one_per_unit'])
|
||||
->default('per_event_date')
|
||||
->after('has_tickets');
|
||||
});
|
||||
|
||||
DB::table('catalog_items')
|
||||
->where('tenant_code', 'fiesta_futbol_infantil')
|
||||
->update([
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'ticket_generation_policy' => 'one_per_unit',
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?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
|
||||
{
|
||||
DB::table('catalog_items')
|
||||
->join('event_dates', function ($join): void {
|
||||
$join->on('event_dates.tenant_code', '=', 'catalog_items.tenant_code')
|
||||
->on('event_dates.validity_time_id', '=', 'catalog_items.validity_time_id');
|
||||
})
|
||||
->whereNotNull('catalog_items.validity_time_id')
|
||||
->select([
|
||||
'catalog_items.id as catalog_item_id',
|
||||
'event_dates.id as event_date_id',
|
||||
])
|
||||
->orderBy('catalog_items.id')
|
||||
->orderBy('event_dates.id')
|
||||
->each(function (object $association): void {
|
||||
$variantIds = DB::table('variantes')
|
||||
->where('catalog_item_id', $association->catalog_item_id)
|
||||
->pluck('id');
|
||||
|
||||
if ($variantIds->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('variantes')
|
||||
->whereIn('id', $variantIds)
|
||||
->whereNull('event_date_id')
|
||||
->update(['event_date_id' => $association->event_date_id]);
|
||||
|
||||
DB::table('variant_event_dates')->insertOrIgnore(
|
||||
$variantIds->map(fn (int $variantId): array => [
|
||||
'variant_id' => $variantId,
|
||||
'event_date_id' => $association->event_date_id,
|
||||
])->all()
|
||||
);
|
||||
});
|
||||
|
||||
Schema::table('catalog_items', function (Blueprint $table): void {
|
||||
if (DB::getDriverName() !== 'sqlite') {
|
||||
$table->dropForeign(['validity_time_id']);
|
||||
}
|
||||
|
||||
$table->dropColumn('validity_time_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('catalog_items', function (Blueprint $table): void {
|
||||
$table->foreignId('validity_time_id')
|
||||
->nullable()
|
||||
->after('has_tickets')
|
||||
->constrained('validity_times')
|
||||
->cascadeOnUpdate()
|
||||
->nullOnDelete();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
<?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::dropIfExists('ticket_validity_group_times');
|
||||
Schema::dropIfExists('ticket_validity_groups');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::create('ticket_validity_groups', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('ticket_id')
|
||||
->constrained('tickets')
|
||||
->cascadeOnUpdate()
|
||||
->cascadeOnDelete();
|
||||
});
|
||||
|
||||
Schema::create('ticket_validity_group_times', function (Blueprint $table): void {
|
||||
$table->foreignId('ticket_validity_group_id')
|
||||
->constrained('ticket_validity_groups')
|
||||
->cascadeOnUpdate()
|
||||
->cascadeOnDelete();
|
||||
$table->foreignId('validity_time_id')
|
||||
->constrained('validity_times')
|
||||
->cascadeOnUpdate()
|
||||
->restrictOnDelete();
|
||||
$table->primary(['ticket_validity_group_id', 'validity_time_id']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
<?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 (DB::getDriverName() === 'sqlite') {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->dropForeign(['source_catalog_item_id']);
|
||||
$table->dropForeign(['source_variant_id']);
|
||||
|
||||
$table->foreign('source_catalog_item_id')
|
||||
->references('id')
|
||||
->on('catalog_items')
|
||||
->cascadeOnUpdate()
|
||||
->restrictOnDelete();
|
||||
$table->foreign('source_variant_id')
|
||||
->references('id')
|
||||
->on('variantes')
|
||||
->cascadeOnUpdate()
|
||||
->restrictOnDelete();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::getDriverName() === 'sqlite') {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->dropForeign(['source_catalog_item_id']);
|
||||
$table->dropForeign(['source_variant_id']);
|
||||
|
||||
$table->foreign('source_catalog_item_id')
|
||||
->references('id')
|
||||
->on('catalog_items')
|
||||
->cascadeOnUpdate()
|
||||
->nullOnDelete();
|
||||
$table->foreign('source_variant_id')
|
||||
->references('id')
|
||||
->on('variantes')
|
||||
->cascadeOnUpdate()
|
||||
->nullOnDelete();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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', function (Blueprint $table): void {
|
||||
$table->dropColumn('ticket_generation_policy');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('catalog_items', function (Blueprint $table): void {
|
||||
$table->enum('ticket_generation_policy', ['one_per_unit'])
|
||||
->default('one_per_unit')
|
||||
->after('has_tickets');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<?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
|
||||
{
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->string('name')->nullable()->change();
|
||||
$table->text('description')->nullable()->change();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('tickets')->whereNull('name')->update(['name' => '']);
|
||||
DB::table('tickets')->whereNull('description')->update(['description' => '']);
|
||||
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->string('name')->nullable(false)->change();
|
||||
$table->text('description')->nullable(false)->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?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', function (Blueprint $table): void {
|
||||
$table->softDeletes();
|
||||
});
|
||||
|
||||
Schema::table('variantes', function (Blueprint $table): void {
|
||||
$table->softDeletes();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('variantes', function (Blueprint $table): void {
|
||||
$table->dropSoftDeletes();
|
||||
});
|
||||
|
||||
Schema::table('catalog_items', function (Blueprint $table): void {
|
||||
$table->dropSoftDeletes();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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),
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -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),
|
||||
));
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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',
|
||||
]);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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)]);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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');
|
||||
}
|
||||
};
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Seeder;
|
||||
@@ -155,6 +154,7 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
|
||||
CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->orderByRaw("CASE WHEN type = 'bundle' THEN 0 ELSE 1 END")
|
||||
->orderBy('id')
|
||||
->each(fn (CatalogItem $item) => $this->catalogService->delete($item));
|
||||
}
|
||||
|
||||
@@ -167,7 +167,6 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
...$data,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -241,14 +241,17 @@ class MenuSeeder extends Seeder
|
||||
|
||||
Role::query()
|
||||
->whereIn('codigo', [RoleCode::Admin->value, RoleCode::AdminApp->value])
|
||||
->orderBy('codigo')
|
||||
->each(fn (Role $role) => $role->menus()->sync($allRoleMenuCodes));
|
||||
|
||||
Role::query()
|
||||
->where('codigo', RoleCode::User->value)
|
||||
->orderBy('codigo')
|
||||
->each(fn (Role $role) => $role->menus()->sync($userMenuCodes));
|
||||
|
||||
Role::query()
|
||||
->where('codigo', RoleCode::Scanner->value)
|
||||
->orderBy('codigo')
|
||||
->each(fn (Role $role) => $role->menus()->sync($scannerMenuCodes));
|
||||
|
||||
$tenants = Tenant::all();
|
||||
|
||||
@@ -86,7 +86,7 @@ class WebsiteTypeSeeder extends Seeder
|
||||
'description_html' => 'nullable|string',
|
||||
'button_text' => 'nullable|string',
|
||||
'button_href' => 'nullable|string',
|
||||
'background_image_id' => 'nullable|image_or_base64',
|
||||
'background_image_id' => 'nullable|cropped_image_or_base64',
|
||||
],
|
||||
'transforms' => [
|
||||
'background_image_id' => [
|
||||
|
||||
@@ -7,12 +7,12 @@ require __DIR__.'/../app/Domains/StorageTest/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/MailTest/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Purchase/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Sale/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Bootstrap/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Integration/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Menu/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Ticket/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Event/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Bootstrap/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Forms/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/Staff/routes/api.php';
|
||||
require __DIR__.'/../app/Domains/FiestaFutbolInfantil/routes/api.php';
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Tests\Feature\Attachable;
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
@@ -70,6 +71,163 @@ class AttachmentTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_it_stores_an_original_image_and_its_crop(): void
|
||||
{
|
||||
Storage::fake('s3');
|
||||
|
||||
$original = app(AttachmentService::class)->storeCroppedImageVariants(
|
||||
UploadedFile::fake()->image('product.jpg', 200, 100),
|
||||
'attachments/acme',
|
||||
[
|
||||
'desktop' => [
|
||||
'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
|
||||
'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
|
||||
],
|
||||
'mobile' => [
|
||||
'crop_horizontal' => ['start_percentage' => 20, 'end_percentage' => 80],
|
||||
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
$desktopCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
|
||||
$mobileCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::MOBILE);
|
||||
$cropped = $desktopCrop->croppedAttachment;
|
||||
|
||||
$this->assertNotNull($cropped);
|
||||
$this->assertEquals(
|
||||
['start_percentage' => 25.0, 'end_percentage' => 75.0],
|
||||
$desktopCrop->crop_horizontal,
|
||||
);
|
||||
$this->assertEquals(
|
||||
['start_percentage' => 10.0, 'end_percentage' => 85.0],
|
||||
$desktopCrop->crop_vertical,
|
||||
);
|
||||
$this->assertTrue($cropped->cropSource->attachment->is($original));
|
||||
$this->assertDatabaseCount('attachments', 3);
|
||||
$this->assertDatabaseCount('attachment_crops', 2);
|
||||
$this->assertDatabaseHas('attachment_crops', [
|
||||
'attachment_id' => $original->id,
|
||||
'variant' => AttachmentCrop::DESKTOP,
|
||||
'cropped_attachment_id' => $cropped->id,
|
||||
]);
|
||||
Storage::disk('s3')->assertExists($original->path);
|
||||
Storage::disk('s3')->assertExists($cropped->path);
|
||||
Storage::disk('s3')->assertExists($mobileCrop->croppedAttachment->path);
|
||||
|
||||
$croppedSize = getimagesizefromstring(Storage::disk('s3')->get($cropped->path));
|
||||
|
||||
$this->assertIsArray($croppedSize);
|
||||
$this->assertSame(100, $croppedSize[0]);
|
||||
$this->assertSame(75, $croppedSize[1]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_invalid_crop_percentages_without_storing_files(): void
|
||||
{
|
||||
Storage::fake('s3');
|
||||
|
||||
try {
|
||||
app(AttachmentService::class)->storeCroppedImageVariants(
|
||||
UploadedFile::fake()->image('product.png'),
|
||||
'attachments/acme',
|
||||
[
|
||||
'desktop' => [
|
||||
'crop_horizontal' => ['start_percentage' => 75, 'end_percentage' => 25],
|
||||
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
],
|
||||
'mobile' => [
|
||||
'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
$this->fail('Expected an AttachmentStorageException to be thrown.');
|
||||
} catch (AttachmentStorageException) {
|
||||
$this->assertDatabaseCount('attachments', 0);
|
||||
$this->assertSame([], Storage::disk('s3')->allFiles());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_it_rolls_back_the_original_when_the_file_is_not_a_valid_image(): void
|
||||
{
|
||||
Storage::fake('s3');
|
||||
|
||||
try {
|
||||
app(AttachmentService::class)->storeCroppedImageVariants(
|
||||
UploadedFile::fake()->createWithContent('invalid.png', 'not-an-image'),
|
||||
'attachments/acme',
|
||||
$this->fullCropVariants(),
|
||||
);
|
||||
|
||||
$this->fail('Expected an AttachmentStorageException to be thrown.');
|
||||
} catch (AttachmentStorageException) {
|
||||
$this->assertDatabaseCount('attachments', 0);
|
||||
$this->assertSame([], Storage::disk('s3')->allFiles());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_it_deletes_the_crop_together_with_its_original(): void
|
||||
{
|
||||
Storage::fake('s3');
|
||||
|
||||
$original = app(AttachmentService::class)->storeCroppedImageVariants(
|
||||
UploadedFile::fake()->image('product.png'),
|
||||
'attachments/acme',
|
||||
$this->fullCropVariants(),
|
||||
);
|
||||
$cropped = $original->cropVariants->pluck('croppedAttachment');
|
||||
|
||||
app(AttachmentService::class)->delete($original);
|
||||
|
||||
$this->assertDatabaseCount('attachments', 0);
|
||||
Storage::disk('s3')->assertMissing($original->path);
|
||||
foreach ($cropped as $variant) {
|
||||
Storage::disk('s3')->assertMissing($variant->path);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_it_replaces_the_crop_of_an_existing_image(): void
|
||||
{
|
||||
Storage::fake('s3');
|
||||
|
||||
$original = app(AttachmentService::class)->storeCroppedImageVariants(
|
||||
UploadedFile::fake()->image('product.jpg', 200, 100),
|
||||
'attachments/acme',
|
||||
$this->fullCropVariants(),
|
||||
);
|
||||
$previousCrops = $original->cropVariants->pluck('croppedAttachment');
|
||||
|
||||
$updated = app(AttachmentService::class)->updateImageCropVariants(
|
||||
$original,
|
||||
[
|
||||
'desktop' => [
|
||||
'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
|
||||
'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
|
||||
],
|
||||
'mobile' => [
|
||||
'crop_horizontal' => ['start_percentage' => 30, 'end_percentage' => 70],
|
||||
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
foreach ($previousCrops as $previousCrop) {
|
||||
$this->assertDatabaseMissing('attachments', ['id' => $previousCrop->id]);
|
||||
Storage::disk('s3')->assertMissing($previousCrop->path);
|
||||
}
|
||||
|
||||
$desktop = $updated->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
|
||||
|
||||
$croppedSize = getimagesizefromstring(
|
||||
Storage::disk('s3')->get($desktop->croppedAttachment->path)
|
||||
);
|
||||
|
||||
$this->assertIsArray($croppedSize);
|
||||
$this->assertSame(100, $croppedSize[0]);
|
||||
$this->assertSame(75, $croppedSize[1]);
|
||||
}
|
||||
|
||||
public function test_it_deletes_from_s3_before_removing_the_database_record(): void
|
||||
{
|
||||
Storage::fake('s3');
|
||||
@@ -126,4 +284,14 @@ class AttachmentTest extends TestCase
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function fullCropVariants(): array
|
||||
{
|
||||
$crop = [
|
||||
'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
|
||||
];
|
||||
|
||||
return ['desktop' => $crop, 'mobile' => $crop];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,9 +49,12 @@ class CartControllerTest extends TestCase
|
||||
->assertCookie('guest_token')
|
||||
->assertJsonPath('data.items.0.catalog_item_id', $item->id)
|
||||
->assertJsonPath('data.items.0.variant_id', null)
|
||||
->assertJsonPath('data.items.0.variant', null)
|
||||
->assertJsonPath('data.items.0.cantidad', 2)
|
||||
->assertJsonPath('data.items.0.precio_unitario', '49.90')
|
||||
->assertJsonPath('data.items.0.product.nombre', 'Item acme')
|
||||
->assertJsonPath('data.items.0.nombre', 'Item acme')
|
||||
->assertJsonPath('data.items.0.imagen', null)
|
||||
->assertJsonMissingPath('data.items.0.product')
|
||||
->assertJsonPath('data.subtotal', '99.80');
|
||||
|
||||
$guestTokenCookie = $response->getCookie('guest_token', false);
|
||||
@@ -276,11 +279,6 @@ class CartControllerTest extends TestCase
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '20.00',
|
||||
]);
|
||||
$unavailableInventory = Inventory::query()->create(['real_stock' => 0]);
|
||||
$unavailableVariant = $item->variants()->create([
|
||||
'inventory_id' => $unavailableInventory->id,
|
||||
'precio' => '25.00',
|
||||
]);
|
||||
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'catalog_item_id' => $item->id,
|
||||
'variant_id' => $firstVariant->id,
|
||||
@@ -301,11 +299,10 @@ class CartControllerTest extends TestCase
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.variant_id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.precio_unitario', '20.00')
|
||||
->assertJsonCount(2, 'data.items.0.product.variants')
|
||||
->assertJsonPath('data.items.0.product.variants.0.id', $firstVariant->id)
|
||||
->assertJsonPath('data.items.0.product.variants.1.id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.product.variants.1.stock_tecnico', 0)
|
||||
->assertJsonMissing(['id' => $unavailableVariant->id, 'stock_tecnico' => 0]);
|
||||
->assertJsonPath('data.items.0.variant.id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.variant.precio', '20.00')
|
||||
->assertJsonPath('data.items.0.variant.stock_tecnico', 0)
|
||||
->assertJsonMissingPath('data.items.0.product');
|
||||
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
|
||||
@@ -287,7 +287,7 @@ class BundleCatalogItemTest extends TestCase
|
||||
->assertJsonValidationErrors(['real_stock']);
|
||||
}
|
||||
|
||||
public function test_bundle_components_are_deleted_with_the_bundle(): void
|
||||
public function test_bundle_components_are_preserved_when_the_bundle_is_soft_deleted(): void
|
||||
{
|
||||
$component = $this->createStandardItem('deletion-component', 5);
|
||||
$bundle = $this->createBundle('deletable-bundle', [
|
||||
@@ -295,8 +295,8 @@ class BundleCatalogItemTest extends TestCase
|
||||
]);
|
||||
$this->catalogService->delete($bundle);
|
||||
|
||||
$this->assertDatabaseMissing('catalog_items', ['id' => $bundle->id]);
|
||||
$this->assertDatabaseMissing('bundle_components', [
|
||||
$this->assertSoftDeleted('catalog_items', ['id' => $bundle->id]);
|
||||
$this->assertDatabaseHas('bundle_components', [
|
||||
'bundle_catalog_item_id' => $bundle->id,
|
||||
]);
|
||||
$this->assertDatabaseHas('catalog_items', ['id' => $component->id]);
|
||||
|
||||
@@ -264,7 +264,8 @@ class CatalogControllerTest extends TestCase
|
||||
->assertJsonPath('0.layout', ProductLayout::TicketSelector->value)
|
||||
->assertJsonPath('0.group_layout', GroupLayout::Single->value)
|
||||
->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
|
||||
|
||||
@@ -62,6 +62,7 @@ class CatalogItemControllerTest extends TestCase
|
||||
'catalog_item_id' => $item->id,
|
||||
'variant_id' => $variant->id,
|
||||
'orden' => 0,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace Tests\Feature\Catalog;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
@@ -296,6 +298,122 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
->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(
|
||||
Tenant $tenant,
|
||||
string $name,
|
||||
|
||||
@@ -33,7 +33,6 @@ class CatalogSchemaTest extends TestCase
|
||||
{
|
||||
$this->assertEqualsCanonicalizing([
|
||||
'id',
|
||||
'validity_time_id',
|
||||
'tenant_code',
|
||||
'category_id',
|
||||
'brand_id',
|
||||
@@ -46,7 +45,6 @@ class CatalogSchemaTest extends TestCase
|
||||
'inventory_policy',
|
||||
'max_units_per_user',
|
||||
'has_tickets',
|
||||
'ticket_generation_policy',
|
||||
'validity_time_id',
|
||||
], Schema::getColumnListing('catalog_items'));
|
||||
}
|
||||
@@ -106,6 +104,7 @@ class CatalogSchemaTest extends TestCase
|
||||
'catalog_item_id',
|
||||
'attachment_id',
|
||||
'orden',
|
||||
'is_enabled',
|
||||
], Schema::getColumnListing('catalog_items_attachments'));
|
||||
}
|
||||
|
||||
@@ -172,12 +171,14 @@ class CatalogSchemaTest extends TestCase
|
||||
'variant_id' => null,
|
||||
'attachment_id' => $itemAttachment->id,
|
||||
'orden' => 2,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
$this->assertDatabaseHas('catalog_items_attachments', [
|
||||
'catalog_item_id' => $item->id,
|
||||
'variant_id' => $variant->id,
|
||||
'attachment_id' => $variantAttachment->id,
|
||||
'orden' => 3,
|
||||
'is_enabled' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,10 @@ class CatalogSearchTest extends TestCase
|
||||
->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value)
|
||||
->assertJsonPath('data.search_items_per_page', 24);
|
||||
|
||||
$this->getJson("/api/tenants/bootstrap/{$tenant->dominio}")
|
||||
$this->getJson('/api/tenants/bootstrap?'.http_build_query([
|
||||
'dominio' => $tenant->dominio,
|
||||
'path' => '/',
|
||||
]))
|
||||
->assertOk()
|
||||
->assertJsonPath('data.search_product_layout', ProductLayout::Row->value)
|
||||
->assertJsonPath('data.search_group_layout', GroupLayout::SimpleVertical->value)
|
||||
|
||||
@@ -93,6 +93,89 @@ class CatalogServiceTest extends TestCase
|
||||
}
|
||||
}
|
||||
|
||||
public function test_it_soft_deletes_an_item_and_its_variants_without_removing_their_sources(): void
|
||||
{
|
||||
$attribute = $this->createAttribute('size');
|
||||
$item = $this->service->create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'slug' => 'archived-item',
|
||||
'nombre' => 'Archived item',
|
||||
'precio' => 100,
|
||||
'attribute_codes' => [$attribute->codigo],
|
||||
'variants' => [[
|
||||
'real_stock' => 5,
|
||||
'values' => [$attribute->codigo => 'M'],
|
||||
]],
|
||||
]);
|
||||
$variant = $item->variants->sole();
|
||||
|
||||
$this->service->delete($item);
|
||||
|
||||
$this->assertSoftDeleted('catalog_items', ['id' => $item->id]);
|
||||
$this->assertSoftDeleted('variantes', ['id' => $variant->id]);
|
||||
$this->assertDatabaseHas('inventories', ['id' => $variant->inventory_id]);
|
||||
$this->assertDatabaseHas('variant_values', [
|
||||
'variant_id' => $variant->id,
|
||||
'value' => 'M',
|
||||
]);
|
||||
$this->assertNull(CatalogItem::query()->find($item->id));
|
||||
$this->assertNull(Variant::query()->find($variant->id));
|
||||
$this->assertNotNull(CatalogItem::withTrashed()->find($item->id));
|
||||
$this->assertNotNull(Variant::withTrashed()->find($variant->id));
|
||||
}
|
||||
|
||||
public function test_deleting_the_last_variant_soft_deletes_its_catalog_item(): void
|
||||
{
|
||||
$attribute = $this->createAttribute('size');
|
||||
$item = $this->service->create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'slug' => 'last-variant',
|
||||
'nombre' => 'Last variant',
|
||||
'precio' => 100,
|
||||
'attribute_codes' => [$attribute->codigo],
|
||||
'variants' => [[
|
||||
'real_stock' => 5,
|
||||
'values' => [$attribute->codigo => 'M'],
|
||||
]],
|
||||
]);
|
||||
$variant = $item->variants->sole();
|
||||
|
||||
$this->service->deleteVariant($variant);
|
||||
|
||||
$this->assertSoftDeleted('variantes', ['id' => $variant->id]);
|
||||
$this->assertSoftDeleted('catalog_items', ['id' => $item->id]);
|
||||
$this->assertDatabaseHas('inventories', ['id' => $variant->inventory_id]);
|
||||
}
|
||||
|
||||
public function test_deleting_a_variant_keeps_the_item_active_when_an_inherited_price_variant_remains(): void
|
||||
{
|
||||
$attribute = $this->createAttribute('size');
|
||||
$item = $this->service->create([
|
||||
'tenant_code' => $this->tenant->codigo,
|
||||
'slug' => 'remaining-variant',
|
||||
'nombre' => 'Remaining variant',
|
||||
'precio' => 100,
|
||||
'attribute_codes' => [$attribute->codigo],
|
||||
'variants' => [
|
||||
[
|
||||
'real_stock' => 5,
|
||||
'values' => [$attribute->codigo => 'M'],
|
||||
],
|
||||
[
|
||||
'real_stock' => 5,
|
||||
'values' => [$attribute->codigo => 'L'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$deletedVariant = $item->variants->first();
|
||||
|
||||
$this->service->deleteVariant($deletedVariant);
|
||||
|
||||
$this->assertSoftDeleted('variantes', ['id' => $deletedVariant->id]);
|
||||
$this->assertFalse($item->fresh()->trashed());
|
||||
$this->assertSame(1, $item->variants()->count());
|
||||
}
|
||||
|
||||
public function test_it_can_hide_an_item_attribute_from_the_product_selector(): void
|
||||
{
|
||||
$attribute = $this->createAttribute('internal_type');
|
||||
|
||||
280
tests/Feature/Desfile/EntryControllerTest.php
Normal file
280
tests/Feature/Desfile/EntryControllerTest.php
Normal 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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -141,9 +142,10 @@ class AccommodationControllerTest extends TestCase
|
||||
$this->deleteJson("/api/v1/adminapp/tenant/accommodations/{$accommodationId}")
|
||||
->assertNoContent();
|
||||
|
||||
$this->assertDatabaseCount('catalog_items', 0);
|
||||
$this->assertDatabaseCount('variantes', 0);
|
||||
$this->assertDatabaseCount('inventories', 0);
|
||||
$this->assertSame(0, CatalogItem::query()->count());
|
||||
$this->assertSoftDeleted('variantes', ['id' => $accommodationId]);
|
||||
$this->assertSame(0, Variant::query()->count());
|
||||
$this->assertDatabaseCount('inventories', 1);
|
||||
}
|
||||
|
||||
public function test_it_rejects_duplicate_normalized_titles(): void
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -97,7 +98,7 @@ class EntryControllerTest extends TestCase
|
||||
->where('nombre', 'Entradas')
|
||||
->sole();
|
||||
|
||||
CatalogItem::query()->each(function (CatalogItem $entry) use ($tenant, $entryCategory): void {
|
||||
CatalogItem::query()->orderBy('id')->each(function (CatalogItem $entry) use ($tenant, $entryCategory): void {
|
||||
$this->assertSame($tenant->codigo, $entry->tenant_code);
|
||||
$this->assertSame($entryCategory->id, $entry->category_id);
|
||||
$this->assertSame('tracked', $entry->inventory_policy->value);
|
||||
@@ -191,9 +192,10 @@ class EntryControllerTest extends TestCase
|
||||
$this->deleteJson("/api/v1/adminapp/tenant/entries/{$entryId}")
|
||||
->assertNoContent();
|
||||
|
||||
$this->assertDatabaseCount('catalog_items', 0);
|
||||
$this->assertDatabaseCount('variantes', 0);
|
||||
$this->assertDatabaseCount('inventories', 0);
|
||||
$this->assertSoftDeleted('catalog_items', ['id' => $entryId]);
|
||||
$this->assertSame(0, CatalogItem::query()->count());
|
||||
$this->assertSame(0, Variant::query()->count());
|
||||
$this->assertDatabaseCount('inventories', 1);
|
||||
}
|
||||
|
||||
public function test_dates_must_belong_to_the_authenticated_tenant(): void
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -163,15 +164,17 @@ class FoodControllerTest extends TestCase
|
||||
'slug' => 'comida',
|
||||
'precio' => 10000,
|
||||
]);
|
||||
$this->assertDatabaseCount('variantes', 1);
|
||||
$this->assertDatabaseCount('inventories', 1);
|
||||
$this->assertSoftDeleted('variantes', ['id' => $secondId]);
|
||||
$this->assertSame(1, Variant::query()->count());
|
||||
$this->assertDatabaseCount('inventories', 2);
|
||||
|
||||
$this->deleteJson("/api/v1/adminapp/tenant/foods/{$firstId}")
|
||||
->assertNoContent();
|
||||
|
||||
$this->assertDatabaseCount('catalog_items', 0);
|
||||
$this->assertDatabaseCount('variantes', 0);
|
||||
$this->assertDatabaseCount('inventories', 0);
|
||||
$this->assertSoftDeleted('variantes', ['id' => $firstId]);
|
||||
$this->assertSame(0, CatalogItem::query()->count());
|
||||
$this->assertSame(0, Variant::query()->count());
|
||||
$this->assertDatabaseCount('inventories', 2);
|
||||
}
|
||||
|
||||
public function test_it_rejects_duplicate_combinations(): void
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user