Compare commits

..

No commits in common. "dev" and "feature/scanners" have entirely different histories.

417 changed files with 4031 additions and 26888 deletions

View File

@ -8,8 +8,6 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
PURCHASE_QR_EXPIRATION_MINUTES=15 PURCHASE_QR_EXPIRATION_MINUTES=15
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30 PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440 PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
PURCHASE_TRANSFER_CANDIDATE_AMOUNT_TOLERANCE_PERCENTAGE=5
STOCK_RESERVATION_EXPIRATION_MINUTES=30
FRONTEND_URLS=http://localhost:4200 FRONTEND_URLS=http://localhost:4200
APP_LOCALE=es APP_LOCALE=es
@ -32,19 +30,11 @@ AUTH_LOGIN_ATTEMPT_WINDOW_MINUTES=30
AUTH_LOGIN_LOCK_MINUTES=15 AUTH_LOGIN_LOCK_MINUTES=15
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10 AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30 AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
AUTH_PASSWORD_RESET_EXPIRATION_MINUTES=60
LOG_CHANNEL=daily LOG_CHANNEL=stack
LOG_STACK=single LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug LOG_LEVEL=debug
LOG_DAILY_DAYS=14
TELEPAGOS_LOG_LEVEL=info
TELEPAGOS_LOG_DAYS=30
COMMANDS_LOG_LEVEL=info
COMMANDS_LOG_DAYS=30
EMAILS_LOG_LEVEL=info
EMAILS_LOG_DAYS=30
DB_CONNECTION=mysql DB_CONNECTION=mysql
DB_HOST=127.0.0.1 DB_HOST=127.0.0.1

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,29 +0,0 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Requests\AdminAppCreateResetPasswordAttemptRequest;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
class CreateAdminAppResetPasswordAttemptController extends Controller
{
public function __construct(
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
) {}
public function __invoke(AdminAppCreateResetPasswordAttemptRequest $request): JsonResponse
{
$this->resetPasswordAttemptService->createForAdminAppEmail(
$request->validated('email'),
);
return response()->json([
'code' => 'auth.password_reset_requested',
'message' => __('api.auth.password_reset_requested'),
'status' => ResetPasswordAttempt::STATUS_PENDING,
], 202);
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Requests\ScannerCreateResetPasswordAttemptRequest;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
class CreateScannerResetPasswordAttemptController extends Controller
{
public function __construct(
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
) {}
public function __invoke(ScannerCreateResetPasswordAttemptRequest $request): JsonResponse
{
$this->resetPasswordAttemptService->createForScannerEmail(
$request->validated('email'),
);
return response()->json([
'code' => 'auth.password_reset_requested',
'message' => __('api.auth.password_reset_requested'),
'status' => ResetPasswordAttempt::STATUS_PENDING,
], 202);
}
}

View File

@ -22,18 +22,10 @@ class ValidateResetPasswordAttemptController extends Controller
{ {
$data = $request->validated(); $data = $request->validated();
$result = $this->resetPasswordAttemptService->validateCode( if (! $this->resetPasswordAttemptService->validateCode(
$data['email'], $data['email'],
$data['codigo'], $data['codigo'],
); )) {
if ($result === ResetPasswordAttemptService::CODE_EXPIRED) {
throw ValidationException::withMessages([
'codigo' => __('api.auth.reset_code_expired'),
]);
}
if ($result !== ResetPasswordAttemptService::CODE_VALID) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'codigo' => __('api.auth.reset_code_invalid'), 'codigo' => __('api.auth.reset_code_invalid'),
]); ]);

View File

@ -7,16 +7,10 @@ use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['user_id', 'codigo', 'reason', 'status', 'expires_at'])] #[Fillable(['user_id', 'codigo', 'reason', 'status'])]
#[Hidden(['codigo'])] #[Hidden(['codigo'])]
class ResetPasswordAttempt extends Model class ResetPasswordAttempt extends Model
{ {
public const REASON_MANUAL = 'manual';
public const REASON_ACCOUNT_LOCKED = 'account_locked';
public const REASON_STAFF_CREATED = 'staff_created';
public const STATUS_PENDING = 'pending'; public const STATUS_PENDING = 'pending';
public const STATUS_VALIDATED = 'validated'; public const STATUS_VALIDATED = 'validated';
@ -31,7 +25,6 @@ class ResetPasswordAttempt extends Model
{ {
return [ return [
'user_id' => 'integer', 'user_id' => 'integer',
'expires_at' => 'datetime',
]; ];
} }

View File

@ -1,31 +0,0 @@
<?php
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
class AdminAppCreateResetPasswordAttemptRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
protected function prepareForValidation(): void
{
$email = $this->input('email');
if (is_string($email)) {
$this->merge(['email' => Str::lower(trim($email))]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'email' => ['required', 'string', 'email', 'max:255'],
];
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
class ScannerCreateResetPasswordAttemptRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
protected function prepareForValidation(): void
{
$email = $this->input('email');
if (is_string($email)) {
$this->merge(['email' => Str::lower(trim($email))]);
}
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'email' => ['required', 'string', 'email', 'max:255'],
];
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use Illuminate\Support\Facades\Hash;
class AdminCredentialVerifier
{
public function verify(string $email, string $password): bool
{
$admin = User::query()
->where('email', mb_strtolower(trim($email)))
->where('rol_codigo', RoleCode::Admin->value)
->first();
return $admin !== null
&& ! $admin->locked_until?->isFuture()
&& Hash::check($password, $admin->getAuthPassword());
}
}

View File

@ -155,19 +155,16 @@ class GoogleAuthService
$parts = parse_url($returnUrl); $parts = parse_url($returnUrl);
if (! is_array($parts) if (! is_array($parts)
|| ! isset($parts['scheme'], $parts['host']) || ! isset($parts['scheme'], $parts['host'])
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])) { || isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|| ($parts['path'] ?? '') !== '') {
return false; return false;
} }
$scheme = strtolower($parts['scheme']); $scheme = strtolower($parts['scheme']);
$host = TenantDomainNormalizer::normalize($parts['host']); $host = TenantDomainNormalizer::normalize($parts['host']);
$tenantDomain = TenantDomainNormalizer::normalize($tenant->dominio); $tenantDomain = TenantDomainNormalizer::normalize($tenant->dominio);
$returnPath = TenantDomainNormalizer::normalizePath($parts['path'] ?? '/');
if ($host === null if ($host === null || $tenantDomain === null || $host !== $tenantDomain) {
|| $tenantDomain === null
|| $host !== $tenantDomain
|| $returnPath !== $tenant->base_path) {
return false; return false;
} }

View File

@ -4,11 +4,9 @@ namespace App\Domains\Auth\Services;
use App\Domains\Auth\Exceptions\AccountLockedException; use App\Domains\Auth\Exceptions\AccountLockedException;
use App\Domains\Auth\Models\LoginAttempt; use App\Domains\Auth\Models\LoginAttempt;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\PermissionCode; use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode; use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Notification\Events\PasswordResetRequested;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
@ -62,8 +60,6 @@ class PasswordLoginService
$userAgent, $userAgent,
RoleCode::AdminApp, RoleCode::AdminApp,
true, true,
null,
PasswordResetRequested::CHANNEL_ADMINAPP,
); );
} }
@ -88,7 +84,6 @@ class PasswordLoginService
null, null,
true, true,
PermissionCode::ScanTickets->value, PermissionCode::ScanTickets->value,
PasswordResetRequested::CHANNEL_SCANNER,
); );
} }
@ -101,7 +96,6 @@ class PasswordLoginService
?RoleCode $requiredRole = RoleCode::User, ?RoleCode $requiredRole = RoleCode::User,
bool $requiresTenant = false, bool $requiresTenant = false,
?string $requiredPermission = null, ?string $requiredPermission = null,
string $passwordResetChannel = PasswordResetRequested::CHANNEL_STOREFRONT,
): User { ): User {
$normalizedEmail = mb_strtolower(trim($email)); $normalizedEmail = mb_strtolower(trim($email));
$now = CarbonImmutable::now(); $now = CarbonImmutable::now();
@ -117,7 +111,6 @@ class PasswordLoginService
$requiredRole, $requiredRole,
$requiresTenant, $requiresTenant,
$requiredPermission, $requiredPermission,
$passwordResetChannel,
): array { ): array {
$user = User::query() $user = User::query()
->where('email', $normalizedEmail) ->where('email', $normalizedEmail)
@ -167,12 +160,7 @@ class PasswordLoginService
if ($user === null || ! Hash::check($password, $user->password)) { if ($user === null || ! Hash::check($password, $user->password)) {
if ($user !== null && $attemptTenantCode !== null) { if ($user !== null && $attemptTenantCode !== null) {
$this->registerFailure( $this->registerFailure($user, $now, $attemptTenantCode);
$user,
$now,
$attemptTenantCode,
$passwordResetChannel,
);
} }
$outcome = $user?->locked_until?->isFuture() $outcome = $user?->locked_until?->isFuture()
@ -231,12 +219,8 @@ class PasswordLoginService
return $result['user']; return $result['user'];
} }
private function registerFailure( private function registerFailure(User $user, CarbonImmutable $now, string $tenantCode): void
User $user, {
CarbonImmutable $now,
string $tenantCode,
string $passwordResetChannel,
): void {
$windowMinutes = max(1, (int) config('login-security.attempt_window_minutes')); $windowMinutes = max(1, (int) config('login-security.attempt_window_minutes'));
$maxAttempts = max(1, (int) config('login-security.max_attempts')); $maxAttempts = max(1, (int) config('login-security.max_attempts'));
$lockMinutes = max(1, (int) config('login-security.lock_minutes')); $lockMinutes = max(1, (int) config('login-security.lock_minutes'));
@ -259,23 +243,7 @@ class PasswordLoginService
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) { if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
try { try {
if ($passwordResetChannel === PasswordResetRequested::CHANNEL_ADMINAPP) { $this->resetPasswordAttemptService->createForEmail($user->email, $tenantCode, 'account_locked');
$this->resetPasswordAttemptService->createForAdminAppEmail(
$user->email,
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
);
} elseif ($passwordResetChannel === PasswordResetRequested::CHANNEL_SCANNER) {
$this->resetPasswordAttemptService->createForScannerEmail(
$user->email,
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
);
} else {
$this->resetPasswordAttemptService->createForEmail(
$user->email,
$tenantCode,
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
);
}
} catch (\Throwable $e) { } catch (\Throwable $e) {
Log::error('Failed to trigger reset password on account lock', [ Log::error('Failed to trigger reset password on account lock', [
'user_id' => $user->id, 'user_id' => $user->id,

View File

@ -4,7 +4,6 @@ namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\ResetPasswordAttempt; use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Notification\Events\PasswordResetRequested; use App\Domains\Notification\Events\PasswordResetRequested;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@ -12,17 +11,8 @@ use Throwable;
class ResetPasswordAttemptService class ResetPasswordAttemptService
{ {
public const CODE_VALID = 'valid'; public function createForEmail(string $email, string $tenantCode, string $reason = 'manual'): void
{
public const CODE_INVALID = 'invalid';
public const CODE_EXPIRED = 'expired';
public function createForEmail(
string $email,
string $tenantCode,
string $reason = ResetPasswordAttempt::REASON_MANUAL,
): void {
$emailFingerprint = $this->emailFingerprint($email); $emailFingerprint = $this->emailFingerprint($email);
try { try {
@ -32,12 +22,28 @@ class ResetPasswordAttemptService
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
return $this->createAttemptForUser( if ($user === null) {
$user, Log::warning('Password reset attempt was not created because the user was not found.', [
$reason, 'email_fingerprint' => $emailFingerprint,
$emailFingerprint, ]);
'Password reset attempt was not created because the user was not found.',
); return null;
}
$user->resetPasswordAttempts()
->whereIn('status', [
ResetPasswordAttempt::STATUS_PENDING,
ResetPasswordAttempt::STATUS_VALIDATED,
])
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
$attempt = $user->resetPasswordAttempts()->create([
'codigo' => $this->generateCode(),
'reason' => $reason,
'status' => ResetPasswordAttempt::STATUS_PENDING,
]);
return $attempt->getKey();
}); });
} catch (Throwable $exception) { } catch (Throwable $exception) {
Log::error('Failed to create password reset attempt.', [ Log::error('Failed to create password reset attempt.', [
@ -48,116 +54,28 @@ class ResetPasswordAttemptService
throw $exception; throw $exception;
} }
$this->dispatchPasswordResetRequested( if ($attemptId !== null) {
$attemptId, try {
$tenantCode, PasswordResetRequested::dispatch($attemptId, $tenantCode);
PasswordResetRequested::CHANNEL_STOREFRONT, } catch (Throwable $exception) {
$emailFingerprint, Log::error('Failed to dispatch password reset email.', [
);
}
public function createForAdminAppEmail(
string $email,
string $reason = ResetPasswordAttempt::REASON_MANUAL,
): void {
$emailFingerprint = $this->emailFingerprint($email);
try {
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
$user = User::query()
->where('email', $email)
->where('rol_codigo', RoleCode::AdminApp->value)
->whereNotNull('tenant_codigo')
->lockForUpdate()
->first();
$attemptId = $this->createAttemptForUser(
$user,
$reason,
$emailFingerprint,
'AdminApp password reset attempt was not created because the user was not found.',
);
if ($user === null || $attemptId === null) {
return null;
}
return [
'attempt_id' => $attemptId, 'attempt_id' => $attemptId,
'tenant_code' => $user->tenant_codigo, 'tenant_code' => $tenantCode,
]; 'email_fingerprint' => $emailFingerprint,
}); 'exception' => $exception,
} catch (Throwable $exception) { ]);
Log::error('Failed to create AdminApp password reset attempt.', [
'email_fingerprint' => $emailFingerprint,
'exception' => $exception,
]);
throw $exception; throw $exception;
}
} }
$this->dispatchPasswordResetRequested(
$result['attempt_id'] ?? null,
$result['tenant_code'] ?? null,
PasswordResetRequested::CHANNEL_ADMINAPP,
$emailFingerprint,
);
} }
public function createForScannerEmail( public function validateCode(string $email, string $code): bool
string $email,
string $reason = ResetPasswordAttempt::REASON_MANUAL,
): void {
$emailFingerprint = $this->emailFingerprint($email);
try {
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
$user = User::query()
->where('email', $email)
->where('rol_codigo', RoleCode::Scanner->value)
->whereNotNull('tenant_codigo')
->lockForUpdate()
->first();
$attemptId = $this->createAttemptForUser(
$user,
$reason,
$emailFingerprint,
'Scanner password reset attempt was not created because the user was not found.',
);
if ($user === null || $attemptId === null) {
return null;
}
return [
'attempt_id' => $attemptId,
'tenant_code' => $user->tenant_codigo,
];
});
} catch (Throwable $exception) {
Log::error('Failed to create Scanner password reset attempt.', [
'email_fingerprint' => $emailFingerprint,
'exception' => $exception,
]);
throw $exception;
}
$this->dispatchPasswordResetRequested(
$result['attempt_id'] ?? null,
$result['tenant_code'] ?? null,
PasswordResetRequested::CHANNEL_SCANNER,
$emailFingerprint,
);
}
public function validateCode(string $email, string $code): string
{ {
$emailFingerprint = $this->emailFingerprint($email); $emailFingerprint = $this->emailFingerprint($email);
try { try {
return DB::transaction(function () use ($email, $code, $emailFingerprint): string { return DB::transaction(function () use ($email, $code, $emailFingerprint): bool {
$user = User::query() $user = User::query()
->where('email', $email) ->where('email', $email)
->lockForUpdate() ->lockForUpdate()
@ -175,27 +93,14 @@ class ResetPasswordAttemptService
'email_fingerprint' => $emailFingerprint, 'email_fingerprint' => $emailFingerprint,
]); ]);
return self::CODE_INVALID; return false;
}
if ($attempt->expires_at?->isPast()) {
$attempt->update([
'status' => ResetPasswordAttempt::STATUS_EXPIRED,
]);
Log::info('Password reset code validation failed: attempt expired.', [
'email_fingerprint' => $emailFingerprint,
'attempt_id' => $attempt->getKey(),
]);
return self::CODE_EXPIRED;
} }
$attempt->update([ $attempt->update([
'status' => ResetPasswordAttempt::STATUS_VALIDATED, 'status' => ResetPasswordAttempt::STATUS_VALIDATED,
]); ]);
return self::CODE_VALID; return true;
}); });
} catch (Throwable $exception) { } catch (Throwable $exception) {
Log::error('Failed to validate password reset code.', [ Log::error('Failed to validate password reset code.', [
@ -233,19 +138,6 @@ class ResetPasswordAttemptService
return false; return false;
} }
if ($attempt->expires_at?->isPast()) {
$attempt->update([
'status' => ResetPasswordAttempt::STATUS_EXPIRED,
]);
Log::info('Password reset failed: attempt expired.', [
'email_fingerprint' => $emailFingerprint,
'attempt_id' => $attempt->getKey(),
]);
return false;
}
$user->password = $password; $user->password = $password;
$user->failed_login_attempts = 0; $user->failed_login_attempts = 0;
$user->last_failed_login_at = null; $user->last_failed_login_at = null;
@ -277,62 +169,6 @@ class ResetPasswordAttemptService
} }
} }
private function createAttemptForUser(
?User $user,
string $reason,
string $emailFingerprint,
string $userNotFoundMessage,
): ?int {
if ($user === null) {
Log::warning($userNotFoundMessage, [
'email_fingerprint' => $emailFingerprint,
]);
return null;
}
$user->resetPasswordAttempts()
->whereIn('status', [
ResetPasswordAttempt::STATUS_PENDING,
ResetPasswordAttempt::STATUS_VALIDATED,
])
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
$attempt = $user->resetPasswordAttempts()->create([
'codigo' => $this->generateCode(),
'reason' => $reason,
'status' => ResetPasswordAttempt::STATUS_PENDING,
'expires_at' => now()->addMinutes((int) config('auth.passwords.users.expire')),
]);
return $attempt->getKey();
}
private function dispatchPasswordResetRequested(
?int $attemptId,
?string $tenantCode,
string $channel,
string $emailFingerprint,
): void {
if ($attemptId === null || $tenantCode === null) {
return;
}
try {
PasswordResetRequested::dispatch($attemptId, $tenantCode, $channel);
} catch (Throwable $exception) {
Log::error('Failed to dispatch password reset email.', [
'attempt_id' => $attemptId,
'tenant_code' => $tenantCode,
'channel' => $channel,
'email_fingerprint' => $emailFingerprint,
'exception' => $exception,
]);
throw $exception;
}
}
private function generateCode(): string private function generateCode(): string
{ {
return str_pad((string) random_int(0, 9999), 4, '0', STR_PAD_LEFT); return str_pad((string) random_int(0, 9999), 4, '0', STR_PAD_LEFT);

View File

@ -2,19 +2,10 @@
use App\Domains\Auth\Controllers\AdminAppLoginController; use App\Domains\Auth\Controllers\AdminAppLoginController;
use App\Domains\Auth\Controllers\AdminAppMeController; use App\Domains\Auth\Controllers\AdminAppMeController;
use App\Domains\Auth\Controllers\CreateAdminAppResetPasswordAttemptController;
use App\Domains\Auth\Controllers\ResetPasswordController;
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp')->group(function (): void { Route::prefix('v1/adminapp')->group(function (): void {
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login'); Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
Route::post('password/reset-attempts', CreateAdminAppResetPasswordAttemptController::class)
->middleware('throttle:5,1');
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
->middleware('throttle:10,1');
Route::post('password/reset', ResetPasswordController::class)
->middleware('throttle:5,1');
Route::middleware(['auth:sanctum', 'adminapp.tenant']) Route::middleware(['auth:sanctum', 'adminapp.tenant'])
->get('me', AdminAppMeController::class); ->get('me', AdminAppMeController::class);
}); });

View File

@ -1,20 +1,11 @@
<?php <?php
use App\Domains\Auth\Controllers\CreateScannerResetPasswordAttemptController;
use App\Domains\Auth\Controllers\ResetPasswordController;
use App\Domains\Auth\Controllers\ScannerLoginController; use App\Domains\Auth\Controllers\ScannerLoginController;
use App\Domains\Auth\Controllers\ScannerMeController; use App\Domains\Auth\Controllers\ScannerMeController;
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1/scanner')->group(function (): void { Route::prefix('v1/scanner')->group(function (): void {
Route::post('login', ScannerLoginController::class)->middleware('throttle:login'); Route::post('login', ScannerLoginController::class)->middleware('throttle:login');
Route::post('password/reset-attempts', CreateScannerResetPasswordAttemptController::class)
->middleware('throttle:5,1');
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
->middleware('throttle:10,1');
Route::post('password/reset', ResetPasswordController::class)
->middleware('throttle:5,1');
Route::middleware(['auth:sanctum', 'scanner.tenant']) Route::middleware(['auth:sanctum', 'scanner.tenant'])
->get('me', ScannerMeController::class); ->get('me', ScannerMeController::class);
}); });

