Compare commits

..

42 Commits

Author SHA1 Message Date
5197862a62 feat(ticket): implement ticket generation policies and validity time management
- Added `ticket_generation_policy` column to `catalog_items` table to manage ticket generation strategies.
- Created `ticket_validity_times` table to allow multiple validity times per ticket.
- Introduced `validity_time_id` column in `event_dates` table to associate event dates with validity times.
- Established `ticket_validity_groups` and `ticket_validity_group_times` tables to group validity times for tickets.
- Updated seeder to set default ticket generation policy for specific tenant.
- Enhanced tests to cover new functionality, including ticket generation based on event dates and validity times.
- Refactored ticket validity checks to accommodate multiple validity times in a group.
2026-08-11 12:29:32 -03:00
2115d2384d feat(ticket): add tickets endpoint and resource for sales; implement ticket retrieval logic and tests 2026-08-11 11:20:55 -03:00
a458c564ca feat(sale): implement confirm and cancel functionality for sales in AdminApp; update routes and tests 2026-08-11 11:00:09 -03:00
68dd373d61 feat(tenant): add display options for categories and search bar; update requests, migrations, seeder, and tests 2026-08-11 10:04:18 -03:00
8d8e49fcfb feat(event): implement automatic tenant date text synchronization on save and delete; update related tests 2026-08-11 09:49:59 -03:00
19b506a465 feat(catalog): add scope to filter available variants and update related queries; enhance seeder and tests for stock validation 2026-08-11 09:10:26 -03:00
6f63a87af5 feat(test): add unit test for SaleDetailResource serialization 2026-08-10 17:11:45 -03:00
a59b96dd22 feat(sale): add sale detail retrieval functionality; implement controller method and resource, and create corresponding tests 2026-08-10 17:10:55 -03:00
6354e26620 feat(ticket): append variant properties to ticket name in generation process; add corresponding test case 2026-08-10 17:10:46 -03:00
69320c54d4 feat: remove EventProductType references and related logic from catalog and fiesta futbol infantil components 2026-08-10 16:37:28 -03:00
5bfc8b9f70 feat(seeder): update product layout and group layout for Fiesta Futbol Infantil seeder; adjust related test assertions 2026-08-10 15:05:42 -03:00
17f4cb6502 feat: enable ticketing for Fiesta Futbol Infantil catalog items; update services, migrations, seeders, and tests to reflect changes 2026-08-10 14:13:46 -03:00
6844ab7af9 feat(cart): update CartItemResource to use visibleVariants method with included variant ID; enhance variant filtering logic 2026-08-10 13:59:45 -03:00
8542c03466 feat: enhance item attributes management by adding sort order; update related models, resources, and tests for visibility and ordering of variants 2026-08-10 13:58:35 -03:00
e7c8807a67 feat(variant): refactor selection values to expose options with labels; update related resources and tests for consistency 2026-08-10 12:27:00 -03:00
c6351d706f feat(cart): enhance item update functionality to support variant changes and stock management; update related request validation and resource formatting; add tests for variant handling in cart 2026-08-10 12:08:09 -03:00
2693df2cbf feat: implement delete functionality for accommodations, entries, foods, and merchandise; enhance related services and tests 2026-08-10 11:33:05 -03:00
4aaa66dc38 feat(event): add EventDateTextFormatter for formatting event dates; update Tenant model and resource to include event_date_text; create migration for event_date_text column; enhance tests for event date formatting and tenant updates 2026-08-10 10:42:12 -03:00
1cd60f7021 feat(food): implement FoodFormController and FoodFormService; add FoodFormResource for managing food options and routes 2026-08-10 10:05:35 -03:00
ca605127d0 feat: implement index methods for Accommodation, Entry, Food, and Merchandise controllers; add service methods for fetching current items 2026-08-10 10:04:57 -03:00
00489c14d3 feat(forms): implement MerchandiseFormController, MerchandiseFormService, and MerchandiseFormResource for managing merchandise options 2026-08-10 09:28:52 -03:00
63f98b5da2 feat(merchandise): implement MerchandiseController, MerchandiseService, and UpsertMerchandiseRequest for managing merchandise items and variants 2026-08-07 15:05:50 -03:00
b05314b1dd refactor: remove tenant code check and implement middleware for menu validation in controllers 2026-08-07 14:44:52 -03:00
feed3205eb feat(accommodation): implement AccommodationController, AccommodationService, and UpsertAccommodationVariantsRequest for managing accommodations 2026-08-07 14:43:06 -03:00
11776f0734 refactor: integrate category handling for entries and food items in services and tests 2026-08-07 14:34:59 -03:00
e1ad27ecf0 feat(food): implement FoodController, FoodService, and related resources for managing food items and variants
refactor(catalog): add description and price fields to variants and update related resources

feat(migration): add commercial overrides to variants with description and price fields

test(food): add tests for FoodController and ensure correct seeding of food items and variants
2026-08-07 14:17:51 -03:00
6a6d3690cc feat(entry): implement EntryController, EntryService, and EntryResource for managing entries 2026-08-07 12:34:38 -03:00
ed4502425a refactor(catalog): replace hardcoded validation messages with translatable strings 2026-08-07 12:07:40 -03:00
6318a99328 refactor(variant): enhance selection values handling for multi-select attributes 2026-08-07 12:07:07 -03:00
21b70777f2 feat: add support for multiple event dates in variants
- Updated the FeaturedGroupService to include 'variants.eventDates' in the items query.
- Introduced a BelongsToMany relationship in EventDate for selected variants.
- Modified PurchaseItemResource and PurchaseItemSnapshotFactory to handle multiple event dates for variants.
- Enhanced StartCheckoutService to load event dates for variants.
- Updated TicketGeneratorService to accommodate event dates in ticket generation.
- Created migrations to support multi-value event dates and allow multiple variant values per attribute.
- Adjusted seeders to reflect new event date handling and added new attributes.
- Added tests to ensure correct functionality for multi-date variants and their integration with ticket generation.
2026-08-07 11:57:38 -03:00
91af233941 refactor(ticket): implement fixed validity time generation for event date and time windows in TicketGeneratorService 2026-08-07 10:43:05 -03:00
717ee5d194 refactor(catalog): add event date attribute with dynamic options and update related logic 2026-08-07 10:03:31 -03:00
14d53d1e0b refactor(catalog): handle null validity time in CatalogItemDetailResource and update related tests 2026-08-07 09:20:52 -03:00
7b7efeb4cc refactor(event): move event configuration onto tenant 2026-08-07 09:08:14 -03:00
60b8415c59 refactor(checkout): split checkout workflows into focused services 2026-08-07 09:04:36 -03:00
f578c6e24a feat(cart): implement user purchase limit validation for cart items and add related tests 2026-08-06 16:43:04 -03:00
5ad61eb217 feat(catalog): add max_units_per_user field to catalog items and implement purchase limit validation 2026-08-06 16:37:48 -03:00
20dd246cd8 feat(validity-time): add ValidityTimeResource and integrate into catalog and ticket resources 2026-08-06 16:13:29 -03:00
7561ba756c refactor(validity-time): remove 'active' field from ValidityTime model and related migrations/tests 2026-08-06 16:09:11 -03:00
b224dd8650 refactor(ticket): remove service_date field and update validity time logic 2026-08-06 16:05:08 -03:00
448ffb4102 feat(ticket): implement validity time management for tickets and catalog items
- Added ValidityTime model and migration to manage ticket validity periods.
- Updated TicketGeneratorService to resolve and assign validity times to tickets.
- Refactored ticket generation logic to remove legacy date fields and use validity time.
- Introduced timezone support for tenants to handle service dates correctly.
- Updated migrations to remove deprecated columns and add foreign keys for validity times.
- Modified seeders and tests to accommodate new validity time structure.
- Enhanced tests to validate ticket generation and validity time behavior.
2026-08-06 15:52:19 -03:00
7f01adab73 feat(seeders): update FiestaFutbolInfantil seeders and tests to include new categories and menu items 2026-08-06 14:12:58 -03:00
858 changed files with 9288 additions and 49633 deletions

View File

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

View File

