Compare commits
25 Commits
tenant/des
...
4aaa66dc38
| Author | SHA1 | Date | |
|---|---|---|---|
| 4aaa66dc38 | |||
| 1cd60f7021 | |||
| ca605127d0 | |||
| 00489c14d3 | |||
| 63f98b5da2 | |||
| b05314b1dd | |||
| feed3205eb | |||
| 11776f0734 | |||
| e1ad27ecf0 | |||
| 6a6d3690cc | |||
| ed4502425a | |||
| 6318a99328 | |||
| 21b70777f2 | |||
| 91af233941 | |||
| 717ee5d194 | |||
| 14d53d1e0b | |||
| 7b7efeb4cc | |||
| 60b8415c59 | |||
| f578c6e24a | |||
| 5ad61eb217 | |||
| 20dd246cd8 | |||
| 7561ba756c | |||
| b224dd8650 | |||
| 448ffb4102 | |||
| 7f01adab73 |
@@ -188,18 +188,15 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"url": {
|
"url": {
|
||||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio={{tenant_domain}}&path={{tenant_path}}",
|
"raw": "{{base_url}}/api/tenants/bootstrap/{{tenant_domain}}",
|
||||||
"host": [
|
"host": [
|
||||||
"{{base_url}}"
|
"{{base_url}}"
|
||||||
],
|
],
|
||||||
"path": [
|
"path": [
|
||||||
"api",
|
"api",
|
||||||
"tenants",
|
"tenants",
|
||||||
"bootstrap"
|
"bootstrap",
|
||||||
],
|
"{{tenant_domain}}"
|
||||||
"query": [
|
|
||||||
{"key": "dominio", "value": "{{tenant_domain}}"},
|
|
||||||
{"key": "path", "value": "{{tenant_path}}"}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -1405,11 +1402,6 @@
|
|||||||
"value": "localhost",
|
"value": "localhost",
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"key": "tenant_path",
|
|
||||||
"value": "/",
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"key": "tenant_id",
|
"key": "tenant_id",
|
||||||
"value": "1",
|
"value": "1",
|
||||||
|
|||||||
@@ -41,18 +41,15 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"url": {
|
"url": {
|
||||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
|
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
|
||||||
"host": [
|
"host": [
|
||||||
"{{base_url}}"
|
"{{base_url}}"
|
||||||
],
|
],
|
||||||
"path": [
|
"path": [
|
||||||
"api",
|
"api",
|
||||||
"tenants",
|
"tenants",
|
||||||
"bootstrap"
|
"bootstrap",
|
||||||
],
|
"acme.com"
|
||||||
"query": [
|
|
||||||
{"key": "dominio", "value": "acme.com"},
|
|
||||||
{"key": "path", "value": "/"}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,9 +6,6 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
|||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
|
||||||
use Illuminate\Support\Facades\Storage;
|
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
@@ -43,34 +40,12 @@ class Attachment extends Model
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function cropVariants(): HasMany
|
|
||||||
{
|
|
||||||
return $this->hasMany(AttachmentCrop::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function desktopCrop(): HasOne
|
|
||||||
{
|
|
||||||
return $this->hasOne(AttachmentCrop::class)
|
|
||||||
->where('variant', AttachmentCrop::DESKTOP);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function mobileCrop(): HasOne
|
|
||||||
{
|
|
||||||
return $this->hasOne(AttachmentCrop::class)
|
|
||||||
->where('variant', AttachmentCrop::MOBILE);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function cropSource(): HasOne
|
|
||||||
{
|
|
||||||
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the pre-signed temporary S3 URL for this attachment.
|
* Get the pre-signed temporary S3 URL for this attachment.
|
||||||
*/
|
*/
|
||||||
public function getTemporaryUrl(int $expiresInMinutes = 10): string
|
public function getTemporaryUrl(int $expiresInMinutes = 10): string
|
||||||
{
|
{
|
||||||
return Storage::disk('s3')->temporaryUrl(
|
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl(
|
||||||
$this->path,
|
$this->path,
|
||||||
now()->addMinutes($expiresInMinutes)
|
now()->addMinutes($expiresInMinutes)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Attachable\Models;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
|
|
||||||
#[Fillable([
|
|
||||||
'attachment_id',
|
|
||||||
'variant',
|
|
||||||
'crop_horizontal',
|
|
||||||
'crop_vertical',
|
|
||||||
'cropped_attachment_id',
|
|
||||||
])]
|
|
||||||
class AttachmentCrop extends Model
|
|
||||||
{
|
|
||||||
public const DESKTOP = 'desktop';
|
|
||||||
|
|
||||||
public const MOBILE = 'mobile';
|
|
||||||
|
|
||||||
public const VARIANTS = [self::DESKTOP, self::MOBILE];
|
|
||||||
|
|
||||||
protected function casts(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'attachment_id' => 'integer',
|
|
||||||
'crop_horizontal' => 'array',
|
|
||||||
'crop_vertical' => 'array',
|
|
||||||
'cropped_attachment_id' => 'integer',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function attachment(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Attachment::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function croppedAttachment(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Attachment::class, 'cropped_attachment_id');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,9 +5,7 @@ namespace App\Domains\Attachable\Services;
|
|||||||
use App\Domains\Attachable\Enums\AttachmentType;
|
use App\Domains\Attachable\Enums\AttachmentType;
|
||||||
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
|
||||||
use Illuminate\Http\UploadedFile;
|
use Illuminate\Http\UploadedFile;
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Symfony\Component\Mime\MimeTypes;
|
use Symfony\Component\Mime\MimeTypes;
|
||||||
@@ -15,107 +13,6 @@ use Throwable;
|
|||||||
|
|
||||||
class AttachmentService
|
class AttachmentService
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
|
||||||
*/
|
|
||||||
public function storeCroppedImageVariants(
|
|
||||||
UploadedFile|string $image,
|
|
||||||
string $path,
|
|
||||||
array $crops,
|
|
||||||
): Attachment {
|
|
||||||
$crops = $this->validateCropVariants($crops);
|
|
||||||
$storedPaths = [];
|
|
||||||
|
|
||||||
try {
|
|
||||||
return DB::transaction(function () use (
|
|
||||||
$image,
|
|
||||||
$path,
|
|
||||||
$crops,
|
|
||||||
&$storedPaths,
|
|
||||||
): Attachment {
|
|
||||||
$original = $this->store($image, $path);
|
|
||||||
$storedPaths[] = $original->path;
|
|
||||||
$contents = $this->imageContents($image);
|
|
||||||
|
|
||||||
foreach ($crops as $variant => $crop) {
|
|
||||||
$cropped = $this->storeCropVariant($contents, $path, $crop);
|
|
||||||
$storedPaths[] = $cropped->path;
|
|
||||||
$original->cropVariants()->create([
|
|
||||||
'variant' => $variant,
|
|
||||||
'crop_horizontal' => $crop['crop_horizontal'],
|
|
||||||
'crop_vertical' => $crop['crop_vertical'],
|
|
||||||
'cropped_attachment_id' => $cropped->id,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $original->load('cropVariants.croppedAttachment');
|
|
||||||
});
|
|
||||||
} catch (Throwable $throwable) {
|
|
||||||
if ($storedPaths !== []) {
|
|
||||||
Storage::disk('s3')->delete(array_values(array_unique($storedPaths)));
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $throwable;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
|
||||||
*/
|
|
||||||
public function updateImageCropVariants(
|
|
||||||
Attachment $original,
|
|
||||||
array $crops,
|
|
||||||
): Attachment {
|
|
||||||
if ($original->type !== AttachmentType::Image) {
|
|
||||||
throw new AttachmentStorageException('Only image attachments can be cropped.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$crops = $this->validateCropVariants($crops);
|
|
||||||
$contents = Storage::disk('s3')->get($original->path);
|
|
||||||
|
|
||||||
if (! is_string($contents) || $contents === '') {
|
|
||||||
throw new AttachmentStorageException('The original image could not be read from the s3 disk.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$directory = trim(str_replace('\\', '/', dirname($original->path)), './');
|
|
||||||
$directory = $directory !== '' ? $directory : 'attachments';
|
|
||||||
$previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
|
|
||||||
$storedCrops = [];
|
|
||||||
|
|
||||||
try {
|
|
||||||
foreach ($crops as $variant => $crop) {
|
|
||||||
$storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
|
|
||||||
}
|
|
||||||
|
|
||||||
DB::transaction(function () use ($original, $crops, $storedCrops): void {
|
|
||||||
foreach ($crops as $variant => $crop) {
|
|
||||||
$original->cropVariants()->updateOrCreate(
|
|
||||||
['variant' => $variant],
|
|
||||||
[
|
|
||||||
'crop_horizontal' => $crop['crop_horizontal'],
|
|
||||||
'crop_vertical' => $crop['crop_vertical'],
|
|
||||||
'cropped_attachment_id' => $storedCrops[$variant]->id,
|
|
||||||
]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (Throwable $throwable) {
|
|
||||||
foreach ($storedCrops as $storedCrop) {
|
|
||||||
$this->delete($storedCrop);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $throwable;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($previousCrops as $previousCrop) {
|
|
||||||
if ($previousCrop->croppedAttachment !== null) {
|
|
||||||
$this->delete($previousCrop->croppedAttachment);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $original->refresh()->load('cropVariants.croppedAttachment');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function store(
|
public function store(
|
||||||
UploadedFile|string $file,
|
UploadedFile|string $file,
|
||||||
string $path,
|
string $path,
|
||||||
@@ -160,30 +57,13 @@ class AttachmentService
|
|||||||
|
|
||||||
public function delete(Attachment $attachment): void
|
public function delete(Attachment $attachment): void
|
||||||
{
|
{
|
||||||
$croppedAttachments = $attachment->cropVariants()
|
$deleted = Storage::disk('s3')->delete($attachment->path);
|
||||||
->with('croppedAttachment')
|
|
||||||
->get()
|
|
||||||
->pluck('croppedAttachment')
|
|
||||||
->filter();
|
|
||||||
$paths = $croppedAttachments
|
|
||||||
->pluck('path')
|
|
||||||
->prepend($attachment->path)
|
|
||||||
->filter()
|
|
||||||
->unique()
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
$deleted = Storage::disk('s3')->delete(
|
|
||||||
count($paths) === 1 ? $paths[0] : $paths
|
|
||||||
);
|
|
||||||
|
|
||||||
if (! $deleted) {
|
if (! $deleted) {
|
||||||
throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.');
|
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
|
||||||
}
|
}
|
||||||
|
|
||||||
DB::transaction(function () use ($attachment, $croppedAttachments): void {
|
$attachment->delete();
|
||||||
$attachment->delete();
|
|
||||||
Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function copy(Attachment $source, string $path): Attachment
|
public function copy(Attachment $source, string $path): Attachment
|
||||||
@@ -227,171 +107,6 @@ class AttachmentService
|
|||||||
return trim($path, '/');
|
return trim($path, '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, array{crop_horizontal?: mixed, crop_vertical?: mixed}> $crops
|
|
||||||
* @return array<string, array{crop_horizontal: array{start_percentage: float, end_percentage: float}, crop_vertical: array{start_percentage: float, end_percentage: float}}>
|
|
||||||
*/
|
|
||||||
protected function validateCropVariants(array $crops): array
|
|
||||||
{
|
|
||||||
$validated = [];
|
|
||||||
|
|
||||||
foreach (AttachmentCrop::VARIANTS as $variant) {
|
|
||||||
$crop = $crops[$variant] ?? null;
|
|
||||||
|
|
||||||
if (! is_array($crop)) {
|
|
||||||
throw new AttachmentStorageException("The {$variant} crop is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
$horizontal = $crop['crop_horizontal'] ?? null;
|
|
||||||
$vertical = $crop['crop_vertical'] ?? null;
|
|
||||||
|
|
||||||
if (! is_array($horizontal) || ! is_array($vertical)) {
|
|
||||||
throw new AttachmentStorageException(
|
|
||||||
"The {$variant} crop must contain crop_horizontal and crop_vertical ranges."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$validated[$variant] = [
|
|
||||||
'crop_horizontal' => $this->validateCropRange($horizontal, "{$variant} horizontal"),
|
|
||||||
'crop_vertical' => $this->validateCropRange($vertical, "{$variant} vertical"),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
return $validated;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>} $crop
|
|
||||||
*/
|
|
||||||
protected function storeCropVariant(string $contents, string $path, array $crop): Attachment
|
|
||||||
{
|
|
||||||
$croppedContents = $this->cropImage(
|
|
||||||
$contents,
|
|
||||||
$crop['crop_horizontal'],
|
|
||||||
$crop['crop_vertical'],
|
|
||||||
);
|
|
||||||
|
|
||||||
return $this->store(
|
|
||||||
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
|
|
||||||
$path,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range
|
|
||||||
* @return array{start_percentage: float, end_percentage: float}
|
|
||||||
*/
|
|
||||||
protected function validateCropRange(array $range, string $axis): array
|
|
||||||
{
|
|
||||||
$start = $range['start_percentage'] ?? null;
|
|
||||||
$end = $range['end_percentage'] ?? null;
|
|
||||||
|
|
||||||
if (! is_numeric($start) || ! is_numeric($end)) {
|
|
||||||
throw new AttachmentStorageException(
|
|
||||||
"The {$axis} crop range must contain numeric start_percentage and end_percentage values."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$start = (float) $start;
|
|
||||||
$end = (float) $end;
|
|
||||||
|
|
||||||
if (! is_finite($start) || ! is_finite($end) || $start < 0 || $end > 100 || $start >= $end) {
|
|
||||||
throw new AttachmentStorageException(
|
|
||||||
"The {$axis} crop range must satisfy 0 <= start_percentage < end_percentage <= 100."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'start_percentage' => $start,
|
|
||||||
'end_percentage' => $end,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function imageContents(UploadedFile|string $image): string
|
|
||||||
{
|
|
||||||
if (is_string($image)) {
|
|
||||||
return $this->decodeBase64File($image)['data'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$contents = file_get_contents($image->getRealPath());
|
|
||||||
|
|
||||||
if (! is_string($contents) || $contents === '') {
|
|
||||||
throw new AttachmentStorageException('The image content cannot be empty.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $contents;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array{contents: string, mime_type: string}
|
|
||||||
*/
|
|
||||||
protected function cropImage(
|
|
||||||
string $contents,
|
|
||||||
array $cropHorizontal,
|
|
||||||
array $cropVertical,
|
|
||||||
): array {
|
|
||||||
$source = @imagecreatefromstring($contents);
|
|
||||||
|
|
||||||
if ($source === false) {
|
|
||||||
throw new AttachmentStorageException('The attachment must contain a valid image.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$width = imagesx($source);
|
|
||||||
$height = imagesy($source);
|
|
||||||
$x = min($width - 1, (int) floor($width * $cropHorizontal['start_percentage'] / 100));
|
|
||||||
$right = min($width, (int) ceil($width * $cropHorizontal['end_percentage'] / 100));
|
|
||||||
$y = min($height - 1, (int) floor($height * $cropVertical['start_percentage'] / 100));
|
|
||||||
$bottom = min($height, (int) ceil($height * $cropVertical['end_percentage'] / 100));
|
|
||||||
$cropped = imagecrop($source, [
|
|
||||||
'x' => $x,
|
|
||||||
'y' => $y,
|
|
||||||
'width' => $right - $x,
|
|
||||||
'height' => $bottom - $y,
|
|
||||||
]);
|
|
||||||
|
|
||||||
if ($cropped === false) {
|
|
||||||
throw new AttachmentStorageException('The image could not be cropped.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->encodeImage($cropped, $contents);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return array{contents: string, mime_type: string}
|
|
||||||
*/
|
|
||||||
protected function encodeImage(\GdImage $image, string $originalContents): array
|
|
||||||
{
|
|
||||||
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($originalContents);
|
|
||||||
$mimeType = is_string($mimeType) ? strtolower($mimeType) : '';
|
|
||||||
|
|
||||||
ob_start();
|
|
||||||
|
|
||||||
try {
|
|
||||||
$encoded = match ($mimeType) {
|
|
||||||
'image/jpeg' => imagejpeg($image, null, 90),
|
|
||||||
'image/gif' => imagegif($image),
|
|
||||||
'image/webp' => imagewebp($image, null, 90),
|
|
||||||
'image/avif' => function_exists('imageavif') && imageavif($image, null, 90),
|
|
||||||
default => imagepng($image),
|
|
||||||
};
|
|
||||||
$output = ob_get_contents();
|
|
||||||
} finally {
|
|
||||||
ob_end_clean();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! $encoded || ! is_string($output) || $output === '') {
|
|
||||||
throw new AttachmentStorageException('The cropped image could not be encoded.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'contents' => $output,
|
|
||||||
'mime_type' => match ($mimeType) {
|
|
||||||
'image/jpeg', 'image/gif', 'image/webp', 'image/avif' => $mimeType,
|
|
||||||
default => 'image/png',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
||||||
{
|
{
|
||||||
if ($file instanceof UploadedFile) {
|
if ($file instanceof UploadedFile) {
|
||||||
|
|||||||
@@ -2,12 +2,11 @@
|
|||||||
|
|
||||||
## Propósito
|
## Propósito
|
||||||
|
|
||||||
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con variantes recortadas para desktop y mobile.
|
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única.
|
||||||
|
|
||||||
## Componentes principales
|
## Componentes principales
|
||||||
|
|
||||||
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
|
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
|
||||||
- `Models/AttachmentCrop.php`: relaciona un original con su crop desktop o mobile y la imagen generada.
|
|
||||||
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
|
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
|
||||||
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
|
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
|
||||||
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
|
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
|
||||||
@@ -26,8 +25,5 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
|
|||||||
## Consideraciones
|
## Consideraciones
|
||||||
|
|
||||||
- El directorio no puede quedar vacío después de normalizarlo.
|
- El directorio no puede quedar vacío después de normalizarlo.
|
||||||
- Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`.
|
|
||||||
- `attachment_crops` guarda una fila por variante con los rangos horizontal/vertical y el attachment procesado.
|
|
||||||
- Al eliminar el original mediante el servicio también se eliminan todas sus variantes recortadas.
|
|
||||||
- La eliminación se considera fallida si S3 no confirma el borrado.
|
- La eliminación se considera fallida si S3 no confirma el borrado.
|
||||||
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.
|
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Auth\Controllers;
|
|
||||||
|
|
||||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
|
||||||
use App\Domains\Auth\Requests\AdminAppCreateResetPasswordAttemptRequest;
|
|
||||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
|
||||||
use App\Http\Controllers\Controller;
|
|
||||||
use Illuminate\Http\JsonResponse;
|
|
||||||
|
|
||||||
class CreateAdminAppResetPasswordAttemptController extends Controller
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function __invoke(AdminAppCreateResetPasswordAttemptRequest $request): JsonResponse
|
|
||||||
{
|
|
||||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
|
||||||
$request->validated('email'),
|
|
||||||
);
|
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'code' => 'auth.password_reset_requested',
|
|
||||||
'message' => __('api.auth.password_reset_requested'),
|
|
||||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
|
||||||
], 202);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Auth\Controllers;
|
|
||||||
|
|
||||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
|
||||||
use App\Domains\Auth\Requests\ScannerCreateResetPasswordAttemptRequest;
|
|
||||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
|
||||||
use App\Http\Controllers\Controller;
|
|
||||||
use Illuminate\Http\JsonResponse;
|
|
||||||
|
|
||||||
class CreateScannerResetPasswordAttemptController extends Controller
|
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function __invoke(ScannerCreateResetPasswordAttemptRequest $request): JsonResponse
|
|
||||||
{
|
|
||||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
|
||||||
$request->validated('email'),
|
|
||||||
);
|
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'code' => 'auth.password_reset_requested',
|
|
||||||
'message' => __('api.auth.password_reset_requested'),
|
|
||||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
|
||||||
], 202);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
<?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),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<?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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,12 +11,6 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|||||||
#[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';
|
||||||
|
|||||||
@@ -53,16 +53,6 @@ class User extends Authenticatable
|
|||||||
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
|
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>
|
* @return BelongsTo<Tenant, $this>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Auth\Requests;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
use Illuminate\Support\Str;
|
|
||||||
|
|
||||||
class AdminAppCreateResetPasswordAttemptRequest extends FormRequest
|
|
||||||
{
|
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function prepareForValidation(): void
|
|
||||||
{
|
|
||||||
$email = $this->input('email');
|
|
||||||
|
|
||||||
if (is_string($email)) {
|
|
||||||
$this->merge(['email' => Str::lower(trim($email))]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function rules(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'email' => ['required', 'string', 'email', 'max:255'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Auth\Requests;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
use Illuminate\Support\Str;
|
|
||||||
|
|
||||||
class ScannerCreateResetPasswordAttemptRequest extends FormRequest
|
|
||||||
{
|
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function prepareForValidation(): void
|
|
||||||
{
|
|
||||||
$email = $this->input('email');
|
|
||||||
|
|
||||||
if (is_string($email)) {
|
|
||||||
$this->merge(['email' => Str::lower(trim($email))]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function rules(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'email' => ['required', 'string', 'email', 'max:255'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Auth\Requests;
|
|
||||||
|
|
||||||
class ScannerLoginRequest extends AdminAppLoginRequest {}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
<?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),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,11 +4,8 @@ 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\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
@@ -62,33 +59,6 @@ class PasswordLoginService
|
|||||||
$userAgent,
|
$userAgent,
|
||||||
RoleCode::AdminApp,
|
RoleCode::AdminApp,
|
||||||
true,
|
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,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,10 +68,8 @@ class PasswordLoginService
|
|||||||
?string $tenantCode,
|
?string $tenantCode,
|
||||||
?string $ipAddress,
|
?string $ipAddress,
|
||||||
?string $userAgent,
|
?string $userAgent,
|
||||||
?RoleCode $requiredRole = RoleCode::User,
|
RoleCode $requiredRole = RoleCode::User,
|
||||||
bool $requiresTenant = false,
|
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();
|
||||||
@@ -116,22 +84,10 @@ class PasswordLoginService
|
|||||||
$now,
|
$now,
|
||||||
$requiredRole,
|
$requiredRole,
|
||||||
$requiresTenant,
|
$requiresTenant,
|
||||||
$requiredPermission,
|
|
||||||
$passwordResetChannel,
|
|
||||||
): array {
|
): array {
|
||||||
$user = User::query()
|
$user = User::query()
|
||||||
->where('email', $normalizedEmail)
|
->where('email', $normalizedEmail)
|
||||||
->when(
|
->where('rol_codigo', $requiredRole->value)
|
||||||
$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(
|
->when(
|
||||||
$requiresTenant,
|
$requiresTenant,
|
||||||
fn ($query) => $query->whereNotNull('tenant_codigo'),
|
fn ($query) => $query->whereNotNull('tenant_codigo'),
|
||||||
@@ -166,13 +122,8 @@ class PasswordLoginService
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($user === null || ! Hash::check($password, $user->password)) {
|
if ($user === null || ! Hash::check($password, $user->password)) {
|
||||||
if ($user !== null && $attemptTenantCode !== null) {
|
if ($user !== null) {
|
||||||
$this->registerFailure(
|
$this->registerFailure($user, $now, $tenantCode);
|
||||||
$user,
|
|
||||||
$now,
|
|
||||||
$attemptTenantCode,
|
|
||||||
$passwordResetChannel,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$outcome = $user?->locked_until?->isFuture()
|
$outcome = $user?->locked_until?->isFuture()
|
||||||
@@ -231,12 +182,8 @@ class PasswordLoginService
|
|||||||
return $result['user'];
|
return $result['user'];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function registerFailure(
|
private function registerFailure(User $user, CarbonImmutable $now, string $tenantCode): void
|
||||||
User $user,
|
{
|
||||||
CarbonImmutable $now,
|
|
||||||
string $tenantCode,
|
|
||||||
string $passwordResetChannel,
|
|
||||||
): void {
|
|
||||||
$windowMinutes = max(1, (int) config('login-security.attempt_window_minutes'));
|
$windowMinutes = max(1, (int) config('login-security.attempt_window_minutes'));
|
||||||
$maxAttempts = max(1, (int) config('login-security.max_attempts'));
|
$maxAttempts = max(1, (int) config('login-security.max_attempts'));
|
||||||
$lockMinutes = max(1, (int) config('login-security.lock_minutes'));
|
$lockMinutes = max(1, (int) config('login-security.lock_minutes'));
|
||||||
@@ -259,27 +206,11 @@ class PasswordLoginService
|
|||||||
|
|
||||||
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
|
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
|
||||||
try {
|
try {
|
||||||
if ($passwordResetChannel === PasswordResetRequested::CHANNEL_ADMINAPP) {
|
$this->resetPasswordAttemptService->createForEmail($user->email, $tenantCode, 'account_locked');
|
||||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
|
||||||
$user->email,
|
|
||||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
|
||||||
);
|
|
||||||
} elseif ($passwordResetChannel === PasswordResetRequested::CHANNEL_SCANNER) {
|
|
||||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
|
||||||
$user->email,
|
|
||||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
$this->resetPasswordAttemptService->createForEmail(
|
|
||||||
$user->email,
|
|
||||||
$tenantCode,
|
|
||||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (\Throwable $e) {
|
} catch (\Throwable $e) {
|
||||||
Log::error('Failed to trigger reset password on account lock', [
|
Log::error('Failed to trigger reset password on account lock', [
|
||||||
'user_id' => $user->id,
|
'user_id' => $user->id,
|
||||||
'exception' => $e,
|
'exception' => $e
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ namespace App\Domains\Auth\Services;
|
|||||||
|
|
||||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Authorization\Enums\RoleCode;
|
|
||||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
@@ -12,11 +11,8 @@ use Throwable;
|
|||||||
|
|
||||||
class ResetPasswordAttemptService
|
class ResetPasswordAttemptService
|
||||||
{
|
{
|
||||||
public function createForEmail(
|
public function createForEmail(string $email, string $tenantCode, string $reason = 'manual'): void
|
||||||
string $email,
|
{
|
||||||
string $tenantCode,
|
|
||||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
|
||||||
): void {
|
|
||||||
$emailFingerprint = $this->emailFingerprint($email);
|
$emailFingerprint = $this->emailFingerprint($email);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -26,12 +22,28 @@ class ResetPasswordAttemptService
|
|||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
return $this->createAttemptForUser(
|
if ($user === null) {
|
||||||
$user,
|
Log::warning('Password reset attempt was not created because the user was not found.', [
|
||||||
$reason,
|
'email_fingerprint' => $emailFingerprint,
|
||||||
$emailFingerprint,
|
]);
|
||||||
'Password reset attempt was not created because the user was not found.',
|
|
||||||
);
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$user->resetPasswordAttempts()
|
||||||
|
->whereIn('status', [
|
||||||
|
ResetPasswordAttempt::STATUS_PENDING,
|
||||||
|
ResetPasswordAttempt::STATUS_VALIDATED,
|
||||||
|
])
|
||||||
|
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
|
||||||
|
|
||||||
|
$attempt = $user->resetPasswordAttempts()->create([
|
||||||
|
'codigo' => $this->generateCode(),
|
||||||
|
'reason' => $reason,
|
||||||
|
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $attempt->getKey();
|
||||||
});
|
});
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
Log::error('Failed to create password reset attempt.', [
|
Log::error('Failed to create password reset attempt.', [
|
||||||
@@ -42,108 +54,20 @@ class ResetPasswordAttemptService
|
|||||||
throw $exception;
|
throw $exception;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->dispatchPasswordResetRequested(
|
if ($attemptId !== null) {
|
||||||
$attemptId,
|
try {
|
||||||
$tenantCode,
|
PasswordResetRequested::dispatch($attemptId, $tenantCode);
|
||||||
PasswordResetRequested::CHANNEL_STOREFRONT,
|
} catch (Throwable $exception) {
|
||||||
$emailFingerprint,
|
Log::error('Failed to dispatch password reset email.', [
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function createForAdminAppEmail(
|
|
||||||
string $email,
|
|
||||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
|
||||||
): void {
|
|
||||||
$emailFingerprint = $this->emailFingerprint($email);
|
|
||||||
|
|
||||||
try {
|
|
||||||
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
|
|
||||||
$user = User::query()
|
|
||||||
->where('email', $email)
|
|
||||||
->where('rol_codigo', RoleCode::AdminApp->value)
|
|
||||||
->whereNotNull('tenant_codigo')
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
$attemptId = $this->createAttemptForUser(
|
|
||||||
$user,
|
|
||||||
$reason,
|
|
||||||
$emailFingerprint,
|
|
||||||
'AdminApp password reset attempt was not created because the user was not found.',
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($user === null || $attemptId === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'attempt_id' => $attemptId,
|
'attempt_id' => $attemptId,
|
||||||
'tenant_code' => $user->tenant_codigo,
|
'tenant_code' => $tenantCode,
|
||||||
];
|
'email_fingerprint' => $emailFingerprint,
|
||||||
});
|
'exception' => $exception,
|
||||||
} catch (Throwable $exception) {
|
]);
|
||||||
Log::error('Failed to create AdminApp password reset attempt.', [
|
|
||||||
'email_fingerprint' => $emailFingerprint,
|
|
||||||
'exception' => $exception,
|
|
||||||
]);
|
|
||||||
|
|
||||||
throw $exception;
|
throw $exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->dispatchPasswordResetRequested(
|
|
||||||
$result['attempt_id'] ?? null,
|
|
||||||
$result['tenant_code'] ?? null,
|
|
||||||
PasswordResetRequested::CHANNEL_ADMINAPP,
|
|
||||||
$emailFingerprint,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function createForScannerEmail(
|
|
||||||
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
|
||||||
@@ -245,61 +169,6 @@ class ResetPasswordAttemptService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function createAttemptForUser(
|
|
||||||
?User $user,
|
|
||||||
string $reason,
|
|
||||||
string $emailFingerprint,
|
|
||||||
string $userNotFoundMessage,
|
|
||||||
): ?int {
|
|
||||||
if ($user === null) {
|
|
||||||
Log::warning($userNotFoundMessage, [
|
|
||||||
'email_fingerprint' => $emailFingerprint,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$user->resetPasswordAttempts()
|
|
||||||
->whereIn('status', [
|
|
||||||
ResetPasswordAttempt::STATUS_PENDING,
|
|
||||||
ResetPasswordAttempt::STATUS_VALIDATED,
|
|
||||||
])
|
|
||||||
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
|
|
||||||
|
|
||||||
$attempt = $user->resetPasswordAttempts()->create([
|
|
||||||
'codigo' => $this->generateCode(),
|
|
||||||
'reason' => $reason,
|
|
||||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
|
||||||
]);
|
|
||||||
|
|
||||||
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);
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
<?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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,19 +2,10 @@
|
|||||||
|
|
||||||
use App\Domains\Auth\Controllers\AdminAppLoginController;
|
use App\Domains\Auth\Controllers\AdminAppLoginController;
|
||||||
use App\Domains\Auth\Controllers\AdminAppMeController;
|
use App\Domains\Auth\Controllers\AdminAppMeController;
|
||||||
use App\Domains\Auth\Controllers\CreateAdminAppResetPasswordAttemptController;
|
|
||||||
use App\Domains\Auth\Controllers\ResetPasswordController;
|
|
||||||
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('v1/adminapp')->group(function (): void {
|
Route::prefix('v1/adminapp')->group(function (): void {
|
||||||
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
|
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
|
||||||
Route::post('password/reset-attempts', CreateAdminAppResetPasswordAttemptController::class)
|
|
||||||
->middleware('throttle:5,1');
|
|
||||||
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
|
|
||||||
->middleware('throttle:10,1');
|
|
||||||
Route::post('password/reset', ResetPasswordController::class)
|
|
||||||
->middleware('throttle:5,1');
|
|
||||||
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
|
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||||
->get('me', AdminAppMeController::class);
|
->get('me', AdminAppMeController::class);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,4 +25,3 @@ 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__.'/adminapp.php';
|
||||||
require __DIR__.'/scanner.php';
|
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
<?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);
|
|
||||||
});
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Authorization\Enums;
|
|
||||||
|
|
||||||
enum PermissionCode: string
|
|
||||||
{
|
|
||||||
case ScanTickets = 'tickets.escanear';
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?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'))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,10 +14,7 @@ class TenantBootstrapController extends Controller
|
|||||||
public function __invoke(TenantBootstrapRequest $request): TenantResource
|
public function __invoke(TenantBootstrapRequest $request): TenantResource
|
||||||
{
|
{
|
||||||
return TenantResource::make(
|
return TenantResource::make(
|
||||||
$this->bootstrapService->get(
|
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||||
(string) $request->validated('dominio'),
|
|
||||||
(string) $request->validated('path'),
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Bootstrap\Requests;
|
|
||||||
|
|
||||||
class ScannerBootstrapRequest extends TenantBootstrapRequest {}
|
|
||||||
@@ -10,8 +10,6 @@ class TenantBootstrapRequest extends FormRequest
|
|||||||
{
|
{
|
||||||
protected bool $hasInvalidDomain = false;
|
protected bool $hasInvalidDomain = false;
|
||||||
|
|
||||||
protected bool $hasInvalidPath = false;
|
|
||||||
|
|
||||||
public function authorize(): bool
|
public function authorize(): bool
|
||||||
{
|
{
|
||||||
return true;
|
return true;
|
||||||
@@ -19,20 +17,13 @@ class TenantBootstrapRequest extends FormRequest
|
|||||||
|
|
||||||
protected function prepareForValidation(): void
|
protected function prepareForValidation(): void
|
||||||
{
|
{
|
||||||
$rawDomain = $this->query('dominio', $this->route('dominio'));
|
$rawDomain = $this->route('dominio');
|
||||||
$rawPath = $this->query('path', '/');
|
|
||||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||||
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
|
|
||||||
|
|
||||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||||
&& $normalizedDomain === null;
|
&& $normalizedDomain === null;
|
||||||
|
|
||||||
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
|
$this->merge(['dominio' => $normalizedDomain]);
|
||||||
|
|
||||||
$this->merge([
|
|
||||||
'dominio' => $normalizedDomain,
|
|
||||||
'path' => $normalizedPath,
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
@@ -50,17 +41,6 @@ class TenantBootstrapRequest extends FormRequest
|
|||||||
'string',
|
'string',
|
||||||
'max:255',
|
'max:255',
|
||||||
],
|
],
|
||||||
'path' => [
|
|
||||||
'bail',
|
|
||||||
function (string $attribute, mixed $value, Closure $fail): void {
|
|
||||||
if ($this->hasInvalidPath) {
|
|
||||||
$fail("The {$attribute} field must contain a valid URL path.");
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'required',
|
|
||||||
'string',
|
|
||||||
'max:2048',
|
|
||||||
],
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Bootstrap\Resources;
|
|
||||||
|
|
||||||
class ScannerBootstrapResource extends AdminAppBootstrapResource {}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?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(),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,31 +5,15 @@ namespace App\Domains\Bootstrap\Services;
|
|||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Tenant\Services\TenantInformationService;
|
use App\Domains\Tenant\Services\TenantInformationService;
|
||||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
|
||||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
||||||
|
|
||||||
class TenantBootstrapService
|
class TenantBootstrapService
|
||||||
{
|
{
|
||||||
public function __construct(protected TenantInformationService $tenantInformationService) {}
|
public function __construct(protected TenantInformationService $tenantInformationService) {}
|
||||||
|
|
||||||
public function get(string $domain, string $path = '/'): Tenant
|
public function get(string $domain): Tenant
|
||||||
{
|
{
|
||||||
$candidateKeys = TenantDomainNormalizer::tenantKeyCandidates($domain, $path);
|
|
||||||
$tenantsByDomain = Tenant::query()
|
|
||||||
->whereIn('dominio', $candidateKeys)
|
|
||||||
->get()
|
|
||||||
->keyBy('dominio');
|
|
||||||
|
|
||||||
$tenant = collect($candidateKeys)
|
|
||||||
->map(fn (string $candidate): ?Tenant => $tenantsByDomain->get($candidate))
|
|
||||||
->first(fn (?Tenant $candidate): bool => $candidate !== null);
|
|
||||||
|
|
||||||
if (! $tenant instanceof Tenant) {
|
|
||||||
throw (new ModelNotFoundException)->setModel(Tenant::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->tenantInformationService->load(
|
return $this->tenantInformationService->load(
|
||||||
$tenant,
|
Tenant::query()->where('dominio', $domain)->firstOrFail(),
|
||||||
[
|
[
|
||||||
'menues' => fn ($query) => $query->whereHas(
|
'menues' => fn ($query) => $query->whereHas(
|
||||||
'roles',
|
'roles',
|
||||||
|
|||||||
@@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
|
|||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
- `GET /tenants/bootstrap?dominio={hostname}&path={path}`: bootstrap público de la tienda. Resuelve la clave de tenant más específica que sea prefijo completo del path y usa el dominio raíz como fallback.
|
- `GET /tenants/bootstrap/{dominio}`: bootstrap público de la tienda.
|
||||||
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
|
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
|
||||||
|
|
||||||
## Validación
|
## Validación
|
||||||
|
|
||||||
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
`TenantBootstrapRequest` valida el dominio recibido. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||||
|
|
||||||
## Dependencias
|
## Dependencias
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
|
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::get('tenants/bootstrap', TenantBootstrapController::class);
|
Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class)
|
||||||
|
->where('dominio', '.*');
|
||||||
|
|
||||||
require __DIR__.'/adminapp.php';
|
require __DIR__.'/adminapp.php';
|
||||||
require __DIR__.'/scanner.php';
|
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use App\Domains\Bootstrap\Controllers\ScannerBootstrapController;
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
|
|
||||||
Route::get(
|
|
||||||
'v1/scanner/bootstrap/{dominio}',
|
|
||||||
ScannerBootstrapController::class
|
|
||||||
);
|
|
||||||
@@ -54,26 +54,16 @@ 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->updateItem(
|
$this->cartService->updateItemQuantity(
|
||||||
$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' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
|
'code' => 'cart.quantity_updated',
|
||||||
'message' => $updatesVariant
|
'message' => __('api.cart.quantity_updated'),
|
||||||
? __('api.cart.item_updated')
|
|
||||||
: __('api.cart.quantity_updated'),
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -124,85 +124,27 @@ class Cart extends Model
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateItem(
|
public function updateItem(int $cartItemId, int $quantity): CartItem
|
||||||
int $cartItemId,
|
{
|
||||||
int $quantity,
|
|
||||||
?int $variantId = null,
|
|
||||||
bool $updateVariant = false,
|
|
||||||
): 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 (
|
return DB::transaction(function () use ($cartItemId, $quantity): CartItem {
|
||||||
$cartItemId,
|
|
||||||
$quantity,
|
|
||||||
$variantId,
|
|
||||||
$updateVariant,
|
|
||||||
): CartItem {
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
->where('id', $cartItemId)
|
->where('id', $cartItemId)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->firstOrFail();
|
->firstOrFail();
|
||||||
|
|
||||||
$currentSelection = $this->resolveScopedItem(
|
$selectedItem = $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');
|
|
||||||
$this->assertUserPurchaseLimit(
|
|
||||||
$nextSelection,
|
|
||||||
$otherVariantsQuantity + $quantity,
|
|
||||||
);
|
|
||||||
|
|
||||||
$inventoryService->release($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();
|
|
||||||
|
|
||||||
$inventoryService->reserve($nextSelection, $quantity);
|
|
||||||
|
|
||||||
if ($targetItem !== null) {
|
|
||||||
$targetItem->cantidad += $quantity;
|
|
||||||
$targetItem->save();
|
|
||||||
$item->delete();
|
|
||||||
|
|
||||||
return $targetItem->fresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
$item->variant_id = $variantId;
|
|
||||||
$item->cantidad = $quantity;
|
|
||||||
$item->save();
|
|
||||||
|
|
||||||
return $item->fresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
$delta = $quantity - $item->cantidad;
|
$delta = $quantity - $item->cantidad;
|
||||||
|
|
||||||
if ($delta > 0) {
|
if ($delta > 0) {
|
||||||
@@ -211,12 +153,12 @@ class Cart extends Model
|
|||||||
->whereKeyNot($item->getKey())
|
->whereKeyNot($item->getKey())
|
||||||
->sum('cantidad');
|
->sum('cantidad');
|
||||||
$this->assertUserPurchaseLimit(
|
$this->assertUserPurchaseLimit(
|
||||||
$currentSelection,
|
$selectedItem,
|
||||||
$otherVariantsQuantity + $quantity,
|
$otherVariantsQuantity + $quantity,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||||
|
|
||||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||||
@@ -229,11 +171,11 @@ class Cart extends Model
|
|||||||
$item->save();
|
$item->save();
|
||||||
|
|
||||||
if ($delta > 0) {
|
if ($delta > 0) {
|
||||||
$inventoryService->reserve($currentSelection, $delta);
|
$inventoryService->reserve($selectedItem, $delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($delta < 0) {
|
if ($delta < 0) {
|
||||||
$inventoryService->release($currentSelection, abs($delta));
|
$inventoryService->release($selectedItem, abs($delta));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $item->fresh();
|
return $item->fresh();
|
||||||
|
|||||||
@@ -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' => ['sometimes', 'nullable', 'integer'],
|
'variant_id' => ['prohibited'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
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 Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -34,15 +33,9 @@ class CartItemResource extends JsonResource
|
|||||||
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
||||||
'catalog_item_id' => $this->catalog_item_id,
|
'catalog_item_id' => $this->catalog_item_id,
|
||||||
'variant_id' => $this->variant_id,
|
'variant_id' => $this->variant_id,
|
||||||
'nombre' => $selectedItem?->getName(),
|
'product' => $selectedItem === null ? null : [
|
||||||
'imagen' => $imageUrl,
|
'nombre' => $selectedItem->getName(),
|
||||||
'variant' => $this->variant === null ? null : [
|
'imagen' => $imageUrl,
|
||||||
'id' => $this->variant->id,
|
|
||||||
'precio' => $this->formatMoney($this->variant->getPrice()),
|
|
||||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
|
||||||
? null
|
|
||||||
: $this->variant->inventory->availableStock(),
|
|
||||||
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
|
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,17 +51,11 @@ class CartService
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateItem(
|
public function updateItemQuantity(Tenant $tenant, Request $request, int $cartItemId, int $quantity): Cart
|
||||||
Tenant $tenant,
|
{
|
||||||
Request $request,
|
|
||||||
int $cartItemId,
|
|
||||||
int $quantity,
|
|
||||||
?int $variantId,
|
|
||||||
bool $updateVariant,
|
|
||||||
): Cart {
|
|
||||||
$identity = $this->requireIdentity($request);
|
$identity = $this->requireIdentity($request);
|
||||||
$cart = $this->findCartOrFail($tenant, $identity);
|
$cart = $this->findCartOrFail($tenant, $identity);
|
||||||
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
|
$cart->updateItem($cartItemId, $quantity);
|
||||||
|
|
||||||
return $this->loadCart($cart);
|
return $this->loadCart($cart);
|
||||||
}
|
}
|
||||||
@@ -82,11 +76,11 @@ class CartService
|
|||||||
$guestToken,
|
$guestToken,
|
||||||
60 * 24 * 180,
|
60 * 24 * 180,
|
||||||
'/',
|
'/',
|
||||||
config('session.domain'),
|
null,
|
||||||
(bool) config('session.secure'),
|
false,
|
||||||
true,
|
true,
|
||||||
false,
|
false,
|
||||||
config('session.same_site'),
|
'lax',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,10 +101,9 @@ class CartService
|
|||||||
return $cart->fresh()->load([
|
return $cart->fresh()->load([
|
||||||
'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.options',
|
'items.variant.definitions.itemAttribute.attribute',
|
||||||
'items.variant.eventDates',
|
'items.variant.eventDates',
|
||||||
'items.variant.eventDate',
|
'items.variant.eventDate',
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ Bajo `/tenants/{tenant:codigo}`:
|
|||||||
|
|
||||||
## Contratos
|
## Contratos
|
||||||
|
|
||||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública. Cada ítem expone `nombre`, `imagen` y `precio_unitario` en la raíz, priorizando la variante seleccionada y usando el catálogo base como respaldo. La variante seleccionada se serializa en `variant`; las variantes alternativas no forman parte de la respuesta del carrito.
|
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
|
||||||
|
|
||||||
## Dependencias y reglas
|
## Dependencias y reglas
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Controllers;
|
namespace App\Domains\Catalog\Controllers;
|
||||||
|
|
||||||
use App\Domains\Cart\Services\CartService;
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
||||||
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
|
|
||||||
use App\Domains\Catalog\Requests\CategoryPageRequest;
|
use App\Domains\Catalog\Requests\CategoryPageRequest;
|
||||||
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
||||||
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
|
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
|
||||||
@@ -16,10 +14,8 @@ use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
|||||||
use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogItemResource;
|
use App\Domains\Catalog\Resources\CatalogItemResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
||||||
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
|
|
||||||
use App\Domains\Catalog\Services\CatalogService;
|
use App\Domains\Catalog\Services\CatalogService;
|
||||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
use App\Domains\Catalog\Services\FeaturedGroupService;
|
||||||
use App\Domains\Catalog\Services\VariantSelectionService;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
@@ -114,42 +110,6 @@ class CatalogController extends Controller
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function variantOptions(
|
|
||||||
CatalogVariantOptionsRequest $request,
|
|
||||||
Tenant $tenant,
|
|
||||||
CatalogItem $catalogItem,
|
|
||||||
VariantSelectionService $variantSelectionService,
|
|
||||||
CartService $cartService,
|
|
||||||
): CatalogVariantOptionsResource {
|
|
||||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
|
||||||
|
|
||||||
$includedVariantId = null;
|
|
||||||
$cartItemId = $request->validated('cart_item_id');
|
|
||||||
$selectedValues = $request->validated('selected_values', []);
|
|
||||||
|
|
||||||
if ($cartItemId !== null) {
|
|
||||||
$cartItem = $cartService->show($tenant, $request)
|
|
||||||
->items
|
|
||||||
->firstWhere('id', (int) $cartItemId);
|
|
||||||
abort_unless($cartItem?->catalog_item_id === $catalogItem->id, 404);
|
|
||||||
$includedVariantId = $cartItem->variant_id;
|
|
||||||
|
|
||||||
if ($selectedValues === [] && $cartItem->variant !== null) {
|
|
||||||
$selectedValues = $cartItem->variant
|
|
||||||
->selectorOptions($catalogItem->itemAttributes)
|
|
||||||
->all();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return CatalogVariantOptionsResource::make(
|
|
||||||
$variantSelectionService->options(
|
|
||||||
$catalogItem,
|
|
||||||
$selectedValues,
|
|
||||||
$includedVariantId,
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function store(
|
public function store(
|
||||||
StoreCatalogItemRequest $request,
|
StoreCatalogItemRequest $request,
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
|
|||||||
@@ -2,13 +2,12 @@
|
|||||||
|
|
||||||
namespace App\Domains\Catalog\Enums;
|
namespace App\Domains\Catalog\Enums;
|
||||||
|
|
||||||
enum InventorySubject: string
|
enum EventProductType: string
|
||||||
{
|
{
|
||||||
case Product = 'product';
|
case Entry = 'entrada';
|
||||||
case Seat = 'seat';
|
case Product = 'producto';
|
||||||
case Ticket = 'ticket';
|
|
||||||
|
|
||||||
/** @return array<int, string> */
|
/** @return list<string> */
|
||||||
public static function values(): array
|
public static function values(): array
|
||||||
{
|
{
|
||||||
return array_column(self::cases(), 'value');
|
return array_column(self::cases(), 'value');
|
||||||
@@ -8,7 +8,6 @@ enum GroupLayout: string
|
|||||||
case Simple = 'simple';
|
case Simple = 'simple';
|
||||||
case SimpleVertical = 'simple_vertical';
|
case SimpleVertical = 'simple_vertical';
|
||||||
case Carousel = 'carousel';
|
case Carousel = 'carousel';
|
||||||
case Single = 'single';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return list<string>
|
* @return list<string>
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ enum ProductLayout: string
|
|||||||
case Row = 'row';
|
case Row = 'row';
|
||||||
case ColumnWithImage = 'column_with_image';
|
case ColumnWithImage = 'column_with_image';
|
||||||
case ColumnWithCart = 'column_with_cart';
|
case ColumnWithCart = 'column_with_cart';
|
||||||
case TicketSelector = 'ticket_selector';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return list<string>
|
* @return list<string>
|
||||||
|
|||||||
@@ -4,23 +4,22 @@ 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\EventProductType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Enums\InventorySubject;
|
|
||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
|
use App\Domains\Ticket\Models\ValidityTime;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
use Illuminate\Database\Eloquent\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',
|
||||||
|
'event_product_type',
|
||||||
'category_id',
|
'category_id',
|
||||||
'brand_id',
|
'brand_id',
|
||||||
'inventory_id',
|
'inventory_id',
|
||||||
@@ -30,13 +29,13 @@ use Illuminate\Support\Collection;
|
|||||||
'descripcion',
|
'descripcion',
|
||||||
'precio',
|
'precio',
|
||||||
'inventory_policy',
|
'inventory_policy',
|
||||||
'inventory_subject',
|
|
||||||
'max_units_per_user',
|
'max_units_per_user',
|
||||||
'has_tickets',
|
'has_tickets',
|
||||||
|
'validity_time_id',
|
||||||
])]
|
])]
|
||||||
class CatalogItem extends Model
|
class CatalogItem extends Model
|
||||||
{
|
{
|
||||||
use HasFactory, SoftDeletes;
|
use HasFactory;
|
||||||
|
|
||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
|
|
||||||
@@ -45,7 +44,6 @@ 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,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -55,12 +53,13 @@ class CatalogItem extends Model
|
|||||||
'category_id' => 'integer',
|
'category_id' => 'integer',
|
||||||
'brand_id' => 'integer',
|
'brand_id' => 'integer',
|
||||||
'inventory_id' => 'integer',
|
'inventory_id' => 'integer',
|
||||||
|
'event_product_type' => EventProductType::class,
|
||||||
'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',
|
'max_units_per_user' => 'integer',
|
||||||
'has_tickets' => 'boolean',
|
'has_tickets' => 'boolean',
|
||||||
|
'validity_time_id' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,6 +111,12 @@ class CatalogItem extends Model
|
|||||||
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<ValidityTime, $this> */
|
||||||
|
public function validityTime(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(ValidityTime::class);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return BelongsToMany<Attribute, $this> */
|
/** @return BelongsToMany<Attribute, $this> */
|
||||||
public function attributes(): BelongsToMany
|
public function attributes(): BelongsToMany
|
||||||
{
|
{
|
||||||
@@ -133,12 +138,6 @@ class CatalogItem extends Model
|
|||||||
|
|
||||||
/** @return BelongsToMany<Attachment, $this> */
|
/** @return BelongsToMany<Attachment, $this> */
|
||||||
public function attachments(): BelongsToMany
|
public function attachments(): BelongsToMany
|
||||||
{
|
|
||||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return BelongsToMany<Attachment, $this> */
|
|
||||||
public function allAttachments(): BelongsToMany
|
|
||||||
{
|
{
|
||||||
return $this->belongsToMany(
|
return $this->belongsToMany(
|
||||||
Attachment::class,
|
Attachment::class,
|
||||||
@@ -146,7 +145,7 @@ class CatalogItem extends Model
|
|||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
'attachment_id'
|
'attachment_id'
|
||||||
)
|
)
|
||||||
->withPivot(['orden', 'is_enabled'])
|
->withPivot('orden')
|
||||||
->wherePivotNull('variant_id')
|
->wherePivotNull('variant_id')
|
||||||
->orderByPivot('orden');
|
->orderByPivot('orden');
|
||||||
}
|
}
|
||||||
@@ -171,31 +170,6 @@ 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;
|
||||||
@@ -206,11 +180,6 @@ class CatalogItem extends Model
|
|||||||
return $this->nombre;
|
return $this->nombre;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getSelectionLabel(): string
|
|
||||||
{
|
|
||||||
return $this->getName();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getDescription(): ?string
|
public function getDescription(): ?string
|
||||||
{
|
{
|
||||||
return $this->descripcion;
|
return $this->descripcion;
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
'attribute_id',
|
'attribute_id',
|
||||||
'allow_multi_select',
|
'allow_multi_select',
|
||||||
'sort_order',
|
|
||||||
'show_in_selector',
|
|
||||||
])]
|
])]
|
||||||
class ItemAttribute extends Model
|
class ItemAttribute extends Model
|
||||||
{
|
{
|
||||||
@@ -21,18 +19,12 @@ class ItemAttribute extends Model
|
|||||||
|
|
||||||
protected $table = 'item_attributes';
|
protected $table = 'item_attributes';
|
||||||
|
|
||||||
protected $attributes = [
|
|
||||||
'show_in_selector' => true,
|
|
||||||
];
|
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'catalog_item_id' => 'integer',
|
'catalog_item_id' => 'integer',
|
||||||
'attribute_id' => 'integer',
|
'attribute_id' => 'integer',
|
||||||
'allow_multi_select' => 'boolean',
|
'allow_multi_select' => 'boolean',
|
||||||
'sort_order' => 'integer',
|
|
||||||
'show_in_selector' => 'boolean',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\Lang;
|
|
||||||
use Illuminate\Support\Str;
|
|
||||||
|
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'catalog_item_id',
|
'catalog_item_id',
|
||||||
@@ -25,7 +22,7 @@ use Illuminate\Support\Str;
|
|||||||
])]
|
])]
|
||||||
class Variant extends Model
|
class Variant extends Model
|
||||||
{
|
{
|
||||||
use HasFactory, SoftDeletes;
|
use HasFactory;
|
||||||
|
|
||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
|
|
||||||
@@ -44,7 +41,7 @@ class Variant extends Model
|
|||||||
/** @return BelongsTo<CatalogItem, $this> */
|
/** @return BelongsTo<CatalogItem, $this> */
|
||||||
public function catalogItem(): BelongsTo
|
public function catalogItem(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(CatalogItem::class)->withTrashed();
|
return $this->belongsTo(CatalogItem::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<EventDate, $this> */
|
/** @return BelongsTo<EventDate, $this> */
|
||||||
@@ -84,12 +81,6 @@ class Variant extends Model
|
|||||||
|
|
||||||
/** @return BelongsToMany<Attachment, $this> */
|
/** @return BelongsToMany<Attachment, $this> */
|
||||||
public function attachments(): BelongsToMany
|
public function attachments(): BelongsToMany
|
||||||
{
|
|
||||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return BelongsToMany<Attachment, $this> */
|
|
||||||
public function allAttachments(): BelongsToMany
|
|
||||||
{
|
{
|
||||||
$relation = $this->belongsToMany(
|
$relation = $this->belongsToMany(
|
||||||
Attachment::class,
|
Attachment::class,
|
||||||
@@ -97,7 +88,7 @@ class Variant extends Model
|
|||||||
'variant_id',
|
'variant_id',
|
||||||
'attachment_id'
|
'attachment_id'
|
||||||
)
|
)
|
||||||
->withPivot(['orden', 'is_enabled'])
|
->withPivot('orden')
|
||||||
->orderByPivot('orden');
|
->orderByPivot('orden');
|
||||||
|
|
||||||
if ($this->catalog_item_id !== null) {
|
if ($this->catalog_item_id !== null) {
|
||||||
@@ -122,42 +113,6 @@ class Variant extends Model
|
|||||||
return $this->catalogItem->nombre;
|
return $this->catalogItem->nombre;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getSelectionLabel(): string
|
|
||||||
{
|
|
||||||
$this->loadMissing([
|
|
||||||
'catalogItem.itemAttributes.attribute.options',
|
|
||||||
'definitions.itemAttribute.attribute.options',
|
|
||||||
'eventDates',
|
|
||||||
'eventDate',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$itemAttributes = $this->catalogItem->itemAttributes;
|
|
||||||
|
|
||||||
$label = $this->selectionOptions($itemAttributes)
|
|
||||||
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
|
||||||
$itemAttribute = $itemAttributes->first(
|
|
||||||
fn (ItemAttribute $candidate): bool => $candidate->attribute?->codigo === $attributeCode,
|
|
||||||
);
|
|
||||||
$translationKey = "api.catalog.attribute_labels.{$attributeCode}";
|
|
||||||
$attributeName = Lang::has($translationKey)
|
|
||||||
? __($translationKey)
|
|
||||||
: ($itemAttribute?->attribute?->nombre ?? Str::headline($attributeCode));
|
|
||||||
$selectedOptions = array_is_list($option) ? $option : [$option];
|
|
||||||
$selectedLabels = collect($selectedOptions)
|
|
||||||
->pluck('label')
|
|
||||||
->filter()
|
|
||||||
->implode(', ');
|
|
||||||
|
|
||||||
return $selectedLabels === ''
|
|
||||||
? null
|
|
||||||
: "{$attributeName} {$selectedLabels}";
|
|
||||||
})
|
|
||||||
->filter()
|
|
||||||
->implode(' · ');
|
|
||||||
|
|
||||||
return $label !== '' ? $label : $this->getName();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return Collection<string, string|array<int, string>> */
|
/** @return Collection<string, string|array<int, string>> */
|
||||||
public function selectionValues(): Collection
|
public function selectionValues(): Collection
|
||||||
{
|
{
|
||||||
@@ -194,106 +149,6 @@ class Variant extends Model
|
|||||||
return $values;
|
return $values;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
|
||||||
*/
|
|
||||||
public function selectionOptions(?Collection $itemAttributes = null): Collection
|
|
||||||
{
|
|
||||||
$options = $this->definitions
|
|
||||||
->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> */
|
/** @return Collection<int, EventDate> */
|
||||||
public function selectedEventDates(): Collection
|
public function selectedEventDates(): Collection
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Requests;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
|
|
||||||
class CatalogVariantOptionsRequest extends FormRequest
|
|
||||||
{
|
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, list<string>> */
|
|
||||||
public function rules(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'selected_values' => ['sometimes', 'array'],
|
|
||||||
'selected_values.*' => ['nullable'],
|
|
||||||
'cart_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
namespace App\Domains\Catalog\Requests;
|
namespace App\Domains\Catalog\Requests;
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||||
|
use App\Domains\Catalog\Enums\EventProductType;
|
||||||
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;
|
||||||
@@ -26,6 +26,11 @@ class StoreCatalogItemRequest extends FormRequest
|
|||||||
return [
|
return [
|
||||||
'tenant_code' => ['prohibited'],
|
'tenant_code' => ['prohibited'],
|
||||||
'type' => ['sometimes', Rule::enum(CatalogItemType::class)],
|
'type' => ['sometimes', Rule::enum(CatalogItemType::class)],
|
||||||
|
'event_product_type' => [
|
||||||
|
'sometimes',
|
||||||
|
'nullable',
|
||||||
|
Rule::enum(EventProductType::class),
|
||||||
|
],
|
||||||
'category_id' => [
|
'category_id' => [
|
||||||
'sometimes',
|
'sometimes',
|
||||||
'nullable',
|
'nullable',
|
||||||
@@ -54,9 +59,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'],
|
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||||
|
'validity_time_id' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'integer', Rule::exists('validity_times', 'id')],
|
||||||
'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
|
'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
|
||||||
'inventory_id' => ['prohibited'],
|
'inventory_id' => ['prohibited'],
|
||||||
'reserved_stock' => ['prohibited'],
|
'reserved_stock' => ['prohibited'],
|
||||||
@@ -79,15 +84,6 @@ class StoreCatalogItemRequest extends FormRequest
|
|||||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
'hidden_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
|
||||||
'hidden_attribute_codes.*' => [
|
|
||||||
'required',
|
|
||||||
'string',
|
|
||||||
'distinct',
|
|
||||||
Rule::exists('attribute', 'codigo')->where(
|
|
||||||
fn ($query) => $query->where('tenant_codigo', $tenantCode)
|
|
||||||
),
|
|
||||||
],
|
|
||||||
'images' => ['sometimes', 'array'],
|
'images' => ['sometimes', 'array'],
|
||||||
'images.*' => ['required', new ImageOrBase64Rule],
|
'images.*' => ['required', new ImageOrBase64Rule],
|
||||||
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use App\Domains\Catalog\Enums\ProductLayout;
|
|||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
|
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -24,18 +25,16 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
return $this->columnWithImageData($catalogItem);
|
return $this->columnWithImageData($catalogItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
return [
|
||||||
return $this->ticketSelectorData($catalogItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
$data = [
|
|
||||||
'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,
|
||||||
|
'validity_time_id' => $catalogItem->validity_time_id,
|
||||||
|
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||||
'stock_tecnico' => $catalogItem->availableStock(),
|
'stock_tecnico' => $catalogItem->availableStock(),
|
||||||
'variants' => $catalogItem->visibleVariants()
|
'variants' => $catalogItem->variants
|
||||||
->map(fn (Variant $variant): array => [
|
->map(fn (Variant $variant): array => [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
'event_date_id' => $variant->event_date_id,
|
'event_date_id' => $variant->event_date_id,
|
||||||
@@ -47,46 +46,28 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
? null
|
? null
|
||||||
: $variant->inventory->availableStock(),
|
: $variant->inventory->availableStock(),
|
||||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
'values' => $variant->selectionValues(),
|
||||||
])
|
])
|
||||||
->values(),
|
->values(),
|
||||||
];
|
];
|
||||||
|
|
||||||
return $data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
private function ticketSelectorData(CatalogItem $catalogItem): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'id' => $catalogItem->id,
|
|
||||||
'type' => $catalogItem->type->value,
|
|
||||||
'nombre' => $catalogItem->nombre,
|
|
||||||
'descripcion' => $catalogItem->descripcion,
|
|
||||||
'precio' => $catalogItem->precio,
|
|
||||||
'image' => $this->firstImageUrl($catalogItem),
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||||
{
|
|
||||||
return [
|
|
||||||
'id' => $catalogItem->id,
|
|
||||||
'type' => $catalogItem->type->value,
|
|
||||||
'nombre' => $catalogItem->nombre,
|
|
||||||
'precio' => $catalogItem->precio,
|
|
||||||
'image' => $this->firstImageUrl($catalogItem),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
|
||||||
{
|
{
|
||||||
$attachment = $catalogItem->attachments->first()
|
$attachment = $catalogItem->attachments->first()
|
||||||
?? $catalogItem->variants
|
?? $catalogItem->variants
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
return $attachment?->getTemporaryUrl(1440);
|
return [
|
||||||
|
'id' => $catalogItem->id,
|
||||||
|
'type' => $catalogItem->type->value,
|
||||||
|
'nombre' => $catalogItem->nombre,
|
||||||
|
'precio' => $catalogItem->precio,
|
||||||
|
'validity_time_id' => $catalogItem->validity_time_id,
|
||||||
|
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||||
|
'image' => $attachment?->getTemporaryUrl(1440),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'type' => $this->type->value,
|
'type' => $this->type->value,
|
||||||
|
'event_product_type' => $this->event_product_type?->value,
|
||||||
'category_id' => $this->category_id,
|
'category_id' => $this->category_id,
|
||||||
'brand_id' => $this->brand_id,
|
'brand_id' => $this->brand_id,
|
||||||
'slug' => $this->slug,
|
'slug' => $this->slug,
|
||||||
@@ -33,9 +34,12 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
'category' => $this->category?->nombre,
|
'category' => $this->category?->nombre,
|
||||||
'brand' => $this->brand?->nombre,
|
'brand' => $this->brand?->nombre,
|
||||||
'inventory_policy' => $this->inventory_policy?->value,
|
'inventory_policy' => $this->inventory_policy?->value,
|
||||||
'inventory_subject' => $this->inventory_subject->value,
|
|
||||||
'max_units_per_user' => $this->max_units_per_user,
|
'max_units_per_user' => $this->max_units_per_user,
|
||||||
'has_tickets' => $this->has_tickets,
|
'has_tickets' => $this->has_tickets,
|
||||||
|
'validity_time_id' => $this->validity_time_id,
|
||||||
|
'validity_time' => $this->validityTime === null
|
||||||
|
? null
|
||||||
|
: ValidityTimeResource::make($this->validityTime),
|
||||||
'attributes' => $this->attributesData(),
|
'attributes' => $this->attributesData(),
|
||||||
'stock_tecnico' => $this->when(
|
'stock_tecnico' => $this->when(
|
||||||
$selectedVariant === null,
|
$selectedVariant === null,
|
||||||
@@ -45,7 +49,7 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
$selectedVariant === null,
|
$selectedVariant === null,
|
||||||
fn () => $this->imageUrls($this->attachments),
|
fn () => $this->imageUrls($this->attachments),
|
||||||
),
|
),
|
||||||
'variants' => $this->visibleVariants()
|
'variants' => $this->variants
|
||||||
->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(
|
||||||
@@ -83,8 +87,6 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
'id' => $attribute->id,
|
'id' => $attribute->id,
|
||||||
'codigo' => $attribute->codigo,
|
'codigo' => $attribute->codigo,
|
||||||
'nombre' => $attribute->nombre,
|
'nombre' => $attribute->nombre,
|
||||||
'sort_order' => $itemAttribute->sort_order,
|
|
||||||
'show_in_selector' => $itemAttribute->show_in_selector,
|
|
||||||
'is_required' => $attribute->is_required,
|
'is_required' => $attribute->is_required,
|
||||||
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
||||||
'metadata_schema' => $attribute->metadata_schema,
|
'metadata_schema' => $attribute->metadata_schema,
|
||||||
@@ -102,10 +104,12 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
->map(fn ($eventDate, int $index): array => [
|
->map(fn ($eventDate, int $index): array => [
|
||||||
'id' => $eventDate->id,
|
'id' => $eventDate->id,
|
||||||
'value' => (string) $eventDate->id,
|
'value' => (string) $eventDate->id,
|
||||||
'label' => $eventDate->date->format('d/m/Y'),
|
'label' => $eventDate->date->format('d/m/Y').' · '
|
||||||
|
.substr($eventDate->time_start, 0, 5).' a '
|
||||||
|
.substr($eventDate->time_end, 0, 5),
|
||||||
'sort_order' => $index,
|
'sort_order' => $index,
|
||||||
'validity_time_id' => $eventDate->validity_time_id,
|
'validity_time_id' => null,
|
||||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
'validity_time' => null,
|
||||||
'metadata' => [
|
'metadata' => [
|
||||||
'date' => $eventDate->date->format('Y-m-d'),
|
'date' => $eventDate->date->format('Y-m-d'),
|
||||||
'time_start' => $eventDate->time_start,
|
'time_start' => $eventDate->time_start,
|
||||||
@@ -144,10 +148,7 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
private function attributesData(): Collection
|
private function attributesData(): Collection
|
||||||
{
|
{
|
||||||
return $this->itemAttributes
|
return $this->itemAttributes
|
||||||
->sort(function (ItemAttribute $left, ItemAttribute $right): int {
|
->sortBy(fn (ItemAttribute $itemAttribute): int => $itemAttribute->attribute->type === FieldType::EventDate ? 0 : 1)
|
||||||
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))
|
->map(fn (ItemAttribute $itemAttribute): array => $this->attributeData($itemAttribute))
|
||||||
->values();
|
->values();
|
||||||
}
|
}
|
||||||
@@ -155,7 +156,7 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
/** @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);
|
$values = $variant->selectionValues();
|
||||||
$eventDates = $variant->selectedEventDates();
|
$eventDates = $variant->selectedEventDates();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Domains\Catalog\Resources;
|
namespace App\Domains\Catalog\Resources;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ class CatalogItemResource extends JsonResource
|
|||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'type' => $this->type->value,
|
'type' => $this->type->value,
|
||||||
|
'event_product_type' => $this->event_product_type?->value,
|
||||||
'category_id' => $this->category_id,
|
'category_id' => $this->category_id,
|
||||||
'brand_id' => $this->brand_id,
|
'brand_id' => $this->brand_id,
|
||||||
'slug' => $this->slug,
|
'slug' => $this->slug,
|
||||||
@@ -22,9 +24,13 @@ class CatalogItemResource extends JsonResource
|
|||||||
'descripcion' => $this->descripcion,
|
'descripcion' => $this->descripcion,
|
||||||
'precio' => $this->precio,
|
'precio' => $this->precio,
|
||||||
'inventory_policy' => $this->inventory_policy?->value,
|
'inventory_policy' => $this->inventory_policy?->value,
|
||||||
'inventory_subject' => $this->inventory_subject->value,
|
|
||||||
'max_units_per_user' => $this->max_units_per_user,
|
'max_units_per_user' => $this->max_units_per_user,
|
||||||
'has_tickets' => $this->has_tickets,
|
'has_tickets' => $this->has_tickets,
|
||||||
|
'validity_time_id' => $this->validity_time_id,
|
||||||
|
'validity_time' => $this->whenLoaded(
|
||||||
|
'validityTime',
|
||||||
|
fn () => ValidityTimeResource::make($this->validityTime),
|
||||||
|
),
|
||||||
'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
|
'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
|
||||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||||
@@ -39,7 +45,7 @@ class CatalogItemResource extends JsonResource
|
|||||||
'descripcion' => $variant->getDescription(),
|
'descripcion' => $variant->getDescription(),
|
||||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
'real_stock' => $variant->inventory?->real_stock,
|
'real_stock' => $variant->inventory?->real_stock,
|
||||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
'values' => $variant->selectionValues(),
|
||||||
'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\Ticket\Resources\ValidityTimeResource;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -25,9 +26,11 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
'nombre' => $this->nombre,
|
'nombre' => $this->nombre,
|
||||||
'descripcion' => $this->descripcion,
|
'descripcion' => $this->descripcion,
|
||||||
'precio' => $this->precio,
|
'precio' => $this->precio,
|
||||||
|
'validity_time_id' => $this->validity_time_id,
|
||||||
|
'validity_time' => ValidityTimeResource::make($this->validityTime),
|
||||||
'image' => $attachment?->getTemporaryUrl(1440),
|
'image' => $attachment?->getTemporaryUrl(1440),
|
||||||
'stock_tecnico' => $this->availableStock(),
|
'stock_tecnico' => $this->availableStock(),
|
||||||
'variants' => $this->visibleVariants()
|
'variants' => $this->variants
|
||||||
->map(fn (Variant $variant): array => [
|
->map(fn (Variant $variant): array => [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
'event_date_id' => $variant->event_date_id,
|
'event_date_id' => $variant->event_date_id,
|
||||||
@@ -39,7 +42,7 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
? null
|
? null
|
||||||
: $variant->inventory?->availableStock(),
|
: $variant->inventory?->availableStock(),
|
||||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
'values' => $variant->selectionValues(),
|
||||||
])
|
])
|
||||||
->values(),
|
->values(),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Resources;
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
|
||||||
|
|
||||||
class CatalogVariantOptionsResource extends JsonResource
|
|
||||||
{
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function toArray(Request $request): array
|
|
||||||
{
|
|
||||||
return $this->resource;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Catalog\Services;
|
|||||||
use App\Domains\Attachable\Models\Attachment;
|
use App\Domains\Attachable\Models\Attachment;
|
||||||
use App\Domains\Attachable\Services\AttachmentService;
|
use App\Domains\Attachable\Services\AttachmentService;
|
||||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||||
|
use App\Domains\Catalog\Enums\EventProductType;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
@@ -37,7 +38,6 @@ class CatalogService
|
|||||||
$images = $data['images'] ?? [];
|
$images = $data['images'] ?? [];
|
||||||
$attributeCodes = $data['attribute_codes'] ?? [];
|
$attributeCodes = $data['attribute_codes'] ?? [];
|
||||||
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
|
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
|
||||||
$hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? [];
|
|
||||||
$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);
|
||||||
@@ -65,14 +65,7 @@ class CatalogService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (array_diff($hiddenAttributeCodes, $attributeCodes) !== []) {
|
$this->validateEventProductType($data);
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'hidden_attribute_codes' => [
|
|
||||||
__('api.catalog.hidden_attribute_not_on_item'),
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->validateUniqueVariantCombinations($variants, $attributeCodes);
|
$this->validateUniqueVariantCombinations($variants, $attributeCodes);
|
||||||
|
|
||||||
if ($type === CatalogItemType::Bundle) {
|
if ($type === CatalogItemType::Bundle) {
|
||||||
@@ -97,7 +90,6 @@ class CatalogService
|
|||||||
$data['images'],
|
$data['images'],
|
||||||
$data['attribute_codes'],
|
$data['attribute_codes'],
|
||||||
$data['multi_select_attribute_codes'],
|
$data['multi_select_attribute_codes'],
|
||||||
$data['hidden_attribute_codes'],
|
|
||||||
$data['components'],
|
$data['components'],
|
||||||
$data['real_stock'],
|
$data['real_stock'],
|
||||||
$data['reserved_stock'],
|
$data['reserved_stock'],
|
||||||
@@ -119,12 +111,7 @@ class CatalogService
|
|||||||
|
|
||||||
$catalogItem = CatalogItem::query()->create($data);
|
$catalogItem = CatalogItem::query()->create($data);
|
||||||
$itemAttributes = $type === CatalogItemType::Standard
|
$itemAttributes = $type === CatalogItemType::Standard
|
||||||
? $this->createItemAttributes(
|
? $this->createItemAttributes($catalogItem, $attributeCodes, $multiSelectAttributeCodes)
|
||||||
$catalogItem,
|
|
||||||
$attributeCodes,
|
|
||||||
$multiSelectAttributeCodes,
|
|
||||||
$hiddenAttributeCodes,
|
|
||||||
)
|
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
if ($type === CatalogItemType::Bundle) {
|
if ($type === CatalogItemType::Bundle) {
|
||||||
@@ -160,12 +147,13 @@ class CatalogService
|
|||||||
'inventory',
|
'inventory',
|
||||||
'category',
|
'category',
|
||||||
'brand',
|
'brand',
|
||||||
|
'validityTime',
|
||||||
'itemAttributes.attribute',
|
'itemAttributes.attribute',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
'variants.eventDates',
|
'variants.eventDates',
|
||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
]);
|
]);
|
||||||
@@ -179,24 +167,24 @@ class CatalogService
|
|||||||
'inventory',
|
'inventory',
|
||||||
'category',
|
'category',
|
||||||
'brand',
|
'brand',
|
||||||
|
'validityTime',
|
||||||
'itemAttributes.attribute.options.validityTime',
|
'itemAttributes.attribute.options.validityTime',
|
||||||
'itemAttributes.attribute.eventDates.validityTime',
|
'itemAttributes.attribute.eventDates',
|
||||||
'variants' => fn ($query) => $query->orderBy('id'),
|
'variants' => fn ($query) => $query->orderBy('id'),
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
'variants.eventDates',
|
'variants.eventDates',
|
||||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
'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
|
||||||
? $visibleVariants->first()
|
? $catalogItem->variants->first()
|
||||||
: $visibleVariants->firstWhere('id', $variantId);
|
: $catalogItem->variants->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.');
|
||||||
@@ -220,7 +208,6 @@ 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])
|
||||||
@@ -239,12 +226,12 @@ class CatalogService
|
|||||||
->with([
|
->with([
|
||||||
'attachments',
|
'attachments',
|
||||||
'inventory',
|
'inventory',
|
||||||
'itemAttributes.attribute',
|
'validityTime',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
'variants.eventDates',
|
'variants.eventDates',
|
||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
])
|
])
|
||||||
@@ -270,16 +257,15 @@ 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',
|
'validityTime',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
'variants.eventDates',
|
'variants.eventDates',
|
||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
])
|
])
|
||||||
@@ -290,28 +276,32 @@ class CatalogService
|
|||||||
public function delete(CatalogItem $catalogItem): void
|
public function delete(CatalogItem $catalogItem): void
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($catalogItem): void {
|
DB::transaction(function () use ($catalogItem): void {
|
||||||
$catalogItem->variants()->delete();
|
$catalogItem->load([
|
||||||
$catalogItem->delete();
|
'attachments',
|
||||||
});
|
'variants.attachments',
|
||||||
}
|
]);
|
||||||
|
|
||||||
public function deleteVariant(Variant $variant): void
|
$attachments = $catalogItem->attachments
|
||||||
{
|
->merge($catalogItem->variants->flatMap->attachments)
|
||||||
DB::transaction(function () use ($variant): void {
|
->unique('id');
|
||||||
$variant = Variant::query()
|
$inventoryIds = collect([$catalogItem->inventory_id])
|
||||||
->lockForUpdate()
|
->merge($catalogItem->variants->pluck('inventory_id'))
|
||||||
->findOrFail($variant->getKey());
|
->filter()
|
||||||
$catalogItem = CatalogItem::query()
|
->unique();
|
||||||
->lockForUpdate()
|
|
||||||
->findOrFail($variant->catalog_item_id);
|
|
||||||
$variant->delete();
|
|
||||||
|
|
||||||
if (! $catalogItem->variants()->exists()) {
|
$catalogItem->attachments()->detach();
|
||||||
$this->delete($catalogItem);
|
foreach ($catalogItem->variants as $variant) {
|
||||||
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) {
|
$variant->attachments()->detach();
|
||||||
$catalogItem->update(['precio' => $minimumPrice]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$catalogItem->delete();
|
||||||
|
Inventory::query()->whereKey($inventoryIds)->delete();
|
||||||
|
|
||||||
|
foreach ($attachments as $attachment) {
|
||||||
|
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||||
|
$this->attachmentService->delete($attachment);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -416,6 +406,7 @@ class CatalogService
|
|||||||
'attribute_codes',
|
'attribute_codes',
|
||||||
'variants',
|
'variants',
|
||||||
'has_tickets',
|
'has_tickets',
|
||||||
|
'validity_time_id',
|
||||||
] as $field) {
|
] as $field) {
|
||||||
if (array_key_exists($field, $data)) {
|
if (array_key_exists($field, $data)) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
@@ -460,14 +451,12 @@ class CatalogService
|
|||||||
/**
|
/**
|
||||||
* @param array<int, string> $attributeCodes
|
* @param array<int, string> $attributeCodes
|
||||||
* @param array<int, string> $multiSelectAttributeCodes
|
* @param array<int, string> $multiSelectAttributeCodes
|
||||||
* @param array<int, string> $hiddenAttributeCodes
|
|
||||||
* @return array<string, ItemAttribute>
|
* @return array<string, ItemAttribute>
|
||||||
*/
|
*/
|
||||||
private function createItemAttributes(
|
private function createItemAttributes(
|
||||||
CatalogItem $catalogItem,
|
CatalogItem $catalogItem,
|
||||||
array $attributeCodes,
|
array $attributeCodes,
|
||||||
array $multiSelectAttributeCodes = [],
|
array $multiSelectAttributeCodes = [],
|
||||||
array $hiddenAttributeCodes = [],
|
|
||||||
): array {
|
): array {
|
||||||
$itemAttributes = [];
|
$itemAttributes = [];
|
||||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||||
@@ -491,7 +480,6 @@ class CatalogService
|
|||||||
$itemAttribute = $catalogItem->itemAttributes()->create([
|
$itemAttribute = $catalogItem->itemAttributes()->create([
|
||||||
'attribute_id' => $attribute->id,
|
'attribute_id' => $attribute->id,
|
||||||
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
|
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
|
||||||
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$itemAttributes[$attributeCode] = $itemAttribute;
|
$itemAttributes[$attributeCode] = $itemAttribute;
|
||||||
@@ -598,6 +586,22 @@ class CatalogService
|
|||||||
return $variant;
|
return $variant;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed> $data */
|
||||||
|
private function validateEventProductType(array $data): void
|
||||||
|
{
|
||||||
|
$eventProductType = $data['event_product_type'] ?? null;
|
||||||
|
|
||||||
|
if ($eventProductType === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($eventProductType, EventProductType::values(), true)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'event_product_type' => [__('api.catalog.invalid_event_product_type')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<int, array<string, mixed>> $variants
|
* @param array<int, array<string, mixed>> $variants
|
||||||
* @param array<int, string> $attributeCodes
|
* @param array<int, string> $attributeCodes
|
||||||
@@ -688,6 +692,16 @@ class CatalogService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$validityTimeIds = $resolvedOptions
|
||||||
|
->pluck('validity_time_id')
|
||||||
|
->filter()
|
||||||
|
->unique();
|
||||||
|
if ($validityTimeIds->count() > 1) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
$validationKey => [__('api.catalog.incompatible_validity_windows')],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
return $resolvedOptions->pluck('value')->all();
|
return $resolvedOptions->pluck('value')->all();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,13 +18,7 @@ class FeaturedGroupService
|
|||||||
public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
||||||
{
|
{
|
||||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||||
$query = $this->itemsQuery($featuredGroup);
|
$items = $this->itemsQuery($featuredGroup)->get();
|
||||||
|
|
||||||
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
|
||||||
$query->limit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
$items = $query->get();
|
|
||||||
$this->attachGroup($items, $featuredGroup);
|
$this->attachGroup($items, $featuredGroup);
|
||||||
|
|
||||||
return CatalogFeaturedItemResource::collection($items)->resolve();
|
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||||
@@ -43,16 +37,15 @@ class FeaturedGroupService
|
|||||||
{
|
{
|
||||||
$query = CatalogItem::query()
|
$query = CatalogItem::query()
|
||||||
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
|
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
|
||||||
->whereVariantsAvailable()
|
|
||||||
->with([
|
->with([
|
||||||
'inventory',
|
'inventory',
|
||||||
'attachments',
|
'attachments',
|
||||||
'itemAttributes.attribute',
|
'validityTime',
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.attachments',
|
'variants.attachments',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
'variants.eventDates',
|
'variants.eventDates',
|
||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -1,225 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Catalog\Services;
|
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
|
||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
|
||||||
use Illuminate\Support\Collection;
|
|
||||||
|
|
||||||
class VariantSelectionService
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $selectedValues
|
|
||||||
* @return array<string, mixed>
|
|
||||||
*/
|
|
||||||
public function options(
|
|
||||||
CatalogItem $catalogItem,
|
|
||||||
array $selectedValues,
|
|
||||||
?int $includedVariantId = null,
|
|
||||||
): array {
|
|
||||||
$catalogItem->load([
|
|
||||||
'itemAttributes.attribute',
|
|
||||||
'variants' => fn ($query) => $query->orderBy('id'),
|
|
||||||
'variants.inventory',
|
|
||||||
'variants.eventDate',
|
|
||||||
'variants.eventDates',
|
|
||||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
|
||||||
'variants.definitions.itemAttribute.attribute.options',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$variants = $catalogItem->visibleVariants($includedVariantId)
|
|
||||||
->values();
|
|
||||||
$normalizedSelections = collect($selectedValues)
|
|
||||||
->mapWithKeys(fn ($value, string $key): array => [$key => $this->normalizeValue($value)])
|
|
||||||
->filter(fn ($value): bool => $value !== null && $value !== '' && $value !== [])
|
|
||||||
->all();
|
|
||||||
$matchingVariants = $variants
|
|
||||||
->filter(fn (Variant $variant): bool => $this->matches($variant, $normalizedSelections))
|
|
||||||
->values();
|
|
||||||
$attributeKeys = $this->attributeKeys($catalogItem, $catalogItem->variants->values());
|
|
||||||
$isComplete = $attributeKeys->isNotEmpty()
|
|
||||||
&& $attributeKeys->every(fn (string $key): bool => array_key_exists($key, $normalizedSelections));
|
|
||||||
$resolvedVariant = $isComplete && $matchingVariants->count() === 1
|
|
||||||
? $matchingVariants->first()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return [
|
|
||||||
'variants' => $variants
|
|
||||||
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
|
|
||||||
->values()
|
|
||||||
->all(),
|
|
||||||
'selectors' => $this->selectors(
|
|
||||||
$catalogItem,
|
|
||||||
$variants,
|
|
||||||
$attributeKeys,
|
|
||||||
$matchingVariants->isEmpty() ? [] : $normalizedSelections,
|
|
||||||
),
|
|
||||||
'selected_values' => (object) ($matchingVariants->isEmpty() ? [] : $normalizedSelections),
|
|
||||||
'resolved_variant' => $resolvedVariant === null
|
|
||||||
? null
|
|
||||||
: $this->variantData($catalogItem, $resolvedVariant),
|
|
||||||
'valid' => $matchingVariants->isNotEmpty(),
|
|
||||||
'available_variant_count' => $variants->count(),
|
|
||||||
'matching_variant_count' => $matchingVariants->count(),
|
|
||||||
'price_range' => $this->priceRange($catalogItem, $variants),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param array<string, mixed> $selectedValues */
|
|
||||||
private function matches(Variant $variant, array $selectedValues): bool
|
|
||||||
{
|
|
||||||
$variantValues = $variant->selectionValues();
|
|
||||||
|
|
||||||
foreach ($selectedValues as $key => $selectedValue) {
|
|
||||||
if (! $variantValues->has($key)
|
|
||||||
|| $this->valueKey($variantValues->get($key)) !== $this->valueKey($selectedValue)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param Collection<int, Variant> $variants */
|
|
||||||
private function attributeKeys(CatalogItem $catalogItem, Collection $variants): Collection
|
|
||||||
{
|
|
||||||
return $variants
|
|
||||||
->flatMap(fn (Variant $variant): array => $variant
|
|
||||||
->selectorOptions($catalogItem->itemAttributes)
|
|
||||||
->keys()
|
|
||||||
->all())
|
|
||||||
->unique()
|
|
||||||
->values();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param Collection<int, Variant> $variants
|
|
||||||
* @param Collection<int, string> $attributeKeys
|
|
||||||
* @param array<string, mixed> $selectedValues
|
|
||||||
* @return list<array<string, mixed>>
|
|
||||||
*/
|
|
||||||
private function selectors(
|
|
||||||
CatalogItem $catalogItem,
|
|
||||||
Collection $variants,
|
|
||||||
Collection $attributeKeys,
|
|
||||||
array $selectedValues,
|
|
||||||
): array {
|
|
||||||
return $attributeKeys
|
|
||||||
->map(function (string $key, int $index) use (
|
|
||||||
$catalogItem,
|
|
||||||
$variants,
|
|
||||||
$attributeKeys,
|
|
||||||
$selectedValues,
|
|
||||||
): array {
|
|
||||||
$previousKeys = $attributeKeys->take($index);
|
|
||||||
$previousSelections = collect($selectedValues)
|
|
||||||
->only($previousKeys->all())
|
|
||||||
->all();
|
|
||||||
$compatibleVariants = $variants
|
|
||||||
->filter(fn (Variant $variant): bool => $this->matches($variant, $previousSelections));
|
|
||||||
|
|
||||||
return [
|
|
||||||
'key' => $key,
|
|
||||||
'label' => $this->attributeLabel($catalogItem, $key),
|
|
||||||
'options' => $this->optionsFor($catalogItem, $compatibleVariants, $key),
|
|
||||||
'enabled' => $index === 0 || $previousKeys->every(
|
|
||||||
fn (string $previousKey): bool => array_key_exists($previousKey, $selectedValues),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param Collection<int, Variant> $variants
|
|
||||||
* @return list<mixed>
|
|
||||||
*/
|
|
||||||
private function optionsFor(CatalogItem $catalogItem, Collection $variants, string $key): array
|
|
||||||
{
|
|
||||||
$options = [];
|
|
||||||
$seen = [];
|
|
||||||
|
|
||||||
foreach ($variants as $variant) {
|
|
||||||
$option = $variant->selectorOptions($catalogItem->itemAttributes)->get($key);
|
|
||||||
if ($option === null || $option === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$optionKey = $this->valueKey($option);
|
|
||||||
if (isset($seen[$optionKey])) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$seen[$optionKey] = true;
|
|
||||||
$options[] = $option;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $options;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function attributeLabel(CatalogItem $catalogItem, string $key): string
|
|
||||||
{
|
|
||||||
if ($key === 'event_date') {
|
|
||||||
return 'Fecha';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $catalogItem->itemAttributes
|
|
||||||
->first(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo === $key)
|
|
||||||
?->attribute
|
|
||||||
?->nombre ?? str($key)->headline()->toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param Collection<int, Variant> $variants */
|
|
||||||
private function priceRange(CatalogItem $catalogItem, Collection $variants): array
|
|
||||||
{
|
|
||||||
$prices = $variants
|
|
||||||
->map(fn (Variant $variant): float => $variant->getPrice())
|
|
||||||
->whenEmpty(fn (Collection $prices): Collection => $prices->push($catalogItem->getPrice()));
|
|
||||||
|
|
||||||
return [
|
|
||||||
'minimum' => number_format((float) $prices->min(), 2, '.', ''),
|
|
||||||
'maximum' => number_format((float) $prices->max(), 2, '.', ''),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'id' => $variant->id,
|
|
||||||
'descripcion' => $variant->getDescription(),
|
|
||||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
|
||||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
|
||||||
? null
|
|
||||||
: $variant->inventory?->availableStock(),
|
|
||||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
private function normalizeValue(mixed $value): mixed
|
|
||||||
{
|
|
||||||
if (is_array($value) && array_key_exists('value', $value)) {
|
|
||||||
return (string) $value['value'];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_array($value)) {
|
|
||||||
return array_map(fn ($item) => $this->normalizeValue($item), $value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return is_scalar($value) ? (string) $value : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function valueKey(mixed $value): string
|
|
||||||
{
|
|
||||||
$normalized = $this->normalizeValue($value);
|
|
||||||
|
|
||||||
if (is_array($normalized)) {
|
|
||||||
sort($normalized);
|
|
||||||
}
|
|
||||||
|
|
||||||
return json_encode($normalized, JSON_THROW_ON_ERROR);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,6 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
|||||||
Route::get('categories/{category}', [CatalogController::class, 'category'])
|
Route::get('categories/{category}', [CatalogController::class, 'category'])
|
||||||
->name('categories.show');
|
->name('categories.show');
|
||||||
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
|
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
|
||||||
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
|
|
||||||
Route::post('catalog-items', [CatalogController::class, 'store']);
|
Route::post('catalog-items', [CatalogController::class, 'store']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,57 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Desfile\Controllers;
|
|
||||||
|
|
||||||
use App\Domains\Desfile\Requests\ReplaceEntryImageRequest;
|
|
||||||
use App\Domains\Desfile\Requests\SyncEntryRowsRequest;
|
|
||||||
use App\Domains\Desfile\Requests\UpdateEntryImageRequest;
|
|
||||||
use App\Domains\Desfile\Resources\EntryResource;
|
|
||||||
use App\Domains\Desfile\Services\EntryService;
|
|
||||||
use App\Http\Controllers\Controller;
|
|
||||||
use Illuminate\Http\JsonResponse;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Response;
|
|
||||||
|
|
||||||
class EntryController extends Controller
|
|
||||||
{
|
|
||||||
public function __construct(private readonly EntryService $entryService) {}
|
|
||||||
|
|
||||||
public function show(Request $request): EntryResource
|
|
||||||
{
|
|
||||||
return new EntryResource(
|
|
||||||
$this->entryService->current($request->user()->tenant()->firstOrFail()),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function update(SyncEntryRowsRequest $request): EntryResource
|
|
||||||
{
|
|
||||||
return new EntryResource($this->entryService->syncRows(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$request->validated('rows'),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function replaceImage(ReplaceEntryImageRequest $request): JsonResponse
|
|
||||||
{
|
|
||||||
return (new EntryResource($this->entryService->replaceImage(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$request->file('image'),
|
|
||||||
$request->boolean('is_enabled', true),
|
|
||||||
)))->response();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updateImage(UpdateEntryImageRequest $request): EntryResource
|
|
||||||
{
|
|
||||||
return new EntryResource($this->entryService->updateImage(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$request->boolean('is_enabled'),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function destroyImage(Request $request): Response
|
|
||||||
{
|
|
||||||
$this->entryService->deleteImage($request->user()->tenant()->firstOrFail());
|
|
||||||
|
|
||||||
return response()->noContent();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Desfile\Requests;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
|
|
||||||
class ReplaceEntryImageRequest extends FormRequest
|
|
||||||
{
|
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function rules(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'image' => ['required', 'image', 'mimes:jpeg,jpg,png,webp', 'max:10240'],
|
|
||||||
'is_enabled' => ['sometimes', 'boolean'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Desfile\Requests;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
use Illuminate\Validation\Validator;
|
|
||||||
|
|
||||||
class SyncEntryRowsRequest extends FormRequest
|
|
||||||
{
|
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function rules(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'rows' => ['required', 'array', 'min:1', 'max:1000'],
|
|
||||||
'rows.*' => ['required', 'array:type,sector,row,max_seat,price'],
|
|
||||||
'rows.*.type' => ['required', 'string', 'max:100'],
|
|
||||||
'rows.*.sector' => ['required', 'string', 'max:100'],
|
|
||||||
'rows.*.row' => ['required', 'integer', 'between:1,5'],
|
|
||||||
'rows.*.max_seat' => ['required', 'integer', 'between:1,100'],
|
|
||||||
'rows.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<int, callable> */
|
|
||||||
public function after(): array
|
|
||||||
{
|
|
||||||
return [function (Validator $validator): void {
|
|
||||||
$combinations = [];
|
|
||||||
|
|
||||||
foreach ($this->input('rows', []) as $index => $row) {
|
|
||||||
if (! is_array($row)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$combination = collect(['type', 'sector', 'row'])
|
|
||||||
->map(fn (string $field): string => mb_strtolower(trim((string) ($row[$field] ?? ''))))
|
|
||||||
->implode('|');
|
|
||||||
|
|
||||||
if (isset($combinations[$combination])) {
|
|
||||||
$validator->errors()->add(
|
|
||||||
"rows.{$index}",
|
|
||||||
'La combinación de tipo, sector y fila no puede repetirse.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
$combinations[$combination] = true;
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Desfile\Requests;
|
|
||||||
|
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
|
||||||
|
|
||||||
class UpdateEntryImageRequest extends FormRequest
|
|
||||||
{
|
|
||||||
public function authorize(): bool
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function rules(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'is_enabled' => ['required', 'boolean'],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Desfile\Resources;
|
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
|
||||||
|
|
||||||
/** @mixin CatalogItem */
|
|
||||||
class EntryResource extends JsonResource
|
|
||||||
{
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function toArray(Request $request): array
|
|
||||||
{
|
|
||||||
$image = $this->allAttachments->first();
|
|
||||||
|
|
||||||
return [
|
|
||||||
'id' => $this->id,
|
|
||||||
'rows' => $this->variants
|
|
||||||
->map(function ($variant): array {
|
|
||||||
$values = $variant->selectionValues();
|
|
||||||
|
|
||||||
return [
|
|
||||||
'type' => $values->get('tipo'),
|
|
||||||
'sector' => $values->get('sector'),
|
|
||||||
'row' => $values->get('fila'),
|
|
||||||
'seat' => (int) $values->get('asiento'),
|
|
||||||
'price' => $variant->getPrice(),
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->groupBy(fn (array $variant): string => implode('|', [
|
|
||||||
mb_strtolower(trim((string) $variant['type'])),
|
|
||||||
mb_strtolower(trim((string) $variant['sector'])),
|
|
||||||
mb_strtolower(trim((string) $variant['row'])),
|
|
||||||
]))
|
|
||||||
->map(function ($variants): array {
|
|
||||||
$first = $variants->first();
|
|
||||||
|
|
||||||
return [
|
|
||||||
'type' => $first['type'],
|
|
||||||
'sector' => $first['sector'],
|
|
||||||
'row' => $first['row'],
|
|
||||||
'max_seat' => $variants->max('seat'),
|
|
||||||
'price' => number_format($first['price'], 2, '.', ''),
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->values(),
|
|
||||||
'image' => $image === null ? null : [
|
|
||||||
'key' => $image->key,
|
|
||||||
'filename' => $image->filename,
|
|
||||||
'url' => $image->getTemporaryUrl(1440),
|
|
||||||
'is_enabled' => (bool) $image->pivot->is_enabled,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,302 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Desfile\Services;
|
|
||||||
|
|
||||||
use App\Domains\Attachable\Models\Attachment;
|
|
||||||
use App\Domains\Attachable\Services\AttachmentService;
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
|
||||||
use App\Domains\Catalog\Models\ItemAttribute;
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
|
||||||
use Illuminate\Http\UploadedFile;
|
|
||||||
use Illuminate\Support\Collection;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
use Illuminate\Support\Str;
|
|
||||||
use Illuminate\Validation\ValidationException;
|
|
||||||
use Throwable;
|
|
||||||
|
|
||||||
class EntryService
|
|
||||||
{
|
|
||||||
private const ATTRIBUTE_MAP = [
|
|
||||||
'type' => 'tipo',
|
|
||||||
'sector' => 'sector',
|
|
||||||
'row' => 'fila',
|
|
||||||
'seat' => 'asiento',
|
|
||||||
];
|
|
||||||
|
|
||||||
private const ROW_ATTRIBUTE_MAP = [
|
|
||||||
'type' => 'tipo',
|
|
||||||
'sector' => 'sector',
|
|
||||||
'row' => 'fila',
|
|
||||||
];
|
|
||||||
|
|
||||||
public function __construct(private readonly AttachmentService $attachmentService) {}
|
|
||||||
|
|
||||||
public function current(Tenant $tenant): CatalogItem
|
|
||||||
{
|
|
||||||
return $this->entryQuery($tenant)
|
|
||||||
->with([
|
|
||||||
'allAttachments',
|
|
||||||
'itemAttributes.attribute.options',
|
|
||||||
'variants' => fn ($query) => $query->orderBy('id'),
|
|
||||||
'variants.inventory',
|
|
||||||
'variants.definitions.itemAttribute.attribute',
|
|
||||||
])
|
|
||||||
->firstOrFail();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<int, array<string, mixed>> $rows
|
|
||||||
*/
|
|
||||||
public function syncRows(Tenant $tenant, array $rows): CatalogItem
|
|
||||||
{
|
|
||||||
DB::transaction(function () use ($tenant, $rows): void {
|
|
||||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
|
||||||
$itemAttributes = $this->itemAttributes($entry);
|
|
||||||
$existingVariants = $entry->variants()
|
|
||||||
->with(['inventory', 'definitions.itemAttribute.attribute'])
|
|
||||||
->lockForUpdate()
|
|
||||||
->get();
|
|
||||||
$existingBySelection = $existingVariants->keyBy(
|
|
||||||
fn (Variant $variant): string => $this->selectionKey($variant->selectionValues()->all()),
|
|
||||||
);
|
|
||||||
$desiredSelections = collect();
|
|
||||||
|
|
||||||
foreach (array_values($rows) as $index => $data) {
|
|
||||||
$rowValues = $this->resolveRowValues($itemAttributes, $data, $index);
|
|
||||||
|
|
||||||
foreach (range(1, (int) $data['max_seat']) as $seat) {
|
|
||||||
$values = [
|
|
||||||
...$rowValues,
|
|
||||||
'asiento' => $this->resolveAttributeValue(
|
|
||||||
$itemAttributes,
|
|
||||||
'asiento',
|
|
||||||
(string) $seat,
|
|
||||||
"rows.{$index}.max_seat",
|
|
||||||
),
|
|
||||||
];
|
|
||||||
$selectionKey = $this->selectionKey($values);
|
|
||||||
$desiredSelections->put($selectionKey, true);
|
|
||||||
$variant = $existingBySelection->get($selectionKey);
|
|
||||||
|
|
||||||
if ($variant === null) {
|
|
||||||
$variant = $entry->variants()->create([
|
|
||||||
'inventory_id' => Inventory::query()->create(['real_stock' => 1])->id,
|
|
||||||
'descripcion' => $this->description($values),
|
|
||||||
'precio' => $data['price'],
|
|
||||||
]);
|
|
||||||
$variant->definitions()->createMany(
|
|
||||||
collect($values)->map(
|
|
||||||
fn (string $value, string $code): array => [
|
|
||||||
'item_attribute_id' => $itemAttributes[$code]->id,
|
|
||||||
'value' => $value,
|
|
||||||
],
|
|
||||||
)->values()->all(),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
$variant->update([
|
|
||||||
'descripcion' => $this->description($values),
|
|
||||||
'precio' => $data['price'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($existingVariants as $variant) {
|
|
||||||
$selectionKey = $this->selectionKey($variant->selectionValues()->all());
|
|
||||||
if ($desiredSelections->has($selectionKey)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->assertVariantCanChangeIdentity($variant, 'rows');
|
|
||||||
$variant->delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
$minimumPrice = $entry->variants()->min('precio');
|
|
||||||
if ($minimumPrice !== null) {
|
|
||||||
$entry->update(['precio' => $minimumPrice]);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this->current($tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function replaceImage(
|
|
||||||
Tenant $tenant,
|
|
||||||
UploadedFile $image,
|
|
||||||
bool $isEnabled,
|
|
||||||
): CatalogItem {
|
|
||||||
$attachment = $this->attachmentService->store($image, 'catalog-items');
|
|
||||||
$previousAttachments = collect();
|
|
||||||
|
|
||||||
try {
|
|
||||||
DB::transaction(function () use ($tenant, $attachment, $isEnabled, &$previousAttachments): void {
|
|
||||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
|
||||||
$previousAttachments = $entry->allAttachments()->get();
|
|
||||||
$entry->allAttachments()->sync([
|
|
||||||
$attachment->id => [
|
|
||||||
'orden' => 0,
|
|
||||||
'is_enabled' => $isEnabled,
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
} catch (Throwable $throwable) {
|
|
||||||
$this->deleteAttachmentQuietly($attachment);
|
|
||||||
throw $throwable;
|
|
||||||
}
|
|
||||||
|
|
||||||
$previousAttachments->each(fn (Attachment $previous) => $this->deleteIfUnused($previous));
|
|
||||||
|
|
||||||
return $this->current($tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updateImage(Tenant $tenant, bool $isEnabled): CatalogItem
|
|
||||||
{
|
|
||||||
DB::transaction(function () use ($tenant, $isEnabled): void {
|
|
||||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
|
||||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
|
||||||
|
|
||||||
$entry->allAttachments()->updateExistingPivot($attachment->id, [
|
|
||||||
'is_enabled' => $isEnabled,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
return $this->current($tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function deleteImage(Tenant $tenant): void
|
|
||||||
{
|
|
||||||
$attachment = DB::transaction(function () use ($tenant): Attachment {
|
|
||||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
|
||||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
|
||||||
$entry->allAttachments()->detach($attachment->id);
|
|
||||||
|
|
||||||
return $attachment;
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->deleteIfUnused($attachment);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return Collection<string, ItemAttribute> */
|
|
||||||
private function itemAttributes(CatalogItem $entry): Collection
|
|
||||||
{
|
|
||||||
$attributes = $entry->itemAttributes()
|
|
||||||
->with('attribute.options')
|
|
||||||
->get()
|
|
||||||
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute !== null)
|
|
||||||
->keyBy(fn (ItemAttribute $itemAttribute): string => $itemAttribute->attribute->codigo);
|
|
||||||
$missing = collect(self::ATTRIBUTE_MAP)->diff($attributes->keys());
|
|
||||||
|
|
||||||
if ($missing->isNotEmpty()) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'rows' => [
|
|
||||||
'Faltan atributos requeridos para las entradas del desfile: '.$missing->implode(', ').'.',
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $attributes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
|
||||||
* @param array<string, mixed> $data
|
|
||||||
* @return array<string, string>
|
|
||||||
*/
|
|
||||||
private function resolveRowValues(Collection $itemAttributes, array $data, int $index): array
|
|
||||||
{
|
|
||||||
$values = [];
|
|
||||||
|
|
||||||
foreach (self::ROW_ATTRIBUTE_MAP as $input => $code) {
|
|
||||||
$values[$code] = $this->resolveAttributeValue(
|
|
||||||
$itemAttributes,
|
|
||||||
$code,
|
|
||||||
(string) $data[$input],
|
|
||||||
"rows.{$index}.{$input}",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $values;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param Collection<string, ItemAttribute> $itemAttributes */
|
|
||||||
private function resolveAttributeValue(
|
|
||||||
Collection $itemAttributes,
|
|
||||||
string $code,
|
|
||||||
string $requestedValue,
|
|
||||||
string $errorKey,
|
|
||||||
): string {
|
|
||||||
$requestedValue = trim($requestedValue);
|
|
||||||
$option = $itemAttributes[$code]->attribute->options->first(
|
|
||||||
fn ($candidate): bool => $this->normalize($candidate->value) === $this->normalize($requestedValue),
|
|
||||||
);
|
|
||||||
|
|
||||||
if ($option === null) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
$errorKey => ['La opción seleccionada no es válida.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $option->value;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param array<string, mixed> $values */
|
|
||||||
private function selectionKey(array $values): string
|
|
||||||
{
|
|
||||||
return collect(self::ATTRIBUTE_MAP)
|
|
||||||
->map(fn (string $code): string => $this->normalize((string) ($values[$code] ?? '')))
|
|
||||||
->implode('|');
|
|
||||||
}
|
|
||||||
|
|
||||||
private function assertVariantCanChangeIdentity(Variant $variant, string $key): void
|
|
||||||
{
|
|
||||||
$inventory = $variant->inventory;
|
|
||||||
|
|
||||||
if (($inventory?->reserved_stock ?? 0) > 0 || ($inventory?->sold_units ?? 0) > 0) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
$key => [
|
|
||||||
'No se puede modificar ni eliminar un asiento con ventas o reservas.',
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param array<string, string> $values */
|
|
||||||
private function description(array $values): string
|
|
||||||
{
|
|
||||||
return "Sector {$values['sector']} - Fila {$values['fila']} - Asiento {$values['asiento']} - {$values['tipo']}";
|
|
||||||
}
|
|
||||||
|
|
||||||
private function normalize(string $value): string
|
|
||||||
{
|
|
||||||
return Str::ascii(mb_strtolower(trim($value)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return Builder<CatalogItem> */
|
|
||||||
private function entryQuery(Tenant $tenant): Builder
|
|
||||||
{
|
|
||||||
return CatalogItem::query()
|
|
||||||
->where('tenant_code', $tenant->codigo)
|
|
||||||
->where('slug', 'entrada');
|
|
||||||
}
|
|
||||||
|
|
||||||
private function deleteIfUnused(Attachment $attachment): void
|
|
||||||
{
|
|
||||||
if (DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->deleteAttachmentQuietly($attachment);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function deleteAttachmentQuietly(Attachment $attachment): void
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$this->attachmentService->delete($attachment);
|
|
||||||
} catch (Throwable $throwable) {
|
|
||||||
report($throwable);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
use App\Domains\Desfile\Controllers\EntryController;
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
|
|
||||||
Route::prefix('v1/adminapp/tenant/desfile')
|
|
||||||
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.entradas'])
|
|
||||||
->group(function (): void {
|
|
||||||
Route::get('entries', [EntryController::class, 'show'])
|
|
||||||
->name('adminapp.desfile.entries.show');
|
|
||||||
Route::put('entries', [EntryController::class, 'update'])
|
|
||||||
->name('adminapp.desfile.entries.update');
|
|
||||||
Route::post('entries/image', [EntryController::class, 'replaceImage'])
|
|
||||||
->name('adminapp.desfile.entries.image.replace');
|
|
||||||
Route::patch('entries/image', [EntryController::class, 'updateImage'])
|
|
||||||
->name('adminapp.desfile.entries.image.update');
|
|
||||||
Route::delete('entries/image', [EntryController::class, 'destroyImage'])
|
|
||||||
->name('adminapp.desfile.entries.image.destroy');
|
|
||||||
});
|
|
||||||
@@ -3,10 +3,7 @@
|
|||||||
namespace App\Domains\Event\Models;
|
namespace App\Domains\Event\Models;
|
||||||
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
use App\Domains\Catalog\Models\Variant;
|
||||||
use App\Domains\Event\Services\EventDateTextFormatter;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
|
||||||
use App\Domains\Ticket\Models\ValidityTime;
|
|
||||||
use Carbon\CarbonInterface;
|
use Carbon\CarbonInterface;
|
||||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
@@ -28,30 +25,10 @@ class EventDate extends Model
|
|||||||
|
|
||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
|
|
||||||
protected static function booted(): void
|
|
||||||
{
|
|
||||||
static::creating(fn (self $eventDate) => $eventDate->syncValidityTime());
|
|
||||||
static::created(fn (self $eventDate) => $eventDate->syncTenantDateText());
|
|
||||||
static::updated(function (self $eventDate): void {
|
|
||||||
if ($eventDate->wasChanged(['date', 'time_start', 'time_end'])) {
|
|
||||||
$eventDate->syncValidityTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
$eventDate->syncTenantDateText();
|
|
||||||
});
|
|
||||||
static::deleted(function (self $eventDate): void {
|
|
||||||
$eventDate->syncTenantDateText();
|
|
||||||
ValidityTime::query()
|
|
||||||
->whereKey($eventDate->validity_time_id)
|
|
||||||
->delete();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'date' => 'date:Y-m-d',
|
'date' => 'date:Y-m-d',
|
||||||
'validity_time_id' => 'integer',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,12 +38,6 @@ class EventDate extends Model
|
|||||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return BelongsTo<ValidityTime, $this> */
|
|
||||||
public function validityTime(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(ValidityTime::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return HasMany<Variant, $this> */
|
/** @return HasMany<Variant, $this> */
|
||||||
public function variants(): HasMany
|
public function variants(): HasMany
|
||||||
{
|
{
|
||||||
@@ -93,48 +64,4 @@ class EventDate extends Model
|
|||||||
{
|
{
|
||||||
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
|
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function syncTenantDateText(): void
|
|
||||||
{
|
|
||||||
$tenant = $this->tenant()->first();
|
|
||||||
|
|
||||||
if (! $tenant) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tenant->update([
|
|
||||||
'event_date_text' => app(EventDateTextFormatter::class)->format(
|
|
||||||
$tenant->eventDates()->pluck('date')
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function syncValidityTime(): void
|
|
||||||
{
|
|
||||||
$startsAt = $this->startsAt();
|
|
||||||
$expiresAt = $this->endsAt();
|
|
||||||
|
|
||||||
if ($expiresAt->lessThanOrEqualTo($startsAt)) {
|
|
||||||
$expiresAt = $expiresAt->addDay();
|
|
||||||
}
|
|
||||||
|
|
||||||
$attributes = [
|
|
||||||
'type' => ValidityTimeType::FixedWindow,
|
|
||||||
'start_time' => null,
|
|
||||||
'end_time' => null,
|
|
||||||
'fixed_starts_at' => $startsAt,
|
|
||||||
'fixed_expires_at' => $expiresAt,
|
|
||||||
];
|
|
||||||
|
|
||||||
if ($this->validity_time_id === null) {
|
|
||||||
$validityTime = ValidityTime::query()->create($attributes);
|
|
||||||
$this->validity_time_id = $validityTime->getKey();
|
|
||||||
$this->setRelation('validityTime', $validityTime);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->validityTime()->update($attributes);
|
|
||||||
$this->unsetRelation('validityTime');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
namespace App\Domains\Event\Resources;
|
namespace App\Domains\Event\Resources;
|
||||||
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
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;
|
||||||
|
|
||||||
@@ -21,8 +20,6 @@ class EventResource extends JsonResource
|
|||||||
'location' => $this->event_location,
|
'location' => $this->event_location,
|
||||||
'dates' => $this->eventDates->map(fn ($eventDate): array => [
|
'dates' => $this->eventDates->map(fn ($eventDate): array => [
|
||||||
'id' => $eventDate->id,
|
'id' => $eventDate->id,
|
||||||
'validity_time_id' => $eventDate->validity_time_id,
|
|
||||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
|
||||||
'date' => $eventDate->date->format('Y-m-d'),
|
'date' => $eventDate->date->format('Y-m-d'),
|
||||||
'start_time' => substr($eventDate->time_start, 0, 5),
|
'start_time' => substr($eventDate->time_start, 0, 5),
|
||||||
'end_time' => substr($eventDate->time_end, 0, 5),
|
'end_time' => substr($eventDate->time_end, 0, 5),
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ namespace App\Domains\Event\Services;
|
|||||||
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
|
||||||
|
|
||||||
class EventService
|
class EventService
|
||||||
{
|
{
|
||||||
@@ -14,9 +13,11 @@ class EventService
|
|||||||
'facebook_url' => 'facebook',
|
'facebook_url' => 'facebook',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public function __construct(protected EventDateTextFormatter $eventDateTextFormatter) {}
|
||||||
|
|
||||||
public function forTenant(Tenant $tenant): Tenant
|
public function forTenant(Tenant $tenant): Tenant
|
||||||
{
|
{
|
||||||
return $tenant->load(['eventDates.validityTime', 'socialMedia']);
|
return $tenant->load(['eventDates', 'socialMedia']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param array<string, mixed> $data */
|
/** @param array<string, mixed> $data */
|
||||||
@@ -27,6 +28,9 @@ class EventService
|
|||||||
$tenant->update([
|
$tenant->update([
|
||||||
'event_title' => $data['title'],
|
'event_title' => $data['title'],
|
||||||
'event_location' => $data['location'],
|
'event_location' => $data['location'],
|
||||||
|
'event_date_text' => $this->eventDateTextFormatter->format(
|
||||||
|
array_column($data['dates'], 'date')
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->syncDates($tenant, $data['dates']);
|
$this->syncDates($tenant, $data['dates']);
|
||||||
@@ -36,7 +40,7 @@ class EventService
|
|||||||
$this->syncLegacyContact($tenant, $data['contact']);
|
$this->syncLegacyContact($tenant, $data['contact']);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $tenant->load(['eventDates.validityTime', 'socialMedia']);
|
return $tenant->load(['eventDates', 'socialMedia']);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,19 +65,7 @@ class EventService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$datesToDelete = $existingDates->slice(count($dates));
|
$existingDates->slice(count($dates))->each->delete();
|
||||||
|
|
||||||
if ($datesToDelete->contains(fn ($eventDate): bool => $eventDate
|
|
||||||
->selectedByVariants()
|
|
||||||
->whereHas('sourceTickets')
|
|
||||||
->exists()
|
|
||||||
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$datesToDelete->each->delete();
|
|
||||||
$tenant->unsetRelation('eventDates');
|
$tenant->unsetRelation('eventDates');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ use App\Domains\FiestaFutbolInfantil\Resources\AccommodationResource;
|
|||||||
use App\Domains\FiestaFutbolInfantil\Services\AccommodationService;
|
use App\Domains\FiestaFutbolInfantil\Services\AccommodationService;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Response;
|
|
||||||
|
|
||||||
class AccommodationController extends Controller
|
class AccommodationController extends Controller
|
||||||
{
|
{
|
||||||
@@ -31,14 +30,4 @@ class AccommodationController extends Controller
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function destroy(Request $request, int $accommodation): Response
|
|
||||||
{
|
|
||||||
$this->accommodationService->delete(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$accommodation,
|
|
||||||
);
|
|
||||||
|
|
||||||
return response()->noContent();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ use App\Http\Controllers\Controller;
|
|||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||||
use Illuminate\Http\Response;
|
|
||||||
|
|
||||||
class EntryController extends Controller
|
class EntryController extends Controller
|
||||||
{
|
{
|
||||||
@@ -35,14 +34,4 @@ class EntryController extends Controller
|
|||||||
->response()
|
->response()
|
||||||
->setStatusCode(200);
|
->setStatusCode(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function destroy(Request $request, int $entry): Response
|
|
||||||
{
|
|
||||||
$this->entryService->delete(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$entry,
|
|
||||||
);
|
|
||||||
|
|
||||||
return response()->noContent();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ use App\Domains\FiestaFutbolInfantil\Resources\FoodResource;
|
|||||||
use App\Domains\FiestaFutbolInfantil\Services\FoodService;
|
use App\Domains\FiestaFutbolInfantil\Services\FoodService;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Response;
|
|
||||||
|
|
||||||
class FoodController extends Controller
|
class FoodController extends Controller
|
||||||
{
|
{
|
||||||
@@ -31,14 +30,4 @@ class FoodController extends Controller
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function destroy(Request $request, int $food): Response
|
|
||||||
{
|
|
||||||
$this->foodService->delete(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$food,
|
|
||||||
);
|
|
||||||
|
|
||||||
return response()->noContent();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ use App\Http\Controllers\Controller;
|
|||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||||
use Illuminate\Http\Response;
|
|
||||||
|
|
||||||
class MerchandiseController extends Controller
|
class MerchandiseController extends Controller
|
||||||
{
|
{
|
||||||
@@ -34,14 +33,4 @@ class MerchandiseController extends Controller
|
|||||||
->response()
|
->response()
|
||||||
->setStatusCode(200);
|
->setStatusCode(200);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function destroy(Request $request, int $merchandise): Response
|
|
||||||
{
|
|
||||||
$this->merchandiseService->delete(
|
|
||||||
$request->user()->tenant()->firstOrFail(),
|
|
||||||
$merchandise,
|
|
||||||
);
|
|
||||||
|
|
||||||
return response()->noContent();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,11 +29,7 @@ class UpsertEntriesRequest extends FormRequest
|
|||||||
Rule::exists('catalog_items', 'id')->where(
|
Rule::exists('catalog_items', 'id')->where(
|
||||||
fn ($query) => $query
|
fn ($query) => $query
|
||||||
->where('tenant_code', $tenantCode)
|
->where('tenant_code', $tenantCode)
|
||||||
->whereIn('category_id', fn ($categoryQuery) => $categoryQuery
|
->where('event_product_type', 'entrada')
|
||||||
->select('id')
|
|
||||||
->from('categorias')
|
|
||||||
->where('tenant_code', $tenantCode)
|
|
||||||
->where('nombre', 'Entradas'))
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
'entries.*.title' => ['required', 'string', 'max:255'],
|
'entries.*.title' => ['required', 'string', 'max:255'],
|
||||||
|
|||||||
@@ -28,11 +28,7 @@ class UpsertMerchandiseRequest extends FormRequest
|
|||||||
Rule::exists('catalog_items', 'id')->where(
|
Rule::exists('catalog_items', 'id')->where(
|
||||||
fn ($query) => $query
|
fn ($query) => $query
|
||||||
->where('tenant_code', $tenantCode)
|
->where('tenant_code', $tenantCode)
|
||||||
->whereIn('category_id', fn ($categoryQuery) => $categoryQuery
|
->where('event_product_type', 'producto')
|
||||||
->select('id')
|
|
||||||
->from('categorias')
|
|
||||||
->where('tenant_code', $tenantCode)
|
|
||||||
->where('nombre', 'Merchandising'))
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
'items.*.title' => ['required', 'string', 'max:255'],
|
'items.*.title' => ['required', 'string', 'max:255'],
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\EventProductType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\AttributeOption;
|
use App\Domains\Catalog\Models\AttributeOption;
|
||||||
@@ -10,7 +11,6 @@ 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\Catalog\Services\CatalogService;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -20,8 +20,6 @@ class AccommodationService
|
|||||||
{
|
{
|
||||||
private const ATTRIBUTE_CODE = 'tipo_alojamiento';
|
private const ATTRIBUTE_CODE = 'tipo_alojamiento';
|
||||||
|
|
||||||
public function __construct(private readonly CatalogService $catalogService) {}
|
|
||||||
|
|
||||||
public function current(Tenant $tenant): ?CatalogItem
|
public function current(Tenant $tenant): ?CatalogItem
|
||||||
{
|
{
|
||||||
return CatalogItem::query()
|
return CatalogItem::query()
|
||||||
@@ -88,18 +86,6 @@ class AccommodationService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function delete(Tenant $tenant, int $accommodationId): void
|
|
||||||
{
|
|
||||||
$variant = Variant::query()
|
|
||||||
->whereKey($accommodationId)
|
|
||||||
->whereHas('catalogItem', fn ($query) => $query
|
|
||||||
->where('tenant_code', $tenant->codigo)
|
|
||||||
->where('slug', 'alojamiento'))
|
|
||||||
->firstOrFail();
|
|
||||||
|
|
||||||
$this->catalogService->deleteVariant($variant);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function attribute(Tenant $tenant): Attribute
|
private function attribute(Tenant $tenant): Attribute
|
||||||
{
|
{
|
||||||
$attribute = Attribute::query()
|
$attribute = Attribute::query()
|
||||||
@@ -125,21 +111,18 @@ class AccommodationService
|
|||||||
'tenant_code' => $tenant->codigo,
|
'tenant_code' => $tenant->codigo,
|
||||||
'nombre' => 'Alojamientos',
|
'nombre' => 'Alojamientos',
|
||||||
]);
|
]);
|
||||||
$accommodation = CatalogItem::withTrashed()
|
$accommodation = CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('slug', 'alojamiento')
|
->where('slug', 'alojamiento')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($accommodation !== null) {
|
if ($accommodation !== null) {
|
||||||
if ($accommodation->trashed()) {
|
|
||||||
$accommodation->restore();
|
|
||||||
}
|
|
||||||
|
|
||||||
$accommodation->update([
|
$accommodation->update([
|
||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
|
'event_product_type' => EventProductType::Product->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => false,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $accommodation;
|
return $accommodation;
|
||||||
@@ -152,8 +135,9 @@ class AccommodationService
|
|||||||
'descripcion' => 'Alojamiento',
|
'descripcion' => 'Alojamiento',
|
||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
'precio' => collect($variants)->min('price') ?? 0,
|
'precio' => collect($variants)->min('price') ?? 0,
|
||||||
|
'event_product_type' => EventProductType::Product->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => false,
|
||||||
'inventory_id' => null,
|
'inventory_id' => null,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\EventProductType;
|
||||||
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\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
@@ -23,7 +24,7 @@ class EntryService
|
|||||||
{
|
{
|
||||||
return CatalogItem::query()
|
return CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
->where('event_product_type', EventProductType::Entry->value)
|
||||||
->with([
|
->with([
|
||||||
'variants.inventory',
|
'variants.inventory',
|
||||||
'variants.eventDate',
|
'variants.eventDate',
|
||||||
@@ -61,6 +62,7 @@ class EntryService
|
|||||||
'descripcion' => $entry['description'] ?? null,
|
'descripcion' => $entry['description'] ?? null,
|
||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
'precio' => $entry['price'],
|
'precio' => $entry['price'],
|
||||||
|
'event_product_type' => EventProductType::Entry->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => true,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'attribute_codes' => ['event_date'],
|
'attribute_codes' => ['event_date'],
|
||||||
@@ -74,24 +76,13 @@ class EntryService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function delete(Tenant $tenant, int $entryId): void
|
|
||||||
{
|
|
||||||
$entry = CatalogItem::query()
|
|
||||||
->whereKey($entryId)
|
|
||||||
->where('tenant_code', $tenant->codigo)
|
|
||||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
|
||||||
->firstOrFail();
|
|
||||||
|
|
||||||
$this->catalogService->delete($entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param array<string, mixed> $entry */
|
/** @param array<string, mixed> $entry */
|
||||||
private function update(Tenant $tenant, Category $category, array $entry, int $index): CatalogItem
|
private function update(Tenant $tenant, Category $category, array $entry, int $index): CatalogItem
|
||||||
{
|
{
|
||||||
$catalogItem = CatalogItem::query()
|
$catalogItem = CatalogItem::query()
|
||||||
->whereKey($entry['id'])
|
->whereKey($entry['id'])
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
->where('event_product_type', EventProductType::Entry->value)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->firstOrFail();
|
->firstOrFail();
|
||||||
|
|
||||||
@@ -160,7 +151,7 @@ class EntryService
|
|||||||
|
|
||||||
while (
|
while (
|
||||||
in_array($slug, $reservedSlugs, true)
|
in_array($slug, $reservedSlugs, true)
|
||||||
|| CatalogItem::withTrashed()
|
|| CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('slug', $slug)
|
->where('slug', $slug)
|
||||||
->exists()
|
->exists()
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\EventProductType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\AttributeOption;
|
use App\Domains\Catalog\Models\AttributeOption;
|
||||||
@@ -10,7 +11,6 @@ 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\Catalog\Services\CatalogService;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -20,14 +20,6 @@ class FoodService
|
|||||||
{
|
{
|
||||||
private const ATTRIBUTE_CODES = ['event_date', 'horario', 'servicio'];
|
private const ATTRIBUTE_CODES = ['event_date', 'horario', 'servicio'];
|
||||||
|
|
||||||
private const ATTRIBUTE_SORT_ORDERS = [
|
|
||||||
'event_date' => 1,
|
|
||||||
'horario' => 2,
|
|
||||||
'servicio' => 3,
|
|
||||||
];
|
|
||||||
|
|
||||||
public function __construct(private readonly CatalogService $catalogService) {}
|
|
||||||
|
|
||||||
public function current(Tenant $tenant): ?CatalogItem
|
public function current(Tenant $tenant): ?CatalogItem
|
||||||
{
|
{
|
||||||
return CatalogItem::query()
|
return CatalogItem::query()
|
||||||
@@ -95,18 +87,6 @@ class FoodService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function delete(Tenant $tenant, int $foodId): void
|
|
||||||
{
|
|
||||||
$variant = Variant::query()
|
|
||||||
->whereKey($foodId)
|
|
||||||
->whereHas('catalogItem', fn ($query) => $query
|
|
||||||
->where('tenant_code', $tenant->codigo)
|
|
||||||
->where('slug', 'comida'))
|
|
||||||
->firstOrFail();
|
|
||||||
|
|
||||||
$this->catalogService->deleteVariant($variant);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return Collection<string, Attribute> */
|
/** @return Collection<string, Attribute> */
|
||||||
private function attributes(Tenant $tenant): Collection
|
private function attributes(Tenant $tenant): Collection
|
||||||
{
|
{
|
||||||
@@ -136,21 +116,18 @@ class FoodService
|
|||||||
'tenant_code' => $tenant->codigo,
|
'tenant_code' => $tenant->codigo,
|
||||||
'nombre' => 'Comidas',
|
'nombre' => 'Comidas',
|
||||||
]);
|
]);
|
||||||
$food = CatalogItem::withTrashed()
|
$food = CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('slug', 'comida')
|
->where('slug', 'comida')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($food !== null) {
|
if ($food !== null) {
|
||||||
if ($food->trashed()) {
|
|
||||||
$food->restore();
|
|
||||||
}
|
|
||||||
|
|
||||||
$food->update([
|
$food->update([
|
||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
|
'event_product_type' => EventProductType::Product->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => false,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return $food;
|
return $food;
|
||||||
@@ -163,8 +140,9 @@ class FoodService
|
|||||||
'descripcion' => 'Comida',
|
'descripcion' => 'Comida',
|
||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
'precio' => collect($variants)->min('price') ?? 0,
|
'precio' => collect($variants)->min('price') ?? 0,
|
||||||
|
'event_product_type' => EventProductType::Product->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => false,
|
||||||
'inventory_id' => null,
|
'inventory_id' => null,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -176,12 +154,9 @@ class FoodService
|
|||||||
private function itemAttributes(CatalogItem $food, Collection $attributes): Collection
|
private function itemAttributes(CatalogItem $food, Collection $attributes): Collection
|
||||||
{
|
{
|
||||||
return $attributes->mapWithKeys(function (Attribute $attribute, string $code) use ($food): array {
|
return $attributes->mapWithKeys(function (Attribute $attribute, string $code) use ($food): array {
|
||||||
$itemAttribute = $food->itemAttributes()->updateOrCreate(
|
$itemAttribute = $food->itemAttributes()->firstOrCreate(
|
||||||
['attribute_id' => $attribute->id],
|
['attribute_id' => $attribute->id],
|
||||||
[
|
['allow_multi_select' => false],
|
||||||
'allow_multi_select' => false,
|
|
||||||
'sort_order' => self::ATTRIBUTE_SORT_ORDERS[$code],
|
|
||||||
],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
return [$code => $itemAttribute];
|
return [$code => $itemAttribute];
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\EventProductType;
|
||||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
use App\Domains\Catalog\Models\Attribute;
|
use App\Domains\Catalog\Models\Attribute;
|
||||||
use App\Domains\Catalog\Models\AttributeOption;
|
use App\Domains\Catalog\Models\AttributeOption;
|
||||||
@@ -10,7 +11,6 @@ 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\Catalog\Services\CatalogService;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -21,13 +21,12 @@ class MerchandiseService
|
|||||||
{
|
{
|
||||||
private const ATTRIBUTE_CODES = ['color', 'talle'];
|
private const ATTRIBUTE_CODES = ['color', 'talle'];
|
||||||
|
|
||||||
public function __construct(private readonly CatalogService $catalogService) {}
|
|
||||||
|
|
||||||
/** @return Collection<int, CatalogItem> */
|
/** @return Collection<int, CatalogItem> */
|
||||||
public function all(Tenant $tenant): Collection
|
public function all(Tenant $tenant): Collection
|
||||||
{
|
{
|
||||||
return CatalogItem::query()
|
return CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('event_product_type', EventProductType::Product->value)
|
||||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Merchandising'))
|
->whereHas('category', fn ($query) => $query->where('nombre', 'Merchandising'))
|
||||||
->with([
|
->with([
|
||||||
'itemAttributes.attribute.options',
|
'itemAttributes.attribute.options',
|
||||||
@@ -72,8 +71,9 @@ class MerchandiseService
|
|||||||
'descripcion' => $data['description'] ?? null,
|
'descripcion' => $data['description'] ?? null,
|
||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||||
|
'event_product_type' => EventProductType::Product->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => false,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$itemAttributes = $this->itemAttributes($item, $attributes);
|
$itemAttributes = $this->itemAttributes($item, $attributes);
|
||||||
@@ -120,19 +120,6 @@ class MerchandiseService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function delete(Tenant $tenant, int $merchandiseId): void
|
|
||||||
{
|
|
||||||
$variant = Variant::query()
|
|
||||||
->whereKey($merchandiseId)
|
|
||||||
->whereHas('catalogItem', fn ($query) => $query
|
|
||||||
->where('tenant_code', $tenant->codigo)
|
|
||||||
->whereHas('category', fn ($categoryQuery) => $categoryQuery
|
|
||||||
->where('nombre', 'Merchandising')))
|
|
||||||
->firstOrFail();
|
|
||||||
|
|
||||||
$this->catalogService->deleteVariant($variant);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return Collection<string, Attribute> */
|
/** @return Collection<string, Attribute> */
|
||||||
private function attributes(Tenant $tenant): Collection
|
private function attributes(Tenant $tenant): Collection
|
||||||
{
|
{
|
||||||
@@ -166,6 +153,7 @@ class MerchandiseService
|
|||||||
->whereKey($itemId)
|
->whereKey($itemId)
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('category_id', $category->id)
|
->where('category_id', $category->id)
|
||||||
|
->where('event_product_type', EventProductType::Product->value)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
@@ -196,8 +184,9 @@ class MerchandiseService
|
|||||||
'category_id' => $category->id,
|
'category_id' => $category->id,
|
||||||
'precio' => collect($data['variants'])->min('price') ?? 0,
|
'precio' => collect($data['variants'])->min('price') ?? 0,
|
||||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||||
|
'event_product_type' => EventProductType::Product->value,
|
||||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||||
'has_tickets' => true,
|
'has_tickets' => false,
|
||||||
'inventory_id' => null,
|
'inventory_id' => null,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -411,7 +400,7 @@ class MerchandiseService
|
|||||||
|
|
||||||
while (
|
while (
|
||||||
in_array($slug, $reservedSlugs, true)
|
in_array($slug, $reservedSlugs, true)
|
||||||
|| CatalogItem::withTrashed()
|
|| CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('slug', $slug)
|
->where('slug', $slug)
|
||||||
->exists()
|
->exists()
|
||||||
|
|||||||
@@ -15,34 +15,22 @@ Route::prefix('v1/adminapp/tenant')
|
|||||||
Route::post('entries', [EntryController::class, 'store'])
|
Route::post('entries', [EntryController::class, 'store'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
|
||||||
->name('adminapp.fiesta-futbol-infantil.entries.store');
|
->name('adminapp.fiesta-futbol-infantil.entries.store');
|
||||||
Route::delete('entries/{entry}', [EntryController::class, 'destroy'])
|
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
|
|
||||||
->name('adminapp.fiesta-futbol-infantil.entries.destroy');
|
|
||||||
Route::get('foods', [FoodController::class, 'index'])
|
Route::get('foods', [FoodController::class, 'index'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
||||||
->name('adminapp.fiesta-futbol-infantil.foods.index');
|
->name('adminapp.fiesta-futbol-infantil.foods.index');
|
||||||
Route::post('foods', [FoodController::class, 'store'])
|
Route::post('foods', [FoodController::class, 'store'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
||||||
->name('adminapp.fiesta-futbol-infantil.foods.store');
|
->name('adminapp.fiesta-futbol-infantil.foods.store');
|
||||||
Route::delete('foods/{food}', [FoodController::class, 'destroy'])
|
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.comida')
|
|
||||||
->name('adminapp.fiesta-futbol-infantil.foods.destroy');
|
|
||||||
Route::get('accommodations', [AccommodationController::class, 'index'])
|
Route::get('accommodations', [AccommodationController::class, 'index'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.alojamientos')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.alojamientos')
|
||||||
->name('adminapp.fiesta-futbol-infantil.accommodations.index');
|
->name('adminapp.fiesta-futbol-infantil.accommodations.index');
|
||||||
Route::post('accommodations', [AccommodationController::class, 'store'])
|
Route::post('accommodations', [AccommodationController::class, 'store'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.alojamientos')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.alojamientos')
|
||||||
->name('adminapp.fiesta-futbol-infantil.accommodations.store');
|
->name('adminapp.fiesta-futbol-infantil.accommodations.store');
|
||||||
Route::delete('accommodations/{accommodation}', [AccommodationController::class, 'destroy'])
|
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.alojamientos')
|
|
||||||
->name('adminapp.fiesta-futbol-infantil.accommodations.destroy');
|
|
||||||
Route::get('merchandise', [MerchandiseController::class, 'index'])
|
Route::get('merchandise', [MerchandiseController::class, 'index'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.merchandising')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.merchandising')
|
||||||
->name('adminapp.fiesta-futbol-infantil.merchandise.index');
|
->name('adminapp.fiesta-futbol-infantil.merchandise.index');
|
||||||
Route::post('merchandise', [MerchandiseController::class, 'store'])
|
Route::post('merchandise', [MerchandiseController::class, 'store'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.merchandising')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.merchandising')
|
||||||
->name('adminapp.fiesta-futbol-infantil.merchandise.store');
|
->name('adminapp.fiesta-futbol-infantil.merchandise.store');
|
||||||
Route::delete('merchandise/{merchandise}', [MerchandiseController::class, 'destroy'])
|
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.merchandising')
|
|
||||||
->name('adminapp.fiesta-futbol-infantil.merchandise.destroy');
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ namespace App\Domains\Forms\Resources;
|
|||||||
|
|
||||||
use App\Domains\Catalog\Models\AttributeOption;
|
use App\Domains\Catalog\Models\AttributeOption;
|
||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\Event\Models\EventDate;
|
||||||
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;
|
||||||
@@ -18,8 +17,6 @@ class FoodFormResource extends JsonResource
|
|||||||
'event_dates' => $this->resource['event_dates']->map(
|
'event_dates' => $this->resource['event_dates']->map(
|
||||||
fn (EventDate $eventDate): array => [
|
fn (EventDate $eventDate): array => [
|
||||||
'id' => $eventDate->id,
|
'id' => $eventDate->id,
|
||||||
'validity_time_id' => $eventDate->validity_time_id,
|
|
||||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
|
||||||
'date' => $eventDate->date->format('Y-m-d'),
|
'date' => $eventDate->date->format('Y-m-d'),
|
||||||
]
|
]
|
||||||
)->values(),
|
)->values(),
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ class FoodFormService
|
|||||||
->keyBy('codigo');
|
->keyBy('codigo');
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'event_dates' => $tenant->eventDates()->with('validityTime')->get(),
|
'event_dates' => $tenant->eventDates()->get(),
|
||||||
'schedules' => $attributes->get('horario')?->options ?? new Collection,
|
'schedules' => $attributes->get('horario')?->options ?? new Collection,
|
||||||
'services' => $attributes->get('servicio')?->options ?? new Collection,
|
'services' => $attributes->get('servicio')?->options ?? new Collection,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -127,7 +127,8 @@ class TelepagosWebhookService
|
|||||||
|
|
||||||
DB::transaction(function () use ($compra, $paymentData) {
|
DB::transaction(function () use ($compra, $paymentData) {
|
||||||
TelepagosPayment::create($paymentData);
|
TelepagosPayment::create($paymentData);
|
||||||
$this->checkoutService->confirmPaidPurchase($compra);
|
$this->checkoutService->confirmPurchase($compra);
|
||||||
|
$compra->markAsPaid();
|
||||||
});
|
});
|
||||||
|
|
||||||
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
|
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
|
||||||
|
|||||||
@@ -9,15 +9,8 @@ class PasswordResetRequested
|
|||||||
{
|
{
|
||||||
use Dispatchable, SerializesModels;
|
use Dispatchable, SerializesModels;
|
||||||
|
|
||||||
public const CHANNEL_STOREFRONT = 'storefront';
|
|
||||||
|
|
||||||
public const CHANNEL_ADMINAPP = 'adminapp';
|
|
||||||
|
|
||||||
public const CHANNEL_SCANNER = 'scanner';
|
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public readonly int $attemptId,
|
public readonly int $attemptId,
|
||||||
public readonly string $tenantCode,
|
public readonly string $tenantCode,
|
||||||
public readonly string $channel = self::CHANNEL_STOREFRONT,
|
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,13 +26,11 @@ class SendPasswordResetEmail implements ShouldQueueAfterCommit
|
|||||||
app(NotificationMailService::class)->sendPasswordResetCode(
|
app(NotificationMailService::class)->sendPasswordResetCode(
|
||||||
$event->attemptId,
|
$event->attemptId,
|
||||||
$event->tenantCode,
|
$event->tenantCode,
|
||||||
$event->channel,
|
|
||||||
);
|
);
|
||||||
} catch (Throwable $exception) {
|
} catch (Throwable $exception) {
|
||||||
Log::error('Failed to send password reset email.', [
|
Log::error('Failed to send password reset email.', [
|
||||||
'attempt_id' => $event->attemptId,
|
'attempt_id' => $event->attemptId,
|
||||||
'tenant_code' => $event->tenantCode,
|
'tenant_code' => $event->tenantCode,
|
||||||
'channel' => $event->channel,
|
|
||||||
'exception' => $exception,
|
'exception' => $exception,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -5,11 +5,9 @@ namespace App\Domains\Notification\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\Integration\Services\MailService;
|
use App\Domains\Integration\Services\MailService;
|
||||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
use App\Domains\Ticket\Models\Ticket;
|
||||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
@@ -33,15 +31,9 @@ class NotificationMailService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function sendPasswordResetCode(
|
public function sendPasswordResetCode(int $attemptId, string $tenantCode): void
|
||||||
int $attemptId,
|
{
|
||||||
string $tenantCode,
|
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
|
||||||
string $channel = PasswordResetRequested::CHANNEL_STOREFRONT,
|
|
||||||
): void {
|
|
||||||
$tenant = Tenant::query()
|
|
||||||
->with('websiteType')
|
|
||||||
->where('codigo', $tenantCode)
|
|
||||||
->firstOrFail();
|
|
||||||
$attempt = ResetPasswordAttempt::query()
|
$attempt = ResetPasswordAttempt::query()
|
||||||
->with('user')
|
->with('user')
|
||||||
->findOrFail($attemptId);
|
->findOrFail($attemptId);
|
||||||
@@ -56,28 +48,12 @@ class NotificationMailService
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$recoveryDomain = match ($channel) {
|
|
||||||
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
|
||||||
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
|
||||||
default => $tenant->dominio,
|
|
||||||
};
|
|
||||||
$recoveryQuery = ['email' => $attempt->user->email];
|
|
||||||
if (
|
|
||||||
$channel === PasswordResetRequested::CHANNEL_SCANNER
|
|
||||||
&& $attempt->reason === ResetPasswordAttempt::REASON_STAFF_CREATED
|
|
||||||
) {
|
|
||||||
$recoveryQuery['code'] = $attempt->codigo;
|
|
||||||
}
|
|
||||||
$recoveryUrl = $recoveryDomain === null
|
|
||||||
? null
|
|
||||||
: 'https://'.$recoveryDomain.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
|
||||||
|
|
||||||
$this->mailService
|
$this->mailService
|
||||||
->forTenant($tenantCode)
|
->forTenant($tenantCode)
|
||||||
->send(
|
->send(
|
||||||
$attempt->user->email,
|
$attempt->user->email,
|
||||||
"Código para recuperar tu contraseña - {$tenant->nombre}",
|
"Código para recuperar tu contraseña - {$tenant->nombre}",
|
||||||
view('mail.notifications.password-reset', compact('tenant', 'attempt', 'recoveryUrl'))->render(),
|
view('mail.notifications.password-reset', compact('tenant', 'attempt'))->render(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,7 +81,6 @@ class NotificationMailService
|
|||||||
->where('tenant_code', $purchase->tenant_codigo)
|
->where('tenant_code', $purchase->tenant_codigo)
|
||||||
->where('user_id', $purchase->user_id)
|
->where('user_id', $purchase->user_id)
|
||||||
->whereKey($ticketIds)
|
->whereKey($ticketIds)
|
||||||
->with(TicketPresentationResolver::RELATIONS)
|
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
if ($tickets->isEmpty()) {
|
if ($tickets->isEmpty()) {
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Exceptions;
|
|
||||||
|
|
||||||
use RuntimeException;
|
|
||||||
|
|
||||||
class InsufficientStockException extends RuntimeException
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* @param array<int, array{
|
|
||||||
* index: int,
|
|
||||||
* catalog_item_id: int,
|
|
||||||
* variant_id: int|null,
|
|
||||||
* requested_quantity: int,
|
|
||||||
* available_quantity: int,
|
|
||||||
* message: string
|
|
||||||
* }> $unavailableItems
|
|
||||||
*/
|
|
||||||
public function __construct(
|
|
||||||
public readonly array $unavailableItems,
|
|
||||||
) {
|
|
||||||
parent::__construct(
|
|
||||||
collect($unavailableItems)->pluck('message')->unique()->implode(' '),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<string, array<int, string>> */
|
|
||||||
public function errors(): array
|
|
||||||
{
|
|
||||||
return collect($this->unavailableItems)
|
|
||||||
->mapWithKeys(fn (array $item): array => [
|
|
||||||
"direct_items.{$item['index']}.cantidad" => [$item['message']],
|
|
||||||
])
|
|
||||||
->all();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -19,21 +19,29 @@ class StartCheckoutRequest extends FormRequest
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'cart_id' => [
|
'cart_id' => [
|
||||||
'required_without:direct_items',
|
'required_without:direct_item',
|
||||||
Rule::prohibitedIf(fn (): bool => $this->has('direct_items')),
|
Rule::prohibitedIf(fn (): bool => $this->has('direct_item')),
|
||||||
'integer',
|
'integer',
|
||||||
'exists:carritos,id',
|
'exists:carritos,id',
|
||||||
],
|
],
|
||||||
'direct_items' => [
|
'direct_item' => [
|
||||||
'required_without:cart_id',
|
'required_without:cart_id',
|
||||||
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
||||||
'array',
|
'array',
|
||||||
|
],
|
||||||
|
'direct_item.catalog_item_id' => [
|
||||||
|
'required_with:direct_item',
|
||||||
|
'integer',
|
||||||
|
],
|
||||||
|
'direct_item.variant_id' => [
|
||||||
|
'nullable',
|
||||||
|
'integer',
|
||||||
|
],
|
||||||
|
'direct_item.cantidad' => [
|
||||||
|
'required_with:direct_item',
|
||||||
|
'integer',
|
||||||
'min:1',
|
'min:1',
|
||||||
],
|
],
|
||||||
'direct_items.*' => ['required', 'array'],
|
|
||||||
'direct_items.*.catalog_item_id' => ['required', 'integer'],
|
|
||||||
'direct_items.*.variant_id' => ['nullable', 'integer'],
|
|
||||||
'direct_items.*.cantidad' => ['required', 'integer', 'min:1'],
|
|
||||||
'dni' => ['prohibited'],
|
'dni' => ['prohibited'],
|
||||||
'telefono' => ['prohibited'],
|
'telefono' => ['prohibited'],
|
||||||
'nombre_apellido' => ['prohibited'],
|
'nombre_apellido' => ['prohibited'],
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ class CatalogSelectionResolver
|
|||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
int $catalogItemId,
|
int $catalogItemId,
|
||||||
?int $variantId,
|
?int $variantId,
|
||||||
string $fieldPrefix = 'direct_items',
|
|
||||||
): CatalogItem|Variant {
|
): CatalogItem|Variant {
|
||||||
/** @var CatalogItem|null $catalogItem */
|
/** @var CatalogItem|null $catalogItem */
|
||||||
$catalogItem = CatalogItem::query()
|
$catalogItem = CatalogItem::query()
|
||||||
@@ -32,13 +31,13 @@ class CatalogSelectionResolver
|
|||||||
if ($catalogItem->isBundle()) {
|
if ($catalogItem->isBundle()) {
|
||||||
if ($variantId !== null) {
|
if ($variantId !== null) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
"{$fieldPrefix}.variant_id" => __('api.cart.bundle_variant_forbidden'),
|
'direct_item.variant_id' => __('api.cart.bundle_variant_forbidden'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $catalogItem->bundleComponents()->exists()) {
|
if (! $catalogItem->bundleComponents()->exists()) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
"{$fieldPrefix}.catalog_item_id" => __('api.cart.empty_bundle'),
|
'direct_item.catalog_item_id' => __('api.cart.empty_bundle'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +47,7 @@ class CatalogSelectionResolver
|
|||||||
if ($variantId === null) {
|
if ($variantId === null) {
|
||||||
if ($catalogItem->inventory_id === null) {
|
if ($catalogItem->inventory_id === null) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
"{$fieldPrefix}.variant_id" => __('api.cart.variant_required'),
|
'direct_item.variant_id' => __('api.cart.variant_required'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
|
||||||
|
|
||||||
use App\Domains\Catalog\Enums\InventorySubject;
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
|
||||||
|
|
||||||
class InsufficientStockMessageBuilder
|
|
||||||
{
|
|
||||||
public function build(
|
|
||||||
CatalogItem $catalogItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
int $availableQuantity,
|
|
||||||
): string {
|
|
||||||
return match ($catalogItem->inventory_subject) {
|
|
||||||
InventorySubject::Seat => __('api.purchase.stock.seat_unavailable', [
|
|
||||||
'selection' => $selection->getSelectionLabel(),
|
|
||||||
]),
|
|
||||||
InventorySubject::Ticket => __('api.purchase.stock.ticket_unavailable', [
|
|
||||||
'selection' => $selection->getSelectionLabel(),
|
|
||||||
]),
|
|
||||||
InventorySubject::Product => __('api.purchase.stock.product_unavailable', [
|
|
||||||
'selection' => $this->productSelectionLabel($catalogItem, $selection),
|
|
||||||
'max' => $availableQuantity,
|
|
||||||
]),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private function productSelectionLabel(
|
|
||||||
CatalogItem $catalogItem,
|
|
||||||
CatalogItem|Variant $selection,
|
|
||||||
): string {
|
|
||||||
if ($selection instanceof CatalogItem) {
|
|
||||||
return $selection->getSelectionLabel();
|
|
||||||
}
|
|
||||||
|
|
||||||
return __('api.purchase.stock.product_selection', [
|
|
||||||
'product' => $catalogItem->getName(),
|
|
||||||
'selection' => $selection->getSelectionLabel(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,17 +18,12 @@ class ReleaseCheckoutService
|
|||||||
|
|
||||||
public function cancel(Purchase $purchase): Purchase
|
public function cancel(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: true);
|
return $this->release($purchase, Purchase::STATUS_CANCELLED);
|
||||||
}
|
|
||||||
|
|
||||||
public function cancelWithoutRestoringCart(Purchase $purchase): Purchase
|
|
||||||
{
|
|
||||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function expire(Purchase $purchase): Purchase
|
public function expire(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $this->release($purchase, Purchase::STATUS_EXPIRED, restoreCart: true);
|
return $this->release($purchase, Purchase::STATUS_EXPIRED);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function expireOverdue(): int
|
public function expireOverdue(): int
|
||||||
@@ -51,9 +46,9 @@ class ReleaseCheckoutService
|
|||||||
return $expiredCount;
|
return $expiredCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function release(Purchase $purchase, string $targetStatus, bool $restoreCart): Purchase
|
private function release(Purchase $purchase, string $targetStatus): Purchase
|
||||||
{
|
{
|
||||||
return DB::transaction(function () use ($purchase, $targetStatus, $restoreCart): Purchase {
|
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
@@ -81,7 +76,7 @@ class ReleaseCheckoutService
|
|||||||
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
|
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->get();
|
->get();
|
||||||
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
|
$reservationReturnedToCart = $this->sourceCart->restore($purchase);
|
||||||
|
|
||||||
foreach ($items as $item) {
|
foreach ($items as $item) {
|
||||||
if (! $reservationReturnedToCart) {
|
if (! $reservationReturnedToCart) {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ use App\Domains\Cart\Models\CartItem;
|
|||||||
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\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
@@ -23,7 +22,6 @@ class StartCheckoutService
|
|||||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||||
private readonly CatalogSelectionResolver $selections,
|
private readonly CatalogSelectionResolver $selections,
|
||||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
@@ -35,17 +33,12 @@ class StartCheckoutService
|
|||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->findOrFail($tenant->getKey());
|
->findOrFail($tenant->getKey());
|
||||||
|
|
||||||
$directItems = $purchaseData['direct_items'] ?? null;
|
$directItem = $purchaseData['direct_item'] ?? null;
|
||||||
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
||||||
unset($purchaseData['direct_items'], $purchaseData['cart_id']);
|
unset($purchaseData['direct_item'], $purchaseData['cart_id']);
|
||||||
|
|
||||||
if (is_array($directItems)) {
|
if (is_array($directItem)) {
|
||||||
return $this->startDirectItems(
|
return $this->startDirect($tenant, $userId, $purchaseData, $directItem);
|
||||||
$tenant,
|
|
||||||
$userId,
|
|
||||||
$purchaseData,
|
|
||||||
$directItems,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($cartId === null) {
|
if ($cartId === null) {
|
||||||
@@ -60,153 +53,63 @@ class StartCheckoutService
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $purchaseData
|
* @param array<string, mixed> $purchaseData
|
||||||
* @param array<int, array<string, mixed>> $directItems
|
* @param array<string, mixed> $directItem
|
||||||
*/
|
*/
|
||||||
private function startDirectItems(
|
private function startDirect(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
int $userId,
|
int $userId,
|
||||||
array $purchaseData,
|
array $purchaseData,
|
||||||
array $directItems,
|
array $directItem,
|
||||||
): Purchase {
|
): Purchase {
|
||||||
$lines = collect(array_values($directItems))
|
$catalogItemId = (int) $directItem['catalog_item_id'];
|
||||||
->map(function (array $item, int $index): array {
|
$variantId = isset($directItem['variant_id']) ? (int) $directItem['variant_id'] : null;
|
||||||
return [
|
$quantity = (int) $directItem['cantidad'];
|
||||||
'index' => $index,
|
$selection = $this->selections->resolve($tenant, $catalogItemId, $variantId);
|
||||||
'catalog_item_id' => (int) $item['catalog_item_id'],
|
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
|
||||||
'variant_id' => isset($item['variant_id']) ? (int) $item['variant_id'] : null,
|
|
||||||
'quantity' => (int) $item['cantidad'],
|
|
||||||
'field' => "direct_items.{$index}",
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->groupBy(fn (array $line): string => sprintf(
|
|
||||||
'%d:%s',
|
|
||||||
$line['catalog_item_id'],
|
|
||||||
$line['variant_id'] === null ? 'none' : (string) $line['variant_id'],
|
|
||||||
))
|
|
||||||
->map(function (Collection $duplicateLines): array {
|
|
||||||
$line = $duplicateLines->first();
|
|
||||||
$line['quantity'] = (int) $duplicateLines->sum('quantity');
|
|
||||||
|
|
||||||
return $line;
|
$this->purchaseLimits->assertCanPurchase(
|
||||||
})
|
$catalogItem,
|
||||||
->sortBy(fn (array $line): string => sprintf(
|
$userId,
|
||||||
'%020d:%020d',
|
$quantity,
|
||||||
$line['catalog_item_id'],
|
field: 'direct_item.cantidad',
|
||||||
$line['variant_id'] ?? 0,
|
);
|
||||||
))
|
|
||||||
->values();
|
|
||||||
|
|
||||||
$resolvedLines = $lines->map(function (array $line) use ($tenant): array {
|
$availableQuantity = $this->inventory->availableQuantity($selection);
|
||||||
$selection = $this->selections->resolve(
|
|
||||||
$tenant,
|
|
||||||
$line['catalog_item_id'],
|
|
||||||
$line['variant_id'],
|
|
||||||
$line['field'],
|
|
||||||
);
|
|
||||||
|
|
||||||
return [
|
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||||
...$line,
|
throw ValidationException::withMessages([
|
||||||
'selection' => $selection,
|
'direct_item.cantidad' => __('api.purchase.direct_item_max_stock', ['max' => $availableQuantity]),
|
||||||
'catalog_item' => $selection instanceof Variant
|
]);
|
||||||
? $selection->catalogItem
|
|
||||||
: $selection,
|
|
||||||
];
|
|
||||||
});
|
|
||||||
|
|
||||||
$resolvedLines
|
|
||||||
->groupBy(fn (array $line): int => $line['catalog_item']->getKey())
|
|
||||||
->each(function (Collection $catalogLines) use ($userId): void {
|
|
||||||
/** @var CatalogItem $catalogItem */
|
|
||||||
$catalogItem = $catalogLines->first()['catalog_item'];
|
|
||||||
$this->purchaseLimits->assertCanPurchase(
|
|
||||||
$catalogItem,
|
|
||||||
$userId,
|
|
||||||
(int) $catalogLines->sum('quantity'),
|
|
||||||
field: 'direct_items',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
$unavailableItems = $resolvedLines
|
|
||||||
->map(function (array $line): ?array {
|
|
||||||
$availableQuantity = $this->inventory->availableQuantity($line['selection']);
|
|
||||||
|
|
||||||
if ($availableQuantity === null || $availableQuantity >= $line['quantity']) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->unavailableItem($line, $availableQuantity);
|
|
||||||
})
|
|
||||||
->filter()
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
|
|
||||||
if ($unavailableItems !== []) {
|
|
||||||
throw new InsufficientStockException($unavailableItems);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($resolvedLines as $line) {
|
try {
|
||||||
try {
|
$this->inventory->reserve($selection, $quantity);
|
||||||
$this->inventory->reserve($line['selection'], $line['quantity']);
|
} catch (\InvalidArgumentException) {
|
||||||
} catch (\InvalidArgumentException) {
|
throw ValidationException::withMessages([
|
||||||
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
|
'direct_item.cantidad' => __('api.purchase.insufficient_stock'),
|
||||||
|
]);
|
||||||
throw new InsufficientStockException([
|
|
||||||
$this->unavailableItem($line, $availableQuantity),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$purchase = $this->createPurchase(
|
$purchase = $this->createPurchase(
|
||||||
$tenant,
|
$tenant,
|
||||||
$userId,
|
$userId,
|
||||||
$purchaseData,
|
$purchaseData,
|
||||||
(float) $resolvedLines->sum(
|
$selection->getPrice() * $quantity,
|
||||||
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
|
|
||||||
),
|
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
|
$directCartItem = $this->makeDirectCartItem(
|
||||||
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem(
|
$selection,
|
||||||
$line['selection'],
|
$catalogItemId,
|
||||||
$line['catalog_item_id'],
|
$variantId,
|
||||||
$line['variant_id'],
|
$quantity,
|
||||||
$line['quantity'],
|
);
|
||||||
));
|
|
||||||
|
|
||||||
$purchase->items()->createMany(
|
$purchase->items()->createMany(
|
||||||
$this->snapshots->fromCartItems($directCartItems),
|
$this->snapshots->fromCartItems(collect([$directCartItem])),
|
||||||
);
|
);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $line
|
|
||||||
* @return array{
|
|
||||||
* index: int,
|
|
||||||
* catalog_item_id: int,
|
|
||||||
* variant_id: int|null,
|
|
||||||
* requested_quantity: int,
|
|
||||||
* available_quantity: int,
|
|
||||||
* message: string
|
|
||||||
* }
|
|
||||||
*/
|
|
||||||
private function unavailableItem(array $line, int $availableQuantity): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'index' => $line['index'],
|
|
||||||
'catalog_item_id' => $line['catalog_item_id'],
|
|
||||||
'variant_id' => $line['variant_id'],
|
|
||||||
'requested_quantity' => $line['quantity'],
|
|
||||||
'available_quantity' => $availableQuantity,
|
|
||||||
'message' => $this->stockMessages->build(
|
|
||||||
$line['catalog_item'],
|
|
||||||
$line['selection'],
|
|
||||||
$availableQuantity,
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
private function startFromCart(
|
private function startFromCart(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
|
|||||||
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
|
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
|
||||||
use App\Domains\Purchase\Services\Checkout\StartCheckoutService;
|
use App\Domains\Purchase\Services\Checkout\StartCheckoutService;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stable checkout API used by controllers, commands and integrations.
|
* Stable checkout API used by controllers, commands and integrations.
|
||||||
@@ -65,26 +64,11 @@ class CheckoutService
|
|||||||
$this->completer->confirm($purchase);
|
$this->completer->confirm($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function confirmPaidPurchase(Purchase $purchase): Purchase
|
|
||||||
{
|
|
||||||
return DB::transaction(function () use ($purchase): Purchase {
|
|
||||||
$this->completer->confirm($purchase);
|
|
||||||
$purchase->markAsPaid();
|
|
||||||
|
|
||||||
return $purchase->refresh()->load(['items.imageAttachment']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function cancelPurchase(Purchase $purchase): Purchase
|
public function cancelPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $this->releaser->cancel($purchase);
|
return $this->releaser->cancel($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function cancelPurchaseWithoutRestoringCart(Purchase $purchase): Purchase
|
|
||||||
{
|
|
||||||
return $this->releaser->cancelWithoutRestoringCart($purchase);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function expirePurchase(Purchase $purchase): Purchase
|
public function expirePurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $this->releaser->expire($purchase);
|
return $this->releaser->expire($purchase);
|
||||||
|
|||||||
@@ -3,10 +3,8 @@
|
|||||||
namespace App\Domains\Sale\Controllers\AdminApp;
|
namespace App\Domains\Sale\Controllers\AdminApp;
|
||||||
|
|
||||||
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
|
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
|
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleResource;
|
use App\Domains\Sale\Resources\AdminApp\SaleResource;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleTicketResource;
|
|
||||||
use App\Domains\Sale\Services\AdminAppSalePdfService;
|
use App\Domains\Sale\Services\AdminAppSalePdfService;
|
||||||
use App\Domains\Sale\Services\AdminAppSaleService;
|
use App\Domains\Sale\Services\AdminAppSaleService;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
@@ -32,36 +30,6 @@ class SaleController extends Controller
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, int $sale): SaleDetailResource
|
|
||||||
{
|
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
|
||||||
|
|
||||||
return new SaleDetailResource($this->saleService->detail($tenant, $sale));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function tickets(Request $request, int $sale): AnonymousResourceCollection
|
|
||||||
{
|
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
|
||||||
|
|
||||||
return SaleTicketResource::collection(
|
|
||||||
$this->saleService->tickets($tenant, $sale)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function confirm(Request $request, int $sale): SaleResource
|
|
||||||
{
|
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
|
||||||
|
|
||||||
return new SaleResource($this->saleService->confirm($tenant, $sale));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function cancel(Request $request, int $sale): SaleResource
|
|
||||||
{
|
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
|
||||||
|
|
||||||
return new SaleResource($this->saleService->cancel($tenant, $sale));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function modifications(Request $request): AnonymousResourceCollection
|
public function modifications(Request $request): AnonymousResourceCollection
|
||||||
{
|
{
|
||||||
return SaleModificationResource::collection(
|
return SaleModificationResource::collection(
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Sale\Resources\AdminApp;
|
|
||||||
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
|
||||||
|
|
||||||
/** @mixin Purchase */
|
|
||||||
class SaleDetailResource extends JsonResource
|
|
||||||
{
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function toArray(Request $request): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'id' => $this->id,
|
|
||||||
'items' => $this->items->map(fn (PurchaseItem $item): array => [
|
|
||||||
'id' => $item->id,
|
|
||||||
'product' => $item->item_nombre,
|
|
||||||
'event_dates' => $this->eventDates($item),
|
|
||||||
'quantity' => (int) $item->cantidad,
|
|
||||||
'unit_price' => $this->formatMoney($item->precio_unitario),
|
|
||||||
'total' => $this->formatMoney($item->total),
|
|
||||||
])->values(),
|
|
||||||
'total' => $this->formatMoney($this->total),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return list<string> */
|
|
||||||
private function eventDates(PurchaseItem $item): array
|
|
||||||
{
|
|
||||||
return collect($item->variant_attributes ?? [])
|
|
||||||
->filter(fn (mixed $attribute): bool => is_array($attribute)
|
|
||||||
&& mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
|
|
||||||
->flatMap(function (array $attribute): array {
|
|
||||||
$value = $attribute['value'] ?? [];
|
|
||||||
|
|
||||||
return is_array($value) ? $value : [$value];
|
|
||||||
})
|
|
||||||
->filter(fn (mixed $date): bool => is_string($date) && $date !== '')
|
|
||||||
->values()
|
|
||||||
->all();
|
|
||||||
}
|
|
||||||
|
|
||||||
private function formatMoney(float|int|string|null $amount): string
|
|
||||||
{
|
|
||||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Sale\Resources\AdminApp;
|
|
||||||
|
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
|
||||||
|
|
||||||
/** @mixin Ticket */
|
|
||||||
class SaleTicketResource extends JsonResource
|
|
||||||
{
|
|
||||||
/** @return array<string, mixed> */
|
|
||||||
public function toArray(Request $request): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'product' => $this->name,
|
|
||||||
'id' => $this->id,
|
|
||||||
'expires_at' => $this->getEffectiveExpiresAt(),
|
|
||||||
'status' => $this->status,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,21 +4,13 @@ namespace App\Domains\Sale\Services;
|
|||||||
|
|
||||||
use App\Domains\Logging\Models\ValueChange;
|
use App\Domains\Logging\Models\ValueChange;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Services\CheckoutService;
|
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use App\Domains\Ticket\Models\Ticket;
|
|
||||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
|
||||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Pagination\LengthAwarePaginator;
|
use Illuminate\Pagination\LengthAwarePaginator;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
class AdminAppSaleService
|
class AdminAppSaleService
|
||||||
{
|
{
|
||||||
public function __construct(
|
|
||||||
protected CheckoutService $checkoutService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function confirmedSalesTotal(Tenant $tenant): string
|
public function confirmedSalesTotal(Tenant $tenant): string
|
||||||
{
|
{
|
||||||
$total = Purchase::query()
|
$total = Purchase::query()
|
||||||
@@ -47,42 +39,6 @@ class AdminAppSaleService
|
|||||||
->withQueryString();
|
->withQueryString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function detail(Tenant $tenant, int $saleId): Purchase
|
|
||||||
{
|
|
||||||
return Purchase::query()
|
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
|
||||||
->with('items')
|
|
||||||
->findOrFail($saleId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return Collection<int, Ticket> */
|
|
||||||
public function tickets(Tenant $tenant, int $saleId): Collection
|
|
||||||
{
|
|
||||||
return $this->findForTenant($tenant, $saleId)
|
|
||||||
->tickets()
|
|
||||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
|
||||||
->orderBy('id')
|
|
||||||
->get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function confirm(Tenant $tenant, int $saleId): Purchase
|
|
||||||
{
|
|
||||||
$sale = $this->findForTenant($tenant, $saleId);
|
|
||||||
|
|
||||||
return $this->saleForResponse(
|
|
||||||
$this->checkoutService->confirmPaidPurchase($sale)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function cancel(Tenant $tenant, int $saleId): Purchase
|
|
||||||
{
|
|
||||||
$sale = $this->findForTenant($tenant, $saleId);
|
|
||||||
|
|
||||||
return $this->saleForResponse(
|
|
||||||
$this->checkoutService->cancelPurchaseWithoutRestoringCart($sale)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $filters
|
* @param array<string, mixed> $filters
|
||||||
* @return Collection<int, Purchase>
|
* @return Collection<int, Purchase>
|
||||||
@@ -161,18 +117,4 @@ class AdminAppSaleService
|
|||||||
->orderByDesc('changed_at')
|
->orderByDesc('changed_at')
|
||||||
->orderByDesc('id');
|
->orderByDesc('id');
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function findForTenant(Tenant $tenant, int $saleId): Purchase
|
|
||||||
{
|
|
||||||
return Purchase::query()
|
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
|
||||||
->findOrFail($saleId);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function saleForResponse(Purchase $sale): Purchase
|
|
||||||
{
|
|
||||||
return $sale->refresh()
|
|
||||||
->loadSum('items as quantity', 'cantidad')
|
|
||||||
->loadCount('tickets');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,4 @@ Route::prefix('v1/adminapp/tenant')
|
|||||||
Route::get('sales/pdf', [SaleController::class, 'downloadPdf']);
|
Route::get('sales/pdf', [SaleController::class, 'downloadPdf']);
|
||||||
Route::get('sales/modifications', [SaleController::class, 'modifications']);
|
Route::get('sales/modifications', [SaleController::class, 'modifications']);
|
||||||
Route::get('sales/modifications/pdf', [SaleController::class, 'downloadModificationsPdf']);
|
Route::get('sales/modifications/pdf', [SaleController::class, 'downloadModificationsPdf']);
|
||||||
Route::post('sales/{sale}/confirm', [SaleController::class, 'confirm'])->whereNumber('sale');
|
|
||||||
Route::post('sales/{sale}/cancel', [SaleController::class, 'cancel'])->whereNumber('sale');
|
|
||||||
Route::get('sales/{sale}/tickets', [SaleController::class, 'tickets'])->whereNumber('sale');
|
|
||||||
Route::get('sales/{sale}', [SaleController::class, 'show'])->whereNumber('sale');
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,86 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Domains\Shared\Rules;
|
|
||||||
|
|
||||||
use Closure;
|
|
||||||
use Illuminate\Contracts\Validation\ValidationRule;
|
|
||||||
|
|
||||||
class CroppedImageOrBase64Rule implements ValidationRule
|
|
||||||
{
|
|
||||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
||||||
{
|
|
||||||
if (! is_array($value)) {
|
|
||||||
(new ImageOrBase64Rule)->validate($attribute, $value, $fail);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! array_key_exists('image', $value)) {
|
|
||||||
$fail('The :attribute.image field is required.');
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$valid = true;
|
|
||||||
(new ImageOrBase64Rule)->validate(
|
|
||||||
"{$attribute}.image",
|
|
||||||
$value['image'],
|
|
||||||
function (string $message) use ($fail, &$valid): void {
|
|
||||||
$valid = false;
|
|
||||||
$fail($message);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (! $valid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($value['crops']) && is_array($value['crops'])) {
|
|
||||||
foreach (['desktop', 'mobile'] as $variant) {
|
|
||||||
$crop = $value['crops'][$variant] ?? null;
|
|
||||||
|
|
||||||
if (! is_array($crop)) {
|
|
||||||
$fail("The :attribute.crops.{$variant} field must be an object.");
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_horizontal', $crop, $fail);
|
|
||||||
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_vertical', $crop, $fail);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backwards compatibility with the original single-crop payload.
|
|
||||||
$this->validateRange($attribute, 'crop_horizontal', $value, $fail);
|
|
||||||
$this->validateRange($attribute, 'crop_vertical', $value, $fail);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function validateRange(string $attribute, string $axis, array $value, Closure $fail): void
|
|
||||||
{
|
|
||||||
$range = $value[$axis] ?? null;
|
|
||||||
|
|
||||||
if (! is_array($range)) {
|
|
||||||
$fail("The :attribute.{$axis} field must be an object.");
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$start = $range['start_percentage'] ?? null;
|
|
||||||
$end = $range['end_percentage'] ?? null;
|
|
||||||
|
|
||||||
if (
|
|
||||||
! is_numeric($start)
|
|
||||||
|| ! is_numeric($end)
|
|
||||||
|| (float) $start < 0
|
|
||||||
|| (float) $end > 100
|
|
||||||
|| (float) $start >= (float) $end
|
|
||||||
) {
|
|
||||||
$fail(
|
|
||||||
"The :attribute.{$axis} field must satisfy "
|
|
||||||
.'0 <= start_percentage < end_percentage <= 100.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,17 +15,12 @@ class StoreStaffRequest extends FormRequest
|
|||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
$categoryRules = $this->user()->tenant()->firstOrFail()
|
|
||||||
->requiresScannerCategoryValidation()
|
|
||||||
? ['required', 'array', 'min:1']
|
|
||||||
: ['sometimes', 'array'];
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||||
'dni' => ['required', 'string', 'max:50'],
|
'dni' => ['required', 'string', 'max:50'],
|
||||||
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
|
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
|
||||||
'category_ids' => $categoryRules,
|
'category_ids' => ['required', 'array', 'min:1'],
|
||||||
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
|
'category_ids.*' => ['required', 'integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,10 +16,6 @@ class UpdateStaffRequest extends FormRequest
|
|||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
$staffId = (int) $this->route('staff');
|
$staffId = (int) $this->route('staff');
|
||||||
$categoryRules = $this->user()->tenant()->firstOrFail()
|
|
||||||
->requiresScannerCategoryValidation()
|
|
||||||
? ['required', 'array', 'min:1']
|
|
||||||
: ['sometimes', 'array'];
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||||
@@ -30,8 +26,8 @@ class UpdateStaffRequest extends FormRequest
|
|||||||
'max:255',
|
'max:255',
|
||||||
Rule::unique('users', 'email')->ignore($staffId),
|
Rule::unique('users', 'email')->ignore($staffId),
|
||||||
],
|
],
|
||||||
'category_ids' => $categoryRules,
|
'category_ids' => ['required', 'array', 'min:1'],
|
||||||
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
|
'category_ids.*' => ['required', 'integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domains\Staff\Services;
|
namespace App\Domains\Staff\Services;
|
||||||
|
|
||||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
|
||||||
use App\Domains\Auth\Models\User;
|
use App\Domains\Auth\Models\User;
|
||||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
|
||||||
use App\Domains\Authorization\Enums\RoleCode;
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
use App\Domains\Catalog\Models\Category;
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
@@ -17,10 +15,6 @@ use Illuminate\Validation\ValidationException;
|
|||||||
|
|
||||||
class StaffService
|
class StaffService
|
||||||
{
|
{
|
||||||
public function __construct(
|
|
||||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/** @return Collection<int, User> */
|
/** @return Collection<int, User> */
|
||||||
public function list(Tenant $tenant, ?string $search = null): Collection
|
public function list(Tenant $tenant, ?string $search = null): Collection
|
||||||
{
|
{
|
||||||
@@ -54,10 +48,9 @@ class StaffService
|
|||||||
/** @param array<string, mixed> $data */
|
/** @param array<string, mixed> $data */
|
||||||
public function create(Tenant $tenant, array $data): User
|
public function create(Tenant $tenant, array $data): User
|
||||||
{
|
{
|
||||||
$categoryIds = $this->categoryIdsFor($tenant, $data);
|
$this->assertCategoriesBelongToTenant($tenant, $data['category_ids']);
|
||||||
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
|
|
||||||
|
|
||||||
return DB::transaction(function () use ($tenant, $data, $categoryIds): User {
|
return DB::transaction(function () use ($tenant, $data): User {
|
||||||
$staff = User::query()->create([
|
$staff = User::query()->create([
|
||||||
...Arr::only($data, ['nombre_apellido', 'dni', 'email']),
|
...Arr::only($data, ['nombre_apellido', 'dni', 'email']),
|
||||||
'email' => mb_strtolower(trim((string) $data['email'])),
|
'email' => mb_strtolower(trim((string) $data['email'])),
|
||||||
@@ -65,11 +58,7 @@ class StaffService
|
|||||||
'rol_codigo' => RoleCode::Scanner->value,
|
'rol_codigo' => RoleCode::Scanner->value,
|
||||||
'tenant_codigo' => $tenant->codigo,
|
'tenant_codigo' => $tenant->codigo,
|
||||||
]);
|
]);
|
||||||
$staff->scanCategories()->sync($categoryIds);
|
$staff->scanCategories()->sync($data['category_ids']);
|
||||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
|
||||||
$staff->email,
|
|
||||||
ResetPasswordAttempt::REASON_STAFF_CREATED,
|
|
||||||
);
|
|
||||||
|
|
||||||
return $staff->load('role', 'scanCategories');
|
return $staff->load('role', 'scanCategories');
|
||||||
});
|
});
|
||||||
@@ -79,14 +68,13 @@ class StaffService
|
|||||||
public function update(Tenant $tenant, int $staffId, array $data): User
|
public function update(Tenant $tenant, int $staffId, array $data): User
|
||||||
{
|
{
|
||||||
$staff = $this->find($tenant, $staffId);
|
$staff = $this->find($tenant, $staffId);
|
||||||
$categoryIds = $this->categoryIdsFor($tenant, $data);
|
$this->assertCategoriesBelongToTenant($tenant, $data['category_ids']);
|
||||||
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
|
|
||||||
|
|
||||||
return DB::transaction(function () use ($staff, $data, $categoryIds): User {
|
return DB::transaction(function () use ($staff, $data): User {
|
||||||
$attributes = Arr::only($data, ['nombre_apellido', 'dni', 'email']);
|
$attributes = Arr::only($data, ['nombre_apellido', 'dni', 'email']);
|
||||||
$attributes['email'] = mb_strtolower(trim((string) $data['email']));
|
$attributes['email'] = mb_strtolower(trim((string) $data['email']));
|
||||||
$staff->update($attributes);
|
$staff->update($attributes);
|
||||||
$staff->scanCategories()->sync($categoryIds);
|
$staff->scanCategories()->sync($data['category_ids']);
|
||||||
|
|
||||||
return $staff->load('role', 'scanCategories');
|
return $staff->load('role', 'scanCategories');
|
||||||
});
|
});
|
||||||
@@ -109,19 +97,6 @@ class StaffService
|
|||||||
->where('rol_codigo', RoleCode::Scanner->value);
|
->where('rol_codigo', RoleCode::Scanner->value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param array<string, mixed> $data
|
|
||||||
* @return array<int, int>
|
|
||||||
*/
|
|
||||||
private function categoryIdsFor(Tenant $tenant, array $data): array
|
|
||||||
{
|
|
||||||
if (! $tenant->requiresScannerCategoryValidation()) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return $data['category_ids'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param array<int, int> $categoryIds */
|
/** @param array<int, int> $categoryIds */
|
||||||
private function assertCategoriesBelongToTenant(Tenant $tenant, array $categoryIds): void
|
private function assertCategoriesBelongToTenant(Tenant $tenant, array $categoryIds): void
|
||||||
{
|
{
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user