View File

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

View File

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

View File

@ -30,7 +30,6 @@ class AdminAppBootstrapResource extends JsonResource
'login_header_footer_color' => $websiteType->login_header_footer_color, 'login_header_footer_color' => $websiteType->login_header_footer_color,
'site_logo' => $websiteType->siteLogo?->getTemporaryUrl(1440), 'site_logo' => $websiteType->siteLogo?->getTemporaryUrl(1440),
'footer_logo' => $websiteType->footerLogo?->getTemporaryUrl(1440), 'footer_logo' => $websiteType->footerLogo?->getTemporaryUrl(1440),
'favicon' => $websiteType->favicon?->getTemporaryUrl(1440),
]; ];
} }
} }

View File

@ -11,7 +11,7 @@ class AdminAppBootstrapService
{ {
return [ return [
'website_type' => WebsiteType::query() 'website_type' => WebsiteType::query()
->with(['siteLogo', 'footerLogo', 'favicon']) ->with(['siteLogo', 'footerLogo'])
->where('dominio', $domain) ->where('dominio', $domain)
->firstOrFail(), ->firstOrFail(),
]; ];

View File

@ -11,7 +11,7 @@ class ScannerBootstrapService
{ {
return [ return [
'website_type' => WebsiteType::query() 'website_type' => WebsiteType::query()
->with(['siteLogo', 'footerLogo', 'favicon']) ->with(['siteLogo', 'footerLogo'])
->where('scanner_domain', $domain) ->where('scanner_domain', $domain)
->firstOrFail(), ->firstOrFail(),
]; ];

View File

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

View File

@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
## Endpoints ## Endpoints
- `GET /tenants/bootstrap?dominio={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. - `GET /tenants/bootstrap/{dominio}`: bootstrap público de la tienda.
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`. - Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
## Validación ## Validación
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel. `TenantBootstrapRequest` valida el dominio recibido. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
## Dependencias ## Dependencias

View File

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

View File

@ -5,11 +5,8 @@ namespace App\Domains\Cart\Models;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory; use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService; use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\UserPurchaseLimitService; use App\Domains\Purchase\Services\UserPurchaseLimitService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
@ -27,9 +24,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
'user_id', 'user_id',
'guest_token', 'guest_token',
'status', 'status',
'origin',
'current_purchase_id',
'current_stock_reservation_id',
])] ])]
class Cart extends Model class Cart extends Model
{ {
@ -38,26 +32,10 @@ class Cart extends Model
protected $table = 'carritos'; protected $table = 'carritos';
public const STATUS_ACTIVE = 'active';
public const STATUS_CHECKOUT = 'checkout';
public const STATUS_CONVERTED = 'converted';
public const STATUS_EXPIRED = 'expired';
public const STATUS_ABANDONED = 'abandoned';
public const ORIGIN_USER = 'user';
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
protected function casts(): array protected function casts(): array
{ {
return [ return [
'user_id' => 'integer', 'user_id' => 'integer',
'current_purchase_id' => 'integer',
'current_stock_reservation_id' => 'integer',
]; ];
} }
@ -85,27 +63,6 @@ class Cart extends Model
return $this->hasMany(CartItem::class, 'cart_id'); return $this->hasMany(CartItem::class, 'cart_id');
} }
/** @return HasMany<Purchase, $this> */
public function purchases(): HasMany
{
return $this->hasMany(Purchase::class, 'cart_id');
}
/** @return BelongsTo<Purchase, $this> */
public function currentPurchase(): BelongsTo
{
return $this->belongsTo(Purchase::class, 'current_purchase_id');
}
/** @return BelongsTo<StockReservation, $this> */
public function currentStockReservation(): BelongsTo
{
return $this->belongsTo(
StockReservation::class,
'current_stock_reservation_id',
);
}
public function getTotalAmount(): float public function getTotalAmount(): float
{ {
$items = $this->relationLoaded('items') $items = $this->relationLoaded('items')
@ -128,20 +85,14 @@ class Cart extends Model
} }
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem { return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
$this->invalidateCurrentCheckout(); self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
app(StockReservationService::class)->assertCartReservationUsable($this);
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true); $selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
$cartQuantity = (int) $this->items() $cartQuantity = (int) $this->items()
->where('catalog_item_id', $catalogItemId) ->where('catalog_item_id', $catalogItemId)
->sum('cantidad'); ->sum('cantidad');
$this->assertUserPurchaseLimit($selectedItem, $cartQuantity + $quantity);
$inventoryService = app(CatalogInventoryService::class); $inventoryService = app(CatalogInventoryService::class);
$availableQuantity = $inventoryService->availableQuantity($selectedItem); $availableQuantity = $inventoryService->availableQuantity($selectedItem);
$this->assertUserPurchaseLimit(
$selectedItem,
$cartQuantity + $quantity,
heldQuantity: $cartQuantity,
maximumAddableCeiling: $availableQuantity,
);
if ($availableQuantity !== null && $availableQuantity < $quantity) { if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@ -167,7 +118,7 @@ class Cart extends Model
$item->save(); $item->save();
} }
app(StockReservationService::class)->syncCart($this); $inventoryService->reserve($selectedItem, $quantity);
return $item->fresh(); return $item->fresh();
}); });
@ -178,7 +129,6 @@ class Cart extends Model
int $quantity, int $quantity,
?int $variantId = null, ?int $variantId = null,
bool $updateVariant = false, bool $updateVariant = false,
?int $excludedPurchaseId = null,
): CartItem { ): CartItem {
if ($quantity <= 0) { if ($quantity <= 0) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@ -191,11 +141,7 @@ class Cart extends Model
$quantity, $quantity,
$variantId, $variantId,
$updateVariant, $updateVariant,
$excludedPurchaseId,
): CartItem { ): CartItem {
$this->invalidateCurrentCheckout();
app(StockReservationService::class)->assertCartReservationUsable($this);
/** @var CartItem $item */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
->where('id', $cartItemId) ->where('id', $cartItemId)
@ -219,15 +165,12 @@ class Cart extends Model
->where('catalog_item_id', $item->catalog_item_id) ->where('catalog_item_id', $item->catalog_item_id)
->whereKeyNot($item->getKey()) ->whereKeyNot($item->getKey())
->sum('cantidad'); ->sum('cantidad');
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
$this->assertUserPurchaseLimit( $this->assertUserPurchaseLimit(
$nextSelection, $nextSelection,
$otherVariantsQuantity + $quantity, $otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$nextAvailableQuantity,
); );
$inventoryService->release($currentSelection, $item->cantidad);
$availableQuantity = $inventoryService->availableQuantity($nextSelection); $availableQuantity = $inventoryService->availableQuantity($nextSelection);
if ($availableQuantity !== null && $availableQuantity < $quantity) { if ($availableQuantity !== null && $availableQuantity < $quantity) {
@ -243,11 +186,12 @@ class Cart extends Model
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
$inventoryService->reserve($nextSelection, $quantity);
if ($targetItem !== null) { if ($targetItem !== null) {
$targetItem->cantidad += $quantity; $targetItem->cantidad += $quantity;
$targetItem->save(); $targetItem->save();
$item->delete(); $item->delete();
app(StockReservationService::class)->syncCart($this);
return $targetItem->fresh(); return $targetItem->fresh();
} }
@ -255,13 +199,11 @@ class Cart extends Model
$item->variant_id = $variantId; $item->variant_id = $variantId;
$item->cantidad = $quantity; $item->cantidad = $quantity;
$item->save(); $item->save();
app(StockReservationService::class)->syncCart($this);
return $item->fresh(); return $item->fresh();
} }
$delta = $quantity - $item->cantidad; $delta = $quantity - $item->cantidad;
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0) { if ($delta > 0) {
$otherVariantsQuantity = (int) $this->items() $otherVariantsQuantity = (int) $this->items()
@ -271,12 +213,11 @@ class Cart extends Model
$this->assertUserPurchaseLimit( $this->assertUserPurchaseLimit(
$currentSelection, $currentSelection,
$otherVariantsQuantity + $quantity, $otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$availableQuantity,
); );
} }
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) { if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad; $maxAvailable = $availableQuantity + $item->cantidad;
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@ -286,7 +227,14 @@ class Cart extends Model
$item->cantidad = $quantity; $item->cantidad = $quantity;
$item->save(); $item->save();
app(StockReservationService::class)->syncCart($this);
if ($delta > 0) {
$inventoryService->reserve($currentSelection, $delta);
}
if ($delta < 0) {
$inventoryService->release($currentSelection, abs($delta));
}
return $item->fresh(); return $item->fresh();
}); });
@ -295,79 +243,25 @@ class Cart extends Model
public function removeItem(int $cartItemId): void public function removeItem(int $cartItemId): void
{ {
DB::transaction(function () use ($cartItemId): void { DB::transaction(function () use ($cartItemId): void {
$this->invalidateCurrentCheckout();
app(StockReservationService::class)->assertCartReservationUsable($this);
/** @var CartItem $item */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
->where('id', $cartItemId) ->where('id', $cartItemId)
->lockForUpdate() ->lockForUpdate()
->firstOrFail(); ->firstOrFail();
$selectedItem = $this->resolveScopedItem(
$item->catalog_item_id,
$item->variant_id,
true,
);
app(CatalogInventoryService::class)->release(
$selectedItem,
$item->cantidad,
);
$item->delete(); $item->delete();
app(StockReservationService::class)->syncCart($this);
}); });
} }
private function invalidateCurrentCheckout(): void
{
$candidatePurchaseId = self::query()
->whereKey($this->getKey())
->value('current_purchase_id');
$currentPurchase = $candidatePurchaseId === null
? null
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
/** @var self $cart */
$cart = self::query()->lockForUpdate()->findOrFail($this->getKey());
if ($cart->current_purchase_id !== $candidatePurchaseId) {
if ($cart->current_purchase_id !== null) {
throw ValidationException::withMessages([
'cart' => __('api.purchase.checkout_in_progress'),
]);
}
$this->current_purchase_id = null;
return;
}
if ($currentPurchase === null) {
return;
}
if ($currentPurchase->status === Purchase::STATUS_PAID) {
throw ValidationException::withMessages([
'cart' => __('api.cart.editing_disabled'),
]);
}
if (in_array($currentPurchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
app(StockReservationService::class)->returnToCart($currentPurchase, $cart);
$currentPurchase->update([
'status' => Purchase::STATUS_SUPERSEDED,
]);
$this->current_purchase_id = null;
return;
}
app(StockReservationService::class)->releaseForPurchase(
$currentPurchase,
reason: StockReservationService::REASON_PURCHASE_SUPERSEDED,
);
self::query()
->whereKey($cart->getKey())
->where('current_purchase_id', $currentPurchase->getKey())
->update(['current_purchase_id' => null]);
$this->current_purchase_id = null;
}
protected function resolveScopedItem( protected function resolveScopedItem(
int $catalogItemId, int $catalogItemId,
?int $variantId, ?int $variantId,
@ -440,9 +334,6 @@ class Cart extends Model
private function assertUserPurchaseLimit( private function assertUserPurchaseLimit(
CatalogItem|Variant $selectedItem, CatalogItem|Variant $selectedItem,
int $cartQuantity, int $cartQuantity,
?int $excludedPurchaseId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
): void { ): void {
if ($this->user_id === null) { if ($this->user_id === null) {
return; return;
@ -456,10 +347,6 @@ class Cart extends Model
$catalogItem, $catalogItem,
$this->user_id, $this->user_id,
$cartQuantity, $cartQuantity,
$excludedPurchaseId,
$this->getKey(),
$heldQuantity,
$maximumAddableCeiling,
field: 'cantidad', field: 'cantidad',
); );
} }

View File

@ -5,7 +5,6 @@ namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@ -21,16 +20,12 @@ class CartItemResource extends JsonResource
{ {
$selectedItem = $this->selectedItem(); $selectedItem = $this->selectedItem();
$imageUrl = null; $imageUrl = null;
$tenant = $request->route('tenant');
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
$includeVariants = $tenant instanceof Tenant
&& $tenant->cart_editing_policy->allowsVariantChanges();
if ($displayImage && $selectedItem?->relationLoaded('attachments')) { if ($selectedItem?->relationLoaded('attachments')) {
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440); $imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
} }
if ($displayImage && $imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) { if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440); $imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
} }
@ -40,29 +35,20 @@ class CartItemResource extends JsonResource
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()), 'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
'catalog_item_id' => $this->catalog_item_id, 'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id, 'variant_id' => $this->variant_id,
'nombre' => $selectedItem?->getName(), 'product' => $selectedItem === null ? null : [
'imagen' => $imageUrl, 'nombre' => $selectedItem->getName(),
'variant' => $this->variant === null ? null : $this->variantData($this->variant), 'imagen' => $imageUrl,
'variants' => $this->when( 'variants' => $this->catalogItem->visibleVariants($this->variant_id)
$includeVariants, ->map(fn (Variant $variant): array => [
fn () => $this->catalogItem 'id' => $variant->id,
->visibleVariants($this->variant_id) 'precio' => $this->formatMoney($variant->getPrice()),
->map(fn (Variant $variant): array => $this->variantData($variant)) 'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectionOptions($this->catalogItem->itemAttributes),
])
->values(), ->values(),
), ],
];
}
/** @return array<string, mixed> */
protected function variantData(Variant $variant): array
{
return [
'id' => $variant->id,
'precio' => $this->formatMoney($variant->precio ?? $this->catalogItem->precio),
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
]; ];
} }

View File