@@ -1,29 +1,19 @@
# Project Conventions
## Test database safety
- Tests must use SQLite `:memory:` through `tests/bootstrap.php` and `Tests\TestCase`.
- Never run tests, `migrate:fresh`, `migrate:refresh`, or `db:wipe` against a persistent database, including the developer's `shopit` database.
- Never bypass the connection safety guard to resolve test failures. Use `php tests/verify-database-safety.php` to verify isolation without queries or migrations.
## Architecture
This project uses a domain-oriented structure grouped by business area under
`app/Domains`. Cross-cutting modules live under `app/Shared`.
This project uses a domain-oriented structure under `app/Domains`.
Business domains must live in:
Each domain must live in:
```text
app/Domains/<Area>/<DomainName>/
app/Domains/<DomainName>/
```
The current areas are `Core`, `Commerce`, and `Ticketing`. Cross-cutting
modules live in `app/Shared/<ModuleName>/`.
Supported folders inside each domain:
```text
app/Domains/<Area>/<DomainName>/
app/Domains/<DomainName>/
├── Models/
├── Controllers/
├── Requests/
@@ -38,28 +28,22 @@ app/Domains/<Area>/<DomainName>/
- Root API routes live in `routes/api.php`.
- `routes/api.php` should act as an aggregator only.
- Each business domain defines its own routes in
`app/Domains/<Area>/<DomainName>/routes/api.php`.
- Shared modules that expose routes define them in
`app/Shared/<ModuleName>/routes/api.php`.
- Each domain defines its own routes in `app/Domains/<DomainName>/routes/api.php`.
## Namespaces
Use this namespace pattern:
```php
App\Domains\<Area>\<DomainName>\Models
App\Domains\<Area>\<DomainName>\Controllers
App\Domains\<Area>\<DomainName>\Requests
App\Domains\<Area>\<DomainName>\Resources
App\Domains\<Area>\<DomainName>\Services
App\Domains\<Area>\<DomainName>\Policies
App\Domains\<Area>\<DomainName>\Exceptions
App\Domains\<DomainName>\Models
App\Domains\<DomainName>\Controllers
App\Domains\<DomainName>\Requests
App\Domains\<DomainName>\Resources
App\Domains\<DomainName>\Services
App\Domains\<DomainName>\Policies
App\Domains\<DomainName>\Exceptions
```
For cross-cutting modules, use `App\Shared\<ModuleName>\...`. Reusable enums
and rules live directly under `App\Shared`.
## Responsibilities
- `Models/`: Eloquent models and model relationships.
@@ -90,19 +74,13 @@ and rules live directly under `App\Shared`.
- Namespace, folder, and class names must stay aligned.
- Route files should be named `api.php`.
## Current Areas and Modules
## Current Domains
- `Core`: `Administrator`, `Auth`, `Authorization`, `Bootstrap`, `Client`,
`Menu`, `Staff`, `Tenant`.
- `Commerce`: `Cart`, `Catalog`, `Purchase`, `Sale`.
- `Ticketing`: `Desfile`, `Event`, `FiestaFutbolInfantil`, `Ticket`.
- `Shared`: `Attachable`, `Forms`, `Integration`, `Logging`, `MailTest`,
`Notification`, `StorageTest`, plus shared enums and rules.
- `Tenant`
- `Product`
## Notes For Future Changes
- New features should be added inside the corresponding domain first.
- Add new business features to the appropriate area under `app/Domains`.
- Keep generic reusable code in `app/Shared`; do not use it as a catch-all for
business features.
- If a concern does not belong to an existing domain, create a new domain under `app/Domains`.
- Avoid placing new business code in `app/Http/Controllers` or `app/Models`.

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Shared\Attachable\Enums;
namespace App\Domains\Attachable\Enums;
enum AttachmentType: string
{

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Shared\Attachable\Exceptions;
namespace App\Domains\Attachable\Exceptions;
use RuntimeException;

View File

@@ -1,14 +1,11 @@
<?php
namespace App\Shared\Attachable\Models;
namespace App\Domains\Attachable\Models;
use App\Shared\Attachable\Enums\AttachmentType;
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([
@@ -43,34 +40,12 @@ class Attachment extends Model
];
}
public function cropVariants(): HasMany
{
return $this->hasMany(AttachmentCrop::class);
}
public function desktopCrop(): HasOne
{
return $this->hasOne(AttachmentCrop::class)
->where('variant', AttachmentCrop::DESKTOP);
}
public function mobileCrop(): HasOne
{
return $this->hasOne(AttachmentCrop::class)
->where('variant', AttachmentCrop::MOBILE);
}
public function cropSource(): HasOne
{
return $this->hasOne(AttachmentCrop::class, 'cropped_attachment_id');
}
/**
* Get the pre-signed temporary S3 URL for this attachment.
*/
public function getTemporaryUrl(int $expiresInMinutes = 10): string
{
return Storage::disk('s3')->temporaryUrl(
return \Illuminate\Support\Facades\Storage::disk('s3')->temporaryUrl(
$this->path,
now()->addMinutes($expiresInMinutes)
);

View File

@@ -0,0 +1,289 @@
<?php
namespace App\Domains\Attachable\Services;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Mime\MimeTypes;
use Throwable;
class AttachmentService
{
public function store(
UploadedFile|string $file,
string $path,
): Attachment {
$normalizedPath = $this->normalizeDirectory($path);
if ($normalizedPath === '') {
throw new AttachmentStorageException('The attachment path cannot be empty.');
}
$key = (string) Str::uuid();
$fileData = $this->resolveFileData($file, $key);
$storedPath = $this->storeFile(
$fileData,
$normalizedPath,
$this->buildStoredFilename($key, $fileData['extension']),
);
if (! is_string($storedPath) || $storedPath === '') {
throw new AttachmentStorageException('No se pudo subir el archivo al disco s3.');
}
try {
/** @var Attachment $attachment */
$attachment = Attachment::query()->create([
'key' => $key,
'path' => $storedPath,
'filename' => $this->resolveFilename($file, $key),
'type' => $this->resolveAttachmentType($fileData['mime_type']),
'mime_type' => $fileData['mime_type'],
'extension' => $fileData['extension'],
'size' => $fileData['size'],
]);
return $attachment;
} catch (Throwable $throwable) {
Storage::disk('s3')->delete($storedPath);
throw $throwable;
}
}
public function delete(Attachment $attachment): void
{
$deleted = Storage::disk('s3')->delete($attachment->path);
if (! $deleted) {
throw new AttachmentStorageException('No se pudo eliminar el archivo del disco s3.');
}
$attachment->delete();
}
public function copy(Attachment $source, string $path): Attachment
{
$normalizedPath = $this->normalizeDirectory($path);
if ($normalizedPath === '') {
throw new AttachmentStorageException('The attachment path cannot be empty.');
}
$key = (string) Str::uuid();
$storedPath = $normalizedPath.'/'.$this->buildStoredFilename($key, (string) $source->extension);
$copied = Storage::disk('s3')->copy($source->path, $storedPath);
if (! $copied) {
throw new AttachmentStorageException('No se pudo copiar el archivo en el disco s3.');
}
try {
/** @var Attachment $attachment */
$attachment = Attachment::query()->create([
'key' => $key,
'path' => $storedPath,
'filename' => $source->filename,
'type' => $source->type,
'mime_type' => $source->mime_type,
'extension' => $source->extension,
'size' => $source->size,
]);
return $attachment;
} catch (Throwable $throwable) {
Storage::disk('s3')->delete($storedPath);
throw $throwable;
}
}
protected function normalizeDirectory(string $path): string
{
return trim($path, '/');
}
protected function resolveFilename(UploadedFile|string $file, string $key): string
{
if ($file instanceof UploadedFile) {
$originalName = trim($file->getClientOriginalName());
if ($originalName !== '') {
return $originalName;
}
}
return $key;
}
/**
* @return array{contents: string|null, extension: string, file: UploadedFile|null, mime_type: string, size: int}
*/
protected function resolveFileData(UploadedFile|string $file, string $filename): array
{
if ($file instanceof UploadedFile) {
return $this->fileDataFromUploadedFile($file);
}
return $this->fileDataFromBase64($file, $filename);
}
/**
* @return array{contents: string|null, extension: string, file: UploadedFile, mime_type: string, size: int}
*/
protected function fileDataFromUploadedFile(UploadedFile $file): array
{
$mimeType = strtolower($file->getClientMimeType() ?? $file->getMimeType() ?? 'application/octet-stream');
return [
'contents' => null,
'extension' => strtolower($file->getClientOriginalExtension() ?: $file->extension() ?: ''),
'file' => $file,
'mime_type' => $mimeType,
'size' => $file->getSize() ?? 0,
];
}
/**
* @return array{contents: string, extension: string, file: null, mime_type: string, size: int}
*/
protected function fileDataFromBase64(string $file, string $filename): array
{
['data' => $contents, 'mime_type' => $declaredMimeType] = $this->decodeBase64File($file);
$mimeType = $this->detectMimeType($contents, $declaredMimeType);
return [
'contents' => $contents,
'extension' => $this->resolveExtension($filename, $mimeType),
'file' => null,
'mime_type' => $mimeType,
'size' => strlen($contents),
];
}
/**
* @return array{data: string, mime_type: string|null}
*/
protected function decodeBase64File(string $file): array
{
$payload = trim($file);
if ($payload === '') {
throw new AttachmentStorageException('The base64 attachment content cannot be empty.');
}
$declaredMimeType = null;
if (preg_match('/^data:(?<mime>[-\w.+\/]+);base64,(?<data>.+)$/s', $payload, $matches) === 1) {
$declaredMimeType = strtolower($matches['mime']);
$payload = $matches['data'];
}
$decoded = base64_decode(preg_replace('/\s+/', '', $payload), true);
if ($decoded === false || $decoded === '') {
throw new AttachmentStorageException('The attachment base64 payload is invalid.');
}
return [
'data' => $decoded,
'mime_type' => $declaredMimeType,
];
}
protected function detectMimeType(string $contents, ?string $fallback = null): string
{
if (is_string($fallback) && $fallback !== '') {
return strtolower($fallback);
}
$detectedMimeType = (new \finfo(FILEINFO_MIME_TYPE))->buffer($contents);
if (is_string($detectedMimeType) && $detectedMimeType !== '') {
return strtolower($detectedMimeType);
}
return strtolower($fallback ?? 'application/octet-stream');
}
protected function resolveExtension(string $filename, string $mimeType): string
{
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if ($extension !== '') {
return $extension;
}
return strtolower(MimeTypes::getDefault()->getExtensions($mimeType)[0] ?? '');
}
/**
* @param array{contents: string|null, extension: string, file: UploadedFile|null, mime_type: string, size: int} $fileData
*/
protected function storeFile(array $fileData, string $directory, string $storedFilename): string
{
if ($fileData['file'] instanceof UploadedFile) {
return Storage::disk('s3')->putFileAs($directory, $fileData['file'], $storedFilename);
}
$storedPath = $directory !== ''
? $directory.'/'.$storedFilename
: $storedFilename;
$stored = Storage::disk('s3')->put($storedPath, $fileData['contents'] ?? '');
if (! $stored) {
return '';
}
return $storedPath;
}
protected function resolveAttachmentType(string $mimeType): AttachmentType
{
$mimeType = strtolower($mimeType);
if (str_starts_with($mimeType, 'image/')) {
return AttachmentType::Image;
}
if (str_starts_with($mimeType, 'video/')) {
return AttachmentType::Video;
}
if ($mimeType === 'application/pdf') {
return AttachmentType::Pdf;
}
if (str_starts_with($mimeType, 'audio/')) {
return AttachmentType::Audio;
}
if (
str_starts_with($mimeType, 'text/')
|| str_contains($mimeType, 'document')
|| str_contains($mimeType, 'word')
|| str_contains($mimeType, 'excel')
|| str_contains($mimeType, 'spreadsheet')
|| str_contains($mimeType, 'presentation')
|| str_contains($mimeType, 'officedocument')
) {
return AttachmentType::Document;
}
return AttachmentType::Other;
}
protected function buildStoredFilename(string $key, string $extension): string
{
if ($extension === '') {
return $key;
}
return $key.'.'.$extension;
}
}

View File

@@ -2,12 +2,11 @@
## Propósito
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única. Para imágenes también permite guardar un original junto con variantes recortadas para desktop y mobile.
Centraliza el almacenamiento y la metadata de archivos adjuntos. Acepta archivos subidos o contenido Base64, los persiste en S3 y registra su tipo, MIME, extensión, tamaño, nombre original y clave única.
## Componentes principales
- `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.
@@ -26,8 +25,5 @@ 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.

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Requests\AdminAppLoginRequest;
use App\Domains\Core\Auth\Resources\UserResource;
use App\Domains\Core\Auth\Services\PasswordLoginService;
use App\Domains\Auth\Requests\AdminAppLoginRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\PasswordLoginService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Auth\Resources\AdminAppMeResource;
use App\Domains\Core\Auth\Services\AdminAppContextService;
use App\Domains\Auth\Models\User;
use App\Domains\Auth\Resources\AdminAppMeResource;
use App\Domains\Auth\Services\AdminAppContextService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Models\ResetPasswordAttempt;
use App\Domains\Core\Auth\Requests\CreateResetPasswordAttemptRequest;
use App\Domains\Core\Auth\Services\ResetPasswordAttemptService;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Requests\CreateResetPasswordAttemptRequest;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Services\GoogleAuthService;
use App\Domains\Auth\Services\GoogleAuthService;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

