Compare commits
132 Commits
ace3f136e4
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bc57cf0ff | |||
| a78c5cee58 | |||
| cc22e33799 | |||
| 5c0b3503b7 | |||
| 8537d2ed0a | |||
| d97cc12af6 | |||
| 7a19b3a97a | |||
| a94ac7a473 | |||
| 161693509f | |||
| 93c99afb13 | |||
| 32d2b182c6 | |||
| 2632a80722 | |||
| 3cee9c28f8 | |||
| 2091b1361a | |||
| a2c5e687f9 | |||
| 172e14ae9b | |||
| 58cbeae9d3 | |||
| 1dc4e29c69 | |||
| 093e894cc3 | |||
| fdf0f3328f | |||
| 8d6bcdcc43 | |||
| 3206e293eb | |||
| aed99bd05e | |||
| f1649e0e4b | |||
| e6c4b40a37 | |||
| 15878cd9ba | |||
| d6574bfd0d | |||
| 16bc657a31 | |||
| 7cea8d3495 | |||
| 014b5bb012 | |||
| 67e6211857 | |||
| 58471cb13d | |||
| 864bed0113 | |||
| ced7d594e8 | |||
| 38e87fff6c | |||
| a8973f6171 | |||
| 8e26611097 | |||
| 817d0de6d2 | |||
| a2298c9de2 | |||
| d73b4d1daf | |||
| e6785eb5af | |||
| 1a3f564afd | |||
| e619c51ac9 | |||
| c00b3d609c | |||
| 9cfd49f233 | |||
| 58cc35fd61 | |||
| 460ed528cf | |||
| 1c2f6c4127 | |||
| 9e74e21fb5 | |||
| 7c2880646f | |||
| 4817cb28fe | |||
| c1bfab471c | |||
| de8da72354 | |||
| 4be94275f1 | |||
| 21b0517e6c | |||
| 7fbdc00c64 | |||
| 58c7a0f580 | |||
| a63aea0463 | |||
| b8251f3b63 | |||
| a919e9366b | |||
| 11dbcb4082 | |||
| ed321d6c6c | |||
| 573d4fe5e6 | |||
| bfdaf1c38b | |||
| 4de08ff2f2 | |||
| a4a4c9afbc | |||
| 630b49cad7 | |||
| e33ebf0af1 | |||
| a2592987f5 | |||
| 329e0b1953 | |||
| 97995ae728 | |||
| 7c7a295625 | |||
| 8359f0831f | |||
| a12b3dd0c8 | |||
| 1b22989252 | |||
| 8e94cf7856 | |||
| 5b089e71b2 | |||
| 45d74e166f | |||
| f50d3d0587 | |||
| 36c1c185ee | |||
| 0fae1ca1d7 | |||
| 1d7c484510 | |||
| cb98652e2f | |||
| 622a3eef86 | |||
| 498b4d9eac | |||
| 7d9489169d | |||
| 3eaa3f8202 | |||
| 254faedf2c | |||
| e0f0fb1a72 | |||
| 02cf3f3773 | |||
| b294e5c46e | |||
| d02b0c5551 | |||
| ee911171be | |||
| e17d1fa15e | |||
| 2a15dc92be | |||
| 3a039a6055 | |||
| 84e45bb964 | |||
| 8aa3a26ee7 | |||
| 1de08c1ca4 | |||
| 3f9bcd84c4 | |||
| 96f26e2e9d | |||
| c4b317d5fc | |||
| 3b2977a330 | |||
| 3b36abd46d | |||
| 12697c2268 | |||
| f4638bc984 | |||
| c3713c62a6 | |||
| 4a51f3afde | |||
| f1df6a5918 | |||
| dbeaf19513 | |||
| dd76d5d951 | |||
| f603a82b5e | |||
| b478c23f3b | |||
| 6858b387c3 | |||
| 893bea1492 | |||
| ec1d80dff2 | |||
| 3968a10f6a | |||
| cf2beb2ff5 | |||
| 484fa204b3 | |||
| 6dd057874a | |||
| 40cbac17c6 | |||
| 45e56c43a6 | |||
| cbb7b1c3a1 | |||
| 6b3a12b624 | |||
| 40a7dece11 | |||
| 5ec65ce3d3 | |||
| b7e1332b8c | |||
| a087a511e0 | |||
| a20b1713d3 | |||
| d56d387933 | |||
| cba32e90e7 | |||
| a674bcfabc |
@@ -8,6 +8,7 @@ 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
|
||||||
|
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
||||||
FRONTEND_URLS=http://localhost:4200
|
FRONTEND_URLS=http://localhost:4200
|
||||||
|
|
||||||
APP_LOCALE=es
|
APP_LOCALE=es
|
||||||
@@ -31,10 +32,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
|
||||||
|
|
||||||
LOG_CHANNEL=stack
|
LOG_CHANNEL=daily
|
||||||
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
|
||||||
|
|
||||||
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
@@ -41,15 +41,18 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"url": {
|
"url": {
|
||||||
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
|
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
|
||||||
"host": [
|
"host": [
|
||||||
"{{base_url}}"
|
"{{base_url}}"
|
||||||
],
|
],
|
||||||
"path": [
|
"path": [
|
||||||
"api",
|
"api",
|
||||||
"tenants",
|
"tenants",
|
||||||
"bootstrap",
|
"bootstrap"
|
||||||
"acme.com"
|
],
|
||||||
|
"query": [
|
||||||
|
{"key": "dominio", "value": "acme.com"},
|
||||||
|
{"key": "path", "value": "/"}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
|||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
@@ -40,12 +43,34 @@ class Attachment extends Model
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function cropVariants(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(AttachmentCrop::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function desktopCrop(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(AttachmentCrop::class)
|
||||||
|
->where('variant', AttachmentCrop::DESKTOP);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function mobileCrop(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(AttachmentCrop::class)
|
||||||
|
->where('variant', AttachmentCrop::MOBILE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cropSource(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the pre-signed temporary S3 URL for this attachment.
|
* Get the pre-signed temporary S3 URL for this attachment.
|
||||||
*/
|
*/
|
||||||
public function getTemporaryUrl(int $expiresInMinutes = 10): string
|
public function getTemporaryUrl(int $expiresInMinutes = 10): string
|
||||||
{
|
{
|
||||||
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl(
|
return Storage::disk('s3')->temporaryUrl(
|
||||||
$this->path,
|
$this->path,
|
||||||
now()->addMinutes($expiresInMinutes)
|
now()->addMinutes($expiresInMinutes)
|
||||||
);
|
);
|
||||||
|
|||||||
43
app/Domains/Attachable/Models/AttachmentCrop.php
Normal file
43
app/Domains/Attachable/Models/AttachmentCrop.php
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Attachable\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'attachment_id',
|
||||||
|
'variant',
|
||||||
|
'crop_horizontal',
|
||||||
|
'crop_vertical',
|
||||||
|
'cropped_attachment_id',
|
||||||
|
])]
|
||||||
|
class AttachmentCrop extends Model
|
||||||
|
{
|
||||||
|
public const DESKTOP = 'desktop';
|
||||||
|
|
||||||
|
public const MOBILE = 'mobile';
|
||||||
|
|
||||||
|
public const VARIANTS = [self::DESKTOP, self::MOBILE];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'attachment_id' => 'integer',
|
||||||
|
'crop_horizontal' => 'array',
|
||||||
|
'crop_vertical' => 'array',
|
||||||
|
'cropped_attachment_id' => 'integer',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function attachment(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Attachment::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function croppedAttachment(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Attachment::class, 'cropped_attachment_id');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,9 @@ namespace App\Domains\Attachable\Services;
|
|||||||
use App\Domains\Attachable\Enums\AttachmentType;
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
|
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||||
use Illuminate\Http\UploadedFile;
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Symfony\Component\Mime\MimeTypes;
|
use Symfony\Component\Mime\MimeTypes;
|
||||||
@@ -13,6 +15,107 @@ use Throwable;
|
|||||||
|
|
||||||
class AttachmentService
|
class AttachmentService
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
||||||
|
*/
|
||||||
|
public function storeCroppedImageVariants(
|
||||||
|
UploadedFile|string $image,
|
||||||
|
string $path,
|
||||||
|
array $crops,
|
||||||
|
): Attachment {
|
||||||
|
$crops = $this->validateCropVariants($crops);
|
||||||
|
$storedPaths = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
return DB::transaction(function () use (
|
||||||
|
$image,
|
||||||
|
$path,
|
||||||
|
$crops,
|
||||||
|
&$storedPaths,
|
||||||
|
): Attachment {
|
||||||
|
$original = $this->store($image, $path);
|
||||||
|
$storedPaths[] = $original->path;
|
||||||
|
$contents = $this->imageContents($image);
|
||||||
|
|
||||||
|
foreach ($crops as $variant => $crop) {
|
||||||
|
$cropped = $this->storeCropVariant($contents, $path, $crop);
|
||||||
|
$storedPaths[] = $cropped->path;
|
||||||
|
$original->cropVariants()->create([
|
||||||
|
'variant' => $variant,
|
||||||
|
'crop_horizontal' => $crop['crop_horizontal'],
|
||||||
|
'crop_vertical' => $crop['crop_vertical'],
|
||||||
|
'cropped_attachment_id' => $cropped->id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $original->load('cropVariants.croppedAttachment');
|
||||||
|
});
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
if ($storedPaths !== []) {
|
||||||
|
Storage::disk('s3')->delete(array_values(array_unique($storedPaths)));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw $throwable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
||||||
|
*/
|
||||||
|
public function updateImageCropVariants(
|
||||||
|
Attachment $original,
|
||||||
|
array $crops,
|
||||||
|
): Attachment {
|
||||||
|
if ($original->type !== AttachmentType::Image) {
|
||||||
|
throw new AttachmentStorageException('Only image attachments can be cropped.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$crops = $this->validateCropVariants($crops);
|
||||||
|
$contents = Storage::disk('s3')->get($original->path);
|
||||||
|
|
||||||
|
if (! is_string($contents) || $contents === '') {
|
||||||
|
throw new AttachmentStorageException('The original image could not be read from the s3 disk.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$directory = trim(str_replace('\\', '/', dirname($original->path)), './');
|
||||||
|
$directory = $directory !== '' ? $directory : 'attachments';
|
||||||
|
$previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
|
||||||
|
$storedCrops = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
foreach ($crops as $variant => $crop) {
|
||||||
|
$storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($original, $crops, $storedCrops): void {
|
||||||
|
foreach ($crops as $variant => $crop) {
|
||||||
|
$original->cropVariants()->updateOrCreate(
|
||||||
|
['variant' => $variant],
|
||||||
|
[
|
||||||
|
'crop_horizontal' => $crop['crop_horizontal'],
|
||||||
|
'crop_vertical' => $crop['crop_vertical'],
|
||||||
|
'cropped_attachment_id' => $storedCrops[$variant]->id,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
foreach ($storedCrops as $storedCrop) {
|
||||||
|
$this->delete($storedCrop);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw $throwable;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($previousCrops as $previousCrop) {
|
||||||
|
if ($previousCrop->croppedAttachment !== null) {
|
||||||
|
$this->delete($previousCrop->croppedAttachment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $original->refresh()->load('cropVariants.croppedAttachment');
|
||||||
|
}
|
||||||
|
|
||||||
public function store(
|
public function store(
|
||||||
UploadedFile|string $file,
|
UploadedFile|string $file,
|
||||||
string $path,
|
string $path,
|
||||||
@@ -57,13 +160,30 @@ class AttachmentService
|
|||||||
|
|
||||||
public function delete(Attachment $attachment): void
|
public function delete(Attachment $attachment): void
|
||||||
{
|
{
|
||||||
$deleted = Storage::disk('s3')->delete($attachment->path);
|
$croppedAttachments = $attachment->cropVariants()
|
||||||
|
->with('croppedAttachment')
|
||||||
|
->get()
|
||||||
|
->pluck('croppedAttachment')
|
||||||
|
->filter();
|
||||||
|
$paths = $croppedAttachments
|
||||||
|
->pluck('path')
|
||||||
|
->prepend($attachment->path)
|
||||||
|
->filter()
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
$deleted = Storage::disk('s3')->delete(
|
||||||
|
count($paths) === 1 ? $paths[0] : $paths
|
||||||
|
);
|
||||||
|
|
||||||
if (! $deleted) {
|
if (! $deleted) {
|
||||||
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
|
throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$attachment->delete();
|
DB::transaction(function () use ($attachment, $croppedAttachments): void {
|
||||||
|
$attachment->delete();
|
||||||
|
Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function copy(Attachment $source, string $path): Attachment
|
public function copy(Attachment $source, string $path): Attachment
|
||||||
@@ -107,6 +227,171 @@ class AttachmentService
|
|||||||
return trim($path, '/');
|
return trim($path, '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, array{crop_horizontal?: mixed, crop_vertical?: mixed}> $crops
|
||||||
|
* @return array<string, array{crop_horizontal: array{start_percentage: float, end_percentage: float}, crop_vertical: array{start_percentage: float, end_percentage: float}}>
|
||||||
|
*/
|
||||||
|
protected function validateCropVariants(array $crops): array
|
||||||
|
{
|
||||||
|
$validated = [];
|
||||||
|
|
||||||
|
foreach (AttachmentCrop::VARIANTS as $variant) {
|
||||||
|
$crop = $crops[$variant] ?? null;
|
||||||
|
|
||||||
|
if (! is_array($crop)) {
|
||||||
|
throw new AttachmentStorageException("The {$variant} crop is required.");
|
||||||
|
}
|
||||||
|
|
||||||
|
$horizontal = $crop['crop_horizontal'] ?? null;
|
||||||
|
$vertical = $crop['crop_vertical'] ?? null;
|
||||||
|
|
||||||
|
if (! is_array($horizontal) || ! is_array($vertical)) {
|
||||||
|
throw new AttachmentStorageException(
|
||||||
|
"The {$variant} crop must contain crop_horizontal and crop_vertical ranges."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$validated[$variant] = [
|
||||||
|
'crop_horizontal' => $this->validateCropRange($horizontal, "{$variant} horizontal"),
|
||||||
|
'crop_vertical' => $this->validateCropRange($vertical, "{$variant} vertical"),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $validated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>} $crop
|
||||||
|
*/
|
||||||
|
protected function storeCropVariant(string $contents, string $path, array $crop): Attachment
|
||||||
|
{
|
||||||
|
$croppedContents = $this->cropImage(
|
||||||
|
$contents,
|
||||||
|
$crop['crop_horizontal'],
|
||||||
|
$crop['crop_vertical'],
|
||||||
|
);
|
||||||
|
|
||||||
|
return $this->store(
|
||||||
|
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
|
||||||
|
$path,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range
|
||||||
|
* @return array{start_percentage: float, end_percentage: float}
|
||||||
|
*/
|
||||||
|
protected function validateCropRange(array $range, string $axis): array
|
||||||
|
{
|
||||||
|
$start = $range['start_percentage'] ?? null;
|
||||||
|
$end = $range['end_percentage'] ?? null;
|
||||||
|
|
||||||
|
if (! is_numeric($start) || ! is_numeric($end)) {
|
||||||
|
throw new AttachmentStorageException(
|
||||||
|
"The {$axis} crop range must contain numeric start_percentage and end_percentage values."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$start = (float) $start;
|
||||||
|
$end = (float) $end;
|
||||||
|
|
||||||
|
if (! is_finite($start) || ! is_finite($end) || $start < 0 || $end > 100 || $start >= $end) {
|
||||||
|
throw new AttachmentStorageException(
|
||||||
|
"The {$axis} crop range must satisfy 0 <= start_percentage < end_percentage <= 100."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'start_percentage' => $start,
|
||||||
|
'end_percentage' => $end,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function imageContents(UploadedFile|string $image): string
|
||||||
|
{
|
||||||
|
if (is_string($image)) {
|
||||||
|
return $this->decodeBase64File($image)['data'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$contents = file_get_contents($image->getRealPath());
|
||||||
|
|
||||||
|
if (! is_string($contents) || $contents === '') {
|
||||||
|
throw new AttachmentStorageException('The image content cannot be empty.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $contents;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{contents: string, mime_type: string}
|
||||||
|
*/
|
||||||
|
protected function cropImage(
|
||||||
|
string $contents,
|
||||||
|
array $cropHorizontal,
|
||||||
|
array $cropVertical,
|
||||||
|
): array {
|
||||||
|
$source = @imagecreatefromstring($contents);
|
||||||
|
|
||||||
|
if ($source === false) {
|
||||||
|
throw new AttachmentStorageException('The attachment must contain a valid image.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$width = imagesx($source);
|
||||||
|
$height = imagesy($source);
|
||||||
|
$x = min($width - 1, (int) floor($width * $cropHorizontal['start_percentage'] / 100));
|
||||||
|
$right = min($width, (int) ceil($width * $cropHorizontal['end_percentage'] / 100));
|
||||||
|
$y = min($height - 1, (int) floor($height * $cropVertical['start_percentage'] / 100));
|
||||||
|
$bottom = min($height, (int) ceil($height * $cropVertical['end_percentage'] / 100));
|
||||||
|
$cropped = imagecrop($source, [
|
||||||
|
'x' => $x,
|
||||||
|
'y' => $y,
|
||||||
|
'width' => $right - $x,
|
||||||
|
'height' => $bottom - $y,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($cropped === false) {
|
||||||
|
throw new AttachmentStorageException('The image could not be cropped.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->encodeImage($cropped, $contents);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{contents: string, mime_type: string}
|
||||||
|
*/
|
||||||
|
protected function encodeImage(\GdImage $image, string $originalContents): array
|
||||||
|
{
|
||||||
|
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($originalContents);
|
||||||
|
$mimeType = is_string($mimeType) ? strtolower($mimeType) : '';
|
||||||
|
|
||||||
|
ob_start();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$encoded = match ($mimeType) {
|
||||||
|
'image/jpeg' => imagejpeg($image, null, 90),
|
||||||
|
'image/gif' => imagegif($image),
|
||||||
|
'image/webp' => imagewebp($image, null, 90),
|
||||||
|
'image/avif' => function_exists('imageavif') && imageavif($image, null, 90),
|
||||||
|
default => imagepng($image),
|
||||||
|
};
|
||||||
|
$output = ob_get_contents();
|
||||||
|
} finally {
|
||||||
|
ob_end_clean();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! $encoded || ! is_string($output) || $output === '') {
|
||||||
|
throw new AttachmentStorageException('The cropped image could not be encoded.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'contents' => $output,
|
||||||
|
'mime_type' => match ($mimeType) {
|
||||||
|
'image/jpeg', 'image/gif', 'image/webp', 'image/avif' => $mimeType,
|
||||||
|
default => 'image/png',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
||||||
{
|
{
|
||||||
if ($file instanceof UploadedFile) {
|
if ($file instanceof UploadedFile) {
|
||||||
|
|||||||
33
app/Domains/Attachable/documentacion/README.md
Normal file
33
app/Domains/Attachable/documentacion/README.md
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# Dominio Attachable
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
## Componentes principales
|
||||||
|
|
||||||
|
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
|
||||||
|
- `Models/AttachmentCrop.php`: relaciona un original con su crop desktop o mobile y la imagen generada.
|
||||||
|
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
|
||||||
|
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
|
||||||
|
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
|
||||||
|
|
||||||
|
## Flujo principal
|
||||||
|
|
||||||
|
1. El consumidor entrega un `UploadedFile` o una cadena Base64 y un directorio.
|
||||||
|
2. El servicio valida el contenido, detecta MIME/extensión y genera una clave UUID.
|
||||||
|
3. El archivo se guarda en el disco `s3`.
|
||||||
|
4. Se crea el registro `Attachment`; ante error se elimina el objeto que había sido subido.
|
||||||
|
|
||||||
|
## API y dependencias
|
||||||
|
|
||||||
|
No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog` y `Tenant`. Depende de Laravel Storage, Symfony Mime y del modelo `Attachment`.
|
||||||
|
|
||||||
|
## Consideraciones
|
||||||
|
|
||||||
|
- El directorio no puede quedar vacío después de normalizarlo.
|
||||||
|
- Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`.
|
||||||
|
- `attachment_crops` guarda una fila por variante con los rangos horizontal/vertical y el attachment procesado.
|
||||||
|
- Al eliminar el original mediante el servicio también se eliminan todas sus variantes recortadas.
|
||||||
|
- La eliminación se considera fallida si S3 no confirma el borrado.
|
||||||
|
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.
|
||||||
42
app/Domains/Auth/Controllers/AdminAppLoginController.php
Normal file
42
app/Domains/Auth/Controllers/AdminAppLoginController.php
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Requests\AdminAppLoginRequest;
|
||||||
|
use App\Domains\Auth\Resources\UserResource;
|
||||||
|
use App\Domains\Auth\Services\PasswordLoginService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
|
||||||
|
class AdminAppLoginController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PasswordLoginService $passwordLoginService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function __invoke(AdminAppLoginRequest $request): JsonResponse
|
||||||
|
{
|
||||||
|
$credentials = $request->validated();
|
||||||
|
$user = $this->passwordLoginService->authenticateAdminApp(
|
||||||
|
$credentials['email'],
|
||||||
|
$credentials['password'],
|
||||||
|
$request->ip(),
|
||||||
|
$request->userAgent(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$expirationMinutes = (int) config('sanctum.expiration');
|
||||||
|
$token = $user->createToken(
|
||||||
|
'adminapp-token',
|
||||||
|
['adminapp'],
|
||||||
|
now()->addMinutes($expirationMinutes),
|
||||||
|
)->plainTextToken;
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'code' => 'auth.login_success',
|
||||||
|
'message' => __('api.auth.login_success'),
|
||||||
|
'token' => $token,
|
||||||
|
'token_type' => 'Bearer',
|
||||||
|
'user' => UserResource::make($user),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
26
app/Domains/Auth/Controllers/AdminAppMeController.php
Normal file
26
app/Domains/Auth/Controllers/AdminAppMeController.php
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Auth\Resources\AdminAppMeResource;
|
||||||
|
use App\Domains\Auth\Services\AdminAppContextService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class AdminAppMeController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly AdminAppContextService $adminAppContextService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function __invoke(Request $request): AdminAppMeResource
|
||||||
|
{
|
||||||
|
/** @var User $user */
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
return AdminAppMeResource::make(
|
||||||
|
$this->adminAppContextService->load($user)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?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);
|
||||||
|
}
|
||||||
|
}
|
||||||
42
app/Domains/Auth/Controllers/ScannerLoginController.php
Normal file
42
app/Domains/Auth/Controllers/ScannerLoginController.php
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Requests\ScannerLoginRequest;
|
||||||
|
use App\Domains\Auth\Resources\UserResource;
|
||||||
|
use App\Domains\Auth\Services\PasswordLoginService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
|
||||||
|
class ScannerLoginController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PasswordLoginService $passwordLoginService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function __invoke(ScannerLoginRequest $request): JsonResponse
|
||||||
|
{
|
||||||
|
$credentials = $request->validated();
|
||||||
|
$user = $this->passwordLoginService->authenticateScanner(
|
||||||
|
$credentials['email'],
|
||||||
|
$credentials['password'],
|
||||||
|
$request->ip(),
|
||||||
|
$request->userAgent(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$expirationMinutes = (int) config('sanctum.expiration');
|
||||||
|
$token = $user->createToken(
|
||||||
|
'scanner-token',
|
||||||
|
['scanner'],
|
||||||
|
now()->addMinutes($expirationMinutes),
|
||||||
|
)->plainTextToken;
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'code' => 'auth.login_success',
|
||||||
|
'message' => __('api.auth.login_success'),
|
||||||
|
'token' => $token,
|
||||||
|
'token_type' => 'Bearer',
|
||||||
|
'user' => UserResource::make($user),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
24
app/Domains/Auth/Controllers/ScannerMeController.php
Normal file
24
app/Domains/Auth/Controllers/ScannerMeController.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Auth\Resources\ScannerMeResource;
|
||||||
|
use App\Domains\Auth\Services\ScannerContextService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class ScannerMeController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ScannerContextService $scannerContextService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function __invoke(Request $request): ScannerMeResource
|
||||||
|
{
|
||||||
|
/** @var User $user */
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
return ScannerMeResource::make($this->scannerContextService->load($user));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,10 +7,16 @@ 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', 'status'])]
|
#[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';
|
||||||
|
|||||||
@@ -2,22 +2,32 @@
|
|||||||
|
|
||||||
namespace App\Domains\Auth\Models;
|
namespace App\Domains\Auth\Models;
|
||||||
|
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use App\Domains\Authorization\Models\Role;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Database\Factories\UserFactory;
|
use Database\Factories\UserFactory;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||||
use Illuminate\Notifications\Notifiable;
|
use Illuminate\Notifications\Notifiable;
|
||||||
use Laravel\Sanctum\HasApiTokens;
|
use Laravel\Sanctum\HasApiTokens;
|
||||||
|
|
||||||
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id'])]
|
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo'])]
|
||||||
#[Hidden(['password', 'remember_token'])]
|
#[Hidden(['password', 'remember_token'])]
|
||||||
class User extends Authenticatable
|
class User extends Authenticatable
|
||||||
{
|
{
|
||||||
/** @use HasFactory<UserFactory> */
|
/** @use HasFactory<UserFactory> */
|
||||||
use HasApiTokens, HasFactory, Notifiable;
|
use HasApiTokens, HasFactory, Notifiable;
|
||||||
|
|
||||||
|
protected $attributes = [
|
||||||
|
'rol_codigo' => RoleCode::User->value,
|
||||||
|
];
|
||||||
|
|
||||||
protected static function newFactory(): UserFactory
|
protected static function newFactory(): UserFactory
|
||||||
{
|
{
|
||||||
return UserFactory::new();
|
return UserFactory::new();
|
||||||
@@ -35,6 +45,43 @@ class User extends Authenticatable
|
|||||||
return $this->hasMany(LoginAttempt::class);
|
return $this->hasMany(LoginAttempt::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Role, $this>
|
||||||
|
*/
|
||||||
|
public function role(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasPermission(string $permissionCode): bool
|
||||||
|
{
|
||||||
|
return $this->role()
|
||||||
|
->whereHas(
|
||||||
|
'permissions',
|
||||||
|
fn ($query) => $query->where('permisos.codigo', $permissionCode)
|
||||||
|
)
|
||||||
|
->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Tenant, $this>
|
||||||
|
*/
|
||||||
|
public function tenant(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Tenant::class, 'tenant_codigo', 'codigo');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsToMany<Category, $this> */
|
||||||
|
public function scanCategories(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(
|
||||||
|
Category::class,
|
||||||
|
'category_scanners',
|
||||||
|
'user_id',
|
||||||
|
'categoria_id',
|
||||||
|
)->withTimestamps();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array<string, string>
|
* @return array<string, string>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
36
app/Domains/Auth/Requests/AdminAppLoginRequest.php
Normal file
36
app/Domains/Auth/Requests/AdminAppLoginRequest.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
class AdminAppLoginRequest 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'],
|
||||||
|
'password' => ['required', 'string'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?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'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
5
app/Domains/Auth/Requests/ScannerLoginRequest.php
Normal file
5
app/Domains/Auth/Requests/ScannerLoginRequest.php
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Requests;
|
||||||
|
|
||||||
|
class ScannerLoginRequest extends AdminAppLoginRequest {}
|
||||||
25
app/Domains/Auth/Resources/AdminAppMeResource.php
Normal file
25
app/Domains/Auth/Resources/AdminAppMeResource.php
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Tenant\Resources\TenantResource;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @mixin User
|
||||||
|
*/
|
||||||
|
class AdminAppMeResource extends JsonResource
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'user' => UserResource::make($this->resource),
|
||||||
|
'tenant' => TenantResource::make($this->tenant),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
21
app/Domains/Auth/Resources/ScannerMeResource.php
Normal file
21
app/Domains/Auth/Resources/ScannerMeResource.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Tenant\Resources\TenantResource;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin User */
|
||||||
|
class ScannerMeResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'user' => UserResource::make($this->resource),
|
||||||
|
'tenant' => TenantResource::make($this->tenant),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,12 @@
|
|||||||
|
|
||||||
namespace App\Domains\Auth\Resources;
|
namespace App\Domains\Auth\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @mixin \App\Domains\Auth\Models\User
|
* @mixin User
|
||||||
*/
|
*/
|
||||||
class UserResource extends JsonResource
|
class UserResource extends JsonResource
|
||||||
{
|
{
|
||||||
@@ -21,6 +22,8 @@ class UserResource extends JsonResource
|
|||||||
'email' => $this->email,
|
'email' => $this->email,
|
||||||
'dni' => $this->dni,
|
'dni' => $this->dni,
|
||||||
'telefono' => $this->telefono,
|
'telefono' => $this->telefono,
|
||||||
|
'rol_codigo' => $this->rol_codigo,
|
||||||
|
'tenant_codigo' => $this->tenant_codigo,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
26
app/Domains/Auth/Services/AdminAppContextService.php
Normal file
26
app/Domains/Auth/Services/AdminAppContextService.php
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
|
||||||
|
class AdminAppContextService
|
||||||
|
{
|
||||||
|
public function load(User $user): User
|
||||||
|
{
|
||||||
|
$tenant = $user->tenant()
|
||||||
|
->with([
|
||||||
|
'menues' => fn ($query) => $query
|
||||||
|
->whereHas(
|
||||||
|
'roles',
|
||||||
|
fn ($query) => $query->where('codigo', RoleCode::AdminApp->value)
|
||||||
|
),
|
||||||
|
])
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$user->setRelation('tenant', $tenant);
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
}
|
||||||
22
app/Domains/Auth/Services/AdminCredentialVerifier.php
Normal file
22
app/Domains/Auth/Services/AdminCredentialVerifier.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -155,16 +155,19 @@ 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 || $tenantDomain === null || $host !== $tenantDomain) {
|
if ($host === null
|
||||||
|
|| $tenantDomain === null
|
||||||
|
|| $host !== $tenantDomain
|
||||||
|
|| $returnPath !== $tenant->base_path) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,14 +4,23 @@ 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\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;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
class PasswordLoginService
|
class PasswordLoginService
|
||||||
{
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||||
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @throws AccountLockedException
|
* @throws AccountLockedException
|
||||||
* @throws ValidationException
|
* @throws ValidationException
|
||||||
@@ -22,6 +31,77 @@ class PasswordLoginService
|
|||||||
string $tenantCode,
|
string $tenantCode,
|
||||||
?string $ipAddress,
|
?string $ipAddress,
|
||||||
?string $userAgent,
|
?string $userAgent,
|
||||||
|
): User {
|
||||||
|
return $this->authenticateUser(
|
||||||
|
$email,
|
||||||
|
$password,
|
||||||
|
$tenantCode,
|
||||||
|
$ipAddress,
|
||||||
|
$userAgent,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate a tenant-bound AdminApp user without requiring the caller
|
||||||
|
* to know their tenant code beforehand.
|
||||||
|
*
|
||||||
|
* @throws AccountLockedException
|
||||||
|
* @throws ValidationException
|
||||||
|
*/
|
||||||
|
public function authenticateAdminApp(
|
||||||
|
string $email,
|
||||||
|
string $password,
|
||||||
|
?string $ipAddress,
|
||||||
|
?string $userAgent,
|
||||||
|
): User {
|
||||||
|
return $this->authenticateUser(
|
||||||
|
$email,
|
||||||
|
$password,
|
||||||
|
null,
|
||||||
|
$ipAddress,
|
||||||
|
$userAgent,
|
||||||
|
RoleCode::AdminApp,
|
||||||
|
true,
|
||||||
|
null,
|
||||||
|
PasswordResetRequested::CHANNEL_ADMINAPP,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authenticate a tenant-bound user authorized to scan tickets.
|
||||||
|
*
|
||||||
|
* @throws AccountLockedException
|
||||||
|
* @throws ValidationException
|
||||||
|
*/
|
||||||
|
public function authenticateScanner(
|
||||||
|
string $email,
|
||||||
|
string $password,
|
||||||
|
?string $ipAddress,
|
||||||
|
?string $userAgent,
|
||||||
|
): User {
|
||||||
|
return $this->authenticateUser(
|
||||||
|
$email,
|
||||||
|
$password,
|
||||||
|
null,
|
||||||
|
$ipAddress,
|
||||||
|
$userAgent,
|
||||||
|
null,
|
||||||
|
true,
|
||||||
|
PermissionCode::ScanTickets->value,
|
||||||
|
PasswordResetRequested::CHANNEL_SCANNER,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function authenticateUser(
|
||||||
|
string $email,
|
||||||
|
string $password,
|
||||||
|
?string $tenantCode,
|
||||||
|
?string $ipAddress,
|
||||||
|
?string $userAgent,
|
||||||
|
?RoleCode $requiredRole = RoleCode::User,
|
||||||
|
bool $requiresTenant = false,
|
||||||
|
?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();
|
||||||
@@ -34,17 +114,37 @@ class PasswordLoginService
|
|||||||
$ipAddress,
|
$ipAddress,
|
||||||
$userAgent,
|
$userAgent,
|
||||||
$now,
|
$now,
|
||||||
|
$requiredRole,
|
||||||
|
$requiresTenant,
|
||||||
|
$requiredPermission,
|
||||||
|
$passwordResetChannel,
|
||||||
): array {
|
): array {
|
||||||
$user = User::query()
|
$user = User::query()
|
||||||
->where('email', $normalizedEmail)
|
->where('email', $normalizedEmail)
|
||||||
|
->when(
|
||||||
|
$requiredRole !== null,
|
||||||
|
fn ($query) => $query->where('rol_codigo', $requiredRole->value),
|
||||||
|
)
|
||||||
|
->when(
|
||||||
|
$requiredPermission !== null,
|
||||||
|
fn ($query) => $query->whereHas(
|
||||||
|
'role.permissions',
|
||||||
|
fn ($query) => $query->where('permisos.codigo', $requiredPermission)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
->when(
|
||||||
|
$requiresTenant,
|
||||||
|
fn ($query) => $query->whereNotNull('tenant_codigo'),
|
||||||
|
)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
$attemptTenantCode = $tenantCode ?? $user?->tenant_codigo;
|
||||||
|
|
||||||
if ($user?->locked_until?->isFuture()) {
|
if ($user?->locked_until?->isFuture()) {
|
||||||
$this->recordAttempt(
|
$this->recordAttempt(
|
||||||
$user,
|
$user,
|
||||||
$normalizedEmail,
|
$normalizedEmail,
|
||||||
$tenantCode,
|
$attemptTenantCode,
|
||||||
LoginAttempt::OUTCOME_ACCOUNT_LOCKED,
|
LoginAttempt::OUTCOME_ACCOUNT_LOCKED,
|
||||||
$ipAddress,
|
$ipAddress,
|
||||||
$userAgent,
|
$userAgent,
|
||||||
@@ -66,8 +166,13 @@ class PasswordLoginService
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($user === null || ! Hash::check($password, $user->password)) {
|
if ($user === null || ! Hash::check($password, $user->password)) {
|
||||||
if ($user !== null) {
|
if ($user !== null && $attemptTenantCode !== null) {
|
||||||
$this->registerFailure($user, $now);
|
$this->registerFailure(
|
||||||
|
$user,
|
||||||
|
$now,
|
||||||
|
$attemptTenantCode,
|
||||||
|
$passwordResetChannel,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$outcome = $user?->locked_until?->isFuture()
|
$outcome = $user?->locked_until?->isFuture()
|
||||||
@@ -76,7 +181,7 @@ class PasswordLoginService
|
|||||||
$this->recordAttempt(
|
$this->recordAttempt(
|
||||||
$user,
|
$user,
|
||||||
$normalizedEmail,
|
$normalizedEmail,
|
||||||
$tenantCode,
|
$attemptTenantCode,
|
||||||
$outcome,
|
$outcome,
|
||||||
$ipAddress,
|
$ipAddress,
|
||||||
$userAgent,
|
$userAgent,
|
||||||
@@ -100,7 +205,7 @@ class PasswordLoginService
|
|||||||
$this->recordAttempt(
|
$this->recordAttempt(
|
||||||
$user,
|
$user,
|
||||||
$normalizedEmail,
|
$normalizedEmail,
|
||||||
$tenantCode,
|
$attemptTenantCode,
|
||||||
LoginAttempt::OUTCOME_SUCCESS,
|
LoginAttempt::OUTCOME_SUCCESS,
|
||||||
$ipAddress,
|
$ipAddress,
|
||||||
$userAgent,
|
$userAgent,
|
||||||
@@ -126,8 +231,12 @@ class PasswordLoginService
|
|||||||
return $result['user'];
|
return $result['user'];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function registerFailure(User $user, CarbonImmutable $now): void
|
private function registerFailure(
|
||||||
{
|
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'));
|
||||||
@@ -138,6 +247,8 @@ class PasswordLoginService
|
|||||||
? $user->failed_login_attempts + 1
|
? $user->failed_login_attempts + 1
|
||||||
: 1;
|
: 1;
|
||||||
|
|
||||||
|
$previousAttempts = $user->failed_login_attempts;
|
||||||
|
|
||||||
$user->forceFill([
|
$user->forceFill([
|
||||||
'failed_login_attempts' => $attempts,
|
'failed_login_attempts' => $attempts,
|
||||||
'last_failed_login_at' => $now,
|
'last_failed_login_at' => $now,
|
||||||
@@ -145,12 +256,39 @@ class PasswordLoginService
|
|||||||
? $now->addMinutes($lockMinutes)
|
? $now->addMinutes($lockMinutes)
|
||||||
: null,
|
: null,
|
||||||
])->save();
|
])->save();
|
||||||
|
|
||||||
|
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
|
||||||
|
try {
|
||||||
|
if ($passwordResetChannel === PasswordResetRequested::CHANNEL_ADMINAPP) {
|
||||||
|
$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) {
|
||||||
|
Log::error('Failed to trigger reset password on account lock', [
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'exception' => $e,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function recordAttempt(
|
private function recordAttempt(
|
||||||
?User $user,
|
?User $user,
|
||||||
string $normalizedEmail,
|
string $normalizedEmail,
|
||||||
string $tenantCode,
|
?string $tenantCode,
|
||||||
string $outcome,
|
string $outcome,
|
||||||
?string $ipAddress,
|
?string $ipAddress,
|
||||||
?string $userAgent,
|
?string $userAgent,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ 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;
|
||||||
@@ -11,38 +12,26 @@ use Throwable;
|
|||||||
|
|
||||||
class ResetPasswordAttemptService
|
class ResetPasswordAttemptService
|
||||||
{
|
{
|
||||||
public function createForEmail(string $email, string $tenantCode): void
|
public function createForEmail(
|
||||||
{
|
string $email,
|
||||||
|
string $tenantCode,
|
||||||
|
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||||
|
): void {
|
||||||
$emailFingerprint = $this->emailFingerprint($email);
|
$emailFingerprint = $this->emailFingerprint($email);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$attemptId = DB::transaction(function () use ($email, $emailFingerprint): ?int {
|
$attemptId = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?int {
|
||||||
$user = User::query()
|
$user = User::query()
|
||||||
->where('email', $email)
|
->where('email', $email)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($user === null) {
|
return $this->createAttemptForUser(
|
||||||
Log::warning('Password reset attempt was not created because the user was not found.', [
|
$user,
|
||||||
'email_fingerprint' => $emailFingerprint,
|
$reason,
|
||||||
]);
|
$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(),
|
|
||||||
'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.', [
|
||||||
@@ -53,20 +42,108 @@ class ResetPasswordAttemptService
|
|||||||
throw $exception;
|
throw $exception;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($attemptId !== null) {
|
$this->dispatchPasswordResetRequested(
|
||||||
try {
|
$attemptId,
|
||||||
PasswordResetRequested::dispatch($attemptId, $tenantCode);
|
$tenantCode,
|
||||||
} catch (Throwable $exception) {
|
PasswordResetRequested::CHANNEL_STOREFRONT,
|
||||||
Log::error('Failed to dispatch password reset email.', [
|
$emailFingerprint,
|
||||||
'attempt_id' => $attemptId,
|
);
|
||||||
'tenant_code' => $tenantCode,
|
}
|
||||||
'email_fingerprint' => $emailFingerprint,
|
|
||||||
'exception' => $exception,
|
|
||||||
]);
|
|
||||||
|
|
||||||
throw $exception;
|
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,
|
||||||
|
'tenant_code' => $user->tenant_codigo,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::error('Failed to create AdminApp password reset attempt.', [
|
||||||
|
'email_fingerprint' => $emailFingerprint,
|
||||||
|
'exception' => $exception,
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->dispatchPasswordResetRequested(
|
||||||
|
$result['attempt_id'] ?? null,
|
||||||
|
$result['tenant_code'] ?? null,
|
||||||
|
PasswordResetRequested::CHANNEL_ADMINAPP,
|
||||||
|
$emailFingerprint,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createForScannerEmail(
|
||||||
|
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): bool
|
public function validateCode(string $email, string $code): bool
|
||||||
@@ -168,6 +245,61 @@ 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,
|
||||||
|
]);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|||||||
24
app/Domains/Auth/Services/ScannerContextService.php
Normal file
24
app/Domains/Auth/Services/ScannerContextService.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
|
||||||
|
class ScannerContextService
|
||||||
|
{
|
||||||
|
public function load(User $user): User
|
||||||
|
{
|
||||||
|
$tenant = $user->tenant()
|
||||||
|
->with([
|
||||||
|
'menues' => fn ($query) => $query->whereHas(
|
||||||
|
'roles',
|
||||||
|
fn ($query) => $query->where('codigo', $user->rol_codigo)
|
||||||
|
),
|
||||||
|
])
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$user->setRelation('tenant', $tenant);
|
||||||
|
|
||||||
|
return $user;
|
||||||
|
}
|
||||||
|
}
|
||||||
36
app/Domains/Auth/documentacion/README.md
Normal file
36
app/Domains/Auth/documentacion/README.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Dominio Auth
|
||||||
|
|
||||||
|
## Propósito
|
||||||
|
|
||||||
|
Gestiona identidad y acceso de usuarios de la tienda y del panel administrativo: registro, inicio y cierre de sesión, perfil, autenticación con Google y recuperación de contraseña.
|
||||||
|
|
||||||
|
## Modelo y servicios
|
||||||
|
|
||||||
|
- `User`: usuario autenticable, asociado a tenant, rol, intentos de acceso y categorías habilitadas para escaneo.
|
||||||
|
- `LoginAttempt` y `ResetPasswordAttempt`: trazabilidad de accesos y recuperación de contraseña.
|
||||||
|
- `PasswordLoginService`: autentica tienda y AdminApp, incluyendo bloqueo por intentos.
|
||||||
|
- `RegisterUserService` y `ProfileService`: alta y edición del usuario.
|
||||||
|
- `ResetPasswordAttemptService`: crea, valida y consume códigos de recuperación.
|
||||||
|
- `GoogleAuthService`: redirección, callback e intercambio de código para Google OAuth.
|
||||||
|
- `AdminAppContextService`: carga el contexto requerido por un usuario administrativo.
|
||||||
|
|
||||||
|
## Endpoints públicos
|
||||||
|
|
||||||
|
- `POST /register`, `POST /login` y `POST /logout`.
|
||||||
|
- `GET /me` y `PUT /me`, protegidos por `auth:sanctum`.
|
||||||
|
- Creación, validación y aplicación de intentos de recuperación bajo `/password`.
|
||||||
|
- `POST /auth/google/exchange` para canjear el código de autenticación.
|
||||||
|
- `POST /v1/adminapp/login` y consulta del usuario administrativo dentro del grupo autenticado de AdminApp.
|
||||||
|
|
||||||
|
## Validación y respuestas
|
||||||
|
|
||||||
|
Los `FormRequest` validan cada operación. `UserResource` y `AdminAppMeResource` definen las representaciones de salida. Los endpoints sensibles aplican `auth:sanctum` y límites de frecuencia.
|
||||||
|
|
||||||
|
## Dependencias y eventos
|
||||||
|
|
||||||
|
Se relaciona con `Tenant` y `Authorization`; el registro y la recuperación disparan flujos atendidos por `Notification`. El carrito invitado puede integrarse al usuario autenticado mediante el dominio `Cart`.
|
||||||
|
|
||||||
|
## Consideraciones
|
||||||
|
|
||||||
|
- La resolución del tenant forma parte de la autenticación y no debe omitirse.
|
||||||
|
- Los cambios en reglas de login deben conservar los límites de intentos y el manejo de `AccountLockedException`.
|
||||||
20
app/Domains/Auth/routes/adminapp.php
Normal file
20
app/Domains/Auth/routes/adminapp.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Auth\Controllers\AdminAppLoginController;
|
||||||
|
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;
|
||||||
|
|
||||||
|
Route::prefix('v1/adminapp')->group(function (): void {
|
||||||
|
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'])
|
||||||
|
->get('me', AdminAppMeController::class);
|
||||||
|
});
|
||||||
@@ -23,3 +23,6 @@ Route::post('/auth/google/exchange', GoogleTokenExchangeController::class);
|
|||||||
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
|
||||||
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
Route::middleware('auth:sanctum')->get('/me', MeController::class);
|
||||||
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
|
||||||
|
|
||||||
|
require __DIR__.'/adminapp.php';
|
||||||
|
require __DIR__.'/scanner.php';
|
||||||
|
|||||||
20
app/Domains/Auth/routes/scanner.php
Normal file
20
app/Domains/Auth/routes/scanner.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Auth\Controllers\CreateScannerResetPasswordAttemptController;
|
||||||
|
use App\Domains\Auth\Controllers\ResetPasswordController;
|
||||||
|
use App\Domains\Auth\Controllers\ScannerLoginController;
|
||||||
|
use App\Domains\Auth\Controllers\ScannerMeController;
|
||||||
|
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::prefix('v1/scanner')->group(function (): void {
|
||||||
|
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'])
|
||||||
|
->get('me', ScannerMeController::class);
|
||||||
|
});
|
||||||
8
app/Domains/Authorization/Enums/PermissionCode.php
Normal file
8
app/Domains/Authorization/Enums/PermissionCode.php
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Authorization\Enums;
|
||||||
|
|
||||||
|
enum PermissionCode: string
|
||||||
|
{
|
||||||
|
case ScanTickets = 'tickets.escanear';
|
||||||
|
}
|
||||||
11
app/Domains/Authorization/Enums/RoleCode.php
Normal file
11
app/Domains/Authorization/Enums/RoleCode.php
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Authorization\Enums;
|
||||||
|
|
||||||
|
enum RoleCode: string
|
||||||
|
{
|
||||||
|
case Admin = 'admin';
|
||||||
|
case AdminApp = 'adminapp';
|
||||||
|
case Scanner = 'scanner';
|
||||||
|
case User = 'user';
|
||||||
|
}
|
||||||
32
app/Domains/Authorization/Models/Permission.php
Normal file
32
app/Domains/Authorization/Models/Permission.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Authorization\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
|
|
||||||
|
class Permission extends Model
|
||||||
|
{
|
||||||
|
protected $table = 'permisos';
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'codigo',
|
||||||
|
'nombre',
|
||||||
|
'descripcion',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsToMany<Role, $this>
|
||||||
|
*/
|
||||||
|
public function roles(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(
|
||||||
|
Role::class,
|
||||||
|
'roles_permisos',
|
||||||
|
'codigo_permiso',
|
||||||
|
'rol_codigo',
|
||||||
|
'codigo',
|
||||||
|
'codigo'
|
||||||
|
)->withTimestamps();
|
||||||
|
}
|
||||||
|
}
|
||||||
59
app/Domains/Authorization/Models/Role.php
Normal file
59
app/Domains/Authorization/Models/Role.php
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Authorization\Models;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Menu\Models\Menu;
|
||||||
|
use App\Domains\Menu\Models\MenuRole;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
class Role extends Model
|
||||||
|
{
|
||||||
|
protected $table = 'roles';
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'codigo',
|
||||||
|
'nombre',
|
||||||
|
'descripcion',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsToMany<Permission, $this>
|
||||||
|
*/
|
||||||
|
public function permissions(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(
|
||||||
|
Permission::class,
|
||||||
|
'roles_permisos',
|
||||||
|
'rol_codigo',
|
||||||
|
'codigo_permiso',
|
||||||
|
'codigo',
|
||||||
|
'codigo'
|
||||||
|
)->withTimestamps();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return HasMany<User, $this>
|
||||||
|
*/
|
||||||
|
public function users(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(User::class, 'rol_codigo', 'codigo');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsToMany<Menu, $this>
|
||||||
|
*/
|
||||||
|
public function menus(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(
|
||||||
|
Menu::class,
|
||||||
|
'roles_menues',
|
||||||
|
'rol_codigo',
|
||||||
|
'menu_codigo',
|
||||||
|
'codigo',
|
||||||
|
'code'
|
||||||
|
)->using(MenuRole::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
32
app/Domains/Authorization/Models/RolePermission.php
Normal file
32
app/Domains/Authorization/Models/RolePermission.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Authorization\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class RolePermission extends Model
|
||||||
|
{
|
||||||
|
protected $table = 'roles_permisos';
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'codigo_permiso',
|
||||||
|
'rol_codigo',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Permission, $this>
|
||||||
|
*/
|
||||||
|
public function permission(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Permission::class, 'codigo_permiso', 'codigo');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return BelongsTo<Role, $this>
|
||||||
|
*/
|
||||||
|
public function role(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
||||||
|
}
|
||||||
|
}
|
||||||
26
app/Domains/Authorization/documentacion/README.md
Normal file
26
app/Domains/Authorization/documentacion/README.md
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Dominio Authorization
|
||||||
|
|
||||||
|
## Propósito
|
||||||
|
|
||||||
|
Define el esquema de roles y permisos usado para autorizar funcionalidades de la aplicación.
|
||||||
|
|
||||||
|
## Componentes principales
|
||||||
|
|
||||||
|
- `Enums/RoleCode.php`: códigos de roles conocidos por el sistema.
|
||||||
|
- `Models/Role.php`: rol con relaciones hacia permisos, usuarios y menús.
|
||||||
|
- `Models/Permission.php`: permiso asignable a uno o más roles.
|
||||||
|
- `Models/RolePermission.php`: entidad de asociación entre rol y permiso.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
No expone controladores ni rutas propias. Su información se consume desde autenticación, menús, políticas y middleware de autorización.
|
||||||
|
|
||||||
|
## Relaciones relevantes
|
||||||
|
|
||||||
|
- `Role` tiene muchos usuarios del dominio `Auth`.
|
||||||
|
- Roles y permisos mantienen una relación muchos-a-muchos.
|
||||||
|
- Los roles determinan los menús disponibles mediante el dominio `Menu`.
|
||||||
|
|
||||||
|
## Consideraciones
|
||||||
|
|
||||||
|
Los códigos definidos en `RoleCode` funcionan como contrato entre datos persistidos y lógica de aplicación. Al agregar un rol o permiso se deben revisar seeds, asociaciones y consumidores.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Requests\AdminAppBootstrapRequest;
|
||||||
|
use App\Domains\Bootstrap\Resources\AdminAppBootstrapResource;
|
||||||
|
use App\Domains\Bootstrap\Services\AdminAppBootstrapService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
|
||||||
|
class AdminAppBootstrapController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(protected AdminAppBootstrapService $bootstrapService) {}
|
||||||
|
|
||||||
|
public function __invoke(AdminAppBootstrapRequest $request): AdminAppBootstrapResource
|
||||||
|
{
|
||||||
|
return AdminAppBootstrapResource::make(
|
||||||
|
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Requests\ScannerBootstrapRequest;
|
||||||
|
use App\Domains\Bootstrap\Resources\ScannerBootstrapResource;
|
||||||
|
use App\Domains\Bootstrap\Services\ScannerBootstrapService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
|
||||||
|
class ScannerBootstrapController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(protected ScannerBootstrapService $bootstrapService) {}
|
||||||
|
|
||||||
|
public function __invoke(ScannerBootstrapRequest $request): ScannerBootstrapResource
|
||||||
|
{
|
||||||
|
return ScannerBootstrapResource::make(
|
||||||
|
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Requests\TenantBootstrapRequest;
|
||||||
|
use App\Domains\Bootstrap\Services\TenantBootstrapService;
|
||||||
|
use App\Domains\Tenant\Resources\TenantResource;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
|
||||||
|
class TenantBootstrapController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(protected TenantBootstrapService $bootstrapService) {}
|
||||||
|
|
||||||
|
public function __invoke(TenantBootstrapRequest $request): TenantResource
|
||||||
|
{
|
||||||
|
return TenantResource::make(
|
||||||
|
$this->bootstrapService->get(
|
||||||
|
(string) $request->validated('dominio'),
|
||||||
|
(string) $request->validated('path'),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Requests;
|
||||||
|
|
||||||
|
class AdminAppBootstrapRequest extends TenantBootstrapRequest {}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Requests;
|
||||||
|
|
||||||
|
class ScannerBootstrapRequest extends TenantBootstrapRequest {}
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Domains\Tenant\Requests;
|
namespace App\Domains\Bootstrap\Requests;
|
||||||
|
|
||||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
class BootstrapTenantRequest extends FormRequest
|
class TenantBootstrapRequest extends FormRequest
|
||||||
{
|
{
|
||||||
protected bool $hasInvalidDomain = false;
|
protected bool $hasInvalidDomain = false;
|
||||||
|
|
||||||
|
protected bool $hasInvalidPath = false;
|
||||||
|
|
||||||
public function authorize(): bool
|
public function authorize(): bool
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
@@ -17,20 +19,23 @@ class BootstrapTenantRequest extends FormRequest
|
|||||||
|
|
||||||
protected function prepareForValidation(): void
|
protected function prepareForValidation(): void
|
||||||
{
|
{
|
||||||
$rawDomain = $this->route('dominio');
|
$rawDomain = $this->query('dominio', $this->route('dominio'));
|
||||||
|
$rawPath = $this->query('path', '/');
|
||||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||||
|
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
|
||||||
|
|
||||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||||
&& $normalizedDomain === null;
|
&& $normalizedDomain === null;
|
||||||
|
|
||||||
|
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
|
||||||
|
|
||||||
$this->merge([
|
$this->merge([
|
||||||
'dominio' => $normalizedDomain,
|
'dominio' => $normalizedDomain,
|
||||||
|
'path' => $normalizedPath,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** @return array<string, mixed> */
|
||||||
* @return array<string, mixed>
|
|
||||||
*/
|
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
@@ -45,6 +50,17 @@ class BootstrapTenantRequest 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',
|
||||||
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\WebsiteType;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin array{website_type: WebsiteType} */
|
||||||
|
class AdminAppBootstrapResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
/** @var WebsiteType $websiteType */
|
||||||
|
$websiteType = $this->resource['website_type'];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'website_type_code' => $websiteType->codigo,
|
||||||
|
'primary_color' => $websiteType->primary_color,
|
||||||
|
'secondary_color' => $websiteType->secondary_color,
|
||||||
|
'danger_color' => $websiteType->danger_color,
|
||||||
|
'success_color' => $websiteType->success_color,
|
||||||
|
'warning_color' => $websiteType->warning_color,
|
||||||
|
'body_color' => $websiteType->body_color,
|
||||||
|
'darker_body_color' => $websiteType->darker_body_color,
|
||||||
|
'surface_color' => $websiteType->surface_color,
|
||||||
|
'background_color' => $websiteType->background_color,
|
||||||
|
'border_color' => $websiteType->border_color,
|
||||||
|
'login_header_footer_color' => $websiteType->login_header_footer_color,
|
||||||
|
'site_logo' => $websiteType->siteLogo?->getTemporaryUrl(1440),
|
||||||
|
'footer_logo' => $websiteType->footerLogo?->getTemporaryUrl(1440),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Resources;
|
||||||
|
|
||||||
|
class ScannerBootstrapResource extends AdminAppBootstrapResource {}
|
||||||
19
app/Domains/Bootstrap/Services/AdminAppBootstrapService.php
Normal file
19
app/Domains/Bootstrap/Services/AdminAppBootstrapService.php
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\WebsiteType;
|
||||||
|
|
||||||
|
class AdminAppBootstrapService
|
||||||
|
{
|
||||||
|
/** @return array{website_type: WebsiteType} */
|
||||||
|
public function get(string $domain): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'website_type' => WebsiteType::query()
|
||||||
|
->with(['siteLogo', 'footerLogo'])
|
||||||
|
->where('dominio', $domain)
|
||||||
|
->firstOrFail(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
19
app/Domains/Bootstrap/Services/ScannerBootstrapService.php
Normal file
19
app/Domains/Bootstrap/Services/ScannerBootstrapService.php
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Services;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Models\WebsiteType;
|
||||||
|
|
||||||
|
class ScannerBootstrapService
|
||||||
|
{
|
||||||
|
/** @return array{website_type: WebsiteType} */
|
||||||
|
public function get(string $domain): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'website_type' => WebsiteType::query()
|
||||||
|
->with(['siteLogo', 'footerLogo'])
|
||||||
|
->where('scanner_domain', $domain)
|
||||||
|
->firstOrFail(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
43
app/Domains/Bootstrap/Services/TenantBootstrapService.php
Normal file
43
app/Domains/Bootstrap/Services/TenantBootstrapService.php
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Bootstrap\Services;
|
||||||
|
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Domains\Tenant\Services\TenantInformationService;
|
||||||
|
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
|
||||||
|
class TenantBootstrapService
|
||||||
|
{
|
||||||
|
public function __construct(protected TenantInformationService $tenantInformationService) {}
|
||||||
|
|
||||||
|
public function get(string $domain, string $path = '/'): 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(
|
||||||
|
$tenant,
|
||||||
|
[
|
||||||
|
'menues' => fn ($query) => $query->whereHas(
|
||||||
|
'roles',
|
||||||
|
fn ($query) => $query->where('codigo', RoleCode::User->value)
|
||||||
|
),
|
||||||
|
'categories' => fn ($query) => $query->orderBy('nombre'),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
28
app/Domains/Bootstrap/documentacion/README.md
Normal file
28
app/Domains/Bootstrap/documentacion/README.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Dominio Bootstrap
|
||||||
|
|
||||||
|
## Propósito
|
||||||
|
|
||||||
|
Entrega la configuración inicial que necesitan la tienda y el panel administrativo antes de renderizar su interfaz.
|
||||||
|
|
||||||
|
## Flujos
|
||||||
|
|
||||||
|
- `TenantBootstrapService` resuelve un tenant desde el dominio solicitado y carga su información pública.
|
||||||
|
- `AdminAppBootstrapService` prepara el contexto inicial del panel administrativo para el tenant autenticado.
|
||||||
|
- Los controladores invocables transforman el resultado mediante `TenantResource` o `AdminAppBootstrapResource`.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
|
||||||
|
|
||||||
|
## Validación
|
||||||
|
|
||||||
|
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||||
|
|
||||||
|
## Dependencias
|
||||||
|
|
||||||
|
Depende principalmente de `Tenant` para resolver y cargar la tienda, y de los dominios que aportan datos al contexto administrativo.
|
||||||
|
|
||||||
|
## Consideraciones
|
||||||
|
|
||||||
|
Este dominio es un agregador de lectura. Debe mantenerse liviano y delegar la obtención de cada dato al dominio propietario.
|
||||||
9
app/Domains/Bootstrap/routes/adminapp.php
Normal file
9
app/Domains/Bootstrap/routes/adminapp.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Controllers\AdminAppBootstrapController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::get(
|
||||||
|
'v1/adminapp/bootstrap/{dominio}',
|
||||||
|
AdminAppBootstrapController::class
|
||||||
|
);
|
||||||
9
app/Domains/Bootstrap/routes/api.php
Normal file
9
app/Domains/Bootstrap/routes/api.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::get('tenants/bootstrap', TenantBootstrapController::class);
|
||||||
|
|
||||||
|
require __DIR__.'/adminapp.php';
|
||||||
|
require __DIR__.'/scanner.php';
|
||||||
9
app/Domains/Bootstrap/routes/scanner.php
Normal file
9
app/Domains/Bootstrap/routes/scanner.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Bootstrap\Controllers\ScannerBootstrapController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::get(
|
||||||
|
'v1/scanner/bootstrap/{dominio}',
|
||||||
|
ScannerBootstrapController::class
|
||||||
|
);
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Cart\Controllers;
|
namespace App\Domains\Cart\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Cart\Models\CartItem;
|
||||||
use App\Domains\Cart\Requests\AddCartItemRequest;
|
use App\Domains\Cart\Requests\AddCartItemRequest;
|
||||||
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
|
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
|
||||||
@@ -54,16 +55,56 @@ class CartController extends Controller
|
|||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
CartItem $cartItem,
|
CartItem $cartItem,
|
||||||
): CartResource {
|
): CartResource {
|
||||||
|
$updatesVariant = $request->exists('variant_id');
|
||||||
|
|
||||||
return CartResource::make(
|
return CartResource::make(
|
||||||
$this->cartService->updateItemQuantity(
|
$this->cartService->updateItem(
|
||||||
$tenant,
|
$tenant,
|
||||||
$request,
|
$request,
|
||||||
$cartItem->getKey(),
|
$cartItem->getKey(),
|
||||||
(int) $request->validated('cantidad'),
|
(int) $request->validated('cantidad'),
|
||||||
|
$updatesVariant
|
||||||
|
? ($request->validated('variant_id') !== null
|
||||||
|
? (int) $request->validated('variant_id')
|
||||||
|
: null)
|
||||||
|
: $cartItem->variant_id,
|
||||||
|
$updatesVariant,
|
||||||
)
|
)
|
||||||
)->additional([
|
)->additional([
|
||||||
'code' => 'cart.quantity_updated',
|
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
|
||||||
'message' => __('api.cart.quantity_updated'),
|
'message' => $updatesVariant
|
||||||
|
? __('api.cart.item_updated')
|
||||||
|
: __('api.cart.quantity_updated'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateCheckoutItem(
|
||||||
|
UpdateCartItemQuantityRequest $request,
|
||||||
|
Tenant $tenant,
|
||||||
|
Cart $cart,
|
||||||
|
CartItem $cartItem,
|
||||||
|
): CartResource {
|
||||||
|
$updatesVariant = $request->exists('variant_id');
|
||||||
|
|
||||||
|
return CartResource::make(
|
||||||
|
$this->cartService->updateCheckoutItem(
|
||||||
|
$tenant,
|
||||||
|
$request,
|
||||||
|
$cart,
|
||||||
|
$cartItem->getKey(),
|
||||||
|
(int) $request->validated('cantidad'),
|
||||||
|
$updatesVariant
|
||||||
|
? ($request->validated('variant_id') !== null
|
||||||
|
? (int) $request->validated('variant_id')
|
||||||
|
: null)
|
||||||
|
: $cartItem->variant_id,
|
||||||
|
$updatesVariant,
|
||||||
|
),
|
||||||
|
)->additional([
|
||||||
|
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
|
||||||
|
'message' => $updatesVariant
|
||||||
|
? __('api.cart.item_updated')
|
||||||
|
: __('api.cart.quantity_updated'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ use App\Domains\Catalog\Models\CatalogItem;
|
|||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
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\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -23,6 +26,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|||||||
'user_id',
|
'user_id',
|
||||||
'guest_token',
|
'guest_token',
|
||||||
'status',
|
'status',
|
||||||
|
'origin',
|
||||||
])]
|
])]
|
||||||
class Cart extends Model
|
class Cart extends Model
|
||||||
{
|
{
|
||||||
@@ -31,6 +35,10 @@ class Cart extends Model
|
|||||||
|
|
||||||
protected $table = 'carritos';
|
protected $table = 'carritos';
|
||||||
|
|
||||||
|
public const ORIGIN_USER = 'user';
|
||||||
|
|
||||||
|
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
@@ -62,6 +70,12 @@ 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');
|
||||||
|
}
|
||||||
|
|
||||||
public function getTotalAmount(): float
|
public function getTotalAmount(): float
|
||||||
{
|
{
|
||||||
$items = $this->relationLoaded('items')
|
$items = $this->relationLoaded('items')
|
||||||
@@ -86,8 +100,17 @@ class Cart extends Model
|
|||||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||||
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
||||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||||
|
$cartQuantity = (int) $this->items()
|
||||||
|
->where('catalog_item_id', $catalogItemId)
|
||||||
|
->sum('cantidad');
|
||||||
$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([
|
||||||
@@ -109,39 +132,119 @@ class Cart extends Model
|
|||||||
'cantidad' => $quantity,
|
'cantidad' => $quantity,
|
||||||
]);
|
]);
|
||||||
} else {
|
} else {
|
||||||
|
app(StockReservationService::class)->ensure($item, $selectedItem);
|
||||||
$item->cantidad += $quantity;
|
$item->cantidad += $quantity;
|
||||||
$item->save();
|
$item->save();
|
||||||
}
|
}
|
||||||
|
|
||||||
$inventoryService->reserve($selectedItem, $quantity);
|
app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateItem(int $cartItemId, int $quantity): CartItem
|
public function updateItem(
|
||||||
{
|
int $cartItemId,
|
||||||
|
int $quantity,
|
||||||
|
?int $variantId = null,
|
||||||
|
bool $updateVariant = false,
|
||||||
|
?int $excludedPurchaseId = null,
|
||||||
|
): CartItem {
|
||||||
if ($quantity <= 0) {
|
if ($quantity <= 0) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'cantidad' => __('api.cart.positive_quantity'),
|
'cantidad' => __('api.cart.positive_quantity'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
|
return DB::transaction(function () use (
|
||||||
|
$cartItemId,
|
||||||
|
$quantity,
|
||||||
|
$variantId,
|
||||||
|
$updateVariant,
|
||||||
|
$excludedPurchaseId,
|
||||||
|
): CartItem {
|
||||||
/** @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(
|
$currentSelection = $this->resolveScopedItem(
|
||||||
$item->catalog_item_id,
|
$item->catalog_item_id,
|
||||||
$item->variant_id,
|
$item->variant_id,
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
$inventoryService = app(CatalogInventoryService::class);
|
$inventoryService = app(CatalogInventoryService::class);
|
||||||
|
|
||||||
|
if ($updateVariant && $variantId !== $item->variant_id) {
|
||||||
|
$nextSelection = $this->resolveScopedItem(
|
||||||
|
$item->catalog_item_id,
|
||||||
|
$variantId,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
$otherVariantsQuantity = (int) $this->items()
|
||||||
|
->where('catalog_item_id', $item->catalog_item_id)
|
||||||
|
->whereKeyNot($item->getKey())
|
||||||
|
->sum('cantidad');
|
||||||
|
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||||
|
$this->assertUserPurchaseLimit(
|
||||||
|
$nextSelection,
|
||||||
|
$otherVariantsQuantity + $quantity,
|
||||||
|
$excludedPurchaseId,
|
||||||
|
$otherVariantsQuantity + $item->cantidad,
|
||||||
|
$nextAvailableQuantity,
|
||||||
|
);
|
||||||
|
|
||||||
|
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
||||||
|
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||||
|
|
||||||
|
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'variant_id' => __('api.cart.insufficient_stock', ['max' => $availableQuantity]),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$targetItem = $this->items()
|
||||||
|
->where('catalog_item_id', $item->catalog_item_id)
|
||||||
|
->where('variant_id', $variantId)
|
||||||
|
->whereKeyNot($item->getKey())
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($targetItem !== null) {
|
||||||
|
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
|
||||||
|
$targetItem->cantidad += $quantity;
|
||||||
|
$targetItem->save();
|
||||||
|
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
|
||||||
|
$item->delete();
|
||||||
|
|
||||||
|
return $targetItem->fresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
$item->variant_id = $variantId;
|
||||||
|
$item->cantidad = $quantity;
|
||||||
|
$item->save();
|
||||||
|
app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
|
||||||
|
|
||||||
|
return $item->fresh();
|
||||||
|
}
|
||||||
|
|
||||||
$delta = $quantity - $item->cantidad;
|
$delta = $quantity - $item->cantidad;
|
||||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
||||||
|
|
||||||
|
if ($delta > 0) {
|
||||||
|
$otherVariantsQuantity = (int) $this->items()
|
||||||
|
->where('catalog_item_id', $item->catalog_item_id)
|
||||||
|
->whereKeyNot($item->getKey())
|
||||||
|
->sum('cantidad');
|
||||||
|
$this->assertUserPurchaseLimit(
|
||||||
|
$currentSelection,
|
||||||
|
$otherVariantsQuantity + $quantity,
|
||||||
|
$excludedPurchaseId,
|
||||||
|
$otherVariantsQuantity + $item->cantidad,
|
||||||
|
$availableQuantity,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||||
@@ -150,17 +253,17 @@ class Cart extends Model
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$item->cantidad = $quantity;
|
|
||||||
$item->save();
|
|
||||||
|
|
||||||
if ($delta > 0) {
|
if ($delta > 0) {
|
||||||
$inventoryService->reserve($selectedItem, $delta);
|
app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($delta < 0) {
|
if ($delta < 0) {
|
||||||
$inventoryService->release($selectedItem, abs($delta));
|
app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$item->cantidad = $quantity;
|
||||||
|
$item->save();
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -179,7 +282,8 @@ class Cart extends Model
|
|||||||
$item->variant_id,
|
$item->variant_id,
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
app(CatalogInventoryService::class)->release(
|
app(StockReservationService::class)->release(
|
||||||
|
$item,
|
||||||
$selectedItem,
|
$selectedItem,
|
||||||
$item->cantidad,
|
$item->cantidad,
|
||||||
);
|
);
|
||||||
@@ -256,6 +360,33 @@ class Cart extends Model
|
|||||||
return $variant;
|
return $variant;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function assertUserPurchaseLimit(
|
||||||
|
CatalogItem|Variant $selectedItem,
|
||||||
|
int $cartQuantity,
|
||||||
|
?int $excludedPurchaseId = null,
|
||||||
|
int $heldQuantity = 0,
|
||||||
|
?int $maximumAddableCeiling = null,
|
||||||
|
): void {
|
||||||
|
if ($this->user_id === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$catalogItem = $selectedItem instanceof Variant
|
||||||
|
? $selectedItem->catalogItem
|
||||||
|
: $selectedItem;
|
||||||
|
|
||||||
|
app(UserPurchaseLimitService::class)->assertCanPurchase(
|
||||||
|
$catalogItem,
|
||||||
|
$this->user_id,
|
||||||
|
$cartQuantity,
|
||||||
|
$excludedPurchaseId,
|
||||||
|
$this->getKey(),
|
||||||
|
$heldQuantity,
|
||||||
|
$maximumAddableCeiling,
|
||||||
|
field: 'cantidad',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
protected function resolveInventory(int $inventoryId, bool $lockForUpdate): Inventory
|
protected function resolveInventory(int $inventoryId, bool $lockForUpdate): Inventory
|
||||||
{
|
{
|
||||||
$query = Inventory::query()->whereKey($inventoryId);
|
$query = Inventory::query()->whereKey($inventoryId);
|
||||||
|
|||||||
@@ -3,11 +3,13 @@
|
|||||||
namespace App\Domains\Cart\Models;
|
namespace App\Domains\Cart\Models;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
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\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'cart_id',
|
'cart_id',
|
||||||
@@ -55,4 +57,10 @@ class CartItem extends Model
|
|||||||
{
|
{
|
||||||
return $this->variant ?? $this->catalogItem;
|
return $this->variant ?? $this->catalogItem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<StockReservation, $this> */
|
||||||
|
public function stockReservations(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(StockReservation::class);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ class UpdateCartItemQuantityRequest extends FormRequest
|
|||||||
return [
|
return [
|
||||||
'cantidad' => ['required', 'integer', 'min:1'],
|
'cantidad' => ['required', 'integer', 'min:1'],
|
||||||
'catalog_item_id' => ['prohibited'],
|
'catalog_item_id' => ['prohibited'],
|
||||||
'variant_id' => ['prohibited'],
|
'variant_id' => ['sometimes', 'nullable', 'integer'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,9 @@
|
|||||||
namespace App\Domains\Cart\Resources;
|
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\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;
|
||||||
|
|
||||||
@@ -18,12 +21,16 @@ 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 ($selectedItem?->relationLoaded('attachments')) {
|
if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
|
||||||
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
if ($displayImage && $imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||||
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
|
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,10 +40,29 @@ class CartItemResource extends JsonResource
|
|||||||
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
||||||
'catalog_item_id' => $this->catalog_item_id,
|
'catalog_item_id' => $this->catalog_item_id,
|
||||||
'variant_id' => $this->variant_id,
|
'variant_id' => $this->variant_id,
|
||||||
'product' => $selectedItem === null ? null : [
|
'nombre' => $selectedItem?->getName(),
|
||||||
'nombre' => $selectedItem->getName(),
|
'imagen' => $imageUrl,
|
||||||
'imagen' => $imageUrl,
|
'variant' => $this->variant === null ? null : $this->variantData($this->variant),
|
||||||
],
|
'variants' => $this->when(
|
||||||
|
$includeVariants,
|
||||||
|
fn () => $this->catalogItem
|
||||||
|
->visibleVariants($this->variant_id)
|
||||||
|
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||||
|
->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),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,15 +4,24 @@ 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\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
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;
|
||||||
|
|
||||||
class CartService
|
class CartService
|
||||||
{
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly StockReservationService $reservations,
|
||||||
|
) {}
|
||||||
|
|
||||||
public function show(Tenant $tenant, Request $request): Cart
|
public function show(Tenant $tenant, Request $request): Cart
|
||||||
{
|
{
|
||||||
$resolvedIdentity = $this->resolveIdentity($request);
|
$resolvedIdentity = $this->resolveIdentity($request);
|
||||||
@@ -27,7 +36,7 @@ class CartService
|
|||||||
return $this->makeEmptyCart($tenant);
|
return $this->makeEmptyCart($tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->loadCart($cart);
|
return $this->loadCart($cart, $tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,27 +55,152 @@ class CartService
|
|||||||
$cart->addItem($catalogItemId, $variantId, $quantity);
|
$cart->addItem($catalogItemId, $variantId, $quantity);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'cart' => $this->loadCart($cart),
|
'cart' => $this->loadCart($cart, $tenant),
|
||||||
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
|
public function updateItem(
|
||||||
{
|
Tenant $tenant,
|
||||||
|
Request $request,
|
||||||
|
int $cartItemId,
|
||||||
|
int $quantity,
|
||||||
|
?int $variantId,
|
||||||
|
bool $updateVariant,
|
||||||
|
): 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);
|
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
|
||||||
|
|
||||||
return $this->loadCart($cart);
|
return $this->loadCart($cart, $tenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateCheckoutItem(
|
||||||
|
Tenant $tenant,
|
||||||
|
Request $request,
|
||||||
|
Cart $cart,
|
||||||
|
int $cartItemId,
|
||||||
|
int $quantity,
|
||||||
|
?int $variantId,
|
||||||
|
bool $updateVariant,
|
||||||
|
): Cart {
|
||||||
|
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||||
|
|
||||||
|
if (! $user instanceof User) {
|
||||||
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::transaction(function () use (
|
||||||
|
$tenant,
|
||||||
|
$user,
|
||||||
|
$cart,
|
||||||
|
$cartItemId,
|
||||||
|
$quantity,
|
||||||
|
$variantId,
|
||||||
|
$updateVariant,
|
||||||
|
): Cart {
|
||||||
|
/** @var Purchase|null $purchase */
|
||||||
|
$purchase = Purchase::query()
|
||||||
|
->where('cart_id', $cart->getKey())
|
||||||
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
|
->where('user_id', $user->getKey())
|
||||||
|
->whereIn('status', [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
])
|
||||||
|
->whereDoesntHave('items')
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($purchase === null) {
|
||||||
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'cart' => __('api.purchase.not_editable'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Cart|null $checkoutCart */
|
||||||
|
$checkoutCart = Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
|
->where('user_id', $user->getKey())
|
||||||
|
->where('status', 'checkout')
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($checkoutCart === null) {
|
||||||
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var CartItem|null $cartItem */
|
||||||
|
$cartItem = $checkoutCart->items()
|
||||||
|
->whereKey($cartItemId)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($cartItem === null) {
|
||||||
|
throw new NotFoundHttpException('Checkout item not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$hasChanges = (int) $cartItem->cantidad !== $quantity
|
||||||
|
|| ($updateVariant && $cartItem->variant_id !== $variantId);
|
||||||
|
|
||||||
|
if (! $hasChanges) {
|
||||||
|
return $this->loadCart($checkoutCart);
|
||||||
|
}
|
||||||
|
|
||||||
|
$checkoutCart->updateItem(
|
||||||
|
$cartItemId,
|
||||||
|
$quantity,
|
||||||
|
$variantId,
|
||||||
|
$updateVariant,
|
||||||
|
$purchase->getKey(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$purchase->telepagosQr()->delete();
|
||||||
|
$purchase->update([
|
||||||
|
'status' => Purchase::STATUS_CREATED,
|
||||||
|
'payment_method' => null,
|
||||||
|
'transfer_payer_dni' => null,
|
||||||
|
'total' => $checkoutCart->getTotalAmount(),
|
||||||
|
'expires_at' => now()->addMinutes(
|
||||||
|
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
$this->reservations->syncPurchaseExpiration($purchase);
|
||||||
|
|
||||||
|
return $this->loadCart($checkoutCart);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
return $this->loadCart($cart, $tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function makeGuestTokenCookie(string $guestToken): Cookie
|
public function makeGuestTokenCookie(string $guestToken): Cookie
|
||||||
@@ -76,11 +210,11 @@ class CartService
|
|||||||
$guestToken,
|
$guestToken,
|
||||||
60 * 24 * 180,
|
60 * 24 * 180,
|
||||||
'/',
|
'/',
|
||||||
null,
|
config('session.domain'),
|
||||||
false,
|
(bool) config('session.secure'),
|
||||||
true,
|
true,
|
||||||
false,
|
false,
|
||||||
'lax',
|
config('session.same_site'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,15 +230,32 @@ class CartService
|
|||||||
return $cart;
|
return $cart;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function loadCart(Cart $cart): Cart
|
protected function loadCart(Cart $cart, Tenant $tenant): Cart
|
||||||
{
|
{
|
||||||
return $cart->fresh()->load([
|
$relations = [
|
||||||
'items.catalogItem.attachments',
|
'items.catalogItem.attachments',
|
||||||
'items.catalogItem.inventory',
|
'items.catalogItem.inventory',
|
||||||
|
'items.catalogItem.itemAttributes.attribute',
|
||||||
'items.variant.attachments',
|
'items.variant.attachments',
|
||||||
'items.variant.inventory',
|
'items.variant.inventory',
|
||||||
'items.variant.definitions.itemAttribute.attribute',
|
'items.variant.definitions.itemAttribute.attribute.options',
|
||||||
]);
|
'items.variant.eventDates',
|
||||||
|
'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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
123
app/Domains/Cart/Services/ExpireCartReservationsService.php
Normal file
123
app/Domains/Cart/Services/ExpireCartReservationsService.php
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Cart\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class ExpireCartReservationsService
|
||||||
|
{
|
||||||
|
public function expireOverdue(): int
|
||||||
|
{
|
||||||
|
$expiredItems = 0;
|
||||||
|
$lastCartItemId = 0;
|
||||||
|
|
||||||
|
do {
|
||||||
|
$cartItemIds = StockReservation::query()
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->whereNull('purchase_id')
|
||||||
|
->whereNotNull('cart_item_id')
|
||||||
|
->whereNotNull('expires_at')
|
||||||
|
->where('expires_at', '<=', now())
|
||||||
|
->where('cart_item_id', '>', $lastCartItemId)
|
||||||
|
->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
|
||||||
|
->select('cart_item_id')
|
||||||
|
->distinct()
|
||||||
|
->orderBy('cart_item_id')
|
||||||
|
->limit(500)
|
||||||
|
->pluck('cart_item_id');
|
||||||
|
|
||||||
|
foreach ($cartItemIds as $cartItemId) {
|
||||||
|
$lastCartItemId = (int) $cartItemId;
|
||||||
|
|
||||||
|
if ($this->expireCartItem($lastCartItemId)) {
|
||||||
|
$expiredItems++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while ($cartItemIds->count() === 500);
|
||||||
|
|
||||||
|
return $expiredItems;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function expireCartItem(int $cartItemId): bool
|
||||||
|
{
|
||||||
|
/** @var CartItem|null $candidate */
|
||||||
|
$candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
|
||||||
|
if ($candidate === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($candidate, $cartItemId): bool {
|
||||||
|
/** @var Cart|null $cart */
|
||||||
|
$cart = Cart::query()
|
||||||
|
->whereKey($candidate->cart_id)
|
||||||
|
->where('status', 'active')
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($cart === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var CartItem|null $cartItem */
|
||||||
|
$cartItem = $cart->items()
|
||||||
|
->whereKey($cartItemId)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($cartItem === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reservations = StockReservation::query()
|
||||||
|
->where('cart_item_id', $cartItem->getKey())
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->orderBy('inventory_id')
|
||||||
|
->lockForUpdate()
|
||||||
|
->get();
|
||||||
|
|
||||||
|
if (
|
||||||
|
$reservations->isEmpty()
|
||||||
|
|| $reservations->contains(
|
||||||
|
fn (StockReservation $reservation): bool => $reservation->purchase_id !== null
|
||||||
|
|| $reservation->expires_at === null
|
||||||
|
|| $reservation->expires_at->isFuture(),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventories = Inventory::query()
|
||||||
|
->whereKey($reservations->pluck('inventory_id'))
|
||||||
|
->orderBy('id')
|
||||||
|
->lockForUpdate()
|
||||||
|
->get()
|
||||||
|
->keyBy('id');
|
||||||
|
|
||||||
|
foreach ($reservations as $reservation) {
|
||||||
|
$inventory = $inventories->get($reservation->inventory_id)
|
||||||
|
?? throw new \InvalidArgumentException('No se encontro el inventario reservado.');
|
||||||
|
|
||||||
|
$inventory->release((int) $reservation->quantity);
|
||||||
|
$reservation->update([
|
||||||
|
'quantity' => 0,
|
||||||
|
'status' => StockReservation::STATUS_EXPIRED,
|
||||||
|
'expires_at' => null,
|
||||||
|
'released_at' => now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$cartItem->delete();
|
||||||
|
|
||||||
|
if (! $cart->items()->exists()) {
|
||||||
|
$cart->update(['status' => 'expired']);
|
||||||
|
$cart->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,6 +34,10 @@ 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',
|
||||||
]);
|
]);
|
||||||
|
|||||||
37
app/Domains/Cart/documentacion/README.md
Normal file
37
app/Domains/Cart/documentacion/README.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Dominio Cart
|
||||||
|
|
||||||
|
## Propósito
|
||||||
|
|
||||||
|
Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios autenticados.
|
||||||
|
|
||||||
|
## Modelo
|
||||||
|
|
||||||
|
- `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.
|
||||||
|
|
||||||
|
## Servicios
|
||||||
|
|
||||||
|
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
||||||
|
- `ExpireCartReservationsService`: libera las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
|
||||||
|
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
Bajo `/tenants/{tenant:codigo}`:
|
||||||
|
|
||||||
|
- `GET /cart`.
|
||||||
|
- `POST /cart/items`.
|
||||||
|
- `PATCH /cart/items/{cartItem}`.
|
||||||
|
- `DELETE /cart/items/{cartItem}`.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.
|
||||||
@@ -10,3 +10,9 @@ Route::prefix('tenants/{tenant:codigo}')
|
|||||||
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
|
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
|
||||||
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
|
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Route::prefix('tenants/{tenant:codigo}')
|
||||||
|
->middleware('auth:sanctum')
|
||||||
|
->group(function (): void {
|
||||||
|
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem']);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Controllers\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||||
|
use App\Domains\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
|
||||||
|
use App\Domains\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
|
||||||
|
use App\Domains\Catalog\Services\OnTicketFeaturedGroupService;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||||
|
|
||||||
|
class OnTicketFeaturedGroupController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly OnTicketFeaturedGroupService $featuredGroupService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function index(Request $request): AnonymousResourceCollection
|
||||||
|
{
|
||||||
|
return OnTicketFeaturedGroupResource::collection(
|
||||||
|
$this->featuredGroupService->forTenant($this->onTicketTenant($request))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(UpsertOnTicketFeaturedGroupRequest $request): JsonResponse
|
||||||
|
{
|
||||||
|
$featuredGroup = $this->featuredGroupService->create(
|
||||||
|
$this->onTicketTenant($request),
|
||||||
|
$request->validated(),
|
||||||
|
);
|
||||||
|
|
||||||
|
return OnTicketFeaturedGroupResource::make($featuredGroup)
|
||||||
|
->response()
|
||||||
|
->setStatusCode(201);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(
|
||||||
|
UpsertOnTicketFeaturedGroupRequest $request,
|
||||||
|
FeaturedGroup $featuredGroup,
|
||||||
|
): OnTicketFeaturedGroupResource {
|
||||||
|
$tenant = $this->onTicketTenant($request);
|
||||||
|
|
||||||
|
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||||
|
|
||||||
|
return OnTicketFeaturedGroupResource::make(
|
||||||
|
$this->featuredGroupService->update(
|
||||||
|
$tenant,
|
||||||
|
$featuredGroup,
|
||||||
|
$request->validated(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function onTicketTenant(Request $request): Tenant
|
||||||
|
{
|
||||||
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
|
abort_unless($tenant->website_type_code === 'onticket', 404);
|
||||||
|
|
||||||
|
return $tenant;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,34 +2,35 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Controllers;
|
namespace App\Domains\Catalog\Controllers;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\GroupLayout;
|
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\Models\FeaturedItem;
|
|
||||||
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;
|
||||||
use App\Domains\Catalog\Requests\StoreCatalogItemRequest;
|
use App\Domains\Catalog\Requests\StoreCatalogItemRequest;
|
||||||
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogFeaturedItemResource;
|
|
||||||
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\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\Database\Eloquent\Relations\HasMany;
|
|
||||||
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\Pagination\LengthAwarePaginator;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
|
||||||
class CatalogController extends Controller
|
class CatalogController extends Controller
|
||||||
{
|
{
|
||||||
private const ITEMS_PER_PAGE = 12;
|
public function index(Request $request, Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
|
||||||
|
|
||||||
public function index(Tenant $tenant): JsonResponse
|
|
||||||
{
|
{
|
||||||
$featuredGroups = FeaturedGroup::query()
|
$featuredGroups = FeaturedGroup::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
@@ -39,7 +40,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,
|
||||||
$this->featuredItemsResponse($featuredGroup, 1),
|
$featuredGroupService->itemsResponse($featuredGroup, 1, $this->userId($request)),
|
||||||
))->resolve()
|
))->resolve()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -48,15 +49,17 @@ class CatalogController extends Controller
|
|||||||
SearchCatalogItemsRequest $request,
|
SearchCatalogItemsRequest $request,
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
CatalogService $catalogService,
|
CatalogService $catalogService,
|
||||||
|
CatalogItemAllowanceService $allowances,
|
||||||
): AnonymousResourceCollection {
|
): AnonymousResourceCollection {
|
||||||
return CatalogSearchItemResource::collection(
|
$items = $catalogService->search(
|
||||||
$catalogService->search(
|
$tenant,
|
||||||
$tenant,
|
$request->validated('q'),
|
||||||
$request->validated('q'),
|
$tenant->search_items_per_page,
|
||||||
$tenant->search_items_per_page,
|
(int) $request->validated('page', 1),
|
||||||
(int) $request->validated('page', 1),
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
$allowances->attach($items->getCollection(), $this->userId($request));
|
||||||
|
|
||||||
|
return CatalogSearchItemResource::collection($items);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function category(
|
public function category(
|
||||||
@@ -64,17 +67,19 @@ 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);
|
||||||
|
|
||||||
return CatalogSearchItemResource::collection(
|
$items = $catalogService->categoryItems(
|
||||||
$catalogService->categoryItems(
|
$tenant,
|
||||||
$tenant,
|
$category,
|
||||||
$category,
|
$tenant->search_items_per_page,
|
||||||
$tenant->search_items_per_page,
|
(int) $request->validated('page', 1),
|
||||||
(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,
|
||||||
@@ -89,12 +94,17 @@ class CatalogController extends Controller
|
|||||||
FeaturedGroupPageRequest $request,
|
FeaturedGroupPageRequest $request,
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
FeaturedGroup $featuredGroup,
|
FeaturedGroup $featuredGroup,
|
||||||
|
FeaturedGroupService $featuredGroupService,
|
||||||
): JsonResponse {
|
): JsonResponse {
|
||||||
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
|
||||||
|
|
||||||
$page = (int) $request->validated('page', 1);
|
$page = (int) $request->validated('page', 1);
|
||||||
|
|
||||||
return response()->json($this->featuredItemsResponse($featuredGroup, $page));
|
return response()->json($featuredGroupService->itemsResponse(
|
||||||
|
$featuredGroup,
|
||||||
|
$page,
|
||||||
|
$this->userId($request),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(
|
public function show(
|
||||||
@@ -102,15 +112,53 @@ 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');
|
||||||
|
|
||||||
return CatalogItemDetailResource::make(
|
$item = $catalogService->getDetail(
|
||||||
$catalogService->getDetail(
|
$catalogItem,
|
||||||
|
$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,
|
||||||
$variantId === null ? null : (int) $variantId,
|
$selectedValues,
|
||||||
|
$includedVariantId,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -130,57 +178,10 @@ class CatalogController extends Controller
|
|||||||
->setStatusCode(201);
|
->setStatusCode(201);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<array-key, mixed> */
|
private function userId(Request $request): ?int
|
||||||
private function featuredItemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
|
||||||
{
|
{
|
||||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
$userId = $request->user()?->getAuthIdentifier() ?? Auth::guard('sanctum')->id();
|
||||||
$featuredItems = $this->featuredItemsQuery($featuredGroup)->get();
|
|
||||||
|
|
||||||
$featuredItems->each(
|
return $userId === null ? null : (int) $userId;
|
||||||
fn ($featuredItem) => $featuredItem->setRelation('featuredGroup', $featuredGroup)
|
|
||||||
);
|
|
||||||
|
|
||||||
return CatalogFeaturedItemResource::collection($featuredItems)->resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
$paginator = $this->paginateFeaturedItems($featuredGroup, $page);
|
|
||||||
|
|
||||||
$paginator->getCollection()->each(
|
|
||||||
fn ($featuredItem) => $featuredItem->setRelation('featuredGroup', $featuredGroup)
|
|
||||||
);
|
|
||||||
|
|
||||||
return CatalogFeaturedItemResource::collection($paginator)
|
|
||||||
->response()
|
|
||||||
->getData(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function paginateFeaturedItems(
|
|
||||||
FeaturedGroup $featuredGroup,
|
|
||||||
int $page,
|
|
||||||
): LengthAwarePaginator {
|
|
||||||
$paginator = $this->featuredItemsQuery($featuredGroup)->paginate(
|
|
||||||
perPage: self::ITEMS_PER_PAGE,
|
|
||||||
pageName: 'page',
|
|
||||||
page: $page,
|
|
||||||
);
|
|
||||||
|
|
||||||
return $paginator->withPath(route('catalog.featured-groups.items.index', [
|
|
||||||
'tenant' => $featuredGroup->tenant_code,
|
|
||||||
'featuredGroup' => $featuredGroup->id,
|
|
||||||
]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return HasMany<FeaturedItem, FeaturedGroup> */
|
|
||||||
private function featuredItemsQuery(FeaturedGroup $featuredGroup): HasMany
|
|
||||||
{
|
|
||||||
return $featuredGroup->featuredItems()->with([
|
|
||||||
'catalogItem.inventory',
|
|
||||||
'catalogItem.attachments',
|
|
||||||
'catalogItem.variants.inventory',
|
|
||||||
'catalogItem.variants.attachments',
|
|
||||||
'catalogItem.variants.definitions.itemAttribute.attribute',
|
|
||||||
'catalogItem.bundleComponents.catalogItem',
|
|
||||||
'catalogItem.bundleComponents.variant.catalogItem',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
18
app/Domains/Catalog/Enums/FeaturedGroupSource.php
Normal file
18
app/Domains/Catalog/Enums/FeaturedGroupSource.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Enums;
|
||||||
|
|
||||||
|
enum FeaturedGroupSource: string
|
||||||
|
{
|
||||||
|
case Manual = 'manual';
|
||||||
|
case Category = 'category';
|
||||||
|
case All = 'all';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public static function values(): array
|
||||||
|
{
|
||||||
|
return array_column(self::cases(), 'value');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ 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>
|
||||||
|
|||||||
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<?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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ 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>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
|
use App\Domains\Event\Models\EventDate;
|
||||||
use App\Domains\Shared\Enums\FieldType;
|
use App\Domains\Shared\Enums\FieldType;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
@@ -51,4 +52,14 @@ class Attribute extends Model
|
|||||||
{
|
{
|
||||||
return $this->hasMany(AttributeOption::class, 'attribute_id')->orderBy('sort_order');
|
return $this->hasMany(AttributeOption::class, 'attribute_id')->orderBy('sort_order');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return HasMany<EventDate, $this>
|
||||||
|
*/
|
||||||
|
public function eventDates(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(EventDate::class, 'tenant_code', 'tenant_codigo')
|
||||||
|
->orderBy('date')
|
||||||
|
->orderBy('time_start');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
|
use App\Domains\Ticket\Models\ValidityTime;
|
||||||
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;
|
||||||
@@ -9,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'attribute_id',
|
'attribute_id',
|
||||||
|
'validity_time_id',
|
||||||
'value',
|
'value',
|
||||||
'label',
|
'label',
|
||||||
'sort_order',
|
'sort_order',
|
||||||
@@ -26,6 +28,7 @@ class AttributeOption extends Model
|
|||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
|
'validity_time_id' => 'integer',
|
||||||
'sort_order' => 'integer',
|
'sort_order' => 'integer',
|
||||||
'metadata' => 'array',
|
'metadata' => 'array',
|
||||||
];
|
];
|
||||||
@@ -38,4 +41,10 @@ class AttributeOption extends Model
|
|||||||
{
|
{
|
||||||
return $this->belongsTo(Attribute::class, 'attribute_id');
|
return $this->belongsTo(Attribute::class, 'attribute_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<ValidityTime, $this> */
|
||||||
|
public function validityTime(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(ValidityTime::class);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,15 +5,19 @@ 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 Carbon\CarbonInterface;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
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\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;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'tenant_code',
|
'tenant_code',
|
||||||
@@ -26,13 +30,13 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
'descripcion',
|
'descripcion',
|
||||||
'precio',
|
'precio',
|
||||||
'inventory_policy',
|
'inventory_policy',
|
||||||
|
'inventory_subject',
|
||||||
|
'max_units_per_user',
|
||||||
'has_tickets',
|
'has_tickets',
|
||||||
'maximum_use_date',
|
|
||||||
'minimum_use_date',
|
|
||||||
])]
|
])]
|
||||||
class CatalogItem extends Model
|
class CatalogItem extends Model
|
||||||
{
|
{
|
||||||
use HasFactory;
|
use HasFactory, SoftDeletes;
|
||||||
|
|
||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
|
|
||||||
@@ -41,6 +45,7 @@ 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,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -53,9 +58,9 @@ class CatalogItem extends Model
|
|||||||
'type' => CatalogItemType::class,
|
'type' => CatalogItemType::class,
|
||||||
'precio' => 'decimal:2',
|
'precio' => 'decimal:2',
|
||||||
'inventory_policy' => InventoryPolicy::class,
|
'inventory_policy' => InventoryPolicy::class,
|
||||||
|
'inventory_subject' => InventorySubject::class,
|
||||||
|
'max_units_per_user' => 'integer',
|
||||||
'has_tickets' => 'boolean',
|
'has_tickets' => 'boolean',
|
||||||
'maximum_use_date' => 'datetime',
|
|
||||||
'minimum_use_date' => 'datetime',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +106,12 @@ class CatalogItem extends Model
|
|||||||
return $this->hasMany(Variant::class);
|
return $this->hasMany(Variant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<Ticket, $this> */
|
||||||
|
public function sourceTickets(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
||||||
|
}
|
||||||
|
|
||||||
/** @return BelongsToMany<Attribute, $this> */
|
/** @return BelongsToMany<Attribute, $this> */
|
||||||
public function attributes(): BelongsToMany
|
public function attributes(): BelongsToMany
|
||||||
{
|
{
|
||||||
@@ -122,6 +133,12 @@ class CatalogItem extends Model
|
|||||||
|
|
||||||
/** @return BelongsToMany<Attachment, $this> */
|
/** @return BelongsToMany<Attachment, $this> */
|
||||||
public function attachments(): BelongsToMany
|
public function attachments(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsToMany<Attachment, $this> */
|
||||||
|
public function allAttachments(): BelongsToMany
|
||||||
{
|
{
|
||||||
return $this->belongsToMany(
|
return $this->belongsToMany(
|
||||||
Attachment::class,
|
Attachment::class,
|
||||||
@@ -129,7 +146,7 @@ class CatalogItem extends Model
|
|||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
'attachment_id'
|
'attachment_id'
|
||||||
)
|
)
|
||||||
->withPivot('orden')
|
->withPivot(['orden', 'is_enabled'])
|
||||||
->wherePivotNull('variant_id')
|
->wherePivotNull('variant_id')
|
||||||
->orderByPivot('orden');
|
->orderByPivot('orden');
|
||||||
}
|
}
|
||||||
@@ -154,6 +171,31 @@ class CatalogItem extends Model
|
|||||||
return ($this->availableStock() ?? 0) > 0;
|
return ($this->availableStock() ?? 0) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param Builder<CatalogItem> $query */
|
||||||
|
public function scopeWhereVariantsAvailable(Builder $query): Builder
|
||||||
|
{
|
||||||
|
return $query->where(function (Builder $query): void {
|
||||||
|
$query
|
||||||
|
->whereDoesntHave('variants')
|
||||||
|
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||||
|
->orWhereHas(
|
||||||
|
'variants.inventory',
|
||||||
|
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
||||||
|
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Collection<int, Variant> */
|
||||||
|
public function visibleVariants(?int $includedVariantId = null): Collection
|
||||||
|
{
|
||||||
|
return $this->variants
|
||||||
|
->filter(fn (Variant $variant): bool => ($includedVariantId !== null && $variant->id === $includedVariantId)
|
||||||
|
|| $this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
|| ($variant->inventory?->availableStock() ?? 0) > 0)
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
public function getPrice(): float
|
public function getPrice(): float
|
||||||
{
|
{
|
||||||
return (float) $this->precio;
|
return (float) $this->precio;
|
||||||
@@ -164,14 +206,14 @@ class CatalogItem extends Model
|
|||||||
return $this->nombre;
|
return $this->nombre;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getMinimumUseDate(): ?CarbonInterface
|
public function getSelectionLabel(): string
|
||||||
{
|
{
|
||||||
return $this->minimum_use_date;
|
return $this->getName();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getMaximumUseDate(): ?CarbonInterface
|
public function getDescription(): ?string
|
||||||
{
|
{
|
||||||
return $this->maximum_use_date;
|
return $this->descripcion;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function isBundle(): bool
|
public function isBundle(): bool
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
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\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
@@ -64,4 +66,15 @@ class Category extends Model
|
|||||||
{
|
{
|
||||||
return $this->hasMany(CatalogItem::class);
|
return $this->hasMany(CatalogItem::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return BelongsToMany<User, $this> */
|
||||||
|
public function scanners(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(
|
||||||
|
User::class,
|
||||||
|
'category_scanners',
|
||||||
|
'categoria_id',
|
||||||
|
'user_id',
|
||||||
|
)->withTimestamps();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||||
use App\Domains\Catalog\Enums\GroupLayout;
|
use App\Domains\Catalog\Enums\GroupLayout;
|
||||||
use App\Domains\Catalog\Enums\ProductLayout;
|
use App\Domains\Catalog\Enums\ProductLayout;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
@@ -13,6 +14,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'tenant_code',
|
'tenant_code',
|
||||||
|
'source_type',
|
||||||
|
'category_id',
|
||||||
'product_layout',
|
'product_layout',
|
||||||
'group_layout',
|
'group_layout',
|
||||||
'group_name',
|
'group_name',
|
||||||
@@ -26,9 +29,15 @@ class FeaturedGroup extends Model
|
|||||||
|
|
||||||
protected $table = 'featured_groups';
|
protected $table = 'featured_groups';
|
||||||
|
|
||||||
|
protected $attributes = [
|
||||||
|
'source_type' => FeaturedGroupSource::Manual->value,
|
||||||
|
];
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
|
'source_type' => FeaturedGroupSource::class,
|
||||||
|
'category_id' => 'integer',
|
||||||
'product_layout' => ProductLayout::class,
|
'product_layout' => ProductLayout::class,
|
||||||
'group_layout' => GroupLayout::class,
|
'group_layout' => GroupLayout::class,
|
||||||
'group_order' => 'integer',
|
'group_order' => 'integer',
|
||||||
@@ -41,6 +50,12 @@ class FeaturedGroup extends Model
|
|||||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Category, $this> */
|
||||||
|
public function category(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Category::class);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return HasMany<FeaturedItem, $this> */
|
/** @return HasMany<FeaturedItem, $this> */
|
||||||
public function featuredItems(): HasMany
|
public function featuredItems(): HasMany
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ 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([
|
||||||
@@ -47,6 +48,12 @@ class Inventory extends Model
|
|||||||
return $this->hasOne(Variant::class);
|
return $this->hasOne(Variant::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<StockReservation, $this> */
|
||||||
|
public function stockReservations(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(StockReservation::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);
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
#[Fillable([
|
#[Fillable([
|
||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
'attribute_id',
|
'attribute_id',
|
||||||
|
'allow_multi_select',
|
||||||
|
'sort_order',
|
||||||
|
'show_in_selector',
|
||||||
|
'ticket_label',
|
||||||
])]
|
])]
|
||||||
class ItemAttribute extends Model
|
class ItemAttribute extends Model
|
||||||
{
|
{
|
||||||
@@ -18,6 +22,21 @@ class ItemAttribute extends Model
|
|||||||
|
|
||||||
protected $table = 'item_attributes';
|
protected $table = 'item_attributes';
|
||||||
|
|
||||||
|
protected $attributes = [
|
||||||
|
'show_in_selector' => true,
|
||||||
|
];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'catalog_item_id' => 'integer',
|
||||||
|
'attribute_id' => 'integer',
|
||||||
|
'allow_multi_select' => 'boolean',
|
||||||
|
'sort_order' => 'integer',
|
||||||
|
'show_in_selector' => 'boolean',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<CatalogItem, $this> */
|
/** @return BelongsTo<CatalogItem, $this> */
|
||||||
public function catalogItem(): BelongsTo
|
public function catalogItem(): BelongsTo
|
||||||
{
|
{
|
||||||
|
|||||||
61
app/Domains/Catalog/Models/StockReservation.php
Normal file
61
app/Domains/Catalog/Models/StockReservation.php
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
#[Fillable([
|
||||||
|
'inventory_id',
|
||||||
|
'cart_item_id',
|
||||||
|
'purchase_id',
|
||||||
|
'quantity',
|
||||||
|
'status',
|
||||||
|
'expires_at',
|
||||||
|
'committed_at',
|
||||||
|
'released_at',
|
||||||
|
])]
|
||||||
|
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 [
|
||||||
|
'inventory_id' => 'integer',
|
||||||
|
'cart_item_id' => 'integer',
|
||||||
|
'purchase_id' => 'integer',
|
||||||
|
'quantity' => 'integer',
|
||||||
|
'expires_at' => 'datetime',
|
||||||
|
'committed_at' => 'datetime',
|
||||||
|
'released_at' => 'datetime',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Inventory, $this> */
|
||||||
|
public function inventory(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Inventory::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<CartItem, $this> */
|
||||||
|
public function cartItem(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(CartItem::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Purchase, $this> */
|
||||||
|
public function purchase(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Purchase::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,23 +3,29 @@
|
|||||||
namespace App\Domains\Catalog\Models;
|
namespace App\Domains\Catalog\Models;
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use Carbon\CarbonInterface;
|
use App\Domains\Event\Models\EventDate;
|
||||||
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
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\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\Facades\Lang;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
|
'event_date_id',
|
||||||
'inventory_id',
|
'inventory_id',
|
||||||
'minimum_use_date',
|
'descripcion',
|
||||||
'maximum_use_date',
|
'precio',
|
||||||
])]
|
])]
|
||||||
class Variant extends Model
|
class Variant extends Model
|
||||||
{
|
{
|
||||||
use HasFactory;
|
use HasFactory, SoftDeletes;
|
||||||
|
|
||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
|
|
||||||
@@ -29,16 +35,39 @@ class Variant extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'catalog_item_id' => 'integer',
|
'catalog_item_id' => 'integer',
|
||||||
|
'event_date_id' => 'integer',
|
||||||
'inventory_id' => 'integer',
|
'inventory_id' => 'integer',
|
||||||
'minimum_use_date' => 'datetime',
|
'precio' => 'decimal:2',
|
||||||
'maximum_use_date' => 'datetime',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<CatalogItem, $this> */
|
/** @return BelongsTo<CatalogItem, $this> */
|
||||||
public function catalogItem(): BelongsTo
|
public function catalogItem(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(CatalogItem::class);
|
return $this->belongsTo(CatalogItem::class)->withTrashed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<EventDate, $this> */
|
||||||
|
public function eventDate(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(EventDate::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsToMany<EventDate, $this> */
|
||||||
|
public function eventDates(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->belongsToMany(
|
||||||
|
EventDate::class,
|
||||||
|
'variant_event_dates',
|
||||||
|
'variant_id',
|
||||||
|
'event_date_id',
|
||||||
|
)->orderBy('date')->orderBy('time_start');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return HasMany<Ticket, $this> */
|
||||||
|
public function sourceTickets(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(Ticket::class, 'source_variant_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<Inventory, $this> */
|
/** @return BelongsTo<Inventory, $this> */
|
||||||
@@ -55,6 +84,12 @@ class Variant extends Model
|
|||||||
|
|
||||||
/** @return BelongsToMany<Attachment, $this> */
|
/** @return BelongsToMany<Attachment, $this> */
|
||||||
public function attachments(): BelongsToMany
|
public function attachments(): BelongsToMany
|
||||||
|
{
|
||||||
|
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return BelongsToMany<Attachment, $this> */
|
||||||
|
public function allAttachments(): BelongsToMany
|
||||||
{
|
{
|
||||||
$relation = $this->belongsToMany(
|
$relation = $this->belongsToMany(
|
||||||
Attachment::class,
|
Attachment::class,
|
||||||
@@ -62,7 +97,7 @@ class Variant extends Model
|
|||||||
'variant_id',
|
'variant_id',
|
||||||
'attachment_id'
|
'attachment_id'
|
||||||
)
|
)
|
||||||
->withPivot('orden')
|
->withPivot(['orden', 'is_enabled'])
|
||||||
->orderByPivot('orden');
|
->orderByPivot('orden');
|
||||||
|
|
||||||
if ($this->catalog_item_id !== null) {
|
if ($this->catalog_item_id !== null) {
|
||||||
@@ -74,36 +109,200 @@ class Variant extends Model
|
|||||||
|
|
||||||
public function getPrice(): float
|
public function getPrice(): float
|
||||||
{
|
{
|
||||||
return $this->catalogItem->getPrice();
|
return (float) ($this->precio ?? $this->catalogItem->precio);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getDescription(): ?string
|
||||||
|
{
|
||||||
|
return $this->descripcion ?? $this->catalogItem->descripcion;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getName(): string
|
public function getName(): string
|
||||||
{
|
{
|
||||||
$name = $this->catalogItem->nombre;
|
return $this->catalogItem->nombre;
|
||||||
$this->loadMissing('definitions.itemAttribute.attribute');
|
}
|
||||||
$definitions = $this->definitions
|
|
||||||
->map(function (VariantDefinition $definition): ?string {
|
|
||||||
$attributeName = $definition->itemAttribute?->attribute?->nombre;
|
|
||||||
|
|
||||||
return $attributeName
|
public function getSelectionLabel(): string
|
||||||
? "{$attributeName}: {$definition->value}"
|
{
|
||||||
: $definition->value;
|
$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()
|
->filter()
|
||||||
->implode(', ');
|
->implode(' · ');
|
||||||
|
|
||||||
return $definitions === '' ? $name : "{$name} ({$definitions})";
|
return $label !== '' ? $label : $this->getName();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getMinimumUseDate(): ?CarbonInterface
|
/** @return Collection<string, string|array<int, string>> */
|
||||||
|
public function selectionValues(): Collection
|
||||||
{
|
{
|
||||||
return $this->minimum_use_date
|
$values = $this->definitions
|
||||||
?? $this->catalogItem->getMinimumUseDate();
|
->groupBy('item_attribute_id')
|
||||||
|
->mapWithKeys(function (Collection $definitions): array {
|
||||||
|
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||||
|
$attributeCode = $itemAttribute?->attribute?->codigo;
|
||||||
|
|
||||||
|
if ($attributeCode === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$definitionValues = $definitions->pluck('value')->values();
|
||||||
|
|
||||||
|
return [
|
||||||
|
$attributeCode => $itemAttribute->allow_multi_select
|
||||||
|
? $definitionValues->all()
|
||||||
|
: $definitionValues->first(),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
$eventDateIds = $this->selectedEventDates()
|
||||||
|
->pluck('id')
|
||||||
|
->map(fn ($id): string => (string) $id)
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($eventDateIds->count() === 1) {
|
||||||
|
$values->put('event_date', $eventDateIds->first());
|
||||||
|
} elseif ($eventDateIds->isNotEmpty()) {
|
||||||
|
$values->put('event_date', $eventDateIds->all());
|
||||||
|
}
|
||||||
|
|
||||||
|
return $values;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getMaximumUseDate(): ?CarbonInterface
|
/**
|
||||||
|
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
||||||
|
*/
|
||||||
|
public function selectionOptions(?Collection $itemAttributes = null): Collection
|
||||||
{
|
{
|
||||||
return $this->maximum_use_date
|
$options = $this->definitions
|
||||||
?? $this->catalogItem->getMaximumUseDate();
|
->groupBy('item_attribute_id')
|
||||||
|
->mapWithKeys(function (Collection $definitions): array {
|
||||||
|
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||||
|
$attribute = $itemAttribute?->attribute;
|
||||||
|
$attributeCode = $attribute?->codigo;
|
||||||
|
|
||||||
|
if ($attributeCode === null) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$values = $definitions
|
||||||
|
->pluck('value')
|
||||||
|
->values()
|
||||||
|
->map(function (string $value) use ($attribute): array {
|
||||||
|
$attributeOption = $attribute->options->firstWhere('value', $value);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'value' => $value,
|
||||||
|
'label' => $attributeOption?->label ?? $value,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
return [
|
||||||
|
$attributeCode => $itemAttribute->allow_multi_select
|
||||||
|
? $values->all()
|
||||||
|
: $values->first(),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
$eventDateOptions = $this->selectedEventDates()
|
||||||
|
->map(fn (EventDate $eventDate): array => [
|
||||||
|
'value' => (string) $eventDate->id,
|
||||||
|
'label' => $eventDate->date->format('d/m/Y'),
|
||||||
|
])
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($eventDateOptions->count() === 1) {
|
||||||
|
$options->put('event_date', $eventDateOptions->first());
|
||||||
|
} elseif ($eventDateOptions->isNotEmpty()) {
|
||||||
|
$options->put('event_date', $eventDateOptions->all());
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($itemAttributes === null) {
|
||||||
|
$itemAttributes = $this->definitions
|
||||||
|
->map(fn (VariantDefinition $definition) => $definition->itemAttribute)
|
||||||
|
->filter()
|
||||||
|
->unique('id')
|
||||||
|
->values();
|
||||||
|
|
||||||
|
if ($this->catalogItem !== null) {
|
||||||
|
$itemAttributes = $itemAttributes
|
||||||
|
->merge($this->catalogItem->itemAttributes)
|
||||||
|
->unique('id')
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$ordering = $itemAttributes->mapWithKeys(function (ItemAttribute $itemAttribute): array {
|
||||||
|
$attribute = $itemAttribute->attribute;
|
||||||
|
|
||||||
|
return $attribute === null
|
||||||
|
? []
|
||||||
|
: [$attribute->codigo => [$itemAttribute->sort_order, mb_strtolower($attribute->nombre)]];
|
||||||
|
});
|
||||||
|
|
||||||
|
return $options->sortKeysUsing(function (string $left, string $right) use ($ordering): int {
|
||||||
|
[$leftOrder, $leftLabel] = $ordering->get($left, [0, mb_strtolower($left)]);
|
||||||
|
[$rightOrder, $rightLabel] = $ordering->get($right, [0, mb_strtolower($right)]);
|
||||||
|
|
||||||
|
return $leftOrder <=> $rightOrder
|
||||||
|
?: $leftLabel <=> $rightLabel
|
||||||
|
?: $left <=> $right;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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> */
|
||||||
|
public function selectedEventDates(): Collection
|
||||||
|
{
|
||||||
|
$eventDates = $this->eventDates;
|
||||||
|
|
||||||
|
if ($eventDates->isEmpty() && $this->event_date_id !== null && $this->eventDate !== null) {
|
||||||
|
return collect([$this->eventDate]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $eventDates;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Requests\AdminApp;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class UpsertOnTicketFeaturedGroupRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'category_name' => ['required', 'string', 'max:255'],
|
||||||
|
'is_featured' => ['required', 'boolean'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class CatalogVariantOptionsRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, list<string>> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'selected_values' => ['sometimes', 'array'],
|
||||||
|
'selected_values.*' => ['nullable'],
|
||||||
|
'cart_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ 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 Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
@@ -53,9 +54,9 @@ class StoreCatalogItemRequest extends FormRequest
|
|||||||
'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'],
|
||||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||||
'minimum_use_date' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'date'],
|
|
||||||
'maximum_use_date' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'date', 'after_or_equal:minimum_use_date'],
|
|
||||||
'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'],
|
||||||
@@ -69,22 +70,53 @@ class StoreCatalogItemRequest extends FormRequest
|
|||||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
'multi_select_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||||
|
'multi_select_attribute_codes.*' => [
|
||||||
|
'required',
|
||||||
|
'string',
|
||||||
|
'distinct',
|
||||||
|
Rule::exists('attribute', 'codigo')->where(
|
||||||
|
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'],
|
||||||
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
|
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
|
||||||
|
'variants.*.descripcion' => ['sometimes', 'nullable', 'string'],
|
||||||
|
'variants.*.precio' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:99999999.99'],
|
||||||
|
'variants.*.event_date_id' => [
|
||||||
|
'sometimes',
|
||||||
|
'nullable',
|
||||||
|
'integer',
|
||||||
|
Rule::exists('event_dates', 'id')->where(
|
||||||
|
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||||
|
),
|
||||||
|
],
|
||||||
|
'variants.*.event_date_ids' => ['sometimes', 'array', 'min:1'],
|
||||||
|
'variants.*.event_date_ids.*' => [
|
||||||
|
'required',
|
||||||
|
'integer',
|
||||||
|
'distinct',
|
||||||
|
Rule::exists('event_dates', 'id')->where(
|
||||||
|
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||||
|
),
|
||||||
|
],
|
||||||
'variants.*.inventory_id' => ['prohibited'],
|
'variants.*.inventory_id' => ['prohibited'],
|
||||||
'variants.*.reserved_stock' => ['prohibited'],
|
'variants.*.reserved_stock' => ['prohibited'],
|
||||||
'variants.*.sold_units' => ['prohibited'],
|
'variants.*.sold_units' => ['prohibited'],
|
||||||
'variants.*.minimum_use_date' => ['sometimes', 'nullable', 'date'],
|
|
||||||
'variants.*.maximum_use_date' => [
|
|
||||||
'sometimes',
|
|
||||||
'nullable',
|
|
||||||
'date',
|
|
||||||
'after_or_equal:variants.*.minimum_use_date',
|
|
||||||
],
|
|
||||||
'variants.*.values' => ['sometimes', 'array'],
|
'variants.*.values' => ['sometimes', 'array'],
|
||||||
'variants.*.values.*' => ['nullable', 'string'],
|
'variants.*.values.*' => ['nullable'],
|
||||||
|
'variants.*.values.*.*' => ['required', 'string'],
|
||||||
'variants.*.images' => ['sometimes', 'array'],
|
'variants.*.images' => ['sometimes', 'array'],
|
||||||
'variants.*.images.*' => ['required', new ImageOrBase64Rule],
|
'variants.*.images.*' => ['required', new ImageOrBase64Rule],
|
||||||
'components' => [
|
'components' => [
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Resources\AdminApp;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\ProductLayout;
|
||||||
|
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin FeaturedGroup */
|
||||||
|
class OnTicketFeaturedGroupResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->id,
|
||||||
|
'category_id' => $this->category_id,
|
||||||
|
'category_name' => $this->category->nombre,
|
||||||
|
'group_name' => $this->group_name,
|
||||||
|
'is_featured' => $this->product_layout === ProductLayout::Row,
|
||||||
|
'type' => $this->source_type->value,
|
||||||
|
'product_layout' => $this->product_layout->value,
|
||||||
|
'group_layout' => $this->group_layout->value,
|
||||||
|
'order' => $this->group_order,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,60 +5,102 @@ namespace App\Domains\Catalog\Resources;
|
|||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Enums\ProductLayout;
|
use App\Domains\Catalog\Enums\ProductLayout;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\FeaturedItem;
|
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 Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
/** @mixin FeaturedItem */
|
/** @mixin CatalogItem */
|
||||||
class CatalogFeaturedItemResource extends JsonResource
|
class CatalogFeaturedItemResource extends JsonResource
|
||||||
{
|
{
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
$catalogItem = $this->catalogItem;
|
$catalogItem = $this->resource;
|
||||||
|
/** @var FeaturedGroup $featuredGroup */
|
||||||
|
$featuredGroup = $catalogItem->getRelation('featuredGroup');
|
||||||
|
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||||
|
|
||||||
if ($this->featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
||||||
return $this->columnWithImageData($catalogItem);
|
return $this->columnWithImageData($catalogItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||||
|
return $this->ticketSelectorData($catalogItem);
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = [
|
||||||
|
'id' => $catalogItem->id,
|
||||||
|
'type' => $catalogItem->type->value,
|
||||||
|
'nombre' => $catalogItem->nombre,
|
||||||
|
'descripcion' => $catalogItem->descripcion,
|
||||||
|
'precio' => $catalogItem->precio,
|
||||||
|
'maximum_addable_quantity' => $this->maximumAddable(
|
||||||
|
$catalogItem->availableStock(),
|
||||||
|
$remainingUserQuota,
|
||||||
|
),
|
||||||
|
'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, '.', ''),
|
||||||
|
'maximum_addable_quantity' => $this->maximumAddable(
|
||||||
|
$catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
? null
|
||||||
|
: $variant->inventory->availableStock(),
|
||||||
|
$remainingUserQuota,
|
||||||
|
),
|
||||||
|
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||||
|
])
|
||||||
|
->values(),
|
||||||
|
];
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function ticketSelectorData(CatalogItem $catalogItem): array
|
||||||
|
{
|
||||||
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,
|
||||||
'stock_tecnico' => $catalogItem->availableStock(),
|
'image' => $this->firstImageUrl($catalogItem),
|
||||||
'variants' => $catalogItem->variants
|
|
||||||
->map(fn (Variant $variant): array => [
|
|
||||||
'id' => $variant->id,
|
|
||||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
|
||||||
? null
|
|
||||||
: $variant->inventory->availableStock(),
|
|
||||||
'values' => $variant->definitions
|
|
||||||
->mapWithKeys(fn ($definition) => [
|
|
||||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
|
||||||
])
|
|
||||||
->filter(fn ($value, $key): bool => $key !== null),
|
|
||||||
])
|
|
||||||
->values(),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||||
{
|
{
|
||||||
$attachment = $catalogItem->attachments->first()
|
|
||||||
?? $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' => $attachment?->getTemporaryUrl(1440),
|
'image' => $this->firstImageUrl($catalogItem),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||||
|
{
|
||||||
|
$attachment = $catalogItem->attachments->first()
|
||||||
|
?? $catalogItem->variants
|
||||||
|
->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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ 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\Ticket\Resources\ValidityTimeResource;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
@@ -31,21 +34,19 @@ 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,
|
||||||
'has_tickets' => $this->has_tickets,
|
'has_tickets' => $this->has_tickets,
|
||||||
'minimum_use_date' => $this->minimum_use_date,
|
'attributes' => $this->attributesData(),
|
||||||
'maximum_use_date' => $this->maximum_use_date,
|
'maximum_addable_quantity' => $this->when(
|
||||||
'attributes' => $this->itemAttributes
|
|
||||||
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
|
||||||
->values(),
|
|
||||||
'stock_tecnico' => $this->when(
|
|
||||||
$selectedVariant === null,
|
$selectedVariant === null,
|
||||||
fn () => $this->availableStock(),
|
fn () => $this->maximumAddable($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(
|
||||||
@@ -78,6 +79,46 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
private function attributeData(ItemAttribute $itemAttribute): array
|
private function attributeData(ItemAttribute $itemAttribute): array
|
||||||
{
|
{
|
||||||
$attribute = $itemAttribute->attribute;
|
$attribute = $itemAttribute->attribute;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $attribute->id,
|
||||||
|
'codigo' => $attribute->codigo,
|
||||||
|
'nombre' => $attribute->nombre,
|
||||||
|
'sort_order' => $itemAttribute->sort_order,
|
||||||
|
'show_in_selector' => $itemAttribute->show_in_selector,
|
||||||
|
'ticket_label' => $itemAttribute->ticket_label,
|
||||||
|
'is_required' => $attribute->is_required,
|
||||||
|
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
||||||
|
'metadata_schema' => $attribute->metadata_schema,
|
||||||
|
'type' => $attribute->type->value,
|
||||||
|
'options' => $attribute->type === FieldType::EventDate
|
||||||
|
? $this->eventDateOptions($itemAttribute)
|
||||||
|
: $this->catalogAttributeOptions($itemAttribute),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Collection<int, array<string, mixed>> */
|
||||||
|
private function eventDateOptions(ItemAttribute $itemAttribute): Collection
|
||||||
|
{
|
||||||
|
return $itemAttribute->attribute->eventDates
|
||||||
|
->map(fn ($eventDate, int $index): array => [
|
||||||
|
'id' => $eventDate->id,
|
||||||
|
'value' => (string) $eventDate->id,
|
||||||
|
'label' => $eventDate->date->format('d/m/Y'),
|
||||||
|
'sort_order' => $index,
|
||||||
|
'validity_time_id' => $eventDate->validity_time_id,
|
||||||
|
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
||||||
|
'metadata' => [
|
||||||
|
'date' => $eventDate->date->format('Y-m-d'),
|
||||||
|
'time_start' => $eventDate->time_start,
|
||||||
|
'time_end' => $eventDate->time_end,
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Collection<int, array<string, mixed>> */
|
||||||
|
private function catalogAttributeOptions(ItemAttribute $itemAttribute): Collection
|
||||||
|
{
|
||||||
$availableValues = $this->variants
|
$availableValues = $this->variants
|
||||||
->flatMap->definitions
|
->flatMap->definitions
|
||||||
->where('item_attribute_id', $itemAttribute->id)
|
->where('item_attribute_id', $itemAttribute->id)
|
||||||
@@ -85,43 +126,50 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
->filter()
|
->filter()
|
||||||
->unique();
|
->unique();
|
||||||
|
|
||||||
return [
|
return $itemAttribute->attribute->options
|
||||||
'id' => $attribute->id,
|
->whereIn('value', $availableValues)
|
||||||
'codigo' => $attribute->codigo,
|
->map(fn ($option): array => [
|
||||||
'nombre' => $attribute->nombre,
|
'id' => $option->id,
|
||||||
'is_required' => $attribute->is_required,
|
'value' => $option->value,
|
||||||
'metadata_schema' => $attribute->metadata_schema,
|
'label' => $option->label,
|
||||||
'type' => $attribute->type->value,
|
'sort_order' => $option->sort_order,
|
||||||
'options' => $attribute->options
|
'validity_time_id' => $option->validity_time_id,
|
||||||
->whereIn('value', $availableValues)
|
'validity_time' => $option->validityTime === null
|
||||||
->map(fn ($option): array => [
|
? null
|
||||||
'id' => $option->id,
|
: ValidityTimeResource::make($option->validityTime),
|
||||||
'value' => $option->value,
|
'metadata' => $option->metadata,
|
||||||
'label' => $option->label,
|
])
|
||||||
'sort_order' => $option->sort_order,
|
->values();
|
||||||
'metadata' => $option->metadata,
|
}
|
||||||
])
|
|
||||||
->values(),
|
/** @return Collection<int, array<string, mixed>> */
|
||||||
];
|
private function attributesData(): Collection
|
||||||
|
{
|
||||||
|
return $this->itemAttributes
|
||||||
|
->sort(function (ItemAttribute $left, ItemAttribute $right): int {
|
||||||
|
return $left->sort_order <=> $right->sort_order
|
||||||
|
?: mb_strtolower($left->attribute->nombre) <=> mb_strtolower($right->attribute->nombre);
|
||||||
|
})
|
||||||
|
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
||||||
|
->values();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function variantData(Variant $variant): array
|
private function variantData(Variant $variant): array
|
||||||
{
|
{
|
||||||
|
$values = $variant->selectionOptions($this->itemAttributes);
|
||||||
|
$eventDates = $variant->selectedEventDates();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
'stock_tecnico' => $this->variantStock($variant),
|
'event_date_id' => $variant->event_date_id,
|
||||||
'minimum_use_date' => $variant->minimum_use_date,
|
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||||
'maximum_use_date' => $variant->maximum_use_date,
|
'event_date_ids' => $eventDates->pluck('id')->values(),
|
||||||
'effective_minimum_use_date' => $variant->minimum_use_date
|
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||||
?? $this->minimum_use_date,
|
'descripcion' => $variant->getDescription(),
|
||||||
'effective_maximum_use_date' => $variant->maximum_use_date
|
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
?? $this->maximum_use_date,
|
'maximum_addable_quantity' => $this->maximumAddable($this->variantStock($variant)),
|
||||||
'values' => $variant->definitions
|
'values' => $values,
|
||||||
->mapWithKeys(fn ($definition) => [
|
|
||||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
|
||||||
])
|
|
||||||
->filter(fn ($value, $key): bool => $key !== null),
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,4 +187,12 @@ 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'),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,9 +22,9 @@ 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,
|
||||||
'has_tickets' => $this->has_tickets,
|
'has_tickets' => $this->has_tickets,
|
||||||
'minimum_use_date' => $this->minimum_use_date,
|
|
||||||
'maximum_use_date' => $this->maximum_use_date,
|
|
||||||
'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))
|
||||||
@@ -32,18 +32,14 @@ class CatalogItemResource extends JsonResource
|
|||||||
'variants' => $this->whenLoaded('variants', fn () => $this->variants
|
'variants' => $this->whenLoaded('variants', fn () => $this->variants
|
||||||
->map(fn ($variant) => [
|
->map(fn ($variant) => [
|
||||||
'id' => $variant->id,
|
'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, '.', ''),
|
||||||
'real_stock' => $variant->inventory?->real_stock,
|
'real_stock' => $variant->inventory?->real_stock,
|
||||||
'minimum_use_date' => $variant->minimum_use_date,
|
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||||
'maximum_use_date' => $variant->maximum_use_date,
|
|
||||||
'effective_minimum_use_date' => $variant->minimum_use_date
|
|
||||||
?? $this->minimum_use_date,
|
|
||||||
'effective_maximum_use_date' => $variant->maximum_use_date
|
|
||||||
?? $this->maximum_use_date,
|
|
||||||
'values' => $variant->definitions
|
|
||||||
->mapWithKeys(fn ($definition) => [
|
|
||||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
|
||||||
])
|
|
||||||
->filter(fn ($value, $key) => $key !== null),
|
|
||||||
'images' => $variant->attachments
|
'images' => $variant->attachments
|
||||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||||
->values(),
|
->values(),
|
||||||
|
|||||||
@@ -5,6 +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 Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -26,20 +27,32 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
'descripcion' => $this->descripcion,
|
'descripcion' => $this->descripcion,
|
||||||
'precio' => $this->precio,
|
'precio' => $this->precio,
|
||||||
'image' => $attachment?->getTemporaryUrl(1440),
|
'image' => $attachment?->getTemporaryUrl(1440),
|
||||||
'stock_tecnico' => $this->availableStock(),
|
'maximum_addable_quantity' => $this->maximumAddable($this->availableStock()),
|
||||||
'variants' => $this->variants
|
'variants' => $this->visibleVariants()
|
||||||
->map(fn (Variant $variant): array => [
|
->map(fn (Variant $variant): array => [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
'event_date_id' => $variant->event_date_id,
|
||||||
? null
|
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||||
: $variant->inventory?->availableStock(),
|
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||||
'values' => $variant->definitions
|
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||||
->mapWithKeys(fn ($definition) => [
|
'descripcion' => $variant->getDescription(),
|
||||||
$definition->itemAttribute?->attribute?->codigo => $definition->value,
|
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
])
|
'maximum_addable_quantity' => $this->maximumAddable(
|
||||||
->filter(fn ($value, $key): bool => $key !== null),
|
$this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
? null
|
||||||
|
: $variant->inventory?->availableStock(),
|
||||||
|
),
|
||||||
|
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||||
])
|
])
|
||||||
->values(),
|
->values(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function maximumAddable(?int $stock): ?int
|
||||||
|
{
|
||||||
|
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
|
||||||
|
$stock,
|
||||||
|
$this->getAttribute('remaining_user_quota'),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Resources;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
class CatalogVariantOptionsResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return $this->resource;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,19 @@ 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),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
||||||
{
|
{
|
||||||
if ($selection instanceof CatalogItem
|
if ($selection instanceof CatalogItem
|
||||||
|
|||||||
40
app/Domains/Catalog/Services/CatalogItemAllowanceService.php
Normal file
40
app/Domains/Catalog/Services/CatalogItemAllowanceService.php
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class CatalogItemAllowanceService
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use App\Domains\Catalog\Models\Category;
|
|||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
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\Event\Models\EventDate;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
@@ -35,11 +36,53 @@ class CatalogService
|
|||||||
$variants = $data['variants'] ?? [];
|
$variants = $data['variants'] ?? [];
|
||||||
$images = $data['images'] ?? [];
|
$images = $data['images'] ?? [];
|
||||||
$attributeCodes = $data['attribute_codes'] ?? [];
|
$attributeCodes = $data['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);
|
||||||
|
|
||||||
$hasVariants = $attributeCodes !== [];
|
$hasEventDateVariants = $variants !== [] && collect($variants)->every(
|
||||||
|
fn (array $variant): bool => ! empty($variant['event_date_id'])
|
||||||
|
|| ! empty($variant['event_date_ids'])
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($hasEventDateVariants && ! in_array('event_date', $attributeCodes, true)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'attribute_codes' => [
|
||||||
|
__('api.catalog.event_date_attribute_required'),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$hasVariants = $attributeCodes !== [] || $hasEventDateVariants;
|
||||||
|
|
||||||
|
if (array_diff($multiSelectAttributeCodes, $attributeCodes) !== []) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'multi_select_attribute_codes' => [
|
||||||
|
__('api.catalog.multi_select_attribute_not_on_item'),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
if ($type === CatalogItemType::Bundle) {
|
if ($type === CatalogItemType::Bundle) {
|
||||||
$this->validateBundleData($data, $components);
|
$this->validateBundleData($data, $components);
|
||||||
@@ -62,6 +105,9 @@ class CatalogService
|
|||||||
$data['variants'],
|
$data['variants'],
|
||||||
$data['images'],
|
$data['images'],
|
||||||
$data['attribute_codes'],
|
$data['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'],
|
||||||
@@ -75,8 +121,6 @@ class CatalogService
|
|||||||
$data['inventory_id'] = null;
|
$data['inventory_id'] = null;
|
||||||
$data['inventory_policy'] = null;
|
$data['inventory_policy'] = null;
|
||||||
$data['has_tickets'] = false;
|
$data['has_tickets'] = false;
|
||||||
$data['minimum_use_date'] = null;
|
|
||||||
$data['maximum_use_date'] = null;
|
|
||||||
} elseif ($hasVariants) {
|
} elseif ($hasVariants) {
|
||||||
$data['inventory_id'] = null;
|
$data['inventory_id'] = null;
|
||||||
} else {
|
} else {
|
||||||
@@ -85,7 +129,13 @@ class CatalogService
|
|||||||
|
|
||||||
$catalogItem = CatalogItem::query()->create($data);
|
$catalogItem = CatalogItem::query()->create($data);
|
||||||
$itemAttributes = $type === CatalogItemType::Standard
|
$itemAttributes = $type === CatalogItemType::Standard
|
||||||
? $this->createItemAttributes($catalogItem, $attributeCodes)
|
? $this->createItemAttributes(
|
||||||
|
$catalogItem,
|
||||||
|
$attributeCodes,
|
||||||
|
$multiSelectAttributeCodes,
|
||||||
|
$hiddenAttributeCodes,
|
||||||
|
$ticketAttributeLabels,
|
||||||
|
)
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
if ($type === CatalogItemType::Bundle) {
|
if ($type === CatalogItemType::Bundle) {
|
||||||
@@ -124,7 +174,9 @@ class CatalogService
|
|||||||
'itemAttributes.attribute',
|
'itemAttributes.attribute',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.definitions.itemAttribute.attribute',
|
'variants.eventDate',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
]);
|
]);
|
||||||
@@ -138,20 +190,24 @@ class CatalogService
|
|||||||
'inventory',
|
'inventory',
|
||||||
'category',
|
'category',
|
||||||
'brand',
|
'brand',
|
||||||
'itemAttributes.attribute.options',
|
'itemAttributes.attribute.options.validityTime',
|
||||||
|
'itemAttributes.attribute.eventDates.validityTime',
|
||||||
'variants' => fn ($query) => $query->orderBy('id'),
|
'variants' => fn ($query) => $query->orderBy('id'),
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
|
'variants.eventDate',
|
||||||
|
'variants.eventDates',
|
||||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||||
'variants.definitions.itemAttribute.attribute',
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
'bundleComponents.catalogItem.inventory',
|
'bundleComponents.catalogItem.inventory',
|
||||||
'bundleComponents.variant.inventory',
|
'bundleComponents.variant.inventory',
|
||||||
'bundleComponents.variant.definitions.itemAttribute.attribute',
|
'bundleComponents.variant.definitions.itemAttribute.attribute',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$visibleVariants = $catalogItem->visibleVariants();
|
||||||
$selectedVariant = $variantId === null
|
$selectedVariant = $variantId === null
|
||||||
? $catalogItem->variants->first()
|
? $visibleVariants->first()
|
||||||
: $catalogItem->variants->firstWhere('id', $variantId);
|
: $visibleVariants->firstWhere('id', $variantId);
|
||||||
|
|
||||||
if ($variantId !== null && $selectedVariant === null) {
|
if ($variantId !== null && $selectedVariant === null) {
|
||||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||||
@@ -175,6 +231,7 @@ class CatalogService
|
|||||||
|
|
||||||
$paginator = CatalogItem::query()
|
$paginator = CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->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])
|
||||||
@@ -193,9 +250,12 @@ class CatalogService
|
|||||||
->with([
|
->with([
|
||||||
'attachments',
|
'attachments',
|
||||||
'inventory',
|
'inventory',
|
||||||
|
'itemAttributes.attribute',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.definitions.itemAttribute.attribute',
|
'variants.eventDate',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
])
|
])
|
||||||
@@ -221,12 +281,16 @@ 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)
|
||||||
|
->whereVariantsAvailable()
|
||||||
->with([
|
->with([
|
||||||
'attachments',
|
'attachments',
|
||||||
'inventory',
|
'inventory',
|
||||||
|
'itemAttributes.attribute',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.definitions.itemAttribute.attribute',
|
'variants.eventDate',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
])
|
])
|
||||||
@@ -237,32 +301,28 @@ 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->load([
|
$catalogItem->variants()->delete();
|
||||||
'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) {
|
public function deleteVariant(Variant $variant): void
|
||||||
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
{
|
||||||
$this->attachmentService->delete($attachment);
|
DB::transaction(function () use ($variant): void {
|
||||||
}
|
$variant = Variant::query()
|
||||||
|
->lockForUpdate()
|
||||||
|
->findOrFail($variant->getKey());
|
||||||
|
$catalogItem = CatalogItem::query()
|
||||||
|
->lockForUpdate()
|
||||||
|
->findOrFail($variant->catalog_item_id);
|
||||||
|
$variant->delete();
|
||||||
|
|
||||||
|
if (! $catalogItem->variants()->exists()) {
|
||||||
|
$this->delete($catalogItem);
|
||||||
|
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) {
|
||||||
|
$catalogItem->update(['precio' => $minimumPrice]);
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -367,8 +427,6 @@ class CatalogService
|
|||||||
'attribute_codes',
|
'attribute_codes',
|
||||||
'variants',
|
'variants',
|
||||||
'has_tickets',
|
'has_tickets',
|
||||||
'minimum_use_date',
|
|
||||||
'maximum_use_date',
|
|
||||||
] as $field) {
|
] as $field) {
|
||||||
if (array_key_exists($field, $data)) {
|
if (array_key_exists($field, $data)) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
@@ -412,11 +470,17 @@ class CatalogService
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<int, string> $attributeCodes
|
* @param array<int, string> $attributeCodes
|
||||||
|
* @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 $hiddenAttributeCodes = [],
|
||||||
|
array $ticketAttributeLabels = [],
|
||||||
): array {
|
): array {
|
||||||
$itemAttributes = [];
|
$itemAttributes = [];
|
||||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||||
@@ -439,6 +503,9 @@ 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),
|
||||||
|
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
|
||||||
|
'ticket_label' => $ticketAttributeLabels[$attributeCode] ?? null,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$itemAttributes[$attributeCode] = $itemAttribute;
|
$itemAttributes[$attributeCode] = $itemAttribute;
|
||||||
@@ -472,15 +539,53 @@ class CatalogService
|
|||||||
}
|
}
|
||||||
|
|
||||||
$inventory = $this->createInventory((int) ($data['real_stock'] ?? 0));
|
$inventory = $this->createInventory((int) ($data['real_stock'] ?? 0));
|
||||||
|
$eventDateIds = collect($data['event_date_ids'] ?? [])
|
||||||
|
->when(
|
||||||
|
isset($data['event_date_id']),
|
||||||
|
fn ($ids) => $ids->push($data['event_date_id']),
|
||||||
|
)
|
||||||
|
->filter(fn ($id): bool => $id !== null)
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->unique()
|
||||||
|
->sort()
|
||||||
|
->values();
|
||||||
|
|
||||||
|
$eventDateItemAttribute = $itemAttributes['event_date'] ?? null;
|
||||||
|
if ($eventDateItemAttribute !== null && (
|
||||||
|
$eventDateIds->isEmpty()
|
||||||
|
|| (! $eventDateItemAttribute->allow_multi_select && $eventDateIds->count() !== 1)
|
||||||
|
)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
"variants.{$index}.event_date_ids" => [
|
||||||
|
$eventDateItemAttribute->allow_multi_select
|
||||||
|
? __('api.catalog.event_date_selection_required')
|
||||||
|
: __('api.catalog.single_event_date_required'),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$validEventDateCount = EventDate::query()
|
||||||
|
->whereKey($eventDateIds)
|
||||||
|
->where('tenant_code', $catalogItem->tenant_code)
|
||||||
|
->count();
|
||||||
|
|
||||||
|
if ($validEventDateCount !== $eventDateIds->count()) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
"variants.{$index}.event_date_ids" => [
|
||||||
|
__('api.catalog.event_date_wrong_tenant'),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
$variant = $catalogItem->variants()->create([
|
$variant = $catalogItem->variants()->create([
|
||||||
'inventory_id' => $inventory->id,
|
'inventory_id' => $inventory->id,
|
||||||
'minimum_use_date' => $data['minimum_use_date'] ?? null,
|
'event_date_id' => $eventDateIds->count() === 1 ? $eventDateIds->first() : null,
|
||||||
'maximum_use_date' => $data['maximum_use_date'] ?? null,
|
'descripcion' => $data['descripcion'] ?? null,
|
||||||
|
'precio' => $data['precio'] ?? null,
|
||||||
]);
|
]);
|
||||||
|
$variant->eventDates()->sync($eventDateIds->all());
|
||||||
$variant->setRelation('catalogItem', $catalogItem);
|
$variant->setRelation('catalogItem', $catalogItem);
|
||||||
|
|
||||||
$this->validateVariantUseDates($variant, $index);
|
|
||||||
|
|
||||||
foreach ($data['values'] ?? [] as $attributeCode => $value) {
|
foreach ($data['values'] ?? [] as $attributeCode => $value) {
|
||||||
$itemAttribute = $itemAttributes[$attributeCode] ?? null;
|
$itemAttribute = $itemAttributes[$attributeCode] ?? null;
|
||||||
|
|
||||||
@@ -492,31 +597,120 @@ class CatalogService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$variant->definitions()->create([
|
foreach ($this->validatedVariantValues(
|
||||||
'item_attribute_id' => $itemAttribute->id,
|
$itemAttribute,
|
||||||
'value' => $value,
|
$value,
|
||||||
]);
|
"variants.{$index}.values.{$attributeCode}",
|
||||||
|
) as $validatedValue) {
|
||||||
|
$variant->definitions()->create([
|
||||||
|
'item_attribute_id' => $itemAttribute->id,
|
||||||
|
'value' => $validatedValue,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $variant;
|
return $variant;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function validateVariantUseDates(Variant $variant, int $index): void
|
/**
|
||||||
|
* @param array<int, array<string, mixed>> $variants
|
||||||
|
* @param array<int, string> $attributeCodes
|
||||||
|
*/
|
||||||
|
private function validateUniqueVariantCombinations(array $variants, array $attributeCodes): void
|
||||||
{
|
{
|
||||||
$minimumUseDate = $variant->getMinimumUseDate();
|
$seen = [];
|
||||||
$maximumUseDate = $variant->getMaximumUseDate();
|
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||||
|
sort($attributeCodes);
|
||||||
|
|
||||||
if (
|
foreach (array_values($variants) as $index => $variant) {
|
||||||
$minimumUseDate !== null
|
$eventDateIds = collect($variant['event_date_ids'] ?? [])
|
||||||
&& $maximumUseDate !== null
|
->when(
|
||||||
&& $maximumUseDate->lessThan($minimumUseDate)
|
isset($variant['event_date_id']),
|
||||||
) {
|
fn ($ids) => $ids->push($variant['event_date_id']),
|
||||||
|
)
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->unique()
|
||||||
|
->sort()
|
||||||
|
->values()
|
||||||
|
->implode(',');
|
||||||
|
$combination = [$eventDateIds];
|
||||||
|
|
||||||
|
foreach ($attributeCodes as $attributeCode) {
|
||||||
|
$values = $variant['values'][$attributeCode] ?? '';
|
||||||
|
$normalizedValues = collect(is_array($values) ? $values : [$values])
|
||||||
|
->map(fn ($value): string => $this->normalizeVariantValue((string) $value))
|
||||||
|
->unique()
|
||||||
|
->sort()
|
||||||
|
->values()
|
||||||
|
->implode(',');
|
||||||
|
$combination[] = $normalizedValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
$key = implode('|', $combination);
|
||||||
|
if (isset($seen[$key])) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
"variants.{$index}" => [__('api.catalog.duplicate_variant_combination')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$seen[$key] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<int, string> */
|
||||||
|
private function validatedVariantValues(
|
||||||
|
ItemAttribute $itemAttribute,
|
||||||
|
mixed $value,
|
||||||
|
string $validationKey,
|
||||||
|
): array {
|
||||||
|
$values = is_array($value) ? array_values($value) : [$value];
|
||||||
|
|
||||||
|
if ($values === [] || (! $itemAttribute->allow_multi_select && count($values) !== 1)) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
"variants.{$index}.maximum_use_date" => [
|
$validationKey => [
|
||||||
__('api.catalog.invalid_effective_date_range'),
|
$itemAttribute->allow_multi_select
|
||||||
|
? __('api.catalog.multi_value_required')
|
||||||
|
: __('api.catalog.single_value_required'),
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (collect($values)->contains(fn ($item): bool => ! is_string($item) || trim($item) === '')) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
$validationKey => [__('api.catalog.selected_values_non_empty')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalizedValues = collect($values)
|
||||||
|
->map(fn (string $item): string => $this->normalizeVariantValue($item));
|
||||||
|
|
||||||
|
if ($normalizedValues->unique()->count() !== count($values)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
$validationKey => [__('api.catalog.selected_values_distinct')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$attribute = $itemAttribute->attribute;
|
||||||
|
if ($attribute->type->supportsOptions() && ! $attribute->type->usesDynamicOptions()) {
|
||||||
|
$optionsByNormalizedValue = $attribute->options
|
||||||
|
->keyBy(fn ($option): string => $this->normalizeVariantValue($option->value));
|
||||||
|
|
||||||
|
$resolvedOptions = $normalizedValues->map(fn (string $normalizedValue) => $optionsByNormalizedValue->get($normalizedValue));
|
||||||
|
if ($resolvedOptions->contains(null)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
$validationKey => [__('api.catalog.invalid_attribute_options')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $resolvedOptions->pluck('value')->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
return collect($values)->map(fn (string $item): string => trim($item))->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizeVariantValue(string $value): string
|
||||||
|
{
|
||||||
|
return Str::ascii(mb_strtolower(trim($value)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
||||||
|
use App\Domains\Purchase\Services\CheckoutService;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class ExpireStockReservationsService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly CheckoutService $checkout,
|
||||||
|
private readonly ExpireCartReservationsService $carts,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{purchases: int, cart_items: int}
|
||||||
|
*/
|
||||||
|
public function expireOverdue(): array
|
||||||
|
{
|
||||||
|
$expiredPurchases = null;
|
||||||
|
$expiredCartItems = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$expiredPurchases = $this->checkout->expireOverduePurchases();
|
||||||
|
$expiredCartItems = $this->carts->expireOverdue();
|
||||||
|
|
||||||
|
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
||||||
|
'command' => 'reservations:expire',
|
||||||
|
'expired_purchases' => $expiredPurchases,
|
||||||
|
'expired_cart_items' => $expiredCartItems,
|
||||||
|
'total_expired' => $expiredPurchases + $expiredCartItems,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'purchases' => $expiredPurchases,
|
||||||
|
'cart_items' => $expiredCartItems,
|
||||||
|
];
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::channel('commands')->error('Stock reservation cleanup failed.', [
|
||||||
|
'command' => 'reservations:expire',
|
||||||
|
'expired_purchases' => $expiredPurchases,
|
||||||
|
'expired_cart_items' => $expiredCartItems,
|
||||||
|
'exception' => $exception,
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
102
app/Domains/Catalog/Services/FeaturedGroupService.php
Normal file
102
app/Domains/Catalog/Services/FeaturedGroupService.php
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||||
|
use App\Domains\Catalog\Enums\GroupLayout;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||||
|
use App\Domains\Catalog\Resources\CatalogFeaturedItemResource;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
|
|
||||||
|
class FeaturedGroupService
|
||||||
|
{
|
||||||
|
private const ITEMS_PER_PAGE = 12;
|
||||||
|
|
||||||
|
/** @return array<array-key, mixed> */
|
||||||
|
public function __construct(
|
||||||
|
private readonly CatalogItemAllowanceService $allowances,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function itemsResponse(FeaturedGroup $featuredGroup, int $page, ?int $userId = null): array
|
||||||
|
{
|
||||||
|
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||||
|
$query = $this->itemsQuery($featuredGroup);
|
||||||
|
|
||||||
|
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
||||||
|
$query->limit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
$items = $query->get();
|
||||||
|
$this->attachGroup($items, $featuredGroup);
|
||||||
|
$this->allowances->attach($items, $userId);
|
||||||
|
|
||||||
|
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
$paginator = $this->paginateItems($featuredGroup, $page);
|
||||||
|
$this->attachGroup($paginator->getCollection(), $featuredGroup);
|
||||||
|
$this->allowances->attach($paginator->getCollection(), $userId);
|
||||||
|
|
||||||
|
return CatalogFeaturedItemResource::collection($paginator)
|
||||||
|
->response()
|
||||||
|
->getData(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return Builder<CatalogItem> */
|
||||||
|
private function itemsQuery(FeaturedGroup $featuredGroup): Builder
|
||||||
|
{
|
||||||
|
$query = CatalogItem::query()
|
||||||
|
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
|
||||||
|
->whereVariantsAvailable()
|
||||||
|
->with([
|
||||||
|
'inventory',
|
||||||
|
'attachments',
|
||||||
|
'itemAttributes.attribute',
|
||||||
|
'variants.inventory',
|
||||||
|
'variants.attachments',
|
||||||
|
'variants.eventDate',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
'bundleComponents.catalogItem',
|
||||||
|
'bundleComponents.variant.catalogItem',
|
||||||
|
]);
|
||||||
|
|
||||||
|
return match ($featuredGroup->source_type) {
|
||||||
|
FeaturedGroupSource::Manual => $query
|
||||||
|
->select('catalog_items.*')
|
||||||
|
->join('featured_items', 'featured_items.catalog_item_id', '=', 'catalog_items.id')
|
||||||
|
->where('featured_items.featured_group_id', $featuredGroup->id)
|
||||||
|
->orderBy('featured_items.order')
|
||||||
|
->orderBy('featured_items.id'),
|
||||||
|
FeaturedGroupSource::Category => $query
|
||||||
|
->where('catalog_items.category_id', $featuredGroup->category_id)
|
||||||
|
->orderBy('catalog_items.id'),
|
||||||
|
FeaturedGroupSource::All => $query->orderBy('catalog_items.id'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function paginateItems(
|
||||||
|
FeaturedGroup $featuredGroup,
|
||||||
|
int $page,
|
||||||
|
): LengthAwarePaginator {
|
||||||
|
$paginator = $this->itemsQuery($featuredGroup)->paginate(
|
||||||
|
perPage: self::ITEMS_PER_PAGE,
|
||||||
|
pageName: 'page',
|
||||||
|
page: $page,
|
||||||
|
);
|
||||||
|
|
||||||
|
return $paginator->withPath(route('catalog.featured-groups.items.index', [
|
||||||
|
'tenant' => $featuredGroup->tenant_code,
|
||||||
|
'featuredGroup' => $featuredGroup->id,
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function attachGroup(iterable $items, FeaturedGroup $featuredGroup): void
|
||||||
|
{
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$item->setRelation('featuredGroup', $featuredGroup);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||||
|
use App\Domains\Catalog\Enums\GroupLayout;
|
||||||
|
use App\Domains\Catalog\Enums\ProductLayout;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class OnTicketFeaturedGroupService
|
||||||
|
{
|
||||||
|
/** @return Collection<int, FeaturedGroup> */
|
||||||
|
public function forTenant(Tenant $tenant): Collection
|
||||||
|
{
|
||||||
|
return FeaturedGroup::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('source_type', FeaturedGroupSource::Category)
|
||||||
|
->whereHas('category', fn ($query) => $query->where('tenant_code', $tenant->codigo))
|
||||||
|
->with('category')
|
||||||
|
->orderBy('group_order')
|
||||||
|
->orderBy('id')
|
||||||
|
->get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array{category_name: string, is_featured: bool} $data */
|
||||||
|
public function create(Tenant $tenant, array $data): FeaturedGroup
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($tenant, $data): FeaturedGroup {
|
||||||
|
$category = $tenant->categories()->create([
|
||||||
|
'nombre' => $data['category_name'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$featuredGroup = FeaturedGroup::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'source_type' => FeaturedGroupSource::Category,
|
||||||
|
'category_id' => $category->id,
|
||||||
|
'product_layout' => $this->productLayout($data['is_featured']),
|
||||||
|
'group_layout' => GroupLayout::Paginated,
|
||||||
|
'group_name' => $data['category_name'],
|
||||||
|
'group_order' => $this->nextOrder($tenant),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $featuredGroup->setRelation('category', $category);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array{category_name: string, is_featured: bool} $data */
|
||||||
|
public function update(
|
||||||
|
Tenant $tenant,
|
||||||
|
FeaturedGroup $featuredGroup,
|
||||||
|
array $data,
|
||||||
|
): FeaturedGroup {
|
||||||
|
return DB::transaction(function () use ($tenant, $featuredGroup, $data): FeaturedGroup {
|
||||||
|
$featuredGroup = FeaturedGroup::query()
|
||||||
|
->whereKey($featuredGroup->getKey())
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('source_type', FeaturedGroupSource::Category)
|
||||||
|
->lockForUpdate()
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$category = Category::query()
|
||||||
|
->whereKey($featuredGroup->category_id)
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->lockForUpdate()
|
||||||
|
->firstOrFail();
|
||||||
|
|
||||||
|
$category->update(['nombre' => $data['category_name']]);
|
||||||
|
$featuredGroup->update([
|
||||||
|
'group_name' => $data['category_name'],
|
||||||
|
'product_layout' => $this->productLayout($data['is_featured']),
|
||||||
|
'group_layout' => GroupLayout::Paginated,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $featuredGroup->setRelation('category', $category);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function productLayout(bool $isFeatured): ProductLayout
|
||||||
|
{
|
||||||
|
return $isFeatured ? ProductLayout::Row : ProductLayout::ColumnWithCart;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function nextOrder(Tenant $tenant): int
|
||||||
|
{
|
||||||
|
$maximumOrder = FeaturedGroup::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->max('group_order');
|
||||||
|
|
||||||
|
return $maximumOrder === null ? 0 : ((int) $maximumOrder) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
230
app/Domains/Catalog/Services/StockReservationService.php
Normal file
230
app/Domains/Catalog/Services/StockReservationService.php
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\CartItem;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class StockReservationService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly CatalogInventoryService $inventory,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($cartItem, $selection, $quantity): void {
|
||||||
|
$this->inventory->reserve($selection, $quantity);
|
||||||
|
$this->recordIncrease($cartItem, $selection, $quantity);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function release(
|
||||||
|
CartItem $cartItem,
|
||||||
|
CatalogItem|Variant $selection,
|
||||||
|
int $quantity,
|
||||||
|
string $releasedStatus = StockReservation::STATUS_RELEASED,
|
||||||
|
): void {
|
||||||
|
DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
|
||||||
|
$this->ensure($cartItem, $selection);
|
||||||
|
$this->inventory->release($selection, $quantity);
|
||||||
|
$this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function commit(CartItem $cartItem, CatalogItem|Variant $selection): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($cartItem, $selection): void {
|
||||||
|
$this->ensure($cartItem, $selection);
|
||||||
|
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
||||||
|
|
||||||
|
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
||||||
|
foreach ($requirements as $inventoryId => $quantity) {
|
||||||
|
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||||
|
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$reservation->update([
|
||||||
|
'status' => StockReservation::STATUS_COMMITTED,
|
||||||
|
'committed_at' => now(),
|
||||||
|
'expires_at' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function ensure(CartItem $cartItem, CatalogItem|Variant $selection): void
|
||||||
|
{
|
||||||
|
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
||||||
|
|
||||||
|
foreach ($requirements as $inventoryId => $quantity) {
|
||||||
|
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||||
|
|
||||||
|
if ($reservation === null) {
|
||||||
|
StockReservation::query()->create([
|
||||||
|
'inventory_id' => $inventoryId,
|
||||||
|
'cart_item_id' => $cartItem->getKey(),
|
||||||
|
'quantity' => $quantity,
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
||||||
|
$reservation->update([
|
||||||
|
'quantity' => $quantity,
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'committed_at' => null,
|
||||||
|
'released_at' => null,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function attachToPurchase(
|
||||||
|
CartItem $cartItem,
|
||||||
|
CatalogItem|Variant $selection,
|
||||||
|
Purchase $purchase,
|
||||||
|
): void {
|
||||||
|
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
||||||
|
$this->ensure($cartItem, $selection);
|
||||||
|
StockReservation::query()
|
||||||
|
->where('cart_item_id', $cartItem->getKey())
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->update([
|
||||||
|
'purchase_id' => $purchase->getKey(),
|
||||||
|
'expires_at' => $purchase->expires_at,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function detachFromPurchase(Purchase $purchase): void
|
||||||
|
{
|
||||||
|
StockReservation::query()
|
||||||
|
->where('purchase_id', $purchase->getKey())
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->update([
|
||||||
|
'purchase_id' => null,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function syncPurchaseExpiration(Purchase $purchase): void
|
||||||
|
{
|
||||||
|
StockReservation::query()
|
||||||
|
->where('purchase_id', $purchase->getKey())
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->update(['expires_at' => $purchase->expires_at]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function transfer(CartItem $source, CartItem $target): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($source, $target): void {
|
||||||
|
$sourceReservations = StockReservation::query()
|
||||||
|
->where('cart_item_id', $source->getKey())
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->orderBy('inventory_id')
|
||||||
|
->lockForUpdate()
|
||||||
|
->get();
|
||||||
|
|
||||||
|
foreach ($sourceReservations as $sourceReservation) {
|
||||||
|
$targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
|
||||||
|
|
||||||
|
if ($targetReservation === null) {
|
||||||
|
$sourceItemQuantity = (int) $source->cantidad;
|
||||||
|
$targetItemQuantity = (int) $target->fresh()->cantidad;
|
||||||
|
$perItemQuantity = intdiv((int) $sourceReservation->quantity, $sourceItemQuantity);
|
||||||
|
$sourceReservation->update([
|
||||||
|
'cart_item_id' => $target->getKey(),
|
||||||
|
'purchase_id' => null,
|
||||||
|
'quantity' => $perItemQuantity * $targetItemQuantity,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$targetReservation->update([
|
||||||
|
'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
$sourceReservation->delete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
||||||
|
{
|
||||||
|
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
||||||
|
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||||
|
|
||||||
|
if ($reservation === null) {
|
||||||
|
StockReservation::query()->create([
|
||||||
|
'inventory_id' => $inventoryId,
|
||||||
|
'cart_item_id' => $cartItem->getKey(),
|
||||||
|
'quantity' => $requiredQuantity,
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$reservation->update([
|
||||||
|
'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
|
||||||
|
'status' => StockReservation::STATUS_ACTIVE,
|
||||||
|
'committed_at' => null,
|
||||||
|
'released_at' => null,
|
||||||
|
'expires_at' => $this->expiration(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function recordDecrease(
|
||||||
|
CartItem $cartItem,
|
||||||
|
CatalogItem|Variant $selection,
|
||||||
|
int $quantity,
|
||||||
|
string $releasedStatus,
|
||||||
|
): void {
|
||||||
|
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
||||||
|
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||||
|
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity < $requiredQuantity) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock no alcanza para liberar la cantidad solicitada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$remaining = $reservation->quantity - $requiredQuantity;
|
||||||
|
$reservation->update([
|
||||||
|
'quantity' => $remaining,
|
||||||
|
'status' => $remaining === 0 ? $releasedStatus : StockReservation::STATUS_ACTIVE,
|
||||||
|
'released_at' => $remaining === 0 ? now() : null,
|
||||||
|
'expires_at' => $remaining === 0 ? null : $reservation->expires_at,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function lockReservation(CartItem $cartItem, int $inventoryId): ?StockReservation
|
||||||
|
{
|
||||||
|
return StockReservation::query()
|
||||||
|
->where('cart_item_id', $cartItem->getKey())
|
||||||
|
->where('inventory_id', $inventoryId)
|
||||||
|
->lockForUpdate()
|
||||||
|
->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function expiration(): Carbon
|
||||||
|
{
|
||||||
|
return now()->addMinutes(
|
||||||
|
max(1, (int) config('catalog.stock_reservation_expiration_minutes', 30)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
225
app/Domains/Catalog/Services/VariantSelectionService.php
Normal file
225
app/Domains/Catalog/Services/VariantSelectionService.php
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\ItemAttribute;
|
||||||
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class VariantSelectionService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $selectedValues
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function options(
|
||||||
|
CatalogItem $catalogItem,
|
||||||
|
array $selectedValues,
|
||||||
|
?int $includedVariantId = null,
|
||||||
|
): array {
|
||||||
|
$catalogItem->load([
|
||||||
|
'itemAttributes.attribute',
|
||||||
|
'variants' => fn ($query) => $query->orderBy('id'),
|
||||||
|
'variants.inventory',
|
||||||
|
'variants.eventDate',
|
||||||
|
'variants.eventDates',
|
||||||
|
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||||
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$variants = $catalogItem->visibleVariants($includedVariantId)
|
||||||
|
->values();
|
||||||
|
$normalizedSelections = collect($selectedValues)
|
||||||
|
->mapWithKeys(fn ($value, string $key): array => [$key => $this->normalizeValue($value)])
|
||||||
|
->filter(fn ($value): bool => $value !== null && $value !== '' && $value !== [])
|
||||||
|
->all();
|
||||||
|
$matchingVariants = $variants
|
||||||
|
->filter(fn (Variant $variant): bool => $this->matches($variant, $normalizedSelections))
|
||||||
|
->values();
|
||||||
|
$attributeKeys = $this->attributeKeys($catalogItem, $catalogItem->variants->values());
|
||||||
|
$isComplete = $attributeKeys->isNotEmpty()
|
||||||
|
&& $attributeKeys->every(fn (string $key): bool => array_key_exists($key, $normalizedSelections));
|
||||||
|
$resolvedVariant = $isComplete && $matchingVariants->count() === 1
|
||||||
|
? $matchingVariants->first()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'variants' => $variants
|
||||||
|
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
|
||||||
|
->values()
|
||||||
|
->all(),
|
||||||
|
'selectors' => $this->selectors(
|
||||||
|
$catalogItem,
|
||||||
|
$variants,
|
||||||
|
$attributeKeys,
|
||||||
|
$matchingVariants->isEmpty() ? [] : $normalizedSelections,
|
||||||
|
),
|
||||||
|
'selected_values' => (object) ($matchingVariants->isEmpty() ? [] : $normalizedSelections),
|
||||||
|
'resolved_variant' => $resolvedVariant === null
|
||||||
|
? null
|
||||||
|
: $this->variantData($catalogItem, $resolvedVariant),
|
||||||
|
'valid' => $matchingVariants->isNotEmpty(),
|
||||||
|
'available_variant_count' => $variants->count(),
|
||||||
|
'matching_variant_count' => $matchingVariants->count(),
|
||||||
|
'price_range' => $this->priceRange($catalogItem, $variants),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed> $selectedValues */
|
||||||
|
private function matches(Variant $variant, array $selectedValues): bool
|
||||||
|
{
|
||||||
|
$variantValues = $variant->selectionValues();
|
||||||
|
|
||||||
|
foreach ($selectedValues as $key => $selectedValue) {
|
||||||
|
if (! $variantValues->has($key)
|
||||||
|
|| $this->valueKey($variantValues->get($key)) !== $this->valueKey($selectedValue)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Collection<int, Variant> $variants */
|
||||||
|
private function attributeKeys(CatalogItem $catalogItem, Collection $variants): Collection
|
||||||
|
{
|
||||||
|
return $variants
|
||||||
|
->flatMap(fn (Variant $variant): array => $variant
|
||||||
|
->selectorOptions($catalogItem->itemAttributes)
|
||||||
|
->keys()
|
||||||
|
->all())
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Variant> $variants
|
||||||
|
* @param Collection<int, string> $attributeKeys
|
||||||
|
* @param array<string, mixed> $selectedValues
|
||||||
|
* @return list<array<string, mixed>>
|
||||||
|
*/
|
||||||
|
private function selectors(
|
||||||
|
CatalogItem $catalogItem,
|
||||||
|
Collection $variants,
|
||||||
|
Collection $attributeKeys,
|
||||||
|
array $selectedValues,
|
||||||
|
): array {
|
||||||
|
return $attributeKeys
|
||||||
|
->map(function (string $key, int $index) use (
|
||||||
|
$catalogItem,
|
||||||
|
$variants,
|
||||||
|
$attributeKeys,
|
||||||
|
$selectedValues,
|
||||||
|
): array {
|
||||||
|
$previousKeys = $attributeKeys->take($index);
|
||||||
|
$previousSelections = collect($selectedValues)
|
||||||
|
->only($previousKeys->all())
|
||||||
|
->all();
|
||||||
|
$compatibleVariants = $variants
|
||||||
|
->filter(fn (Variant $variant): bool => $this->matches($variant, $previousSelections));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'key' => $key,
|
||||||
|
'label' => $this->attributeLabel($catalogItem, $key),
|
||||||
|
'options' => $this->optionsFor($catalogItem, $compatibleVariants, $key),
|
||||||
|
'enabled' => $index === 0 || $previousKeys->every(
|
||||||
|
fn (string $previousKey): bool => array_key_exists($previousKey, $selectedValues),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->values()
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Collection<int, Variant> $variants
|
||||||
|
* @return list<mixed>
|
||||||
|
*/
|
||||||
|
private function optionsFor(CatalogItem $catalogItem, Collection $variants, string $key): array
|
||||||
|
{
|
||||||
|
$options = [];
|
||||||
|
$seen = [];
|
||||||
|
|
||||||
|
foreach ($variants as $variant) {
|
||||||
|
$option = $variant->selectorOptions($catalogItem->itemAttributes)->get($key);
|
||||||
|
if ($option === null || $option === '') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$optionKey = $this->valueKey($option);
|
||||||
|
if (isset($seen[$optionKey])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$seen[$optionKey] = true;
|
||||||
|
$options[] = $option;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $options;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function attributeLabel(CatalogItem $catalogItem, string $key): string
|
||||||
|
{
|
||||||
|
if ($key === 'event_date') {
|
||||||
|
return 'Fecha';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $catalogItem->itemAttributes
|
||||||
|
->first(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo === $key)
|
||||||
|
?->attribute
|
||||||
|
?->nombre ?? str($key)->headline()->toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Collection<int, Variant> $variants */
|
||||||
|
private function priceRange(CatalogItem $catalogItem, Collection $variants): array
|
||||||
|
{
|
||||||
|
$prices = $variants
|
||||||
|
->map(fn (Variant $variant): float => $variant->getPrice())
|
||||||
|
->whenEmpty(fn (Collection $prices): Collection => $prices->push($catalogItem->getPrice()));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'minimum' => number_format((float) $prices->min(), 2, '.', ''),
|
||||||
|
'maximum' => number_format((float) $prices->max(), 2, '.', ''),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'descripcion' => $variant->getDescription(),
|
||||||
|
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
|
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
? null
|
||||||
|
: $variant->inventory?->availableStock(),
|
||||||
|
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizeValue(mixed $value): mixed
|
||||||
|
{
|
||||||
|
if (is_array($value) && array_key_exists('value', $value)) {
|
||||||
|
return (string) $value['value'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_array($value)) {
|
||||||
|
return array_map(fn ($item) => $this->normalizeValue($item), $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return is_scalar($value) ? (string) $value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function valueKey(mixed $value): string
|
||||||
|
{
|
||||||
|
$normalized = $this->normalizeValue($value);
|
||||||
|
|
||||||
|
if (is_array($normalized)) {
|
||||||
|
sort($normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
return json_encode($normalized, JSON_THROW_ON_ERROR);
|
||||||
|
}
|
||||||
|
}
|
||||||
35
app/Domains/Catalog/documentacion/README.md
Normal file
35
app/Domains/Catalog/documentacion/README.md
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# Dominio Catalog
|
||||||
|
|
||||||
|
## Propósito
|
||||||
|
|
||||||
|
Modela y publica la oferta comercial del tenant: productos, variantes, categorías, marcas, atributos, inventario, bundles y grupos destacados.
|
||||||
|
|
||||||
|
## Modelo
|
||||||
|
|
||||||
|
- `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.
|
||||||
|
- `Inventory` administra stock disponible, reservado y comprado.
|
||||||
|
- `StockReservation` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
|
||||||
|
- `Category` soporta jerarquía y categorías globales o propias del tenant.
|
||||||
|
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
||||||
|
- `BundleComponent` representa los componentes de un paquete.
|
||||||
|
|
||||||
|
## Servicios
|
||||||
|
|
||||||
|
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
||||||
|
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
||||||
|
- `StockReservationService`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
|
||||||
|
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
||||||
|
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
||||||
|
|
||||||
|
## Endpoints de tienda
|
||||||
|
|
||||||
|
Bajo `/tenants/{tenant:codigo}` se publican catálogo, búsqueda, categoría, detalle, alta de ítems y paginación de grupos destacados.
|
||||||
|
|
||||||
|
## Endpoints administrativos
|
||||||
|
|
||||||
|
Bajo `/v1/adminapp/tenant/featured-groups`, con `auth:sanctum` y `adminapp.tenant`, se listan, crean y actualizan grupos destacados.
|
||||||
|
|
||||||
|
## Dependencias y reglas
|
||||||
|
|
||||||
|
Usa `Attachable` para imágenes/archivos, `Tenant` para aislamiento y `Ticket`/`Event` para vigencia y fechas. `Cart` y `Purchase` consumen sus precios, variantes e inventario. Los cambios de stock deben pasar por `CatalogInventoryService` para conservar reservas y disponibilidad.
|
||||||
15
app/Domains/Catalog/routes/adminapp.php
Normal file
15
app/Domains/Catalog/routes/adminapp.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Controllers\AdminApp\OnTicketFeaturedGroupController;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::prefix('v1/adminapp/tenant')
|
||||||
|
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||||
|
->group(function (): void {
|
||||||
|
Route::get('featured-groups', [OnTicketFeaturedGroupController::class, 'index'])
|
||||||
|
->name('adminapp.featured-groups.index');
|
||||||
|
Route::post('featured-groups', [OnTicketFeaturedGroupController::class, 'store'])
|
||||||
|
->name('adminapp.featured-groups.store');
|
||||||
|
Route::put('featured-groups/{featuredGroup}', [OnTicketFeaturedGroupController::class, 'update'])
|
||||||
|
->name('adminapp.featured-groups.update');
|
||||||
|
});
|
||||||
@@ -12,5 +12,8 @@ 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']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
require __DIR__.'/adminapp.php';
|
||||||
|
|||||||
47
app/Domains/Client/Controllers/ClientController.php
Normal file
47
app/Domains/Client/Controllers/ClientController.php
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
<?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();
|
||||||
|
}
|
||||||
|
}
|
||||||
30
app/Domains/Client/Models/Client.php
Normal file
30
app/Domains/Client/Models/Client.php
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<?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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user