@ -4,14 +4,10 @@ namespace App\Domains\Cart\Services;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
use App\Domains\Catalog\Services\ExpireStockReservationsService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@ -25,13 +21,13 @@ class CartService
return $this->makeEmptyCart($tenant); return $this->makeEmptyCart($tenant);
} }
$cart = $this->resolveCart($tenant, $resolvedIdentity['identity']); $cart = $this->findCart($tenant, $resolvedIdentity['identity']);
if ($cart === null) { if ($cart === null) {
return $this->makeEmptyCart($tenant); return $this->makeEmptyCart($tenant);
} }
return $this->loadCart($cart, $tenant); return $this->loadCart($cart);
} }
/** /**
@ -50,7 +46,7 @@ class CartService
$cart->addItem($catalogItemId, $variantId, $quantity); $cart->addItem($catalogItemId, $variantId, $quantity);
return [ return [
'cart' => $this->loadCart($cart, $tenant), 'cart' => $this->loadCart($cart),
'guest_token' => $resolvedIdentity['generated_guest_token'], 'guest_token' => $resolvedIdentity['generated_guest_token'],
]; ];
} }
@ -63,58 +59,34 @@ class CartService
?int $variantId, ?int $variantId,
bool $updateVariant, bool $updateVariant,
): Cart { ): Cart {
if ($updateVariant && ! $tenant->cart_editing_policy->allowsVariantChanges()) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_change_disabled'),
]);
}
if (! $updateVariant && ! $tenant->cart_editing_policy->allowsQuantityChanges()) {
throw ValidationException::withMessages([
'cantidad' => __('api.cart.editing_disabled'),
]);
}
$identity = $this->requireIdentity($request); $identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity); $cart = $this->findCartOrFail($tenant, $identity);
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant); $cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
return $this->loadCart($cart, $tenant); return $this->loadCart($cart);
} }
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
{ {
if (! $tenant->cart_editing_policy->allowsRemoval()) {
throw ValidationException::withMessages([
'cart_item' => __('api.cart.editing_disabled'),
]);
}
$identity = $this->requireIdentity($request); $identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity); $cart = $this->findCartOrFail($tenant, $identity);
$cart->removeItem($cartItemId); $cart->removeItem($cartItemId);
return $this->loadCart($cart, $tenant); return $this->loadCart($cart);
} }
public function makeGuestTokenCookie(string $guestToken): Cookie public function makeGuestTokenCookie(string $guestToken): Cookie
{ {
$secure = (bool) config('session.secure'); return cookie(
$sameSite = config('session.same_site'); 'guest_token',
$partitioned = (bool) config('session.partitioned') $guestToken,
|| ($secure && strtolower((string) $sameSite) === 'none'); 60 * 24 * 180,
'/',
return Cookie::create( null,
name: 'guest_token', false,
value: $guestToken, true,
expire: now()->addDays(180), false,
path: '/', 'lax',
domain: config('session.domain'),
secure: $secure,
httpOnly: true,
raw: false,
sameSite: $sameSite,
partitioned: $partitioned,
); );
} }
@ -122,7 +94,7 @@ class CartService
{ {
$cart = new Cart([ $cart = new Cart([
'tenant_codigo' => $tenant->codigo, 'tenant_codigo' => $tenant->codigo,
'status' => Cart::STATUS_ACTIVE, 'status' => 'active',
]); ]);
$cart->setRelation('items', collect()); $cart->setRelation('items', collect());
@ -130,32 +102,22 @@ class CartService
return $cart; return $cart;
} }
protected function loadCart(Cart $cart, Tenant $tenant): Cart protected function loadCart(Cart $cart): Cart
{ {
$relations = [ return $cart->fresh()->load([
'items.catalogItem.attachments', 'items.catalogItem.attachments',
'items.catalogItem.inventory', 'items.catalogItem.inventory',
'items.catalogItem.itemAttributes.attribute', 'items.catalogItem.itemAttributes.attribute',
'items.catalogItem.variants.inventory',
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
'items.catalogItem.variants.eventDates',
'items.catalogItem.variants.eventDate',
'items.variant.attachments', 'items.variant.attachments',
'items.variant.inventory', 'items.variant.inventory',
'items.variant.definitions.itemAttribute.attribute.options', 'items.variant.definitions.itemAttribute.attribute.options',
'items.variant.eventDates', 'items.variant.eventDates',
'items.variant.eventDate', 'items.variant.eventDate',
]; ]);
if ($tenant->cart_editing_policy->allowsVariantChanges()) {
$relations = [
...$relations,
'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
'items.catalogItem.variants.inventory',
'items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
'items.catalogItem.variants.eventDates',
'items.catalogItem.variants.eventDate',
];
}
return $cart->fresh()->load($relations);
} }
/** /**
@ -223,14 +185,12 @@ class CartService
{ {
return Cart::query() return Cart::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
->where('origin', Cart::ORIGIN_USER) ->where('status', 'active')
->whereIn('status', [Cart::STATUS_ACTIVE, Cart::STATUS_EXPIRED])
->when( ->when(
$identity['user_id'] !== null, $identity['user_id'] !== null,
fn ($query) => $query->where('user_id', $identity['user_id']), fn ($query) => $query->where('user_id', $identity['user_id']),
fn ($query) => $query->where('guest_token', $identity['guest_token']), fn ($query) => $query->where('guest_token', $identity['guest_token']),
) )
->orderByRaw('CASE WHEN status = ? THEN 0 ELSE 1 END', [Cart::STATUS_ACTIVE])
->first(); ->first();
} }
@ -239,7 +199,7 @@ class CartService
*/ */
protected function findCartOrFail(Tenant $tenant, array $identity): Cart protected function findCartOrFail(Tenant $tenant, array $identity): Cart
{ {
$cart = $this->resolveCart($tenant, $identity, replaceExpired: false); $cart = $this->findCart($tenant, $identity);
if ($cart === null) { if ($cart === null) {
throw new NotFoundHttpException('Cart not found.'); throw new NotFoundHttpException('Cart not found.');
@ -252,73 +212,10 @@ class CartService
* @param array{user_id: ?int, guest_token: ?string} $identity * @param array{user_id: ?int, guest_token: ?string} $identity
*/ */
protected function findOrCreateCart(Tenant $tenant, array $identity): Cart protected function findOrCreateCart(Tenant $tenant, array $identity): Cart
{
return $this->resolveCart($tenant, $identity)
?? $this->createCart($tenant, $identity);
}
/**
* @param array{user_id: ?int, guest_token: ?string} $identity
*/
protected function resolveCart(
Tenant $tenant,
array $identity,
bool $replaceExpired = true,
): ?Cart {
$cart = $this->findCart($tenant, $identity);
if ($cart?->status === Cart::STATUS_ACTIVE
&& $cart->current_stock_reservation_id !== null
&& app(ExpireStockReservationsService::class)
->expireIfOverdue($cart->current_stock_reservation_id)) {
$cart = $this->findCart($tenant, $identity);
}
if ($cart?->status === Cart::STATUS_EXPIRED) {
if (! $replaceExpired) {
throw new StockReservationExpiredException;
}
return $this->replaceExpiredCart($cart, $tenant, $identity);
}
if ($cart !== null) {
return $cart;
}
return null;
}
/**
* @param array{user_id: ?int, guest_token: ?string} $identity
*/
protected function replaceExpiredCart(Cart $expiredCart, Tenant $tenant, array $identity): Cart
{
return DB::transaction(function () use ($expiredCart, $tenant, $identity): Cart {
/** @var Cart|null $lockedCart */
$lockedCart = Cart::query()->lockForUpdate()->find($expiredCart->getKey());
if ($lockedCart?->status === Cart::STATUS_EXPIRED) {
$lockedCart->update([
'status' => Cart::STATUS_ABANDONED,
'current_purchase_id' => null,
]);
}
return $this->findCart($tenant, $identity)
?? $this->createCart($tenant, $identity);
});
}
/**
* @param array{user_id: ?int, guest_token: ?string} $identity
*/
protected function createCart(Tenant $tenant, array $identity): Cart
{ {
$attributes = [ $attributes = [
'tenant_codigo' => $tenant->codigo, 'tenant_codigo' => $tenant->codigo,
'status' => Cart::STATUS_ACTIVE, 'status' => 'active',
'origin' => Cart::ORIGIN_USER,
]; ];
if ($identity['user_id'] !== null) { if ($identity['user_id'] !== null) {

View File

@ -34,10 +34,6 @@ class GuestCartMergeService
->first(); ->first();
if ($userCart !== null) { if ($userCart !== null) {
$userCart->items()
->orderBy('id')
->pluck('id')
->each(fn (int $itemId) => $userCart->removeItem($itemId));
$userCart->update([ $userCart->update([
'status' => 'converted', 'status' => 'converted',
]); ]);

View File

@ -6,8 +6,8 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
## Modelo ## Modelo
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total, permite agregar, actualizar o quitar ítems y apunta a su reserva de stock vigente mediante `current_stock_reservation_id`. - `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo. - `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; expone la selección efectiva.
## Servicios ## Servicios
@ -25,14 +25,8 @@ Bajo `/tenants/{tenant:codigo}`:
## Contratos ## Contratos
`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. `AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
## Dependencias y reglas ## Dependencias y reglas
Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual. Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual.
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
Cada edición sincroniza una única reserva para el carrito completo. Si varios ítems o bundles consumen el mismo inventario, se persiste una sola línea con la cantidad agregada. Al editar durante checkout, la compra anterior queda `superseded`, se desvincula y el carrito conserva la misma reserva activa con sus líneas actualizadas.
El comando unificado `php artisan reservations:expire` recorre una sola vez las reservas activas cuyo `expires_at` haya vencido. Cuando pertenecen a un carrito, conserva la reserva y sus líneas como historial, libera el stock como conjunto y cambia el carrito asociado a `expired` sin eliminar sus ítems. Al volver a resolver ese carrito desde la API, el anterior pasa automáticamente a `abandoned` y se crea uno activo y vacío para la misma identidad. El cliente nunca necesita reiniciarlo explícitamente. La API también materializa este vencimiento al acceder al carrito aunque el comando programado todavía no haya corrido.

View File

@ -2,12 +2,10 @@
namespace App\Domains\Catalog\Controllers; namespace App\Domains\Catalog\Controllers;
use App\Domains\Cart\Services\CartService;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup; use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Requests\CatalogItemDetailRequest; use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
use App\Domains\Catalog\Requests\CategoryPageRequest; use App\Domains\Catalog\Requests\CategoryPageRequest;
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest; use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest; use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
@ -16,21 +14,16 @@ use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
use App\Domains\Catalog\Resources\CatalogItemDetailResource; use App\Domains\Catalog\Resources\CatalogItemDetailResource;
use App\Domains\Catalog\Resources\CatalogItemResource; use App\Domains\Catalog\Resources\CatalogItemResource;
use App\Domains\Catalog\Resources\CatalogSearchItemResource; use App\Domains\Catalog\Resources\CatalogSearchItemResource;
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Catalog\Services\FeaturedGroupService; use App\Domains\Catalog\Services\FeaturedGroupService;
use App\Domains\Catalog\Services\VariantSelectionService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Auth;
class CatalogController extends Controller class CatalogController extends Controller
{ {
public function index(Request $request, Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse public function index(Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
{ {
$featuredGroups = FeaturedGroup::query() $featuredGroups = FeaturedGroup::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
@ -40,7 +33,7 @@ class CatalogController extends Controller
return response()->json($featuredGroups->map( return response()->json($featuredGroups->map(
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource( fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
$featuredGroup, $featuredGroup,
$featuredGroupService->itemsResponse($featuredGroup, 1, $this->userId($request)), $featuredGroupService->itemsResponse($featuredGroup, 1),
))->resolve() ))->resolve()
)); ));
} }
@ -49,17 +42,15 @@ class CatalogController extends Controller
SearchCatalogItemsRequest $request, SearchCatalogItemsRequest $request,
Tenant $tenant, Tenant $tenant,
CatalogService $catalogService, CatalogService $catalogService,
CatalogItemAllowanceService $allowances,
): AnonymousResourceCollection { ): AnonymousResourceCollection {
$items = $catalogService->search( return CatalogSearchItemResource::collection(
$tenant, $catalogService->search(
$request->validated('q'), $tenant,
$tenant->search_items_per_page, $request->validated('q'),
(int) $request->validated('page', 1), $tenant->search_items_per_page,
(int) $request->validated('page', 1),
)
); );
$allowances->attach($items->getCollection(), $this->userId($request));
return CatalogSearchItemResource::collection($items);
} }
public function category( public function category(
@ -67,19 +58,17 @@ class CatalogController extends Controller
Tenant $tenant, Tenant $tenant,
Category $category, Category $category,
CatalogService $catalogService, CatalogService $catalogService,
CatalogItemAllowanceService $allowances,
): AnonymousResourceCollection { ): AnonymousResourceCollection {
abort_unless($category->tenant_code === $tenant->codigo, 404); abort_unless($category->tenant_code === $tenant->codigo, 404);
$items = $catalogService->categoryItems( return CatalogSearchItemResource::collection(
$tenant, $catalogService->categoryItems(
$category, $tenant,
$tenant->search_items_per_page, $category,
(int) $request->validated('page', 1), $tenant->search_items_per_page,
); (int) $request->validated('page', 1),
$allowances->attach($items->getCollection(), $this->userId($request)); )
)->additional([
return CatalogSearchItemResource::collection($items)->additional([
'category' => [ 'category' => [
'id' => $category->id, 'id' => $category->id,
'nombre' => $category->nombre, 'nombre' => $category->nombre,
@ -100,11 +89,7 @@ class CatalogController extends Controller
$page = (int) $request->validated('page', 1); $page = (int) $request->validated('page', 1);
return response()->json($featuredGroupService->itemsResponse( return response()->json($featuredGroupService->itemsResponse($featuredGroup, $page));
$featuredGroup,
$page,
$this->userId($request),
));
} }
public function show( public function show(
@ -112,53 +97,15 @@ class CatalogController extends Controller
Tenant $tenant, Tenant $tenant,
CatalogItem $catalogItem, CatalogItem $catalogItem,
CatalogService $catalogService, CatalogService $catalogService,
CatalogItemAllowanceService $allowances,
): CatalogItemDetailResource { ): CatalogItemDetailResource {
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404); abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
$variantId = $request->validated('variant_id'); $variantId = $request->validated('variant_id');
$item = $catalogService->getDetail( return CatalogItemDetailResource::make(
$catalogItem, $catalogService->getDetail(
$variantId === null ? null : (int) $variantId,
);
$allowances->attach(collect([$item]), $this->userId($request));
return CatalogItemDetailResource::make($item);
}
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, $catalogItem,
$selectedValues, $variantId === null ? null : (int) $variantId,
$includedVariantId,
) )
); );
} }
@ -177,11 +124,4 @@ class CatalogController extends Controller
->response() ->response()
->setStatusCode(201); ->setStatusCode(201);
} }
private function userId(Request $request): ?int
{
$userId = $request->user()?->getAuthIdentifier() ?? Auth::guard('sanctum')->id();
return $userId === null ? null : (int) $userId;
}
} }

View File

@ -8,7 +8,6 @@ enum GroupLayout: string
case Simple = 'simple'; case Simple = 'simple';
case SimpleVertical = 'simple_vertical'; case SimpleVertical = 'simple_vertical';
case Carousel = 'carousel'; case Carousel = 'carousel';
case Single = 'single';
/** /**
* @return list<string> * @return list<string>

View File

@ -1,16 +0,0 @@
<?php
namespace App\Domains\Catalog\Enums;
enum InventorySubject: string
{
case Product = 'product';
case Seat = 'seat';
case Ticket = 'ticket';
/** @return array<int, string> */
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}

View File

@ -7,7 +7,6 @@ enum ProductLayout: string
case Row = 'row'; case Row = 'row';
case ColumnWithImage = 'column_with_image'; case ColumnWithImage = 'column_with_image';
case ColumnWithCart = 'column_with_cart'; case ColumnWithCart = 'column_with_cart';
case TicketSelector = 'ticket_selector';
/** /**
* @return list<string> * @return list<string>

View File

@ -1,13 +0,0 @@
<?php
namespace App\Domains\Catalog\Exceptions;
use RuntimeException;
class StockReservationExpiredException extends RuntimeException
{
public function __construct()
{
parent::__construct(__('api.cart.reservation_expired'));
}
}

View File

@ -5,10 +5,11 @@ namespace App\Domains\Catalog\Models;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Enums\CatalogItemType; use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Enums\InventorySubject;
use App\Domains\Catalog\Services\CatalogInventoryService; use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use App\Domains\Ticket\Models\Ticket; use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
@ -16,7 +17,6 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
#[Fillable([ #[Fillable([
@ -27,17 +27,17 @@ use Illuminate\Support\Collection;
'type', 'type',
'slug', 'slug',
'nombre', 'nombre',
'group_order',
'descripcion', 'descripcion',
'precio', 'precio',
'inventory_policy', 'inventory_policy',
'inventory_subject',
'max_units_per_user', 'max_units_per_user',
'has_tickets', 'has_tickets',
'ticket_generation_policy',
'validity_time_id',
])] ])]
class CatalogItem extends Model class CatalogItem extends Model
{ {
use HasFactory, SoftDeletes; use HasFactory;
public $timestamps = false; public $timestamps = false;
@ -46,9 +46,8 @@ class CatalogItem extends Model
protected $attributes = [ protected $attributes = [
'type' => CatalogItemType::Standard->value, 'type' => CatalogItemType::Standard->value,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'inventory_subject' => InventorySubject::Product->value,
'has_tickets' => false, 'has_tickets' => false,
'group_order' => 0, 'ticket_generation_policy' => TicketGenerationPolicy::PerEventDate->value,
]; ];
protected function casts(): array protected function casts(): array
@ -58,12 +57,12 @@ class CatalogItem extends Model
'brand_id' => 'integer', 'brand_id' => 'integer',
'inventory_id' => 'integer', 'inventory_id' => 'integer',
'type' => CatalogItemType::class, 'type' => CatalogItemType::class,
'group_order' => 'integer',
'precio' => 'decimal:2', 'precio' => 'decimal:2',
'inventory_policy' => InventoryPolicy::class, 'inventory_policy' => InventoryPolicy::class,
'inventory_subject' => InventorySubject::class,
'max_units_per_user' => 'integer', 'max_units_per_user' => 'integer',
'has_tickets' => 'boolean', 'has_tickets' => 'boolean',
'ticket_generation_policy' => TicketGenerationPolicy::class,
'validity_time_id' => 'integer',
]; ];
} }
@ -115,6 +114,12 @@ class CatalogItem extends Model
return $this->hasMany(Ticket::class, 'source_catalog_item_id'); 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> */ /** @return BelongsToMany<Attribute, $this> */
public function attributes(): BelongsToMany public function attributes(): BelongsToMany
{ {
@ -136,12 +141,6 @@ class CatalogItem extends Model
/** @return BelongsToMany<Attachment, $this> */ /** @return BelongsToMany<Attachment, $this> */
public function attachments(): BelongsToMany public function attachments(): BelongsToMany
{
return $this->allAttachments()->wherePivot('is_enabled', true);
}
/** @return BelongsToMany<Attachment, $this> */
public function allAttachments(): BelongsToMany
{ {
return $this->belongsToMany( return $this->belongsToMany(
Attachment::class, Attachment::class,
@ -149,7 +148,7 @@ class CatalogItem extends Model
'catalog_item_id', 'catalog_item_id',
'attachment_id' 'attachment_id'
) )
->withPivot(['orden', 'is_enabled']) ->withPivot('orden')
->wherePivotNull('variant_id') ->wherePivotNull('variant_id')
->orderByPivot('orden'); ->orderByPivot('orden');
} }
@ -175,29 +174,17 @@ class CatalogItem extends Model
} }
/** @param Builder<CatalogItem> $query */ /** @param Builder<CatalogItem> $query */
public function scopeWhereAvailable(Builder $query): Builder public function scopeWhereVariantsAvailable(Builder $query): Builder
{ {
return $query->where(function (Builder $query): void { return $query->where(function (Builder $query): void {
$query $query
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value) ->whereDoesntHave('variants')
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
->orWhereHas( ->orWhereHas(
'variants.inventory', 'variants.inventory',
fn (Builder $inventoryQuery): Builder => $inventoryQuery fn (Builder $inventoryQuery): Builder => $inventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock') ->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
) );
->orWhere(function (Builder $directItemQuery): void {
$directItemQuery
->whereDoesntHave('variants')
->where(function (Builder $inventoryQuery): void {
$inventoryQuery
->whereNull('catalog_items.inventory_id')
->orWhereHas(
'inventory',
fn (Builder $availableInventoryQuery): Builder => $availableInventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
);
});
});
}); });
} }
@ -221,11 +208,6 @@ class CatalogItem extends Model
return $this->nombre; return $this->nombre;
} }
public function getSelectionLabel(): string
{
return $this->getName();
}
public function getDescription(): ?string public function getDescription(): ?string
{ {
return $this->descripcion; return $this->descripcion;

View File

@ -15,7 +15,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'tenant_code', 'tenant_code',
'categoria_id', 'categoria_id',
'nombre', 'nombre',
'is_enabled',
])] ])]
class Category extends Model class Category extends Model
{ {
@ -23,10 +22,6 @@ class Category extends Model
protected $table = 'categorias'; protected $table = 'categorias';
protected $attributes = [
'is_enabled' => true,
];
/** /**
* @return array<string, string> * @return array<string, string>
*/ */
@ -34,7 +29,6 @@ class Category extends Model
{ {
return [ return [
'categoria_id' => 'integer', 'categoria_id' => 'integer',
'is_enabled' => 'boolean',
]; ];
} }

View File

@ -11,11 +11,9 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
#[Fillable([ #[Fillable([
'tenant_code', 'tenant_code',
'code',
'source_type', 'source_type',
'category_id', 'category_id',
'product_layout', 'product_layout',
@ -35,29 +33,6 @@ class FeaturedGroup extends Model
'source_type' => FeaturedGroupSource::Manual->value, 'source_type' => FeaturedGroupSource::Manual->value,
]; ];
protected static function booted(): void
{
static::creating(function (FeaturedGroup $featuredGroup): void {
if (filled($featuredGroup->code)) {
return;
}
$baseCode = Str::slug($featuredGroup->group_name) ?: 'group';
$code = $baseCode;
$suffix = 2;
while (static::query()
->where('tenant_code', $featuredGroup->tenant_code)
->where('code', $code)
->exists()) {
$code = "{$baseCode}-{$suffix}";
$suffix++;
}
$featuredGroup->code = $code;
});
}
protected function casts(): array protected function casts(): array
{ {
return [ return [

View File

@ -5,7 +5,6 @@ namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\HasOne;
#[Fillable([ #[Fillable([
@ -48,12 +47,6 @@ class Inventory extends Model
return $this->hasOne(Variant::class); return $this->hasOne(Variant::class);
} }
/** @return HasMany<StockReservationLine, $this> */
public function stockReservationLines(): HasMany
{
return $this->hasMany(StockReservationLine::class);
}
public function availableStock(): int public function availableStock(): int
{ {
return max(0, $this->real_stock - $this->reserved_stock); return max(0, $this->real_stock - $this->reserved_stock);

View File

@ -13,8 +13,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'attribute_id', 'attribute_id',
'allow_multi_select', 'allow_multi_select',
'sort_order', 'sort_order',
'show_in_selector',
'ticket_label',
])] ])]
class ItemAttribute extends Model class ItemAttribute extends Model
{ {
@ -22,10 +20,6 @@ class ItemAttribute extends Model
protected $table = 'item_attributes'; protected $table = 'item_attributes';
protected $attributes = [
'show_in_selector' => true,
];
protected function casts(): array protected function casts(): array
{ {
return [ return [
@ -33,7 +27,6 @@ class ItemAttribute extends Model
'attribute_id' => 'integer', 'attribute_id' => 'integer',
'allow_multi_select' => 'boolean', 'allow_multi_select' => 'boolean',
'sort_order' => 'integer', 'sort_order' => 'integer',
'show_in_selector' => 'boolean',
]; ];
} }

View File

@ -1,57 +0,0 @@
<?php
namespace App\Domains\Catalog\Models;
use App\Domains\Cart\Models\Cart;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
#[Fillable([
'status',
'expires_at',
'committed_at',
'released_at',
'expired_at',
'release_reason',
])]
class StockReservation extends Model
{
public const STATUS_ACTIVE = 'active';
public const STATUS_COMMITTED = 'committed';
public const STATUS_RELEASED = 'released';
public const STATUS_EXPIRED = 'expired';
protected function casts(): array
{
return [
'expires_at' => 'datetime',
'committed_at' => 'datetime',
'released_at' => 'datetime',
'expired_at' => 'datetime',
];
}
/** @return HasMany<StockReservationLine, $this> */
public function lines(): HasMany
{
return $this->hasMany(StockReservationLine::class);
}
/** @return HasOne<Cart, $this> */
public function currentCart(): HasOne
{
return $this->hasOne(Cart::class, 'current_stock_reservation_id');
}
/** @return HasOne<Purchase, $this> */
public function purchase(): HasOne
{
return $this->hasOne(Purchase::class);
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'stock_reservation_id',
'inventory_id',
'quantity',
'tracks_inventory',
])]
class StockReservationLine extends Model
{
protected function casts(): array
{
return [
'stock_reservation_id' => 'integer',
'inventory_id' => 'integer',
'quantity' => 'integer',
'tracks_inventory' => 'boolean',
];
}
/** @return BelongsTo<StockReservation, $this> */
public function reservation(): BelongsTo
{
return $this->belongsTo(StockReservation::class, 'stock_reservation_id');
}
/** @return BelongsTo<Inventory, $this> */
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
}