View File

@@ -1,11 +1,11 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Requests\GoogleTokenExchangeRequest;
use App\Domains\Core\Auth\Resources\UserResource;
use App\Domains\Core\Auth\Services\GoogleAuthService;
use App\Domains\Commerce\Cart\Services\GuestCartMergeService;
use App\Domains\Auth\Requests\GoogleTokenExchangeRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\GoogleAuthService;
use App\Domains\Cart\Services\GuestCartMergeService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cookie;

View File

@@ -1,11 +1,11 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Requests\LoginUserRequest;
use App\Domains\Core\Auth\Resources\UserResource;
use App\Domains\Core\Auth\Services\PasswordLoginService;
use App\Domains\Commerce\Cart\Services\GuestCartMergeService;
use App\Domains\Auth\Requests\LoginUserRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\PasswordLoginService;
use App\Domains\Cart\Services\GuestCartMergeService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cookie;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Resources\UserResource;
use App\Domains\Auth\Resources\UserResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Requests\RegisterUserRequest;
use App\Domains\Core\Auth\Resources\UserResource;
use App\Domains\Core\Auth\Services\RegisterUserService;
use App\Domains\Auth\Requests\RegisterUserRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\RegisterUserService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

View File

@@ -1,11 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Models\ResetPasswordAttempt;
use App\Domains\Core\Auth\Requests\ResetPasswordRequest;
use App\Domains\Core\Auth\Services\ResetPasswordAttemptService;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Requests\ResetPasswordRequest;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
@@ -27,7 +26,6 @@ class ResetPasswordController extends Controller
$data['email'],
$data['codigo'],
$data['password'],
RoleCode::from($request->route('reset_role', RoleCode::User->value)),
)) {
throw ValidationException::withMessages([
'codigo' => __('api.auth.password_reset_invalid'),

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Requests\UpdateProfileRequest;
use App\Domains\Core\Auth\Resources\UserResource;
use App\Domains\Core\Auth\Services\ProfileService;
use App\Domains\Auth\Requests\UpdateProfileRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\ProfileService;
use Illuminate\Http\JsonResponse;
class UpdateProfileController

View File

@@ -1,11 +1,10 @@
<?php
namespace App\Domains\Core\Auth\Controllers;
namespace App\Domains\Auth\Controllers;
use App\Domains\Core\Auth\Models\ResetPasswordAttempt;
use App\Domains\Core\Auth\Requests\ValidateResetPasswordAttemptRequest;
use App\Domains\Core\Auth\Services\ResetPasswordAttemptService;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Requests\ValidateResetPasswordAttemptRequest;
use App\Domains\Auth\Services\ResetPasswordAttemptService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
@@ -23,19 +22,10 @@ class ValidateResetPasswordAttemptController extends Controller
{
$data = $request->validated();
$result = $this->resetPasswordAttemptService->validateCode(
if (! $this->resetPasswordAttemptService->validateCode(
$data['email'],
$data['codigo'],
RoleCode::from($request->route('reset_role', RoleCode::User->value)),
);
if ($result === ResetPasswordAttemptService::CODE_EXPIRED) {
throw ValidationException::withMessages([
'codigo' => __('api.auth.reset_code_expired'),
]);
}
if ($result !== ResetPasswordAttemptService::CODE_VALID) {
)) {
throw ValidationException::withMessages([
'codigo' => __('api.auth.reset_code_invalid'),
]);

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Exceptions;
namespace App\Domains\Auth\Exceptions;
use Carbon\CarbonImmutable;
use RuntimeException;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Models;
namespace App\Domains\Auth\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;

View File

@@ -1,24 +1,16 @@
<?php
namespace App\Domains\Core\Auth\Models;
namespace App\Domains\Auth\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['user_id', 'codigo', 'reason', 'status', 'expires_at'])]
#[Fillable(['user_id', 'codigo', 'reason', 'status'])]
#[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 REASON_ADMINISTRATOR_CREATED = 'administrator_created';
public const STATUS_PENDING = 'pending';
public const STATUS_VALIDATED = 'validated';
@@ -33,7 +25,6 @@ class ResetPasswordAttempt extends Model
{
return [
'user_id' => 'integer',
'expires_at' => 'datetime',
];
}

View File

@@ -1,13 +1,11 @@
<?php
namespace App\Domains\Core\Auth\Models;
namespace App\Domains\Auth\Models;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Core\Authorization\Models\Role;
use App\Domains\Commerce\Catalog\Models\Category;
use App\Domains\Ticketing\Event\Models\EventDateChangeView;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\ScanAttempt;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category;
use App\Domains\Tenant\Models\Tenant;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -15,17 +13,16 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id', 'rol_codigo', 'tenant_codigo'])]
#[Hidden(['password', 'remember_token', 'active_email', 'active_google_id'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasApiTokens, HasFactory, Notifiable, SoftDeletes;
use HasApiTokens, HasFactory, Notifiable;
protected $attributes = [
'rol_codigo' => RoleCode::User->value,
@@ -48,18 +45,6 @@ class User extends Authenticatable
return $this->hasMany(LoginAttempt::class);
}
/** @return HasMany<ScanAttempt, $this> */
public function scanAttempts(): HasMany
{
return $this->hasMany(ScanAttempt::class, 'scanner_user_id');
}
/** @return HasMany<EventDateChangeView, $this> */
public function eventDateChangeViews(): HasMany
{
return $this->hasMany(EventDateChangeView::class);
}
/**
* @return BelongsTo<Role, $this>
*/
@@ -68,16 +53,6 @@ class User extends Authenticatable
return $this->belongsTo(Role::class, 'rol_codigo', 'codigo');
}
public function hasPermission(string $permissionCode): bool
{
return $this->role()
->whereHas(
'permissions',
fn ($query) => $query->where('permisos.codigo', $permissionCode)
)
->exists();
}
/**
* @return BelongsTo<Tenant, $this>
*/

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

View File

@@ -1,8 +1,7 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use App\Domains\Core\Authorization\Enums\RoleCode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
@@ -14,26 +13,15 @@ class RegisterUserRequest extends FormRequest
return true;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
/** @return array<string, mixed> */
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'tenant_codigo' => ['nullable', 'string', Rule::exists('tenants', 'codigo')],
'nombre_apellido' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique('users', 'active_email')->where('rol_codigo', RoleCode::User->value)->whereNull('deleted_at'),
],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
'password' => ['required', 'string', 'confirmed', Password::min(8)->mixedCase()->symbols()],
'dni' => ['nullable', 'string', 'max:255'],
'telefono' => ['nullable', 'string', 'max:255'],

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

View File

@@ -1,10 +1,9 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
class UpdateProfileRequest extends FormRequest
{
@@ -13,13 +12,6 @@ class UpdateProfileRequest extends FormRequest
return true;
}
protected function prepareForValidation(): void
{
if (is_string($this->input('email'))) {
$this->merge(['email' => mb_strtolower(trim($this->input('email')))]);
}
}
public function rules(): array
{
return [
@@ -27,13 +19,11 @@ class UpdateProfileRequest extends FormRequest
'email' => [
'required',
'email',
Rule::unique('users', 'active_email')->where('rol_codigo', $this->user()->rol_codigo)
->whereNull('deleted_at')
->ignore($this->user()->id),
Rule::unique('users', 'email')->ignore($this->user()->id),
],
'dni' => ['nullable', 'string', 'regex:/^[0-9]{7,8}$/'],
'telefono' => ['nullable', 'string', 'regex:/^\+?[0-9\s\-]+$/'],
'password' => ['nullable', 'string', Password::min(8)->mixedCase()->symbols()],
'password' => ['nullable', 'string', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
];
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Auth\Requests;
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Core\Auth\Resources;
namespace App\Domains\Auth\Resources;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Resources\TenantResource;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Resources\TenantResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Core\Auth\Resources;
namespace App\Domains\Auth\Resources;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Auth\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -24,11 +24,6 @@ class UserResource extends JsonResource
'telefono' => $this->telefono,
'rol_codigo' => $this->rol_codigo,
'tenant_codigo' => $this->tenant_codigo,
'categories' => $this->whenLoaded('scanCategories', fn () => $this->scanCategories
->map(fn ($category) => [
'id' => $category->id,
'nombre' => $category->nombre,
])->values()),
];
}
}

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Core\Auth\Services;
namespace App\Domains\Auth\Services;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
class AdminAppContextService
{

View File

@@ -1,12 +1,11 @@
<?php
namespace App\Domains\Core\Auth\Services;
namespace App\Domains\Auth\Services;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Shared\Notification\Events\UserRegistered;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Core\Tenant\Support\TenantDomainNormalizer;
use App\Domains\Auth\Models\User;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
@@ -125,12 +124,12 @@ class GoogleAuthService
]);
}
$user = User::query()->where('rol_codigo', RoleCode::User->value)->where('google_id', $googleId)->first();
$user = User::query()->where('google_id', $googleId)->first();
if ($user) {
return $user;
}
$user = User::query()->where('rol_codigo', RoleCode::User->value)->where('active_email', mb_strtolower(trim($email)))->first();
$user = User::query()->where('email', $email)->first();
if ($user) {
$user->forceFill(['google_id' => $googleId])->save();
@@ -156,19 +155,16 @@ class GoogleAuthService
$parts = parse_url($returnUrl);
if (! is_array($parts)
|| ! isset($parts['scheme'], $parts['host'])
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])) {
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|| ($parts['path'] ?? '') !== '') {
return false;
}
$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
|| $returnPath !== $tenant->base_path) {
if ($host === null || $tenantDomain === null || $host !== $tenantDomain) {
return false;
}

View File

@@ -1,14 +1,11 @@
<?php
namespace App\Domains\Core\Auth\Services;
namespace App\Domains\Auth\Services;
use App\Domains\Core\Auth\Exceptions\AccountLockedException;
use App\Domains\Core\Auth\Models\LoginAttempt;
use App\Domains\Core\Auth\Models\ResetPasswordAttempt;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Authorization\Enums\PermissionCode;
use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Shared\Notification\Events\PasswordResetRequested;
use App\Domains\Auth\Exceptions\AccountLockedException;
use App\Domains\Auth\Models\LoginAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
@@ -62,33 +59,6 @@ class PasswordLoginService
$userAgent,
RoleCode::AdminApp,
true,
null,
PasswordResetRequested::CHANNEL_ADMINAPP,
);
}
/**
* Authenticate a tenant-bound user authorized to scan tickets.
*
* @throws AccountLockedException
* @throws ValidationException
*/
public function authenticateScanner(
string $email,
string $password,
?string $ipAddress,
?string $userAgent,
): User {
return $this->authenticateUser(
$email,
$password,
null,
$ipAddress,
$userAgent,
RoleCode::Scanner,
true,
PermissionCode::ScanTickets->value,
PasswordResetRequested::CHANNEL_SCANNER,
);
}
@@ -98,10 +68,8 @@ class PasswordLoginService
?string $tenantCode,
?string $ipAddress,
?string $userAgent,
?RoleCode $requiredRole = RoleCode::User,
RoleCode $requiredRole = RoleCode::User,
bool $requiresTenant = false,
?string $requiredPermission = null,
string $passwordResetChannel = PasswordResetRequested::CHANNEL_STOREFRONT,
): User {
$normalizedEmail = mb_strtolower(trim($email));
$now = CarbonImmutable::now();
@@ -116,22 +84,10 @@ class PasswordLoginService
$now,
$requiredRole,
$requiresTenant,
$requiredPermission,
$passwordResetChannel,
): array {
$user = User::query()
->where('active_email', $normalizedEmail)
->when(
$requiredRole !== null,
fn ($query) => $query->where('rol_codigo', $requiredRole->value),
)
->when(
$requiredPermission !== null,
fn ($query) => $query->whereHas(
'role.permissions',
fn ($query) => $query->where('permisos.codigo', $requiredPermission)
),
)
->where('email', $normalizedEmail)
->where('rol_codigo', $requiredRole->value)
->when(
$requiresTenant,
fn ($query) => $query->whereNotNull('tenant_codigo'),
@@ -166,13 +122,8 @@ class PasswordLoginService
}
if ($user === null || ! Hash::check($password, $user->password)) {
if ($user !== null && $attemptTenantCode !== null) {
$this->registerFailure(
$user,
$now,
$attemptTenantCode,
$passwordResetChannel,
);
if ($user !== null) {
$this->registerFailure($user, $now, $tenantCode);
}
$outcome = $user?->locked_until?->isFuture()
@@ -231,12 +182,8 @@ class PasswordLoginService
return $result['user'];
}
private function registerFailure(
User $user,
CarbonImmutable $now,
string $tenantCode,
string $passwordResetChannel,
): void {
private function registerFailure(User $user, CarbonImmutable $now, string $tenantCode): 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'));
@@ -259,27 +206,11 @@ class PasswordLoginService
if ($attempts >= $maxAttempts && $previousAttempts < $maxAttempts) {
try {
if ($passwordResetChannel === PasswordResetRequested::CHANNEL_ADMINAPP) {
$this->resetPasswordAttemptService->createForAdminAppEmail(
$user->email,
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
);
} elseif ($passwordResetChannel === PasswordResetRequested::CHANNEL_SCANNER) {
$this->resetPasswordAttemptService->createForScannerEmail(
$user->email,
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
);
} else {
$this->resetPasswordAttemptService->createForEmail(
$user->email,
$tenantCode,
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED,
);
}
$this->resetPasswordAttemptService->createForEmail($user->email, $tenantCode, 'account_locked');
} catch (\Throwable $e) {
Log::error('Failed to trigger reset password on account lock', [
'user_id' => $user->id,
'exception' => $e,
'exception' => $e
]);
}
}

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Core\Auth\Services;
namespace App\Domains\Auth\Services;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Auth\Models\User;
use Illuminate\Support\Facades\Hash;
class ProfileService

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Core\Auth\Services;
namespace App\Domains\Auth\Services;
use App\Domains\Core\Auth\Models\User;
use App\Shared\Notification\Events\UserRegistered;
use App\Domains\Auth\Models\User;
use App\Domains\Notification\Events\UserRegistered;
class RegisterUserService
{

View File

@@ -0,0 +1,181 @@
<?php
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Notification\Events\PasswordResetRequested;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
class ResetPasswordAttemptService
{
public function createForEmail(string $email, string $tenantCode, string $reason = 'manual'): void
{
$emailFingerprint = $this->emailFingerprint($email);
try {
$attemptId = DB::transaction(function () use ($email, $emailFingerprint, $reason): ?int {
$user = User::query()
->where('email', $email)
->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();
});
} catch (Throwable $exception) {
Log::error('Failed to create password reset attempt.', [
'email_fingerprint' => $emailFingerprint,
'exception' => $exception,
]);
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,
]);
throw $exception;
}
}
}
public function validateCode(string $email, string $code): bool
{
$emailFingerprint = $this->emailFingerprint($email);
try {
return DB::transaction(function () use ($email, $code, $emailFingerprint): bool {
$user = User::query()
->where('email', $email)
->lockForUpdate()
->first();
$attempt = $user?->resetPasswordAttempts()
->where('codigo', $code)
->where('status', ResetPasswordAttempt::STATUS_PENDING)
->latest('id')
->lockForUpdate()
->first();
if ($attempt === null) {
Log::warning('Password reset code validation failed: no matching pending attempt.', [
'email_fingerprint' => $emailFingerprint,
]);
return false;
}
$attempt->update([
'status' => ResetPasswordAttempt::STATUS_VALIDATED,
]);
return true;
});
} catch (Throwable $exception) {
Log::error('Failed to validate password reset code.', [
'email_fingerprint' => $emailFingerprint,
'exception' => $exception,
]);
throw $exception;
}
}
public function resetPassword(string $email, string $code, string $password): bool
{
$emailFingerprint = $this->emailFingerprint($email);
try {
return DB::transaction(function () use ($email, $code, $password, $emailFingerprint): bool {
$user = User::query()
->where('email', $email)
->lockForUpdate()
->first();
$attempt = $user?->resetPasswordAttempts()
->where('codigo', $code)
->where('status', ResetPasswordAttempt::STATUS_VALIDATED)
->latest('id')
->lockForUpdate()
->first();
if ($user === null || $attempt === null) {
Log::warning('Password reset failed: no matching validated attempt.', [
'email_fingerprint' => $emailFingerprint,
]);
return false;
}
$user->password = $password;
$user->failed_login_attempts = 0;
$user->last_failed_login_at = null;
$user->locked_until = null;
$user->save();
$user->tokens()->delete();
$user->resetPasswordAttempts()
->whereKeyNot($attempt->getKey())
->whereIn('status', [
ResetPasswordAttempt::STATUS_PENDING,
ResetPasswordAttempt::STATUS_VALIDATED,
])
->update(['status' => ResetPasswordAttempt::STATUS_EXPIRED]);
$attempt->update([
'status' => ResetPasswordAttempt::STATUS_USED,
]);
return true;
});
} catch (Throwable $exception) {
Log::error('Failed to reset user password.', [
'email_fingerprint' => $emailFingerprint,
'exception' => $exception,
]);
throw $exception;
}
}
private function generateCode(): string
{
return str_pad((string) random_int(0, 9999), 4, '0', STR_PAD_LEFT);
}
private function emailFingerprint(string $email): string
{
return substr(hash('sha256', strtolower(trim($email))), 0, 12);
}
}

View File

@@ -0,0 +1,11 @@
<?php
use App\Domains\Auth\Controllers\AdminAppLoginController;
use App\Domains\Auth\Controllers\AdminAppMeController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp')->group(function (): void {
Route::post('login', AdminAppLoginController::class)->middleware('throttle:login');
Route::middleware(['auth:sanctum', 'adminapp.tenant'])
->get('me', AdminAppMeController::class);
});

