Compare commits
51 Commits
feature/sc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 67e6211857 | |||
| 58471cb13d | |||
| 864bed0113 | |||
| ced7d594e8 | |||
| 38e87fff6c | |||
| a8973f6171 | |||
| 8e26611097 | |||
| 817d0de6d2 | |||
| a2298c9de2 | |||
| d73b4d1daf | |||
| e6785eb5af | |||
| 1a3f564afd | |||
| e619c51ac9 | |||
| c00b3d609c | |||
| 9cfd49f233 | |||
| 58cc35fd61 | |||
| 460ed528cf | |||
| 1c2f6c4127 | |||
| 9e74e21fb5 | |||
| 7c2880646f | |||
| 4817cb28fe | |||
| c1bfab471c | |||
| de8da72354 | |||
| 4be94275f1 | |||
| 21b0517e6c | |||
| 7fbdc00c64 | |||
| 58c7a0f580 | |||
| a63aea0463 | |||
| b8251f3b63 | |||
| a919e9366b | |||
| 11dbcb4082 | |||
| ed321d6c6c | |||
| 573d4fe5e6 | |||
| bfdaf1c38b | |||
| 4de08ff2f2 | |||
| a4a4c9afbc | |||
| 630b49cad7 | |||
| e33ebf0af1 | |||
| a2592987f5 | |||
| 329e0b1953 | |||
| 97995ae728 | |||
| 7c7a295625 | |||
| 8359f0831f | |||
| a12b3dd0c8 | |||
| 1b22989252 | |||
| 8e94cf7856 | |||
| 5b089e71b2 | |||
| 45d74e166f | |||
| f50d3d0587 | |||
| 36c1c185ee | |||
| 0fae1ca1d7 |
File diff suppressed because it is too large
Load Diff
@@ -41,15 +41,18 @@
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap/acme.com",
|
||||
"raw": "{{base_url}}/api/tenants/bootstrap?dominio=acme.com&path=/",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"bootstrap",
|
||||
"acme.com"
|
||||
"bootstrap"
|
||||
],
|
||||
"query": [
|
||||
{"key": "dominio", "value": "acme.com"},
|
||||
{"key": "path", "value": "/"}
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,6 +6,9 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
@@ -40,12 +43,34 @@ class Attachment extends Model
|
||||
];
|
||||
}
|
||||
|
||||
public function cropVariants(): HasMany
|
||||
{
|
||||
return $this->hasMany(AttachmentCrop::class);
|
||||
}
|
||||
|
||||
public function desktopCrop(): HasOne
|
||||
{
|
||||
return $this->hasOne(AttachmentCrop::class)
|
||||
->where('variant', AttachmentCrop::DESKTOP);
|
||||
}
|
||||
|
||||
public function mobileCrop(): HasOne
|
||||
{
|
||||
return $this->hasOne(AttachmentCrop::class)
|
||||
->where('variant', AttachmentCrop::MOBILE);
|
||||
}
|
||||
|
||||
public function cropSource(): HasOne
|
||||
{
|
||||
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the pre-signed temporary S3 URL for this attachment.
|
||||
*/
|
||||
public function getTemporaryUrl(int $expiresInMinutes = 10): string
|
||||
{
|
||||
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl(
|
||||
return Storage::disk('s3')->temporaryUrl(
|
||||
$this->path,
|
||||
now()->addMinutes($expiresInMinutes)
|
||||
);
|
||||
|
||||
43
app/Domains/Attachable/Models/AttachmentCrop.php
Normal file
43
app/Domains/Attachable/Models/AttachmentCrop.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Attachable\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'attachment_id',
|
||||
'variant',
|
||||
'crop_horizontal',
|
||||
'crop_vertical',
|
||||
'cropped_attachment_id',
|
||||
])]
|
||||
class AttachmentCrop extends Model
|
||||
{
|
||||
public const DESKTOP = 'desktop';
|
||||
|
||||
public const MOBILE = 'mobile';
|
||||
|
||||
public const VARIANTS = [self::DESKTOP, self::MOBILE];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'attachment_id' => 'integer',
|
||||
'crop_horizontal' => 'array',
|
||||
'crop_vertical' => 'array',
|
||||
'cropped_attachment_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
public function attachment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class);
|
||||
}
|
||||
|
||||
public function croppedAttachment(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'cropped_attachment_id');
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,9 @@ namespace App\Domains\Attachable\Services;
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Mime\MimeTypes;
|
||||
@@ -13,6 +15,107 @@ use Throwable;
|
||||
|
||||
class AttachmentService
|
||||
{
|
||||
/**
|
||||
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
||||
*/
|
||||
public function storeCroppedImageVariants(
|
||||
UploadedFile|string $image,
|
||||
string $path,
|
||||
array $crops,
|
||||
): Attachment {
|
||||
$crops = $this->validateCropVariants($crops);
|
||||
$storedPaths = [];
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use (
|
||||
$image,
|
||||
$path,
|
||||
$crops,
|
||||
&$storedPaths,
|
||||
): Attachment {
|
||||
$original = $this->store($image, $path);
|
||||
$storedPaths[] = $original->path;
|
||||
$contents = $this->imageContents($image);
|
||||
|
||||
foreach ($crops as $variant => $crop) {
|
||||
$cropped = $this->storeCropVariant($contents, $path, $crop);
|
||||
$storedPaths[] = $cropped->path;
|
||||
$original->cropVariants()->create([
|
||||
'variant' => $variant,
|
||||
'crop_horizontal' => $crop['crop_horizontal'],
|
||||
'crop_vertical' => $crop['crop_vertical'],
|
||||
'cropped_attachment_id' => $cropped->id,
|
||||
]);
|
||||
}
|
||||
|
||||
return $original->load('cropVariants.croppedAttachment');
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
if ($storedPaths !== []) {
|
||||
Storage::disk('s3')->delete(array_values(array_unique($storedPaths)));
|
||||
}
|
||||
|
||||
throw $throwable;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>}> $crops
|
||||
*/
|
||||
public function updateImageCropVariants(
|
||||
Attachment $original,
|
||||
array $crops,
|
||||
): Attachment {
|
||||
if ($original->type !== AttachmentType::Image) {
|
||||
throw new AttachmentStorageException('Only image attachments can be cropped.');
|
||||
}
|
||||
|
||||
$crops = $this->validateCropVariants($crops);
|
||||
$contents = Storage::disk('s3')->get($original->path);
|
||||
|
||||
if (! is_string($contents) || $contents === '') {
|
||||
throw new AttachmentStorageException('The original image could not be read from the s3 disk.');
|
||||
}
|
||||
|
||||
$directory = trim(str_replace('\\', '/', dirname($original->path)), './');
|
||||
$directory = $directory !== '' ? $directory : 'attachments';
|
||||
$previousCrops = $original->cropVariants()->with('croppedAttachment')->get();
|
||||
$storedCrops = [];
|
||||
|
||||
try {
|
||||
foreach ($crops as $variant => $crop) {
|
||||
$storedCrops[$variant] = $this->storeCropVariant($contents, $directory, $crop);
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($original, $crops, $storedCrops): void {
|
||||
foreach ($crops as $variant => $crop) {
|
||||
$original->cropVariants()->updateOrCreate(
|
||||
['variant' => $variant],
|
||||
[
|
||||
'crop_horizontal' => $crop['crop_horizontal'],
|
||||
'crop_vertical' => $crop['crop_vertical'],
|
||||
'cropped_attachment_id' => $storedCrops[$variant]->id,
|
||||
]
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
foreach ($storedCrops as $storedCrop) {
|
||||
$this->delete($storedCrop);
|
||||
}
|
||||
|
||||
throw $throwable;
|
||||
}
|
||||
|
||||
foreach ($previousCrops as $previousCrop) {
|
||||
if ($previousCrop->croppedAttachment !== null) {
|
||||
$this->delete($previousCrop->croppedAttachment);
|
||||
}
|
||||
}
|
||||
|
||||
return $original->refresh()->load('cropVariants.croppedAttachment');
|
||||
}
|
||||
|
||||
public function store(
|
||||
UploadedFile|string $file,
|
||||
string $path,
|
||||
@@ -57,13 +160,30 @@ class AttachmentService
|
||||
|
||||
public function delete(Attachment $attachment): void
|
||||
{
|
||||
$deleted = Storage::disk('s3')->delete($attachment->path);
|
||||
$croppedAttachments = $attachment->cropVariants()
|
||||
->with('croppedAttachment')
|
||||
->get()
|
||||
->pluck('croppedAttachment')
|
||||
->filter();
|
||||
$paths = $croppedAttachments
|
||||
->pluck('path')
|
||||
->prepend($attachment->path)
|
||||
->filter()
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
$deleted = Storage::disk('s3')->delete(
|
||||
count($paths) === 1 ? $paths[0] : $paths
|
||||
);
|
||||
|
||||
if (! $deleted) {
|
||||
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
|
||||
throw new AttachmentStorageException('No se pudieron eliminar los archivos del disco s3.');
|
||||
}
|
||||
|
||||
$attachment->delete();
|
||||
DB::transaction(function () use ($attachment, $croppedAttachments): void {
|
||||
$attachment->delete();
|
||||
Attachment::query()->whereKey($croppedAttachments->pluck('id'))->delete();
|
||||
});
|
||||
}
|
||||
|
||||
public function copy(Attachment $source, string $path): Attachment
|
||||
@@ -107,6 +227,171 @@ class AttachmentService
|
||||
return trim($path, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{crop_horizontal?: mixed, crop_vertical?: mixed}> $crops
|
||||
* @return array<string, array{crop_horizontal: array{start_percentage: float, end_percentage: float}, crop_vertical: array{start_percentage: float, end_percentage: float}}>
|
||||
*/
|
||||
protected function validateCropVariants(array $crops): array
|
||||
{
|
||||
$validated = [];
|
||||
|
||||
foreach (AttachmentCrop::VARIANTS as $variant) {
|
||||
$crop = $crops[$variant] ?? null;
|
||||
|
||||
if (! is_array($crop)) {
|
||||
throw new AttachmentStorageException("The {$variant} crop is required.");
|
||||
}
|
||||
|
||||
$horizontal = $crop['crop_horizontal'] ?? null;
|
||||
$vertical = $crop['crop_vertical'] ?? null;
|
||||
|
||||
if (! is_array($horizontal) || ! is_array($vertical)) {
|
||||
throw new AttachmentStorageException(
|
||||
"The {$variant} crop must contain crop_horizontal and crop_vertical ranges."
|
||||
);
|
||||
}
|
||||
|
||||
$validated[$variant] = [
|
||||
'crop_horizontal' => $this->validateCropRange($horizontal, "{$variant} horizontal"),
|
||||
'crop_vertical' => $this->validateCropRange($vertical, "{$variant} vertical"),
|
||||
];
|
||||
}
|
||||
|
||||
return $validated;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{crop_horizontal: array<string, mixed>, crop_vertical: array<string, mixed>} $crop
|
||||
*/
|
||||
protected function storeCropVariant(string $contents, string $path, array $crop): Attachment
|
||||
{
|
||||
$croppedContents = $this->cropImage(
|
||||
$contents,
|
||||
$crop['crop_horizontal'],
|
||||
$crop['crop_vertical'],
|
||||
);
|
||||
|
||||
return $this->store(
|
||||
'data:'.$croppedContents['mime_type'].';base64,'.base64_encode($croppedContents['contents']),
|
||||
$path,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{start_percentage?: mixed, end_percentage?: mixed} $range
|
||||
* @return array{start_percentage: float, end_percentage: float}
|
||||
*/
|
||||
protected function validateCropRange(array $range, string $axis): array
|
||||
{
|
||||
$start = $range['start_percentage'] ?? null;
|
||||
$end = $range['end_percentage'] ?? null;
|
||||
|
||||
if (! is_numeric($start) || ! is_numeric($end)) {
|
||||
throw new AttachmentStorageException(
|
||||
"The {$axis} crop range must contain numeric start_percentage and end_percentage values."
|
||||
);
|
||||
}
|
||||
|
||||
$start = (float) $start;
|
||||
$end = (float) $end;
|
||||
|
||||
if (! is_finite($start) || ! is_finite($end) || $start < 0 || $end > 100 || $start >= $end) {
|
||||
throw new AttachmentStorageException(
|
||||
"The {$axis} crop range must satisfy 0 <= start_percentage < end_percentage <= 100."
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'start_percentage' => $start,
|
||||
'end_percentage' => $end,
|
||||
];
|
||||
}
|
||||
|
||||
protected function imageContents(UploadedFile|string $image): string
|
||||
{
|
||||
if (is_string($image)) {
|
||||
return $this->decodeBase64File($image)['data'];
|
||||
}
|
||||
|
||||
$contents = file_get_contents($image->getRealPath());
|
||||
|
||||
if (! is_string($contents) || $contents === '') {
|
||||
throw new AttachmentStorageException('The image content cannot be empty.');
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string, mime_type: string}
|
||||
*/
|
||||
protected function cropImage(
|
||||
string $contents,
|
||||
array $cropHorizontal,
|
||||
array $cropVertical,
|
||||
): array {
|
||||
$source = @imagecreatefromstring($contents);
|
||||
|
||||
if ($source === false) {
|
||||
throw new AttachmentStorageException('The attachment must contain a valid image.');
|
||||
}
|
||||
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
$x = min($width - 1, (int) floor($width * $cropHorizontal['start_percentage'] / 100));
|
||||
$right = min($width, (int) ceil($width * $cropHorizontal['end_percentage'] / 100));
|
||||
$y = min($height - 1, (int) floor($height * $cropVertical['start_percentage'] / 100));
|
||||
$bottom = min($height, (int) ceil($height * $cropVertical['end_percentage'] / 100));
|
||||
$cropped = imagecrop($source, [
|
||||
'x' => $x,
|
||||
'y' => $y,
|
||||
'width' => $right - $x,
|
||||
'height' => $bottom - $y,
|
||||
]);
|
||||
|
||||
if ($cropped === false) {
|
||||
throw new AttachmentStorageException('The image could not be cropped.');
|
||||
}
|
||||
|
||||
return $this->encodeImage($cropped, $contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{contents: string, mime_type: string}
|
||||
*/
|
||||
protected function encodeImage(\GdImage $image, string $originalContents): array
|
||||
{
|
||||
$mimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($originalContents);
|
||||
$mimeType = is_string($mimeType) ? strtolower($mimeType) : '';
|
||||
|
||||
ob_start();
|
||||
|
||||
try {
|
||||
$encoded = match ($mimeType) {
|
||||
'image/jpeg' => imagejpeg($image, null, 90),
|
||||
'image/gif' => imagegif($image),
|
||||
'image/webp' => imagewebp($image, null, 90),
|
||||
'image/avif' => function_exists('imageavif') && imageavif($image, null, 90),
|
||||
default => imagepng($image),
|
||||
};
|
||||
$output = ob_get_contents();
|
||||
} finally {
|
||||
ob_end_clean();
|
||||
}
|
||||
|
||||
if (! $encoded || ! is_string($output) || $output === '') {
|
||||
throw new AttachmentStorageException('The cropped image could not be encoded.');
|
||||
}
|
||||
|
||||
return [
|
||||
'contents' => $output,
|
||||
'mime_type' => match ($mimeType) {
|
||||
'image/jpeg', 'image/gif', 'image/webp', 'image/avif' => $mimeType,
|
||||
default => 'image/png',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveFilename(UploadedFile|string $file, string $key): string
|
||||
{
|
||||
if ($file instanceof UploadedFile) {
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
## Propósito
|
||||
|
||||
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única.
|
||||
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con variantes recortadas para desktop y mobile.
|
||||
|
||||
## Componentes principales
|
||||
|
||||
- `Models/Attachment.php`: representa un adjunto y genera URL temporales de acceso.
|
||||
- `Models/AttachmentCrop.php`: relaciona un original con su crop desktop o mobile y la imagen generada.
|
||||
- `Services/AttachmentService.php`: almacena, copia y elimina archivos, compensando en S3 si falla la escritura en base de datos.
|
||||
- `Enums/AttachmentType.php`: clasifica imágenes, videos, PDF, audio, documentos y otros archivos.
|
||||
- `Exceptions/AttachmentStorageException.php`: expresa fallos propios del almacenamiento.
|
||||
@@ -25,5 +26,8 @@ No expone rutas HTTP propias. Lo consumen otros dominios, especialmente `Catalog
|
||||
## Consideraciones
|
||||
|
||||
- El directorio no puede quedar vacío después de normalizarlo.
|
||||
- Cada eje del crop guarda `start_percentage` y `end_percentage`, cumpliendo `0 <= start < end <= 100`.
|
||||
- `attachment_crops` guarda una fila por variante con los rangos horizontal/vertical y el attachment procesado.
|
||||
- Al eliminar el original mediante el servicio también se eliminan todas sus variantes recortadas.
|
||||
- La eliminación se considera fallida si S3 no confirma el borrado.
|
||||
- Las URL generadas son temporales; el vencimiento predeterminado es de 10 minutos.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\AdminAppCreateResetPasswordAttemptRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class CreateAdminAppResetPasswordAttemptController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
public function __invoke(AdminAppCreateResetPasswordAttemptRequest $request): JsonResponse
|
||||
{
|
||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
||||
$request->validated('email'),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.password_reset_requested',
|
||||
'message' => __('api.auth.password_reset_requested'),
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
], 202);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Controllers;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Requests\ScannerCreateResetPasswordAttemptRequest;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class CreateScannerResetPasswordAttemptController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
public function __invoke(ScannerCreateResetPasswordAttemptRequest $request): JsonResponse
|
||||
{
|
||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
||||
$request->validated('email'),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'auth.password_reset_requested',
|
||||
'message' => __('api.auth.password_reset_requested'),
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
], 202);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,12 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
#[Hidden(['codigo'])]
|
||||
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_VALIDATED = 'validated';
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class AdminAppCreateResetPasswordAttemptRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge(['email' => Str::lower(trim($email))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ScannerCreateResetPasswordAttemptRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$email = $this->input('email');
|
||||
|
||||
if (is_string($email)) {
|
||||
$this->merge(['email' => Str::lower(trim($email))]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -155,16 +155,19 @@ class GoogleAuthService
|
||||
$parts = parse_url($returnUrl);
|
||||
if (! is_array($parts)
|
||||
|| ! isset($parts['scheme'], $parts['host'])
|
||||
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|
||||
|| ($parts['path'] ?? '') !== '') {
|
||||
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$scheme = strtolower($parts['scheme']);
|
||||
$host = TenantDomainNormalizer::normalize($parts['host']);
|
||||
$tenantDomain = TenantDomainNormalizer::normalize($tenant->dominio);
|
||||
$returnPath = TenantDomainNormalizer::normalizePath($parts['path'] ?? '/');
|
||||
|
||||
if ($host === null || $tenantDomain === null || $host !== $tenantDomain) {
|
||||
if ($host === null
|
||||
|| $tenantDomain === null
|
||||
|| $host !== $tenantDomain
|
||||
|| $returnPath !== $tenant->base_path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@ namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||
use App\Domains\Auth\Models\LoginAttempt;
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\PermissionCode;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
@@ -60,6 +62,8 @@ class PasswordLoginService
|
||||
$userAgent,
|
||||
RoleCode::AdminApp,
|
||||
true,
|
||||
null,
|
||||
PasswordResetRequested::CHANNEL_ADMINAPP,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,6 +88,7 @@ class PasswordLoginService
|
||||
null,
|
||||
true,
|
||||
PermissionCode::ScanTickets->value,
|
||||
PasswordResetRequested::CHANNEL_SCANNER,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -96,6 +101,7 @@ class PasswordLoginService
|
||||
?RoleCode $requiredRole = RoleCode::User,
|
||||
bool $requiresTenant = false,
|
||||
?string $requiredPermission = null,
|
||||
string $passwordResetChannel = PasswordResetRequested::CHANNEL_STOREFRONT,
|
||||
): User {
|
||||
$normalizedEmail = mb_strtolower(trim($email));
|
||||
$now = CarbonImmutable::now();
|
||||
@@ -111,6 +117,7 @@ class PasswordLoginService
|
||||
$requiredRole,
|
||||
$requiresTenant,
|
||||
$requiredPermission,
|
||||
$passwordResetChannel,
|
||||
): array {
|
||||
$user = User::query()
|
||||
->where('email', $normalizedEmail)
|
||||
@@ -160,7 +167,12 @@ class PasswordLoginService
|
||||
|
||||
if ($user === null || ! Hash::check($password, $user->password)) {
|
||||
if ($user !== null && $attemptTenantCode !== null) {
|
||||
$this->registerFailure($user, $now, $attemptTenantCode);
|
||||
$this->registerFailure(
|
||||
$user,
|
||||
$now,
|
||||
$attemptTenantCode,
|
||||
$passwordResetChannel,
|
||||
);
|
||||
}
|
||||
|
||||
$outcome = $user?->locked_until?->isFuture()
|
||||
@@ -219,8 +231,12 @@ class PasswordLoginService
|
||||
return $result['user'];
|
||||
}
|
||||
|
||||
private function registerFailure(User $user, CarbonImmutable $now, string $tenantCode): void
|
||||
{
|
||||
private function registerFailure(
|
||||
User $user,
|
||||
CarbonImmutable $now,
|
||||
string $tenantCode,
|
||||
string $passwordResetChannel,
|
||||
): void {
|
||||
$windowMinutes = max(1, (int) config('login-security.attempt_window_minutes'));
|
||||
$maxAttempts = max(1, (int) config('login-security.max_attempts'));
|
||||
$lockMinutes = max(1, (int) config('login-security.lock_minutes'));
|
||||
@@ -243,7 +259,23 @@ class PasswordLoginService
|
||||
|
||||
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
|
||||
try {
|
||||
$this->resetPasswordAttemptService->createForEmail($user->email, $tenantCode, 'account_locked');
|
||||
if ($passwordResetChannel === PasswordResetRequested::CHANNEL_ADMINAPP) {
|
||||
$this->resetPasswordAttemptService->createForAdminAppEmail(
|
||||
$user->email,
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
);
|
||||
} elseif ($passwordResetChannel === PasswordResetRequested::CHANNEL_SCANNER) {
|
||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
||||
$user->email,
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
);
|
||||
} else {
|
||||
$this->resetPasswordAttemptService->createForEmail(
|
||||
$user->email,
|
||||
$tenantCode,
|
||||
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
|
||||
);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('Failed to trigger reset password on account lock', [
|
||||
'user_id' => $user->id,
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -11,8 +12,11 @@ use Throwable;
|
||||
|
||||
class ResetPasswordAttemptService
|
||||
{
|
||||
public function createForEmail(string $email, string $tenantCode, string $reason = 'manual'): void
|
||||
{
|
||||
public function createForEmail(
|
||||
string $email,
|
||||
string $tenantCode,
|
||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||
): void {
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
@@ -22,28 +26,12 @@ class ResetPasswordAttemptService
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($user === null) {
|
||||
Log::warning('Password reset attempt was not created because the user was not found.', [
|
||||
'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();
|
||||
return $this->createAttemptForUser(
|
||||
$user,
|
||||
$reason,
|
||||
$emailFingerprint,
|
||||
'Password reset attempt was not created because the user was not found.',
|
||||
);
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to create password reset attempt.', [
|
||||
@@ -54,20 +42,108 @@ class ResetPasswordAttemptService
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
if ($attemptId !== null) {
|
||||
try {
|
||||
PasswordResetRequested::dispatch($attemptId, $tenantCode);
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to dispatch password reset email.', [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $tenantCode,
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
$this->dispatchPasswordResetRequested(
|
||||
$attemptId,
|
||||
$tenantCode,
|
||||
PasswordResetRequested::CHANNEL_STOREFRONT,
|
||||
$emailFingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
public function createForAdminAppEmail(
|
||||
string $email,
|
||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||
): void {
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->where('rol_codigo', RoleCode::AdminApp->value)
|
||||
->whereNotNull('tenant_codigo')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$attemptId = $this->createAttemptForUser(
|
||||
$user,
|
||||
$reason,
|
||||
$emailFingerprint,
|
||||
'AdminApp password reset attempt was not created because the user was not found.',
|
||||
);
|
||||
|
||||
if ($user === null || $attemptId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $user->tenant_codigo,
|
||||
];
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to create AdminApp password reset attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->dispatchPasswordResetRequested(
|
||||
$result['attempt_id'] ?? null,
|
||||
$result['tenant_code'] ?? null,
|
||||
PasswordResetRequested::CHANNEL_ADMINAPP,
|
||||
$emailFingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
public function createForScannerEmail(
|
||||
string $email,
|
||||
string $reason = ResetPasswordAttempt::REASON_MANUAL,
|
||||
): void {
|
||||
$emailFingerprint = $this->emailFingerprint($email);
|
||||
|
||||
try {
|
||||
$result = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?array {
|
||||
$user = User::query()
|
||||
->where('email', $email)
|
||||
->where('rol_codigo', RoleCode::Scanner->value)
|
||||
->whereNotNull('tenant_codigo')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$attemptId = $this->createAttemptForUser(
|
||||
$user,
|
||||
$reason,
|
||||
$emailFingerprint,
|
||||
'Scanner password reset attempt was not created because the user was not found.',
|
||||
);
|
||||
|
||||
if ($user === null || $attemptId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $user->tenant_codigo,
|
||||
];
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to create Scanner password reset attempt.', [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->dispatchPasswordResetRequested(
|
||||
$result['attempt_id'] ?? null,
|
||||
$result['tenant_code'] ?? null,
|
||||
PasswordResetRequested::CHANNEL_SCANNER,
|
||||
$emailFingerprint,
|
||||
);
|
||||
}
|
||||
|
||||
public function validateCode(string $email, string $code): bool
|
||||
@@ -169,6 +245,61 @@ class ResetPasswordAttemptService
|
||||
}
|
||||
}
|
||||
|
||||
private function createAttemptForUser(
|
||||
?User $user,
|
||||
string $reason,
|
||||
string $emailFingerprint,
|
||||
string $userNotFoundMessage,
|
||||
): ?int {
|
||||
if ($user === null) {
|
||||
Log::warning($userNotFoundMessage, [
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$user->resetPasswordAttempts()
|
||||
->whereIn('status', [
|
||||
ResetPasswordAttempt::STATUS_PENDING,
|
||||
ResetPasswordAttempt::STATUS_VALIDATED,
|
||||
])
|
||||
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
|
||||
|
||||
$attempt = $user->resetPasswordAttempts()->create([
|
||||
'codigo' => $this->generateCode(),
|
||||
'reason' => $reason,
|
||||
'status' => ResetPasswordAttempt::STATUS_PENDING,
|
||||
]);
|
||||
|
||||
return $attempt->getKey();
|
||||
}
|
||||
|
||||
private function dispatchPasswordResetRequested(
|
||||
?int $attemptId,
|
||||
?string $tenantCode,
|
||||
string $channel,
|
||||
string $emailFingerprint,
|
||||
): void {
|
||||
if ($attemptId === null || $tenantCode === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
PasswordResetRequested::dispatch($attemptId, $tenantCode, $channel);
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to dispatch password reset email.', [
|
||||
'attempt_id' => $attemptId,
|
||||
'tenant_code' => $tenantCode,
|
||||
'channel' => $channel,
|
||||
'email_fingerprint' => $emailFingerprint,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
private function generateCode(): string
|
||||
{
|
||||
return str_pad((string) random_int(0, 9999), 4, '0', STR_PAD_LEFT);
|
||||
|
||||
@@ -2,10 +2,19 @@
|
||||
|
||||
use App\Domains\Auth\Controllers\AdminAppLoginController;
|
||||
use App\Domains\Auth\Controllers\AdminAppMeController;
|
||||
use App\Domains\Auth\Controllers\CreateAdminAppResetPasswordAttemptController;
|
||||
use App\Domains\Auth\Controllers\ResetPasswordController;
|
||||
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp')->group(function (): void {
|
||||
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
|
||||
Route::post('password/reset-attempts', CreateAdminAppResetPasswordAttemptController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
|
||||
->middleware('throttle:10,1');
|
||||
Route::post('password/reset', ResetPasswordController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->get('me', AdminAppMeController::class);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Auth\Controllers\CreateScannerResetPasswordAttemptController;
|
||||
use App\Domains\Auth\Controllers\ResetPasswordController;
|
||||
use App\Domains\Auth\Controllers\ScannerLoginController;
|
||||
use App\Domains\Auth\Controllers\ScannerMeController;
|
||||
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/scanner')->group(function (): void {
|
||||
Route::post('login', ScannerLoginController::class)->middleware('throttle:login');
|
||||
Route::post('password/reset-attempts', CreateScannerResetPasswordAttemptController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::post('password/reset-attempts/validate', ValidateResetPasswordAttemptController::class)
|
||||
->middleware('throttle:10,1');
|
||||
Route::post('password/reset', ResetPasswordController::class)
|
||||
->middleware('throttle:5,1');
|
||||
Route::middleware(['auth:sanctum', 'scanner.tenant'])
|
||||
->get('me', ScannerMeController::class);
|
||||
});
|
||||
|
||||
@@ -14,7 +14,10 @@ class TenantBootstrapController extends Controller
|
||||
public function __invoke(TenantBootstrapRequest $request): TenantResource
|
||||
{
|
||||
return TenantResource::make(
|
||||
$this->bootstrapService->get((string) $request->validated('dominio'))
|
||||
$this->bootstrapService->get(
|
||||
(string) $request->validated('dominio'),
|
||||
(string) $request->validated('path'),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ class TenantBootstrapRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidPath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -17,13 +19,20 @@ class TenantBootstrapRequest extends FormRequest
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->route('dominio');
|
||||
$rawDomain = $this->query('dominio', $this->route('dominio'));
|
||||
$rawPath = $this->query('path', '/');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
|
||||
$this->merge(['dominio' => $normalizedDomain]);
|
||||
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
'path' => $normalizedPath,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
@@ -41,6 +50,17 @@ class TenantBootstrapRequest extends FormRequest
|
||||
'string',
|
||||
'max:255',
|
||||
],
|
||||
'path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidPath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:2048',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,32 @@ namespace App\Domains\Bootstrap\Services;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Services\TenantInformationService;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
|
||||
class TenantBootstrapService
|
||||
{
|
||||
public function __construct(protected TenantInformationService $tenantInformationService) {}
|
||||
|
||||
public function get(string $domain): Tenant
|
||||
public function get(string $domain, string $path = '/'): Tenant
|
||||
{
|
||||
$candidateBasePaths = TenantDomainNormalizer::basePathCandidates($path);
|
||||
$tenantsByBasePath = Tenant::query()
|
||||
->where('dominio', $domain)
|
||||
->whereIn('base_path', $candidateBasePaths)
|
||||
->get()
|
||||
->keyBy('base_path');
|
||||
|
||||
$tenant = collect($candidateBasePaths)
|
||||
->map(fn (string $candidate): ?Tenant => $tenantsByBasePath->get($candidate))
|
||||
->first(fn (?Tenant $candidate): bool => $candidate !== null);
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
throw (new ModelNotFoundException)->setModel(Tenant::class);
|
||||
}
|
||||
|
||||
return $this->tenantInformationService->load(
|
||||
Tenant::query()->where('dominio', $domain)->firstOrFail(),
|
||||
$tenant,
|
||||
[
|
||||
'menues' => fn ($query) => $query->whereHas(
|
||||
'roles',
|
||||
|
||||
@@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `GET /tenants/bootstrap/{dominio}`: bootstrap público de la tienda.
|
||||
- `GET /tenants/bootstrap?dominio={hostname}&path={path}`: bootstrap público de la tienda. Resuelve la clave de tenant más específica que sea prefijo completo del path y usa el dominio raíz como fallback.
|
||||
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
|
||||
|
||||
## Validación
|
||||
|
||||
`TenantBootstrapRequest` valida el dominio recibido. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
|
||||
|
||||
## Dependencias
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
use App\Domains\Bootstrap\Controllers\TenantBootstrapController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('tenants/bootstrap/{dominio}', TenantBootstrapController::class)
|
||||
->where('dominio', '.*');
|
||||
Route::get('tenants/bootstrap', TenantBootstrapController::class);
|
||||
|
||||
require __DIR__.'/adminapp.php';
|
||||
require __DIR__.'/scanner.php';
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -20,12 +20,14 @@ class CartItemResource extends JsonResource
|
||||
{
|
||||
$selectedItem = $this->selectedItem();
|
||||
$imageUrl = null;
|
||||
$tenant = $request->route('tenant');
|
||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||
|
||||
if ($selectedItem?->relationLoaded('attachments')) {
|
||||
if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||
if ($displayImage && $imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
@@ -35,19 +37,15 @@ class CartItemResource extends JsonResource
|
||||
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
|
||||
'catalog_item_id' => $this->catalog_item_id,
|
||||
'variant_id' => $this->variant_id,
|
||||
'product' => $selectedItem === null ? null : [
|
||||
'nombre' => $selectedItem->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variants' => $this->catalogItem->visibleVariants($this->variant_id)
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
'precio' => $this->formatMoney($variant->getPrice()),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectionOptions($this->catalogItem->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
'nombre' => $selectedItem?->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variant' => $this->variant === null ? null : [
|
||||
'id' => $this->variant->id,
|
||||
'precio' => $this->formatMoney($this->variant->getPrice()),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $this->variant->inventory->availableStock(),
|
||||
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -82,11 +82,11 @@ class CartService
|
||||
$guestToken,
|
||||
60 * 24 * 180,
|
||||
'/',
|
||||
null,
|
||||
false,
|
||||
config('session.domain'),
|
||||
(bool) config('session.secure'),
|
||||
true,
|
||||
false,
|
||||
'lax',
|
||||
config('session.same_site'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -108,10 +108,6 @@ class CartService
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.catalogItem.itemAttributes.attribute',
|
||||
'items.catalogItem.variants.inventory',
|
||||
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'items.catalogItem.variants.eventDates',
|
||||
'items.catalogItem.variants.eventDate',
|
||||
'items.variant.attachments',
|
||||
'items.variant.inventory',
|
||||
'items.variant.definitions.itemAttribute.attribute.options',
|
||||
|
||||
@@ -25,7 +25,7 @@ Bajo `/tenants/{tenant:codigo}`:
|
||||
|
||||
## Contratos
|
||||
|
||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
|
||||
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública. Cada ítem expone `nombre`, `imagen` y `precio_unitario` en la raíz, priorizando la variante seleccionada y usando el catálogo base como respaldo. La variante seleccionada se serializa en `variant`; las variantes alternativas no forman parte de la respuesta del carrito.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Cart\Services\CartService;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Requests\CatalogItemDetailRequest;
|
||||
use App\Domains\Catalog\Requests\CatalogVariantOptionsRequest;
|
||||
use App\Domains\Catalog\Requests\CategoryPageRequest;
|
||||
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
|
||||
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
|
||||
@@ -14,8 +16,10 @@ use App\Domains\Catalog\Resources\CatalogFeaturedGroupResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
||||
use App\Domains\Catalog\Services\VariantSelectionService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -110,6 +114,42 @@ class CatalogController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function variantOptions(
|
||||
CatalogVariantOptionsRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogItem $catalogItem,
|
||||
VariantSelectionService $variantSelectionService,
|
||||
CartService $cartService,
|
||||
): CatalogVariantOptionsResource {
|
||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$includedVariantId = null;
|
||||
$cartItemId = $request->validated('cart_item_id');
|
||||
$selectedValues = $request->validated('selected_values', []);
|
||||
|
||||
if ($cartItemId !== null) {
|
||||
$cartItem = $cartService->show($tenant, $request)
|
||||
->items
|
||||
->firstWhere('id', (int) $cartItemId);
|
||||
abort_unless($cartItem?->catalog_item_id === $catalogItem->id, 404);
|
||||
$includedVariantId = $cartItem->variant_id;
|
||||
|
||||
if ($selectedValues === [] && $cartItem->variant !== null) {
|
||||
$selectedValues = $cartItem->variant
|
||||
->selectorOptions($catalogItem->itemAttributes)
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
||||
return CatalogVariantOptionsResource::make(
|
||||
$variantSelectionService->options(
|
||||
$catalogItem,
|
||||
$selectedValues,
|
||||
$includedVariantId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function store(
|
||||
StoreCatalogItemRequest $request,
|
||||
Tenant $tenant,
|
||||
|
||||
@@ -8,6 +8,7 @@ enum GroupLayout: string
|
||||
case Simple = 'simple';
|
||||
case SimpleVertical = 'simple_vertical';
|
||||
case Carousel = 'carousel';
|
||||
case Single = 'single';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
|
||||
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
16
app/Domains/Catalog/Enums/InventorySubject.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Enums;
|
||||
|
||||
enum InventorySubject: string
|
||||
{
|
||||
case Product = 'product';
|
||||
case Seat = 'seat';
|
||||
case Ticket = 'ticket';
|
||||
|
||||
/** @return array<int, string> */
|
||||
public static function values(): array
|
||||
{
|
||||
return array_column(self::cases(), 'value');
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ enum ProductLayout: string
|
||||
case Row = 'row';
|
||||
case ColumnWithImage = 'column_with_image';
|
||||
case ColumnWithCart = 'column_with_cart';
|
||||
case TicketSelector = 'ticket_selector';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
|
||||
@@ -5,11 +5,10 @@ namespace App\Domains\Catalog\Models;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -17,6 +16,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
@@ -30,14 +30,13 @@ use Illuminate\Support\Collection;
|
||||
'descripcion',
|
||||
'precio',
|
||||
'inventory_policy',
|
||||
'inventory_subject',
|
||||
'max_units_per_user',
|
||||
'has_tickets',
|
||||
'ticket_generation_policy',
|
||||
'validity_time_id',
|
||||
])]
|
||||
class CatalogItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -46,8 +45,8 @@ class CatalogItem extends Model
|
||||
protected $attributes = [
|
||||
'type' => CatalogItemType::Standard->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'inventory_subject' => InventorySubject::Product->value,
|
||||
'has_tickets' => false,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::PerEventDate->value,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -59,10 +58,9 @@ class CatalogItem extends Model
|
||||
'type' => CatalogItemType::class,
|
||||
'precio' => 'decimal:2',
|
||||
'inventory_policy' => InventoryPolicy::class,
|
||||
'inventory_subject' => InventorySubject::class,
|
||||
'max_units_per_user' => 'integer',
|
||||
'has_tickets' => 'boolean',
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::class,
|
||||
'validity_time_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -114,12 +112,6 @@ class CatalogItem extends Model
|
||||
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<ValidityTime, $this> */
|
||||
public function validityTime(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ValidityTime::class);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attribute, $this> */
|
||||
public function attributes(): BelongsToMany
|
||||
{
|
||||
@@ -141,6 +133,12 @@ class CatalogItem extends Model
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Attachment::class,
|
||||
@@ -148,7 +146,7 @@ class CatalogItem extends Model
|
||||
'catalog_item_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->wherePivotNull('variant_id')
|
||||
->orderByPivot('orden');
|
||||
}
|
||||
@@ -208,6 +206,11 @@ class CatalogItem extends Model
|
||||
return $this->nombre;
|
||||
}
|
||||
|
||||
public function getSelectionLabel(): string
|
||||
{
|
||||
return $this->getName();
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion;
|
||||
|
||||
@@ -13,6 +13,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'attribute_id',
|
||||
'allow_multi_select',
|
||||
'sort_order',
|
||||
'show_in_selector',
|
||||
])]
|
||||
class ItemAttribute extends Model
|
||||
{
|
||||
@@ -20,6 +21,10 @@ class ItemAttribute extends Model
|
||||
|
||||
protected $table = 'item_attributes';
|
||||
|
||||
protected $attributes = [
|
||||
'show_in_selector' => true,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
@@ -27,6 +32,7 @@ class ItemAttribute extends Model
|
||||
'attribute_id' => 'integer',
|
||||
'allow_multi_select' => 'boolean',
|
||||
'sort_order' => 'integer',
|
||||
'show_in_selector' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,10 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Lang;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
'catalog_item_id',
|
||||
@@ -22,7 +25,7 @@ use Illuminate\Support\Collection;
|
||||
])]
|
||||
class Variant extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, SoftDeletes;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
@@ -41,7 +44,7 @@ class Variant extends Model
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function catalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class);
|
||||
return $this->belongsTo(CatalogItem::class)->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
@@ -81,6 +84,12 @@ class Variant extends Model
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function attachments(): BelongsToMany
|
||||
{
|
||||
return $this->allAttachments()->wherePivot('is_enabled', true);
|
||||
}
|
||||
|
||||
/** @return BelongsToMany<Attachment, $this> */
|
||||
public function allAttachments(): BelongsToMany
|
||||
{
|
||||
$relation = $this->belongsToMany(
|
||||
Attachment::class,
|
||||
@@ -88,7 +97,7 @@ class Variant extends Model
|
||||
'variant_id',
|
||||
'attachment_id'
|
||||
)
|
||||
->withPivot('orden')
|
||||
->withPivot(['orden', 'is_enabled'])
|
||||
->orderByPivot('orden');
|
||||
|
||||
if ($this->catalog_item_id !== null) {
|
||||
@@ -113,6 +122,42 @@ class Variant extends Model
|
||||
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>> */
|
||||
public function selectionValues(): Collection
|
||||
{
|
||||
@@ -230,6 +275,25 @@ class Variant extends Model
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, ItemAttribute> $itemAttributes
|
||||
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
|
||||
*/
|
||||
public function selectorOptions(Collection $itemAttributes): Collection
|
||||
{
|
||||
$visibleAttributeCodes = $itemAttributes
|
||||
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->show_in_selector)
|
||||
->map(fn (ItemAttribute $itemAttribute): ?string => $itemAttribute->attribute?->codigo)
|
||||
->filter()
|
||||
->values();
|
||||
|
||||
return $this->selectionOptions($itemAttributes)
|
||||
->filter(
|
||||
fn (array $option, string $attributeCode): bool => $visibleAttributeCodes
|
||||
->contains($attributeCode)
|
||||
);
|
||||
}
|
||||
|
||||
/** @return Collection<int, EventDate> */
|
||||
public function selectedEventDates(): Collection
|
||||
{
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class CatalogVariantOptionsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'selected_values' => ['sometimes', 'array'],
|
||||
'selected_values.*' => ['nullable'],
|
||||
'cart_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@ namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Enums\InventorySubject;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -54,10 +54,9 @@ class StoreCatalogItemRequest extends FormRequest
|
||||
'descripcion' => ['sometimes', 'nullable', 'string'],
|
||||
'precio' => ['required', 'numeric', 'min:0'],
|
||||
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::class)],
|
||||
'inventory_subject' => ['sometimes', Rule::enum(InventorySubject::class)],
|
||||
'max_units_per_user' => ['sometimes', 'nullable', 'integer', 'min:1'],
|
||||
'has_tickets' => [Rule::prohibitedIf($isBundle), 'sometimes', 'boolean'],
|
||||
'ticket_generation_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(TicketGenerationPolicy::class)],
|
||||
'validity_time_id' => [Rule::prohibitedIf($isBundle), 'sometimes', 'nullable', 'integer', Rule::exists('validity_times', 'id')],
|
||||
'real_stock' => [Rule::prohibitedIf($isBundle), 'sometimes', 'integer', 'min:0'],
|
||||
'inventory_id' => ['prohibited'],
|
||||
'reserved_stock' => ['prohibited'],
|
||||
@@ -80,6 +79,15 @@ class StoreCatalogItemRequest extends FormRequest
|
||||
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.*' => ['required', new ImageOrBase64Rule],
|
||||
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
|
||||
@@ -7,7 +7,6 @@ use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -25,15 +24,16 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
return $this->columnWithImageData($catalogItem);
|
||||
}
|
||||
|
||||
return [
|
||||
if ($featuredGroup->product_layout === ProductLayout::TicketSelector) {
|
||||
return $this->ticketSelectorData($catalogItem);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
|
||||
'validity_time_id' => $catalogItem->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||
'stock_tecnico' => $catalogItem->availableStock(),
|
||||
'variants' => $catalogItem->visibleVariants()
|
||||
->map(fn (Variant $variant): array => [
|
||||
@@ -47,29 +47,46 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectionOptions($catalogItem->itemAttributes),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
])
|
||||
->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> */
|
||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||
{
|
||||
$attachment = $catalogItem->attachments->first()
|
||||
?? $catalogItem->variants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return [
|
||||
'id' => $catalogItem->id,
|
||||
'type' => $catalogItem->type->value,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'precio' => $catalogItem->precio,
|
||||
'ticket_generation_policy' => $catalogItem->ticket_generation_policy->value,
|
||||
'validity_time_id' => $catalogItem->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($catalogItem->validityTime),
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'image' => $this->firstImageUrl($catalogItem),
|
||||
];
|
||||
}
|
||||
|
||||
private function firstImageUrl(CatalogItem $catalogItem): ?string
|
||||
{
|
||||
$attachment = $catalogItem->attachments->first()
|
||||
?? $catalogItem->variants
|
||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||
->first();
|
||||
|
||||
return $attachment?->getTemporaryUrl(1440);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,13 +33,9 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'category' => $this->category?->nombre,
|
||||
'brand' => $this->brand?->nombre,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => $this->validityTime === null
|
||||
? null
|
||||
: ValidityTimeResource::make($this->validityTime),
|
||||
'attributes' => $this->attributesData(),
|
||||
'stock_tecnico' => $this->when(
|
||||
$selectedVariant === null,
|
||||
@@ -88,6 +84,7 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'codigo' => $attribute->codigo,
|
||||
'nombre' => $attribute->nombre,
|
||||
'sort_order' => $itemAttribute->sort_order,
|
||||
'show_in_selector' => $itemAttribute->show_in_selector,
|
||||
'is_required' => $attribute->is_required,
|
||||
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
||||
'metadata_schema' => $attribute->metadata_schema,
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -23,14 +22,9 @@ class CatalogItemResource extends JsonResource
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'inventory_policy' => $this->inventory_policy?->value,
|
||||
'inventory_subject' => $this->inventory_subject->value,
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => $this->whenLoaded(
|
||||
'validityTime',
|
||||
fn () => ValidityTimeResource::make($this->validityTime),
|
||||
),
|
||||
'real_stock' => $this->whenLoaded('inventory', fn () => $this->inventory?->real_stock),
|
||||
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
@@ -45,7 +39,7 @@ class CatalogItemResource extends JsonResource
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'real_stock' => $variant->inventory?->real_stock,
|
||||
'values' => $variant->selectionOptions($this->itemAttributes),
|
||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||
'images' => $variant->attachments
|
||||
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
|
||||
->values(),
|
||||
|
||||
@@ -5,7 +5,6 @@ namespace App\Domains\Catalog\Resources;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -26,9 +25,6 @@ class CatalogSearchItemResource extends JsonResource
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'ticket_generation_policy' => $this->ticket_generation_policy->value,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($this->validityTime),
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'stock_tecnico' => $this->availableStock(),
|
||||
'variants' => $this->visibleVariants()
|
||||
@@ -43,7 +39,7 @@ class CatalogSearchItemResource extends JsonResource
|
||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
'values' => $variant->selectionOptions($this->itemAttributes),
|
||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class CatalogVariantOptionsResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return $this->resource;
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ class CatalogService
|
||||
$images = $data['images'] ?? [];
|
||||
$attributeCodes = $data['attribute_codes'] ?? [];
|
||||
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
|
||||
$hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? [];
|
||||
$components = $data['components'] ?? [];
|
||||
$hasDirectStock = array_key_exists('real_stock', $data);
|
||||
$realStock = (int) ($data['real_stock'] ?? 0);
|
||||
@@ -64,6 +65,14 @@ class CatalogService
|
||||
]);
|
||||
}
|
||||
|
||||
if (array_diff($hiddenAttributeCodes, $attributeCodes) !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'hidden_attribute_codes' => [
|
||||
__('api.catalog.hidden_attribute_not_on_item'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->validateUniqueVariantCombinations($variants, $attributeCodes);
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
@@ -88,6 +97,7 @@ class CatalogService
|
||||
$data['images'],
|
||||
$data['attribute_codes'],
|
||||
$data['multi_select_attribute_codes'],
|
||||
$data['hidden_attribute_codes'],
|
||||
$data['components'],
|
||||
$data['real_stock'],
|
||||
$data['reserved_stock'],
|
||||
@@ -109,7 +119,12 @@ class CatalogService
|
||||
|
||||
$catalogItem = CatalogItem::query()->create($data);
|
||||
$itemAttributes = $type === CatalogItemType::Standard
|
||||
? $this->createItemAttributes($catalogItem, $attributeCodes, $multiSelectAttributeCodes)
|
||||
? $this->createItemAttributes(
|
||||
$catalogItem,
|
||||
$attributeCodes,
|
||||
$multiSelectAttributeCodes,
|
||||
$hiddenAttributeCodes,
|
||||
)
|
||||
: [];
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
@@ -145,7 +160,6 @@ class CatalogService
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
@@ -165,7 +179,6 @@ class CatalogService
|
||||
'inventory',
|
||||
'category',
|
||||
'brand',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute.options.validityTime',
|
||||
'itemAttributes.attribute.eventDates.validityTime',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
@@ -226,7 +239,6 @@ class CatalogService
|
||||
->with([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
@@ -262,7 +274,6 @@ class CatalogService
|
||||
->with([
|
||||
'attachments',
|
||||
'inventory',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
@@ -279,32 +290,8 @@ class CatalogService
|
||||
public function delete(CatalogItem $catalogItem): void
|
||||
{
|
||||
DB::transaction(function () use ($catalogItem): void {
|
||||
$catalogItem->load([
|
||||
'attachments',
|
||||
'variants.attachments',
|
||||
]);
|
||||
|
||||
$attachments = $catalogItem->attachments
|
||||
->merge($catalogItem->variants->flatMap->attachments)
|
||||
->unique('id');
|
||||
$inventoryIds = collect([$catalogItem->inventory_id])
|
||||
->merge($catalogItem->variants->pluck('inventory_id'))
|
||||
->filter()
|
||||
->unique();
|
||||
|
||||
$catalogItem->attachments()->detach();
|
||||
foreach ($catalogItem->variants as $variant) {
|
||||
$variant->attachments()->detach();
|
||||
}
|
||||
|
||||
$catalogItem->variants()->delete();
|
||||
$catalogItem->delete();
|
||||
Inventory::query()->whereKey($inventoryIds)->delete();
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
$this->attachmentService->delete($attachment);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -312,32 +299,19 @@ class CatalogService
|
||||
{
|
||||
DB::transaction(function () use ($variant): void {
|
||||
$variant = Variant::query()
|
||||
->with('attachments')
|
||||
->lockForUpdate()
|
||||
->findOrFail($variant->getKey());
|
||||
$catalogItem = CatalogItem::query()
|
||||
->lockForUpdate()
|
||||
->findOrFail($variant->catalog_item_id);
|
||||
$attachments = $variant->attachments;
|
||||
$inventoryId = $variant->inventory_id;
|
||||
|
||||
$variant->attachments()->detach();
|
||||
$variant->delete();
|
||||
Inventory::query()->whereKey($inventoryId)->delete();
|
||||
|
||||
$minimumPrice = $catalogItem->variants()->min('precio');
|
||||
|
||||
if ($minimumPrice === null) {
|
||||
if (! $catalogItem->variants()->exists()) {
|
||||
$this->delete($catalogItem);
|
||||
} else {
|
||||
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) {
|
||||
$catalogItem->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
foreach ($attachments as $attachment) {
|
||||
if (! DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
$this->attachmentService->delete($attachment);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -442,8 +416,6 @@ class CatalogService
|
||||
'attribute_codes',
|
||||
'variants',
|
||||
'has_tickets',
|
||||
'ticket_generation_policy',
|
||||
'validity_time_id',
|
||||
] as $field) {
|
||||
if (array_key_exists($field, $data)) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -488,12 +460,14 @@ class CatalogService
|
||||
/**
|
||||
* @param array<int, string> $attributeCodes
|
||||
* @param array<int, string> $multiSelectAttributeCodes
|
||||
* @param array<int, string> $hiddenAttributeCodes
|
||||
* @return array<string, ItemAttribute>
|
||||
*/
|
||||
private function createItemAttributes(
|
||||
CatalogItem $catalogItem,
|
||||
array $attributeCodes,
|
||||
array $multiSelectAttributeCodes = [],
|
||||
array $hiddenAttributeCodes = [],
|
||||
): array {
|
||||
$itemAttributes = [];
|
||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||
@@ -517,6 +491,7 @@ class CatalogService
|
||||
$itemAttribute = $catalogItem->itemAttributes()->create([
|
||||
'attribute_id' => $attribute->id,
|
||||
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
|
||||
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
|
||||
]);
|
||||
|
||||
$itemAttributes[$attributeCode] = $itemAttribute;
|
||||
@@ -713,16 +688,6 @@ class CatalogService
|
||||
]);
|
||||
}
|
||||
|
||||
$validityTimeIds = $resolvedOptions
|
||||
->pluck('validity_time_id')
|
||||
->filter()
|
||||
->unique();
|
||||
if ($validityTimeIds->count() > 1) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => [__('api.catalog.incompatible_validity_windows')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $resolvedOptions->pluck('value')->all();
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,13 @@ class FeaturedGroupService
|
||||
public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
||||
{
|
||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||
$items = $this->itemsQuery($featuredGroup)->get();
|
||||
$query = $this->itemsQuery($featuredGroup);
|
||||
|
||||
if ($featuredGroup->group_layout === GroupLayout::Single) {
|
||||
$query->limit(1);
|
||||
}
|
||||
|
||||
$items = $query->get();
|
||||
$this->attachGroup($items, $featuredGroup);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||
@@ -41,7 +47,6 @@ class FeaturedGroupService
|
||||
->with([
|
||||
'inventory',
|
||||
'attachments',
|
||||
'validityTime',
|
||||
'itemAttributes.attribute',
|
||||
'variants.inventory',
|
||||
'variants.attachments',
|
||||
|
||||
225
app/Domains/Catalog/Services/VariantSelectionService.php
Normal file
225
app/Domains/Catalog/Services/VariantSelectionService.php
Normal file
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class VariantSelectionService
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $selectedValues
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function options(
|
||||
CatalogItem $catalogItem,
|
||||
array $selectedValues,
|
||||
?int $includedVariantId = null,
|
||||
): array {
|
||||
$catalogItem->load([
|
||||
'itemAttributes.attribute',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.inventory',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.definitions.itemAttribute.attribute.options',
|
||||
]);
|
||||
|
||||
$variants = $catalogItem->visibleVariants($includedVariantId)
|
||||
->values();
|
||||
$normalizedSelections = collect($selectedValues)
|
||||
->mapWithKeys(fn ($value, string $key): array => [$key => $this->normalizeValue($value)])
|
||||
->filter(fn ($value): bool => $value !== null && $value !== '' && $value !== [])
|
||||
->all();
|
||||
$matchingVariants = $variants
|
||||
->filter(fn (Variant $variant): bool => $this->matches($variant, $normalizedSelections))
|
||||
->values();
|
||||
$attributeKeys = $this->attributeKeys($catalogItem, $catalogItem->variants->values());
|
||||
$isComplete = $attributeKeys->isNotEmpty()
|
||||
&& $attributeKeys->every(fn (string $key): bool => array_key_exists($key, $normalizedSelections));
|
||||
$resolvedVariant = $isComplete && $matchingVariants->count() === 1
|
||||
? $matchingVariants->first()
|
||||
: null;
|
||||
|
||||
return [
|
||||
'variants' => $variants
|
||||
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
|
||||
->values()
|
||||
->all(),
|
||||
'selectors' => $this->selectors(
|
||||
$catalogItem,
|
||||
$variants,
|
||||
$attributeKeys,
|
||||
$matchingVariants->isEmpty() ? [] : $normalizedSelections,
|
||||
),
|
||||
'selected_values' => (object) ($matchingVariants->isEmpty() ? [] : $normalizedSelections),
|
||||
'resolved_variant' => $resolvedVariant === null
|
||||
? null
|
||||
: $this->variantData($catalogItem, $resolvedVariant),
|
||||
'valid' => $matchingVariants->isNotEmpty(),
|
||||
'available_variant_count' => $variants->count(),
|
||||
'matching_variant_count' => $matchingVariants->count(),
|
||||
'price_range' => $this->priceRange($catalogItem, $variants),
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $selectedValues */
|
||||
private function matches(Variant $variant, array $selectedValues): bool
|
||||
{
|
||||
$variantValues = $variant->selectionValues();
|
||||
|
||||
foreach ($selectedValues as $key => $selectedValue) {
|
||||
if (! $variantValues->has($key)
|
||||
|| $this->valueKey($variantValues->get($key)) !== $this->valueKey($selectedValue)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param Collection<int, Variant> $variants */
|
||||
private function attributeKeys(CatalogItem $catalogItem, Collection $variants): Collection
|
||||
{
|
||||
return $variants
|
||||
->flatMap(fn (Variant $variant): array => $variant
|
||||
->selectorOptions($catalogItem->itemAttributes)
|
||||
->keys()
|
||||
->all())
|
||||
->unique()
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Variant> $variants
|
||||
* @param Collection<int, string> $attributeKeys
|
||||
* @param array<string, mixed> $selectedValues
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function selectors(
|
||||
CatalogItem $catalogItem,
|
||||
Collection $variants,
|
||||
Collection $attributeKeys,
|
||||
array $selectedValues,
|
||||
): array {
|
||||
return $attributeKeys
|
||||
->map(function (string $key, int $index) use (
|
||||
$catalogItem,
|
||||
$variants,
|
||||
$attributeKeys,
|
||||
$selectedValues,
|
||||
): array {
|
||||
$previousKeys = $attributeKeys->take($index);
|
||||
$previousSelections = collect($selectedValues)
|
||||
->only($previousKeys->all())
|
||||
->all();
|
||||
$compatibleVariants = $variants
|
||||
->filter(fn (Variant $variant): bool => $this->matches($variant, $previousSelections));
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'label' => $this->attributeLabel($catalogItem, $key),
|
||||
'options' => $this->optionsFor($catalogItem, $compatibleVariants, $key),
|
||||
'enabled' => $index === 0 || $previousKeys->every(
|
||||
fn (string $previousKey): bool => array_key_exists($previousKey, $selectedValues),
|
||||
),
|
||||
];
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Variant> $variants
|
||||
* @return list<mixed>
|
||||
*/
|
||||
private function optionsFor(CatalogItem $catalogItem, Collection $variants, string $key): array
|
||||
{
|
||||
$options = [];
|
||||
$seen = [];
|
||||
|
||||
foreach ($variants as $variant) {
|
||||
$option = $variant->selectorOptions($catalogItem->itemAttributes)->get($key);
|
||||
if ($option === null || $option === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$optionKey = $this->valueKey($option);
|
||||
if (isset($seen[$optionKey])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$seen[$optionKey] = true;
|
||||
$options[] = $option;
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
private function attributeLabel(CatalogItem $catalogItem, string $key): string
|
||||
{
|
||||
if ($key === 'event_date') {
|
||||
return 'Fecha';
|
||||
}
|
||||
|
||||
return $catalogItem->itemAttributes
|
||||
->first(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute?->codigo === $key)
|
||||
?->attribute
|
||||
?->nombre ?? str($key)->headline()->toString();
|
||||
}
|
||||
|
||||
/** @param Collection<int, Variant> $variants */
|
||||
private function priceRange(CatalogItem $catalogItem, Collection $variants): array
|
||||
{
|
||||
$prices = $variants
|
||||
->map(fn (Variant $variant): float => $variant->getPrice())
|
||||
->whenEmpty(fn (Collection $prices): Collection => $prices->push($catalogItem->getPrice()));
|
||||
|
||||
return [
|
||||
'minimum' => number_format((float) $prices->min(), 2, '.', ''),
|
||||
'maximum' => number_format((float) $prices->max(), 2, '.', ''),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizeValue(mixed $value): mixed
|
||||
{
|
||||
if (is_array($value) && array_key_exists('value', $value)) {
|
||||
return (string) $value['value'];
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return array_map(fn ($item) => $this->normalizeValue($item), $value);
|
||||
}
|
||||
|
||||
return is_scalar($value) ? (string) $value : null;
|
||||
}
|
||||
|
||||
private function valueKey(mixed $value): string
|
||||
{
|
||||
$normalized = $this->normalizeValue($value);
|
||||
|
||||
if (is_array($normalized)) {
|
||||
sort($normalized);
|
||||
}
|
||||
|
||||
return json_encode($normalized, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::get('categories/{category}', [CatalogController::class, 'category'])
|
||||
->name('categories.show');
|
||||
Route::get('catalog-items/{catalogItem}', [CatalogController::class, 'show']);
|
||||
Route::post('catalog-items/{catalogItem}/variant-options', [CatalogController::class, 'variantOptions']);
|
||||
Route::post('catalog-items', [CatalogController::class, 'store']);
|
||||
});
|
||||
|
||||
|
||||
47
app/Domains/Client/Controllers/ClientController.php
Normal file
47
app/Domains/Client/Controllers/ClientController.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Client\Requests\StoreClientRequest;
|
||||
use App\Domains\Client\Requests\UpdateClientRequest;
|
||||
use App\Domains\Client\Resources\ClientResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class ClientController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return ClientResource::collection(
|
||||
Client::query()->with('tenants')->latest()->paginateFromRequest()
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StoreClientRequest $request): JsonResponse
|
||||
{
|
||||
return ClientResource::make(
|
||||
Client::query()->create($request->validated())->load('tenants')
|
||||
)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Client $client): ClientResource
|
||||
{
|
||||
return ClientResource::make($client->load('tenants'));
|
||||
}
|
||||
|
||||
public function update(UpdateClientRequest $request, Client $client): ClientResource
|
||||
{
|
||||
$client->update($request->validated());
|
||||
|
||||
return ClientResource::make($client->fresh()->load('tenants'));
|
||||
}
|
||||
|
||||
public function destroy(Client $client): Response
|
||||
{
|
||||
$client->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
30
app/Domains/Client/Models/Client.php
Normal file
30
app/Domains/Client/Models/Client.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Models;
|
||||
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable(['code', 'name'])]
|
||||
class Client extends Model
|
||||
{
|
||||
public function getRouteKeyName(): string
|
||||
{
|
||||
return 'code';
|
||||
}
|
||||
|
||||
/** @return HasMany<Tenant, $this> */
|
||||
public function tenants(): HasMany
|
||||
{
|
||||
return $this->hasMany(Tenant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<ClientIntegration, $this> */
|
||||
public function integrations(): HasMany
|
||||
{
|
||||
return $this->hasMany(ClientIntegration::class);
|
||||
}
|
||||
}
|
||||
22
app/Domains/Client/Requests/StoreClientRequest.php
Normal file
22
app/Domains/Client/Requests/StoreClientRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'code' => ['required', 'string', 'max:255', Rule::unique('clients', 'code')],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Client/Requests/UpdateClientRequest.php
Normal file
26
app/Domains/Client/Requests/UpdateClientRequest.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var Client|null $client */
|
||||
$client = $this->route('client');
|
||||
|
||||
return [
|
||||
'code' => ['sometimes', 'string', 'max:255', Rule::unique('clients', 'code')->ignore($client?->id)],
|
||||
'name' => ['sometimes', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Client/Resources/ClientResource.php
Normal file
26
app/Domains/Client/Resources/ClientResource.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Resources;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Client */
|
||||
class ClientResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'name' => $this->name,
|
||||
'tenants' => $this->whenLoaded('tenants', fn () => $this->tenants->map(fn ($tenant): array => [
|
||||
'id' => $tenant->id,
|
||||
'codigo' => $tenant->codigo,
|
||||
'nombre' => $tenant->nombre,
|
||||
'dominio' => $tenant->dominio,
|
||||
])),
|
||||
];
|
||||
}
|
||||
}
|
||||
6
app/Domains/Client/routes/api.php
Normal file
6
app/Domains/Client/routes/api.php
Normal file
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Client\Controllers\ClientController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('clients', ClientController::class);
|
||||
57
app/Domains/Desfile/Controllers/EntryController.php
Normal file
57
app/Domains/Desfile/Controllers/EntryController.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Controllers;
|
||||
|
||||
use App\Domains\Desfile\Requests\ReplaceEntryImageRequest;
|
||||
use App\Domains\Desfile\Requests\SyncEntryRowsRequest;
|
||||
use App\Domains\Desfile\Requests\UpdateEntryImageRequest;
|
||||
use App\Domains\Desfile\Resources\EntryResource;
|
||||
use App\Domains\Desfile\Services\EntryService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class EntryController extends Controller
|
||||
{
|
||||
public function __construct(private readonly EntryService $entryService) {}
|
||||
|
||||
public function show(Request $request): EntryResource
|
||||
{
|
||||
return new EntryResource(
|
||||
$this->entryService->current($request->user()->tenant()->firstOrFail()),
|
||||
);
|
||||
}
|
||||
|
||||
public function update(SyncEntryRowsRequest $request): EntryResource
|
||||
{
|
||||
return new EntryResource($this->entryService->syncRows(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->validated('rows'),
|
||||
));
|
||||
}
|
||||
|
||||
public function replaceImage(ReplaceEntryImageRequest $request): JsonResponse
|
||||
{
|
||||
return (new EntryResource($this->entryService->replaceImage(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->file('image'),
|
||||
$request->boolean('is_enabled', true),
|
||||
)))->response();
|
||||
}
|
||||
|
||||
public function updateImage(UpdateEntryImageRequest $request): EntryResource
|
||||
{
|
||||
return new EntryResource($this->entryService->updateImage(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->boolean('is_enabled'),
|
||||
));
|
||||
}
|
||||
|
||||
public function destroyImage(Request $request): Response
|
||||
{
|
||||
$this->entryService->deleteImage($request->user()->tenant()->firstOrFail());
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
22
app/Domains/Desfile/Requests/ReplaceEntryImageRequest.php
Normal file
22
app/Domains/Desfile/Requests/ReplaceEntryImageRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ReplaceEntryImageRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'image' => ['required', 'image', 'mimes:jpeg,jpg,png,webp', 'max:10240'],
|
||||
'is_enabled' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
55
app/Domains/Desfile/Requests/SyncEntryRowsRequest.php
Normal file
55
app/Domains/Desfile/Requests/SyncEntryRowsRequest.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class SyncEntryRowsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'rows' => ['required', 'array', 'min:1', 'max:1000'],
|
||||
'rows.*' => ['required', 'array:type,sector,row,max_seat,price'],
|
||||
'rows.*.type' => ['required', 'string', 'max:100'],
|
||||
'rows.*.sector' => ['required', 'string', 'max:100'],
|
||||
'rows.*.row' => ['required', 'integer', 'between:1,5'],
|
||||
'rows.*.max_seat' => ['required', 'integer', 'between:1,100'],
|
||||
'rows.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<int, callable> */
|
||||
public function after(): array
|
||||
{
|
||||
return [function (Validator $validator): void {
|
||||
$combinations = [];
|
||||
|
||||
foreach ($this->input('rows', []) as $index => $row) {
|
||||
if (! is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$combination = collect(['type', 'sector', 'row'])
|
||||
->map(fn (string $field): string => mb_strtolower(trim((string) ($row[$field] ?? ''))))
|
||||
->implode('|');
|
||||
|
||||
if (isset($combinations[$combination])) {
|
||||
$validator->errors()->add(
|
||||
"rows.{$index}",
|
||||
'La combinación de tipo, sector y fila no puede repetirse.',
|
||||
);
|
||||
}
|
||||
|
||||
$combinations[$combination] = true;
|
||||
}
|
||||
}];
|
||||
}
|
||||
}
|
||||
21
app/Domains/Desfile/Requests/UpdateEntryImageRequest.php
Normal file
21
app/Domains/Desfile/Requests/UpdateEntryImageRequest.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateEntryImageRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'is_enabled' => ['required', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
56
app/Domains/Desfile/Resources/EntryResource.php
Normal file
56
app/Domains/Desfile/Resources/EntryResource.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Resources;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class EntryResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$image = $this->allAttachments->first();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'rows' => $this->variants
|
||||
->map(function ($variant): array {
|
||||
$values = $variant->selectionValues();
|
||||
|
||||
return [
|
||||
'type' => $values->get('tipo'),
|
||||
'sector' => $values->get('sector'),
|
||||
'row' => $values->get('fila'),
|
||||
'seat' => (int) $values->get('asiento'),
|
||||
'price' => $variant->getPrice(),
|
||||
];
|
||||
})
|
||||
->groupBy(fn (array $variant): string => implode('|', [
|
||||
mb_strtolower(trim((string) $variant['type'])),
|
||||
mb_strtolower(trim((string) $variant['sector'])),
|
||||
mb_strtolower(trim((string) $variant['row'])),
|
||||
]))
|
||||
->map(function ($variants): array {
|
||||
$first = $variants->first();
|
||||
|
||||
return [
|
||||
'type' => $first['type'],
|
||||
'sector' => $first['sector'],
|
||||
'row' => $first['row'],
|
||||
'max_seat' => $variants->max('seat'),
|
||||
'price' => number_format($first['price'], 2, '.', ''),
|
||||
];
|
||||
})
|
||||
->values(),
|
||||
'image' => $image === null ? null : [
|
||||
'key' => $image->key,
|
||||
'filename' => $image->filename,
|
||||
'url' => $image->getTemporaryUrl(1440),
|
||||
'is_enabled' => (bool) $image->pivot->is_enabled,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
302
app/Domains/Desfile/Services/EntryService.php
Normal file
302
app/Domains/Desfile/Services/EntryService.php
Normal file
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Services;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Throwable;
|
||||
|
||||
class EntryService
|
||||
{
|
||||
private const ATTRIBUTE_MAP = [
|
||||
'type' => 'tipo',
|
||||
'sector' => 'sector',
|
||||
'row' => 'fila',
|
||||
'seat' => 'asiento',
|
||||
];
|
||||
|
||||
private const ROW_ATTRIBUTE_MAP = [
|
||||
'type' => 'tipo',
|
||||
'sector' => 'sector',
|
||||
'row' => 'fila',
|
||||
];
|
||||
|
||||
public function __construct(private readonly AttachmentService $attachmentService) {}
|
||||
|
||||
public function current(Tenant $tenant): CatalogItem
|
||||
{
|
||||
return $this->entryQuery($tenant)
|
||||
->with([
|
||||
'allAttachments',
|
||||
'itemAttributes.attribute.options',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.inventory',
|
||||
'variants.definitions.itemAttribute.attribute',
|
||||
])
|
||||
->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $rows
|
||||
*/
|
||||
public function syncRows(Tenant $tenant, array $rows): CatalogItem
|
||||
{
|
||||
DB::transaction(function () use ($tenant, $rows): void {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$itemAttributes = $this->itemAttributes($entry);
|
||||
$existingVariants = $entry->variants()
|
||||
->with(['inventory', 'definitions.itemAttribute.attribute'])
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$existingBySelection = $existingVariants->keyBy(
|
||||
fn (Variant $variant): string => $this->selectionKey($variant->selectionValues()->all()),
|
||||
);
|
||||
$desiredSelections = collect();
|
||||
|
||||
foreach (array_values($rows) as $index => $data) {
|
||||
$rowValues = $this->resolveRowValues($itemAttributes, $data, $index);
|
||||
|
||||
foreach (range(1, (int) $data['max_seat']) as $seat) {
|
||||
$values = [
|
||||
...$rowValues,
|
||||
'asiento' => $this->resolveAttributeValue(
|
||||
$itemAttributes,
|
||||
'asiento',
|
||||
(string) $seat,
|
||||
"rows.{$index}.max_seat",
|
||||
),
|
||||
];
|
||||
$selectionKey = $this->selectionKey($values);
|
||||
$desiredSelections->put($selectionKey, true);
|
||||
$variant = $existingBySelection->get($selectionKey);
|
||||
|
||||
if ($variant === null) {
|
||||
$variant = $entry->variants()->create([
|
||||
'inventory_id' => Inventory::query()->create(['real_stock' => 1])->id,
|
||||
'descripcion' => $this->description($values),
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
$variant->definitions()->createMany(
|
||||
collect($values)->map(
|
||||
fn (string $value, string $code): array => [
|
||||
'item_attribute_id' => $itemAttributes[$code]->id,
|
||||
'value' => $value,
|
||||
],
|
||||
)->values()->all(),
|
||||
);
|
||||
} else {
|
||||
$variant->update([
|
||||
'descripcion' => $this->description($values),
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($existingVariants as $variant) {
|
||||
$selectionKey = $this->selectionKey($variant->selectionValues()->all());
|
||||
if ($desiredSelections->has($selectionKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->assertVariantCanChangeIdentity($variant, 'rows');
|
||||
$variant->delete();
|
||||
}
|
||||
|
||||
$minimumPrice = $entry->variants()->min('precio');
|
||||
if ($minimumPrice !== null) {
|
||||
$entry->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
});
|
||||
|
||||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function replaceImage(
|
||||
Tenant $tenant,
|
||||
UploadedFile $image,
|
||||
bool $isEnabled,
|
||||
): CatalogItem {
|
||||
$attachment = $this->attachmentService->store($image, 'catalog-items');
|
||||
$previousAttachments = collect();
|
||||
|
||||
try {
|
||||
DB::transaction(function () use ($tenant, $attachment, $isEnabled, &$previousAttachments): void {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$previousAttachments = $entry->allAttachments()->get();
|
||||
$entry->allAttachments()->sync([
|
||||
$attachment->id => [
|
||||
'orden' => 0,
|
||||
'is_enabled' => $isEnabled,
|
||||
],
|
||||
]);
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
$this->deleteAttachmentQuietly($attachment);
|
||||
throw $throwable;
|
||||
}
|
||||
|
||||
$previousAttachments->each(fn (Attachment $previous) => $this->deleteIfUnused($previous));
|
||||
|
||||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function updateImage(Tenant $tenant, bool $isEnabled): CatalogItem
|
||||
{
|
||||
DB::transaction(function () use ($tenant, $isEnabled): void {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
||||
|
||||
$entry->allAttachments()->updateExistingPivot($attachment->id, [
|
||||
'is_enabled' => $isEnabled,
|
||||
]);
|
||||
});
|
||||
|
||||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function deleteImage(Tenant $tenant): void
|
||||
{
|
||||
$attachment = DB::transaction(function () use ($tenant): Attachment {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
||||
$entry->allAttachments()->detach($attachment->id);
|
||||
|
||||
return $attachment;
|
||||
});
|
||||
|
||||
$this->deleteIfUnused($attachment);
|
||||
}
|
||||
|
||||
/** @return Collection<string, ItemAttribute> */
|
||||
private function itemAttributes(CatalogItem $entry): Collection
|
||||
{
|
||||
$attributes = $entry->itemAttributes()
|
||||
->with('attribute.options')
|
||||
->get()
|
||||
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute !== null)
|
||||
->keyBy(fn (ItemAttribute $itemAttribute): string => $itemAttribute->attribute->codigo);
|
||||
$missing = collect(self::ATTRIBUTE_MAP)->diff($attributes->keys());
|
||||
|
||||
if ($missing->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => [
|
||||
'Faltan atributos requeridos para las entradas del desfile: '.$missing->implode(', ').'.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function resolveRowValues(Collection $itemAttributes, array $data, int $index): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach (self::ROW_ATTRIBUTE_MAP as $input => $code) {
|
||||
$values[$code] = $this->resolveAttributeValue(
|
||||
$itemAttributes,
|
||||
$code,
|
||||
(string) $data[$input],
|
||||
"rows.{$index}.{$input}",
|
||||
);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/** @param Collection<string, ItemAttribute> $itemAttributes */
|
||||
private function resolveAttributeValue(
|
||||
Collection $itemAttributes,
|
||||
string $code,
|
||||
string $requestedValue,
|
||||
string $errorKey,
|
||||
): string {
|
||||
$requestedValue = trim($requestedValue);
|
||||
$option = $itemAttributes[$code]->attribute->options->first(
|
||||
fn ($candidate): bool => $this->normalize($candidate->value) === $this->normalize($requestedValue),
|
||||
);
|
||||
|
||||
if ($option === null) {
|
||||
throw ValidationException::withMessages([
|
||||
$errorKey => ['La opción seleccionada no es válida.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $option->value;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $values */
|
||||
private function selectionKey(array $values): string
|
||||
{
|
||||
return collect(self::ATTRIBUTE_MAP)
|
||||
->map(fn (string $code): string => $this->normalize((string) ($values[$code] ?? '')))
|
||||
->implode('|');
|
||||
}
|
||||
|
||||
private function assertVariantCanChangeIdentity(Variant $variant, string $key): void
|
||||
{
|
||||
$inventory = $variant->inventory;
|
||||
|
||||
if (($inventory?->reserved_stock ?? 0) > 0 || ($inventory?->sold_units ?? 0) > 0) {
|
||||
throw ValidationException::withMessages([
|
||||
$key => [
|
||||
'No se puede modificar ni eliminar un asiento con ventas o reservas.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, string> $values */
|
||||
private function description(array $values): string
|
||||
{
|
||||
return "Sector {$values['sector']} - Fila {$values['fila']} - Asiento {$values['asiento']} - {$values['tipo']}";
|
||||
}
|
||||
|
||||
private function normalize(string $value): string
|
||||
{
|
||||
return Str::ascii(mb_strtolower(trim($value)));
|
||||
}
|
||||
|
||||
/** @return Builder<CatalogItem> */
|
||||
private function entryQuery(Tenant $tenant): Builder
|
||||
{
|
||||
return CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'entrada');
|
||||
}
|
||||
|
||||
private function deleteIfUnused(Attachment $attachment): void
|
||||
{
|
||||
if (DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->deleteAttachmentQuietly($attachment);
|
||||
}
|
||||
|
||||
private function deleteAttachmentQuietly(Attachment $attachment): void
|
||||
{
|
||||
try {
|
||||
$this->attachmentService->delete($attachment);
|
||||
} catch (Throwable $throwable) {
|
||||
report($throwable);
|
||||
}
|
||||
}
|
||||
}
|
||||
19
app/Domains/Desfile/routes/api.php
Normal file
19
app/Domains/Desfile/routes/api.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?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');
|
||||
});
|
||||
@@ -43,7 +43,6 @@ class EventDate extends Model
|
||||
$eventDate->syncTenantDateText();
|
||||
ValidityTime::query()
|
||||
->whereKey($eventDate->validity_time_id)
|
||||
->whereDoesntHave('ticketValidityGroups')
|
||||
->delete();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Event\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class EventService
|
||||
{
|
||||
@@ -60,7 +61,19 @@ class EventService
|
||||
}
|
||||
}
|
||||
|
||||
$existingDates->slice(count($dates))->each->delete();
|
||||
$datesToDelete = $existingDates->slice(count($dates));
|
||||
|
||||
if ($datesToDelete->contains(fn ($eventDate): bool => $eventDate
|
||||
->selectedByVariants()
|
||||
->whereHas('sourceTickets')
|
||||
->exists()
|
||||
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
|
||||
throw ValidationException::withMessages([
|
||||
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$datesToDelete->each->delete();
|
||||
$tenant->unsetRelation('eventDates');
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -126,18 +125,21 @@ class AccommodationService
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Alojamientos',
|
||||
]);
|
||||
$accommodation = CatalogItem::query()
|
||||
$accommodation = CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'alojamiento')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($accommodation !== null) {
|
||||
if ($accommodation->trashed()) {
|
||||
$accommodation->restore();
|
||||
}
|
||||
|
||||
$accommodation->update([
|
||||
'category_id' => $category->id,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
return $accommodation;
|
||||
@@ -152,7 +154,6 @@ class AccommodationService
|
||||
'precio' => collect($variants)->min('price') ?? 0,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -63,7 +62,6 @@ class EntryService
|
||||
'category_id' => $category->id,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'attribute_codes' => ['event_date'],
|
||||
'multi_select_attribute_codes' => ['event_date'],
|
||||
@@ -135,7 +133,6 @@ class EntryService
|
||||
'category_id' => $category->id,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
]);
|
||||
$variant->update([
|
||||
@@ -163,7 +160,7 @@ class EntryService
|
||||
|
||||
while (
|
||||
in_array($slug, $reservedSlugs, true)
|
||||
|| CatalogItem::query()
|
||||
|| CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', $slug)
|
||||
->exists()
|
||||
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -137,18 +136,21 @@ class FoodService
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Comidas',
|
||||
]);
|
||||
$food = CatalogItem::query()
|
||||
$food = CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($food !== null) {
|
||||
if ($food->trashed()) {
|
||||
$food->restore();
|
||||
}
|
||||
|
||||
$food->update([
|
||||
'category_id' => $category->id,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
return $food;
|
||||
@@ -163,7 +165,6 @@ class FoodService
|
||||
'precio' => collect($variants)->min('price') ?? 0,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -75,7 +74,6 @@ class MerchandiseService
|
||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
$itemAttributes = $this->itemAttributes($item, $attributes);
|
||||
@@ -200,7 +198,6 @@ class MerchandiseService
|
||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
@@ -414,7 +411,7 @@ class MerchandiseService
|
||||
|
||||
while (
|
||||
in_array($slug, $reservedSlugs, true)
|
||||
|| CatalogItem::query()
|
||||
|| CatalogItem::withTrashed()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', $slug)
|
||||
->exists()
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreClientIntegrationRequest;
|
||||
use App\Domains\Integration\Services\ClientIntegrationService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ClientIntegrationController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClientIntegrationService $clientIntegrationService,
|
||||
) {}
|
||||
|
||||
public function index(Client $client): JsonResponse
|
||||
{
|
||||
return response()->json($this->clientIntegrationService->getAllForClient($client));
|
||||
}
|
||||
|
||||
public function show(Client $client, string $integrationCode): JsonResponse
|
||||
{
|
||||
$integration = $this->clientIntegrationService->getClientIntegration($client, $integrationCode);
|
||||
|
||||
if (! $integration) {
|
||||
return response()->json([
|
||||
'code' => 'integration.not_configured',
|
||||
'message' => __('api.integration.not_configured'),
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function store(
|
||||
StoreClientIntegrationRequest $request,
|
||||
Client $client,
|
||||
string $integrationCode,
|
||||
): JsonResponse {
|
||||
$integration = Integration::query()
|
||||
->where('integration_code', $integrationCode)
|
||||
->firstOrFail();
|
||||
|
||||
try {
|
||||
$this->clientIntegrationService->updateOrCreateIntegration(
|
||||
$client,
|
||||
$integration,
|
||||
$request->input('integration_data', []),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.configured',
|
||||
'message' => __('api.integration.configured'),
|
||||
]);
|
||||
} catch (\Exception $exception) {
|
||||
return response()->json([
|
||||
'code' => 'integration.validation_failed',
|
||||
'message' => __('api.integration.validation_failed', ['error' => $exception->getMessage()]),
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Requests\TelepagosWebhookRequest;
|
||||
use App\Domains\Integration\Services\TelepagosWebhookService;
|
||||
use App\Http\Controllers\Controller;
|
||||
@@ -12,12 +13,12 @@ class TelepagosWebhookController extends Controller
|
||||
/**
|
||||
* Handle the incoming Telepagos webhook.
|
||||
*/
|
||||
public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
|
||||
public function handle(TelepagosWebhookRequest $request, Client $client, TelepagosWebhookService $service): JsonResponse
|
||||
{
|
||||
try {
|
||||
$cashinId = $request->validated('id');
|
||||
|
||||
$service->handleWebhook($tenantCodigo, $cashinId);
|
||||
$service->handleWebhook($client, $cashinId);
|
||||
|
||||
return response()->json(['status' => 'success']);
|
||||
} catch (\Exception $e) {
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreTenantIntegrationRequest;
|
||||
use App\Domains\Integration\Services\TenantIntegrationService;
|
||||
use Illuminate\Routing\Controller;
|
||||
|
||||
class TenantIntegrationController extends Controller
|
||||
{
|
||||
protected TenantIntegrationService $tenantIntegrationService;
|
||||
|
||||
public function __construct(TenantIntegrationService $tenantIntegrationService)
|
||||
{
|
||||
$this->tenantIntegrationService = $tenantIntegrationService;
|
||||
}
|
||||
|
||||
public function index(string $tenantCode)
|
||||
{
|
||||
return response()->json($this->tenantIntegrationService->getAllForTenant($tenantCode));
|
||||
}
|
||||
|
||||
public function show(string $tenantCode, string $integrationCode)
|
||||
{
|
||||
$integration = $this->tenantIntegrationService->getTenantIntegration($tenantCode, $integrationCode);
|
||||
|
||||
if (! $integration) {
|
||||
return response()->json([
|
||||
'code' => 'integration.not_configured',
|
||||
'message' => __('api.integration.not_configured'),
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function store(StoreTenantIntegrationRequest $request, string $tenantCode, string $integrationCode)
|
||||
{
|
||||
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
|
||||
|
||||
try {
|
||||
$this->tenantIntegrationService->updateOrCreateIntegration(
|
||||
$tenantCode,
|
||||
$integration,
|
||||
$request->input('integration_data', [])
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.configured',
|
||||
'message' => __('api.integration.configured'),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'code' => 'integration.validation_failed',
|
||||
'message' => __('api.integration.validation_failed', ['error' => $e->getMessage()]),
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,18 @@
|
||||
|
||||
namespace App\Domains\Integration\Models;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Casts\EncryptedIntegrationData;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class TenantIntegration extends Model
|
||||
class ClientIntegration extends Model
|
||||
{
|
||||
protected $table = 'tenant_integration';
|
||||
protected $hidden = ['integration_data'];
|
||||
|
||||
protected $fillable = [
|
||||
'client_id',
|
||||
'integration_code',
|
||||
'tenant_code',
|
||||
'integration_data',
|
||||
];
|
||||
|
||||
@@ -19,7 +21,14 @@ class TenantIntegration extends Model
|
||||
'integration_data' => EncryptedIntegrationData::class,
|
||||
];
|
||||
|
||||
public function integration()
|
||||
/** @return BelongsTo<Client, $this> */
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Client::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Integration, $this> */
|
||||
public function integration(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Integration::class, 'integration_code', 'integration_code');
|
||||
}
|
||||
@@ -13,16 +13,16 @@ class Integration extends Model
|
||||
'name',
|
||||
'url',
|
||||
'integration_data_schema',
|
||||
'requires_tenant_configuration',
|
||||
'requires_client_configuration',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'integration_data_schema' => 'array',
|
||||
'requires_tenant_configuration' => 'boolean',
|
||||
'requires_client_configuration' => 'boolean',
|
||||
];
|
||||
|
||||
public function tenantIntegrations()
|
||||
|
||||
public function clientIntegrations()
|
||||
{
|
||||
return $this->hasMany(TenantIntegration::class, 'integration_code', 'integration_code');
|
||||
return $this->hasMany(ClientIntegration::class, 'integration_code', 'integration_code');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Domains\Integration\Models\Integration;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class StoreTenantIntegrationRequest extends FormRequest
|
||||
class StoreClientIntegrationRequest extends FormRequest
|
||||
{
|
||||
protected ?Integration $integrationModel = null;
|
||||
|
||||
@@ -15,10 +15,12 @@ class StoreTenantIntegrationRequest extends FormRequest
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation()
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$integrationCode = $this->route('integration_code');
|
||||
$this->integrationModel = Integration::where('integration_code', $integrationCode)->first();
|
||||
$this->integrationModel = Integration::query()
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
|
||||
if (! $this->integrationModel) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -31,11 +33,8 @@ class StoreTenantIntegrationRequest extends FormRequest
|
||||
{
|
||||
$rules = [];
|
||||
|
||||
// Dynamic validation rules based on the integration data schema
|
||||
if ($this->integrationModel && $this->integrationModel->integration_data_schema) {
|
||||
foreach ($this->integrationModel->integration_data_schema as $field => $rule) {
|
||||
$rules['integration_data.'.$field] = $rule;
|
||||
}
|
||||
foreach ($this->integrationModel?->integration_data_schema ?? [] as $field => $rule) {
|
||||
$rules['integration_data.'.$field] = $rule;
|
||||
}
|
||||
|
||||
return $rules;
|
||||
@@ -18,7 +18,7 @@ class StoreIntegrationRequest extends FormRequest
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_tenant_configuration' => ['sometimes', 'boolean'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,14 +14,14 @@ class UpdateIntegrationRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
$integration = $this->route('integration');
|
||||
|
||||
|
||||
return [
|
||||
'name' => ['sometimes', 'required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_tenant_configuration' => ['sometimes', 'boolean'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
// the code shouldn't ideally be updatable, but if it is:
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,' . ($integration->id ?? '')],
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,'.($integration->id ?? '')],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,58 +2,54 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Exception;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
abstract class BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* The unique code of the integration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $integrationCode;
|
||||
|
||||
/**
|
||||
* The current tenant code.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $tenantCode;
|
||||
|
||||
protected ?Tenant $tenant = null;
|
||||
|
||||
protected ?Client $clientContext = null;
|
||||
|
||||
/**
|
||||
* The integration model instance.
|
||||
*
|
||||
* @var Integration|null
|
||||
*/
|
||||
protected ?Integration $integration = null;
|
||||
|
||||
/**
|
||||
* The tenant-specific integration model instance.
|
||||
*
|
||||
* @var TenantIntegration|null
|
||||
* The client-owned integration configuration.
|
||||
*/
|
||||
protected ?TenantIntegration $tenantIntegration = null;
|
||||
protected ?ClientIntegration $clientIntegration = null;
|
||||
|
||||
/**
|
||||
* Set the integration code.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
* @return $this
|
||||
*/
|
||||
public function setIntegrationCode(string $integrationCode): self
|
||||
{
|
||||
$this->integrationCode = $integrationCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the integration code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getIntegrationCode(): string
|
||||
{
|
||||
@@ -63,53 +59,69 @@ abstract class BaseIntegrationService
|
||||
/**
|
||||
* Set the tenant code and load the integration models.
|
||||
*
|
||||
* @param string $tenantCode
|
||||
* @return $this
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function forTenant(string $tenantCode): self
|
||||
{
|
||||
$this->tenantCode = $tenantCode;
|
||||
$this->tenant = Tenant::query()->with('client')->where('codigo', $tenantCode)->firstOrFail();
|
||||
$this->clientContext = $this->tenant->client;
|
||||
$this->loadIntegration();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function forClient(Client|string $client): self
|
||||
{
|
||||
$this->clientContext = $client instanceof Client
|
||||
? $client
|
||||
: Client::query()->where('code', $client)->firstOrFail();
|
||||
$this->tenant = null;
|
||||
$this->loadIntegration();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the Integration and TenantIntegration models.
|
||||
* Load the integration definition and its client-owned configuration.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function loadIntegration(): void
|
||||
{
|
||||
if (empty($this->integrationCode)) {
|
||||
throw new Exception("Integration code is not set.");
|
||||
throw new Exception('Integration code is not set.');
|
||||
}
|
||||
|
||||
$this->integration = Integration::where('integration_code', $this->integrationCode)->first();
|
||||
if (!$this->integration) {
|
||||
if (! $this->integration) {
|
||||
throw new Exception("Integration with code '{$this->integrationCode}' not found.");
|
||||
}
|
||||
|
||||
$this->tenantIntegration = TenantIntegration::where('tenant_code', $this->tenantCode)
|
||||
if (! $this->clientContext) {
|
||||
throw new Exception('Client context is not set.');
|
||||
}
|
||||
|
||||
$this->clientIntegration = ClientIntegration::where('client_id', $this->clientContext->id)
|
||||
->where('integration_code', $this->integrationCode)
|
||||
->first();
|
||||
|
||||
if (!$this->tenantIntegration && $this->integration->requires_tenant_configuration) {
|
||||
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
|
||||
if (! $this->clientIntegration && $this->integration->requires_client_configuration) {
|
||||
throw new Exception("Client '{$this->clientContext->code}' does not have integration '{$this->integrationCode}' configured.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the request URL.
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getUrl(string $path = ''): string
|
||||
{
|
||||
if (!$this->integration) {
|
||||
throw new Exception("Integration is not loaded. Call forTenant() first.");
|
||||
if (! $this->integration) {
|
||||
throw new Exception('Integration is not loaded. Call forTenant() or forClient() first.');
|
||||
}
|
||||
|
||||
$baseUrl = rtrim($this->integration->url, '/');
|
||||
@@ -119,25 +131,20 @@ abstract class BaseIntegrationService
|
||||
}
|
||||
|
||||
/**
|
||||
* Get integration setting by key from tenant's integration data.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
* @return mixed
|
||||
* Get an integration setting from the client-owned configuration.
|
||||
*/
|
||||
protected function getIntegrationSetting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
if (!$this->tenantIntegration || !$this->tenantIntegration->integration_data) {
|
||||
if (! $this->clientIntegration || ! $this->clientIntegration->integration_data) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $this->tenantIntegration->integration_data[$key] ?? $default;
|
||||
return $this->clientIntegration->integration_data[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a pre-configured HTTP client builder.
|
||||
*
|
||||
* @return PendingRequest
|
||||
* @throws Exception
|
||||
*/
|
||||
public function client(): PendingRequest
|
||||
@@ -148,17 +155,13 @@ abstract class BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Get the headers for the integration.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract public function getHeaders(): array;
|
||||
|
||||
/**
|
||||
* Hook called after the integration is configured for the tenant.
|
||||
* Hook called after the integration is configured for the client.
|
||||
* Can be used to validate credentials or perform initial setups.
|
||||
* Throw an Exception on failure.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function onSetup(): void
|
||||
{
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ClientIntegrationService
|
||||
{
|
||||
public function getClientIntegration(Client $client, string $integrationCode): ?ClientIntegration
|
||||
{
|
||||
return $client->integrations()
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
}
|
||||
|
||||
/** @return Collection<int, ClientIntegration> */
|
||||
public function getAllForClient(Client $client): Collection
|
||||
{
|
||||
return $client->integrations()->with('integration')->get();
|
||||
}
|
||||
|
||||
public function updateOrCreateIntegration(
|
||||
Client $client,
|
||||
Integration $integration,
|
||||
array $data,
|
||||
): ClientIntegration {
|
||||
return DB::transaction(function () use ($client, $integration, $data): ClientIntegration {
|
||||
$clientIntegration = ClientIntegration::query()->updateOrCreate(
|
||||
[
|
||||
'client_id' => $client->id,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
['integration_data' => $data],
|
||||
);
|
||||
|
||||
$service = $this->resolveService($integration->integration_code);
|
||||
$service?->forClient($client)->onSetup();
|
||||
|
||||
return $clientIntegration;
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveService(string $integrationCode): ?BaseIntegrationService
|
||||
{
|
||||
return match ($integrationCode) {
|
||||
'email' => new MailService,
|
||||
'telepagos', 'telepagos_homo' => new TelepagosIntegrationService($integrationCode),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Mail\Factory as MailFactory;
|
||||
use Illuminate\Contracts\Mail\Mailer;
|
||||
@@ -27,9 +27,7 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
private ?Mailer $mailer = null;
|
||||
|
||||
private ?Tenant $tenant = null;
|
||||
|
||||
private bool $usesTenantMailer = false;
|
||||
private bool $usesClientMailer = false;
|
||||
|
||||
public function __construct(?MailFactory $mailFactory = null)
|
||||
{
|
||||
@@ -40,16 +38,28 @@ class MailService extends BaseIntegrationService
|
||||
{
|
||||
parent::forTenant($tenantCode);
|
||||
|
||||
$this->tenant = Tenant::query()
|
||||
->where('codigo', $tenantCode)
|
||||
->firstOrFail();
|
||||
|
||||
if ($this->tenantIntegration) {
|
||||
if ($this->clientIntegration) {
|
||||
$this->mailer = $this->resolveMailer();
|
||||
$this->usesTenantMailer = true;
|
||||
$this->usesClientMailer = true;
|
||||
} else {
|
||||
$this->mailer = $this->mailFactory->mailer();
|
||||
$this->usesTenantMailer = false;
|
||||
$this->usesClientMailer = false;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function forClient(Client|string $client): self
|
||||
{
|
||||
parent::forClient($client);
|
||||
$this->tenant = $this->clientContext?->tenants()->first();
|
||||
|
||||
if ($this->clientIntegration) {
|
||||
$this->mailer = $this->resolveMailer();
|
||||
$this->usesClientMailer = true;
|
||||
} else {
|
||||
$this->mailer = $this->mailFactory->mailer();
|
||||
$this->usesClientMailer = false;
|
||||
}
|
||||
|
||||
return $this;
|
||||
@@ -63,7 +73,7 @@ class MailService extends BaseIntegrationService
|
||||
public function send(string|array $recipient, string $subject, string $content): void
|
||||
{
|
||||
if (! $this->mailer || ! $this->tenant) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() primero.');
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
|
||||
}
|
||||
|
||||
$this->tenant->loadMissing(['headerLogo', 'footerLogo']);
|
||||
@@ -91,43 +101,50 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
public function mailerName(): string
|
||||
{
|
||||
return $this->usesTenantMailer
|
||||
? 'tenant-smtp'
|
||||
return $this->usesClientMailer
|
||||
? 'client-smtp'
|
||||
: (string) config('mail.default');
|
||||
}
|
||||
|
||||
public function onSetup(): void
|
||||
{
|
||||
if (! $this->tenant) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() primero.');
|
||||
if (! $this->mailer || ! $this->clientContext) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
|
||||
}
|
||||
|
||||
$recipient = $this->getIntegrationSetting('MAIL_FROM_ADDRESS');
|
||||
|
||||
if (! is_string($recipient) || $recipient === '') {
|
||||
throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del tenant.');
|
||||
throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del cliente.');
|
||||
}
|
||||
|
||||
$this->send(
|
||||
$recipient,
|
||||
'Configuración de correo validada',
|
||||
'<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
|
||||
.'<p>La integración SMTP de '.e($this->tenant->nombre).' fue configurada correctamente.</p>'
|
||||
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>',
|
||||
$subject = 'Configuración de correo validada';
|
||||
$content = '<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
|
||||
.'<p>La integración SMTP de '.e($this->clientContext->name).' fue configurada correctamente.</p>'
|
||||
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>';
|
||||
|
||||
if ($this->tenant) {
|
||||
$this->send($recipient, $subject, $content);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->mailer->to($recipient)->send(
|
||||
(new Mailable)->subject($subject)->html($content)
|
||||
);
|
||||
}
|
||||
|
||||
private function resolveMailer(): Mailer
|
||||
{
|
||||
$data = $this->tenantIntegration?->integration_data;
|
||||
$data = $this->clientIntegration?->integration_data;
|
||||
|
||||
if (! is_array($data)) {
|
||||
throw new InvalidArgumentException('La configuración SMTP del tenant no es válida.');
|
||||
throw new InvalidArgumentException('La configuración SMTP del cliente no es válida.');
|
||||
}
|
||||
|
||||
foreach (self::REQUIRED_SMTP_FIELDS as $field) {
|
||||
if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') {
|
||||
throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del tenant.");
|
||||
throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del cliente.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +154,7 @@ class MailService extends BaseIntegrationService
|
||||
}
|
||||
|
||||
$mailer = $this->mailFactory->build([
|
||||
'name' => "tenant-smtp-{$this->tenantCode}",
|
||||
'name' => 'client-smtp-'.$this->clientContext?->id,
|
||||
'transport' => 'smtp',
|
||||
'scheme' => $data['MAIL_SCHEME'] ?? null,
|
||||
'host' => $data['MAIL_HOST'],
|
||||
@@ -150,7 +167,7 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
$mailer->alwaysFrom(
|
||||
$data['MAIL_FROM_ADDRESS'],
|
||||
$data['MAIL_FROM_NAME'] ?? $this->tenant?->nombre,
|
||||
$data['MAIL_FROM_NAME'] ?? $this->clientContext?->name,
|
||||
);
|
||||
|
||||
return $mailer;
|
||||
|
||||
@@ -2,39 +2,37 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class TelepagosIntegrationService extends BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* TelepagosIntegrationService constructor.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
*/
|
||||
public function __construct(string $integrationCode = 'telepagos')
|
||||
{
|
||||
// Force homologation code if not in production and using default
|
||||
if ($integrationCode === 'telepagos' && !app()->environment('production')) {
|
||||
if ($integrationCode === 'telepagos' && ! app()->environment('production')) {
|
||||
$integrationCode = 'telepagos_homo';
|
||||
}
|
||||
|
||||
|
||||
$this->integrationCode = $integrationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headers for Telepagos integration.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => 'Bearer ' . $this->getToken(),
|
||||
'Authorization' => 'Bearer '.$this->getToken(),
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
@@ -43,16 +41,15 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get a valid token, either from cache or by performing a login.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getToken(): string
|
||||
{
|
||||
if (!$this->tenantIntegration) {
|
||||
throw new Exception("Tenant integration is not loaded. Call forTenant() first.");
|
||||
if (! $this->clientIntegration || ! $this->clientContext) {
|
||||
throw new Exception('Client integration is not loaded. Call forTenant() or forClient() first.');
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
|
||||
$token = Cache::get($cacheKey);
|
||||
|
||||
@@ -66,7 +63,6 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Authenticate with Telepagos and cache the returned token.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function login(): string
|
||||
@@ -75,7 +71,7 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
$password = $this->getIntegrationSetting('password');
|
||||
|
||||
if (empty($username) || empty($password)) {
|
||||
throw new Exception("Missing username or password in Telepagos integration settings.");
|
||||
throw new Exception('Missing username or password in Telepagos integration settings.');
|
||||
}
|
||||
|
||||
$url = $this->getUrl('/v2/auth/token');
|
||||
@@ -92,15 +88,15 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
$token = $data['token'] ?? null;
|
||||
$expiresAtStr = $data['expires_at'] ?? null;
|
||||
|
||||
if (!$token || !$expiresAtStr) {
|
||||
throw new Exception("Telepagos authentication response is missing token or expires_at.");
|
||||
if (! $token || ! $expiresAtStr) {
|
||||
throw new Exception('Telepagos authentication response is missing token or expires_at.');
|
||||
}
|
||||
|
||||
$expiresAt = Carbon::parse($expiresAtStr);
|
||||
// Calculate TTL and subtract a buffer of 60 seconds
|
||||
$ttlSeconds = max(1, $expiresAt->diffInSeconds(now()) - 60);
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
Cache::put($cacheKey, $token, $ttlSeconds);
|
||||
|
||||
return $token;
|
||||
@@ -108,21 +104,16 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Send a request to Telepagos, handling 401 Unauthorized for token refresh.
|
||||
*
|
||||
* @param string $method
|
||||
* @param string $endpoint
|
||||
* @param array $data
|
||||
* @return \Illuminate\Http\Client\Response
|
||||
*/
|
||||
protected function sendRequest(string $method, string $endpoint, array $data = []): \Illuminate\Http\Client\Response
|
||||
protected function sendRequest(string $method, string $endpoint, array $data = []): Response
|
||||
{
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
|
||||
if ($response->status() === 401) {
|
||||
Log::info("Telepagos 401 Unauthorized. Refreshing token and retrying...");
|
||||
|
||||
Log::info('Telepagos 401 Unauthorized. Refreshing token and retrying...');
|
||||
|
||||
$this->clearToken();
|
||||
|
||||
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
}
|
||||
|
||||
@@ -132,10 +123,6 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Generate a QR code for cash-in.
|
||||
*
|
||||
* @param float $amount
|
||||
* @param string $concept
|
||||
* @param string $description
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function generateQr(float $amount, string $concept, string $description): array
|
||||
@@ -154,8 +141,8 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get the details of a cash-in payment.
|
||||
*
|
||||
* @param int $cashinId
|
||||
* @return array
|
||||
* @param int $cashinId
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCashinDetails(string $cashinId): array
|
||||
@@ -170,25 +157,21 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get the account info.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getAccountInfo(): array
|
||||
{
|
||||
$response = $this->sendRequest('get', '/v2/account/info');
|
||||
|
||||
return $this->handleResponse($response, 'get account info');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the Telepagos API response, logging any failures and throwing Exceptions.
|
||||
*
|
||||
* @param \Illuminate\Http\Client\Response $response
|
||||
* @param string $actionDescription
|
||||
* @param array $context
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function handleResponse(\Illuminate\Http\Client\Response $response, string $actionDescription, array $context = []): array
|
||||
protected function handleResponse(Response $response, string $actionDescription, array $context = []): array
|
||||
{
|
||||
if ($response->failed() || $response->json('status') !== 'ok') {
|
||||
$errorMessage = $response->json('message') ?? $response->body();
|
||||
@@ -205,19 +188,20 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Clear the cached token.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearToken(): void
|
||||
{
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
if (! $this->clientContext) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform initial setup validation for Telepagos.
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onSetup(): void
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\TelepagosPayment;
|
||||
use App\Domains\Purchase\Models\TelepagosQr;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -22,12 +22,10 @@ class TelepagosWebhookService
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handleWebhook(string $tenantCodigo, string $cashinId): void
|
||||
public function handleWebhook(Client $client, string $cashinId): void
|
||||
{
|
||||
$tenant = Tenant::where('codigo', $tenantCodigo)->firstOrFail();
|
||||
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
$telepagosService->forClient($client);
|
||||
|
||||
try {
|
||||
$details = $telepagosService->getCashinDetails($cashinId);
|
||||
@@ -52,7 +50,8 @@ class TelepagosWebhookService
|
||||
|
||||
$dni = substr($cuit, 2, -1);
|
||||
|
||||
$compra = Purchase::where('tenant_codigo', $tenantCodigo)
|
||||
$tenantCodes = $client->tenants()->pluck('codigo');
|
||||
$purchases = Purchase::whereIn('tenant_codigo', $tenantCodes)
|
||||
->where('transfer_payer_dni', $dni)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
@@ -61,10 +60,13 @@ class TelepagosWebhookService
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->latest()
|
||||
->first();
|
||||
->limit(2)
|
||||
->get();
|
||||
|
||||
$compra = $purchases->count() === 1 ? $purchases->first() : null;
|
||||
|
||||
if (! $compra) {
|
||||
Log::warning("Telepagos webhook: No matching purchase found for DNI {$dni} and amount {$amount} for cashin {$cashinId}");
|
||||
Log::warning("Telepagos webhook: Expected one matching purchase for client {$client->code}, DNI {$dni}, amount {$amount} and cashin {$cashinId}; found {$purchases->count()}");
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -91,6 +93,12 @@ class TelepagosWebhookService
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) {
|
||||
Log::warning("Telepagos webhook: Purchase {$compra->id} does not belong to client {$client->code}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array($compra->status, [
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class TenantIntegrationService
|
||||
{
|
||||
public function getTenantIntegration(string $tenantCode, string $integrationCode): ?TenantIntegration
|
||||
{
|
||||
return TenantIntegration::where('tenant_code', $tenantCode)
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function getAllForTenant(string $tenantCode)
|
||||
{
|
||||
return TenantIntegration::with('integration')
|
||||
->where('tenant_code', $tenantCode)
|
||||
->get();
|
||||
}
|
||||
|
||||
public function updateOrCreateIntegration(string $tenantCode, Integration $integration, array $data): TenantIntegration
|
||||
{
|
||||
return DB::transaction(function () use ($tenantCode, $integration, $data) {
|
||||
$tenantIntegration = TenantIntegration::updateOrCreate(
|
||||
[
|
||||
'tenant_code' => $tenantCode,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
[
|
||||
'integration_data' => $data,
|
||||
]
|
||||
);
|
||||
|
||||
$service = $this->resolveService($integration->integration_code);
|
||||
if ($service) {
|
||||
$service->forTenant($tenantCode)->onSetup();
|
||||
}
|
||||
|
||||
return $tenantIntegration;
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveService(string $integrationCode): ?BaseIntegrationService
|
||||
{
|
||||
switch ($integrationCode) {
|
||||
case 'email':
|
||||
return new MailService;
|
||||
case 'telepagos':
|
||||
case 'telepagos_homo':
|
||||
return new TelepagosIntegrationService($integrationCode);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,18 @@
|
||||
|
||||
## Propósito
|
||||
|
||||
Gestiona integraciones externas disponibles y su configuración por tenant. Incluye correo y pagos mediante Telepagos.
|
||||
Gestiona integraciones externas disponibles y su configuración por cliente. Un cliente puede agrupar múltiples tenants que comparten las mismas credenciales. Incluye correo y pagos mediante Telepagos.
|
||||
|
||||
## Modelo y seguridad
|
||||
|
||||
- `Integration`: definición global de una integración.
|
||||
- `TenantIntegration`: configuración y credenciales de una integración para un tenant.
|
||||
- `ClientIntegration`: configuración y credenciales de una integración para un cliente.
|
||||
- `EncryptedIntegrationData`: cast que protege los datos sensibles persistidos.
|
||||
- `TenantIntegrationService`: consulta y configura integraciones del tenant.
|
||||
- `ClientIntegrationService`: consulta y configura integraciones del cliente.
|
||||
|
||||
## Servicios externos
|
||||
|
||||
- `BaseIntegrationService`: base para resolver configuración, URL y cliente del tenant.
|
||||
- `BaseIntegrationService`: resuelve el cliente desde el tenant operativo y carga exclusivamente la configuración del cliente.
|
||||
- `MailService`: envío de correo usando la integración configurada.
|
||||
- `TelepagosIntegrationService`: autenticación, caché de token, generación de QR y consulta de cobros.
|
||||
- `TelepagosWebhookService`: procesa notificaciones recibidas desde Telepagos.
|
||||
@@ -21,9 +21,9 @@ Gestiona integraciones externas disponibles y su configuración por tenant. Incl
|
||||
## Endpoints
|
||||
|
||||
- CRUD global bajo `/integrations`.
|
||||
- Consulta y configuración por tenant bajo `/{tenant_code}/integrations`.
|
||||
- `POST /webhooks/telepagos/{tenant_codigo}` para notificaciones del proveedor.
|
||||
- Consulta y configuración por cliente bajo `/clients/{client}/integrations`.
|
||||
- `POST /webhooks/telepagos/{client}` para notificaciones del proveedor.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Se integra con `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. Las credenciales no deben exponerse en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
Se integra con `Client`, `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. El tenant conserva el contexto operativo y de branding, pero nunca es dueño de credenciales. Las credenciales no se exponen en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Integration\Controllers\ClientIntegrationController;
|
||||
use App\Domains\Integration\Controllers\IntegrationController;
|
||||
use App\Domains\Integration\Controllers\TenantIntegrationController;
|
||||
use App\Domains\Integration\Controllers\TelepagosWebhookController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::group(['prefix' => 'integrations'], function () {
|
||||
@@ -12,10 +13,10 @@ Route::group(['prefix' => 'integrations'], function () {
|
||||
Route::delete('/{integration}', [IntegrationController::class, 'destroy']);
|
||||
});
|
||||
|
||||
Route::group(['prefix' => '{tenant_code}/integrations'], function () {
|
||||
Route::get('/', [TenantIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [TenantIntegrationController::class, 'show']);
|
||||
Route::post('/{integration_code}', [TenantIntegrationController::class, 'store']);
|
||||
Route::group(['prefix' => 'clients/{client}/integrations'], function () {
|
||||
Route::get('/', [ClientIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [ClientIntegrationController::class, 'show']);
|
||||
Route::put('/{integration_code}', [ClientIntegrationController::class, 'store']);
|
||||
});
|
||||
|
||||
Route::post('webhooks/telepagos/{tenant_codigo}', [\App\Domains\Integration\Controllers\TelepagosWebhookController::class, 'handle']);
|
||||
Route::post('webhooks/telepagos/{client}', [TelepagosWebhookController::class, 'handle']);
|
||||
|
||||
@@ -9,8 +9,15 @@ class PasswordResetRequested
|
||||
{
|
||||
use Dispatchable, SerializesModels;
|
||||
|
||||
public const CHANNEL_STOREFRONT = 'storefront';
|
||||
|
||||
public const CHANNEL_ADMINAPP = 'adminapp';
|
||||
|
||||
public const CHANNEL_SCANNER = 'scanner';
|
||||
|
||||
public function __construct(
|
||||
public readonly int $attemptId,
|
||||
public readonly string $tenantCode,
|
||||
public readonly string $channel = self::CHANNEL_STOREFRONT,
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -26,11 +26,13 @@ class SendPasswordResetEmail implements ShouldQueueAfterCommit
|
||||
app(NotificationMailService::class)->sendPasswordResetCode(
|
||||
$event->attemptId,
|
||||
$event->tenantCode,
|
||||
$event->channel,
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
Log::error('Failed to send password reset email.', [
|
||||
'attempt_id' => $event->attemptId,
|
||||
'tenant_code' => $event->tenantCode,
|
||||
'channel' => $event->channel,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@ namespace App\Domains\Notification\Services;
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Integration\Services\MailService;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
@@ -31,9 +33,15 @@ class NotificationMailService
|
||||
);
|
||||
}
|
||||
|
||||
public function sendPasswordResetCode(int $attemptId, string $tenantCode): void
|
||||
{
|
||||
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
|
||||
public function sendPasswordResetCode(
|
||||
int $attemptId,
|
||||
string $tenantCode,
|
||||
string $channel = PasswordResetRequested::CHANNEL_STOREFRONT,
|
||||
): void {
|
||||
$tenant = Tenant::query()
|
||||
->with('websiteType')
|
||||
->where('codigo', $tenantCode)
|
||||
->firstOrFail();
|
||||
$attempt = ResetPasswordAttempt::query()
|
||||
->with('user')
|
||||
->findOrFail($attemptId);
|
||||
@@ -48,12 +56,32 @@ class NotificationMailService
|
||||
return;
|
||||
}
|
||||
|
||||
$recoveryDomain = match ($channel) {
|
||||
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
||||
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
||||
default => $tenant->dominio,
|
||||
};
|
||||
$recoveryBasePath = $channel === PasswordResetRequested::CHANNEL_STOREFRONT
|
||||
&& $tenant->base_path !== '/'
|
||||
? $tenant->base_path
|
||||
: '';
|
||||
$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.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
||||
|
||||
$this->mailService
|
||||
->forTenant($tenantCode)
|
||||
->send(
|
||||
$attempt->user->email,
|
||||
"Código para recuperar tu contraseña - {$tenant->nombre}",
|
||||
view('mail.notifications.password-reset', compact('tenant', 'attempt'))->render(),
|
||||
view('mail.notifications.password-reset', compact('tenant', 'attempt', 'recoveryUrl'))->render(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -81,6 +109,7 @@ class NotificationMailService
|
||||
->where('tenant_code', $purchase->tenant_codigo)
|
||||
->where('user_id', $purchase->user_id)
|
||||
->whereKey($ticketIds)
|
||||
->with(TicketPresentationResolver::RELATIONS)
|
||||
->get();
|
||||
|
||||
if ($tickets->isEmpty()) {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?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,29 +19,21 @@ class StartCheckoutRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'cart_id' => [
|
||||
'required_without:direct_item',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('direct_item')),
|
||||
'required_without:direct_items',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('direct_items')),
|
||||
'integer',
|
||||
'exists:carritos,id',
|
||||
],
|
||||
'direct_item' => [
|
||||
'direct_items' => [
|
||||
'required_without:cart_id',
|
||||
Rule::prohibitedIf(fn (): bool => $this->has('cart_id')),
|
||||
'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',
|
||||
],
|
||||
'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'],
|
||||
'telefono' => ['prohibited'],
|
||||
'nombre_apellido' => ['prohibited'],
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -15,8 +16,13 @@ class PurchaseItemResource extends JsonResource
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$tenant = $request->route('tenant');
|
||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||
|
||||
if ($this->resource instanceof PurchaseItem) {
|
||||
$imageUrl = $this->imageAttachment?->getTemporaryUrl(1440);
|
||||
$imageUrl = $displayImage
|
||||
? $this->imageAttachment?->getTemporaryUrl(1440)
|
||||
: null;
|
||||
$attributes = $this->variant_attributes ?? [];
|
||||
|
||||
return [
|
||||
@@ -42,7 +48,9 @@ class PurchaseItemResource extends JsonResource
|
||||
$quantity = (int) ($this->cantidad ?? 0);
|
||||
$unitPrice = $this->resolveUnitPrice($selectedItem);
|
||||
$lineTotal = $unitPrice * $quantity;
|
||||
$imageUrl = $this->resolveImageUrl($selectedItem, $catalogItem);
|
||||
$imageUrl = $displayImage
|
||||
? $this->resolveImageUrl($selectedItem, $catalogItem)
|
||||
: null;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
|
||||
@@ -16,6 +16,7 @@ class CatalogSelectionResolver
|
||||
Tenant $tenant,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
string $fieldPrefix = 'direct_items',
|
||||
): CatalogItem|Variant {
|
||||
/** @var CatalogItem|null $catalogItem */
|
||||
$catalogItem = CatalogItem::query()
|
||||
@@ -31,13 +32,13 @@ class CatalogSelectionResolver
|
||||
if ($catalogItem->isBundle()) {
|
||||
if ($variantId !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.variant_id' => __('api.cart.bundle_variant_forbidden'),
|
||||
"{$fieldPrefix}.variant_id" => __('api.cart.bundle_variant_forbidden'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $catalogItem->bundleComponents()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.catalog_item_id' => __('api.cart.empty_bundle'),
|
||||
"{$fieldPrefix}.catalog_item_id" => __('api.cart.empty_bundle'),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -47,7 +48,7 @@ class CatalogSelectionResolver
|
||||
if ($variantId === null) {
|
||||
if ($catalogItem->inventory_id === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.variant_id' => __('api.cart.variant_required'),
|
||||
"{$fieldPrefix}.variant_id" => __('api.cart.variant_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -22,6 +23,7 @@ class StartCheckoutService
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||
) {}
|
||||
|
||||
/** @param array<string, mixed> $purchaseData */
|
||||
@@ -33,12 +35,17 @@ class StartCheckoutService
|
||||
->lockForUpdate()
|
||||
->findOrFail($tenant->getKey());
|
||||
|
||||
$directItem = $purchaseData['direct_item'] ?? null;
|
||||
$directItems = $purchaseData['direct_items'] ?? null;
|
||||
$cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
|
||||
unset($purchaseData['direct_item'], $purchaseData['cart_id']);
|
||||
unset($purchaseData['direct_items'], $purchaseData['cart_id']);
|
||||
|
||||
if (is_array($directItem)) {
|
||||
return $this->startDirect($tenant, $userId, $purchaseData, $directItem);
|
||||
if (is_array($directItems)) {
|
||||
return $this->startDirectItems(
|
||||
$tenant,
|
||||
$userId,
|
||||
$purchaseData,
|
||||
$directItems,
|
||||
);
|
||||
}
|
||||
|
||||
if ($cartId === null) {
|
||||
@@ -53,63 +60,153 @@ class StartCheckoutService
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $purchaseData
|
||||
* @param array<string, mixed> $directItem
|
||||
* @param array<int, array<string, mixed>> $directItems
|
||||
*/
|
||||
private function startDirect(
|
||||
private function startDirectItems(
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
array $purchaseData,
|
||||
array $directItem,
|
||||
array $directItems,
|
||||
): Purchase {
|
||||
$catalogItemId = (int) $directItem['catalog_item_id'];
|
||||
$variantId = isset($directItem['variant_id']) ? (int) $directItem['variant_id'] : null;
|
||||
$quantity = (int) $directItem['cantidad'];
|
||||
$selection = $this->selections->resolve($tenant, $catalogItemId, $variantId);
|
||||
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
|
||||
$lines = collect(array_values($directItems))
|
||||
->map(function (array $item, int $index): array {
|
||||
return [
|
||||
'index' => $index,
|
||||
'catalog_item_id' => (int) $item['catalog_item_id'],
|
||||
'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');
|
||||
|
||||
$this->purchaseLimits->assertCanPurchase(
|
||||
$catalogItem,
|
||||
$userId,
|
||||
$quantity,
|
||||
field: 'direct_item.cantidad',
|
||||
);
|
||||
return $line;
|
||||
})
|
||||
->sortBy(fn (array $line): string => sprintf(
|
||||
'%020d:%020d',
|
||||
$line['catalog_item_id'],
|
||||
$line['variant_id'] ?? 0,
|
||||
))
|
||||
->values();
|
||||
|
||||
$availableQuantity = $this->inventory->availableQuantity($selection);
|
||||
$resolvedLines = $lines->map(function (array $line) use ($tenant): array {
|
||||
$selection = $this->selections->resolve(
|
||||
$tenant,
|
||||
$line['catalog_item_id'],
|
||||
$line['variant_id'],
|
||||
$line['field'],
|
||||
);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.cantidad' => __('api.purchase.direct_item_max_stock', ['max' => $availableQuantity]),
|
||||
]);
|
||||
return [
|
||||
...$line,
|
||||
'selection' => $selection,
|
||||
'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);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->inventory->reserve($selection, $quantity);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'direct_item.cantidad' => __('api.purchase.insufficient_stock'),
|
||||
]);
|
||||
foreach ($resolvedLines as $line) {
|
||||
try {
|
||||
$this->inventory->reserve($line['selection'], $line['quantity']);
|
||||
} catch (\InvalidArgumentException) {
|
||||
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
|
||||
|
||||
throw new InsufficientStockException([
|
||||
$this->unavailableItem($line, $availableQuantity),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$purchase = $this->createPurchase(
|
||||
$tenant,
|
||||
$userId,
|
||||
$purchaseData,
|
||||
$selection->getPrice() * $quantity,
|
||||
(float) $resolvedLines->sum(
|
||||
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
|
||||
),
|
||||
null,
|
||||
);
|
||||
$directCartItem = $this->makeDirectCartItem(
|
||||
$selection,
|
||||
$catalogItemId,
|
||||
$variantId,
|
||||
$quantity,
|
||||
);
|
||||
|
||||
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem(
|
||||
$line['selection'],
|
||||
$line['catalog_item_id'],
|
||||
$line['variant_id'],
|
||||
$line['quantity'],
|
||||
));
|
||||
|
||||
$purchase->items()->createMany(
|
||||
$this->snapshots->fromCartItems(collect([$directCartItem])),
|
||||
$this->snapshots->fromCartItems($directCartItems),
|
||||
);
|
||||
|
||||
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 */
|
||||
private function startFromCart(
|
||||
Tenant $tenant,
|
||||
|
||||
@@ -7,6 +7,8 @@ use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -58,7 +60,7 @@ class AdminAppSaleService
|
||||
{
|
||||
return $this->findForTenant($tenant, $saleId)
|
||||
->tickets()
|
||||
->with('validityGroups.validityTimes')
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
86
app/Domains/Shared/Rules/CroppedImageOrBase64Rule.php
Normal file
86
app/Domains/Shared/Rules/CroppedImageOrBase64Rule.php
Normal file
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Shared\Rules;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
class CroppedImageOrBase64Rule implements ValidationRule
|
||||
{
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
(new ImageOrBase64Rule)->validate($attribute, $value, $fail);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! array_key_exists('image', $value)) {
|
||||
$fail('The :attribute.image field is required.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$valid = true;
|
||||
(new ImageOrBase64Rule)->validate(
|
||||
"{$attribute}.image",
|
||||
$value['image'],
|
||||
function (string $message) use ($fail, &$valid): void {
|
||||
$valid = false;
|
||||
$fail($message);
|
||||
}
|
||||
);
|
||||
|
||||
if (! $valid) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isset($value['crops']) && is_array($value['crops'])) {
|
||||
foreach (['desktop', 'mobile'] as $variant) {
|
||||
$crop = $value['crops'][$variant] ?? null;
|
||||
|
||||
if (! is_array($crop)) {
|
||||
$fail("The :attribute.crops.{$variant} field must be an object.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_horizontal', $crop, $fail);
|
||||
$this->validateRange("{$attribute}.crops.{$variant}", 'crop_vertical', $crop, $fail);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Backwards compatibility with the original single-crop payload.
|
||||
$this->validateRange($attribute, 'crop_horizontal', $value, $fail);
|
||||
$this->validateRange($attribute, 'crop_vertical', $value, $fail);
|
||||
}
|
||||
|
||||
private function validateRange(string $attribute, string $axis, array $value, Closure $fail): void
|
||||
{
|
||||
$range = $value[$axis] ?? null;
|
||||
|
||||
if (! is_array($range)) {
|
||||
$fail("The :attribute.{$axis} field must be an object.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$start = $range['start_percentage'] ?? null;
|
||||
$end = $range['end_percentage'] ?? null;
|
||||
|
||||
if (
|
||||
! is_numeric($start)
|
||||
|| ! is_numeric($end)
|
||||
|| (float) $start < 0
|
||||
|| (float) $end > 100
|
||||
|| (float) $start >= (float) $end
|
||||
) {
|
||||
$fail(
|
||||
"The :attribute.{$axis} field must satisfy "
|
||||
.'0 <= start_percentage < end_percentage <= 100.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,12 +15,17 @@ class StoreStaffRequest extends FormRequest
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$categoryRules = $this->user()->tenant()->firstOrFail()
|
||||
->requiresScannerCategoryValidation()
|
||||
? ['required', 'array', 'min:1']
|
||||
: ['sometimes', 'array'];
|
||||
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
'dni' => ['required', 'string', 'max:50'],
|
||||
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
|
||||
'category_ids' => ['required', 'array', 'min:1'],
|
||||
'category_ids.*' => ['required', 'integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||
'category_ids' => $categoryRules,
|
||||
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@ class UpdateStaffRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
$staffId = (int) $this->route('staff');
|
||||
$categoryRules = $this->user()->tenant()->firstOrFail()
|
||||
->requiresScannerCategoryValidation()
|
||||
? ['required', 'array', 'min:1']
|
||||
: ['sometimes', 'array'];
|
||||
|
||||
return [
|
||||
'nombre_apellido' => ['required', 'string', 'max:255'],
|
||||
@@ -26,8 +30,8 @@ class UpdateStaffRequest extends FormRequest
|
||||
'max:255',
|
||||
Rule::unique('users', 'email')->ignore($staffId),
|
||||
],
|
||||
'category_ids' => ['required', 'array', 'min:1'],
|
||||
'category_ids.*' => ['required', 'integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||
'category_ids' => $categoryRules,
|
||||
'category_ids.*' => ['integer', 'distinct', Rule::exists('categorias', 'id')],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Domains\Staff\Services;
|
||||
|
||||
use App\Domains\Auth\Models\ResetPasswordAttempt;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Auth\Services\ResetPasswordAttemptService;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -15,6 +17,10 @@ use Illuminate\Validation\ValidationException;
|
||||
|
||||
class StaffService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResetPasswordAttemptService $resetPasswordAttemptService,
|
||||
) {}
|
||||
|
||||
/** @return Collection<int, User> */
|
||||
public function list(Tenant $tenant, ?string $search = null): Collection
|
||||
{
|
||||
@@ -48,9 +54,10 @@ class StaffService
|
||||
/** @param array<string, mixed> $data */
|
||||
public function create(Tenant $tenant, array $data): User
|
||||
{
|
||||
$this->assertCategoriesBelongToTenant($tenant, $data['category_ids']);
|
||||
$categoryIds = $this->categoryIdsFor($tenant, $data);
|
||||
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
|
||||
|
||||
return DB::transaction(function () use ($tenant, $data): User {
|
||||
return DB::transaction(function () use ($tenant, $data, $categoryIds): User {
|
||||
$staff = User::query()->create([
|
||||
...Arr::only($data, ['nombre_apellido', 'dni', 'email']),
|
||||
'email' => mb_strtolower(trim((string) $data['email'])),
|
||||
@@ -58,7 +65,11 @@ class StaffService
|
||||
'rol_codigo' => RoleCode::Scanner->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
$staff->scanCategories()->sync($data['category_ids']);
|
||||
$staff->scanCategories()->sync($categoryIds);
|
||||
$this->resetPasswordAttemptService->createForScannerEmail(
|
||||
$staff->email,
|
||||
ResetPasswordAttempt::REASON_STAFF_CREATED,
|
||||
);
|
||||
|
||||
return $staff->load('role', 'scanCategories');
|
||||
});
|
||||
@@ -68,13 +79,14 @@ class StaffService
|
||||
public function update(Tenant $tenant, int $staffId, array $data): User
|
||||
{
|
||||
$staff = $this->find($tenant, $staffId);
|
||||
$this->assertCategoriesBelongToTenant($tenant, $data['category_ids']);
|
||||
$categoryIds = $this->categoryIdsFor($tenant, $data);
|
||||
$this->assertCategoriesBelongToTenant($tenant, $categoryIds);
|
||||
|
||||
return DB::transaction(function () use ($staff, $data): User {
|
||||
return DB::transaction(function () use ($staff, $data, $categoryIds): User {
|
||||
$attributes = Arr::only($data, ['nombre_apellido', 'dni', 'email']);
|
||||
$attributes['email'] = mb_strtolower(trim((string) $data['email']));
|
||||
$staff->update($attributes);
|
||||
$staff->scanCategories()->sync($data['category_ids']);
|
||||
$staff->scanCategories()->sync($categoryIds);
|
||||
|
||||
return $staff->load('role', 'scanCategories');
|
||||
});
|
||||
@@ -97,6 +109,19 @@ class StaffService
|
||||
->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 */
|
||||
private function assertCategoriesBelongToTenant(Tenant $tenant, array $categoryIds): void
|
||||
{
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Models\TenantMenu;
|
||||
@@ -16,11 +17,15 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
#[Fillable([
|
||||
'client_id',
|
||||
'codigo',
|
||||
'nombre',
|
||||
'dominio',
|
||||
'base_path',
|
||||
'site_title',
|
||||
'primary_color',
|
||||
'secondary_color',
|
||||
'danger_color',
|
||||
@@ -29,12 +34,19 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'footer_bg_color',
|
||||
'header_logo_id',
|
||||
'footer_logo_id',
|
||||
'favicon_id',
|
||||
'header_bg_image_id',
|
||||
'footer_bg_image_id',
|
||||
'website_type_code',
|
||||
'search_product_layout',
|
||||
'search_group_layout',
|
||||
'search_items_per_page',
|
||||
'display_categories',
|
||||
'display_seach_bar',
|
||||
'display_cart',
|
||||
'cart_editing_enabled',
|
||||
'display_cart_item_images',
|
||||
'scanner_category_validation_enabled',
|
||||
'event_title',
|
||||
'event_location',
|
||||
'event_date_text',
|
||||
@@ -44,11 +56,16 @@ class Tenant extends Model
|
||||
use HasFactory;
|
||||
|
||||
protected $attributes = [
|
||||
'base_path' => '/',
|
||||
'search_product_layout' => ProductLayout::ColumnWithImage->value,
|
||||
'search_group_layout' => GroupLayout::Paginated->value,
|
||||
'search_items_per_page' => 12,
|
||||
'display_categories' => true,
|
||||
'display_seach_bar' => true,
|
||||
'display_cart' => true,
|
||||
'cart_editing_enabled' => true,
|
||||
'display_cart_item_images' => true,
|
||||
'scanner_category_validation_enabled' => true,
|
||||
];
|
||||
|
||||
public function getRouteKeyName(): string
|
||||
@@ -56,6 +73,33 @@ class Tenant extends Model
|
||||
return 'codigo';
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (Tenant $tenant): void {
|
||||
if ($tenant->client_id !== null || ! Schema::hasTable('clients')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$client = Client::query()->firstOrCreate(
|
||||
['code' => $tenant->codigo],
|
||||
['name' => $tenant->nombre],
|
||||
);
|
||||
|
||||
$tenant->client()->associate($client);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Client, $this> */
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Client::class);
|
||||
}
|
||||
|
||||
public function requiresScannerCategoryValidation(): bool
|
||||
{
|
||||
return $this->scanner_category_validation_enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
@@ -69,6 +113,10 @@ class Tenant extends Model
|
||||
'search_items_per_page' => 'integer',
|
||||
'display_categories' => 'boolean',
|
||||
'display_seach_bar' => 'boolean',
|
||||
'display_cart' => 'boolean',
|
||||
'cart_editing_enabled' => 'boolean',
|
||||
'display_cart_item_images' => 'boolean',
|
||||
'scanner_category_validation_enabled' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -88,6 +136,30 @@ class Tenant extends Model
|
||||
return $this->belongsTo(Attachment::class, 'footer_logo_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Attachment, $this>
|
||||
*/
|
||||
public function favicon(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'favicon_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Attachment, $this>
|
||||
*/
|
||||
public function headerBackgroundImage(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'header_bg_image_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Attachment, $this>
|
||||
*/
|
||||
public function footerBackgroundImage(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'footer_bg_image_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<WebsiteType, $this>
|
||||
*/
|
||||
|
||||
@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'nombre',
|
||||
'dominio',
|
||||
'scanner_domain',
|
||||
'site_title',
|
||||
'primary_color',
|
||||
'secondary_color',
|
||||
'danger_color',
|
||||
@@ -27,6 +28,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'login_header_footer_color',
|
||||
'site_logo',
|
||||
'footer_logo',
|
||||
'favicon_id',
|
||||
])]
|
||||
class WebsiteType extends Model
|
||||
{
|
||||
@@ -50,6 +52,14 @@ class WebsiteType extends Model
|
||||
return $this->belongsTo(Attachment::class, 'footer_logo');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Attachment, $this>
|
||||
*/
|
||||
public function favicon(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'favicon_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<WebsiteTypeExtra, $this>
|
||||
*/
|
||||
|
||||
@@ -15,6 +15,8 @@ class StoreTenantRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidBasePath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -23,13 +25,21 @@ class StoreTenantRequest extends FormRequest
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->input('dominio');
|
||||
$hasExplicitBasePath = $this->has('base_path');
|
||||
$rawBasePath = $hasExplicitBasePath
|
||||
? $this->input('base_path')
|
||||
: TenantDomainNormalizer::pathFromDomain($rawDomain);
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedBasePath = TenantDomainNormalizer::normalizePath($rawBasePath);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
$this->hasInvalidBasePath = ($hasExplicitBasePath && ! is_string($rawBasePath))
|
||||
|| $normalizedBasePath === null;
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
'base_path' => $normalizedBasePath,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -41,6 +51,7 @@ class StoreTenantRequest extends FormRequest
|
||||
$logoRule = ['required', new ImageOrBase64Rule];
|
||||
|
||||
return array_merge([
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => ['required', 'string', 'max:255', Rule::unique('tenants', 'codigo')],
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'dominio' => [
|
||||
@@ -53,8 +64,23 @@ class StoreTenantRequest extends FormRequest
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'dominio'),
|
||||
Rule::unique('tenants', 'dominio')
|
||||
->where('base_path', $this->input('base_path')),
|
||||
],
|
||||
'base_path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidBasePath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'base_path')
|
||||
->where('dominio', $this->input('dominio')),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'primary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'secondary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'danger_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
@@ -63,6 +89,9 @@ class StoreTenantRequest extends FormRequest
|
||||
'footer_bg_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'header_logo' => $logoRule,
|
||||
'footer_logo' => $logoRule,
|
||||
'favicon' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'header_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'footer_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'social_media' => ['sometimes', 'array'],
|
||||
'social_media.*.code' => [
|
||||
'required',
|
||||
@@ -77,6 +106,10 @@ class StoreTenantRequest extends FormRequest
|
||||
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_enabled' => ['sometimes', 'boolean'],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
'website_type_code' => [
|
||||
'required_with:extras',
|
||||
'sometimes',
|
||||
|
||||
@@ -15,6 +15,8 @@ class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidBasePath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -25,13 +27,28 @@ class UpdateTenantRequest extends FormRequest
|
||||
if ($this->has('dominio')) {
|
||||
$rawDomain = $this->input('dominio');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$embeddedBasePath = TenantDomainNormalizer::pathFromDomain($rawDomain);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
&& ($normalizedDomain === null || $embeddedBasePath === null);
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
]);
|
||||
|
||||
if (! $this->has('base_path') && $embeddedBasePath !== null && $embeddedBasePath !== '/') {
|
||||
$this->merge(['base_path' => $embeddedBasePath]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->has('base_path')) {
|
||||
$rawBasePath = $this->input('base_path');
|
||||
$normalizedBasePath = TenantDomainNormalizer::normalizePath($rawBasePath);
|
||||
|
||||
$this->hasInvalidBasePath = ! is_string($rawBasePath)
|
||||
|| $normalizedBasePath === null;
|
||||
|
||||
$this->merge(['base_path' => $normalizedBasePath]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +59,13 @@ class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
/** @var Tenant|null $tenant */
|
||||
$tenant = $this->route('tenant');
|
||||
$domain = $this->input('dominio', $tenant?->dominio);
|
||||
$basePath = $this->input('base_path', $tenant?->base_path ?? '/');
|
||||
|
||||
$logoRule = ['nullable', new ImageOrBase64Rule];
|
||||
|
||||
return [
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => [
|
||||
'nullable',
|
||||
'string',
|
||||
@@ -63,8 +83,25 @@ class UpdateTenantRequest extends FormRequest
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'dominio')->ignore($tenant?->id),
|
||||
Rule::unique('tenants', 'dominio')
|
||||
->where('base_path', $basePath)
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'base_path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidBasePath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'base_path')
|
||||
->where('dominio', $domain)
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'primary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'secondary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'danger_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
@@ -73,6 +110,9 @@ class UpdateTenantRequest extends FormRequest
|
||||
'footer_bg_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'header_logo' => $logoRule,
|
||||
'footer_logo' => $logoRule,
|
||||
'favicon' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'header_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'footer_bg_image' => ['sometimes', 'nullable', new ImageOrBase64Rule],
|
||||
'social_media' => ['sometimes', 'array'],
|
||||
'social_media.*.code' => [
|
||||
'required',
|
||||
@@ -87,6 +127,10 @@ class UpdateTenantRequest extends FormRequest
|
||||
'search_items_per_page' => ['sometimes', 'integer', 'min:4', 'max:48'],
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_enabled' => ['sometimes', 'boolean'],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Tenant\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Tenant\Models\WebsiteExtra;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
@@ -29,12 +30,44 @@ class WebsiteExtraResource extends JsonResource
|
||||
fn (Attachment $attachment): string => $attachment->key
|
||||
),
|
||||
'resolved_config' => $this->formatConfig(
|
||||
$this->resolvedConfig(),
|
||||
$this->resolvedAdminConfig(),
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
private function resolvedAdminConfig(): mixed
|
||||
{
|
||||
$config = $this->resolvedConfig();
|
||||
|
||||
if (
|
||||
$this->websiteTypeExtra->codigo !== 'heroConfig'
|
||||
|| ! is_array($config)
|
||||
|| ! ($config['background_image_id'] ?? null) instanceof Attachment
|
||||
) {
|
||||
return $config;
|
||||
}
|
||||
|
||||
$attachment = $config['background_image_id'];
|
||||
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
|
||||
$crops = $attachment->cropVariants->keyBy('variant');
|
||||
$config['background_image_id'] = [
|
||||
'url' => $attachment->getTemporaryUrl(1440),
|
||||
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
|
||||
function (string $variant) use ($crops, $fullRange): array {
|
||||
$crop = $crops->get($variant);
|
||||
|
||||
return [$variant => [
|
||||
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
|
||||
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
|
||||
]];
|
||||
}
|
||||
)->all(),
|
||||
];
|
||||
|
||||
return $config;
|
||||
}
|
||||
|
||||
private function formatConfig(mixed $value, callable $formatAttachment): mixed
|
||||
{
|
||||
if ($value instanceof Attachment) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Tenant\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
@@ -45,14 +46,53 @@ class WebsiteExtrasResource extends JsonResource
|
||||
),
|
||||
]),
|
||||
'resolved_extras' => $websiteExtras->mapWithKeys(fn ($extra) => [
|
||||
$extra->websiteTypeExtra->codigo => $this->formatConfig(
|
||||
$extra->resolvedConfig(),
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
),
|
||||
$extra->websiteTypeExtra->codigo => $this->formatResolvedConfig($extra),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
private function formatResolvedConfig(mixed $extra): mixed
|
||||
{
|
||||
$config = $extra->resolvedConfig();
|
||||
|
||||
if (
|
||||
$extra->websiteTypeExtra->codigo === 'heroConfig'
|
||||
&& is_array($config)
|
||||
&& ($config['background_image_id'] ?? null) instanceof Attachment
|
||||
) {
|
||||
$attachment = $config['background_image_id'];
|
||||
$config['background_image_id'] = $this->formatHeroAttachment($attachment);
|
||||
}
|
||||
|
||||
return $this->formatConfig(
|
||||
$config,
|
||||
fn (Attachment $attachment): string => $attachment->getTemporaryUrl(1440)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string, crops: array<string, array<string, array<string, float>>>}
|
||||
*/
|
||||
private function formatHeroAttachment(Attachment $attachment): array
|
||||
{
|
||||
$fullRange = ['start_percentage' => 0.0, 'end_percentage' => 100.0];
|
||||
$crops = $attachment->cropVariants->keyBy('variant');
|
||||
|
||||
return [
|
||||
'url' => $attachment->getTemporaryUrl(1440),
|
||||
'crops' => collect(AttachmentCrop::VARIANTS)->mapWithKeys(
|
||||
function (string $variant) use ($crops, $fullRange): array {
|
||||
$crop = $crops->get($variant);
|
||||
|
||||
return [$variant => [
|
||||
'crop_horizontal' => $crop?->crop_horizontal ?? $fullRange,
|
||||
'crop_vertical' => $crop?->crop_vertical ?? $fullRange,
|
||||
]];
|
||||
}
|
||||
)->all(),
|
||||
];
|
||||
}
|
||||
|
||||
private function formatConfig(mixed $value, callable $formatAttachment): mixed
|
||||
{
|
||||
if ($value instanceof Attachment) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Tenant\Resources;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -23,9 +24,16 @@ class TenantResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'client_id' => $this->client_id,
|
||||
'codigo' => $this->codigo,
|
||||
'nombre' => $this->nombre,
|
||||
'dominio' => $this->dominio,
|
||||
'base_path' => $this->base_path,
|
||||
'site_title' => $this->site_title
|
||||
?? $this->websiteType?->site_title
|
||||
?? 'ShopitFront',
|
||||
'favicon' => ($this->favicon ?? $this->websiteType?->favicon)
|
||||
?->getTemporaryUrl(1440),
|
||||
'primary_color' => $this->primary_color,
|
||||
'secondary_color' => $this->secondary_color,
|
||||
'danger_color' => $this->danger_color,
|
||||
@@ -59,11 +67,17 @@ class TenantResource extends JsonResource
|
||||
// 1 day
|
||||
'header_logo' => $this->headerLogo?->getTemporaryUrl(1440),
|
||||
'footer_logo' => $this->footerLogo?->getTemporaryUrl(1440),
|
||||
'header_bg_image' => $this->headerBackgroundImage?->getTemporaryUrl(1440),
|
||||
'footer_bg_image' => $this->footerBackgroundImage?->getTemporaryUrl(1440),
|
||||
'search_product_layout' => $this->search_product_layout->value,
|
||||
'search_group_layout' => $this->search_group_layout->value,
|
||||
'search_items_per_page' => $this->search_items_per_page,
|
||||
'display_categories' => $this->display_categories,
|
||||
'display_seach_bar' => $this->display_seach_bar,
|
||||
'display_cart' => $this->display_cart,
|
||||
'cart_editing_enabled' => $this->cart_editing_enabled,
|
||||
'display_cart_item_images' => $this->display_cart_item_images,
|
||||
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled,
|
||||
'social_media' => $this->whenLoaded(
|
||||
'socialMedia',
|
||||
fn () => $this->socialMedia
|
||||
@@ -89,7 +103,18 @@ class TenantResource extends JsonResource
|
||||
private function formatExtraConfig(mixed $value): mixed
|
||||
{
|
||||
if ($value instanceof Attachment) {
|
||||
return $value->getTemporaryUrl(1440);
|
||||
$crops = $value->cropVariants->keyBy('variant');
|
||||
$desktop = $crops->get(AttachmentCrop::DESKTOP)?->croppedAttachment ?? $value;
|
||||
$mobile = $crops->get(AttachmentCrop::MOBILE)?->croppedAttachment ?? $desktop;
|
||||
|
||||
if ($crops->isEmpty()) {
|
||||
return $value->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
return [
|
||||
'desktop' => $desktop->getTemporaryUrl(1440),
|
||||
'mobile' => $mobile->getTemporaryUrl(1440),
|
||||
];
|
||||
}
|
||||
|
||||
if (! is_array($value)) {
|
||||
|
||||
@@ -13,6 +13,10 @@ class TenantInformationService
|
||||
private const DEFAULT_RELATIONS = [
|
||||
'headerLogo',
|
||||
'footerLogo',
|
||||
'favicon',
|
||||
'websiteType.favicon',
|
||||
'headerBackgroundImage',
|
||||
'footerBackgroundImage',
|
||||
'socialMedia',
|
||||
'websiteExtras.websiteTypeExtra',
|
||||
'eventDates',
|
||||
@@ -77,6 +81,7 @@ class TenantInformationService
|
||||
|
||||
$attachments = Attachment::query()
|
||||
->whereIn('id', $attachmentIds)
|
||||
->with('cropVariants.croppedAttachment')
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
|
||||
@@ -25,12 +25,18 @@ class TenantService
|
||||
return DB::transaction(function () use ($data): Tenant {
|
||||
$headerLogo = $data['header_logo'] ?? null;
|
||||
$footerLogo = $data['footer_logo'] ?? null;
|
||||
$favicon = $data['favicon'] ?? null;
|
||||
$headerBackgroundImage = $data['header_bg_image'] ?? null;
|
||||
$footerBackgroundImage = $data['footer_bg_image'] ?? null;
|
||||
$socialMedia = $data['social_media'] ?? [];
|
||||
$extras = $data['extras'] ?? [];
|
||||
|
||||
unset(
|
||||
$data['header_logo'],
|
||||
$data['footer_logo'],
|
||||
$data['favicon'],
|
||||
$data['header_bg_image'],
|
||||
$data['footer_bg_image'],
|
||||
$data['social_media'],
|
||||
$data['extras'],
|
||||
);
|
||||
@@ -59,6 +65,9 @@ class TenantService
|
||||
|
||||
$data['header_logo_id'] = $headerAttachmentId;
|
||||
$data['footer_logo_id'] = $footerAttachmentId;
|
||||
$data['favicon_id'] = $this->storeTenantImage($favicon);
|
||||
$data['header_bg_image_id'] = $this->storeTenantImage($headerBackgroundImage);
|
||||
$data['footer_bg_image_id'] = $this->storeTenantImage($footerBackgroundImage);
|
||||
|
||||
/** @var Tenant $tenant */
|
||||
$tenant = Tenant::query()->create($data);
|
||||
@@ -79,14 +88,23 @@ class TenantService
|
||||
return DB::transaction(function () use ($tenant, $data): Tenant {
|
||||
$hasHeaderLogoKey = array_key_exists('header_logo', $data);
|
||||
$hasFooterLogoKey = array_key_exists('footer_logo', $data);
|
||||
$hasFaviconKey = array_key_exists('favicon', $data);
|
||||
$hasHeaderBackgroundImageKey = array_key_exists('header_bg_image', $data);
|
||||
$hasFooterBackgroundImageKey = array_key_exists('footer_bg_image', $data);
|
||||
$hasSocialMediaKey = array_key_exists('social_media', $data);
|
||||
$headerLogo = $data['header_logo'] ?? null;
|
||||
$footerLogo = $data['footer_logo'] ?? null;
|
||||
$favicon = $data['favicon'] ?? null;
|
||||
$headerBackgroundImage = $data['header_bg_image'] ?? null;
|
||||
$footerBackgroundImage = $data['footer_bg_image'] ?? null;
|
||||
$socialMedia = $data['social_media'] ?? [];
|
||||
|
||||
unset(
|
||||
$data['header_logo'],
|
||||
$data['footer_logo'],
|
||||
$data['favicon'],
|
||||
$data['header_bg_image'],
|
||||
$data['footer_bg_image'],
|
||||
$data['social_media']
|
||||
);
|
||||
|
||||
@@ -124,6 +142,18 @@ class TenantService
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasFaviconKey) {
|
||||
$tenant->favicon_id = $this->storeTenantImage($favicon);
|
||||
}
|
||||
|
||||
if ($hasHeaderBackgroundImageKey) {
|
||||
$tenant->header_bg_image_id = $this->storeTenantImage($headerBackgroundImage);
|
||||
}
|
||||
|
||||
if ($hasFooterBackgroundImageKey) {
|
||||
$tenant->footer_bg_image_id = $this->storeTenantImage($footerBackgroundImage);
|
||||
}
|
||||
|
||||
$tenant->save();
|
||||
|
||||
if ($hasSocialMediaKey) {
|
||||
@@ -151,4 +181,17 @@ class TenantService
|
||||
$tenant->socialMedia()->sync($associations);
|
||||
$tenant->unsetRelation('socialMedia');
|
||||
}
|
||||
|
||||
private function storeTenantImage(mixed $image): ?int
|
||||
{
|
||||
if (! $image) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$attachment = is_string($image) && Str::isUuid($image)
|
||||
? Attachment::query()->where('key', $image)->first()
|
||||
: $this->attachmentService->store($image, 'tenants');
|
||||
|
||||
return $attachment?->id;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user