View File

@ -11,10 +11,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Str;
#[Fillable([ #[Fillable([
'catalog_item_id', 'catalog_item_id',
@ -25,7 +22,7 @@ use Illuminate\Support\Str;
])] ])]
class Variant extends Model class Variant extends Model
{ {
use HasFactory, SoftDeletes; use HasFactory;
public $timestamps = false; public $timestamps = false;
@ -44,7 +41,7 @@ class Variant extends Model
/** @return BelongsTo<CatalogItem, $this> */ /** @return BelongsTo<CatalogItem, $this> */
public function catalogItem(): BelongsTo public function catalogItem(): BelongsTo
{ {
return $this->belongsTo(CatalogItem::class)->withTrashed(); return $this->belongsTo(CatalogItem::class);
} }
/** @return BelongsTo<EventDate, $this> */ /** @return BelongsTo<EventDate, $this> */
@ -84,12 +81,6 @@ class Variant extends Model
/** @return BelongsToMany<Attachment, $this> */ /** @return BelongsToMany<Attachment, $this> */
public function attachments(): BelongsToMany public function attachments(): BelongsToMany
{
return $this->allAttachments()->wherePivot('is_enabled', true);
}
/** @return BelongsToMany<Attachment, $this> */
public function allAttachments(): BelongsToMany
{ {
$relation = $this->belongsToMany( $relation = $this->belongsToMany(
Attachment::class, Attachment::class,
@ -97,7 +88,7 @@ class Variant extends Model
'variant_id', 'variant_id',
'attachment_id' 'attachment_id'
) )
->withPivot(['orden', 'is_enabled']) ->withPivot('orden')
->orderByPivot('orden'); ->orderByPivot('orden');
if ($this->catalog_item_id !== null) { if ($this->catalog_item_id !== null) {
@ -122,42 +113,6 @@ class Variant extends Model
return $this->catalogItem->nombre; return $this->catalogItem->nombre;
} }
public function getSelectionLabel(): string
{
$this->loadMissing([
'catalogItem.itemAttributes.attribute.options',
'definitions.itemAttribute.attribute.options',
'eventDates',
'eventDate',
]);
$itemAttributes = $this->catalogItem->itemAttributes;
$label = $this->selectionOptions($itemAttributes)
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
$itemAttribute = $itemAttributes->first(
fn (ItemAttribute $candidate): bool => $candidate->attribute?->codigo === $attributeCode,
);
$translationKey = "api.catalog.attribute_labels.{$attributeCode}";
$attributeName = Lang::has($translationKey)
? __($translationKey)
: ($itemAttribute?->attribute?->nombre ?? Str::headline($attributeCode));
$selectedOptions = array_is_list($option) ? $option : [$option];
$selectedLabels = collect($selectedOptions)
->pluck('label')
->filter()
->implode(', ');
return $selectedLabels === ''
? null
: "{$attributeName} {$selectedLabels}";
})
->filter()
->implode(' · ');
return $label !== '' ? $label : $this->getName();
}
/** @return Collection<string, string|array<int, string>> */ /** @return Collection<string, string|array<int, string>> */
public function selectionValues(): Collection public function selectionValues(): Collection
{ {
@ -275,25 +230,6 @@ class Variant extends Model
}); });
} }
/**
* @param Collection<int, ItemAttribute> $itemAttributes
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
*/
public function selectorOptions(Collection $itemAttributes): Collection
{
$visibleAttributeCodes = $itemAttributes
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->show_in_selector)
->map(fn (ItemAttribute $itemAttribute): ?string => $itemAttribute->attribute?->codigo)
->filter()
->values();
return $this->selectionOptions($itemAttributes)
->filter(
fn (array $option, string $attributeCode): bool => $visibleAttributeCodes
->contains($attributeCode)
);
}
/** @return Collection<int, EventDate> */ /** @return Collection<int, EventDate> */
public function selectedEventDates(): Collection public function selectedEventDates(): Collection
{ {

View File

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

View File

@ -4,8 +4,8 @@ namespace App\Domains\Catalog\Requests;
use App\Domains\Catalog\Enums\CatalogItemType; use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Enums\InventorySubject;
use App\Domains\Shared\Rules\ImageOrBase64Rule; use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
@ -51,13 +51,13 @@ class StoreCatalogItemRequest extends FormRequest
), ),
], ],
'nombre' => ['required', 'string', 'max:255'], 'nombre' => ['required', 'string', 'max:255'],
'group_order' => ['sometimes', 'integer', 'min:0'],
'descripcion' => ['sometimes', 'nullable', 'string'], 'descripcion' => ['sometimes', 'nullable', 'string'],
'precio' => ['required', 'numeric', 'min:0'], 'precio' => ['required', 'numeric', 'min:0'],
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)], 'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],
'inventory_subject' => ['sometimes', Rule::enum(InventorySubject::class)],
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'], 'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'], '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'], 'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
'inventory_id' => ['prohibited'], 'inventory_id' => ['prohibited'],
'reserved_stock' => ['prohibited'], 'reserved_stock' => ['prohibited'],
@ -80,15 +80,6 @@ class StoreCatalogItemRequest extends FormRequest
fn ($query) => $query->where('tenant_codigo', $tenantCode) fn ($query) => $query->where('tenant_codigo', $tenantCode)
), ),
], ],
'hidden_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
'hidden_attribute_codes.*' => [
'required',
'string',
'distinct',
Rule::exists('attribute', 'codigo')->where(
fn ($query) => $query->where('tenant_codigo', $tenantCode)
),
],
'images' => ['sometimes', 'array'], 'images' => ['sometimes', 'array'],
'images.*' => ['required', new ImageOrBase64Rule], 'images.*' => ['required', new ImageOrBase64Rule],
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'], 'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],

View File

@ -15,7 +15,6 @@ class OnTicketFeaturedGroupResource extends JsonResource
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'code' => $this->code,
'category_id' => $this->category_id, 'category_id' => $this->category_id,
'category_name' => $this->category->nombre, 'category_name' => $this->category->nombre,
'group_name' => $this->group_name, 'group_name' => $this->group_name,

View File

@ -20,7 +20,6 @@ class CatalogFeaturedGroupResource extends JsonResource
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'code' => $this->code,
'title' => $this->group_name, 'title' => $this->group_name,
'layout' => $this->product_layout->value, 'layout' => $this->product_layout->value,
'group_layout' => $this->group_layout->value, 'group_layout' => $this->group_layout->value,

View File

@ -7,7 +7,7 @@ use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\FeaturedGroup; use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService; use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@ -25,112 +25,51 @@ class CatalogFeaturedItemResource extends JsonResource
return $this->columnWithImageData($catalogItem); return $this->columnWithImageData($catalogItem);
} }
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
return $this->ticketSelectorData($catalogItem);
}
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
$availableStock = $catalogItem->availableStock();
$data = [
'id' => $catalogItem->id,
'type' => $catalogItem->type->value,
'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio,
'maximum_addable_quantity' => $this->maximumAddable(
$availableStock,
$remainingUserQuota,
),
'unavailable_message' => $this->unavailableMessage(
$availableStock,
$remainingUserQuota,
),
'variants' => $catalogItem->visibleVariants()
->map(function (Variant $variant) use ($catalogItem, $remainingUserQuota): array {
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock();
return [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable(
$variantStock,
$remainingUserQuota,
),
'unavailable_message' => $this->unavailableMessage(
$variantStock,
$remainingUserQuota,
),
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
];
})
->values(),
];
return $data;
}
/** @return array<string, mixed> */
private function ticketSelectorData(CatalogItem $catalogItem): array
{
$availableStock = $catalogItem->availableStock();
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
return [ return [
'id' => $catalogItem->id, 'id' => $catalogItem->id,
'type' => $catalogItem->type->value, 'type' => $catalogItem->type->value,
'nombre' => $catalogItem->nombre, 'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion, 'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem), 'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota), 'validity_time_id' => $catalogItem->validity_time_id,
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota), 'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
'stock_tecnico' => $catalogItem->availableStock(),
'variants' => $catalogItem->visibleVariants()
->map(fn (Variant $variant): array => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectionOptions($catalogItem->itemAttributes),
])
->values(),
]; ];
} }
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function columnWithImageData(CatalogItem $catalogItem): array private function columnWithImageData(CatalogItem $catalogItem): array
{ {
$availableStock = $catalogItem->availableStock(); $attachment = $catalogItem->attachments->first()
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota'); ?? $catalogItem->variants
->flatMap(fn (Variant $variant) => $variant->attachments)
->first();
return [ return [
'id' => $catalogItem->id, 'id' => $catalogItem->id,
'type' => $catalogItem->type->value, 'type' => $catalogItem->type->value,
'nombre' => $catalogItem->nombre, 'nombre' => $catalogItem->nombre,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'image' => $this->firstImageUrl($catalogItem), 'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
'maximum_addable_quantity' => $this->maximumAddable($availableStock, $remainingUserQuota), 'validity_time_id' => $catalogItem->validity_time_id,
'unavailable_message' => $this->unavailableMessage($availableStock, $remainingUserQuota), 'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
'image' => $attachment?->getTemporaryUrl(1440),
]; ];
} }
private function firstImageUrl(CatalogItem $catalogItem): ?string
{
$attachment = $catalogItem->attachments->first()
?? $catalogItem->visibleVariants()
->flatMap(fn (Variant $variant) => $variant->attachments)
->first();
return $attachment?->getTemporaryUrl(1440);
}
private function maximumAddable(?int $stock, ?int $remainingUserQuota): ?int
{
return app(CatalogItemAllowanceService::class)
->maximumAddableQuantity($stock, $remainingUserQuota);
}
private function unavailableMessage(?int $stock, ?int $remainingUserQuota): ?string
{
return app(CatalogItemAllowanceService::class)
->unavailableMessage($stock, $remainingUserQuota);
}
} }

View File

@ -6,7 +6,6 @@ use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\ItemAttribute; use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use App\Domains\Shared\Enums\FieldType; use App\Domains\Shared\Enums\FieldType;
use App\Domains\Ticket\Resources\ValidityTimeResource; use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@ -34,23 +33,23 @@ class CatalogItemDetailResource extends JsonResource
'category' => $this->category?->nombre, 'category' => $this->category?->nombre,
'brand' => $this->brand?->nombre, 'brand' => $this->brand?->nombre,
'inventory_policy' => $this->inventory_policy?->value, 'inventory_policy' => $this->inventory_policy?->value,
'inventory_subject' => $this->inventory_subject->value,
'max_units_per_user' => $this->max_units_per_user, 'max_units_per_user' => $this->max_units_per_user,
'has_tickets' => $this->has_tickets, '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(), 'attributes' => $this->attributesData(),
'maximum_addable_quantity' => $this->when( 'stock_tecnico' => $this->when(
$selectedVariant === null, $selectedVariant === null,
fn () => $this->maximumAddable($this->availableStock()), fn () => $this->availableStock(),
),
'unavailable_message' => $this->when(
$selectedVariant === null,
fn () => $this->unavailableMessage($this->availableStock()),
), ),
'images' => $this->when( 'images' => $this->when(
$selectedVariant === null, $selectedVariant === null,
fn () => $this->imageUrls($this->attachments), fn () => $this->imageUrls($this->attachments),
), ),
'variants' => $this->variants 'variants' => $this->visibleVariants()
->map(fn (Variant $variant): array => $this->variantData($variant)) ->map(fn (Variant $variant): array => $this->variantData($variant))
->values(), ->values(),
'selected_variant' => $this->when( 'selected_variant' => $this->when(
@ -89,8 +88,6 @@ class CatalogItemDetailResource extends JsonResource
'codigo' => $attribute->codigo, 'codigo' => $attribute->codigo,
'nombre' => $attribute->nombre, 'nombre' => $attribute->nombre,
'sort_order' => $itemAttribute->sort_order, 'sort_order' => $itemAttribute->sort_order,
'show_in_selector' => $itemAttribute->show_in_selector,
'ticket_label' => $itemAttribute->ticket_label,
'is_required' => $attribute->is_required, 'is_required' => $attribute->is_required,
'allow_multi_select' => $itemAttribute->allow_multi_select, 'allow_multi_select' => $itemAttribute->allow_multi_select,
'metadata_schema' => $attribute->metadata_schema, 'metadata_schema' => $attribute->metadata_schema,
@ -163,7 +160,6 @@ class CatalogItemDetailResource extends JsonResource
{ {
$values = $variant->selectionOptions($this->itemAttributes); $values = $variant->selectionOptions($this->itemAttributes);
$eventDates = $variant->selectedEventDates(); $eventDates = $variant->selectedEventDates();
$variantStock = $this->variantStock($variant);
return [ return [
'id' => $variant->id, 'id' => $variant->id,
@ -173,8 +169,7 @@ class CatalogItemDetailResource extends JsonResource
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), 'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable($variantStock), 'stock_tecnico' => $this->variantStock($variant),
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $values, 'values' => $values,
]; ];
} }
@ -193,20 +188,4 @@ class CatalogItemDetailResource extends JsonResource
? null ? null
: $variant->inventory->availableStock(); : $variant->inventory->availableStock();
} }
private function maximumAddable(?int $stock): ?int
{
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
} }

View File

@ -3,6 +3,7 @@
namespace App\Domains\Catalog\Resources; namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@ -22,9 +23,14 @@ class CatalogItemResource extends JsonResource
'descripcion' => $this->descripcion, 'descripcion' => $this->descripcion,
'precio' => $this->precio, 'precio' => $this->precio,
'inventory_policy' => $this->inventory_policy?->value, 'inventory_policy' => $this->inventory_policy?->value,
'inventory_subject' => $this->inventory_subject->value,
'max_units_per_user' => $this->max_units_per_user, 'max_units_per_user' => $this->max_units_per_user,
'has_tickets' => $this->has_tickets, '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), 'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
'images' => $this->whenLoaded('attachments', fn () => $this->attachments 'images' => $this->whenLoaded('attachments', fn () => $this->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440)) ->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
@ -39,7 +45,7 @@ class CatalogItemResource extends JsonResource
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'real_stock' => $variant->inventory?->real_stock, 'real_stock' => $variant->inventory?->real_stock,
'values' => $variant->selectorOptions($this->itemAttributes), 'values' => $variant->selectionOptions($this->itemAttributes),
'images' => $variant->attachments 'images' => $variant->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440)) ->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values(), ->values(),

View File