View File

@@ -1,14 +1,14 @@
<?php
use App\Domains\Core\Auth\Controllers\CreateResetPasswordAttemptController;
use App\Domains\Core\Auth\Controllers\GoogleTokenExchangeController;
use App\Domains\Core\Auth\Controllers\LoginController;
use App\Domains\Core\Auth\Controllers\LogoutController;
use App\Domains\Core\Auth\Controllers\MeController;
use App\Domains\Core\Auth\Controllers\RegisterController;
use App\Domains\Core\Auth\Controllers\ResetPasswordController;
use App\Domains\Core\Auth\Controllers\UpdateProfileController;
use App\Domains\Core\Auth\Controllers\ValidateResetPasswordAttemptController;
use App\Domains\Auth\Controllers\CreateResetPasswordAttemptController;
use App\Domains\Auth\Controllers\GoogleTokenExchangeController;
use App\Domains\Auth\Controllers\LoginController;
use App\Domains\Auth\Controllers\LogoutController;
use App\Domains\Auth\Controllers\MeController;
use App\Domains\Auth\Controllers\RegisterController;
use App\Domains\Auth\Controllers\ResetPasswordController;
use App\Domains\Auth\Controllers\UpdateProfileController;
use App\Domains\Auth\Controllers\ValidateResetPasswordAttemptController;
use Illuminate\Support\Facades\Route;
Route::post('/register', RegisterController::class);
@@ -25,4 +25,3 @@ Route::middleware('auth:sanctum')->get('/me', MeController::class);
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);
require __DIR__.'/adminapp.php';
require __DIR__.'/scanner.php';

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Authorization\Enums;
namespace App\Domains\Authorization\Enums;
enum RoleCode: string
{

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Authorization\Models;
namespace App\Domains\Authorization\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Authorization\Models;
namespace App\Domains\Authorization\Models;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Menu\Models\Menu;
use App\Domains\Core\Menu\Models\MenuRole;
use App\Domains\Auth\Models\User;
use App\Domains\Menu\Models\Menu;
use App\Domains\Menu\Models\MenuRole;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Core\Authorization\Models;
namespace App\Domains\Authorization\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Core\Bootstrap\Controllers;
namespace App\Domains\Bootstrap\Controllers;
use App\Domains\Core\Bootstrap\Requests\AdminAppBootstrapRequest;
use App\Domains\Core\Bootstrap\Resources\AdminAppBootstrapResource;
use App\Domains\Core\Bootstrap\Services\AdminAppBootstrapService;
use App\Domains\Bootstrap\Requests\AdminAppBootstrapRequest;
use App\Domains\Bootstrap\Resources\AdminAppBootstrapResource;
use App\Domains\Bootstrap\Services\AdminAppBootstrapService;
use App\Http\Controllers\Controller;
class AdminAppBootstrapController extends Controller

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Domains\Bootstrap\Controllers;
use App\Domains\Bootstrap\Requests\TenantBootstrapRequest;
use App\Domains\Bootstrap\Services\TenantBootstrapService;
use App\Domains\Tenant\Resources\TenantResource;
use App\Http\Controllers\Controller;
class TenantBootstrapController extends Controller
{
public function __construct(protected TenantBootstrapService $bootstrapService) {}
public function __invoke(TenantBootstrapRequest $request): TenantResource
{
return TenantResource::make(
$this->bootstrapService->get((string) $request->validated('dominio'))
);
}
}

View File

@@ -1,5 +1,5 @@
<?php
namespace App\Domains\Core\Bootstrap\Requests;
namespace App\Domains\Bootstrap\Requests;
class AdminAppBootstrapRequest extends TenantBootstrapRequest {}

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Core\Bootstrap\Requests;
namespace App\Domains\Bootstrap\Requests;
use App\Domains\Core\Tenant\Support\TenantDomainNormalizer;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Closure;
use Illuminate\Foundation\Http\FormRequest;
@@ -10,8 +10,6 @@ class TenantBootstrapRequest extends FormRequest
{
protected bool $hasInvalidDomain = false;
protected bool $hasInvalidPath = false;
public function authorize(): bool
{
return true;
@@ -19,20 +17,13 @@ class TenantBootstrapRequest extends FormRequest
protected function prepareForValidation(): void
{
$rawDomain = $this->query('dominio', $this->route('dominio'));
$rawPath = $this->query('path', '/');
$rawDomain = $this->route('dominio');
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
$normalizedPath = TenantDomainNormalizer::normalizePath($rawPath);
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
&& $normalizedDomain === null;
$this->hasInvalidPath = ! is_string($rawPath) || $normalizedPath === null;
$this->merge([
'dominio' => $normalizedDomain,
'path' => $normalizedPath,
]);
$this->merge(['dominio' => $normalizedDomain]);
}
/** @return array<string, mixed> */
@@ -50,17 +41,6 @@ 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',
],
];
}
}