@ -5,7 +5,7 @@ namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService; use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@ -15,10 +15,8 @@ class CatalogSearchItemResource extends JsonResource
/** @return array<string, mixed> */ /** @return array<string, mixed> */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$availableStock = $this->availableStock();
$visibleVariants = $this->visibleVariants();
$attachment = $this->attachments->first() $attachment = $this->attachments->first()
?? $visibleVariants ?? $this->variants
->flatMap(fn (Variant $variant) => $variant->attachments) ->flatMap(fn (Variant $variant) => $variant->attachments)
->first(); ->first();
@ -28,45 +26,26 @@ class CatalogSearchItemResource extends JsonResource
'nombre' => $this->nombre, 'nombre' => $this->nombre,
'descripcion' => $this->descripcion, 'descripcion' => $this->descripcion,
'precio' => $this->precio, '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), 'image' => $attachment?->getTemporaryUrl(1440),
'maximum_addable_quantity' => $this->maximumAddable($availableStock), 'stock_tecnico' => $this->availableStock(),
'unavailable_message' => $this->unavailableMessage($availableStock), 'variants' => $this->visibleVariants()
'variants' => $visibleVariants ->map(fn (Variant $variant): array => [
->map(function (Variant $variant): array { 'id' => $variant->id,
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited 'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
? null ? null
: $variant->inventory?->availableStock(); : $variant->inventory?->availableStock(),
'values' => $variant->selectionOptions($this->itemAttributes),
return [ ])
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'maximum_addable_quantity' => $this->maximumAddable($variantStock),
'unavailable_message' => $this->unavailableMessage($variantStock),
'values' => $variant->selectorOptions($this->itemAttributes),
];
})
->values(), ->values(),
]; ];
} }
private function maximumAddable(?int $stock): ?int
{
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
private function unavailableMessage(?int $stock): ?string
{
return app(CatalogItemAllowanceService::class)->unavailableMessage(
$stock,
$this->getAttribute('remaining_user_quota'),
);
}
} }

View File

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

View File

@ -12,37 +12,6 @@ use Illuminate\Support\Facades\DB;
class CatalogInventoryService class CatalogInventoryService
{ {
/** @return array<int, int> */
public function requirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
{
if ($quantity <= 0) {
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
}
return array_map(
fn (array $requirement): int => $requirement['quantity'] * $quantity,
$this->inventoryRequirements($selection),
);
}
/**
* @return array<int, array{quantity: int, tracks_inventory: bool}>
*/
public function detailedRequirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
{
if ($quantity <= 0) {
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
}
return array_map(
fn (array $requirement): array => [
...$requirement,
'quantity' => $requirement['quantity'] * $quantity,
],
$this->inventoryRequirements($selection),
);
}
public function availableQuantity(CatalogItem|Variant $selection): ?int public function availableQuantity(CatalogItem|Variant $selection): ?int
{ {
if ($selection instanceof CatalogItem if ($selection instanceof CatalogItem

View File

@ -1,57 +0,0 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
use Illuminate\Support\Collection;
class CatalogItemAllowanceService
{
private const USER_QUOTA_REACHED_MESSAGE = 'Alcanzaste el cupo máximo permitido para este producto.';
private const OUT_OF_STOCK_MESSAGE = 'Este producto no tiene stock disponible.';
public function __construct(
private readonly UserPurchaseLimitService $purchaseLimits,
) {}
/** @param Collection<int, CatalogItem> $catalogItems */
public function attach(Collection $catalogItems, ?int $userId): void
{
$remaining = $this->purchaseLimits->remainingByCatalogItem($catalogItems, $userId);
foreach ($catalogItems as $catalogItem) {
$catalogItem->setAttribute(
'remaining_user_quota',
$remaining->get($catalogItem->getKey()),
);
}
}
public function maximumAddableQuantity(?int $availableStock, ?int $remainingUserQuota): ?int
{
if ($availableStock === null) {
return $remainingUserQuota;
}
if ($remainingUserQuota === null) {
return $availableStock;
}
return min($availableStock, $remainingUserQuota);
}
public function unavailableMessage(?int $availableStock, ?int $remainingUserQuota): ?string
{
if ($remainingUserQuota !== null && $remainingUserQuota <= 0) {
return self::USER_QUOTA_REACHED_MESSAGE;
}
if ($availableStock !== null && $availableStock <= 0) {
return self::OUT_OF_STOCK_MESSAGE;
}
return null;
}
}

View File

@ -37,8 +37,6 @@ class CatalogService
$images = $data['images'] ?? []; $images = $data['images'] ?? [];
$attributeCodes = $data['attribute_codes'] ?? []; $attributeCodes = $data['attribute_codes'] ?? [];
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? []; $multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
$hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? [];
$ticketAttributeLabels = $data['ticket_attribute_labels'] ?? [];
$components = $data['components'] ?? []; $components = $data['components'] ?? [];
$hasDirectStock = array_key_exists('real_stock', $data); $hasDirectStock = array_key_exists('real_stock', $data);
$realStock = (int) ($data['real_stock'] ?? 0); $realStock = (int) ($data['real_stock'] ?? 0);
@ -66,22 +64,6 @@ class CatalogService
]); ]);
} }
if (array_diff($hiddenAttributeCodes, $attributeCodes) !== []) {
throw ValidationException::withMessages([
'hidden_attribute_codes' => [
__('api.catalog.hidden_attribute_not_on_item'),
],
]);
}
if (array_diff(array_keys($ticketAttributeLabels), $attributeCodes) !== []) {
throw ValidationException::withMessages([
'ticket_attribute_labels' => [
__('api.catalog.ticket_label_attribute_not_on_item'),
],
]);
}
$this->validateUniqueVariantCombinations($variants, $attributeCodes); $this->validateUniqueVariantCombinations($variants, $attributeCodes);
if ($type === CatalogItemType::Bundle) { if ($type === CatalogItemType::Bundle) {
@ -106,8 +88,6 @@ class CatalogService
$data['images'], $data['images'],
$data['attribute_codes'], $data['attribute_codes'],
$data['multi_select_attribute_codes'], $data['multi_select_attribute_codes'],
$data['hidden_attribute_codes'],
$data['ticket_attribute_labels'],
$data['components'], $data['components'],
$data['real_stock'], $data['real_stock'],
$data['reserved_stock'], $data['reserved_stock'],
@ -129,13 +109,7 @@ class CatalogService
$catalogItem = CatalogItem::query()->create($data); $catalogItem = CatalogItem::query()->create($data);
$itemAttributes = $type === CatalogItemType::Standard $itemAttributes = $type === CatalogItemType::Standard
? $this->createItemAttributes( ? $this->createItemAttributes($catalogItem, $attributeCodes, $multiSelectAttributeCodes)
$catalogItem,
$attributeCodes,
$multiSelectAttributeCodes,
$hiddenAttributeCodes,
$ticketAttributeLabels,
)
: []; : [];
if ($type === CatalogItemType::Bundle) { if ($type === CatalogItemType::Bundle) {
@ -171,6 +145,7 @@ class CatalogService
'inventory', 'inventory',
'category', 'category',
'brand', 'brand',
'validityTime',
'itemAttributes.attribute', 'itemAttributes.attribute',
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
@ -190,6 +165,7 @@ class CatalogService
'inventory', 'inventory',
'category', 'category',
'brand', 'brand',
'validityTime',
'itemAttributes.attribute.options.validityTime', 'itemAttributes.attribute.options.validityTime',
'itemAttributes.attribute.eventDates.validityTime', 'itemAttributes.attribute.eventDates.validityTime',
'variants' => fn ($query) => $query->orderBy('id'), 'variants' => fn ($query) => $query->orderBy('id'),
@ -205,13 +181,6 @@ class CatalogService
]); ]);
$visibleVariants = $catalogItem->visibleVariants(); $visibleVariants = $catalogItem->visibleVariants();
if ($catalogItem->type === CatalogItemType::Standard
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
&& ! $catalogItem->isAvailable()) {
throw new NotFoundHttpException('Catalog item is out of stock.');
}
$catalogItem->setRelation('variants', $visibleVariants);
$selectedVariant = $variantId === null $selectedVariant = $variantId === null
? $visibleVariants->first() ? $visibleVariants->first()
: $visibleVariants->firstWhere('id', $variantId); : $visibleVariants->firstWhere('id', $variantId);
@ -238,7 +207,7 @@ class CatalogService
$paginator = CatalogItem::query() $paginator = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->whereAvailable() ->whereVariantsAvailable()
->where(function (Builder $query) use ($containsPattern): void { ->where(function (Builder $query) use ($containsPattern): void {
$query $query
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern]) ->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
@ -257,6 +226,7 @@ class CatalogService
->with([ ->with([
'attachments', 'attachments',
'inventory', 'inventory',
'validityTime',
'itemAttributes.attribute', 'itemAttributes.attribute',
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
@ -288,10 +258,11 @@ class CatalogService
return CatalogItem::query() return CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('category_id', $category->id) ->where('category_id', $category->id)
->whereAvailable() ->whereVariantsAvailable()
->with([ ->with([
'attachments', 'attachments',
'inventory', 'inventory',
'validityTime',
'itemAttributes.attribute', 'itemAttributes.attribute',
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
@ -308,8 +279,32 @@ class CatalogService
public function delete(CatalogItem $catalogItem): void public function delete(CatalogItem $catalogItem): void
{ {
DB::transaction(function () use ($catalogItem): void { DB::transaction(function () use ($catalogItem): void {
$catalogItem->variants()->delete(); $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->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);
}
}
}); });
} }
@ -317,19 +312,32 @@ class CatalogService
{ {
DB::transaction(function () use ($variant): void { DB::transaction(function () use ($variant): void {
$variant = Variant::query() $variant = Variant::query()
->with('attachments')
->lockForUpdate() ->lockForUpdate()
->findOrFail($variant->getKey()); ->findOrFail($variant->getKey());
$catalogItem = CatalogItem::query() $catalogItem = CatalogItem::query()
->lockForUpdate() ->lockForUpdate()
->findOrFail($variant->catalog_item_id); ->findOrFail($variant->catalog_item_id);
$variant->delete(); $attachments = $variant->attachments;
$inventoryId = $variant->inventory_id;
if (! $catalogItem->variants()->exists()) { $variant->attachments()->detach();
$variant->delete();
Inventory::query()->whereKey($inventoryId)->delete();
$minimumPrice = $catalogItem->variants()->min('precio');
if ($minimumPrice === null) {
$this->delete($catalogItem); $this->delete($catalogItem);
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) { } else {
$catalogItem->update(['precio' => $minimumPrice]); $catalogItem->update(['precio' => $minimumPrice]);
} }
foreach ($attachments as $attachment) {
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
$this->attachmentService->delete($attachment);
}
}
}); });
} }
@ -434,6 +442,8 @@ class CatalogService
'attribute_codes', 'attribute_codes',
'variants', 'variants',
'has_tickets', 'has_tickets',
'ticket_generation_policy',
'validity_time_id',
] as $field) { ] as $field) {
if (array_key_exists($field, $data)) { if (array_key_exists($field, $data)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@ -478,16 +488,12 @@ class CatalogService
/** /**
* @param array<int, string> $attributeCodes * @param array<int, string> $attributeCodes
* @param array<int, string> $multiSelectAttributeCodes * @param array<int, string> $multiSelectAttributeCodes
* @param array<int, string> $hiddenAttributeCodes
* @param array<string, string> $ticketAttributeLabels
* @return array<string, ItemAttribute> * @return array<string, ItemAttribute>
*/ */
private function createItemAttributes( private function createItemAttributes(
CatalogItem $catalogItem, CatalogItem $catalogItem,
array $attributeCodes, array $attributeCodes,
array $multiSelectAttributeCodes = [], array $multiSelectAttributeCodes = [],
array $hiddenAttributeCodes = [],
array $ticketAttributeLabels = [],
): array { ): array {
$itemAttributes = []; $itemAttributes = [];
$attributeCodes = array_values(array_unique($attributeCodes)); $attributeCodes = array_values(array_unique($attributeCodes));
@ -511,8 +517,6 @@ class CatalogService
$itemAttribute = $catalogItem->itemAttributes()->create([ $itemAttribute = $catalogItem->itemAttributes()->create([
'attribute_id' => $attribute->id, 'attribute_id' => $attribute->id,
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true), 'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
'ticket_label' => $ticketAttributeLabels[$attributeCode] ?? null,
]); ]);
$itemAttributes[$attributeCode] = $itemAttribute; $itemAttributes[$attributeCode] = $itemAttribute;
@ -709,6 +713,16 @@ 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(); return $resolvedOptions->pluck('value')->all();
} }

View File

@ -1,185 +0,0 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;
class ExpireStockReservationsService
{
private const BATCH_SIZE = 500;
public function __construct(
private readonly ReleaseCheckoutService $purchases,
private readonly StockReservationService $reservations,
) {}
/**
* @return array{purchases: int, cart_reservations: int, orphan_reservations: int, failed: int}
*/
public function expireOverdue(): array
{
$summary = [
'purchases' => 0,
'cart_reservations' => 0,
'orphan_reservations' => 0,
'failed' => 0,
];
$lastReservationId = 0;
do {
$reservationIds = StockReservation::query()
->where('status', StockReservation::STATUS_ACTIVE)
->whereNotNull('expires_at')
->where('expires_at', '<=', now())
->where('id', '>', $lastReservationId)
->orderBy('id')
->limit(self::BATCH_SIZE)
->pluck('id');
foreach ($reservationIds as $reservationId) {
$lastReservationId = (int) $reservationId;
try {
$owner = $this->expireReservation($lastReservationId);
if ($owner !== null) {
$summary[$owner]++;
}
} catch (Throwable $exception) {
$summary['failed']++;
Log::channel('commands')->error('Failed to expire overdue stock reservation.', [
'command' => 'reservations:expire',
'stock_reservation_id' => $lastReservationId,
'exception' => $exception,
]);
}
}
} while ($reservationIds->count() === self::BATCH_SIZE);
Log::channel('commands')->info('Stock reservation cleanup completed.', [
'command' => 'reservations:expire',
'expired_purchases' => $summary['purchases'],
'expired_cart_reservations' => $summary['cart_reservations'],
'expired_orphan_reservations' => $summary['orphan_reservations'],
'failed_reservations' => $summary['failed'],
'total_expired' => $summary['purchases']
+ $summary['cart_reservations']
+ $summary['orphan_reservations'],
]);
return $summary;
}
public function expireIfOverdue(int $reservationId): bool
{
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->find($reservationId);
if ($reservation?->status === StockReservation::STATUS_EXPIRED) {
return true;
}
if (! $this->isOverdue($reservation)) {
return false;
}
return $this->expireReservation($reservationId) !== null;
}
/** @return 'purchases'|'cart_reservations'|'orphan_reservations'|null */
private function expireReservation(int $reservationId): ?string
{
$purchaseId = Purchase::query()
->where('stock_reservation_id', $reservationId)
->value('id');
if ($purchaseId !== null) {
return $this->expirePurchase((int) $purchaseId);
}
$cartId = Cart::query()
->where('current_stock_reservation_id', $reservationId)
->where('status', 'active')
->value('id');
if ($cartId !== null) {
return $this->expireCart((int) $cartId, $reservationId);
}
return $this->expireOrphan($reservationId);
}
/** @return 'purchases'|null */
private function expirePurchase(int $purchaseId): ?string
{
/** @var Purchase|null $purchase */
$purchase = Purchase::query()->find($purchaseId);
if ($purchase === null) {
return null;
}
$purchase = $this->purchases->expire($purchase);
if ($purchase->status === Purchase::STATUS_EXPIRED) {
return 'purchases';
}
$reservation = $purchase->stockReservation;
if ($this->isOverdue($reservation)) {
throw new RuntimeException('An overdue active reservation belongs to a purchase that cannot expire.');
}
return null;
}
/** @return 'cart_reservations'|null */
private function expireCart(int $cartId, int $reservationId): ?string
{
return DB::transaction(function () use ($cartId, $reservationId): ?string {
/** @var Cart|null $cart */
$cart = Cart::query()
->whereKey($cartId)
->where('current_stock_reservation_id', $reservationId)
->where('status', Cart::STATUS_ACTIVE)
->lockForUpdate()
->first();
if ($cart === null) {
return null;
}
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->lockForUpdate()->find($reservationId);
if (! $this->isOverdue($reservation)) {
return null;
}
$this->reservations->expire($reservation);
$cart->update(['status' => Cart::STATUS_EXPIRED]);
return 'cart_reservations';
});
}
/** @return 'orphan_reservations'|null */
private function expireOrphan(int $reservationId): ?string
{
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->find($reservationId);
if (! $this->isOverdue($reservation)) {
return null;
}
$this->reservations->expire($reservation);
return 'orphan_reservations';
}
private function isOverdue(?StockReservation $reservation): bool
{
return $reservation !== null
&& $reservation->status === StockReservation::STATUS_ACTIVE
&& $reservation->expires_at !== null
&& ! $reservation->expires_at->isFuture();
}
}

View File

@ -15,29 +15,17 @@ class FeaturedGroupService
private const ITEMS_PER_PAGE = 12; private const ITEMS_PER_PAGE = 12;
/** @return array<array-key, mixed> */ /** @return array<array-key, mixed> */
public function __construct( public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
private readonly CatalogItemAllowanceService $allowances,
) {}
public function itemsResponse(FeaturedGroup $featuredGroup, int $page, ?int $userId = null): array
{ {
if ($featuredGroup->group_layout !== GroupLayout::Paginated) { if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
$query = $this->itemsQuery($featuredGroup); $items = $this->itemsQuery($featuredGroup)->get();
if ($featuredGroup->group_layout === GroupLayout::Single) {
$query->limit(1);
}
$items = $query->get();
$this->attachGroup($items, $featuredGroup); $this->attachGroup($items, $featuredGroup);
$this->allowances->attach($items, $userId);
return CatalogFeaturedItemResource::collection($items)->resolve(); return CatalogFeaturedItemResource::collection($items)->resolve();
} }
$paginator = $this->paginateItems($featuredGroup, $page); $paginator = $this->paginateItems($featuredGroup, $page);
$this->attachGroup($paginator->getCollection(), $featuredGroup); $this->attachGroup($paginator->getCollection(), $featuredGroup);
$this->allowances->attach($paginator->getCollection(), $userId);
return CatalogFeaturedItemResource::collection($paginator) return CatalogFeaturedItemResource::collection($paginator)
->response() ->response()
@ -49,19 +37,11 @@ class FeaturedGroupService
{ {
$query = CatalogItem::query() $query = CatalogItem::query()
->where('catalog_items.tenant_code', $featuredGroup->tenant_code) ->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
->whereAvailable() ->whereVariantsAvailable()
->where(function (Builder $query): void {
$query
->whereDoesntHave('category')
->orWhereHas(
'category',
fn (Builder $categoryQuery): Builder => $categoryQuery
->where('is_enabled', true),
);
})
->with([ ->with([
'inventory', 'inventory',
'attachments', 'attachments',
'validityTime',
'itemAttributes.attribute', 'itemAttributes.attribute',
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
@ -82,9 +62,7 @@ class FeaturedGroupService
FeaturedGroupSource::Category => $query FeaturedGroupSource::Category => $query
->where('catalog_items.category_id', $featuredGroup->category_id) ->where('catalog_items.category_id', $featuredGroup->category_id)
->orderBy('catalog_items.id'), ->orderBy('catalog_items.id'),
FeaturedGroupSource::All => $query FeaturedGroupSource::All => $query->orderBy('catalog_items.id'),
->orderBy('catalog_items.group_order')
->orderBy('catalog_items.id'),
}; };
} }

View File

@ -1,493 +0,0 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\StockReservationLine;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class StockReservationService
{
public const REASON_CART_EMPTY = 'cart_empty';
public const REASON_CART_CHANGED = 'cart_changed';
public const REASON_PURCHASE_SUPERSEDED = 'purchase_superseded';
public const REASON_PURCHASE_CANCELLED = 'purchase_cancelled';
public const REASON_PAYMENT_REJECTED = 'payment_rejected';
public const REASON_MANUAL_RELEASE = 'manual_release';
public function __construct(
private readonly CatalogInventoryService $inventory,
) {}
public function syncCart(Cart $cart): ?StockReservation
{
return DB::transaction(function () use ($cart): ?StockReservation {
/** @var Cart $lockedCart */
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
$items = $lockedCart->items()->orderBy('id')->lockForUpdate()->get();
$this->loadSelections($items);
$requirements = $this->requirementsForItems($items);
$reservation = $lockedCart->current_stock_reservation_id === null
? null
: StockReservation::query()->lockForUpdate()->find($lockedCart->current_stock_reservation_id);
if ($reservation !== null) {
$this->assertUsableCartReservation($reservation);
}
if ($requirements === []) {
if ($reservation !== null && $reservation->status === StockReservation::STATUS_ACTIVE) {
$this->finalizeLocked(
$reservation,
StockReservation::STATUS_RELEASED,
self::REASON_CART_EMPTY,
);
}
$lockedCart->update(['current_stock_reservation_id' => null]);
$cart->current_stock_reservation_id = null;
return null;
}
if ($reservation === null) {
$reservation = StockReservation::query()->create([
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
$lockedCart->update(['current_stock_reservation_id' => $reservation->getKey()]);
}
if (Purchase::query()->where('stock_reservation_id', $reservation->getKey())->exists()) {
throw new \InvalidArgumentException('La reserva vinculada a una compra no se puede modificar.');
}
$currentLines = StockReservationLine::query()
->where('stock_reservation_id', $reservation->getKey())
->orderBy('inventory_id')
->lockForUpdate()
->get()
->keyBy('inventory_id');
$inventoryIds = collect(array_keys($requirements))
->merge($currentLines->keys())
->map(fn ($id): int => (int) $id)
->unique()
->sort()
->values();
$inventories = Inventory::query()
->whereKey($inventoryIds)
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
foreach ($inventoryIds as $inventoryId) {
$inventory = $inventories->get($inventoryId)
?? throw new \InvalidArgumentException('No se encontró el inventario requerido.');
$previous = (int) ($currentLines->get($inventoryId)?->quantity ?? 0);
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
$delta = $required - $previous;
if ($delta > 0
&& $requirements[$inventoryId]['tracks_inventory']
&& $inventory->availableStock() < $delta) {
throw new \InvalidArgumentException('No hay suficiente stock disponible para reservar el carrito.');
}
if ($delta < 0 && $inventory->reserved_stock < abs($delta)) {
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
}
}
foreach ($inventoryIds as $inventoryId) {
/** @var Inventory $inventory */
$inventory = $inventories->get($inventoryId);
$line = $currentLines->get($inventoryId);
$previous = (int) ($line?->quantity ?? 0);
$required = (int) ($requirements[$inventoryId]['quantity'] ?? 0);
$delta = $required - $previous;
if ($delta > 0) {
$inventory->reserve($delta, $requirements[$inventoryId]['tracks_inventory']);
} elseif ($delta < 0) {
$inventory->release(abs($delta));
}
if ($required === 0) {
$line?->delete();
continue;
}
StockReservationLine::query()->updateOrCreate(
[
'stock_reservation_id' => $reservation->getKey(),
'inventory_id' => $inventoryId,
],
[
'quantity' => $required,
'tracks_inventory' => $requirements[$inventoryId]['tracks_inventory'],
],
);
}
$reservation->update([
'expires_at' => $this->expiration(),
'release_reason' => null,
]);
$cart->current_stock_reservation_id = $reservation->getKey();
return $reservation->fresh('lines');
});
}
public function attachToPurchase(
Cart $cart,
Purchase $purchase,
Carbon $expiresAt,
): StockReservation {
return DB::transaction(function () use ($cart, $purchase, $expiresAt): StockReservation {
/** @var Cart $lockedCart */
$lockedCart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
/** @var Purchase $lockedPurchase */
$lockedPurchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($lockedCart->current_stock_reservation_id === null) {
throw new \InvalidArgumentException('El carrito no tiene una reserva de stock activa.');
}
/** @var StockReservation $reservation */
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($lockedCart->current_stock_reservation_id);
$this->assertUsableCartReservation($reservation);
$linkedPurchase = Purchase::query()
->where('stock_reservation_id', $reservation->getKey())
->whereKeyNot($lockedPurchase->getKey())
->exists();
if ($linkedPurchase) {
throw new \InvalidArgumentException('La reserva de stock ya pertenece a otra compra.');
}
$lockedPurchase->update(['stock_reservation_id' => $reservation->getKey()]);
$reservation->update(['expires_at' => $expiresAt]);
$purchase->stock_reservation_id = $reservation->getKey();
$cart->current_stock_reservation_id = $reservation->getKey();
return $reservation->fresh('lines');
});
}
public function commit(Purchase $purchase): void
{
DB::transaction(function () use ($purchase): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($purchase->stock_reservation_id === null) {
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
}
/** @var StockReservation $reservation */
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($purchase->stock_reservation_id);
if ($reservation->status === StockReservation::STATUS_COMMITTED) {
return;
}
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
throw new \InvalidArgumentException('La reserva de stock no está activa.');
}
if ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture()) {
throw new StockReservationExpiredException;
}
$lines = $this->lockLines($reservation);
if ($lines->isEmpty()) {
throw new \InvalidArgumentException('La reserva de stock no tiene inventarios.');
}
$inventories = $this->lockInventories($lines);
foreach ($lines as $line) {
$inventory = $inventories->get($line->inventory_id)
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
if ($inventory->reserved_stock < $line->quantity
|| ($line->tracks_inventory && $inventory->real_stock < $line->quantity)) {
throw new \InvalidArgumentException('La reserva de stock no alcanza para confirmar la compra.');
}
}
foreach ($lines as $line) {
$inventories->get($line->inventory_id)->buy(
(int) $line->quantity,
(bool) $line->tracks_inventory,
);
}
$reservation->update([
'status' => StockReservation::STATUS_COMMITTED,
'expires_at' => null,
'committed_at' => now(),
'released_at' => null,
'expired_at' => null,
'release_reason' => null,
]);
});
}
public function releaseForPurchase(
Purchase $purchase,
string $status = StockReservation::STATUS_RELEASED,
?string $reason = null,
): void {
DB::transaction(function () use ($purchase, $status, $reason): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($purchase->stock_reservation_id === null) {
return;
}
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->lockForUpdate()->find($purchase->stock_reservation_id);
if ($reservation !== null) {
$this->finalizeLocked($reservation, $status, $reason);
}
});
}
public function returnToCart(Purchase $purchase, Cart $cart): StockReservation
{
return DB::transaction(function () use ($purchase, $cart): StockReservation {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
/** @var Cart $cart */
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
if ($purchase->stock_reservation_id === null
|| $cart->current_stock_reservation_id !== $purchase->stock_reservation_id) {
throw new \InvalidArgumentException('La compra y el carrito no comparten la reserva activa.');
}
/** @var StockReservation $reservation */
$reservation = StockReservation::query()
->lockForUpdate()
->findOrFail($purchase->stock_reservation_id);
$this->assertUsableCartReservation($reservation);
$purchase->update(['stock_reservation_id' => null]);
$cart->update(['current_purchase_id' => null]);
$reservation->update(['expires_at' => $this->expiration()]);
return $reservation->fresh('lines');
});
}
public function assertCartReservationUsable(Cart $cart): void
{
DB::transaction(function () use ($cart): void {
/** @var Cart $cart */
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
if ($cart->current_stock_reservation_id === null) {
return;
}
/** @var StockReservation $reservation */
$reservation = StockReservation::query()
->lockForUpdate()
->findOrFail($cart->current_stock_reservation_id);
$this->assertUsableCartReservation($reservation);
});
}
public function releaseCurrentCartReservation(
Cart $cart,
string $reason = self::REASON_CART_CHANGED,
): void {
DB::transaction(function () use ($cart, $reason): void {
/** @var Cart $cart */
$cart = Cart::query()->lockForUpdate()->findOrFail($cart->getKey());
if ($cart->current_stock_reservation_id === null) {
return;
}
/** @var StockReservation|null $reservation */
$reservation = StockReservation::query()->lockForUpdate()->find($cart->current_stock_reservation_id);
if ($reservation !== null) {
$this->finalizeLocked($reservation, StockReservation::STATUS_RELEASED, $reason);
}
$cart->update(['current_stock_reservation_id' => null]);
});
}
public function expire(StockReservation $reservation): void
{
DB::transaction(function () use ($reservation): void {
/** @var StockReservation $reservation */
$reservation = StockReservation::query()->lockForUpdate()->findOrFail($reservation->getKey());
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|| $reservation->expires_at === null
|| $reservation->expires_at->isFuture()) {
return;
}
$this->finalizeLocked($reservation, StockReservation::STATUS_EXPIRED, null);
});
}
public function clearExpirationForReview(Purchase $purchase): void
{
DB::transaction(function () use ($purchase): void {
/** @var Purchase $purchase */
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
if ($purchase->stock_reservation_id === null) {
throw new \InvalidArgumentException('La compra no tiene una reserva de stock.');
}
/** @var StockReservation $reservation */
$reservation = StockReservation::query()
->lockForUpdate()
->findOrFail($purchase->stock_reservation_id);
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
throw new \InvalidArgumentException('La reserva de stock no está activa.');
}
if ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture()) {
throw new StockReservationExpiredException;
}
$reservation->update(['expires_at' => null]);
});
}
/**
* @param Collection<int, CartItem> $items
* @return array<int, array{quantity: int, tracks_inventory: bool}>
*/
private function requirementsForItems(Collection $items): array
{
$requirements = [];
foreach ($items as $item) {
$selection = $item->selectedItem();
if ($selection === null) {
throw new \InvalidArgumentException('El carrito contiene un item de catálogo inexistente.');
}
foreach ($this->inventory->detailedRequirementsFor($selection, (int) $item->cantidad) as $inventoryId => $requirement) {
if (isset($requirements[$inventoryId])) {
$requirements[$inventoryId]['quantity'] += $requirement['quantity'];
$requirements[$inventoryId]['tracks_inventory'] =
$requirements[$inventoryId]['tracks_inventory'] || $requirement['tracks_inventory'];
continue;
}
$requirements[$inventoryId] = $requirement;
}
}
ksort($requirements);
return $requirements;
}
/** @param Collection<int, CartItem> $items */
private function loadSelections(Collection $items): void
{
$items->load([
'catalogItem.inventory',
'catalogItem.bundleComponents.catalogItem.inventory',
'catalogItem.bundleComponents.variant.inventory',
'catalogItem.bundleComponents.variant.catalogItem',
'variant.inventory',
'variant.catalogItem',
]);
}
/** @return Collection<int, StockReservationLine> */
private function lockLines(StockReservation $reservation): Collection
{
return StockReservationLine::query()
->where('stock_reservation_id', $reservation->getKey())
->orderBy('inventory_id')
->lockForUpdate()
->get();
}
/**
* @param Collection<int, StockReservationLine> $lines
* @return Collection<int, Inventory>
*/
private function lockInventories(Collection $lines): Collection
{
return Inventory::query()
->whereKey($lines->pluck('inventory_id'))
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
}
private function finalizeLocked(
StockReservation $reservation,
string $status,
?string $reason,
): void {
if ($reservation->status !== StockReservation::STATUS_ACTIVE) {
return;
}
if (! in_array($status, [StockReservation::STATUS_RELEASED, StockReservation::STATUS_EXPIRED], true)) {
throw new \InvalidArgumentException('El estado final de la reserva no es válido.');
}
$lines = $this->lockLines($reservation);
$inventories = $this->lockInventories($lines);
foreach ($lines as $line) {
$inventory = $inventories->get($line->inventory_id)
?? throw new \InvalidArgumentException('No se encontró el inventario reservado.');
$inventory->release((int) $line->quantity);
}
$now = now();
$reservation->update([
'status' => $status,
'expires_at' => null,
'released_at' => $status === StockReservation::STATUS_RELEASED ? $now : null,
'expired_at' => $status === StockReservation::STATUS_EXPIRED ? $now : null,
'release_reason' => $status === StockReservation::STATUS_RELEASED ? $reason : null,
]);
if ($status === StockReservation::STATUS_RELEASED) {
Cart::query()
->where('current_stock_reservation_id', $reservation->getKey())
->update(['current_stock_reservation_id' => null]);
}
}
private function assertUsableCartReservation(StockReservation $reservation): void
{
if ($reservation->status === StockReservation::STATUS_EXPIRED
|| ($reservation->expires_at !== null && ! $reservation->expires_at->isFuture())) {
throw new StockReservationExpiredException;
}
if ($reservation->status !== StockReservation::STATUS_ACTIVE
|| $reservation->expires_at === null) {
throw new \InvalidArgumentException('La reserva de stock no está disponible para operar el carrito.');
}
}
private function expiration(): Carbon
{
return now()->addMinutes(
max(1, (int) config('catalog.stock_reservation_expiration_minutes', 30)),
);
}
}

View File

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

View File

@ -9,7 +9,6 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados. - `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables. - `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
- `Inventory` administra stock disponible, reservado y comprado. - `Inventory` administra stock disponible, reservado y comprado.
- `StockReservation` representa la reserva completa de un carrito o checkout, con estados `active`, `committed`, `released` y `expired`. Su `expires_at` es el único reloj del bloqueo. Al expirar, también pasan a `expired` la compra pagable y el carrito asociados dentro de la misma transacción. Sus estados terminales nunca se reactivan ni se reemplazan implícitamente. Sus `StockReservationLine` agregan la cantidad requerida por inventario, incluso cuando varios ítems o bundles consumen el mismo stock.
- `Category` soporta jerarquía y categorías globales o propias del tenant. - `Category` soporta jerarquía y categorías globales o propias del tenant.
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas. - `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
- `BundleComponent` representa los componentes de un paquete. - `BundleComponent` representa los componentes de un paquete.
@ -18,8 +17,6 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación. - `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario. - `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
- `StockReservationService`: sincroniza el carrito como conjunto, bloquea todos sus inventarios en orden estable y mantiene el ledger agregado consistente con `Inventory.reserved_stock`.
- `ExpireStockReservationsService`: detecta en un único recorrido reservas vencidas de compras, carritos y huérfanas, y delega los efectos comerciales sin mezclar esas reglas con la liberación física del inventario.
- `FeaturedGroupService`: pagina los ítems destacados para la tienda. - `FeaturedGroupService`: pagina los ítems destacados para la tienda.
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets. - `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.

View File

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

View File

@ -1,47 +0,0 @@
<?php
namespace App\Domains\Client\Controllers;
use App\Domains\Client\Models\Client;
use App\Domains\Client\Requests\StoreClientRequest;
use App\Domains\Client\Requests\UpdateClientRequest;
use App\Domains\Client\Resources\ClientResource;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class ClientController extends Controller
{
public function index(): JsonResponse
{
return ClientResource::collection(
Client::query()->with('tenants')->latest()->paginateFromRequest()
)->response();
}
public function store(StoreClientRequest $request): JsonResponse
{
return ClientResource::make(
Client::query()->create($request->validated())->load('tenants')
)->response()->setStatusCode(201);
}
public function show(Client $client): ClientResource
{
return ClientResource::make($client->load('tenants'));
}
public function update(UpdateClientRequest $request, Client $client): ClientResource
{
$client->update($request->validated());
return ClientResource::make($client->fresh()->load('tenants'));
}
public function destroy(Client $client): Response
{
$client->delete();
return response()->noContent();
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace App\Domains\Client\Models;
use App\Domains\Integration\Models\ClientIntegration;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['code', 'name'])]
class Client extends Model
{
public function getRouteKeyName(): string
{
return 'code';
}
/** @return HasMany<Tenant, $this> */
public function tenants(): HasMany
{
return $this->hasMany(Tenant::class);
}
/** @return HasMany<ClientIntegration, $this> */
public function integrations(): HasMany
{
return $this->hasMany(ClientIntegration::class);
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Domains\Client\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreClientRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'code' => ['required', 'string', 'max:255', Rule::unique('clients', 'code')],
'name' => ['required', 'string', 'max:255'],
];
}
}

View File

@ -1,26 +0,0 @@
<?php
namespace App\Domains\Client\Requests;
use App\Domains\Client\Models\Client;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateClientRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
/** @var Client|null $client */
$client = $this->route('client');
return [
'code' => ['sometimes', 'string', 'max:255', Rule::unique('clients', 'code')->ignore($client?->id)],
'name' => ['sometimes', 'string', 'max:255'],
];
}
}

View File

@ -1,26 +0,0 @@
<?php
namespace App\Domains\Client\Resources;
use App\Domains\Client\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin Client */
class ClientResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'code' => $this->code,
'name' => $this->name,
'tenants' => $this->whenLoaded('tenants', fn () => $this->tenants->map(fn ($tenant): array => [
'id' => $tenant->id,
'codigo' => $tenant->codigo,
'nombre' => $tenant->nombre,
'dominio' => $tenant->dominio,
])),
];
}
}

View File

@ -1,6 +0,0 @@
<?php
use App\Domains\Client\Controllers\ClientController;
use Illuminate\Support\Facades\Route;
Route::apiResource('clients', ClientController::class);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,431 +0,0 @@
<?php
namespace App\Domains\Desfile\Services;
use DateTimeInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use RuntimeException;
class InvitationPurchaseProvisioner
{
public const TENANT_CODE = 'desfile_pura_tendencia';
public const USER_EMAIL = 'invitados@puratendencia.com';
private const PAYMENT_METHOD = 'invitation';
/**
* @var list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>
*/
private const ALLOCATIONS = [
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 17, 'type' => 'VIP + LUNCH'],
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
];
/**
* @param list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>|null $allocations
*/
public function provision(?array $allocations = null): void
{
if (! $this->prerequisitesExist()) {
return;
}
DB::transaction(function () use ($allocations): void {
$now = now();
$userId = $this->userId($now);
$purchaseId = $this->purchaseId($userId, $now);
$catalogItem = DB::table('catalog_items')
->where('tenant_code', self::TENANT_CODE)
->where('slug', 'entrada')
->first();
if ($catalogItem === null) {
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
}
foreach ($allocations ?? self::ALLOCATIONS as $allocation) {
foreach (range($allocation['first_seat'], $allocation['last_seat']) as $seat) {
$variant = $this->variant(
(int) $catalogItem->id,
$allocation['sector'],
$allocation['row'],
$seat,
$allocation['type'],
);
$this->createPurchaseItem(
$purchaseId,
$catalogItem,
$variant,
$allocation['sector'],
$allocation['row'],
$seat,
$allocation['type'],
$now,
);
$this->createTicketAndCommitStock(
$purchaseId,
$userId,
(int) $catalogItem->id,
$variant,
$now,
);
}
}
});
}
private function prerequisitesExist(): bool
{
if (! DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
return false;
}
if (! DB::table('roles')->where('codigo', 'user')->exists()) {
throw new RuntimeException('No se encontró el rol de usuario común.');
}
if (! DB::table('catalog_items')
->where('tenant_code', self::TENANT_CODE)
->where('slug', 'entrada')
->exists()) {
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
}
return true;
}
private function userId(DateTimeInterface $now): int
{
$user = DB::table('users')->where('email', self::USER_EMAIL)->first();
if ($user !== null) {
if ($user->tenant_codigo !== self::TENANT_CODE) {
throw new RuntimeException('El email de invitados ya pertenece a otro tenant.');
}
DB::table('users')->where('id', $user->id)->update([
'rol_codigo' => 'user',
'nombre_apellido' => 'Invitados Pura Tendencia',
'updated_at' => $now,
]);
return (int) $user->id;
}
return DB::table('users')->insertGetId([
'rol_codigo' => 'user',
'tenant_codigo' => self::TENANT_CODE,
'nombre_apellido' => 'Invitados Pura Tendencia',
'email' => self::USER_EMAIL,
'email_verified_at' => $now,
'password' => Hash::make(Str::random(64)),
'dni' => null,
'telefono' => null,
'remember_token' => null,
'created_at' => $now,
'updated_at' => $now,
]);
}
private function purchaseId(int $userId, DateTimeInterface $now): int
{
$purchaseId = DB::table('compras')
->where('tenant_codigo', self::TENANT_CODE)
->where('user_id', $userId)
->where('payment_method', self::PAYMENT_METHOD)
->value('id');
if ($purchaseId !== null) {
DB::table('compras')->where('id', $purchaseId)->update([
'status' => 'paid',
'total' => 0,
'updated_at' => $now,
]);
return (int) $purchaseId;
}
return DB::table('compras')->insertGetId([
'tenant_codigo' => self::TENANT_CODE,
'user_id' => $userId,
'cart_id' => null,
'status' => 'paid',
'payment_method' => self::PAYMENT_METHOD,
'total' => 0,
'dni' => null,
'transfer_payer_dni' => null,
'telefono' => null,
'nombre_apellido' => 'Invitados Pura Tendencia',
'email' => self::USER_EMAIL,
'created_at' => $now,
'updated_at' => $now,
]);
}
private function variant(
int $catalogItemId,
string $sector,
int $row,
int $seat,
string $type,
): object {
$variant = $this->findVariant($catalogItemId, $sector, $row, $seat);
if ($variant === null) {
$variant = $this->createVariant($catalogItemId, $sector, $row, $seat, $type);
}
$this->ensureAttributeOptions($catalogItemId, [
'tipo' => $type,
'sector' => $sector,
'fila' => (string) $row,
'asiento' => (string) $seat,
]);
$typeValueId = DB::table('variant_values as variant_value')
->join('item_attributes as item_attribute', 'item_attribute.id', '=', 'variant_value.item_attribute_id')
->join('attribute', 'attribute.id', '=', 'item_attribute.attribute_id')
->where('variant_value.variant_id', $variant->id)
->where('attribute.codigo', 'tipo')
->value('variant_value.id');
if ($typeValueId === null) {
throw new RuntimeException("La variante {$variant->id} no tiene definido el tipo de entrada.");
}
DB::table('variant_values')->where('id', $typeValueId)->update(['value' => $type]);
DB::table('variantes')->where('id', $variant->id)->update([
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
]);
return DB::table('variantes')->where('id', $variant->id)->first();
}
/** @param array<string, string> $values */
private function ensureAttributeOptions(int $catalogItemId, array $values): void
{
$attributes = DB::table('item_attributes')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->where('item_attributes.catalog_item_id', $catalogItemId)
->pluck('attribute.id', 'attribute.codigo');
foreach ($values as $code => $value) {
$attributeId = $attributes[$code] ?? null;
if ($attributeId === null) {
throw new RuntimeException("Falta el atributo {$code} en el catálogo de entradas.");
}
if (DB::table('attribute_options')
->where('attribute_id', $attributeId)
->where('value', $value)
->exists()) {
continue;
}
$lastSortOrder = (int) DB::table('attribute_options')
->where('attribute_id', $attributeId)
->max('sort_order');
DB::table('attribute_options')->insert([
'attribute_id' => $attributeId,
'validity_time_id' => null,
'value' => $value,
'label' => $value,
'sort_order' => $lastSortOrder + 1,
'metadata' => null,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
private function findVariant(int $catalogItemId, string $sector, int $row, int $seat): ?object
{
$query = DB::table('variantes')->where('catalog_item_id', $catalogItemId);
foreach (['sector' => $sector, 'fila' => (string) $row, 'asiento' => (string) $seat] as $code => $value) {
$query->whereExists(fn ($subquery) => $subquery
->selectRaw('1')
->from('variant_values as selected_value')
->join('item_attributes as selected_item_attribute', 'selected_item_attribute.id', '=', 'selected_value.item_attribute_id')
->join('attribute as selected_attribute', 'selected_attribute.id', '=', 'selected_item_attribute.attribute_id')
->whereColumn('selected_value.variant_id', 'variantes.id')
->where('selected_attribute.codigo', $code)
->where('selected_value.value', $value));
}
return $query->first();
}
private function createVariant(
int $catalogItemId,
string $sector,
int $row,
int $seat,
string $type,
): object {
$itemAttributes = DB::table('item_attributes')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->where('item_attributes.catalog_item_id', $catalogItemId)
->pluck('item_attributes.id', 'attribute.codigo');
foreach (['tipo', 'sector', 'fila', 'asiento'] as $requiredCode) {
if (! isset($itemAttributes[$requiredCode])) {
throw new RuntimeException("Falta el atributo {$requiredCode} en el catálogo de entradas.");
}
}
$inventoryId = DB::table('inventories')->insertGetId([
'sold_units' => 0,
'reserved_stock' => 0,
'real_stock' => 1,
]);
$variantId = DB::table('variantes')->insertGetId([
'catalog_item_id' => $catalogItemId,
'event_date_id' => null,
'inventory_id' => $inventoryId,
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
'precio' => $this->catalogPrice($sector, $row),
]);
foreach (['tipo' => $type, 'sector' => $sector, 'fila' => (string) $row, 'asiento' => (string) $seat] as $code => $value) {
DB::table('variant_values')->insert([
'variant_id' => $variantId,
'item_attribute_id' => $itemAttributes[$code],
'value' => $value,
'created_at' => now(),
'updated_at' => now(),
]);
}
return DB::table('variantes')->where('id', $variantId)->first();
}
private function catalogPrice(string $sector, int $row): int
{
$prices = in_array($sector, ['A', 'C'], true)
? [1 => 250000, 2 => 200000, 3 => 100000, 4 => 75000, 5 => 50000]
: [1 => 240000, 2 => 190000, 3 => 90000, 4 => 65000, 5 => 40000];
return $prices[$row];
}
private function createPurchaseItem(
int $purchaseId,
object $catalogItem,
object $variant,
string $sector,
int $row,
int $seat,
string $type,
DateTimeInterface $now,
): void {
if (DB::table('compra_items')
->where('compra_id', $purchaseId)
->where('source_variant_id', $variant->id)
->exists()) {
return;
}
$attributes = [
['name' => 'Tipo', 'value' => $type],
['name' => 'Sector', 'value' => $sector],
['name' => 'Fila', 'value' => (string) $row],
['name' => 'Asiento', 'value' => (string) $seat],
];
DB::table('compra_items')->insert([
'compra_id' => $purchaseId,
'source_catalog_item_id' => $catalogItem->id,
'source_variant_id' => $variant->id,
'image_attachment_id' => DB::table('catalog_items_attachments')
->where('catalog_item_id', $catalogItem->id)
->whereNull('variant_id')
->orderBy('orden')
->value('attachment_id'),
'nombre' => $catalogItem->nombre,
'descripcion' => $variant->descripcion,
'slug' => $catalogItem->slug,
'item_nombre' => "Entrada (Sector {$sector}, Fila {$row}, Asiento {$seat})",
'variant_attributes' => json_encode($attributes, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'cantidad' => 1,
'precio_unitario' => 0,
'discount_total' => 0,
'tax_total' => 0,
'total' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
}
private function createTicketAndCommitStock(
int $purchaseId,
int $userId,
int $catalogItemId,
object $variant,
DateTimeInterface $now,
): void {
if (DB::table('tickets')
->where('source_purchase_id', $purchaseId)
->where('source_variant_id', $variant->id)
->exists()) {
return;
}
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->lockForUpdate()->first();
if ($inventory === null || $inventory->real_stock < 1 || $inventory->reserved_stock > 0) {
throw new RuntimeException("El asiento {$variant->descripcion} ya no está disponible.");
}
DB::table('inventories')->where('id', $inventory->id)->update([
'real_stock' => $inventory->real_stock - 1,
'sold_units' => $inventory->sold_units + 1,
]);
$reservationId = DB::table('compras')->where('id', $purchaseId)->value('stock_reservation_id');
if ($reservationId === null) {
$reservationId = DB::table('stock_reservations')->insertGetId([
'status' => 'committed',
'committed_at' => $now,
'released_at' => null,
'expired_at' => null,
'release_reason' => null,
'created_at' => $now,
'updated_at' => $now,
]);
DB::table('compras')->where('id', $purchaseId)->update([
'stock_reservation_id' => $reservationId,
]);
}
DB::table('stock_reservation_lines')->insert([
'stock_reservation_id' => $reservationId,
'inventory_id' => $inventory->id,
'quantity' => 1,
'tracks_inventory' => true,
'created_at' => $now,
'updated_at' => $now,
]);
DB::table('tickets')->insert([
'tenant_code' => self::TENANT_CODE,
'ticket' => (string) Str::uuid(),
'name' => null,
'description' => null,
'source_purchase_id' => $purchaseId,
'source_catalog_item_id' => $catalogItemId,
'source_variant_id' => $variant->id,
'used_at' => null,
'scanner_user_id' => null,
'user_id' => $userId,
]);
}
}

View File

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

View File

@ -43,6 +43,7 @@ class EventDate extends Model
$eventDate->syncTenantDateText(); $eventDate->syncTenantDateText();
ValidityTime::query() ValidityTime::query()
->whereKey($eventDate->validity_time_id) ->whereKey($eventDate->validity_time_id)
->whereDoesntHave('ticketValidityGroups')
->delete(); ->delete();
}); });
} }