View File

@@ -1,23 +1,22 @@
<?php
namespace App\Domains\Core\Bootstrap\Resources;
namespace App\Domains\Bootstrap\Resources;
use App\Domains\Core\Tenant\Models\AdminWebsiteType;
use App\Domains\Tenant\Models\WebsiteType;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin array{website_type: AdminWebsiteType} */
/** @mixin array{website_type: WebsiteType} */
class AdminAppBootstrapResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
/** @var AdminWebsiteType $websiteType */
/** @var WebsiteType $websiteType */
$websiteType = $this->resource['website_type'];
return [
'admin_website_type_code' => $websiteType->codigo,
'site_title' => $websiteType->site_title,
'website_type_code' => $websiteType->codigo,
'primary_color' => $websiteType->primary_color,
'secondary_color' => $websiteType->secondary_color,
'danger_color' => $websiteType->danger_color,
@@ -31,7 +30,6 @@ class AdminAppBootstrapResource extends JsonResource
'login_header_footer_color' => $websiteType->login_header_footer_color,
'site_logo' => $websiteType->siteLogo?->getTemporaryUrl(1440),
'footer_logo' => $websiteType->footerLogo?->getTemporaryUrl(1440),
'favicon' => $websiteType->favicon?->getTemporaryUrl(1440),
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Domains\Bootstrap\Services;
use App\Domains\Tenant\Models\WebsiteType;
class AdminAppBootstrapService
{
/** @return array{website_type: WebsiteType} */
public function get(string $domain): array
{
return [
'website_type' => WebsiteType::query()
->with(['siteLogo', 'footerLogo'])
->where('dominio', $domain)
->firstOrFail(),
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Bootstrap\Services;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantInformationService;
class TenantBootstrapService
{
public function __construct(protected TenantInformationService $tenantInformationService) {}
public function get(string $domain): Tenant
{
return $this->tenantInformationService->load(
Tenant::query()->where('dominio', $domain)->firstOrFail(),
[
'menues' => fn ($query) => $query->whereHas(
'roles',
fn ($query) => $query->where('codigo', RoleCode::User->value)
),
'categories' => fn ($query) => $query->orderBy('nombre'),
]
);
}
}

View File

@@ -12,12 +12,12 @@ Entrega la configuración inicial que necesitan la tienda y el panel administrat
## Endpoints
- `GET /tenants/bootstrap?dominio={hostname}&path={path}`: bootstrap público de la tienda. Resuelve la clave de tenant más específica que sea prefijo completo del path y usa el dominio raíz como fallback.
- `GET /tenants/bootstrap/{dominio}`: bootstrap público de la tienda.
- Endpoint de bootstrap bajo `/v1/adminapp`, protegido por `auth:sanctum` y `adminapp.tenant`.
## Validación
`TenantBootstrapRequest` valida y normaliza por separado el hostname y el path recibidos. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
`TenantBootstrapRequest` valida el dominio recibido. `AdminAppBootstrapRequest` reutiliza ese contrato para el panel.
## Dependencias

View File

@@ -1,6 +1,6 @@
<?php
use App\Domains\Core\Bootstrap\Controllers\AdminAppBootstrapController;
use App\Domains\Bootstrap\Controllers\AdminAppBootstrapController;
use Illuminate\Support\Facades\Route;
Route::get(

View File

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

View File

@@ -1,13 +1,13 @@
<?php
namespace App\Domains\Commerce\Cart\Controllers;
namespace App\Domains\Cart\Controllers;
use App\Domains\Commerce\Cart\Models\CartItem;
use App\Domains\Commerce\Cart\Requests\AddCartItemRequest;
use App\Domains\Commerce\Cart\Requests\UpdateCartItemQuantityRequest;
use App\Domains\Commerce\Cart\Resources\CartResource;
use App\Domains\Commerce\Cart\Services\CartService;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
use App\Domains\Cart\Resources\CartResource;
use App\Domains\Cart\Services\CartService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

View File

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

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Commerce\Cart\Models;
namespace App\Domains\Cart\Models;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Cart\Requests;
namespace App\Domains\Cart\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Cart\Requests;
namespace App\Domains\Cart\Requests;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin CartItem
*/
class CartItemResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
$selectedItem = $this->selectedItem();
$imageUrl = null;
if ($selectedItem?->relationLoaded('attachments')) {
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
}
if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
}
return [
'id' => $this->id,
'cantidad' => $this->cantidad,
'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(),
],
];
}
protected function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');
}
}

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Commerce\Cart\Resources;
namespace App\Domains\Cart\Resources;
use App\Domains\Commerce\Cart\Models\Cart;
use App\Domains\Cart\Models\Cart;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