View File

@ -4,7 +4,6 @@ namespace App\Domains\Event\Services;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class EventService class EventService
{ {
@ -61,19 +60,7 @@ class EventService
} }
} }
$datesToDelete = $existingDates->slice(count($dates)); $existingDates->slice(count($dates))->each->delete();
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'); $tenant->unsetRelation('eventDates');
} }

View File

@ -1,52 +0,0 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Controllers;
use App\Domains\FiestaFutbolInfantil\Enums\FiestaCategory;
use App\Domains\FiestaFutbolInfantil\Requests\UpdateCategoryVisibilityRequest;
use App\Domains\FiestaFutbolInfantil\Services\CategoryVisibilityService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CategoryVisibilityController extends Controller
{
public function __construct(private readonly CategoryVisibilityService $visibilityService) {}
public function show(Request $request): JsonResponse
{
$category = $this->category($request);
$tenant = $request->user()->tenant()->firstOrFail();
return response()->json([
'data' => [
'is_enabled' => $this->visibilityService->isEnabled($tenant, $category),
],
]);
}
public function update(UpdateCategoryVisibilityRequest $request): JsonResponse
{
$category = $this->category($request);
$tenant = $request->user()->tenant()->firstOrFail();
$model = $this->visibilityService->update(
$tenant,
$category,
$request->boolean('is_enabled'),
);
return response()->json([
'data' => [
'is_enabled' => $model->is_enabled,
],
'message' => $model->is_enabled
? 'Mostrar en sitio web se activo correctamente'
: 'Mostrar en sitio web se desactivo correctamente',
]);
}
private function category(Request $request): FiestaCategory
{
return FiestaCategory::from((string) $request->route('category'));
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Enums;
enum FiestaCategory: string
{
case Entries = 'entries';
case Foods = 'foods';
case Accommodations = 'accommodations';
case Merchandise = 'merchandise';
public function categoryName(): string
{
return match ($this) {
self::Entries => 'Entradas',
self::Foods => 'Comidas',
self::Accommodations => 'Alojamientos',
self::Merchandise => 'Merchandising',
};
}
}

View File

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

View File

@ -12,6 +12,7 @@ use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
@ -125,21 +126,18 @@ class AccommodationService
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'nombre' => 'Alojamientos', 'nombre' => 'Alojamientos',
]); ]);
$accommodation = CatalogItem::withTrashed() $accommodation = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('slug', 'alojamiento') ->where('slug', 'alojamiento')
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
if ($accommodation !== null) { if ($accommodation !== null) {
if ($accommodation->trashed()) {
$accommodation->restore();
}
$accommodation->update([ $accommodation->update([
'category_id' => $category->id, 'category_id' => $category->id,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
]); ]);
return $accommodation; return $accommodation;
@ -154,6 +152,7 @@ class AccommodationService
'precio' => collect($variants)->min('price') ?? 0, 'precio' => collect($variants)->min('price') ?? 0,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
'inventory_id' => null, 'inventory_id' => null,
]); ]);
} }

View File

@ -1,29 +0,0 @@
<?php
namespace App\Domains\FiestaFutbolInfantil\Services;
use App\Domains\Catalog\Models\Category;
use App\Domains\FiestaFutbolInfantil\Enums\FiestaCategory;
use App\Domains\Tenant\Models\Tenant;
class CategoryVisibilityService
{
public function isEnabled(Tenant $tenant, FiestaCategory $category): bool
{
return Category::query()
->where('tenant_code', $tenant->codigo)
->where('nombre', $category->categoryName())
->value('is_enabled') ?? true;
}
public function update(Tenant $tenant, FiestaCategory $category, bool $isEnabled): Category
{
$model = Category::query()->firstOrCreate([
'tenant_code' => $tenant->codigo,
'nombre' => $category->categoryName(),
]);
$model->update(['is_enabled' => $isEnabled]);
return $model;
}
}

View File

@ -9,6 +9,7 @@ use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@ -62,6 +63,7 @@ class EntryService
'category_id' => $category->id, 'category_id' => $category->id,
'precio' => $entry['price'], 'precio' => $entry['price'],
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'attribute_codes' => ['event_date'], 'attribute_codes' => ['event_date'],
'multi_select_attribute_codes' => ['event_date'], 'multi_select_attribute_codes' => ['event_date'],
@ -133,6 +135,7 @@ class EntryService
'category_id' => $category->id, 'category_id' => $category->id,
'precio' => $entry['price'], 'precio' => $entry['price'],
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
]); ]);
$variant->update([ $variant->update([
@ -160,7 +163,7 @@ class EntryService
while ( while (
in_array($slug, $reservedSlugs, true) in_array($slug, $reservedSlugs, true)
|| CatalogItem::withTrashed() || CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('slug', $slug) ->where('slug', $slug)
->exists() ->exists()

View File

@ -12,6 +12,7 @@ use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
@ -136,21 +137,18 @@ class FoodService
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'nombre' => 'Comidas', 'nombre' => 'Comidas',
]); ]);
$food = CatalogItem::withTrashed() $food = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('slug', 'comida') ->where('slug', 'comida')
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
if ($food !== null) { if ($food !== null) {
if ($food->trashed()) {
$food->restore();
}
$food->update([ $food->update([
'category_id' => $category->id, 'category_id' => $category->id,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
]); ]);
return $food; return $food;
@ -165,6 +163,7 @@ class FoodService
'precio' => collect($variants)->min('price') ?? 0, 'precio' => collect($variants)->min('price') ?? 0,
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
'inventory_id' => null, 'inventory_id' => null,
]); ]);
} }

View File

@ -12,6 +12,7 @@ use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@ -74,6 +75,7 @@ class MerchandiseService
'max_units_per_user' => (int) $data['max_units_per_user'], 'max_units_per_user' => (int) $data['max_units_per_user'],
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
]); ]);
$itemAttributes = $this->itemAttributes($item, $attributes); $itemAttributes = $this->itemAttributes($item, $attributes);
@ -198,6 +200,7 @@ class MerchandiseService
'max_units_per_user' => (int) $data['max_units_per_user'], 'max_units_per_user' => (int) $data['max_units_per_user'],
'inventory_policy' => InventoryPolicy::Tracked->value, 'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => true, 'has_tickets' => true,
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
'inventory_id' => null, 'inventory_id' => null,
]); ]);
} }
@ -411,7 +414,7 @@ class MerchandiseService
while ( while (
in_array($slug, $reservedSlugs, true) in_array($slug, $reservedSlugs, true)
|| CatalogItem::withTrashed() || CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('slug', $slug) ->where('slug', $slug)
->exists() ->exists()

View File

@ -1,7 +1,6 @@
<?php <?php
use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController; use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController;
use App\Domains\FiestaFutbolInfantil\Controllers\CategoryVisibilityController;
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController; use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
use App\Domains\FiestaFutbolInfantil\Controllers\FoodController; use App\Domains\FiestaFutbolInfantil\Controllers\FoodController;
use App\Domains\FiestaFutbolInfantil\Controllers\MerchandiseController; use App\Domains\FiestaFutbolInfantil\Controllers\MerchandiseController;
@ -10,20 +9,6 @@ use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant') Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant']) ->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void { ->group(function (): void {
$visibilityRoutes = static function (string $endpoint, string $category, string $menuCode): void {
Route::get("{$endpoint}/visibility", [CategoryVisibilityController::class, 'show'])
->defaults('category', $category)
->middleware("tenant.menu:{$menuCode}");
Route::patch("{$endpoint}/visibility", [CategoryVisibilityController::class, 'update'])
->defaults('category', $category)
->middleware("tenant.menu:{$menuCode}");
};
$visibilityRoutes('entries', 'entries', 'adminapp.fiesta-futbol-infantil.entradas');
$visibilityRoutes('foods', 'foods', 'adminapp.fiesta-futbol-infantil.comida');
$visibilityRoutes('accommodations', 'accommodations', 'adminapp.fiesta-futbol-infantil.alojamientos');
$visibilityRoutes('merchandise', 'merchandise', 'adminapp.fiesta-futbol-infantil.merchandising');
Route::get('entries', [EntryController::class, 'index']) Route::get('entries', [EntryController::class, 'index'])
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas') ->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
->name('adminapp.fiesta-futbol-infantil.entries.index'); ->name('adminapp.fiesta-futbol-infantil.entries.index');

View File

@ -1,20 +0,0 @@
<?php
namespace App\Domains\Forms\Controllers\AdminApp;
use App\Domains\Forms\Resources\TicketFilterFormResource;
use App\Domains\Forms\Services\TicketFilterFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class TicketFilterFormController extends Controller
{
public function __construct(private readonly TicketFilterFormService $formService) {}
public function __invoke(Request $request): TicketFilterFormResource
{
$tenant = $request->user('sanctum')->tenant()->firstOrFail();
return TicketFilterFormResource::make($this->formService->get($tenant));
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Domains\Forms\Controllers\AdminApp;
use App\Domains\Forms\Resources\TicketFormResource;
use App\Domains\Forms\Services\TicketFormService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class TicketFormController extends Controller
{
public function __construct(protected TicketFormService $ticketFormService) {}
public function __invoke(Request $request): TicketFormResource
{
return TicketFormResource::make(
$this->ticketFormService->get(
$request->user('sanctum')->tenant()->firstOrFail()
)
);
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Domains\Forms\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class TicketFilterFormResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'code' => $this->resource['code'],
'action' => $this->resource['action'],
'method' => $this->resource['method'],
'fields' => $this->resource['fields'],
'columns' => $this->resource['columns'],
];
}
}

View File

@ -1,18 +0,0 @@
<?php
namespace App\Domains\Forms\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class TicketFormResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'statuses' => $this->resource['statuses'],
'categories' => $this->resource['categories'],
];
}
}

View File

@ -12,12 +12,10 @@ class SaleFormService
$names = [ $names = [
Purchase::STATUS_CREATED => 'Creada', Purchase::STATUS_CREATED => 'Creada',
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago', Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
Purchase::STATUS_IN_REVIEW => 'En revisión',
Purchase::STATUS_PAID => 'Confirmada', Purchase::STATUS_PAID => 'Confirmada',
Purchase::STATUS_CANCELLED => 'Cancelada', Purchase::STATUS_CANCELLED => 'Cancelada',
Purchase::STATUS_REJECTED => 'Rechazada', Purchase::STATUS_REJECTED => 'Rechazada',
Purchase::STATUS_EXPIRED => 'Vencida', Purchase::STATUS_EXPIRED => 'Vencida',
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
]; ];
return [ return [

View File

@ -1,127 +0,0 @@
<?php
namespace App\Domains\Forms\Services;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Services\AdminAppTicketColumnService;
class TicketFilterFormService
{
private const FIESTA_FUTBOL_INFANTIL = 'fiesta_futbol_infantil';
public function __construct(
private readonly TicketFormService $ticketFormService,
private readonly AdminAppTicketColumnService $columnService,
) {}
/** @return array<string, mixed> */
public function get(Tenant $tenant): array
{
$fields = $this->commonFields();
if ($tenant->codigo === self::FIESTA_FUTBOL_INFANTIL) {
$fields = [
...$this->fiestaFutbolInfantilFields($tenant),
...$fields,
];
}
return [
'code' => 'tickets_filter',
'action' => '/api/v1/adminapp/tenant/tickets',
'method' => 'GET',
'fields' => $fields,
'columns' => $this->columnService->publicColumns($tenant),
];
}
/** @return list<array<string, mixed>> */
private function fiestaFutbolInfantilFields(Tenant $tenant): array
{
$form = $this->ticketFormService->getForFilters($tenant);
return [
[
'name' => 'category',
'query_param' => 'category',
'label' => 'Categoría',
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => 'Categoría',
'options' => array_map(
fn (array $category): array => [
'value' => $category['value'],
'label' => $category['label'],
'children' => [
'field' => 'product',
'disabled' => $category['products'] === [],
'options' => array_map(
fn (array $product): array => [
'value' => $product['value'],
'label' => $product['label'],
'children' => [
'field' => 'type',
'disabled' => $product['types'] === [],
'options' => $product['types'],
],
],
$category['products'],
),
],
],
$form['categories'],
),
],
$this->dependentSelect('product', 'Producto', 'category'),
$this->dependentSelect('type', 'Tipo', 'product'),
];
}
/** @return list<array<string, mixed>> */
private function commonFields(): array
{
return [
[
'name' => 'date',
'query_param' => 'date',
'label' => 'Fecha',
'type' => 'date',
'required' => false,
'default' => null,
],
[
'name' => 'status',
'query_param' => 'status',
'label' => 'Estado',
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => 'Estado',
'options' => [
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
],
];
}
/** @return array<string, mixed> */
private function dependentSelect(string $name, string $label, string $dependency): array
{
return [
'name' => $name,
'query_param' => $name,
'label' => $label,
'type' => 'select',
'required' => false,
'default' => null,
'placeholder' => $label,
'depends_on' => $dependency,
'disabled' => true,
'options' => [],
];
}
}

View File

@ -1,336 +0,0 @@
<?php
namespace App\Domains\Forms\Services;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Collection;
class TicketFormService
{
private const PRODUCT = 'product';
/**
* @var array<string, array{label: string|null, product: string, type: string|null, order: int}>
*/
private const CATEGORY_PRESENTATIONS = [
'entradas' => [
'label' => null,
'product' => self::PRODUCT,
'type' => null,
'order' => 1,
],
'alojamientos' => [
'label' => 'Camping',
'product' => 'tipo_alojamiento',
'type' => null,
'order' => 2,
],
'camping' => [
'label' => null,
'product' => 'tipo_alojamiento',
'type' => null,
'order' => 2,
],
'comidas' => [
'label' => 'Comida',
'product' => 'event_date',
'type' => 'horario',
'order' => 3,
],
'comida' => [
'label' => null,
'product' => 'event_date',
'type' => 'horario',
'order' => 3,
],
'merchandising' => [
'label' => null,
'product' => self::PRODUCT,
'type' => 'color',
'order' => 4,
],
];
/**
* @return array{
* statuses: list<array{value: string, label: string}>,
* categories: list<array{
* value: string,
* label: string,
* products: list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
* }>
* }
*/
public function get(Tenant $tenant): array
{
$items = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('has_tickets', true)
->whereHas('category')
->with($this->relations())
->orderBy('group_order')
->orderBy('nombre')
->get();
return $this->build($items);
}
/**
* Return active catalog options plus soft-deleted sources still referenced by
* tickets, so historical tickets never become impossible to filter.
*
* @return array{
* statuses: list<array{value: string, label: string}>,
* categories: list<array{
* value: string,
* label: string,
* products: list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
* }>
* }
*/
public function getForFilters(Tenant $tenant): array
{
$historicalVariantIds = Ticket::query()
->where('tenant_code', $tenant->codigo)
->whereNotNull('source_variant_id')
->distinct()
->pluck('source_variant_id')
->map(fn ($id): int => (int) $id)
->all();
$historicalCatalogItemIds = Ticket::query()
->where('tenant_code', $tenant->codigo)
->whereNotNull('source_catalog_item_id')
->distinct()
->pluck('source_catalog_item_id')
->map(fn ($id): int => (int) $id)
->merge(
Variant::withTrashed()
->whereKey($historicalVariantIds)
->pluck('catalog_item_id')
->map(fn ($id): int => (int) $id),
)
->unique()
->values()
->all();
$items = CatalogItem::withTrashed()
->where('tenant_code', $tenant->codigo)
->whereHas('category')
->where(function ($query) use ($historicalCatalogItemIds): void {
$query
->where(function ($activeQuery): void {
$activeQuery
->whereNull('catalog_items.deleted_at')
->where('has_tickets', true);
})
->orWhereIn('catalog_items.id', $historicalCatalogItemIds);
})
->with([
'category',
'itemAttributes.attribute.options',
'variants' => fn ($query) => $query
->withTrashed()
->where(function ($variantQuery) use ($historicalVariantIds): void {
$variantQuery
->whereNull('variantes.deleted_at')
->orWhereIn('variantes.id', $historicalVariantIds);
}),
'variants.definitions.itemAttribute.attribute.options',
'variants.eventDates',
'variants.eventDate',
])
->orderBy('group_order')
->orderBy('nombre')
->get();
return $this->build($items);
}
/**
* @param Collection<int, CatalogItem> $items
* @return array{
* statuses: list<array{value: string, label: string}>,
* categories: list<array{
* value: string,
* label: string,
* products: list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
* }>
* }
*/
private function build(Collection $items): array
{
$categories = [];
foreach ($items as $item) {
$sourceCategory = trim((string) $item->category?->nombre);
$categoryValue = mb_strtolower($sourceCategory);
$presentation = self::CATEGORY_PRESENTATIONS[$categoryValue] ?? [
'label' => null,
'product' => self::PRODUCT,
'type' => null,
'order' => PHP_INT_MAX,
];
$categories[$categoryValue] ??= [
'value' => $categoryValue,
'label' => $presentation['label'] ?? $sourceCategory,
'order' => $presentation['order'],
'products' => [],
];
foreach ($this->products($item, $presentation['product'], $presentation['type']) as $product) {
$productValue = $product['value'];
$existingProduct = $categories[$categoryValue]['products'][$productValue] ?? [
'value' => $productValue,
'label' => $product['label'],
'types' => [],
];
foreach ($product['types'] as $type) {
$existingProduct['types'][$type['value']] = $type;
}
$categories[$categoryValue]['products'][$productValue] = $existingProduct;
}
}
uasort($categories, fn (array $left, array $right): int => $left['order'] <=> $right['order']
?: $left['label'] <=> $right['label']);
return [
'statuses' => [
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
],
'categories' => array_values(array_map(
fn (array $category): array => [
'value' => $category['value'],
'label' => $category['label'],
'products' => array_values(array_map(
fn (array $product): array => [
'value' => $product['value'],
'label' => $product['label'],
'types' => array_values($product['types']),
],
$category['products'],
)),
],
$categories,
)),
];
}
/** @return list<string> */
private function relations(): array
{
return [
'category',
'itemAttributes.attribute.options',
'variants.definitions.itemAttribute.attribute.options',
'variants.eventDates',
'variants.eventDate',
];
}
/**
* @return list<array{
* value: string,
* label: string,
* types: list<array{value: string, label: string}>
* }>
*/
private function products(CatalogItem $item, string $productCode, ?string $typeCode): array
{
if ($productCode === self::PRODUCT) {
return [[
'value' => $item->slug,
'label' => $item->nombre,
'types' => $this->types($item, $typeCode),
]];
}
$products = [];
foreach ($item->variants as $variant) {
foreach ($this->variantOptions($variant, $productCode) as $productOption) {
$productValue = $productOption['value'];
$products[$productValue] ??= [
'value' => $productValue,
'label' => $this->optionLabel($productOption['label'], $productCode),
'types' => [],
];
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
$products[$productValue]['types'][$typeOption['value']] = $typeOption;
}
}
}
return array_values(array_map(
fn (array $product): array => [
'value' => $product['value'],
'label' => $product['label'],
'types' => array_values($product['types']),
],
$products,
));
}
/** @return list<array{value: string, label: string}> */
private function types(CatalogItem $item, ?string $typeCode): array
{
$types = [];
foreach ($item->variants as $variant) {
foreach ($this->variantOptions($variant, $typeCode) as $typeOption) {
$types[$typeOption['value']] = $typeOption;
}
}
return array_values($types);
}
/** @return list<array{value: string, label: string}> */
private function variantOptions(Variant $variant, ?string $attributeCode): array
{
if ($attributeCode === null) {
return [];
}
$selection = $variant->selectionOptions($variant->catalogItem->itemAttributes)
->get($attributeCode);
if ($selection === null) {
return [];
}
return array_is_list($selection) ? $selection : [$selection];
}
private function optionLabel(string $label, string $attributeCode): string
{
if ($attributeCode !== 'event_date') {
return $label;
}
[$day, $month] = array_pad(explode('/', $label), 2, null);
return $day !== null && $month !== null ? "{$day}/{$month}" : $label;
}
}

View File

@ -9,7 +9,6 @@ Provee catálogos y opciones auxiliares para construir formularios del panel adm
- `EventFormService`: devuelve redes sociales disponibles y las URL configuradas para el tenant. - `EventFormService`: devuelve redes sociales disponibles y las URL configuradas para el tenant.
- `SaleFormService`: expone los estados admitidos para compras con sus etiquetas de presentación. - `SaleFormService`: expone los estados admitidos para compras con sus etiquetas de presentación.
- `StaffFormService`: lista categorías raíz que pueden asignarse al personal del tenant. - `StaffFormService`: lista categorías raíz que pueden asignarse al personal del tenant.
- `TicketFormService`: expone estados y opciones anidadas de categoría, producto y tipo para los tickets de Fiesta Fútbol Infantil.
Cada servicio tiene un controlador invocable y un `JsonResource` específico. `SocialMediaOptionResource` representa las opciones de redes sociales. Cada servicio tiene un controlador invocable y un `JsonResource` específico. `SocialMediaOptionResource` representa las opciones de redes sociales.
@ -20,7 +19,6 @@ Bajo `/v1/adminapp/forms`, con `auth:sanctum` y `adminapp.tenant`:
- `GET /event`. - `GET /event`.
- `GET /sale`. - `GET /sale`.
- `GET /staff`. - `GET /staff`.
- `GET /fiesta-futbol-infantil/ticket`: estados y jerarquía categoría → producto → tipo para filtros de tickets.
- `GET /fiesta-futbol-infantil/merchandise`: opciones de color y talle del tenant para merchandising. - `GET /fiesta-futbol-infantil/merchandise`: opciones de color y talle del tenant para merchandising.
## Dependencias ## Dependencias

View File

@ -5,8 +5,6 @@ use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController; use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
use App\Domains\Forms\Controllers\AdminApp\SaleFormController; use App\Domains\Forms\Controllers\AdminApp\SaleFormController;
use App\Domains\Forms\Controllers\AdminApp\StaffFormController; use App\Domains\Forms\Controllers\AdminApp\StaffFormController;
use App\Domains\Forms\Controllers\AdminApp\TicketFilterFormController;
use App\Domains\Forms\Controllers\AdminApp\TicketFormController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/forms') Route::prefix('v1/adminapp/forms')
@ -15,13 +13,6 @@ Route::prefix('v1/adminapp/forms')
Route::get('event', EventFormController::class); Route::get('event', EventFormController::class);
Route::get('sale', SaleFormController::class); Route::get('sale', SaleFormController::class);
Route::get('staff', StaffFormController::class); Route::get('staff', StaffFormController::class);
Route::get('tickets-filter', TicketFilterFormController::class)
->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.forms.tickets-filter');
Route::get(
'fiesta-futbol-infantil/ticket',
TicketFormController::class
);
Route::get( Route::get(
'fiesta-futbol-infantil/merchandise', 'fiesta-futbol-infantil/merchandise',
MerchandiseFormController::class MerchandiseFormController::class

View File

@ -1,64 +0,0 @@
<?php
namespace App\Domains\Integration\Controllers;
use App\Domains\Client\Models\Client;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Requests\StoreClientIntegrationRequest;
use App\Domains\Integration\Services\ClientIntegrationService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
class ClientIntegrationController extends Controller
{
public function __construct(
private readonly ClientIntegrationService $clientIntegrationService,
) {}
public function index(Client $client): JsonResponse
{
return response()->json($this->clientIntegrationService->getAllForClient($client));
}
public function show(Client $client, string $integrationCode): JsonResponse
{
$integration = $this->clientIntegrationService->getClientIntegration($client, $integrationCode);
if (! $integration) {
return response()->json([
'code' => 'integration.not_configured',
'message' => __('api.integration.not_configured'),
], 404);
}
return response()->json($integration);
}
public function store(
StoreClientIntegrationRequest $request,
Client $client,
string $integrationCode,
): JsonResponse {
$integration = Integration::query()
->where('integration_code', $integrationCode)
->firstOrFail();
try {
$this->clientIntegrationService->updateOrCreateIntegration(
$client,
$integration,
$request->input('integration_data', []),
);
return response()->json([
'code' => 'integration.configured',
'message' => __('api.integration.configured'),
]);
} catch (\Exception $exception) {
return response()->json([
'code' => 'integration.validation_failed',
'message' => __('api.integration.validation_failed', ['error' => $exception->getMessage()]),
], 400);
}
}
}

View File

@ -2,7 +2,6 @@
namespace App\Domains\Integration\Controllers; namespace App\Domains\Integration\Controllers;
use App\Domains\Client\Models\Client;
use App\Domains\Integration\Requests\TelepagosWebhookRequest; use App\Domains\Integration\Requests\TelepagosWebhookRequest;
use App\Domains\Integration\Services\TelepagosWebhookService; use App\Domains\Integration\Services\TelepagosWebhookService;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
@ -13,12 +12,12 @@ class TelepagosWebhookController extends Controller
/** /**
* Handle the incoming Telepagos webhook. * Handle the incoming Telepagos webhook.
*/ */
public function handle(TelepagosWebhookRequest $request, Client $client, TelepagosWebhookService $service): JsonResponse public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
{ {
try { try {
$cashinId = $request->validated('id'); $cashinId = $request->validated('id');
$service->handleWebhook($client, $cashinId); $service->handleWebhook($tenantCodigo, $cashinId);
return response()->json(['status' => 'success']); return response()->json(['status' => 'success']);
} catch (\Exception $e) { } catch (\Exception $e) {

View File

@ -0,0 +1,60 @@
<?php
namespace App\Domains\Integration\Controllers;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Requests\StoreTenantIntegrationRequest;
use App\Domains\Integration\Services\TenantIntegrationService;
use Illuminate\Routing\Controller;
class TenantIntegrationController extends Controller
{
protected TenantIntegrationService $tenantIntegrationService;
public function __construct(TenantIntegrationService $tenantIntegrationService)
{
$this->tenantIntegrationService = $tenantIntegrationService;
}
public function index(string $tenantCode)
{
return response()->json($this->tenantIntegrationService->getAllForTenant($tenantCode));
}
public function show(string $tenantCode, string $integrationCode)
{
$integration = $this->tenantIntegrationService->getTenantIntegration($tenantCode, $integrationCode);
if (! $integration) {
return response()->json([
'code' => 'integration.not_configured',
'message' => __('api.integration.not_configured'),
], 404);
}
return response()->json($integration);
}
public function store(StoreTenantIntegrationRequest $request, string $tenantCode, string $integrationCode)
{
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
try {
$this->tenantIntegrationService->updateOrCreateIntegration(
$tenantCode,
$integration,
$request->input('integration_data', [])
);
return response()->json([
'code' => 'integration.configured',
'message' => __('api.integration.configured'),
]);
} catch (\Exception $e) {
return response()->json([
'code' => 'integration.validation_failed',
'message' => __('api.integration.validation_failed', ['error' => $e->getMessage()]),
], 400);
}
}
}

Some files were not shown because too many files have changed in this diff Show More