View File

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

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Commerce\Cart\Services;
namespace App\Domains\Cart\Services;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Commerce\Cart\Models\Cart;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use Illuminate\Support\Facades\DB;
class GuestCartMergeService
@@ -34,10 +34,6 @@ class GuestCartMergeService
->first();
if ($userCart !== null) {
$userCart->items()
->orderBy('id')
->pluck('id')
->each(fn (int $itemId) => $userCart->removeItem($itemId));
$userCart->update([
'status' => 'converted',
]);

View File

@@ -0,0 +1,32 @@
# Dominio Cart
## Propósito
Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios autenticados.
## Modelo
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; expone la selección efectiva.
## Servicios
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
## Endpoints
Bajo `/tenants/{tenant:codigo}`:
- `GET /cart`.
- `POST /cart/items`.
- `PATCH /cart/items/{cartItem}`.
- `DELETE /cart/items/{cartItem}`.
## Contratos
`AddCartItemRequest` y `UpdateCartItemQuantityRequest` validan selección y cantidad. `CartResource` y `CartItemResource` estabilizan la respuesta pública.
## Dependencias y reglas
Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual.

View File

@@ -1,6 +1,6 @@
<?php
use App\Domains\Commerce\Cart\Controllers\CartController;
use App\Domains\Cart\Controllers\CartController;
use Illuminate\Support\Facades\Route;
Route::prefix('tenants/{tenant:codigo}')

View File

@@ -1,12 +1,12 @@
<?php
namespace App\Domains\Commerce\Catalog\Controllers\AdminApp;
namespace App\Domains\Catalog\Controllers\AdminApp;
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
use App\Domains\Commerce\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
use App\Domains\Commerce\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
use App\Domains\Commerce\Catalog\Services\OnTicketFeaturedGroupService;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Requests\AdminApp\UpsertOnTicketFeaturedGroupRequest;
use App\Domains\Catalog\Resources\AdminApp\OnTicketFeaturedGroupResource;
use App\Domains\Catalog\Services\OnTicketFeaturedGroupService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -58,7 +58,7 @@ class OnTicketFeaturedGroupController extends Controller
{
$tenant = $request->user()->tenant()->firstOrFail();
abort_unless(in_array($tenant->storefront_website_type_code, ['onticket', 'onticket_multi_event'], true), 404);
abort_unless($tenant->website_type_code === 'onticket', 404);
return $tenant;
}

View File

@@ -0,0 +1,127 @@
<?php
namespace App\Domains\Catalog\Controllers;
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\CategoryPageRequest;
use App\Domains\Catalog\Requests\FeaturedGroupPageRequest;
use App\Domains\Catalog\Requests\SearchCatalogItemsRequest;
use App\Domains\Catalog\Requests\StoreCatalogItemRequest;
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\Services\CatalogService;
use App\Domains\Catalog\Services\FeaturedGroupService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class CatalogController extends Controller
{
public function index(Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
{
$featuredGroups = FeaturedGroup::query()
->where('tenant_code', $tenant->codigo)
->orderBy('group_order')
->get();
return response()->json($featuredGroups->map(
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
$featuredGroup,
$featuredGroupService->itemsResponse($featuredGroup, 1),
))->resolve()
));
}
public function search(
SearchCatalogItemsRequest $request,
Tenant $tenant,
CatalogService $catalogService,
): AnonymousResourceCollection {
return CatalogSearchItemResource::collection(
$catalogService->search(
$tenant,
$request->validated('q'),
$tenant->search_items_per_page,
(int) $request->validated('page', 1),
)
);
}
public function category(
CategoryPageRequest $request,
Tenant $tenant,
Category $category,
CatalogService $catalogService,
): AnonymousResourceCollection {
abort_unless($category->tenant_code === $tenant->codigo, 404);
return CatalogSearchItemResource::collection(
$catalogService->categoryItems(
$tenant,
$category,
$tenant->search_items_per_page,
(int) $request->validated('page', 1),
)
)->additional([
'category' => [
'id' => $category->id,
'nombre' => $category->nombre,
'categoria_id' => $category->categoria_id,
],
'layout' => $tenant->search_product_layout->value,
'group_layout' => $tenant->search_group_layout->value,
]);
}
public function featuredGroupItems(
FeaturedGroupPageRequest $request,
Tenant $tenant,
FeaturedGroup $featuredGroup,
FeaturedGroupService $featuredGroupService,
): JsonResponse {
abort_unless($featuredGroup->tenant_code === $tenant->codigo, 404);
$page = (int) $request->validated('page', 1);
return response()->json($featuredGroupService->itemsResponse($featuredGroup, $page));
}
public function show(
CatalogItemDetailRequest $request,
Tenant $tenant,
CatalogItem $catalogItem,
CatalogService $catalogService,
): CatalogItemDetailResource {
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
$variantId = $request->validated('variant_id');
return CatalogItemDetailResource::make(
$catalogService->getDetail(
$catalogItem,
$variantId === null ? null : (int) $variantId,
)
);
}
public function store(
StoreCatalogItemRequest $request,
Tenant $tenant,
CatalogService $catalogService,
): JsonResponse {
$catalogItem = $catalogService->create([
...$request->validated(),
'tenant_code' => $tenant->codigo,
]);
return CatalogItemResource::make($catalogItem)
->response()
->setStatusCode(201);
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Enums;
namespace App\Domains\Catalog\Enums;
enum CatalogItemType: string
{

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Enums;
namespace App\Domains\Catalog\Enums;
enum FeaturedGroupSource: string
{

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Enums;
namespace App\Domains\Catalog\Enums;
enum GroupLayout: string
{
@@ -8,7 +8,6 @@ enum GroupLayout: string
case Simple = 'simple';
case SimpleVertical = 'simple_vertical';
case Carousel = 'carousel';
case Single = 'single';
/**
* @return list<string>

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Enums;
namespace App\Domains\Catalog\Enums;
enum InventoryPolicy: string
{

View File

@@ -1,13 +1,12 @@
<?php
namespace App\Domains\Commerce\Catalog\Enums;
namespace App\Domains\Catalog\Enums;
enum ProductLayout: string
{
case Row = 'row';
case ColumnWithImage = 'column_with_image';
case ColumnWithCart = 'column_with_cart';
case TicketSelector = 'ticket_selector';
/**
* @return list<string>

View File

@@ -1,10 +1,10 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Shared\Enums\FieldType;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Event\Models\EventDate;
use App\Domains\Shared\Enums\FieldType;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -59,8 +59,6 @@ class Attribute extends Model
public function eventDates(): HasMany
{
return $this->hasMany(EventDate::class, 'tenant_code', 'tenant_codigo')
->whereNull('rescheduled_to_event_date_id')
->whereNull('suspended_at')
->orderBy('date')
->orderBy('time_start');
}

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use App\Domains\Ticketing\Ticket\Models\ValidityTime;
use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;

View File

@@ -0,0 +1,220 @@
<?php
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\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;
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\Collection;
#[Fillable([
'tenant_code',
'category_id',
'brand_id',
'inventory_id',
'type',
'slug',
'nombre',
'descripcion',
'precio',
'inventory_policy',
'max_units_per_user',
'has_tickets',
'ticket_generation_policy',
'validity_time_id',
])]
class CatalogItem extends Model
{
use HasFactory;
public $timestamps = false;
protected $table = 'catalog_items';
protected $attributes = [
'type' => CatalogItemType::Standard->value,
'inventory_policy' => InventoryPolicy::Tracked->value,
'has_tickets' => false,
'ticket_generation_policy' => TicketGenerationPolicy::PerEventDate->value,
];
protected function casts(): array
{
return [
'category_id' => 'integer',
'brand_id' => 'integer',
'inventory_id' => 'integer',
'type' => CatalogItemType::class,
'precio' => 'decimal:2',
'inventory_policy' => InventoryPolicy::class,
'max_units_per_user' => 'integer',
'has_tickets' => 'boolean',
'ticket_generation_policy' => TicketGenerationPolicy::class,
'validity_time_id' => 'integer',
];
}
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return BelongsTo<Category, $this> */
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
/** @return BelongsTo<Brand, $this> */
public function brand(): BelongsTo
{
return $this->belongsTo(Brand::class);
}
/** @return BelongsTo<Inventory, $this> */
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
/** @return HasMany<BundleComponent, $this> */
public function bundleComponents(): HasMany
{
return $this->hasMany(BundleComponent::class, 'bundle_catalog_item_id');
}
/** @return HasMany<BundleComponent, $this> */
public function bundleComponentUsages(): HasMany
{
return $this->hasMany(BundleComponent::class, 'component_catalog_item_id');
}
/** @return HasMany<Variant, $this> */
public function variants(): HasMany
{
return $this->hasMany(Variant::class);
}
/** @return HasMany<Ticket, $this> */
public function sourceTickets(): HasMany
{
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
{
return $this->belongsToMany(Attribute::class, 'item_attributes')
->withTimestamps();
}
/** @return HasMany<ItemAttribute, $this> */
public function itemAttributes(): HasMany
{
return $this->hasMany(ItemAttribute::class);
}
/** @return HasMany<FeaturedItem, $this> */
public function featuredItems(): HasMany
{
return $this->hasMany(FeaturedItem::class);
}
/** @return BelongsToMany<Attachment, $this> */
public function attachments(): BelongsToMany
{
return $this->belongsToMany(
Attachment::class,
'catalog_items_attachments',
'catalog_item_id',
'attachment_id'
)
->withPivot('orden')
->wherePivotNull('variant_id')
->orderByPivot('orden');
}
public function availableStock(): ?int
{
return app(CatalogInventoryService::class)->availableQuantity($this);
}
public function isAvailable(): bool
{
if ($this->type === CatalogItemType::Bundle) {
$availableStock = $this->availableStock();
return $availableStock === null || $availableStock > 0;
}
if ($this->inventory_policy === InventoryPolicy::Unlimited) {
return true;
}
return ($this->availableStock() ?? 0) > 0;
}
/** @param Builder<CatalogItem> $query */
public function scopeWhereVariantsAvailable(Builder $query): Builder
{
return $query->where(function (Builder $query): void {
$query
->whereDoesntHave('variants')
->orWhere('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
->orWhereHas(
'variants.inventory',
fn (Builder $inventoryQuery): Builder => $inventoryQuery
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
);
});
}
/** @return Collection<int, Variant> */
public function visibleVariants(?int $includedVariantId = null): Collection
{
return $this->variants
->filter(fn (Variant $variant): bool => ($includedVariantId !== null && $variant->id === $includedVariantId)
|| $this->inventory_policy === InventoryPolicy::Unlimited
|| ($variant->inventory?->availableStock() ?? 0) > 0)
->values();
}
public function getPrice(): float
{
return (float) $this->precio;
}
public function getName(): string
{
return $this->nombre;
}
public function getDescription(): ?string
{
return $this->descripcion;
}
public function isBundle(): bool
{
return $this->type === CatalogItemType::Bundle;
}
}

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -15,7 +15,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'tenant_code',
'categoria_id',
'nombre',
'is_enabled',
])]
class Category extends Model
{
@@ -23,10 +22,6 @@ class Category extends Model
protected $table = 'categorias';
protected $attributes = [
'is_enabled' => true,
];
/**
* @return array<string, string>
*/
@@ -34,7 +29,6 @@ class Category extends Model
{
return [
'categoria_id' => 'integer',
'is_enabled' => 'boolean',
];
}

View File

@@ -1,21 +1,19 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use App\Domains\Commerce\Catalog\Enums\FeaturedGroupSource;
use App\Domains\Commerce\Catalog\Enums\GroupLayout;
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Catalog\Enums\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
#[Fillable([
'tenant_code',
'code',
'source_type',
'category_id',
'product_layout',
@@ -35,29 +33,6 @@ class FeaturedGroup extends Model
'source_type' => FeaturedGroupSource::Manual->value,
];
protected static function booted(): void
{
static::creating(function (FeaturedGroup $featuredGroup): void {
if (filled($featuredGroup->code)) {
return;
}
$baseCode = Str::slug($featuredGroup->group_name) ?: 'group';
$code = $baseCode;
$suffix = 2;
while (static::query()
->where('tenant_code', $featuredGroup->tenant_code)
->where('code', $code)
->exists()) {
$code = "{$baseCode}-{$suffix}";
$suffix++;
}
$featuredGroup->code = $code;
});
}
protected function casts(): array
{
return [

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;

View File

@@ -1,16 +1,14 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
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;
#[Fillable([
'sold_units',
'refunded_units',
'reserved_stock',
'real_stock',
])]
@@ -24,7 +22,6 @@ class Inventory extends Model
protected $attributes = [
'sold_units' => 0,
'refunded_units' => 0,
'reserved_stock' => 0,
'real_stock' => 0,
];
@@ -33,7 +30,6 @@ class Inventory extends Model
{
return [
'sold_units' => 'integer',
'refunded_units' => 'integer',
'reserved_stock' => 'integer',
'real_stock' => 'integer',
];
@@ -45,16 +41,10 @@ class Inventory extends Model
return $this->hasOne(CatalogItem::class);
}
/** @return HasMany<Variant, $this> */
public function variants(): HasMany
/** @return HasOne<Variant, $this> */
public function variant(): HasOne
{
return $this->hasMany(Variant::class);
}
/** @return HasMany<StockReservationLine, $this> */
public function stockReservationLines(): HasMany
{
return $this->hasMany(StockReservationLine::class);
return $this->hasOne(Variant::class);
}
public function availableStock(): int

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -13,8 +13,6 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'attribute_id',
'allow_multi_select',
'sort_order',
'show_in_selector',
'ticket_label',
])]
class ItemAttribute extends Model
{
@@ -22,10 +20,6 @@ class ItemAttribute extends Model
protected $table = 'item_attributes';
protected $attributes = [
'show_in_selector' => true,
];
protected function casts(): array
{
return [
@@ -33,7 +27,6 @@ class ItemAttribute extends Model
'attribute_id' => 'integer',
'allow_multi_select' => 'boolean',
'sort_order' => 'integer',
'show_in_selector' => 'boolean',
];
}

View File

@@ -1,33 +1,28 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use App\Shared\Attachable\Models\Attachment;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Event\Models\EventDate;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
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',
'event_date_id',
'inventory_id',
'replaced_by_variant_id',
'sales_disabled_at',
'descripcion',
'precio',
])]
class Variant extends Model
{
use HasFactory, SoftDeletes;
use HasFactory;
public $timestamps = false;
@@ -39,8 +34,6 @@ class Variant extends Model
'catalog_item_id' => 'integer',
'event_date_id' => 'integer',
'inventory_id' => 'integer',
'replaced_by_variant_id' => 'integer',
'sales_disabled_at' => 'datetime',
'precio' => 'decimal:2',
];
}
@@ -48,7 +41,7 @@ class Variant extends Model
/** @return BelongsTo<CatalogItem, $this> */
public function catalogItem(): BelongsTo
{
return $this->belongsTo(CatalogItem::class)->withTrashed();
return $this->belongsTo(CatalogItem::class);
}
/** @return BelongsTo<EventDate, $this> */
@@ -80,40 +73,6 @@ class Variant extends Model
return $this->belongsTo(Inventory::class);
}
/** @return BelongsTo<Variant, $this> */
public function replacement(): BelongsTo
{
return $this->belongsTo(self::class, 'replaced_by_variant_id');
}
/** @return HasMany<Variant, $this> */
public function replacedVariants(): HasMany
{
return $this->hasMany(self::class, 'replaced_by_variant_id');
}
public function isSellable(): bool
{
return $this->sales_disabled_at === null
&& $this->replaced_by_variant_id === null
&& $this->catalogItem->isSaleOpen()
&& $this->hasOnlyActiveEventDates();
}
public function hasOnlyActiveEventDates(): bool
{
if (! $this->exists
&& $this->event_date_id === null
&& ! $this->relationLoaded('eventDates')) {
return true;
}
return $this->selectedEventDates()->every(
fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
&& $eventDate->suspended_at === null,
);
}
/** @return HasMany<VariantDefinition, $this> */
public function definitions(): HasMany
{
@@ -122,12 +81,6 @@ 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,
@@ -135,7 +88,7 @@ class Variant extends Model
'variant_id',
'attachment_id'
)
->withPivot(['orden', 'is_enabled'])
->withPivot('orden')
->orderByPivot('orden');
if ($this->catalog_item_id !== null) {
@@ -160,42 +113,6 @@ 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
{
@@ -313,25 +230,6 @@ class Variant extends Model
});
}
/**
* @param Collection<int, ItemAttribute> $itemAttributes
* @return Collection<string, array{value: string, label: string}|array<int, array{value: string, label: string}>>
*/
public function selectorOptions(Collection $itemAttributes): Collection
{
$visibleAttributeCodes = $itemAttributes
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->show_in_selector)
->map(fn (ItemAttribute $itemAttribute): ?string => $itemAttribute->attribute?->codigo)
->filter()
->values();
return $this->selectionOptions($itemAttributes)
->filter(
fn (array $option, string $attributeCode): bool => $visibleAttributeCodes
->contains($attributeCode)
);
}
/** @return Collection<int, EventDate> */
public function selectedEventDates(): Collection
{

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Models;
namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Requests\AdminApp;
namespace App\Domains\Catalog\Requests\AdminApp;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Requests;
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Requests;
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Requests;
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Commerce\Catalog\Requests;
namespace App\Domains\Catalog\Requests;
use Illuminate\Foundation\Http\FormRequest;

View File

@@ -0,0 +1,136 @@
<?php
namespace App\Domains\Catalog\Requests;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreCatalogItemRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
$tenantCode = $this->route('tenant')?->codigo;
$type = $this->input('type', CatalogItemType::Standard->value);
$isBundle = $type === CatalogItemType::Bundle->value;
return [
'tenant_code' => ['prohibited'],
'type' => ['sometimes', Rule::enum(CatalogItemType::class)],
'category_id' => [
'sometimes',
'nullable',
'integer',
Rule::exists('categorias', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'brand_id' => [
'sometimes',
'nullable',
'integer',
Rule::exists('brands', 'id')->where(
fn ($query) => $query->where('tenant_codigo', $tenantCode)
),
],
'slug' => [
'required',
'string',
'max:255',
Rule::unique('catalog_items', 'slug')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'nombre' => ['required', 'string', 'max:255'],
'descripcion' => ['sometimes', 'nullable', 'string'],
'precio' => ['required', 'numeric', 'min:0'],
'inventory_policy' => [Rule::prohibitedIf($isBundle), 'sometimes', Rule::enum(InventoryPolicy::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'],
'sold_units' => ['prohibited'],
'attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
'attribute_codes.*' => [
'required',
'string',
'distinct',
Rule::exists('attribute', 'codigo')->where(
fn ($query) => $query->where('tenant_codigo', $tenantCode)
),
],
'multi_select_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
'multi_select_attribute_codes.*' => [
'required',
'string',
'distinct',
Rule::exists('attribute', 'codigo')->where(
fn ($query) => $query->where('tenant_codigo', $tenantCode)
),
],
'images' => ['sometimes', 'array'],
'images.*' => ['required', new ImageOrBase64Rule],
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
'variants.*.descripcion' => ['sometimes', 'nullable', 'string'],
'variants.*.precio' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:99999999.99'],
'variants.*.event_date_id' => [
'sometimes',
'nullable',
'integer',
Rule::exists('event_dates', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'variants.*.event_date_ids' => ['sometimes', 'array', 'min:1'],
'variants.*.event_date_ids.*' => [
'required',
'integer',
'distinct',
Rule::exists('event_dates', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'variants.*.inventory_id' => ['prohibited'],
'variants.*.reserved_stock' => ['prohibited'],
'variants.*.sold_units' => ['prohibited'],
'variants.*.values' => ['sometimes', 'array'],
'variants.*.values.*' => ['nullable'],
'variants.*.values.*.*' => ['required', 'string'],
'variants.*.images' => ['sometimes', 'array'],
'variants.*.images.*' => ['required', new ImageOrBase64Rule],
'components' => [
Rule::requiredIf($isBundle),
Rule::prohibitedIf(! $isBundle),
'array',
'min:1',
],
'components.*.catalog_item_id' => [
'required',
'integer',
Rule::exists('catalog_items', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'components.*.variant_id' => [
'sometimes',
'nullable',
'integer',
Rule::exists('variantes', 'id'),
],
'components.*.quantity' => ['required', 'integer', 'min:1'],
];
}
}

View File

@@ -1,9 +1,9 @@
<?php
namespace App\Domains\Commerce\Catalog\Resources\AdminApp;
namespace App\Domains\Catalog\Resources\AdminApp;
use App\Domains\Commerce\Catalog\Enums\ProductLayout;
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\FeaturedGroup;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -15,7 +15,6 @@ class OnTicketFeaturedGroupResource extends JsonResource
{
return [
'id' => $this->id,
'code' => $this->code,
'category_id' => $this->category_id,
'category_name' => $this->category->nombre,
'group_name' => $this->group_name,

View File

@@ -1,8 +1,8 @@
<?php
namespace App\Domains\Commerce\Catalog\Resources;
namespace App\Domains\Catalog\Resources;
use App\Domains\Commerce\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\FeaturedGroup;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -20,7 +20,6 @@ class CatalogFeaturedGroupResource extends JsonResource
{
return [
'id' => $this->id,
'code' => $this->code,
'title' => $this->group_name,
'layout' => $this->product_layout->value,
'group_layout' => $this->group_layout->value,

View File

@@ -0,0 +1,75 @@
<?php
namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Enums\InventoryPolicy;
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;
/** @mixin CatalogItem */
class CatalogFeaturedItemResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$catalogItem = $this->resource;
/** @var FeaturedGroup $featuredGroup */
$featuredGroup = $catalogItem->getRelation('featuredGroup');
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
return $this->columnWithImageData($catalogItem);
}
return [
'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 => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectionOptions($catalogItem->itemAttributes),
])
->values(),
];
}
/** @return array<string, mixed> */
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),
];
}
}

View File

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

View File

@@ -0,0 +1,56 @@
<?php
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;
/** @mixin CatalogItem */
class CatalogItemResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'type' => $this->type->value,
'category_id' => $this->category_id,
'brand_id' => $this->brand_id,
'slug' => $this->slug,
'nombre' => $this->nombre,
'descripcion' => $this->descripcion,
'precio' => $this->precio,
'inventory_policy' => $this->inventory_policy?->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))
->values()),
'variants' => $this->whenLoaded('variants', fn () => $this->variants
->map(fn ($variant) => [
'id' => $variant->id,
'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''),
'real_stock' => $variant->inventory?->real_stock,
'values' => $variant->selectionOptions($this->itemAttributes),
'images' => $variant->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values(),
])
->values()),
];
}
}

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