Compare commits
41 Commits
dev
...
feature/re
| Author | SHA1 | Date | |
|---|---|---|---|
| 9fa4da7de2 | |||
| c27d9628fd | |||
| b1e09b71ad | |||
| 7d45734ad7 | |||
| 91022c5897 | |||
| 61314d5166 | |||
| 0d54887602 | |||
| 54827fbc58 | |||
| 18a0d14fa8 | |||
| b4a7b80430 | |||
| 2bd3bf9dc1 | |||
| e42bc545a5 | |||
| aa14129fe7 | |||
| 289ceba3af | |||
| 28ab6c9ae4 | |||
| 67deca095e | |||
| caed44fcc8 | |||
| adec5d1725 | |||
| a62e989bb4 | |||
| 9c14153199 | |||
| 756f4dad0a | |||
| 205d77bc0b | |||
| 4f7ede1072 | |||
| 4bb4f526e4 | |||
| c0c19c9c01 | |||
| b4da6e3747 | |||
| 1880fc8147 | |||
| 96df431d60 | |||
| 106cf017dc | |||
| d5fdae9a24 | |||
| 4abb6c67fd | |||
| 6384c0046d | |||
| 2ddb046c26 | |||
| 5d00dc439e | |||
| 210c854fee | |||
| beb5d18b29 | |||
| de259f4286 | |||
| f19bca64d0 | |||
| 18f739b712 | |||
| 1564985259 | |||
| 471a941587 |
@@ -45,6 +45,7 @@ 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
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# 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 under `app/Domains`.
|
||||
|
||||
@@ -32,6 +32,7 @@ class TenantBootstrapService
|
||||
return $this->tenantInformationService->load(
|
||||
$tenant,
|
||||
[
|
||||
'eventDateChanges',
|
||||
'menues' => fn ($query) => $query->whereHas(
|
||||
'roles',
|
||||
fn ($query) => $query->where('codigo', RoleCode::User->value)
|
||||
|
||||
@@ -400,6 +400,17 @@ 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;
|
||||
}
|
||||
|
||||
@@ -430,6 +441,12 @@ 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);
|
||||
|
||||
99
app/Domains/Cart/Services/CartVariantReplacementService.php
Normal file
99
app/Domains/Cart/Services/CartVariantReplacementService.php
Normal file
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class CartVariantReplacementService
|
||||
{
|
||||
public function __construct(private readonly CatalogInventoryService $inventory) {}
|
||||
|
||||
public function replaceHistoricalVariants(Cart $cart): void
|
||||
{
|
||||
$items = $cart->items()
|
||||
->whereNotNull('variant_id')
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$variant = Variant::query()->lockForUpdate()->find($item->variant_id);
|
||||
|
||||
if ($variant === null) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
$replacement = $this->latestReplacement($variant);
|
||||
|
||||
if ($replacement->is($variant)) {
|
||||
if (! $variant->isSellable()) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $replacement->isSellable()) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
/** @var CartItem|null $targetItem */
|
||||
$targetItem = $cart->items()
|
||||
->whereKeyNot($item->getKey())
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->where('variant_id', $replacement->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$replacementQuantity = $item->cantidad + ($targetItem?->cantidad ?? 0);
|
||||
if ($replacement->inventory_id !== $variant->inventory_id) {
|
||||
$available = $this->inventory->availableQuantity($replacement);
|
||||
|
||||
if ($available !== null && $available < $replacementQuantity) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
}
|
||||
|
||||
if ($targetItem !== null) {
|
||||
$targetItem->cantidad += $item->cantidad;
|
||||
$targetItem->save();
|
||||
$item->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$item->update(['variant_id' => $replacement->getKey()]);
|
||||
}
|
||||
}
|
||||
|
||||
private function latestReplacement(Variant $variant): Variant
|
||||
{
|
||||
$current = $variant;
|
||||
$visited = [];
|
||||
|
||||
while ($current->replaced_by_variant_id !== null) {
|
||||
if (isset($visited[$current->getKey()])) {
|
||||
throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
$visited[$current->getKey()] = true;
|
||||
$current = Variant::query()
|
||||
->lockForUpdate()
|
||||
->find($current->replaced_by_variant_id)
|
||||
?? throw $this->unavailableVariant();
|
||||
}
|
||||
|
||||
return $current;
|
||||
}
|
||||
|
||||
private function unavailableVariant(): ValidationException
|
||||
{
|
||||
return ValidationException::withMessages([
|
||||
'cart_id' => [__('api.cart.cart_variant_unavailable')],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,8 @@ 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');
|
||||
}
|
||||
|
||||
@@ -179,12 +179,28 @@ class CatalogItem extends Model
|
||||
{
|
||||
return $query->where(function (Builder $query): void {
|
||||
$query
|
||||
->where(function (Builder $unlimitedQuery): void {
|
||||
$unlimitedQuery
|
||||
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||
->where(function (Builder $selectionQuery): void {
|
||||
$selectionQuery
|
||||
->whereDoesntHave('variants')
|
||||
->orWhereHas('variants', fn (Builder $variantQuery): Builder => $variantQuery
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id'));
|
||||
});
|
||||
})
|
||||
->orWhereHas(
|
||||
'variants.inventory',
|
||||
'variants',
|
||||
fn (Builder $variantQuery): Builder => $variantQuery
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->whereHas(
|
||||
'inventory',
|
||||
fn (Builder $inventoryQuery): Builder => $inventoryQuery
|
||||
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock')
|
||||
)
|
||||
)
|
||||
->orWhere(function (Builder $directItemQuery): void {
|
||||
$directItemQuery
|
||||
->whereDoesntHave('variants')
|
||||
@@ -205,9 +221,12 @@ class CatalogItem extends Model
|
||||
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)
|
||||
->filter(fn (Variant $variant): bool => $variant->hasOnlyActiveEventDates()
|
||||
&& (($includedVariantId !== null && $variant->id === $includedVariantId)
|
||||
|| ($variant->isSellable() && (
|
||||
$this->inventory_policy === InventoryPolicy::Unlimited
|
||||
|| ($variant->inventory?->availableStock() ?? 0) > 0
|
||||
))))
|
||||
->values();
|
||||
}
|
||||
|
||||
|
||||
@@ -42,10 +42,10 @@ class Inventory extends Model
|
||||
return $this->hasOne(CatalogItem::class);
|
||||
}
|
||||
|
||||
/** @return HasOne<Variant, $this> */
|
||||
public function variant(): HasOne
|
||||
/** @return HasMany<Variant, $this> */
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasOne(Variant::class);
|
||||
return $this->hasMany(Variant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<StockReservationLine, $this> */
|
||||
|
||||
@@ -20,6 +20,8 @@ use Illuminate\Support\Str;
|
||||
'catalog_item_id',
|
||||
'event_date_id',
|
||||
'inventory_id',
|
||||
'replaced_by_variant_id',
|
||||
'sales_disabled_at',
|
||||
'descripcion',
|
||||
'precio',
|
||||
])]
|
||||
@@ -37,6 +39,8 @@ 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',
|
||||
];
|
||||
}
|
||||
@@ -76,6 +80,39 @@ 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->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
|
||||
{
|
||||
|
||||
@@ -63,7 +63,12 @@ class CatalogInventoryService
|
||||
|
||||
$selection->loadMissing('variants.inventory');
|
||||
|
||||
return $selection->variants->sum(
|
||||
return $selection->variants
|
||||
->filter(fn (Variant $variant): bool => $variant->isSellable())
|
||||
->unique(fn (Variant $variant): string => $variant->inventory_id === null
|
||||
? 'object:'.spl_object_id($variant->inventory)
|
||||
: 'id:'.$variant->inventory_id)
|
||||
->sum(
|
||||
fn (Variant $variant): int => $variant->inventory->availableStock(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -207,7 +207,8 @@ class CatalogService
|
||||
$visibleVariants = $catalogItem->visibleVariants();
|
||||
if ($catalogItem->type === CatalogItemType::Standard
|
||||
&& ($catalogItem->inventory_id !== null || $catalogItem->variants->isNotEmpty())
|
||||
&& ! $catalogItem->isAvailable()) {
|
||||
&& (($catalogItem->variants->isNotEmpty() && $visibleVariants->isEmpty())
|
||||
|| ! $catalogItem->isAvailable())) {
|
||||
throw new NotFoundHttpException('Catalog item is out of stock.');
|
||||
}
|
||||
|
||||
@@ -324,9 +325,13 @@ class CatalogService
|
||||
->findOrFail($variant->catalog_item_id);
|
||||
$variant->delete();
|
||||
|
||||
if (! $catalogItem->variants()->exists()) {
|
||||
$sellableVariants = $catalogItem->variants()
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id');
|
||||
|
||||
if (! (clone $sellableVariants)->exists()) {
|
||||
$this->delete($catalogItem);
|
||||
} elseif (($minimumPrice = $catalogItem->variants()->min('precio')) !== null) {
|
||||
} elseif (($minimumPrice = (clone $sellableVariants)->min('precio')) !== null) {
|
||||
$catalogItem->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
@@ -399,7 +404,11 @@ class CatalogService
|
||||
]);
|
||||
}
|
||||
|
||||
if ($variantId !== null && ! $componentItem->variants()->whereKey($variantId)->exists()) {
|
||||
if ($variantId !== null && ! $componentItem->variants()
|
||||
->whereKey($variantId)
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
"components.{$index}.variant_id" => [
|
||||
__('api.catalog.component_variant_invalid'),
|
||||
|
||||
137
app/Domains/Catalog/Services/VariantReplacementService.php
Normal file
137
app/Domains/Catalog/Services/VariantReplacementService.php
Normal file
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\BundleComponent;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class VariantReplacementService
|
||||
{
|
||||
/** @return Collection<int, Variant> */
|
||||
public function replaceEventDate(EventDate $source, EventDate $destination): Collection
|
||||
{
|
||||
$variants = Variant::query()
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->where(function ($query) use ($source): void {
|
||||
$query->where('event_date_id', $source->getKey())
|
||||
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
|
||||
->where('event_dates.id', $source->getKey()));
|
||||
})
|
||||
->with(['eventDates', 'eventDate', 'definitions', 'allAttachments'])
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
return $variants->map(function (Variant $variant) use ($source, $destination): Variant {
|
||||
$destinationDateIds = $variant->selectedEventDates()
|
||||
->pluck('id')
|
||||
->map(fn ($id): int => (int) $id === (int) $source->getKey()
|
||||
? (int) $destination->getKey()
|
||||
: (int) $id)
|
||||
->unique()
|
||||
->sort()
|
||||
->values();
|
||||
|
||||
$replacement = $this->findEquivalent($variant, $destinationDateIds)
|
||||
?? $this->cloneWithDates($variant, $destinationDateIds);
|
||||
|
||||
$variant->update([
|
||||
'replaced_by_variant_id' => $replacement->getKey(),
|
||||
'sales_disabled_at' => now(),
|
||||
]);
|
||||
|
||||
BundleComponent::query()
|
||||
->where('component_variant_id', $variant->getKey())
|
||||
->update(['component_variant_id' => $replacement->getKey()]);
|
||||
|
||||
return $replacement;
|
||||
})->values();
|
||||
}
|
||||
|
||||
public function disableForSuspension(EventDate $eventDate): void
|
||||
{
|
||||
Variant::query()
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->where(function ($query) use ($eventDate): void {
|
||||
$query->where('event_date_id', $eventDate->getKey())
|
||||
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
|
||||
->where('event_dates.id', $eventDate->getKey()));
|
||||
})
|
||||
->update(['sales_disabled_at' => now()]);
|
||||
}
|
||||
|
||||
/** @param Collection<int, int> $eventDateIds */
|
||||
private function findEquivalent(Variant $source, Collection $eventDateIds): ?Variant
|
||||
{
|
||||
$definitionSignature = $this->definitionSignature($source);
|
||||
$dateSignature = $eventDateIds->map(fn ($id): int => (int) $id)->sort()->values()->all();
|
||||
|
||||
return Variant::query()
|
||||
->where('catalog_item_id', $source->catalog_item_id)
|
||||
->whereKeyNot($source->getKey())
|
||||
->whereNull('sales_disabled_at')
|
||||
->whereNull('replaced_by_variant_id')
|
||||
->with(['eventDates', 'eventDate', 'definitions'])
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->first(fn (Variant $candidate): bool => $this->definitionSignature($candidate) === $definitionSignature
|
||||
&& $candidate->selectedEventDates()
|
||||
->pluck('id')
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->sort()
|
||||
->values()
|
||||
->all() === $dateSignature
|
||||
);
|
||||
}
|
||||
|
||||
/** @param Collection<int, int> $eventDateIds */
|
||||
private function cloneWithDates(Variant $source, Collection $eventDateIds): Variant
|
||||
{
|
||||
$replacement = $source->replicate([
|
||||
'event_date_id',
|
||||
'replaced_by_variant_id',
|
||||
'sales_disabled_at',
|
||||
]);
|
||||
$replacement->event_date_id = $eventDateIds->count() === 1
|
||||
? $eventDateIds->first()
|
||||
: null;
|
||||
$replacement->save();
|
||||
$replacement->eventDates()->sync($eventDateIds->all());
|
||||
|
||||
$replacement->definitions()->createMany(
|
||||
$source->definitions
|
||||
->map(fn ($definition): array => [
|
||||
'item_attribute_id' => $definition->item_attribute_id,
|
||||
'value' => $definition->value,
|
||||
])
|
||||
->all(),
|
||||
);
|
||||
|
||||
$attachments = $source->allAttachments
|
||||
->mapWithKeys(fn ($attachment): array => [
|
||||
$attachment->getKey() => [
|
||||
'orden' => $attachment->pivot->orden,
|
||||
'is_enabled' => $attachment->pivot->is_enabled,
|
||||
],
|
||||
])
|
||||
->all();
|
||||
$replacement->allAttachments()->sync($attachments);
|
||||
|
||||
return $replacement->load(['eventDates', 'eventDate', 'definitions', 'allAttachments']);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function definitionSignature(Variant $variant): array
|
||||
{
|
||||
return $variant->definitions
|
||||
->map(fn ($definition): string => $definition->item_attribute_id.'\0'.$definition->value)
|
||||
->sort()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
namespace App\Domains\Event\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Requests\RescheduleEventDateRequest;
|
||||
use App\Domains\Event\Requests\StoreEventDateRequest;
|
||||
use App\Domains\Event\Requests\UpdateEventRequest;
|
||||
use App\Domains\Event\Resources\EventDateResource;
|
||||
use App\Domains\Event\Resources\EventResource;
|
||||
use App\Domains\Event\Services\EventService;
|
||||
use App\Http\Controllers\Controller;
|
||||
@@ -28,4 +32,39 @@ class EventController extends Controller
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function storeDate(StoreEventDateRequest $request): EventDateResource
|
||||
{
|
||||
return EventDateResource::make(
|
||||
$this->eventService->createDateForTenant(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$request->validated(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function rescheduleDate(
|
||||
RescheduleEventDateRequest $request,
|
||||
EventDate $eventDate,
|
||||
): EventDateResource {
|
||||
return EventDateResource::make(
|
||||
$this->eventService->rescheduleDateForTenant(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$eventDate,
|
||||
$request->validated(),
|
||||
$request->user(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function suspendDate(Request $request, EventDate $eventDate): EventDateResource
|
||||
{
|
||||
return EventDateResource::make(
|
||||
$this->eventService->suspendDateForTenant(
|
||||
$request->user()->tenant()->firstOrFail(),
|
||||
$eventDate,
|
||||
$request->user(),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
9
app/Domains/Event/Enums/EventDateChangeType.php
Normal file
9
app/Domains/Event/Enums/EventDateChangeType.php
Normal file
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Enums;
|
||||
|
||||
enum EventDateChangeType: string
|
||||
{
|
||||
case Rescheduled = 'rescheduled';
|
||||
case Suspended = 'suspended';
|
||||
}
|
||||
12
app/Domains/Event/Enums/EventDateStatus.php
Normal file
12
app/Domains/Event/Enums/EventDateStatus.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Enums;
|
||||
|
||||
enum EventDateStatus: string
|
||||
{
|
||||
case Rescheduled = 'rescheduled';
|
||||
case Suspended = 'suspended';
|
||||
case Scheduled = 'scheduled';
|
||||
case InProgress = 'in_progress';
|
||||
case Completed = 'completed';
|
||||
}
|
||||
22
app/Domains/Event/Events/EventDateRescheduled.php
Normal file
22
app/Domains/Event/Events/EventDateRescheduled.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
|
||||
class EventDateRescheduled
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
/**
|
||||
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $tenantCode,
|
||||
public readonly int $sourceEventDateId,
|
||||
public readonly int $destinationEventDateId,
|
||||
public readonly string $previousDate,
|
||||
public readonly string $newDate,
|
||||
public readonly array $purchaseTickets,
|
||||
) {}
|
||||
}
|
||||
20
app/Domains/Event/Events/EventDateSuspended.php
Normal file
20
app/Domains/Event/Events/EventDateSuspended.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
|
||||
class EventDateSuspended
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
/**
|
||||
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $tenantCode,
|
||||
public readonly int $eventDateId,
|
||||
public readonly string $date,
|
||||
public readonly array $purchaseTickets,
|
||||
) {}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domains\Event\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Event\Enums\EventDateStatus;
|
||||
use App\Domains\Event\Services\EventDateTextFormatter;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
@@ -21,6 +22,8 @@ use Illuminate\Support\Carbon;
|
||||
'date',
|
||||
'time_start',
|
||||
'time_end',
|
||||
'rescheduled_to_event_date_id',
|
||||
'suspended_at',
|
||||
])]
|
||||
class EventDate extends Model
|
||||
{
|
||||
@@ -28,6 +31,8 @@ class EventDate extends Model
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $appends = ['status'];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(fn (self $eventDate) => $eventDate->syncValidityTime());
|
||||
@@ -52,6 +57,8 @@ class EventDate extends Model
|
||||
return [
|
||||
'date' => 'date:Y-m-d',
|
||||
'validity_time_id' => 'integer',
|
||||
'rescheduled_to_event_date_id' => 'integer',
|
||||
'suspended_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -67,6 +74,30 @@ class EventDate extends Model
|
||||
return $this->belongsTo(ValidityTime::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
public function rescheduledTo(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'rescheduled_to_event_date_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<EventDate, $this> */
|
||||
public function rescheduledFrom(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'rescheduled_to_event_date_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<EventDateChange, $this> */
|
||||
public function changeHistory(): HasMany
|
||||
{
|
||||
return $this->hasMany(EventDateChange::class, 'source_event_date_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<EventDateChange, $this> */
|
||||
public function destinationChangeHistory(): HasMany
|
||||
{
|
||||
return $this->hasMany(EventDateChange::class, 'destination_event_date_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Variant, $this> */
|
||||
public function variants(): HasMany
|
||||
{
|
||||
@@ -94,6 +125,27 @@ class EventDate extends Model
|
||||
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end);
|
||||
}
|
||||
|
||||
public function getStatusAttribute(): EventDateStatus
|
||||
{
|
||||
if ($this->rescheduled_to_event_date_id !== null) {
|
||||
return EventDateStatus::Rescheduled;
|
||||
}
|
||||
|
||||
if ($this->suspended_at !== null) {
|
||||
return EventDateStatus::Suspended;
|
||||
}
|
||||
|
||||
if (now()->lt($this->startsAt())) {
|
||||
return EventDateStatus::Scheduled;
|
||||
}
|
||||
|
||||
if (now()->lt($this->endsAt())) {
|
||||
return EventDateStatus::InProgress;
|
||||
}
|
||||
|
||||
return EventDateStatus::Completed;
|
||||
}
|
||||
|
||||
private function syncTenantDateText(): void
|
||||
{
|
||||
$tenant = $this->tenant()->first();
|
||||
@@ -104,7 +156,10 @@ class EventDate extends Model
|
||||
|
||||
$tenant->update([
|
||||
'event_date_text' => app(EventDateTextFormatter::class)->format(
|
||||
$tenant->eventDates()->pluck('date')
|
||||
$tenant->eventDates()
|
||||
->whereNull('rescheduled_to_event_date_id')
|
||||
->whereNull('suspended_at')
|
||||
->pluck('date')
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
61
app/Domains/Event/Models/EventDateChange.php
Normal file
61
app/Domains/Event/Models/EventDateChange.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Event\Enums\EventDateChangeType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'change_type',
|
||||
'source_event_date_id',
|
||||
'destination_event_date_id',
|
||||
'created_by_user_id',
|
||||
'previous_date',
|
||||
'new_date',
|
||||
])]
|
||||
class EventDateChange extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'change_type' => EventDateChangeType::class,
|
||||
'source_event_date_id' => 'integer',
|
||||
'destination_event_date_id' => 'integer',
|
||||
'created_by_user_id' => 'integer',
|
||||
'previous_date' => 'date:Y-m-d',
|
||||
'new_date' => 'date:Y-m-d',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
public function sourceEventDate(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EventDate::class, 'source_event_date_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<EventDate, $this> */
|
||||
public function destinationEventDate(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EventDate::class, 'destination_event_date_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by_user_id')->withTrashed();
|
||||
}
|
||||
}
|
||||
21
app/Domains/Event/Requests/RescheduleEventDateRequest.php
Normal file
21
app/Domains/Event/Requests/RescheduleEventDateRequest.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class RescheduleEventDateRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'date' => ['required', 'date_format:Y-m-d'],
|
||||
];
|
||||
}
|
||||
}
|
||||
23
app/Domains/Event/Requests/StoreEventDateRequest.php
Normal file
23
app/Domains/Event/Requests/StoreEventDateRequest.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreEventDateRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'date' => ['required', 'date_format:Y-m-d'],
|
||||
'start_time' => ['required', 'date_format:H:i'],
|
||||
'end_time' => ['required', 'date_format:H:i'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,6 @@ class UpdateEventRequest extends FormRequest
|
||||
return [
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'location' => ['required', 'string', 'max:255'],
|
||||
'dates' => ['required', 'array', 'min:1'],
|
||||
'dates.*' => ['required', 'array:date,start_time,end_time'],
|
||||
'dates.*.date' => ['required', 'date_format:Y-m-d', 'distinct'],
|
||||
'dates.*.start_time' => ['required', 'date_format:H:i'],
|
||||
'dates.*.end_time' => ['required', 'date_format:H:i'],
|
||||
'social_media' => ['sometimes', 'array'],
|
||||
'social_media.*' => ['required', 'array:code,url,orden'],
|
||||
'social_media.*.code' => [
|
||||
@@ -38,6 +33,16 @@ class UpdateEventRequest extends FormRequest
|
||||
'contact.whatsapp_url' => ['nullable', 'url', 'max:2048'],
|
||||
'contact.instagram_url' => ['nullable', 'url', 'max:2048'],
|
||||
'contact.facebook_url' => ['nullable', 'url', 'max:2048'],
|
||||
'allow_ticket_refund' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_total_refund' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
|
||||
'ticket_partial_refund_percentage' => [
|
||||
'sometimes',
|
||||
'numeric',
|
||||
'decimal:0,2',
|
||||
'min:0',
|
||||
'max:99.99',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -54,6 +59,41 @@ class UpdateEventRequest extends FormRequest
|
||||
'The social media field is required.'
|
||||
);
|
||||
}
|
||||
|
||||
if (! array_key_exists('allow_ticket_refund', $input)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'allow_ticket_total_refund',
|
||||
'allow_ticket_partial_refund',
|
||||
'ticket_partial_refund_percentage',
|
||||
] as $field) {
|
||||
if (! array_key_exists($field, $input)) {
|
||||
$validator->errors()->add($field, 'El campo es obligatorio.');
|
||||
}
|
||||
}
|
||||
|
||||
$totalEnabled = $this->boolean('allow_ticket_total_refund');
|
||||
$partialEnabled = $this->boolean('allow_ticket_partial_refund');
|
||||
|
||||
$refundEnabled = $this->boolean('allow_ticket_refund');
|
||||
|
||||
if ($refundEnabled && ! $totalEnabled && ! $partialEnabled) {
|
||||
$validator->errors()->add(
|
||||
'allow_ticket_refund',
|
||||
'Seleccioná al menos un tipo de reembolso.'
|
||||
);
|
||||
}
|
||||
|
||||
if ($refundEnabled
|
||||
&& $partialEnabled
|
||||
&& (float) ($input['ticket_partial_refund_percentage'] ?? 0) <= 0) {
|
||||
$validator->errors()->add(
|
||||
'ticket_partial_refund_percentage',
|
||||
'Ingresá un porcentaje mayor que cero para el reembolso parcial.'
|
||||
);
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
24
app/Domains/Event/Resources/EventDateChangeResource.php
Normal file
24
app/Domains/Event/Resources/EventDateChangeResource.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Resources;
|
||||
|
||||
use App\Domains\Event\Models\EventDateChange;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin EventDateChange */
|
||||
class EventDateChangeResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'type' => $this->change_type->value,
|
||||
'source_event_date_id' => $this->source_event_date_id,
|
||||
'destination_event_date_id' => $this->destination_event_date_id,
|
||||
'previous_date' => $this->previous_date->format('Y-m-d'),
|
||||
'new_date' => $this->new_date?->format('Y-m-d'),
|
||||
'occurred_at' => $this->created_at->toISOString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
28
app/Domains/Event/Resources/EventDateResource.php
Normal file
28
app/Domains/Event/Resources/EventDateResource.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Resources;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin EventDate */
|
||||
class EventDateResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'validity_time_id' => $this->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($this->whenLoaded('validityTime')),
|
||||
'date' => $this->date->format('Y-m-d'),
|
||||
'start_time' => substr($this->time_start, 0, 5),
|
||||
'end_time' => substr($this->time_end, 0, 5),
|
||||
'status' => $this->status->value,
|
||||
'rescheduled_to_event_date_id' => $this->rescheduled_to_event_date_id,
|
||||
'suspended_at' => $this->suspended_at?->toISOString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domains\Event\Resources;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -19,14 +18,11 @@ class EventResource extends JsonResource
|
||||
'id' => $this->id,
|
||||
'title' => $this->event_title,
|
||||
'location' => $this->event_location,
|
||||
'dates' => $this->eventDates->map(fn ($eventDate): array => [
|
||||
'id' => $eventDate->id,
|
||||
'validity_time_id' => $eventDate->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
||||
'date' => $eventDate->date->format('Y-m-d'),
|
||||
'start_time' => substr($eventDate->time_start, 0, 5),
|
||||
'end_time' => substr($eventDate->time_end, 0, 5),
|
||||
])->values(),
|
||||
'allow_ticket_refund' => $this->allow_ticket_refund,
|
||||
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
|
||||
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
|
||||
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
|
||||
'dates' => EventDateResource::collection($this->eventDates),
|
||||
'social_media' => $this->socialMedia->map(fn ($item): array => [
|
||||
'code' => $item->code,
|
||||
'url' => $item->pivot->url,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Services;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class AffectedEventDatePurchaseResolver
|
||||
{
|
||||
/**
|
||||
* Finds active tickets belonging to paid purchases before an event-date mutation.
|
||||
*
|
||||
* @param Collection<int, int>|list<int> $eventDateIds
|
||||
* @return list<array{purchase_id: int, ticket_ids: list<int>}>
|
||||
*/
|
||||
public function resolve(Tenant $tenant, Collection|array $eventDateIds): array
|
||||
{
|
||||
$eventDateIds = collect($eventDateIds)->map(fn (mixed $id): int => (int) $id)->unique()->values();
|
||||
|
||||
if ($eventDateIds->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @var Collection<int, Ticket> $tickets */
|
||||
$tickets = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('sourcePurchaseItem.purchase', fn (Builder $query) => $query
|
||||
->where('status', Purchase::STATUS_PAID))
|
||||
->whereHas('sourceVariant', function (Builder $query) use ($eventDateIds): void {
|
||||
$query->whereIn('event_date_id', $eventDateIds)
|
||||
->orWhereHas('eventDates', fn (Builder $eventDates) => $eventDates
|
||||
->whereIn('event_dates.id', $eventDateIds));
|
||||
})
|
||||
->with([
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
'sourcePurchaseItem.purchase',
|
||||
])
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||
->values();
|
||||
|
||||
return $tickets
|
||||
->groupBy(fn (Ticket $ticket): int => (int) $ticket->sourcePurchaseItem->purchase->getKey())
|
||||
->map(function (Collection $purchaseTickets): array {
|
||||
return [
|
||||
'purchase_id' => (int) $purchaseTickets->first()->sourcePurchaseItem->purchase->getKey(),
|
||||
'ticket_ids' => $purchaseTickets->modelKeys(),
|
||||
];
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
45
app/Domains/Event/Services/EffectiveEventDateResolver.php
Normal file
45
app/Domains/Event/Services/EffectiveEventDateResolver.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Services;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
|
||||
class EffectiveEventDateResolver
|
||||
{
|
||||
public function resolve(EventDate $eventDate): ?EventDate
|
||||
{
|
||||
$date = $this->resolveLatest($eventDate);
|
||||
|
||||
return $date !== null && $date->suspended_at === null ? $date : null;
|
||||
}
|
||||
|
||||
/** Sigue las reprogramaciones para presentación, incluso si el destino está suspendido. */
|
||||
public function resolveLatest(EventDate $eventDate): ?EventDate
|
||||
{
|
||||
$current = $eventDate;
|
||||
$visited = [];
|
||||
|
||||
while (true) {
|
||||
$identity = $current->getKey() === null
|
||||
? 'object:'.spl_object_id($current)
|
||||
: 'key:'.$current->getKey();
|
||||
|
||||
if (isset($visited[$identity])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$visited[$identity] = true;
|
||||
|
||||
if ($current->rescheduled_to_event_date_id === null) {
|
||||
return $current;
|
||||
}
|
||||
|
||||
$current->loadMissing('rescheduledTo');
|
||||
$current = $current->rescheduledTo;
|
||||
|
||||
if ($current === null) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
109
app/Domains/Event/Services/EventDateNoticeFormatter.php
Normal file
109
app/Domains/Event/Services/EventDateNoticeFormatter.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Event\Services;
|
||||
|
||||
use App\Domains\Event\Enums\EventDateChangeType;
|
||||
use App\Domains\Event\Models\EventDateChange;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class EventDateNoticeFormatter
|
||||
{
|
||||
public function __construct(private readonly EventDateTextFormatter $dateTextFormatter) {}
|
||||
|
||||
/**
|
||||
* @param Collection<int, EventDateChange> $changes
|
||||
* @return list<array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* message: list<array{text: string, bold: bool}>
|
||||
* }>
|
||||
*/
|
||||
public function format(Collection $changes): array
|
||||
{
|
||||
return collect([
|
||||
$this->suspensionNotice(
|
||||
$changes->where('change_type', EventDateChangeType::Suspended)
|
||||
),
|
||||
$this->rescheduleNotice(
|
||||
$changes->where('change_type', EventDateChangeType::Rescheduled)
|
||||
),
|
||||
])->filter()->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, EventDateChange> $changes
|
||||
* @return array{type: string, title: string, message: list<array{text: string, bold: bool}>}|null
|
||||
*/
|
||||
private function suspensionNotice(Collection $changes): ?array
|
||||
{
|
||||
$dates = $this->formatDates($changes, 'previous_date');
|
||||
|
||||
if ($dates === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$plural = $changes->count() > 1;
|
||||
|
||||
return [
|
||||
'type' => EventDateChangeType::Suspended->value,
|
||||
'title' => $plural ? 'FECHAS CANCELADAS!' : 'FECHA CANCELADA!',
|
||||
'message' => [
|
||||
['text' => $plural ? 'Las fechas del ' : 'La fecha del ', 'bold' => false],
|
||||
['text' => $dates, 'bold' => true],
|
||||
['text' => $plural ? ' han sido canceladas.' : ' ha sido cancelada.', 'bold' => false],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, EventDateChange> $changes
|
||||
* @return array{type: string, title: string, message: list<array{text: string, bold: bool}>}|null
|
||||
*/
|
||||
private function rescheduleNotice(Collection $changes): ?array
|
||||
{
|
||||
$changes = $changes->whereNotNull('new_date');
|
||||
$sourceDates = $this->formatDates($changes, 'previous_date');
|
||||
$destinationDates = $this->formatDates($changes, 'new_date');
|
||||
|
||||
if ($sourceDates === null || $destinationDates === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$plural = $changes->count() > 1;
|
||||
$message = [
|
||||
['text' => $plural ? 'Las fechas del ' : 'La fecha del ', 'bold' => false],
|
||||
['text' => $sourceDates, 'bold' => true],
|
||||
[
|
||||
'text' => $plural ? ' han sido reprogramadas para el ' : ' ha sido reprogramada para el ',
|
||||
'bold' => false,
|
||||
],
|
||||
['text' => $destinationDates, 'bold' => true],
|
||||
];
|
||||
|
||||
if ($plural) {
|
||||
$message[] = ['text' => ', ', 'bold' => false];
|
||||
$message[] = ['text' => 'respectivamente', 'bold' => true];
|
||||
}
|
||||
|
||||
$message[] = ['text' => '.', 'bold' => false];
|
||||
|
||||
return [
|
||||
'type' => EventDateChangeType::Rescheduled->value,
|
||||
'title' => $plural ? 'FECHAS REPROGRAMADAS!' : 'FECHA REPROGRAMADA!',
|
||||
'message' => $message,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, EventDateChange> $changes
|
||||
*/
|
||||
private function formatDates(Collection $changes, string $attribute): ?string
|
||||
{
|
||||
return $this->dateTextFormatter->formatForSentence(
|
||||
$changes
|
||||
->pluck($attribute)
|
||||
->filter()
|
||||
->map(fn ($date): string => $date->format('Y-m-d'))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,21 @@ class EventDateTextFormatter
|
||||
/** @param iterable<string> $dates */
|
||||
public function format(iterable $dates): ?string
|
||||
{
|
||||
return $this->formatWithOptions($dates, false, false);
|
||||
}
|
||||
|
||||
/** @param iterable<string> $dates */
|
||||
public function formatForSentence(iterable $dates): ?string
|
||||
{
|
||||
return $this->formatWithOptions($dates, true, true);
|
||||
}
|
||||
|
||||
/** @param iterable<string> $dates */
|
||||
private function formatWithOptions(
|
||||
iterable $dates,
|
||||
bool $padDays,
|
||||
bool $includeYearPreposition,
|
||||
): ?string {
|
||||
$normalizedDates = collect($dates)
|
||||
->map(fn (string $date): DateTimeImmutable => new DateTimeImmutable($date))
|
||||
->unique(fn (DateTimeImmutable $date): string => $date->format('Y-m-d'))
|
||||
@@ -37,12 +52,14 @@ class EventDateTextFormatter
|
||||
|
||||
$years = $normalizedDates
|
||||
->groupBy(fn (DateTimeImmutable $date): string => $date->format('Y'))
|
||||
->map(function ($yearDates, string $year): string {
|
||||
->map(function ($yearDates, string $year) use ($padDays, $includeYearPreposition): string {
|
||||
$months = $yearDates
|
||||
->groupBy(fn (DateTimeImmutable $date): string => $date->format('n'))
|
||||
->map(function ($monthDates, string $month): string {
|
||||
->map(function ($monthDates, string $month) use ($padDays): string {
|
||||
$days = $monthDates
|
||||
->map(fn (DateTimeImmutable $date): string => (string) ((int) $date->format('j')))
|
||||
->map(fn (DateTimeImmutable $date): string => $padDays
|
||||
? $date->format('d')
|
||||
: (string) ((int) $date->format('j')))
|
||||
->values()
|
||||
->all();
|
||||
|
||||
@@ -51,7 +68,7 @@ class EventDateTextFormatter
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return $this->join($months).' '.$year;
|
||||
return $this->join($months).($includeYearPreposition ? ' de ' : ' ').$year;
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
|
||||
@@ -2,7 +2,17 @@
|
||||
|
||||
namespace App\Domains\Event\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\VariantReplacementService;
|
||||
use App\Domains\Event\Enums\EventDateChangeType;
|
||||
use App\Domains\Event\Events\EventDateRescheduled;
|
||||
use App\Domains\Event\Events\EventDateSuspended;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Models\EventDateChange;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
@@ -14,6 +24,12 @@ class EventService
|
||||
'facebook_url' => 'facebook',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly EffectiveEventDateResolver $effectiveEventDateResolver,
|
||||
private readonly AffectedEventDatePurchaseResolver $affectedPurchaseResolver,
|
||||
private readonly VariantReplacementService $variantReplacementService,
|
||||
) {}
|
||||
|
||||
public function forTenant(Tenant $tenant): Tenant
|
||||
{
|
||||
return $tenant->load(['eventDates.validityTime', 'socialMedia']);
|
||||
@@ -27,9 +43,14 @@ class EventService
|
||||
$tenant->update([
|
||||
'event_title' => $data['title'],
|
||||
'event_location' => $data['location'],
|
||||
...array_intersect_key($data, array_flip([
|
||||
'allow_ticket_refund',
|
||||
'allow_ticket_total_refund',
|
||||
'allow_ticket_partial_refund',
|
||||
'ticket_partial_refund_percentage',
|
||||
])),
|
||||
]);
|
||||
|
||||
$this->syncDates($tenant, $data['dates']);
|
||||
if (array_key_exists('social_media', $data)) {
|
||||
$this->syncSocialMedia($tenant, $data['social_media']);
|
||||
} else {
|
||||
@@ -40,41 +61,247 @@ class EventService
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<int, array{date: string, start_time: string, end_time: string}> $dates */
|
||||
private function syncDates(Tenant $tenant, array $dates): void
|
||||
/** @param array{date: string, start_time: string, end_time: string} $data */
|
||||
public function createDateForTenant(Tenant $tenant, array $data): EventDate
|
||||
{
|
||||
$existingDates = $tenant->eventDates()->get()->values();
|
||||
return DB::transaction(function () use ($tenant, $data): EventDate {
|
||||
$attributes = $this->dateAttributes($data);
|
||||
|
||||
foreach (array_values($dates) as $index => $date) {
|
||||
$attributes = [
|
||||
'date' => $date['date'],
|
||||
'time_start' => $date['start_time'],
|
||||
'time_end' => $date['end_time'],
|
||||
];
|
||||
|
||||
$existingDate = $existingDates->get($index);
|
||||
|
||||
if ($existingDate) {
|
||||
$existingDate->update($attributes);
|
||||
} else {
|
||||
$tenant->eventDates()->create($attributes);
|
||||
}
|
||||
}
|
||||
|
||||
$datesToDelete = $existingDates->slice(count($dates));
|
||||
|
||||
if ($datesToDelete->contains(fn ($eventDate): bool => $eventDate
|
||||
->selectedByVariants()
|
||||
->whereHas('sourceTickets')
|
||||
->exists()
|
||||
|| $eventDate->variants()->whereHas('sourceTickets')->exists())) {
|
||||
if ($tenant->eventDates()->where($attributes)->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'dates' => ['No se puede eliminar una fecha utilizada por tickets generados.'],
|
||||
'date' => ['La fecha y el horario ya existen.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$datesToDelete->each->delete();
|
||||
$tenant->unsetRelation('eventDates');
|
||||
return $tenant->eventDates()->create($attributes)->load('validityTime');
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array{date: string} $data */
|
||||
public function rescheduleDateForTenant(
|
||||
Tenant $tenant,
|
||||
EventDate $eventDate,
|
||||
array $data,
|
||||
?User $createdBy = null,
|
||||
): EventDate {
|
||||
return DB::transaction(function () use ($tenant, $eventDate, $data, $createdBy): EventDate {
|
||||
$source = $this->lockedDateForTenant($tenant, $eventDate);
|
||||
|
||||
if ($source->suspended_at !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'event_date' => ['No se puede reprogramar una fecha suspendida.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($source->rescheduled_to_event_date_id !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'event_date' => ['La fecha ya fue reprogramada.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$destination = $tenant->eventDates()
|
||||
->whereDate('date', $data['date'])
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($destination === null) {
|
||||
$destination = $tenant->eventDates()->create([
|
||||
'date' => $data['date'],
|
||||
'time_start' => $source->time_start,
|
||||
'time_end' => $source->time_end,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($destination->is($source) || $this->chainContains($destination, $source)) {
|
||||
throw ValidationException::withMessages([
|
||||
'date' => ['La reprogramación generaría una referencia circular.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$effectiveDestination = $this->effectiveEventDateResolver->resolve($destination);
|
||||
if ($effectiveDestination === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'date' => ['La fecha de destino no es utilizable.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||
$tenant,
|
||||
$this->affectedDateIds($tenant, $source),
|
||||
);
|
||||
$source->update(['rescheduled_to_event_date_id' => $destination->getKey()]);
|
||||
$this->variantReplacementService->replaceEventDate($source, $effectiveDestination);
|
||||
|
||||
EventDateChange::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'change_type' => EventDateChangeType::Rescheduled,
|
||||
'source_event_date_id' => $source->getKey(),
|
||||
'destination_event_date_id' => $destination->getKey(),
|
||||
'created_by_user_id' => $createdBy?->getKey(),
|
||||
'previous_date' => $source->date->format('Y-m-d'),
|
||||
'new_date' => $destination->date->format('Y-m-d'),
|
||||
]);
|
||||
|
||||
EventDateRescheduled::dispatch(
|
||||
$tenant->codigo,
|
||||
$source->getKey(),
|
||||
$destination->getKey(),
|
||||
$source->date->format('d/m/Y'),
|
||||
$destination->date->format('d/m/Y'),
|
||||
$purchaseTickets,
|
||||
);
|
||||
|
||||
return $source->fresh(['validityTime', 'rescheduledTo.validityTime']);
|
||||
});
|
||||
}
|
||||
|
||||
public function suspendDateForTenant(
|
||||
Tenant $tenant,
|
||||
EventDate $eventDate,
|
||||
?User $createdBy = null,
|
||||
): EventDate {
|
||||
return DB::transaction(function () use ($tenant, $eventDate, $createdBy): EventDate {
|
||||
$date = $this->lockedDateForTenant($tenant, $eventDate);
|
||||
|
||||
if ($date->rescheduled_to_event_date_id !== null) {
|
||||
throw ValidationException::withMessages([
|
||||
'event_date' => ['No se puede suspender una fecha que ya fue reprogramada.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($date->suspended_at !== null) {
|
||||
return $date->load('validityTime');
|
||||
}
|
||||
|
||||
$purchaseTickets = $this->affectedPurchaseResolver->resolve(
|
||||
$tenant,
|
||||
$this->affectedDateIds($tenant, $date),
|
||||
);
|
||||
$date->update(['suspended_at' => now()]);
|
||||
$this->variantReplacementService->disableForSuspension($date);
|
||||
$this->disableTicketsWithoutUsableDates($tenant, $date);
|
||||
|
||||
EventDateChange::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'change_type' => EventDateChangeType::Suspended,
|
||||
'source_event_date_id' => $date->getKey(),
|
||||
'destination_event_date_id' => null,
|
||||
'created_by_user_id' => $createdBy?->getKey(),
|
||||
'previous_date' => $date->date->format('Y-m-d'),
|
||||
'new_date' => null,
|
||||
]);
|
||||
|
||||
EventDateSuspended::dispatch(
|
||||
$tenant->codigo,
|
||||
$date->getKey(),
|
||||
$date->date->format('d/m/Y'),
|
||||
$purchaseTickets,
|
||||
);
|
||||
|
||||
return $date->fresh('validityTime');
|
||||
});
|
||||
}
|
||||
|
||||
private function lockedDateForTenant(Tenant $tenant, EventDate $eventDate): EventDate
|
||||
{
|
||||
return $tenant->eventDates()
|
||||
->whereKey($eventDate->getKey())
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
}
|
||||
|
||||
private function chainContains(EventDate $start, EventDate $expected): bool
|
||||
{
|
||||
$current = $start;
|
||||
$visited = [];
|
||||
|
||||
while ($current->rescheduled_to_event_date_id !== null) {
|
||||
if ($current->is($expected)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isset($visited[$current->getKey()])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$visited[$current->getKey()] = true;
|
||||
$current = $current->rescheduledTo()->lockForUpdate()->first();
|
||||
|
||||
if ($current === null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return $current->is($expected);
|
||||
}
|
||||
|
||||
/** @return Collection<int, int> */
|
||||
private function affectedDateIds(Tenant $tenant, EventDate $eventDate): Collection
|
||||
{
|
||||
$affectedDateIds = collect([$eventDate->getKey()]);
|
||||
$frontier = $affectedDateIds;
|
||||
|
||||
while ($frontier->isNotEmpty()) {
|
||||
$predecessors = $tenant->eventDates()
|
||||
->whereIn('rescheduled_to_event_date_id', $frontier)
|
||||
->pluck('id')
|
||||
->diff($affectedDateIds)
|
||||
->values();
|
||||
$affectedDateIds = $affectedDateIds->merge($predecessors)->unique()->values();
|
||||
$frontier = $predecessors;
|
||||
}
|
||||
|
||||
return $affectedDateIds;
|
||||
}
|
||||
|
||||
private function disableTicketsWithoutUsableDates(Tenant $tenant, EventDate $suspendedDate): void
|
||||
{
|
||||
$affectedDateIds = $this->affectedDateIds($tenant, $suspendedDate);
|
||||
|
||||
$variants = Variant::withTrashed()
|
||||
->where(function ($query) use ($affectedDateIds): void {
|
||||
$query->whereIn('event_date_id', $affectedDateIds)
|
||||
->orWhereHas('eventDates', fn ($eventDates) => $eventDates
|
||||
->whereIn('event_dates.id', $affectedDateIds));
|
||||
})
|
||||
->with(['eventDates', 'eventDate'])
|
||||
->get();
|
||||
|
||||
foreach ($variants as $variant) {
|
||||
$hasUsableDate = $variant->selectedEventDates()->contains(
|
||||
fn (EventDate $candidate): bool => $this->effectiveEventDateResolver->resolve($candidate) !== null
|
||||
);
|
||||
|
||||
if ($hasUsableDate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('source_variant_id', $variant->getKey())
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->each(function (Ticket $ticket): void {
|
||||
$ticket->markAsDisabled();
|
||||
$ticket->save();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{date: string, start_time: string, end_time: string} $data
|
||||
* @return array{date: string, time_start: string, time_end: string}
|
||||
*/
|
||||
private function dateAttributes(array $data): array
|
||||
{
|
||||
return [
|
||||
'date' => $data['date'],
|
||||
'time_start' => $data['start_time'].':00',
|
||||
'time_end' => $data['end_time'].':00',
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string, string|null> $contact */
|
||||
|
||||
@@ -8,4 +8,7 @@ Route::prefix('v1/adminapp/tenant')
|
||||
->group(function (): void {
|
||||
Route::get('event', [EventController::class, 'show']);
|
||||
Route::put('event', [EventController::class, 'update']);
|
||||
Route::post('event-dates', [EventController::class, 'storeDate']);
|
||||
Route::post('event-dates/{eventDate}/reschedule', [EventController::class, 'rescheduleDate']);
|
||||
Route::post('event-dates/{eventDate}/suspend', [EventController::class, 'suspendDate']);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Forms\Resources\EntryFormResource;
|
||||
use App\Domains\Forms\Services\EntryFormService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class EntryFormController extends Controller
|
||||
{
|
||||
public function __construct(protected EntryFormService $entryFormService) {}
|
||||
|
||||
public function __invoke(Request $request): EntryFormResource
|
||||
{
|
||||
return EntryFormResource::make(
|
||||
$this->entryFormService->get(
|
||||
$request->user('sanctum')->tenant()->firstOrFail()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
26
app/Domains/Forms/Resources/EntryFormResource.php
Normal file
26
app/Domains/Forms/Resources/EntryFormResource.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Resources;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class EntryFormResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'event_dates' => $this->resource['event_dates']->map(
|
||||
fn (EventDate $eventDate): array => [
|
||||
'id' => $eventDate->id,
|
||||
'validity_time_id' => $eventDate->validity_time_id,
|
||||
'validity_time' => ValidityTimeResource::make($eventDate->validityTime),
|
||||
'date' => $eventDate->date->format('Y-m-d'),
|
||||
]
|
||||
)->values(),
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Domains/Forms/Services/EntryFormService.php
Normal file
22
app/Domains/Forms/Services/EntryFormService.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Forms\Services;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class EntryFormService
|
||||
{
|
||||
/** @return array{event_dates: Collection<int, EventDate>} */
|
||||
public function get(Tenant $tenant): array
|
||||
{
|
||||
return [
|
||||
'event_dates' => $tenant->eventDates()
|
||||
->whereNull('rescheduled_to_event_date_id')
|
||||
->whereNull('suspended_at')
|
||||
->with('validityTime')
|
||||
->get(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,11 @@ class FoodFormService
|
||||
->keyBy('codigo');
|
||||
|
||||
return [
|
||||
'event_dates' => $tenant->eventDates()->with('validityTime')->get(),
|
||||
'event_dates' => $tenant->eventDates()
|
||||
->whereNull('rescheduled_to_event_date_id')
|
||||
->whereNull('suspended_at')
|
||||
->with('validityTime')
|
||||
->get(),
|
||||
'schedules' => $attributes->get('horario')?->options ?? new Collection,
|
||||
'services' => $attributes->get('servicio')?->options ?? new Collection,
|
||||
];
|
||||
|
||||
@@ -124,11 +124,7 @@ class TicketFilterFormService
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'placeholder' => 'Estado',
|
||||
'options' => [
|
||||
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
|
||||
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
|
||||
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
|
||||
],
|
||||
'options' => Ticket::statusOptions(),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -236,11 +236,7 @@ class TicketFormService
|
||||
?: $left['label'] <=> $right['label']);
|
||||
|
||||
return [
|
||||
'statuses' => [
|
||||
['value' => Ticket::STATUS_ACTIVE, 'label' => 'Activo'],
|
||||
['value' => Ticket::STATUS_USED, 'label' => 'Usado'],
|
||||
['value' => Ticket::STATUS_EXPIRED, 'label' => 'Vencido'],
|
||||
],
|
||||
'statuses' => Ticket::statusOptions(),
|
||||
'categories' => array_values(array_map(
|
||||
fn (array $category): array => [
|
||||
'value' => $category['value'],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Forms\Controllers\AdminApp\EntryFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\EventFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\FoodFormController;
|
||||
use App\Domains\Forms\Controllers\AdminApp\MerchandiseFormController;
|
||||
@@ -22,6 +23,10 @@ Route::prefix('v1/adminapp/forms')
|
||||
'fiesta-futbol-infantil/ticket',
|
||||
TicketFormController::class
|
||||
);
|
||||
Route::get(
|
||||
'fiesta-futbol-infantil/entry',
|
||||
EntryFormController::class
|
||||
);
|
||||
Route::get(
|
||||
'fiesta-futbol-infantil/merchandise',
|
||||
MerchandiseFormController::class
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Notification\Listeners;
|
||||
|
||||
use App\Domains\Event\Events\EventDateRescheduled;
|
||||
use App\Domains\Notification\Services\NotificationMailService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
|
||||
class SendEventDateRescheduledEmails implements ShouldQueueAfterCommit
|
||||
{
|
||||
use InteractsWithQueue;
|
||||
|
||||
public string $queue = 'emails';
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
/** @var array<int, int> */
|
||||
public array $backoff = [30, 120, 300];
|
||||
|
||||
public function handle(EventDateRescheduled $event): void
|
||||
{
|
||||
app(NotificationMailService::class)->sendEventDateRescheduled(
|
||||
$event->tenantCode,
|
||||
$event->sourceEventDateId,
|
||||
$event->destinationEventDateId,
|
||||
$event->previousDate,
|
||||
$event->newDate,
|
||||
$event->purchaseTickets,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Notification\Listeners;
|
||||
|
||||
use App\Domains\Event\Events\EventDateSuspended;
|
||||
use App\Domains\Notification\Services\NotificationMailService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
|
||||
class SendEventDateSuspendedEmails implements ShouldQueueAfterCommit
|
||||
{
|
||||
use InteractsWithQueue;
|
||||
|
||||
public string $queue = 'emails';
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
/** @var array<int, int> */
|
||||
public array $backoff = [30, 120, 300];
|
||||
|
||||
public function handle(EventDateSuspended $event): void
|
||||
{
|
||||
app(NotificationMailService::class)->sendEventDateSuspended(
|
||||
$event->tenantCode,
|
||||
$event->eventDateId,
|
||||
$event->date,
|
||||
$event->purchaseTickets,
|
||||
);
|
||||
}
|
||||
}
|
||||
44
app/Domains/Notification/Models/EmailDelivery.php
Normal file
44
app/Domains/Notification/Models/EmailDelivery.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Notification\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
#[Fillable([
|
||||
'idempotency_key',
|
||||
'email_type',
|
||||
'tenant_code',
|
||||
'status',
|
||||
'attempts',
|
||||
'context',
|
||||
'recipient_fingerprint',
|
||||
'claim_token',
|
||||
'claimed_at',
|
||||
'lease_expires_at',
|
||||
'sent_at',
|
||||
'failed_at',
|
||||
'last_error',
|
||||
])]
|
||||
class EmailDelivery extends Model
|
||||
{
|
||||
public const STATUS_PENDING = 'pending';
|
||||
|
||||
public const STATUS_PROCESSING = 'processing';
|
||||
|
||||
public const STATUS_SENT = 'sent';
|
||||
|
||||
public const STATUS_FAILED = 'failed';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'attempts' => 'integer',
|
||||
'context' => 'array',
|
||||
'claimed_at' => 'datetime',
|
||||
'lease_expires_at' => 'datetime',
|
||||
'sent_at' => 'datetime',
|
||||
'failed_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Notification\Services;
|
||||
|
||||
use App\Domains\Notification\Models\EmailDelivery;
|
||||
use Closure;
|
||||
use Illuminate\Database\Query\Expression;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
class IdempotentEmailDeliveryService
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
* @param Closure(): void $send
|
||||
*/
|
||||
public function sendOnce(
|
||||
string $key,
|
||||
string $type,
|
||||
?string $tenantCode,
|
||||
array $context,
|
||||
string $recipient,
|
||||
Closure $send,
|
||||
): bool {
|
||||
$now = now();
|
||||
|
||||
EmailDelivery::query()->insertOrIgnore([
|
||||
'idempotency_key' => $key,
|
||||
'email_type' => $type,
|
||||
'tenant_code' => $tenantCode,
|
||||
'status' => EmailDelivery::STATUS_PENDING,
|
||||
'attempts' => 0,
|
||||
'context' => json_encode($context, JSON_THROW_ON_ERROR),
|
||||
'recipient_fingerprint' => $this->recipientFingerprint($recipient),
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$claimToken = (string) Str::uuid();
|
||||
$leaseExpiresAt = $now->copy()->addSeconds(
|
||||
max(1, (int) config('mail.delivery_lease_seconds', 300)),
|
||||
);
|
||||
|
||||
$claimed = EmailDelivery::query()
|
||||
->where('idempotency_key', $key)
|
||||
->where(function ($query) use ($now): void {
|
||||
$query->whereIn('status', [
|
||||
EmailDelivery::STATUS_PENDING,
|
||||
EmailDelivery::STATUS_FAILED,
|
||||
])->orWhere(function ($query) use ($now): void {
|
||||
$query->where('status', EmailDelivery::STATUS_PROCESSING)
|
||||
->where('lease_expires_at', '<=', $now);
|
||||
});
|
||||
})
|
||||
->update([
|
||||
'status' => EmailDelivery::STATUS_PROCESSING,
|
||||
'attempts' => new Expression('attempts + 1'),
|
||||
'context' => json_encode($context, JSON_THROW_ON_ERROR),
|
||||
'recipient_fingerprint' => $this->recipientFingerprint($recipient),
|
||||
'claim_token' => $claimToken,
|
||||
'claimed_at' => $now,
|
||||
'lease_expires_at' => $leaseExpiresAt,
|
||||
'failed_at' => null,
|
||||
'last_error' => null,
|
||||
'updated_at' => $now,
|
||||
]) === 1;
|
||||
|
||||
if (! $claimed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$send();
|
||||
|
||||
EmailDelivery::query()
|
||||
->where('idempotency_key', $key)
|
||||
->where('claim_token', $claimToken)
|
||||
->update([
|
||||
'status' => EmailDelivery::STATUS_SENT,
|
||||
'claim_token' => null,
|
||||
'lease_expires_at' => null,
|
||||
'sent_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
} catch (Throwable $exception) {
|
||||
EmailDelivery::query()
|
||||
->where('idempotency_key', $key)
|
||||
->where('claim_token', $claimToken)
|
||||
->update([
|
||||
'status' => EmailDelivery::STATUS_FAILED,
|
||||
'claim_token' => null,
|
||||
'lease_expires_at' => null,
|
||||
'failed_at' => now(),
|
||||
'last_error' => Str::limit($exception::class, 2000, ''),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function recipientFingerprint(string $recipient): string
|
||||
{
|
||||
return hash_hmac(
|
||||
'sha256',
|
||||
mb_strtolower(trim($recipient)),
|
||||
(string) config('app.key'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketPdfService;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
use App\Domains\Ticket\Services\TicketValidityResolver;
|
||||
use Closure;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -21,16 +22,25 @@ class NotificationMailService
|
||||
public function __construct(
|
||||
private readonly MailService $mailService,
|
||||
private readonly TicketPdfService $ticketPdfService,
|
||||
private readonly IdempotentEmailDeliveryService $emailDeliveryService,
|
||||
) {}
|
||||
|
||||
public function sendWelcome(int $userId, string $tenantCode): void
|
||||
{
|
||||
$this->sendLogged('welcome', [
|
||||
$context = [
|
||||
'user_id' => $userId,
|
||||
'tenant_code' => $tenantCode,
|
||||
], function () use ($userId, $tenantCode): array {
|
||||
];
|
||||
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
|
||||
$user = User::query()->findOrFail($userId);
|
||||
|
||||
$this->sendIdempotently(
|
||||
"welcome:{$tenantCode}:{$userId}",
|
||||
'welcome',
|
||||
$tenantCode,
|
||||
$context,
|
||||
$user->email,
|
||||
function () use ($user, $tenant, $tenantCode): array {
|
||||
$brand = $tenant->websiteType ?? $tenant;
|
||||
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
|
||||
|
||||
@@ -46,7 +56,8 @@ class NotificationMailService
|
||||
return [
|
||||
'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
|
||||
];
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public function sendPasswordResetCode(
|
||||
@@ -60,7 +71,6 @@ class NotificationMailService
|
||||
'channel' => $channel,
|
||||
];
|
||||
|
||||
$this->sendLogged('password_reset', $context, function () use ($attemptId, $tenantCode, $channel, $context): ?array {
|
||||
$tenant = Tenant::query()
|
||||
->with('websiteType')
|
||||
->where('codigo', $tenantCode)
|
||||
@@ -76,9 +86,16 @@ class NotificationMailService
|
||||
'user_id' => $attempt->user_id,
|
||||
]));
|
||||
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
$this->sendIdempotently(
|
||||
"password-reset:{$attemptId}",
|
||||
'password_reset',
|
||||
$tenantCode,
|
||||
$context,
|
||||
$attempt->user->email,
|
||||
function () use ($attempt, $tenant, $tenantCode, $channel): array {
|
||||
$recoveryDomain = match ($channel) {
|
||||
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
|
||||
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
||||
@@ -130,14 +147,14 @@ class NotificationMailService
|
||||
'user_id' => $attempt->user_id,
|
||||
'recovery_domain_available' => $recoveryDomain !== null,
|
||||
];
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public function sendPurchaseConfirmed(int $purchaseId): void
|
||||
{
|
||||
$context = ['purchase_id' => $purchaseId];
|
||||
|
||||
$this->sendLogged('purchase_confirmed', $context, function () use ($purchaseId, $context): ?array {
|
||||
$purchase = Purchase::query()
|
||||
->with(['tenant', 'user', 'items'])
|
||||
->find($purchaseId);
|
||||
@@ -148,9 +165,23 @@ class NotificationMailService
|
||||
'missing_model' => Purchase::class,
|
||||
]));
|
||||
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
$recipient = $this->recipientFor($purchase);
|
||||
if ($recipient === '') {
|
||||
$this->logSkipped('purchase_confirmed', array_merge($context, ['reason' => 'missing_recipient']));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->sendIdempotently(
|
||||
"purchase-confirmed:{$purchaseId}",
|
||||
'purchase_confirmed',
|
||||
$purchase->tenant_codigo,
|
||||
$context,
|
||||
$recipient,
|
||||
function () use ($purchase, $recipient): array {
|
||||
/** @var Collection<int, Ticket> $tickets */
|
||||
$tickets = $purchase->tickets()
|
||||
->where('tenant_code', $purchase->tenant_codigo)
|
||||
@@ -167,7 +198,7 @@ class NotificationMailService
|
||||
$this->mailService
|
||||
->forTenant($purchase->tenant_codigo)
|
||||
->send(
|
||||
$this->recipientFor($purchase),
|
||||
$recipient,
|
||||
"Compra confirmada - Compra #{$purchase->getKey()}",
|
||||
view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
|
||||
attachments: $attachments,
|
||||
@@ -181,7 +212,215 @@ class NotificationMailService
|
||||
'ticket_count' => $tickets->count(),
|
||||
'ticket_ids' => $tickets->modelKeys(),
|
||||
];
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||
*/
|
||||
public function sendEventDateRescheduled(
|
||||
string $tenantCode,
|
||||
int $sourceEventDateId,
|
||||
int $destinationEventDateId,
|
||||
string $previousDate,
|
||||
string $newDate,
|
||||
array $purchaseTickets,
|
||||
): void {
|
||||
foreach ($purchaseTickets as $purchaseTicketGroup) {
|
||||
$purchaseId = $purchaseTicketGroup['purchase_id'];
|
||||
$ticketIds = $purchaseTicketGroup['ticket_ids'];
|
||||
$context = [
|
||||
'tenant_code' => $tenantCode,
|
||||
'event_date_id' => $sourceEventDateId,
|
||||
'destination_event_date_id' => $destinationEventDateId,
|
||||
'purchase_id' => $purchaseId,
|
||||
'ticket_ids' => $ticketIds,
|
||||
];
|
||||
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
|
||||
|
||||
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
|
||||
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||
'reason' => 'purchase_not_paid_or_not_found',
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
/** @var Collection<int, Ticket> $tickets */
|
||||
$tickets = $purchase->tickets()
|
||||
->where('tenant_code', $tenantCode)
|
||||
->whereKey($ticketIds)
|
||||
->with([
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
])
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||
->values();
|
||||
|
||||
if ($tickets->isEmpty()) {
|
||||
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||
'reason' => 'no_longer_active_tickets',
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$recipient = $this->recipientFor($purchase);
|
||||
if ($recipient === '') {
|
||||
$this->logSkipped('event_date_rescheduled', array_merge($context, [
|
||||
'reason' => 'missing_recipient',
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$deliveryKey = "event-date-rescheduled:{$sourceEventDateId}:{$destinationEventDateId}:{$purchaseId}";
|
||||
$this->sendIdempotently(
|
||||
$deliveryKey,
|
||||
'event_date_rescheduled',
|
||||
$tenantCode,
|
||||
$context,
|
||||
$recipient,
|
||||
function () use (
|
||||
$tenantCode,
|
||||
$purchase,
|
||||
$recipient,
|
||||
$previousDate,
|
||||
$newDate,
|
||||
$tickets,
|
||||
): array {
|
||||
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
|
||||
|
||||
$this->mailService
|
||||
->forTenant($tenantCode)
|
||||
->send(
|
||||
$recipient,
|
||||
"Tu evento fue reprogramado - Compra #{$purchase->getKey()}",
|
||||
view('mail.notifications.event-date-rescheduled', compact(
|
||||
'purchase', 'previousDate', 'newDate', 'tickets'
|
||||
))->render(),
|
||||
$brand,
|
||||
);
|
||||
|
||||
return ['ticket_count' => $tickets->count()];
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
|
||||
*/
|
||||
public function sendEventDateSuspended(
|
||||
string $tenantCode,
|
||||
int $eventDateId,
|
||||
string $date,
|
||||
array $purchaseTickets,
|
||||
): void {
|
||||
foreach ($purchaseTickets as $purchaseTicketGroup) {
|
||||
$purchaseId = $purchaseTicketGroup['purchase_id'];
|
||||
$ticketIds = $purchaseTicketGroup['ticket_ids'];
|
||||
$context = [
|
||||
'tenant_code' => $tenantCode,
|
||||
'event_date_id' => $eventDateId,
|
||||
'purchase_id' => $purchaseId,
|
||||
'ticket_ids' => $ticketIds,
|
||||
];
|
||||
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
|
||||
|
||||
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
|
||||
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||
'reason' => 'purchase_not_paid_or_not_found',
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
/** @var Collection<int, Ticket> $tickets */
|
||||
$tickets = $purchase->tickets()
|
||||
->where('tenant_code', $tenantCode)
|
||||
->whereKey($ticketIds)
|
||||
->with([
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
])
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => in_array($ticket->status, [
|
||||
Ticket::STATUS_ACTIVE,
|
||||
Ticket::STATUS_DISABLED,
|
||||
], true))
|
||||
->values();
|
||||
|
||||
if ($tickets->isEmpty()) {
|
||||
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||
'reason' => 'no_longer_relevant_tickets',
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$recipient = $this->recipientFor($purchase);
|
||||
if ($recipient === '') {
|
||||
$this->logSkipped('event_date_suspended', array_merge($context, [
|
||||
'reason' => 'missing_recipient',
|
||||
]));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$deliveryKey = "event-date-suspended:{$eventDateId}:{$purchaseId}";
|
||||
$disabledTickets = $tickets
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_DISABLED)
|
||||
->values();
|
||||
$activeTickets = $tickets
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_ACTIVE)
|
||||
->values();
|
||||
|
||||
$this->sendIdempotently(
|
||||
$deliveryKey,
|
||||
'event_date_suspended',
|
||||
$tenantCode,
|
||||
$context,
|
||||
$recipient,
|
||||
function () use (
|
||||
$tenantCode,
|
||||
$purchase,
|
||||
$recipient,
|
||||
$date,
|
||||
$disabledTickets,
|
||||
$activeTickets,
|
||||
): array {
|
||||
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
|
||||
|
||||
$this->mailService
|
||||
->forTenant($tenantCode)
|
||||
->send(
|
||||
$recipient,
|
||||
"Una fecha de tu evento fue suspendida - Compra #{$purchase->getKey()}",
|
||||
view('mail.notifications.event-date-suspended', compact(
|
||||
'purchase', 'date', 'disabledTickets', 'activeTickets'
|
||||
))->render(),
|
||||
$brand,
|
||||
);
|
||||
|
||||
return [
|
||||
'ticket_count' => $disabledTickets->count() + $activeTickets->count(),
|
||||
'disabled_ticket_ids' => $disabledTickets->modelKeys(),
|
||||
'active_ticket_ids' => $activeTickets->modelKeys(),
|
||||
];
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function eventDateNotificationPurchase(string $tenantCode, int $purchaseId): ?Purchase
|
||||
{
|
||||
return Purchase::query()
|
||||
->where('tenant_codigo', $tenantCode)
|
||||
->with(['tenant.websiteType', 'user'])
|
||||
->find($purchaseId);
|
||||
}
|
||||
|
||||
private function recipientFor(Purchase $purchase): string
|
||||
@@ -189,6 +428,34 @@ class NotificationMailService
|
||||
return (string) ($purchase->email ?: $purchase->user?->email);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
* @param Closure(): array<string, mixed> $send
|
||||
*/
|
||||
private function sendIdempotently(
|
||||
string $key,
|
||||
string $emailType,
|
||||
?string $tenantCode,
|
||||
array $context,
|
||||
string $recipient,
|
||||
Closure $send,
|
||||
): void {
|
||||
$sent = $this->emailDeliveryService->sendOnce(
|
||||
$key,
|
||||
$emailType,
|
||||
$tenantCode,
|
||||
$context,
|
||||
$recipient,
|
||||
function () use ($emailType, $context, $send): void {
|
||||
$this->sendLogged($emailType, $context, $send);
|
||||
},
|
||||
);
|
||||
|
||||
if (! $sent) {
|
||||
$this->logSkipped($emailType, array_merge($context, ['reason' => 'already_claimed']));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
* @param Closure(): (array<string, mixed>|null) $send
|
||||
|
||||
@@ -12,7 +12,19 @@ Orquesta notificaciones de negocio por correo a partir de eventos de otros domin
|
||||
|
||||
## Componentes
|
||||
|
||||
Los listeners `SendWelcomeEmail`, `SendPasswordResetEmail` y `SendPurchaseConfirmedEmail` delegan en `NotificationMailService`. Este servicio carga el contexto necesario, renderiza las vistas y envía mediante `Integration/MailService`.
|
||||
Los listeners delegan en `NotificationMailService`. Este servicio carga el contexto necesario, renderiza las vistas y envía mediante `Integration/MailService`.
|
||||
|
||||
`IdempotentEmailDeliveryService` coordina los envíos automáticos mediante la tabla
|
||||
`email_deliveries`. Cada correo utiliza una clave de negocio única:
|
||||
|
||||
- bienvenida: `welcome:{tenant_code}:{user_id}`;
|
||||
- recuperación: `password-reset:{attempt_id}`;
|
||||
- compra confirmada: `purchase-confirmed:{purchase_id}`;
|
||||
- reprogramación: `event-date-rescheduled:{source_event_date_id}:{destination_event_date_id}:{purchase_id}`;
|
||||
- suspensión: `event-date-suspended:{event_date_id}:{purchase_id}`.
|
||||
|
||||
Los correos de prueba y de validación de una integración SMTP no usan esta capa,
|
||||
porque su reenvío explícito es parte de su comportamiento esperado.
|
||||
|
||||
## API y dependencias
|
||||
|
||||
@@ -25,3 +37,12 @@ No expone rutas HTTP. Consume datos de `Auth`, `Tenant`, `Purchase` y `Ticket`,
|
||||
- Los correos de cuenta (bienvenida y recuperación de contraseña) usan la identidad visual del `WebsiteType` asociado al tenant, con fallback al tenant si no tiene uno configurado.
|
||||
- El correo transaccional de compra confirmada usa la identidad visual del tenant y adjunta un único PDF cuando la compra generó tickets.
|
||||
- Los handlers deben permanecer idempotentes o tolerantes a reintentos de cola.
|
||||
- Una entrega queda en estado `processing` mientras un worker posee su claim. Si
|
||||
el worker se interrumpe, el claim vence según `EMAIL_DELIVERY_LEASE_SECONDS` y
|
||||
otro intento puede recuperarlo.
|
||||
- Los fallos quedan registrados como `failed` y pueden ser retomados por los
|
||||
reintentos de la cola. Los envíos exitosos permanecen como `sent` y las llamadas
|
||||
posteriores con la misma clave no vuelven a enviar el correo.
|
||||
- SMTP no ofrece una confirmación transaccional junto con la base de datos. Una
|
||||
interrupción ocurrida después de entregar el correo y antes de registrar
|
||||
`sent` puede producir un duplicado excepcional al recuperar el claim.
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\TicketRefund;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -64,6 +65,12 @@ class PurchaseItem extends Model
|
||||
return $this->hasMany(Ticket::class, 'source_purchase_item_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<TicketRefund, $this> */
|
||||
public function ticketRefunds(): HasMany
|
||||
{
|
||||
return $this->hasMany(TicketRefund::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Attachment, $this> */
|
||||
public function imageAttachment(): BelongsTo
|
||||
{
|
||||
|
||||
@@ -41,6 +41,17 @@ class CatalogSelectionResolver
|
||||
]);
|
||||
}
|
||||
|
||||
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([
|
||||
"{$fieldPrefix}.catalog_item_id" => [__('api.cart.bundle_component_unavailable')],
|
||||
]);
|
||||
}
|
||||
|
||||
return $catalogItem;
|
||||
}
|
||||
|
||||
@@ -70,6 +81,12 @@ class CatalogSelectionResolver
|
||||
throw new NotFoundHttpException('Variant not found for catalog item.');
|
||||
}
|
||||
|
||||
if (! $variant->isSellable()) {
|
||||
throw ValidationException::withMessages([
|
||||
"{$fieldPrefix}.variant_id" => [__('api.cart.variant_unavailable')],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
$variant->setRelation(
|
||||
'inventory',
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Cart\Services\CartVariantReplacementService;
|
||||
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
@@ -29,6 +30,7 @@ class StartCheckoutService
|
||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||
private readonly PurchaseResponseLoader $responses,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
private readonly CartVariantReplacementService $variantReplacements,
|
||||
) {}
|
||||
|
||||
/** @param array<string, mixed> $purchaseData */
|
||||
@@ -250,6 +252,7 @@ class StartCheckoutService
|
||||
int $cartId,
|
||||
): Purchase {
|
||||
$cart = $this->resolveCart($tenant, $userId, $cartId);
|
||||
$this->variantReplacements->replaceHistoricalVariants($cart);
|
||||
$cartItems = $cart->items()->lockForUpdate()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\TicketRefund;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class PurchaseRefundSummaryService
|
||||
{
|
||||
public function totalForTenant(Tenant $tenant): string
|
||||
{
|
||||
$total = TicketRefund::query()
|
||||
->whereHas(
|
||||
'purchaseItem.purchase',
|
||||
fn (Builder $query): Builder => $query->where('tenant_codigo', $tenant->codigo)
|
||||
)
|
||||
->sum('amount');
|
||||
|
||||
return number_format((float) $total, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ class SaleController extends Controller
|
||||
$this->saleService->sales($tenant, $request->validated())
|
||||
)->additional([
|
||||
'confirmed_sales_total' => $this->saleService->confirmedSalesTotal($tenant),
|
||||
'refunded_total' => $this->saleService->refundedTotal($tenant),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class SaleTicketResource extends JsonResource
|
||||
'id' => $this->id,
|
||||
'expires_at' => $this->getEffectiveExpiresAt(),
|
||||
'status' => $this->status,
|
||||
'status_label' => $this->status_label,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Sale\Services;
|
||||
use App\Domains\Logging\Models\ValueChange;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Services\TicketPresentationResolver;
|
||||
@@ -17,6 +18,7 @@ class AdminAppSaleService
|
||||
{
|
||||
public function __construct(
|
||||
protected CheckoutService $checkoutService,
|
||||
protected PurchaseRefundSummaryService $refundSummaryService,
|
||||
) {}
|
||||
|
||||
public function confirmedSalesTotal(Tenant $tenant): string
|
||||
@@ -29,6 +31,11 @@ class AdminAppSaleService
|
||||
return number_format((float) $total, 2, '.', '');
|
||||
}
|
||||
|
||||
public function refundedTotal(Tenant $tenant): string
|
||||
{
|
||||
return $this->refundSummaryService->totalForTenant($tenant);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* q?: string|null,
|
||||
@@ -60,7 +67,7 @@ class AdminAppSaleService
|
||||
{
|
||||
return $this->findForTenant($tenant, $saleId)
|
||||
->tickets()
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS])
|
||||
->with([...TicketValidityResolver::RELATIONS, ...TicketPresentationResolver::RELATIONS, 'refund'])
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Models\EventDateChange;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Models\TenantMenu;
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
@@ -52,6 +53,10 @@ use Illuminate\Support\Facades\Schema;
|
||||
'checkout_editing_policy',
|
||||
'display_cart_item_images',
|
||||
'scanner_category_validation_enabled',
|
||||
'allow_ticket_refund',
|
||||
'allow_ticket_total_refund',
|
||||
'allow_ticket_partial_refund',
|
||||
'ticket_partial_refund_percentage',
|
||||
'event_title',
|
||||
'event_location',
|
||||
'event_date_text',
|
||||
@@ -72,6 +77,10 @@ class Tenant extends Model
|
||||
'checkout_editing_policy' => CartEditingPolicy::Disabled->value,
|
||||
'display_cart_item_images' => true,
|
||||
'scanner_category_validation_enabled' => true,
|
||||
'allow_ticket_refund' => false,
|
||||
'allow_ticket_total_refund' => false,
|
||||
'allow_ticket_partial_refund' => false,
|
||||
'ticket_partial_refund_percentage' => 0,
|
||||
];
|
||||
|
||||
public function getRouteKeyName(): string
|
||||
@@ -106,6 +115,35 @@ class Tenant extends Model
|
||||
return $this->scanner_category_validation_enabled;
|
||||
}
|
||||
|
||||
public function allow_refund(): bool
|
||||
{
|
||||
return (bool) $this->allow_ticket_refund
|
||||
&& ((bool) $this->allow_ticket_total_refund || $this->allow_partial_refund());
|
||||
}
|
||||
|
||||
public function allow_partial_refund(): bool
|
||||
{
|
||||
return (bool) $this->allow_ticket_refund
|
||||
&& (bool) $this->allow_ticket_partial_refund
|
||||
&& $this->ticket_partial_refund_percentage !== null
|
||||
&& (float) $this->ticket_partial_refund_percentage > 0;
|
||||
}
|
||||
|
||||
public function allowRefund(): bool
|
||||
{
|
||||
return $this->allow_refund();
|
||||
}
|
||||
|
||||
public function allowPartialRefund(): bool
|
||||
{
|
||||
return $this->allow_partial_refund();
|
||||
}
|
||||
|
||||
public function getAllowRefundAttribute(): bool
|
||||
{
|
||||
return $this->allow_refund();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
@@ -124,6 +162,10 @@ class Tenant extends Model
|
||||
'checkout_editing_policy' => CartEditingPolicy::class,
|
||||
'display_cart_item_images' => 'boolean',
|
||||
'scanner_category_validation_enabled' => 'boolean',
|
||||
'allow_ticket_refund' => 'boolean',
|
||||
'allow_ticket_total_refund' => 'boolean',
|
||||
'allow_ticket_partial_refund' => 'boolean',
|
||||
'ticket_partial_refund_percentage' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -188,6 +230,14 @@ class Tenant extends Model
|
||||
->orderBy('time_start');
|
||||
}
|
||||
|
||||
/** @return HasMany<EventDateChange, $this> */
|
||||
public function eventDateChanges(): HasMany
|
||||
{
|
||||
return $this->hasMany(EventDateChange::class, 'tenant_code', 'codigo')
|
||||
->orderBy('created_at')
|
||||
->orderBy('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Category, $this>
|
||||
*/
|
||||
|
||||
@@ -117,6 +117,16 @@ class StoreTenantRequest extends FormRequest
|
||||
],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_refund' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_total_refund' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
|
||||
'ticket_partial_refund_percentage' => [
|
||||
'sometimes',
|
||||
'numeric',
|
||||
'decimal:0,2',
|
||||
'min:0',
|
||||
'max:99.99',
|
||||
],
|
||||
'website_type_code' => [
|
||||
'required_with:extras',
|
||||
'sometimes',
|
||||
|
||||
@@ -138,6 +138,16 @@ class UpdateTenantRequest extends FormRequest
|
||||
],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_refund' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_total_refund' => ['sometimes', 'boolean'],
|
||||
'allow_ticket_partial_refund' => ['sometimes', 'boolean'],
|
||||
'ticket_partial_refund_percentage' => [
|
||||
'sometimes',
|
||||
'numeric',
|
||||
'decimal:0,2',
|
||||
'min:0',
|
||||
'max:99.99',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ namespace App\Domains\Tenant\Resources;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Models\AttachmentCrop;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Resources\EventDateChangeResource;
|
||||
use App\Domains\Event\Services\EventDateNoticeFormatter;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -50,12 +53,24 @@ class TenantResource extends JsonResource
|
||||
: [
|
||||
'title' => $this->event_title,
|
||||
'location' => $this->event_location,
|
||||
'dates' => $this->eventDates->map(fn ($eventDate): array => [
|
||||
'dates' => $this->eventDates
|
||||
->filter(fn (EventDate $eventDate): bool => $eventDate->rescheduled_to_event_date_id === null
|
||||
&& $eventDate->suspended_at === null
|
||||
)
|
||||
->map(fn (EventDate $eventDate): array => [
|
||||
'id' => $eventDate->id,
|
||||
'date' => $eventDate->date->format('Y-m-d'),
|
||||
'time_start' => $eventDate->time_start,
|
||||
'time_end' => $eventDate->time_end,
|
||||
])->values(),
|
||||
'date_changes' => $this->whenLoaded(
|
||||
'eventDateChanges',
|
||||
fn () => EventDateChangeResource::collection($this->eventDateChanges)
|
||||
),
|
||||
'date_notices' => $this->whenLoaded(
|
||||
'eventDateChanges',
|
||||
fn () => app(EventDateNoticeFormatter::class)->format($this->eventDateChanges)
|
||||
),
|
||||
]),
|
||||
'extras' => $this->whenLoaded(
|
||||
'websiteExtras',
|
||||
@@ -82,6 +97,10 @@ class TenantResource extends JsonResource
|
||||
'checkout_editing_policy' => CartEditingPolicyResource::make($this->checkout_editing_policy),
|
||||
'display_cart_item_images' => $this->display_cart_item_images,
|
||||
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled,
|
||||
'allow_ticket_refund' => $this->allow_ticket_refund,
|
||||
'allow_ticket_total_refund' => $this->allow_ticket_total_refund,
|
||||
'allow_ticket_partial_refund' => $this->allow_ticket_partial_refund,
|
||||
'ticket_partial_refund_percentage' => $this->ticket_partial_refund_percentage,
|
||||
'social_media' => $this->whenLoaded(
|
||||
'socialMedia',
|
||||
fn () => $this->socialMedia
|
||||
|
||||
@@ -4,11 +4,15 @@ namespace App\Domains\Ticket\Controllers\AdminApp;
|
||||
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketExportRequest;
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketIndexRequest;
|
||||
use App\Domains\Ticket\Requests\AdminAppTicketRefundRequest;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketCollection;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketRefundCalculationResource;
|
||||
use App\Domains\Ticket\Resources\AdminApp\AdminAppTicketResource;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketExcelService;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketPdfService;
|
||||
use App\Domains\Ticket\Services\AdminAppTicketService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
@@ -29,6 +33,36 @@ class TicketController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function cancel(Request $request, int $ticket): AdminAppTicketResource
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return new AdminAppTicketResource($this->ticketService->cancel($tenant, $ticket));
|
||||
}
|
||||
|
||||
public function calculateRefund(Request $request, int $ticket): AdminAppTicketRefundCalculationResource
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return new AdminAppTicketRefundCalculationResource(
|
||||
$this->ticketService->calculateRefund($tenant, $ticket)
|
||||
);
|
||||
}
|
||||
|
||||
public function refund(AdminAppTicketRefundRequest $request, int $ticket): AdminAppTicketResource
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
return new AdminAppTicketResource(
|
||||
$this->ticketService->refund(
|
||||
$tenant,
|
||||
$ticket,
|
||||
$request->validated('refund_type'),
|
||||
$request->user(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function downloadPdf(AdminAppTicketExportRequest $request): Response
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Ticket\Models;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Services\ResolvedTicketValidity;
|
||||
@@ -17,7 +18,9 @@ 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\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
@@ -26,12 +29,15 @@ use Illuminate\Support\Collection;
|
||||
'source_catalog_item_id',
|
||||
'source_variant_id',
|
||||
'used_at',
|
||||
'disabled_at',
|
||||
'cancelled_at',
|
||||
'refunded_at',
|
||||
'scanner_user_id',
|
||||
'user_id',
|
||||
])]
|
||||
class Ticket extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasFactory, LogsValueChanges;
|
||||
|
||||
private ?ResolvedTicketValidity $resolvedValidity = null;
|
||||
|
||||
@@ -41,8 +47,22 @@ class Ticket extends Model
|
||||
|
||||
public const STATUS_USED = 'used';
|
||||
|
||||
public const STATUS_DISABLED = 'disabled';
|
||||
|
||||
public const STATUS_CANCELLED = 'cancelled';
|
||||
|
||||
public const STATUS_REFUNDED = 'refunded';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
/** @var list<string> */
|
||||
protected array $loggedAttributes = [
|
||||
'used_at',
|
||||
'disabled_at',
|
||||
'cancelled_at',
|
||||
'refunded_at',
|
||||
];
|
||||
|
||||
protected $appends = [
|
||||
'name',
|
||||
'description',
|
||||
@@ -59,17 +79,123 @@ class Ticket extends Model
|
||||
'source_variant_id' => 'integer',
|
||||
'source_purchase_item_id' => 'integer',
|
||||
'used_at' => 'datetime',
|
||||
'disabled_at' => 'datetime',
|
||||
'cancelled_at' => 'datetime',
|
||||
'refunded_at' => 'datetime',
|
||||
'scanner_user_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function statuses(): array
|
||||
{
|
||||
return array_keys(self::statusLabels());
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function statusLabels(): array
|
||||
{
|
||||
return [
|
||||
self::STATUS_ACTIVE => 'Activo',
|
||||
self::STATUS_USED => 'Usado',
|
||||
self::STATUS_EXPIRED => 'Vencido',
|
||||
self::STATUS_DISABLED => 'Inhabilitado',
|
||||
self::STATUS_CANCELLED => 'Cancelado',
|
||||
self::STATUS_REFUNDED => 'Reembolsado',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<array{value: string, label: string}> */
|
||||
public static function statusOptions(): array
|
||||
{
|
||||
return collect(self::statusLabels())
|
||||
->map(fn (string $label, string $status): array => [
|
||||
'value' => $status,
|
||||
'label' => $label,
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public static function statusLabel(string $status): string
|
||||
{
|
||||
return self::statusLabels()[$status] ?? $status;
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (self $ticket): void {
|
||||
$ticket->ensureTerminalStatusTransitionIsAllowed();
|
||||
});
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Tenant, $this> */
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
|
||||
}
|
||||
|
||||
public function allow_refund(): bool
|
||||
{
|
||||
return $this->tenant?->allow_refund() ?? false;
|
||||
}
|
||||
|
||||
public function allowRefund(): bool
|
||||
{
|
||||
return $this->allow_refund();
|
||||
}
|
||||
|
||||
public function getAllowRefundAttribute(): bool
|
||||
{
|
||||
return $this->allow_refund();
|
||||
}
|
||||
|
||||
public function is_active(): bool
|
||||
{
|
||||
return $this->status === self::STATUS_ACTIVE;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->is_active();
|
||||
}
|
||||
|
||||
public function getIsActiveAttribute(): bool
|
||||
{
|
||||
return $this->is_active();
|
||||
}
|
||||
|
||||
public function can_cancel(): bool
|
||||
{
|
||||
return $this->is_active();
|
||||
}
|
||||
|
||||
public function canCancel(): bool
|
||||
{
|
||||
return $this->can_cancel();
|
||||
}
|
||||
|
||||
public function getCanCancelAttribute(): bool
|
||||
{
|
||||
return $this->can_cancel();
|
||||
}
|
||||
|
||||
public function can_refund(): bool
|
||||
{
|
||||
return $this->is_active() && $this->allow_refund();
|
||||
}
|
||||
|
||||
public function canRefund(): bool
|
||||
{
|
||||
return $this->can_refund();
|
||||
}
|
||||
|
||||
public function getCanRefundAttribute(): bool
|
||||
{
|
||||
return $this->can_refund();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
@@ -94,6 +220,12 @@ class Ticket extends Model
|
||||
return $this->belongsTo(PurchaseItem::class, 'source_purchase_item_id');
|
||||
}
|
||||
|
||||
/** @return HasOne<TicketRefund, $this> */
|
||||
public function refund(): HasOne
|
||||
{
|
||||
return $this->hasOne(TicketRefund::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function sourceCatalogItem(): BelongsTo
|
||||
{
|
||||
@@ -108,7 +240,7 @@ class Ticket extends Model
|
||||
|
||||
public function isValid(): bool
|
||||
{
|
||||
if ($this->used_at !== null) {
|
||||
if ($this->hasTerminalStatus() || $this->used_at !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -122,7 +254,9 @@ class Ticket extends Model
|
||||
|
||||
public function getIsExpiredAttribute(): bool
|
||||
{
|
||||
return $this->used_at === null && $this->resolvedValidity()->isExpired();
|
||||
return ! $this->hasTerminalStatus()
|
||||
&& $this->used_at === null
|
||||
&& $this->resolvedValidity()->isExpired();
|
||||
}
|
||||
|
||||
public function getIsUsedAttribute(): bool
|
||||
@@ -132,6 +266,18 @@ class Ticket extends Model
|
||||
|
||||
public function getStatusAttribute(): string
|
||||
{
|
||||
if ($this->refunded_at !== null) {
|
||||
return self::STATUS_REFUNDED;
|
||||
}
|
||||
|
||||
if ($this->cancelled_at !== null) {
|
||||
return self::STATUS_CANCELLED;
|
||||
}
|
||||
|
||||
if ($this->disabled_at !== null) {
|
||||
return self::STATUS_DISABLED;
|
||||
}
|
||||
|
||||
if ($this->is_used) {
|
||||
return self::STATUS_USED;
|
||||
}
|
||||
@@ -143,6 +289,110 @@ class Ticket extends Model
|
||||
return self::STATUS_ACTIVE;
|
||||
}
|
||||
|
||||
public function getStatusLabelAttribute(): string
|
||||
{
|
||||
if ($this->status === self::STATUS_REFUNDED && $this->relationLoaded('refund')) {
|
||||
$refund = $this->getRelation('refund');
|
||||
|
||||
if ($refund instanceof TicketRefund) {
|
||||
return $refund->typeLabel();
|
||||
}
|
||||
}
|
||||
|
||||
return self::statusLabel($this->status);
|
||||
}
|
||||
|
||||
public function markAsDisabled(): void
|
||||
{
|
||||
$this->markAsTerminalStatus(self::STATUS_DISABLED);
|
||||
}
|
||||
|
||||
public function markAsCancelled(): void
|
||||
{
|
||||
$this->markAsTerminalStatus(self::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
public function markAsRefunded(): void
|
||||
{
|
||||
$this->markAsTerminalStatus(self::STATUS_REFUNDED);
|
||||
}
|
||||
|
||||
protected function valueChangeTenantCode(): string
|
||||
{
|
||||
return $this->tenant_code;
|
||||
}
|
||||
|
||||
private function hasTerminalStatus(): bool
|
||||
{
|
||||
return $this->terminalStatus() !== null;
|
||||
}
|
||||
|
||||
private function markAsTerminalStatus(string $status): void
|
||||
{
|
||||
$currentStatus = $this->terminalStatus();
|
||||
|
||||
if ($currentStatus === $status) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($currentStatus !== null) {
|
||||
$this->throwTerminalStatusTransitionException();
|
||||
}
|
||||
|
||||
$this->ensureTerminalStatusTransitionIsAllowed($status);
|
||||
|
||||
$this->{self::terminalStatusTimestampColumn($status)} = now();
|
||||
}
|
||||
|
||||
private function ensureTerminalStatusTransitionIsAllowed(?string $targetStatus = null): void
|
||||
{
|
||||
$currentStatus = $this->terminalStatusFromAttributes($this->getRawOriginal());
|
||||
$nextStatus = $targetStatus ?? $this->terminalStatus();
|
||||
|
||||
if ($currentStatus === null || $nextStatus === null || $currentStatus === $nextStatus) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->throwTerminalStatusTransitionException();
|
||||
}
|
||||
|
||||
private function throwTerminalStatusTransitionException(): never
|
||||
{
|
||||
throw ValidationException::withMessages([
|
||||
'status' => 'No se puede cambiar un ticket con estado terminal a otro estado terminal.',
|
||||
]);
|
||||
}
|
||||
|
||||
private function terminalStatus(): ?string
|
||||
{
|
||||
return $this->terminalStatusFromAttributes($this->getAttributes());
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $attributes */
|
||||
private function terminalStatusFromAttributes(array $attributes): ?string
|
||||
{
|
||||
foreach ([
|
||||
self::STATUS_REFUNDED,
|
||||
self::STATUS_CANCELLED,
|
||||
self::STATUS_DISABLED,
|
||||
] as $status) {
|
||||
if (($attributes[self::terminalStatusTimestampColumn($status)] ?? null) !== null) {
|
||||
return $status;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function terminalStatusTimestampColumn(string $status): string
|
||||
{
|
||||
return match ($status) {
|
||||
self::STATUS_DISABLED => 'disabled_at',
|
||||
self::STATUS_CANCELLED => 'cancelled_at',
|
||||
self::STATUS_REFUNDED => 'refunded_at',
|
||||
};
|
||||
}
|
||||
|
||||
public function getNameAttribute(): string
|
||||
{
|
||||
return app(TicketPresentationResolver::class)->name($this);
|
||||
|
||||
66
app/Domains/Ticket/Models/TicketRefund.php
Normal file
66
app/Domains/Ticket/Models/TicketRefund.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'ticket_id',
|
||||
'purchase_item_id',
|
||||
'created_by_user_id',
|
||||
'type',
|
||||
'amount',
|
||||
])]
|
||||
class TicketRefund extends Model
|
||||
{
|
||||
public const TYPE_PARTIAL = 'partial';
|
||||
|
||||
public const TYPE_TOTAL = 'total';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'ticket_id' => 'integer',
|
||||
'purchase_item_id' => 'integer',
|
||||
'created_by_user_id' => 'integer',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function types(): array
|
||||
{
|
||||
return [self::TYPE_PARTIAL, self::TYPE_TOTAL];
|
||||
}
|
||||
|
||||
public function typeLabel(): string
|
||||
{
|
||||
return match ($this->type) {
|
||||
self::TYPE_PARTIAL => 'Reembolso parcial',
|
||||
self::TYPE_TOTAL => 'Reembolso total',
|
||||
default => 'Reembolsado',
|
||||
};
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Ticket, $this> */
|
||||
public function ticket(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Ticket::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<PurchaseItem, $this> */
|
||||
public function purchaseItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PurchaseItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function createdBy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'created_by_user_id')->withTrashed();
|
||||
}
|
||||
}
|
||||
@@ -32,11 +32,7 @@ class AdminAppTicketIndexRequest extends FormRequest
|
||||
'status' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
Rule::in([
|
||||
Ticket::STATUS_ACTIVE,
|
||||
Ticket::STATUS_USED,
|
||||
Ticket::STATUS_EXPIRED,
|
||||
]),
|
||||
Rule::in(Ticket::statuses()),
|
||||
],
|
||||
'page' => ['sometimes', 'integer', 'min:1'],
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
|
||||
23
app/Domains/Ticket/Requests/AdminAppTicketRefundRequest.php
Normal file
23
app/Domains/Ticket/Requests/AdminAppTicketRefundRequest.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Requests;
|
||||
|
||||
use App\Domains\Ticket\Models\TicketRefund;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AdminAppTicketRefundRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<string|object>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'refund_type' => ['required', 'string', Rule::in(TicketRefund::types())],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -15,20 +15,24 @@ class AdminAppTicketCollection extends ResourceCollection
|
||||
|
||||
private readonly int $totalTickets;
|
||||
|
||||
private readonly string $refundedTotal;
|
||||
|
||||
public function __construct(AdminAppTicketResult $result)
|
||||
{
|
||||
parent::__construct($result->tickets);
|
||||
|
||||
$this->scannedTickets = $result->scannedTickets;
|
||||
$this->totalTickets = $result->totalTickets;
|
||||
$this->refundedTotal = $result->refundedTotal;
|
||||
}
|
||||
|
||||
/** @return array{scanned_tickets: int, total_tickets: int} */
|
||||
/** @return array{scanned_tickets: int, total_tickets: int, refunded_total: string} */
|
||||
public function with(Request $request): array
|
||||
{
|
||||
return [
|
||||
'scanned_tickets' => $this->scannedTickets,
|
||||
'total_tickets' => $this->totalTickets,
|
||||
'refunded_total' => $this->refundedTotal,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Resources\AdminApp;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @property-read array{
|
||||
* total: string|null,
|
||||
* partial: string|null,
|
||||
* } $resource
|
||||
*/
|
||||
class AdminAppTicketRefundCalculationResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array{total: string|null, partial: string|null}
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'total' => $this->resource['total'],
|
||||
'partial' => $this->resource['partial'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,17 @@ class AdminAppTicketResource extends TicketResource
|
||||
return [
|
||||
...parent::toArray($request),
|
||||
...$details,
|
||||
'allow_refund' => $this->resource->allow_refund(),
|
||||
'is_active' => $this->resource->is_active(),
|
||||
'can_cancel' => $this->resource->can_cancel(),
|
||||
'can_refund' => $this->resource->can_refund(),
|
||||
'refund' => $this->resource->refund === null ? null : [
|
||||
'type' => $this->resource->refund->type,
|
||||
'type_label' => $this->resource->refund->typeLabel(),
|
||||
'amount' => $this->resource->refund->amount,
|
||||
'created_at' => $this->resource->refund->created_at,
|
||||
'created_by' => $this->resource->refund->createdBy?->nombre_apellido,
|
||||
],
|
||||
'values' => $rowService->values($this->resource, $details),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -16,6 +16,14 @@ class TicketResource extends JsonResource
|
||||
'id' => $this->id,
|
||||
'tenant_code' => $this->tenant_code,
|
||||
'ticket' => $this->ticket,
|
||||
'status' => $this->status,
|
||||
'status_label' => $this->status_label,
|
||||
'refund' => $this->whenLoaded('refund', fn (): ?array => $this->refund === null ? null : [
|
||||
'type' => $this->refund->type,
|
||||
'type_label' => $this->refund->typeLabel(),
|
||||
'amount' => $this->refund->amount,
|
||||
'created_at' => $this->refund->created_at,
|
||||
]),
|
||||
'name' => $this->name,
|
||||
'description' => $this->description,
|
||||
'client' => $this->user?->nombre_apellido,
|
||||
|
||||
@@ -41,7 +41,9 @@ class AdminAppTicketExcelService
|
||||
$row = $index + 2;
|
||||
foreach ($columns as $columnIndex => $column) {
|
||||
$coordinate = Coordinate::stringFromColumnIndex($columnIndex + 1).$row;
|
||||
$value = $ticket[$column['key']] ?? null;
|
||||
$value = $column['type'] === 'status'
|
||||
? ($ticket['status_label'] ?? $ticket[$column['key']] ?? null)
|
||||
: ($ticket[$column['key']] ?? null);
|
||||
|
||||
if ($column['type'] === 'currency' && $value !== null) {
|
||||
$sheet->setCellValue($coordinate, (float) $value);
|
||||
|
||||
@@ -12,5 +12,6 @@ final readonly class AdminAppTicketResult
|
||||
public LengthAwarePaginator $tickets,
|
||||
public int $scannedTickets,
|
||||
public int $totalTickets,
|
||||
public string $refundedTotal,
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ class AdminAppTicketRowService
|
||||
public function details(Ticket $ticket): array
|
||||
{
|
||||
$purchaseItem = $ticket->sourcePurchaseItem;
|
||||
$refund = $ticket->refund;
|
||||
|
||||
return [
|
||||
'source_purchase_item_id' => $ticket->source_purchase_item_id,
|
||||
@@ -31,10 +32,13 @@ class AdminAppTicketRowService
|
||||
?? $ticket->sourceCatalogItem?->nombre
|
||||
?? $ticket->name,
|
||||
'amount' => $purchaseItem?->precio_unitario,
|
||||
'refund_type' => $refund?->type,
|
||||
'refund_type_label' => $refund?->typeLabel(),
|
||||
'client' => $purchaseItem?->purchase?->nombre_apellido ?? $ticket->user?->nombre_apellido,
|
||||
'status' => $ticket->status,
|
||||
'scanned_by' => $ticket->scannerUser?->nombre_apellido,
|
||||
'variant_properties' => $this->variantProperties($ticket),
|
||||
'allow_refund' => $ticket->allow_refund(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -55,6 +59,7 @@ class AdminAppTicketRowService
|
||||
'client' => $details['client'] ?? 'Sin nombre',
|
||||
'id' => $ticket->id,
|
||||
'status' => $details['status'],
|
||||
'status_label' => $ticket->status_label,
|
||||
'scanned_by' => $details['scanned_by'] ?? '-',
|
||||
];
|
||||
}
|
||||
@@ -78,7 +83,9 @@ class AdminAppTicketRowService
|
||||
return $rows->map(fn (array $row): array => collect($columns)
|
||||
->mapWithKeys(fn (array $column): array => [
|
||||
$column['key'] => $this->displayValue(
|
||||
$row[$column['key']] ?? null,
|
||||
$column['type'] === 'status'
|
||||
? ($row['status_label'] ?? $row[$column['key']] ?? null)
|
||||
: ($row[$column['key']] ?? null),
|
||||
$column['type'],
|
||||
$timeZone,
|
||||
),
|
||||
@@ -95,11 +102,7 @@ class AdminAppTicketRowService
|
||||
return match ($type) {
|
||||
'order_number' => '#'.$value,
|
||||
'currency' => '$'.number_format((float) $value, 2, ',', '.'),
|
||||
'status' => match ((string) $value) {
|
||||
Ticket::STATUS_USED => 'Usado',
|
||||
Ticket::STATUS_EXPIRED => 'Vencido',
|
||||
default => 'Activo',
|
||||
},
|
||||
'status' => Ticket::statusLabel((string) $value),
|
||||
default => (string) $value,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,26 +4,33 @@ namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Purchase\Services\PurchaseRefundSummaryService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\TicketRefund;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AdminAppTicketService
|
||||
{
|
||||
private const RELATIONS = [
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
'tenant',
|
||||
'user',
|
||||
'scannerUser',
|
||||
'sourceCatalogItem.category',
|
||||
'sourcePurchaseItem.purchase',
|
||||
'refund.createdBy',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly AdminAppTicketColumnService $columnService,
|
||||
private readonly AdminAppTicketRowService $rowService,
|
||||
private readonly PurchaseRefundSummaryService $refundSummaryService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -42,20 +49,30 @@ class AdminAppTicketService
|
||||
->get();
|
||||
$matchingTickets = $this->sortTickets($matchingTickets, $tenant, $filters);
|
||||
$tickets = $this->paginate($matchingTickets, $filters);
|
||||
$scannedTickets = $matchingTickets->whereNotNull('used_at')->count();
|
||||
$scannedTickets = $matchingTickets
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_USED)
|
||||
->count();
|
||||
$activeTickets = $matchingTickets
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||
->count();
|
||||
$totalTickets = $activeTickets + $scannedTickets;
|
||||
} else {
|
||||
$tickets = (clone $query)
|
||||
->with(self::RELATIONS)
|
||||
->when(! $databaseSorted, fn (Builder $query): Builder => $query->orderByDesc('id'))
|
||||
->paginateFromRequest()
|
||||
->withQueryString();
|
||||
$scannedTickets = $countQuery->whereNotNull('used_at')->count();
|
||||
|
||||
$counts = $this->calculateTicketCounts($countQuery);
|
||||
$scannedTickets = $counts['scanned'];
|
||||
$totalTickets = $counts['total'];
|
||||
}
|
||||
|
||||
return new AdminAppTicketResult(
|
||||
tickets: $tickets,
|
||||
scannedTickets: $scannedTickets,
|
||||
totalTickets: $tickets->total(),
|
||||
totalTickets: $totalTickets,
|
||||
refundedTotal: $this->refundSummaryService->totalForTenant($tenant),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -75,6 +92,172 @@ class AdminAppTicketService
|
||||
return $databaseSorted ? $tickets : $this->sortTickets($tickets, $tenant, $filters);
|
||||
}
|
||||
|
||||
public function cancel(Tenant $tenant, int $ticketId): Ticket
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $ticketId): Ticket {
|
||||
$ticket = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->lockForUpdate()
|
||||
->findOrFail($ticketId);
|
||||
|
||||
if (! $ticket->can_cancel()) {
|
||||
throw ValidationException::withMessages([
|
||||
'status' => 'El ticket debe estar activo para poder cancelarlo.',
|
||||
]);
|
||||
}
|
||||
|
||||
$ticket->markAsCancelled();
|
||||
$ticket->save();
|
||||
|
||||
return $ticket->refresh()->load(self::RELATIONS);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* total: string|null,
|
||||
* partial: string|null,
|
||||
* }
|
||||
*/
|
||||
public function calculateRefund(Tenant $tenant, int $ticketId): array
|
||||
{
|
||||
$ticket = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->findOrFail($ticketId);
|
||||
|
||||
if (! $ticket->can_refund()) {
|
||||
throw ValidationException::withMessages([
|
||||
'refund' => 'El reembolso no está disponible para este ticket.',
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseItem = PurchaseItem::query()
|
||||
->find($ticket->source_purchase_item_id);
|
||||
|
||||
if ($purchaseItem === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'ticket' => 'El ticket no tiene un ítem de compra asociado para reembolsar.',
|
||||
]);
|
||||
}
|
||||
|
||||
$unitPrice = (float) $purchaseItem->precio_unitario;
|
||||
$itemTotal = (float) $purchaseItem->total;
|
||||
$itemRefundedAmount = $this->refundedAmountForPurchaseItem($purchaseItem);
|
||||
$remainingItemAmount = max(0.0, round($itemTotal - $itemRefundedAmount, 2));
|
||||
|
||||
$total = null;
|
||||
if ($tenant->allow_refund() && $tenant->allow_ticket_total_refund && $unitPrice <= $remainingItemAmount) {
|
||||
$total = number_format($unitPrice, 2, '.', '');
|
||||
}
|
||||
|
||||
$partial = null;
|
||||
if ($tenant->allow_refund() && $tenant->allow_partial_refund()) {
|
||||
$partialAmount = $this->refundAmount($purchaseItem, $tenant, 'partial');
|
||||
if ($partialAmount <= $remainingItemAmount) {
|
||||
$partial = number_format($partialAmount, 2, '.', '');
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'total' => $total,
|
||||
'partial' => $partial,
|
||||
];
|
||||
}
|
||||
|
||||
public function refund(
|
||||
Tenant $tenant,
|
||||
int $ticketId,
|
||||
string $refundType,
|
||||
?User $createdBy = null,
|
||||
): Ticket {
|
||||
$this->ensureRefundIsAllowed($tenant, $refundType);
|
||||
|
||||
return DB::transaction(function () use ($tenant, $ticketId, $refundType, $createdBy): Ticket {
|
||||
$ticket = Ticket::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->lockForUpdate()
|
||||
->findOrFail($ticketId);
|
||||
|
||||
if (! $ticket->can_refund()) {
|
||||
if ($ticket->status !== Ticket::STATUS_ACTIVE) {
|
||||
throw ValidationException::withMessages([
|
||||
'status' => 'El ticket debe estar activo para poder reembolsarlo.',
|
||||
]);
|
||||
}
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'refund' => 'El reembolso no está disponible para este ticket.',
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseItem = PurchaseItem::query()
|
||||
->lockForUpdate()
|
||||
->find($ticket->source_purchase_item_id);
|
||||
|
||||
if ($purchaseItem === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'ticket' => 'El ticket no tiene un ítem de compra asociado para reembolsar.',
|
||||
]);
|
||||
}
|
||||
|
||||
$refundAmount = $this->refundAmount($purchaseItem, $tenant, $refundType);
|
||||
$refundedAmount = round(
|
||||
$this->refundedAmountForPurchaseItem($purchaseItem) + $refundAmount,
|
||||
2,
|
||||
);
|
||||
|
||||
if ($refundedAmount > (float) $purchaseItem->total) {
|
||||
throw ValidationException::withMessages([
|
||||
'refund_type' => 'El importe reembolsado no puede superar el total del ítem de compra.',
|
||||
]);
|
||||
}
|
||||
|
||||
$ticket->markAsRefunded();
|
||||
$ticket->save();
|
||||
|
||||
TicketRefund::query()->create([
|
||||
'ticket_id' => $ticket->id,
|
||||
'purchase_item_id' => $purchaseItem->id,
|
||||
'created_by_user_id' => $createdBy?->id,
|
||||
'type' => $refundType,
|
||||
'amount' => number_format($refundAmount, 2, '.', ''),
|
||||
]);
|
||||
|
||||
return $ticket->refresh()->load(self::RELATIONS);
|
||||
});
|
||||
}
|
||||
|
||||
private function refundedAmountForPurchaseItem(PurchaseItem $purchaseItem): float
|
||||
{
|
||||
return round((float) TicketRefund::query()
|
||||
->where('purchase_item_id', $purchaseItem->id)
|
||||
->sum('amount'), 2);
|
||||
}
|
||||
|
||||
private function ensureRefundIsAllowed(Tenant $tenant, string $refundType): void
|
||||
{
|
||||
$isAllowed = match ($refundType) {
|
||||
TicketRefund::TYPE_PARTIAL => $tenant->allow_refund() && $tenant->allow_partial_refund(),
|
||||
TicketRefund::TYPE_TOTAL => $tenant->allow_refund() && (bool) $tenant->allow_ticket_total_refund,
|
||||
};
|
||||
|
||||
if (! $isAllowed) {
|
||||
throw ValidationException::withMessages([
|
||||
'refund_type' => 'El tipo de reembolso solicitado no está habilitado para este tenant.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function refundAmount(PurchaseItem $purchaseItem, Tenant $tenant, string $refundType): float
|
||||
{
|
||||
$ticketAmount = (float) $purchaseItem->precio_unitario;
|
||||
|
||||
return match ($refundType) {
|
||||
TicketRefund::TYPE_PARTIAL => round($ticketAmount * (float) $tenant->ticket_partial_refund_percentage / 100, 2),
|
||||
TicketRefund::TYPE_TOTAL => $ticketAmount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{q?: string|null, category?: string|null, product?: string|null, type?: string|null, date?: string|null, size?: string|null, status?: string|null, page?: int, per_page?: int} $filters
|
||||
* @return Builder<Ticket>
|
||||
@@ -255,13 +438,41 @@ class AdminAppTicketService
|
||||
}
|
||||
|
||||
if ($status === Ticket::STATUS_USED) {
|
||||
$query->whereNotNull('used_at');
|
||||
$query
|
||||
->whereNotNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$timestampColumn = match ($status) {
|
||||
Ticket::STATUS_DISABLED => 'disabled_at',
|
||||
Ticket::STATUS_CANCELLED => 'cancelled_at',
|
||||
Ticket::STATUS_REFUNDED => 'refunded_at',
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($timestampColumn !== null) {
|
||||
$query->whereNotNull($timestampColumn);
|
||||
|
||||
if ($status === Ticket::STATUS_DISABLED) {
|
||||
$query->whereNull('cancelled_at')->whereNull('refunded_at');
|
||||
}
|
||||
|
||||
if ($status === Ticket::STATUS_CANCELLED) {
|
||||
$query->whereNull('refunded_at');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$matchingIds = (clone $query)
|
||||
->whereNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->with(TicketValidityResolver::RELATIONS)
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->status === $status)
|
||||
@@ -270,6 +481,35 @@ class AdminAppTicketService
|
||||
$query->whereIn('tickets.id', $matchingIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Ticket> $countQuery
|
||||
* @return array{scanned: int, total: int}
|
||||
*/
|
||||
private function calculateTicketCounts(Builder $countQuery): array
|
||||
{
|
||||
$scannedTickets = (clone $countQuery)
|
||||
->whereNotNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->count();
|
||||
|
||||
$activeTickets = (clone $countQuery)
|
||||
->whereNull('used_at')
|
||||
->whereNull('disabled_at')
|
||||
->whereNull('cancelled_at')
|
||||
->whereNull('refunded_at')
|
||||
->with(TicketValidityResolver::RELATIONS)
|
||||
->get()
|
||||
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
|
||||
->count();
|
||||
|
||||
return [
|
||||
'scanned' => $scannedTickets,
|
||||
'total' => $activeTickets + $scannedTickets,
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizedCategory(string $category): string
|
||||
{
|
||||
return mb_strtolower(trim($category));
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Services\EffectiveEventDateResolver;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
|
||||
class TicketPresentationResolver
|
||||
{
|
||||
public function __construct(private readonly EffectiveEventDateResolver $effectiveEventDateResolver) {}
|
||||
|
||||
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceCatalogItem',
|
||||
@@ -30,9 +34,15 @@ class TicketPresentationResolver
|
||||
}
|
||||
|
||||
$itemAttributes = $variant->catalogItem->itemAttributes;
|
||||
$eventDateLabels = $variant->selectedEventDates()
|
||||
->map(fn (EventDate $date): EventDate => $this->effectiveEventDateResolver->resolveLatest($date) ?? $date)
|
||||
->unique(fn (EventDate $date): int => $date->getKey())
|
||||
->map(fn (EventDate $date): string => $date->date->format('d/m/Y'))
|
||||
->implode(', ');
|
||||
|
||||
$properties = $variant->selectionOptions($itemAttributes)
|
||||
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
||||
$labels = collect(array_is_list($option) ? $option : [$option])
|
||||
->map(function (array $option, string $attributeCode) use ($itemAttributes, $eventDateLabels): ?string {
|
||||
$labels = $attributeCode === 'event_date' ? $eventDateLabels : collect(array_is_list($option) ? $option : [$option])
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->implode(', ');
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Models\VariantDefinition;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Event\Services\EffectiveEventDateResolver;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -17,6 +19,14 @@ use Illuminate\Support\Collection;
|
||||
*/
|
||||
class TicketValidityResolver
|
||||
{
|
||||
private readonly EffectiveEventDateResolver $effectiveEventDateResolver;
|
||||
|
||||
public function __construct(?EffectiveEventDateResolver $effectiveEventDateResolver = null)
|
||||
{
|
||||
$this->effectiveEventDateResolver = $effectiveEventDateResolver
|
||||
?? new EffectiveEventDateResolver;
|
||||
}
|
||||
|
||||
/** Relaciones necesarias para resolver tickets sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceVariant.eventDates.validityTime',
|
||||
@@ -56,7 +66,18 @@ class TicketValidityResolver
|
||||
]);
|
||||
|
||||
$dimensions = collect();
|
||||
$eventDates = $variant->selectedEventDates();
|
||||
$selectedEventDates = $variant->selectedEventDates();
|
||||
$eventDates = $selectedEventDates
|
||||
->map(fn (EventDate $eventDate): ?EventDate => $this->effectiveEventDateResolver->resolve($eventDate))
|
||||
->filter()
|
||||
->unique(fn (EventDate $eventDate): int => $eventDate->getKey() ?? spl_object_id($eventDate))
|
||||
->values();
|
||||
|
||||
if ($selectedEventDates->isNotEmpty() && $eventDates->isEmpty()) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
$eventDates->each->loadMissing('validityTime');
|
||||
|
||||
if ($eventDates->contains(fn ($eventDate): bool => $eventDate->validityTime === null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
|
||||
@@ -9,6 +9,18 @@ Route::prefix('v1/adminapp/tenant')
|
||||
Route::get('tickets', [TicketController::class, 'index'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.index');
|
||||
Route::post('tickets/{ticket}/cancel', [TicketController::class, 'cancel'])
|
||||
->whereNumber('ticket')
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.cancel');
|
||||
Route::get('tickets/{ticket}/refund', [TicketController::class, 'calculateRefund'])
|
||||
->whereNumber('ticket')
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.calculate-refund');
|
||||
Route::post('tickets/{ticket}/refund', [TicketController::class, 'refund'])
|
||||
->whereNumber('ticket')
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.refund');
|
||||
Route::get('tickets/pdf', [TicketController::class, 'downloadPdf'])
|
||||
->middleware('tenant.menu:adminapp.tickets')
|
||||
->name('adminapp.tickets.pdf');
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Domains\Event\Events\EventDateRescheduled;
|
||||
use App\Domains\Event\Events\EventDateSuspended;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Policies\IntegrationPolicy;
|
||||
use App\Domains\Notification\Events\PasswordResetRequested;
|
||||
use App\Domains\Notification\Events\UserRegistered;
|
||||
use App\Domains\Notification\Listeners\SendEventDateRescheduledEmails;
|
||||
use App\Domains\Notification\Listeners\SendEventDateSuspendedEmails;
|
||||
use App\Domains\Notification\Listeners\SendPasswordResetEmail;
|
||||
use App\Domains\Notification\Listeners\SendPurchaseConfirmedEmail;
|
||||
use App\Domains\Notification\Listeners\SendWelcomeEmail;
|
||||
@@ -40,6 +44,8 @@ class AppServiceProvider extends ServiceProvider
|
||||
);
|
||||
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
|
||||
Event::listen(PurchasePaid::class, SendPurchaseConfirmedEmail::class);
|
||||
Event::listen(EventDateRescheduled::class, SendEventDateRescheduledEmails::class);
|
||||
Event::listen(EventDateSuspended::class, SendEventDateSuspendedEmails::class);
|
||||
Event::listen(UserRegistered::class, SendWelcomeEmail::class);
|
||||
Event::listen(PasswordResetRequested::class, SendPasswordResetEmail::class);
|
||||
|
||||
|
||||
@@ -52,8 +52,7 @@
|
||||
"npx concurrently -c \"#93c5fd,#c4b5fd,#a7f3d0,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --queue=emails,default --tries=1 --timeout=0\" \"php artisan schedule:work\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,scheduler,logs,vite --kill-others"
|
||||
],
|
||||
"test": [
|
||||
"@php artisan config:clear --ansi @no_additional_args",
|
||||
"@php artisan test"
|
||||
"@php vendor/phpunit/phpunit/phpunit"
|
||||
],
|
||||
"post-autoload-dump": [
|
||||
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
|
||||
|
||||
@@ -16,6 +16,8 @@ return [
|
||||
|
||||
'default' => env('MAIL_MAILER', 'log'),
|
||||
|
||||
'delivery_lease_seconds' => (int) env('EMAIL_DELIVERY_LEASE_SECONDS', 300),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Mailer Configurations
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->boolean('allow_ticket_total_refund')->default(false);
|
||||
$table->boolean('allow_ticket_partial_refund')->default(false);
|
||||
$table->decimal('ticket_partial_refund_percentage', 4, 2)->default(0);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn([
|
||||
'allow_ticket_total_refund',
|
||||
'allow_ticket_partial_refund',
|
||||
'ticket_partial_refund_percentage',
|
||||
]);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->dateTime('disabled_at')->nullable()->after('used_at');
|
||||
$table->dateTime('cancelled_at')->nullable()->after('disabled_at');
|
||||
$table->dateTime('refunded_at')->nullable()->after('cancelled_at');
|
||||
});
|
||||
|
||||
Schema::table('compra_items', function (Blueprint $table): void {
|
||||
$table->decimal('refunded_amount', 10, 2)->default(0)->after('total');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table): void {
|
||||
$table->dropColumn('refunded_amount');
|
||||
});
|
||||
|
||||
Schema::table('tickets', function (Blueprint $table): void {
|
||||
$table->dropColumn([
|
||||
'disabled_at',
|
||||
'cancelled_at',
|
||||
'refunded_at',
|
||||
]);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('event_dates', function (Blueprint $table): void {
|
||||
$table->foreignId('rescheduled_to_event_date_id')
|
||||
->nullable()
|
||||
->after('validity_time_id')
|
||||
->constrained('event_dates')
|
||||
->restrictOnDelete();
|
||||
$table->dateTime('cancelled_at')
|
||||
->nullable()
|
||||
->after('rescheduled_to_event_date_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('event_dates', function (Blueprint $table): void {
|
||||
$table->dropConstrainedForeignId('rescheduled_to_event_date_id');
|
||||
$table->dropColumn('cancelled_at');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->boolean('allow_ticket_refund')
|
||||
->default(false)
|
||||
->after('scanner_category_validation_enabled');
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->where('allow_ticket_total_refund', true)
|
||||
->orWhere(function ($query): void {
|
||||
$query
|
||||
->where('allow_ticket_partial_refund', true)
|
||||
->where('ticket_partial_refund_percentage', '>', 0);
|
||||
})
|
||||
->update(['allow_ticket_refund' => true]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn('allow_ticket_refund');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('event_dates', function (Blueprint $table): void {
|
||||
$table->renameColumn('cancelled_at', 'suspended_at');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('event_dates', function (Blueprint $table): void {
|
||||
$table->renameColumn('suspended_at', 'cancelled_at');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('email_deliveries', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('idempotency_key')->unique();
|
||||
$table->string('email_type')->index();
|
||||
$table->string('tenant_code')->nullable()->index();
|
||||
$table->string('status')->index();
|
||||
$table->unsignedInteger('attempts')->default(0);
|
||||
$table->json('context')->nullable();
|
||||
$table->string('recipient_fingerprint', 64)->nullable();
|
||||
$table->uuid('claim_token')->nullable()->index();
|
||||
$table->timestamp('claimed_at')->nullable();
|
||||
$table->timestamp('lease_expires_at')->nullable()->index();
|
||||
$table->timestamp('sent_at')->nullable();
|
||||
$table->timestamp('failed_at')->nullable();
|
||||
$table->text('last_error')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('email_deliveries');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('ticket_refunds', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('ticket_id')->unique()->constrained('tickets')->cascadeOnDelete();
|
||||
$table->foreignId('purchase_item_id')->constrained('compra_items')->restrictOnDelete();
|
||||
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->string('type', 16);
|
||||
$table->decimal('amount', 10, 2);
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['purchase_item_id', 'type']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('ticket_refunds');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('event_date_reschedules', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->foreignId('source_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||
$table->foreignId('destination_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->date('previous_date');
|
||||
$table->date('new_date');
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->foreign('tenant_code')
|
||||
->references('codigo')
|
||||
->on('tenants')
|
||||
->cascadeOnUpdate()
|
||||
->cascadeOnDelete();
|
||||
$table->index(['tenant_code', 'created_at']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('event_date_reschedules');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$requiresForeignKeyRecreation = in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||
|
||||
Schema::table('variantes', function (Blueprint $table) use ($requiresForeignKeyRecreation): void {
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->dropForeign(['inventory_id']);
|
||||
}
|
||||
|
||||
$table->dropUnique('variantes_inventory_id_unique');
|
||||
$table->index('inventory_id');
|
||||
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->foreign('inventory_id')->references('id')->on('inventories')->restrictOnDelete();
|
||||
}
|
||||
|
||||
$table->foreignId('replaced_by_variant_id')
|
||||
->nullable()
|
||||
->after('inventory_id')
|
||||
->constrained('variantes')
|
||||
->nullOnDelete();
|
||||
$table->timestamp('sales_disabled_at')
|
||||
->nullable()
|
||||
->after('replaced_by_variant_id');
|
||||
$table->index(
|
||||
['sales_disabled_at', 'replaced_by_variant_id'],
|
||||
'variants_sellable_index',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$requiresForeignKeyRecreation = in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||
|
||||
DB::table('variantes')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->groupBy('inventory_id')
|
||||
->each(function ($variants): void {
|
||||
$variants->skip(1)->each(function (object $variant): void {
|
||||
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->first();
|
||||
|
||||
if ($inventory === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$inventoryId = DB::table('inventories')->insertGetId([
|
||||
'sold_units' => $inventory->sold_units,
|
||||
'reserved_stock' => 0,
|
||||
'real_stock' => $inventory->real_stock,
|
||||
]);
|
||||
|
||||
DB::table('variantes')->where('id', $variant->id)->update([
|
||||
'inventory_id' => $inventoryId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Schema::table('variantes', function (Blueprint $table) use ($requiresForeignKeyRecreation): void {
|
||||
$table->dropIndex('variants_sellable_index');
|
||||
$table->dropConstrainedForeignId('replaced_by_variant_id');
|
||||
$table->dropColumn('sales_disabled_at');
|
||||
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->dropForeign(['inventory_id']);
|
||||
}
|
||||
|
||||
$table->dropIndex(['inventory_id']);
|
||||
$table->unique('inventory_id');
|
||||
|
||||
if ($requiresForeignKeyRecreation) {
|
||||
$table->foreign('inventory_id')->references('id')->on('inventories')->restrictOnDelete();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$this->createEventDateChangesTable();
|
||||
|
||||
DB::table('event_date_changes')->insertUsing(
|
||||
[
|
||||
'tenant_code',
|
||||
'change_type',
|
||||
'source_event_date_id',
|
||||
'destination_event_date_id',
|
||||
'created_by_user_id',
|
||||
'previous_date',
|
||||
'new_date',
|
||||
'created_at',
|
||||
],
|
||||
DB::table('event_date_reschedules')->select([
|
||||
'tenant_code',
|
||||
DB::raw("'rescheduled'"),
|
||||
'source_event_date_id',
|
||||
'destination_event_date_id',
|
||||
'created_by_user_id',
|
||||
'previous_date',
|
||||
'new_date',
|
||||
'created_at',
|
||||
]),
|
||||
);
|
||||
|
||||
Schema::drop('event_date_reschedules');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$this->createEventDateReschedulesTable();
|
||||
|
||||
DB::table('event_date_reschedules')->insertUsing(
|
||||
[
|
||||
'tenant_code',
|
||||
'source_event_date_id',
|
||||
'destination_event_date_id',
|
||||
'created_by_user_id',
|
||||
'previous_date',
|
||||
'new_date',
|
||||
'created_at',
|
||||
],
|
||||
DB::table('event_date_changes')
|
||||
->where('change_type', 'rescheduled')
|
||||
->whereNotNull('destination_event_date_id')
|
||||
->whereNotNull('new_date')
|
||||
->select([
|
||||
'tenant_code',
|
||||
'source_event_date_id',
|
||||
'destination_event_date_id',
|
||||
'created_by_user_id',
|
||||
'previous_date',
|
||||
'new_date',
|
||||
'created_at',
|
||||
]),
|
||||
);
|
||||
|
||||
Schema::drop('event_date_changes');
|
||||
}
|
||||
|
||||
private function createEventDateChangesTable(): void
|
||||
{
|
||||
Schema::create('event_date_changes', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->string('change_type', 16);
|
||||
$table->foreignId('source_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||
$table->foreignId('destination_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->date('previous_date');
|
||||
$table->date('new_date')->nullable();
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->foreign('tenant_code')
|
||||
->references('codigo')
|
||||
->on('tenants')
|
||||
->cascadeOnUpdate()
|
||||
->cascadeOnDelete();
|
||||
$table->index(['tenant_code', 'created_at']);
|
||||
$table->index(['source_event_date_id', 'change_type']);
|
||||
});
|
||||
}
|
||||
|
||||
private function createEventDateReschedulesTable(): void
|
||||
{
|
||||
Schema::create('event_date_reschedules', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->foreignId('source_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||
$table->foreignId('destination_event_date_id')->nullable()->constrained('event_dates')->nullOnDelete();
|
||||
$table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->date('previous_date');
|
||||
$table->date('new_date');
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->foreign('tenant_code')
|
||||
->references('codigo')
|
||||
->on('tenants')
|
||||
->cascadeOnUpdate()
|
||||
->cascadeOnDelete();
|
||||
$table->index(['tenant_code', 'created_at']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$this->backfillLegacyRefunds();
|
||||
|
||||
$mismatchedItem = DB::table('compra_items as purchase_items')
|
||||
->leftJoin('ticket_refunds as refunds', 'refunds.purchase_item_id', '=', 'purchase_items.id')
|
||||
->where('purchase_items.refunded_amount', '>', 0)
|
||||
->groupBy('purchase_items.id', 'purchase_items.refunded_amount')
|
||||
->selectRaw(
|
||||
'purchase_items.id, purchase_items.refunded_amount, COALESCE(SUM(refunds.amount), 0) as refund_total'
|
||||
)
|
||||
->get()
|
||||
->first(fn (object $item): bool => abs(
|
||||
(float) $item->refunded_amount - (float) $item->refund_total
|
||||
) > 0.005);
|
||||
|
||||
if ($mismatchedItem !== null) {
|
||||
throw new RuntimeException(
|
||||
"No se puede eliminar compra_items.refunded_amount: el ítem {$mismatchedItem->id} "
|
||||
.'contiene un importe histórico que no se pudo respaldar con ticket_refunds.'
|
||||
);
|
||||
}
|
||||
|
||||
Schema::table('compra_items', function (Blueprint $table): void {
|
||||
$table->dropColumn('refunded_amount');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table): void {
|
||||
$table->decimal('refunded_amount', 10, 2)->default(0)->after('total');
|
||||
});
|
||||
|
||||
DB::table('ticket_refunds')
|
||||
->selectRaw('purchase_item_id, SUM(amount) as refund_total')
|
||||
->groupBy('purchase_item_id')
|
||||
->orderBy('purchase_item_id')
|
||||
->eachById(function (object $refund): void {
|
||||
DB::table('compra_items')
|
||||
->where('id', $refund->purchase_item_id)
|
||||
->update(['refunded_amount' => $refund->refund_total]);
|
||||
}, column: 'purchase_item_id');
|
||||
}
|
||||
|
||||
private function backfillLegacyRefunds(): void
|
||||
{
|
||||
$items = DB::table('compra_items as purchase_items')
|
||||
->leftJoin('ticket_refunds as refunds', 'refunds.purchase_item_id', '=', 'purchase_items.id')
|
||||
->where('purchase_items.refunded_amount', '>', 0)
|
||||
->groupBy(
|
||||
'purchase_items.id',
|
||||
'purchase_items.refunded_amount',
|
||||
'purchase_items.precio_unitario',
|
||||
)
|
||||
->selectRaw(
|
||||
'purchase_items.id, purchase_items.refunded_amount, purchase_items.precio_unitario, '
|
||||
.'COALESCE(SUM(refunds.amount), 0) as refund_total'
|
||||
)
|
||||
->orderBy('purchase_items.id')
|
||||
->get();
|
||||
|
||||
foreach ($items as $item) {
|
||||
$legacyAmountInCents = (int) round(
|
||||
((float) $item->refunded_amount - (float) $item->refund_total) * 100
|
||||
);
|
||||
|
||||
if ($legacyAmountInCents <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tickets = DB::table('tickets as tickets')
|
||||
->leftJoin('ticket_refunds as refunds', 'refunds.ticket_id', '=', 'tickets.id')
|
||||
->where('tickets.source_purchase_item_id', $item->id)
|
||||
->whereNotNull('tickets.refunded_at')
|
||||
->whereNull('refunds.id')
|
||||
->orderBy('tickets.refunded_at')
|
||||
->orderBy('tickets.id')
|
||||
->get(['tickets.id', 'tickets.refunded_at']);
|
||||
|
||||
$ticketCount = $tickets->count();
|
||||
$unitPriceInCents = (int) round((float) $item->precio_unitario * 100);
|
||||
|
||||
if ($ticketCount === 0
|
||||
|| $unitPriceInCents <= 0
|
||||
|| $legacyAmountInCents > $ticketCount * $unitPriceInCents) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$baseAmountInCents = intdiv($legacyAmountInCents, $ticketCount);
|
||||
$remainderInCents = $legacyAmountInCents % $ticketCount;
|
||||
|
||||
if ($baseAmountInCents === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$refunds = $tickets->values()->map(function (object $ticket, int $index) use (
|
||||
$item,
|
||||
$baseAmountInCents,
|
||||
$remainderInCents,
|
||||
$unitPriceInCents,
|
||||
): array {
|
||||
$amountInCents = $baseAmountInCents + ($index < $remainderInCents ? 1 : 0);
|
||||
|
||||
return [
|
||||
'ticket_id' => $ticket->id,
|
||||
'purchase_item_id' => $item->id,
|
||||
'created_by_user_id' => null,
|
||||
'type' => $amountInCents === $unitPriceInCents ? 'total' : 'partial',
|
||||
'amount' => number_format($amountInCents / 100, 2, '.', ''),
|
||||
'created_at' => $ticket->refunded_at,
|
||||
'updated_at' => $ticket->refunded_at,
|
||||
];
|
||||
})->all();
|
||||
|
||||
DB::table('ticket_refunds')->insert($refunds);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -34,7 +34,10 @@ return [
|
||||
'max_quantity' => 'You can add a maximum of :max.',
|
||||
'bundle_variant_forbidden' => 'A bundle cannot have a variant.',
|
||||
'empty_bundle' => 'The bundle has no components.',
|
||||
'bundle_component_unavailable' => 'The bundle contains a variant that is no longer available for sale.',
|
||||
'variant_required' => 'You must select a variant for this item.',
|
||||
'variant_unavailable' => 'The selected variant was replaced or is no longer available for sale.',
|
||||
'cart_variant_unavailable' => 'The cart contains a replaced variant or one that is no longer available for sale.',
|
||||
'reservation_expired' => 'The stock reservation has expired. Use the active cart to continue.',
|
||||
],
|
||||
'purchase' => [
|
||||
|
||||
@@ -34,7 +34,10 @@ return [
|
||||
'max_quantity' => 'El máximo que se puede agregar es :max.',
|
||||
'bundle_variant_forbidden' => 'Un bundle no admite una variante.',
|
||||
'empty_bundle' => 'El bundle no tiene componentes.',
|
||||
'bundle_component_unavailable' => 'El bundle contiene una variante que ya no está disponible para la venta.',
|
||||
'variant_required' => 'Debe seleccionar una variante para este ítem.',
|
||||
'variant_unavailable' => 'La variante seleccionada fue reemplazada o ya no está disponible para la venta.',
|
||||
'cart_variant_unavailable' => 'El carrito contiene una variante reemplazada o que ya no está disponible para la venta.',
|
||||
'reservation_expired' => 'La reserva de stock venció. Usá el carrito activo para continuar.',
|
||||
],
|
||||
'purchase' => [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
bootstrap="tests/bootstrap.php"
|
||||
colors="true"
|
||||
>
|
||||
<testsuites>
|
||||
@@ -19,7 +19,9 @@
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing" force="true"/>
|
||||
<env name="DB_DATABASE" value="shopit_test" force="true"/>
|
||||
<env name="DB_CONNECTION" value="sqlite" force="true"/>
|
||||
<env name="DB_DATABASE" value=":memory:" force="true"/>
|
||||
<env name="DB_URL" value="null" force="true"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||
<env name="APP_CONFIG_CACHE" value="bootstrap/cache/phpunit-config.php"/>
|
||||
<env name="APP_EVENTS_CACHE" value="bootstrap/cache/phpunit-events.php"/>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<h1 style="margin: 0 0 20px;">Tu evento fue reprogramado</h1>
|
||||
<p>Te informamos que la fecha de tu evento cambió.</p>
|
||||
<p>
|
||||
<strong>Fecha anterior:</strong> {{ $previousDate }}<br>
|
||||
<strong>Nueva fecha:</strong> {{ $newDate }}
|
||||
</p>
|
||||
<p>Tus tickets continúan siendo válidos para la nueva fecha.</p>
|
||||
<p><strong>Tickets afectados</strong></p>
|
||||
<ul>
|
||||
@foreach ($tickets as $ticket)
|
||||
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
<p style="color: #64748b; font-size: 13px;">Compra #{{ $purchase->id }}</p>
|
||||
@@ -0,0 +1,23 @@
|
||||
<h1 style="margin: 0 0 20px;">Actualización sobre tu evento</h1>
|
||||
<p>La fecha <strong>{{ $date }}</strong> fue suspendida.</p>
|
||||
|
||||
@if ($disabledTickets->isNotEmpty())
|
||||
<p>Los siguientes tickets quedaron inhabilitados porque no tienen otra fecha disponible:</p>
|
||||
<ul>
|
||||
@foreach ($disabledTickets as $ticket)
|
||||
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
<p>Para conocer las alternativas o condiciones de devolución, comunicate con la organización.</p>
|
||||
@endif
|
||||
|
||||
@if ($activeTickets->isNotEmpty())
|
||||
<p>Estos tickets conservan otras fechas disponibles:</p>
|
||||
<ul>
|
||||
@foreach ($activeTickets as $ticket)
|
||||
<li>{{ $ticket->name }} · #{{ $ticket->id }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
|
||||
<p style="color: #64748b; font-size: 13px;">Compra #{{ $purchase->id }}</p>
|
||||
@@ -220,6 +220,18 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
'time_start' => '10:00',
|
||||
'time_end' => '19:00',
|
||||
]);
|
||||
$rescheduledEventDate = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-08',
|
||||
'time_start' => '10:00',
|
||||
'time_end' => '19:00',
|
||||
'rescheduled_to_event_date_id' => $unusedEventDate->id,
|
||||
]);
|
||||
$suspendedEventDate = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-11',
|
||||
'time_start' => '10:00',
|
||||
'time_end' => '19:00',
|
||||
'suspended_at' => now(),
|
||||
]);
|
||||
$item = $this->createItem($tenant, 'Entry');
|
||||
$attribute = Attribute::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
@@ -245,6 +257,14 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
->assertJsonPath('data.attributes.0.options.0.validity_time.type', 'fixed_window')
|
||||
->assertJsonPath('data.attributes.0.options.1.id', $unusedEventDate->id)
|
||||
->assertJsonPath('data.attributes.0.options.1.value', (string) $unusedEventDate->id)
|
||||
->assertJsonMissing([
|
||||
'id' => $rescheduledEventDate->id,
|
||||
'value' => (string) $rescheduledEventDate->id,
|
||||
])
|
||||
->assertJsonMissing([
|
||||
'id' => $suspendedEventDate->id,
|
||||
'value' => (string) $suspendedEventDate->id,
|
||||
])
|
||||
->assertJsonPath('data.variants.0.values.event_date.value', (string) $eventDate->id)
|
||||
->assertJsonPath(
|
||||
'data.variants.0.values.event_date.label',
|
||||
|
||||
@@ -200,10 +200,12 @@ class CatalogSchemaTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_variants_can_override_catalog_item_use_dates(): void
|
||||
public function test_variants_support_event_dates_and_commercial_replacements(): void
|
||||
{
|
||||
$this->assertTrue(Schema::hasColumns('variantes', [
|
||||
'event_date_id',
|
||||
'replaced_by_variant_id',
|
||||
'sales_disabled_at',
|
||||
]));
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,22 @@ use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Event\Events\EventDateRescheduled;
|
||||
use App\Domains\Event\Events\EventDateSuspended;
|
||||
use App\Domains\Purchase\Services\Checkout\CatalogSelectionResolver;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Database\Seeders\SocialMediaSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -34,9 +44,10 @@ class AdminAppEventControllerTest extends TestCase
|
||||
{
|
||||
$this->getJson('/api/v1/adminapp/tenant/event')->assertUnauthorized();
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', $this->eventPayload())->assertUnauthorized();
|
||||
$this->postJson('/api/v1/adminapp/tenant/event-dates', $this->datePayload())->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_an_adminapp_user_can_create_the_active_event_and_contact_information(): void
|
||||
public function test_an_adminapp_user_can_update_event_and_contact_information_without_synchronizing_dates(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
@@ -45,10 +56,11 @@ class AdminAppEventControllerTest extends TestCase
|
||||
->assertOk()
|
||||
->assertJsonPath('data.title', 'Festival Acme')
|
||||
->assertJsonPath('data.location', 'Predio Ferial, Rosario')
|
||||
->assertJsonPath('data.dates.0.date', '2026-10-09')
|
||||
->assertJsonPath('data.dates.0.validity_time.type', 'fixed_window')
|
||||
->assertJsonPath('data.dates.0.start_time', '09:00')
|
||||
->assertJsonPath('data.dates.0.end_time', '18:30')
|
||||
->assertJsonPath('data.allow_ticket_refund', true)
|
||||
->assertJsonPath('data.allow_ticket_total_refund', true)
|
||||
->assertJsonPath('data.allow_ticket_partial_refund', true)
|
||||
->assertJsonPath('data.ticket_partial_refund_percentage', '25.50')
|
||||
->assertJsonCount(0, 'data.dates')
|
||||
->assertJsonPath('data.contact.whatsapp_url', 'https://wa.me/5493415550101')
|
||||
->assertJsonPath('data.contact.instagram_url', 'https://instagram.com/acme')
|
||||
->assertJsonPath('data.contact.facebook_url', null);
|
||||
@@ -58,25 +70,13 @@ class AdminAppEventControllerTest extends TestCase
|
||||
'id' => $tenant->id,
|
||||
'event_title' => 'Festival Acme',
|
||||
'event_location' => 'Predio Ferial, Rosario',
|
||||
'event_date_text' => '9 de Octubre 2026',
|
||||
'event_date_text' => null,
|
||||
'allow_ticket_refund' => true,
|
||||
'allow_ticket_total_refund' => true,
|
||||
'allow_ticket_partial_refund' => true,
|
||||
'ticket_partial_refund_percentage' => 25.50,
|
||||
]);
|
||||
$this->assertDatabaseHas('event_dates', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'date' => '2026-10-09',
|
||||
'time_start' => '09:00:00',
|
||||
'time_end' => '18:30:00',
|
||||
]);
|
||||
$eventDate = $tenant->eventDates()->with('validityTime')->sole();
|
||||
$this->assertSame($eventDate->validity_time_id, $response->json('data.dates.0.validity_time_id'));
|
||||
$this->assertSame(ValidityTimeType::FixedWindow, $eventDate->validityTime->type);
|
||||
$this->assertSame(
|
||||
'2026-10-09 09:00:00',
|
||||
$eventDate->validityTime->fixed_starts_at->format('Y-m-d H:i:s'),
|
||||
);
|
||||
$this->assertSame(
|
||||
'2026-10-09 18:30:00',
|
||||
$eventDate->validityTime->fixed_expires_at->format('Y-m-d H:i:s'),
|
||||
);
|
||||
$this->assertDatabaseCount('event_dates', 0);
|
||||
$this->assertDatabaseHas('tenant_social_media', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'social_media_code' => 'whatsapp',
|
||||
@@ -84,6 +84,56 @@ class AdminAppEventControllerTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_disabling_refunds_preserves_the_configured_types_and_percentage(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$tenant->update([
|
||||
'allow_ticket_refund' => true,
|
||||
'allow_ticket_total_refund' => true,
|
||||
'allow_ticket_partial_refund' => true,
|
||||
'ticket_partial_refund_percentage' => 35.50,
|
||||
]);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$payload = $this->eventPayload();
|
||||
$payload['allow_ticket_refund'] = false;
|
||||
$payload['ticket_partial_refund_percentage'] = 35.50;
|
||||
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
|
||||
->assertOk()
|
||||
->assertJsonPath('data.allow_ticket_refund', false)
|
||||
->assertJsonPath('data.allow_ticket_total_refund', true)
|
||||
->assertJsonPath('data.allow_ticket_partial_refund', true)
|
||||
->assertJsonPath('data.ticket_partial_refund_percentage', '35.50');
|
||||
|
||||
$tenant->refresh();
|
||||
$this->assertFalse($tenant->allow_refund());
|
||||
$this->assertTrue($tenant->allow_ticket_total_refund);
|
||||
$this->assertTrue($tenant->allow_ticket_partial_refund);
|
||||
$this->assertSame('35.50', $tenant->ticket_partial_refund_percentage);
|
||||
}
|
||||
|
||||
public function test_enabled_refunds_require_a_type_and_a_valid_partial_percentage(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$payload = $this->eventPayload();
|
||||
$payload['allow_ticket_total_refund'] = false;
|
||||
$payload['allow_ticket_partial_refund'] = false;
|
||||
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('allow_ticket_refund');
|
||||
|
||||
$payload['allow_ticket_partial_refund'] = true;
|
||||
$payload['ticket_partial_refund_percentage'] = 0;
|
||||
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('ticket_partial_refund_percentage');
|
||||
}
|
||||
|
||||
public function test_an_adminapp_user_can_read_only_its_tenant_active_event(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
@@ -109,7 +159,7 @@ class AdminAppEventControllerTest extends TestCase
|
||||
->assertJsonCount(0, 'data.dates');
|
||||
}
|
||||
|
||||
public function test_updating_reuses_the_active_event_and_synchronizes_dates_and_contact(): void
|
||||
public function test_updating_event_does_not_change_or_delete_existing_dates(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$eventTenant = $this->createActiveEvent($tenant, 'Old Event');
|
||||
@@ -124,7 +174,6 @@ class AdminAppEventControllerTest extends TestCase
|
||||
'time_end' => '12:00',
|
||||
]);
|
||||
$firstValidityTimeId = $firstDate->validity_time_id;
|
||||
$removedValidityTimeId = $removedDate->validity_time_id;
|
||||
$tenant->socialMedia()->attach('facebook', [
|
||||
'url' => 'https://facebook.com/old',
|
||||
'orden' => 2,
|
||||
@@ -136,12 +185,6 @@ class AdminAppEventControllerTest extends TestCase
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$payload = $this->eventPayload();
|
||||
$payload['dates'] = [[
|
||||
'date' => '2026-11-15',
|
||||
'start_time' => '10:00',
|
||||
'end_time' => '20:00',
|
||||
]];
|
||||
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', $payload)
|
||||
->assertOk()
|
||||
->assertJsonPath('data.id', $tenant->id)
|
||||
@@ -151,17 +194,16 @@ class AdminAppEventControllerTest extends TestCase
|
||||
$this->assertDatabaseHas('event_dates', [
|
||||
'id' => $firstDate->id,
|
||||
'validity_time_id' => $firstValidityTimeId,
|
||||
'date' => '2026-11-15',
|
||||
'date' => '2026-10-01',
|
||||
]);
|
||||
$this->assertDatabaseHas('validity_times', [
|
||||
'id' => $firstValidityTimeId,
|
||||
'type' => ValidityTimeType::FixedWindow->value,
|
||||
'fixed_starts_at' => '2026-11-15 10:00:00',
|
||||
'fixed_expires_at' => '2026-11-15 20:00:00',
|
||||
'fixed_starts_at' => '2026-10-01 08:00:00',
|
||||
'fixed_expires_at' => '2026-10-01 12:00:00',
|
||||
]);
|
||||
$this->assertDatabaseMissing('event_dates', ['id' => $removedDate->id]);
|
||||
$this->assertDatabaseMissing('validity_times', ['id' => $removedValidityTimeId]);
|
||||
$this->assertSame('15 de Noviembre 2026', $tenant->fresh()->event_date_text);
|
||||
$this->assertDatabaseHas('event_dates', ['id' => $removedDate->id]);
|
||||
$this->assertSame('1 y 2 de Octubre 2026', $tenant->fresh()->event_date_text);
|
||||
$this->assertDatabaseMissing('tenant_social_media', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'social_media_code' => 'facebook',
|
||||
@@ -173,20 +215,17 @@ class AdminAppEventControllerTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_updating_event_dates_recalculates_the_tenant_date_text(): void
|
||||
public function test_dates_are_created_independently_and_recalculate_the_tenant_date_text(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
$payload = $this->eventPayload();
|
||||
$payload['dates'] = collect([9, 10, 11, 12])
|
||||
->map(fn (int $day): array => [
|
||||
foreach ([9, 10, 11, 12] as $day) {
|
||||
$this->postJson('/api/v1/adminapp/tenant/event-dates', [
|
||||
'date' => sprintf('2026-10-%02d', $day),
|
||||
'start_time' => '09:00',
|
||||
'end_time' => '18:30',
|
||||
])
|
||||
->all();
|
||||
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', $payload)->assertOk();
|
||||
])->assertCreated()->assertJsonPath('data.status', 'scheduled');
|
||||
}
|
||||
|
||||
$this->assertSame(
|
||||
'9, 10, 11 y 12 de Octubre 2026',
|
||||
@@ -194,7 +233,289 @@ class AdminAppEventControllerTest extends TestCase
|
||||
);
|
||||
}
|
||||
|
||||
public function test_update_validates_event_dates_and_contact_urls(): void
|
||||
public function test_rescheduling_reuses_an_existing_date_and_tickets_resolve_its_validity(): void
|
||||
{
|
||||
Event::fake([EventDateRescheduled::class]);
|
||||
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||
$admin = $this->createAdminAppUser($tenant);
|
||||
$original = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-09',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$destination = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-20',
|
||||
'time_start' => '11:00',
|
||||
'time_end' => '20:00',
|
||||
]);
|
||||
$variant = $this->createVariant($tenant, $original->id);
|
||||
$variant->inventory()->update(['real_stock' => 5]);
|
||||
$ticket = $this->createTicket($tenant, $admin, $variant);
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$original->id}/reschedule", [
|
||||
'date' => '2027-10-20',
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', 'rescheduled')
|
||||
->assertJsonPath('data.rescheduled_to_event_date_id', $destination->id);
|
||||
|
||||
Event::assertDispatched(EventDateRescheduled::class, function (EventDateRescheduled $event) use ($tenant, $original, $destination): bool {
|
||||
return $event->tenantCode === $tenant->codigo
|
||||
&& $event->sourceEventDateId === $original->id
|
||||
&& $event->destinationEventDateId === $destination->id
|
||||
&& $event->previousDate === '09/10/2027'
|
||||
&& $event->newDate === '20/10/2027'
|
||||
&& $event->purchaseTickets === [];
|
||||
});
|
||||
|
||||
$this->assertDatabaseCount('event_dates', 2);
|
||||
$this->assertDatabaseHas('event_date_changes', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'change_type' => 'rescheduled',
|
||||
'source_event_date_id' => $original->id,
|
||||
'destination_event_date_id' => $destination->id,
|
||||
'created_by_user_id' => $admin->id,
|
||||
'previous_date' => '2027-10-09',
|
||||
'new_date' => '2027-10-20',
|
||||
]);
|
||||
$variant->refresh();
|
||||
$replacement = $variant->replacement()->firstOrFail();
|
||||
$this->assertSame($original->id, $variant->event_date_id);
|
||||
$this->assertSame($destination->id, $replacement->event_date_id);
|
||||
$this->assertSame($variant->inventory_id, $replacement->inventory_id);
|
||||
$this->assertNotNull($variant->sales_disabled_at);
|
||||
$this->assertSame($replacement->id, $variant->replaced_by_variant_id);
|
||||
$this->assertSame(
|
||||
[$replacement->id],
|
||||
$variant->catalogItem->fresh(['variants.inventory'])->visibleVariants()->modelKeys(),
|
||||
);
|
||||
$this->assertSame($variant->id, $ticket->fresh()->source_variant_id);
|
||||
|
||||
try {
|
||||
app(CatalogSelectionResolver::class)->resolve(
|
||||
$tenant,
|
||||
$variant->catalog_item_id,
|
||||
$variant->id,
|
||||
'direct_items.0',
|
||||
);
|
||||
$this->fail('The historical variant should not be sellable.');
|
||||
} catch (ValidationException $exception) {
|
||||
$this->assertArrayHasKey('direct_items.0.variant_id', $exception->errors());
|
||||
}
|
||||
|
||||
$this->assertSame('20 de Octubre 2027', $tenant->fresh()->event_date_text);
|
||||
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data.event.dates')
|
||||
->assertJsonPath('data.event.dates.0.id', $destination->id)
|
||||
->assertJsonCount(1, 'data.event.date_changes')
|
||||
->assertJsonPath('data.event.date_changes.0.type', 'rescheduled')
|
||||
->assertJsonPath('data.event.date_changes.0.source_event_date_id', $original->id)
|
||||
->assertJsonPath('data.event.date_changes.0.destination_event_date_id', $destination->id)
|
||||
->assertJsonPath('data.event.date_changes.0.previous_date', '2027-10-09')
|
||||
->assertJsonPath('data.event.date_changes.0.new_date', '2027-10-20')
|
||||
->assertJsonPath('data.event.date_changes.0.occurred_at', fn ($value) => is_string($value))
|
||||
->assertJsonMissingPath('data.event.date_changes.0.created_by_user_id')
|
||||
->assertJsonCount(1, 'data.event.date_notices')
|
||||
->assertJsonPath('data.event.date_notices.0.type', 'rescheduled')
|
||||
->assertJsonPath('data.event.date_notices.0.title', 'FECHA REPROGRAMADA!')
|
||||
->assertJsonPath('data.event.date_notices.0.message.0.text', 'La fecha del ')
|
||||
->assertJsonPath('data.event.date_notices.0.message.1.text', '09 de Octubre de 2027')
|
||||
->assertJsonPath('data.event.date_notices.0.message.1.bold', true)
|
||||
->assertJsonPath('data.event.date_notices.0.message.3.text', '20 de Octubre de 2027')
|
||||
->assertJsonPath('data.event_date_text', '20 de Octubre 2027');
|
||||
$this->assertSame(
|
||||
'2027-10-20 11:00:00',
|
||||
$ticket->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
|
||||
);
|
||||
$this->assertDatabaseHas('validity_times', [
|
||||
'id' => $original->validity_time_id,
|
||||
'fixed_starts_at' => '2027-10-09 09:00:00',
|
||||
]);
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$destination->id}/reschedule", [
|
||||
'date' => '2027-10-25',
|
||||
])->assertOk()->assertJsonPath('data.status', 'rescheduled');
|
||||
|
||||
$this->assertDatabaseCount('event_dates', 3);
|
||||
$this->assertDatabaseCount('event_date_changes', 2);
|
||||
$this->assertDatabaseHas('event_date_changes', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'change_type' => 'rescheduled',
|
||||
'source_event_date_id' => $destination->id,
|
||||
'created_by_user_id' => $admin->id,
|
||||
'previous_date' => '2027-10-20',
|
||||
'new_date' => '2027-10-25',
|
||||
]);
|
||||
$replacement->refresh();
|
||||
$latestReplacement = $replacement->replacement()->firstOrFail();
|
||||
$this->assertSame($replacement->inventory_id, $latestReplacement->inventory_id);
|
||||
$this->assertSame('2027-10-25', $latestReplacement->eventDate->date->format('Y-m-d'));
|
||||
$this->assertFalse($replacement->isSellable());
|
||||
$this->assertTrue($latestReplacement->isSellable());
|
||||
$this->assertSame('25 de Octubre 2027', $tenant->fresh()->event_date_text);
|
||||
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data.event.dates')
|
||||
->assertJsonPath('data.event.dates.0.date', '2027-10-25')
|
||||
->assertJsonCount(2, 'data.event.date_changes')
|
||||
->assertJsonPath('data.event.date_changes.1.type', 'rescheduled')
|
||||
->assertJsonPath('data.event.date_changes.1.previous_date', '2027-10-20')
|
||||
->assertJsonPath('data.event.date_changes.1.new_date', '2027-10-25')
|
||||
->assertJsonPath('data.event.date_notices.0.title', 'FECHAS REPROGRAMADAS!')
|
||||
->assertJsonPath('data.event.date_notices.0.message.1.text', '09 y 20 de Octubre de 2027')
|
||||
->assertJsonPath('data.event.date_notices.0.message.3.text', '20 y 25 de Octubre de 2027')
|
||||
->assertJsonPath('data.event.date_notices.0.message.5.text', 'respectivamente')
|
||||
->assertJsonPath('data.event.date_notices.0.message.5.bold', true)
|
||||
->assertJsonPath('data.event_date_text', '25 de Octubre 2027');
|
||||
$this->assertSame(
|
||||
'2027-10-25 11:00:00',
|
||||
$ticket->fresh()->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_rescheduling_reuses_an_equivalent_destination_variant(): void
|
||||
{
|
||||
Event::fake([EventDateRescheduled::class]);
|
||||
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||
$original = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-09',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$destination = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-20',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$historicalVariant = $this->createVariant($tenant, $original->id);
|
||||
$destinationVariant = Variant::query()->create([
|
||||
'catalog_item_id' => $historicalVariant->catalog_item_id,
|
||||
'inventory_id' => Inventory::query()->create(['real_stock' => 5])->id,
|
||||
'event_date_id' => $destination->id,
|
||||
]);
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$original->id}/reschedule", [
|
||||
'date' => '2027-10-20',
|
||||
])->assertOk();
|
||||
|
||||
$this->assertSame(2, Variant::query()->count());
|
||||
$this->assertSame(
|
||||
$destinationVariant->id,
|
||||
$historicalVariant->fresh()->replaced_by_variant_id,
|
||||
);
|
||||
$this->assertSame($original->id, $historicalVariant->fresh()->event_date_id);
|
||||
$this->assertTrue($destinationVariant->fresh()->isSellable());
|
||||
}
|
||||
|
||||
public function test_suspending_disables_only_tickets_without_another_usable_date(): void
|
||||
{
|
||||
Event::fake([EventDateSuspended::class]);
|
||||
$tenant = $this->createActiveEvent($this->createTenant('acme'), 'Festival Acme');
|
||||
$admin = $this->createAdminAppUser($tenant);
|
||||
$suspendedDate = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-09',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$otherDate = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-10',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$singleDateVariant = $this->createVariant($tenant, $suspendedDate->id);
|
||||
$multipleDateVariant = $this->createVariant($tenant);
|
||||
$multipleDateVariant->eventDates()->sync([$suspendedDate->id, $otherDate->id]);
|
||||
$singleDateTicket = $this->createTicket($tenant, $admin, $singleDateVariant);
|
||||
$multipleDateTicket = $this->createTicket($tenant, $admin, $multipleDateVariant);
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$suspendedDate->id}/suspend")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', 'suspended')
|
||||
->assertJsonPath('data.suspended_at', fn ($value) => is_string($value));
|
||||
|
||||
Event::assertDispatched(EventDateSuspended::class, function (EventDateSuspended $event) use ($tenant, $suspendedDate): bool {
|
||||
return $event->tenantCode === $tenant->codigo
|
||||
&& $event->eventDateId === $suspendedDate->id
|
||||
&& $event->date === '09/10/2027'
|
||||
&& $event->purchaseTickets === [];
|
||||
});
|
||||
|
||||
$this->assertDatabaseHas('event_date_changes', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'change_type' => 'suspended',
|
||||
'source_event_date_id' => $suspendedDate->id,
|
||||
'destination_event_date_id' => null,
|
||||
'created_by_user_id' => $admin->id,
|
||||
'previous_date' => '2027-10-09',
|
||||
'new_date' => null,
|
||||
]);
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$suspendedDate->id}/suspend")
|
||||
->assertOk();
|
||||
$this->assertDatabaseCount('event_date_changes', 1);
|
||||
|
||||
$this->assertNotNull($singleDateTicket->fresh()->disabled_at);
|
||||
$this->assertNull($multipleDateTicket->fresh()->disabled_at);
|
||||
$this->assertNotNull($singleDateVariant->fresh()->sales_disabled_at);
|
||||
$this->assertNotNull($multipleDateVariant->fresh()->sales_disabled_at);
|
||||
$this->assertSame('10 de Octubre 2027', $tenant->fresh()->event_date_text);
|
||||
$this->getJson('/api/tenants/bootstrap?dominio=acme.test&path=%2F')
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data.event.dates')
|
||||
->assertJsonPath('data.event.dates.0.id', $otherDate->id)
|
||||
->assertJsonCount(1, 'data.event.date_changes')
|
||||
->assertJsonPath('data.event.date_changes.0.type', 'suspended')
|
||||
->assertJsonPath('data.event.date_changes.0.source_event_date_id', $suspendedDate->id)
|
||||
->assertJsonPath('data.event.date_changes.0.destination_event_date_id', null)
|
||||
->assertJsonPath('data.event.date_changes.0.previous_date', '2027-10-09')
|
||||
->assertJsonPath('data.event.date_changes.0.new_date', null)
|
||||
->assertJsonMissingPath('data.event.date_changes.0.created_by_user_id')
|
||||
->assertJsonCount(1, 'data.event.date_notices')
|
||||
->assertJsonPath('data.event.date_notices.0.type', 'suspended')
|
||||
->assertJsonPath('data.event.date_notices.0.title', 'FECHA CANCELADA!')
|
||||
->assertJsonPath('data.event.date_notices.0.message.1.text', '09 de Octubre de 2027')
|
||||
->assertJsonPath('data.event.date_notices.0.message.1.bold', true)
|
||||
->assertJsonPath('data.event_date_text', '10 de Octubre 2027');
|
||||
$this->assertSame(
|
||||
'2027-10-10 09:00:00',
|
||||
$multipleDateTicket->fresh()->resolvedValidity()->effectiveStartsAt()?->format('Y-m-d H:i:s'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_suspending_a_reschedule_destination_disables_tickets_from_predecessor_dates(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$admin = $this->createAdminAppUser($tenant);
|
||||
$original = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-09',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$destination = $tenant->eventDates()->create([
|
||||
'date' => '2027-10-20',
|
||||
'time_start' => '09:00',
|
||||
'time_end' => '18:30',
|
||||
]);
|
||||
$original->update(['rescheduled_to_event_date_id' => $destination->id]);
|
||||
$ticket = $this->createTicket(
|
||||
$tenant,
|
||||
$admin,
|
||||
$this->createVariant($tenant, $original->id),
|
||||
);
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/event-dates/{$destination->id}/suspend")
|
||||
->assertOk();
|
||||
|
||||
$this->assertNotNull($ticket->fresh()->disabled_at);
|
||||
$this->assertFalse($ticket->fresh()->resolvedValidity()->isResolvable);
|
||||
}
|
||||
|
||||
public function test_update_and_date_creation_validate_their_own_payloads(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
@@ -202,10 +523,6 @@ class AdminAppEventControllerTest extends TestCase
|
||||
$this->putJson('/api/v1/adminapp/tenant/event', [
|
||||
'title' => '',
|
||||
'location' => '',
|
||||
'dates' => [
|
||||
['date' => '09/10/2026', 'start_time' => '9am', 'end_time' => '18:00'],
|
||||
['date' => '09/10/2026', 'start_time' => '09:00', 'end_time' => '18:00'],
|
||||
],
|
||||
'contact' => [
|
||||
'whatsapp_url' => 'not-a-url',
|
||||
'instagram_url' => null,
|
||||
@@ -216,12 +533,15 @@ class AdminAppEventControllerTest extends TestCase
|
||||
->assertJsonValidationErrors([
|
||||
'title',
|
||||
'location',
|
||||
'dates.0.date',
|
||||
'dates.0.start_time',
|
||||
'dates.1.date',
|
||||
'contact.whatsapp_url',
|
||||
]);
|
||||
|
||||
$this->postJson('/api/v1/adminapp/tenant/event-dates', [
|
||||
'date' => '09/10/2026',
|
||||
'start_time' => '9am',
|
||||
'end_time' => '18:00',
|
||||
])->assertUnprocessable()->assertJsonValidationErrors(['date', 'start_time']);
|
||||
|
||||
$this->assertNull($tenant->fresh()->event_title);
|
||||
}
|
||||
|
||||
@@ -273,11 +593,10 @@ class AdminAppEventControllerTest extends TestCase
|
||||
return [
|
||||
'title' => 'Festival Acme',
|
||||
'location' => 'Predio Ferial, Rosario',
|
||||
'dates' => [[
|
||||
'date' => '2026-10-09',
|
||||
'start_time' => '09:00',
|
||||
'end_time' => '18:30',
|
||||
]],
|
||||
'allow_ticket_refund' => true,
|
||||
'allow_ticket_total_refund' => true,
|
||||
'allow_ticket_partial_refund' => true,
|
||||
'ticket_partial_refund_percentage' => 25.50,
|
||||
'contact' => [
|
||||
'whatsapp_url' => 'https://wa.me/5493415550101',
|
||||
'instagram_url' => 'https://instagram.com/acme',
|
||||
@@ -286,6 +605,43 @@ class AdminAppEventControllerTest extends TestCase
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{date: string, start_time: string, end_time: string} */
|
||||
private function datePayload(): array
|
||||
{
|
||||
return [
|
||||
'date' => '2026-10-09',
|
||||
'start_time' => '09:00',
|
||||
'end_time' => '18:30',
|
||||
];
|
||||
}
|
||||
|
||||
private function createVariant(Tenant $tenant, ?int $eventDateId = null): Variant
|
||||
{
|
||||
$item = CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'item-'.Str::uuid(),
|
||||
'nombre' => 'Entrada',
|
||||
'precio' => '1000.00',
|
||||
]);
|
||||
|
||||
return Variant::query()->create([
|
||||
'catalog_item_id' => $item->id,
|
||||
'inventory_id' => Inventory::query()->create()->id,
|
||||
'event_date_id' => $eventDateId,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createTicket(Tenant $tenant, User $user, Variant $variant): Ticket
|
||||
{
|
||||
return Ticket::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'user_id' => $user->id,
|
||||
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||
'source_variant_id' => $variant->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createTenant(string $code): Tenant
|
||||
{
|
||||
$headerLogo = $this->createAttachment("{$code}-header");
|
||||
|
||||
82
tests/Feature/Forms/AdminAppEntryFormControllerTest.php
Normal file
82
tests/Feature/Forms/AdminAppEntryFormControllerTest.php
Normal file
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Forms;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Models\WebsiteType;
|
||||
use Database\Seeders\AuthorizationSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AdminAppEntryFormControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->seed(AuthorizationSeeder::class);
|
||||
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
|
||||
}
|
||||
|
||||
public function test_authentication_is_required(): void
|
||||
{
|
||||
$this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/entry')
|
||||
->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_it_returns_only_selectable_event_dates_for_the_tenant(): void
|
||||
{
|
||||
$tenant = $this->createTenant('fiesta');
|
||||
$otherTenant = $this->createTenant('other');
|
||||
$available = $this->createEventDate($tenant, '2026-10-09');
|
||||
$rescheduled = $this->createEventDate($tenant, '2026-10-10');
|
||||
$replacement = $this->createEventDate($tenant, '2026-10-11');
|
||||
$rescheduled->update(['rescheduled_to_event_date_id' => $replacement->id]);
|
||||
$this->createEventDate($tenant, '2026-10-12', ['suspended_at' => now()]);
|
||||
$this->createEventDate($otherTenant, '2026-10-13');
|
||||
|
||||
Sanctum::actingAs(User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/entry')
|
||||
->assertOk()
|
||||
->assertJsonCount(2, 'data.event_dates')
|
||||
->assertJsonFragment(['id' => $available->id, 'date' => '2026-10-09'])
|
||||
->assertJsonFragment(['id' => $replacement->id, 'date' => '2026-10-11'])
|
||||
->assertJsonMissing(['date' => '2026-10-10'])
|
||||
->assertJsonMissing(['date' => '2026-10-12'])
|
||||
->assertJsonMissing(['date' => '2026-10-13']);
|
||||
}
|
||||
|
||||
private function createTenant(string $code): Tenant
|
||||
{
|
||||
return Tenant::query()->create([
|
||||
'codigo' => $code,
|
||||
'nombre' => ucfirst($code),
|
||||
'dominio' => "{$code}.test",
|
||||
'website_type_code' => 'onticket',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $overrides */
|
||||
private function createEventDate(
|
||||
Tenant $tenant,
|
||||
string $date,
|
||||
array $overrides = []
|
||||
): EventDate {
|
||||
return $tenant->eventDates()->create([
|
||||
'date' => $date,
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
...$overrides,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,51 @@ class AdminAppFoodFormControllerTest extends TestCase
|
||||
->assertJsonPath('data.services.0.value', 'Comedor');
|
||||
}
|
||||
|
||||
public function test_it_excludes_rescheduled_and_suspended_event_dates(): void
|
||||
{
|
||||
$tenant = Tenant::query()->create([
|
||||
'codigo' => 'fiesta',
|
||||
'nombre' => 'Fiesta',
|
||||
'dominio' => 'fiesta.test',
|
||||
'website_type_code' => 'onticket',
|
||||
]);
|
||||
$available = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-09',
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
]);
|
||||
$rescheduled = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-10',
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
]);
|
||||
$replacement = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-11',
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
]);
|
||||
$rescheduled->update(['rescheduled_to_event_date_id' => $replacement->id]);
|
||||
$tenant->eventDates()->create([
|
||||
'date' => '2026-10-12',
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
'suspended_at' => now(),
|
||||
]);
|
||||
|
||||
Sanctum::actingAs(User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]));
|
||||
|
||||
$this->getJson('/api/v1/adminapp/forms/fiesta-futbol-infantil/food')
|
||||
->assertOk()
|
||||
->assertJsonCount(2, 'data.event_dates')
|
||||
->assertJsonFragment(['id' => $available->id, 'date' => '2026-10-09'])
|
||||
->assertJsonFragment(['id' => $replacement->id, 'date' => '2026-10-11'])
|
||||
->assertJsonMissing(['date' => '2026-10-10'])
|
||||
->assertJsonMissing(['date' => '2026-10-12']);
|
||||
}
|
||||
|
||||
/** @param array<int, array{value: string, label: string, sort_order: int}> $options */
|
||||
private function createAttribute(Tenant $tenant, string $code, array $options): void
|
||||
{
|
||||
|
||||
@@ -78,6 +78,9 @@ class AdminAppTicketFilterFormControllerTest extends TestCase
|
||||
['value' => 'active', 'label' => 'Activo'],
|
||||
['value' => 'used', 'label' => 'Usado'],
|
||||
['value' => 'expired', 'label' => 'Vencido'],
|
||||
['value' => 'disabled', 'label' => 'Inhabilitado'],
|
||||
['value' => 'cancelled', 'label' => 'Cancelado'],
|
||||
['value' => 'refunded', 'label' => 'Reembolsado'],
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
@@ -63,6 +63,9 @@ class AdminAppTicketFormControllerTest extends TestCase
|
||||
['value' => 'active', 'label' => 'Activo'],
|
||||
['value' => 'used', 'label' => 'Usado'],
|
||||
['value' => 'expired', 'label' => 'Vencido'],
|
||||
['value' => 'disabled', 'label' => 'Inhabilitado'],
|
||||
['value' => 'cancelled', 'label' => 'Cancelado'],
|
||||
['value' => 'refunded', 'label' => 'Reembolsado'],
|
||||
],
|
||||
'categories' => [
|
||||
[
|
||||
|
||||
@@ -6,11 +6,13 @@ use App\Domains\Logging\Enums\ValueChangeActorType;
|
||||
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
|
||||
use App\Domains\Logging\Models\ValueChange;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LogsValueChangesTest extends TestCase
|
||||
@@ -52,6 +54,16 @@ class LogsValueChangesTest extends TestCase
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('tickets', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('tenant_code');
|
||||
$table->uuid('ticket');
|
||||
$table->dateTime('used_at')->nullable();
|
||||
$table->dateTime('disabled_at')->nullable();
|
||||
$table->dateTime('cancelled_at')->nullable();
|
||||
$table->dateTime('refunded_at')->nullable();
|
||||
});
|
||||
|
||||
$migration = require database_path('migrations/2026_08_03_000200_create_value_changes_table.php');
|
||||
$migration->up();
|
||||
$tenantMigration = require database_path('migrations/2026_08_04_000000_add_tenant_code_to_value_changes_table.php');
|
||||
@@ -144,6 +156,39 @@ class LogsValueChangesTest extends TestCase
|
||||
'user_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_ticket_logs_its_status_changes(): void
|
||||
{
|
||||
$ticket = Ticket::query()->create([
|
||||
'tenant_code' => 'test',
|
||||
'ticket' => '794606d5-5f69-458d-9de7-03494757d626',
|
||||
]);
|
||||
|
||||
$ticket->update(['disabled_at' => now()]);
|
||||
|
||||
$this->assertDatabaseHas('value_changes', [
|
||||
'tenant_code' => 'test',
|
||||
'trackable_type' => $ticket->getMorphClass(),
|
||||
'trackable_id' => $ticket->id,
|
||||
'attribute' => 'disabled_at',
|
||||
'old_value' => null,
|
||||
'actor_type' => ValueChangeActorType::System->value,
|
||||
'user_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_ticket_cannot_transition_between_terminal_statuses(): void
|
||||
{
|
||||
$ticket = Ticket::query()->create([
|
||||
'tenant_code' => 'test',
|
||||
'ticket' => '794606d5-5f69-458d-9de7-03494757d626',
|
||||
]);
|
||||
|
||||
$ticket->update(['disabled_at' => now()]);
|
||||
|
||||
$this->expectException(ValidationException::class);
|
||||
$ticket->update(['cancelled_at' => now()]);
|
||||
}
|
||||
}
|
||||
|
||||
#[Fillable(['name', 'price', 'description'])]
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Migrations;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class RemoveRefundedAmountFromPurchaseItemsTest extends TestCase
|
||||
{
|
||||
private string $originalConnection;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->originalConnection = DB::getDefaultConnection();
|
||||
config()->set('database.connections.refund_migration_test', [
|
||||
'driver' => 'sqlite',
|
||||
'database' => ':memory:',
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => true,
|
||||
]);
|
||||
DB::setDefaultConnection('refund_migration_test');
|
||||
|
||||
Schema::create('compra_items', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->decimal('precio_unitario', 10, 2);
|
||||
$table->decimal('total', 10, 2);
|
||||
$table->decimal('refunded_amount', 10, 2)->default(0);
|
||||
});
|
||||
Schema::create('tickets', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('source_purchase_item_id')->nullable();
|
||||
$table->dateTime('refunded_at')->nullable();
|
||||
});
|
||||
Schema::create('ticket_refunds', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('ticket_id')->unique();
|
||||
$table->foreignId('purchase_item_id');
|
||||
$table->foreignId('created_by_user_id')->nullable();
|
||||
$table->string('type', 16);
|
||||
$table->decimal('amount', 10, 2);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
DB::purge('refund_migration_test');
|
||||
DB::setDefaultConnection($this->originalConnection);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_it_backfills_a_refund_created_before_ticket_refunds_existed(): void
|
||||
{
|
||||
DB::table('compra_items')->insert([
|
||||
'id' => 254,
|
||||
'precio_unitario' => '100.00',
|
||||
'total' => '100.00',
|
||||
'refunded_amount' => '40.00',
|
||||
]);
|
||||
DB::table('tickets')->insert([
|
||||
'id' => 501,
|
||||
'source_purchase_item_id' => 254,
|
||||
'refunded_at' => '2026-09-13 18:30:00',
|
||||
]);
|
||||
|
||||
$this->migration()->up();
|
||||
|
||||
$this->assertFalse(Schema::hasColumn('compra_items', 'refunded_amount'));
|
||||
$this->assertDatabaseHas('ticket_refunds', [
|
||||
'ticket_id' => 501,
|
||||
'purchase_item_id' => 254,
|
||||
'created_by_user_id' => null,
|
||||
'type' => 'partial',
|
||||
'amount' => 40,
|
||||
'created_at' => '2026-09-13 18:30:00',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_only_backfills_the_amount_not_already_in_ticket_refunds(): void
|
||||
{
|
||||
DB::table('compra_items')->insert([
|
||||
'id' => 254,
|
||||
'precio_unitario' => '100.00',
|
||||
'total' => '200.00',
|
||||
'refunded_amount' => '140.00',
|
||||
]);
|
||||
DB::table('tickets')->insert([
|
||||
[
|
||||
'id' => 501,
|
||||
'source_purchase_item_id' => 254,
|
||||
'refunded_at' => '2026-09-13 18:30:00',
|
||||
],
|
||||
[
|
||||
'id' => 502,
|
||||
'source_purchase_item_id' => 254,
|
||||
'refunded_at' => '2026-09-14 10:00:00',
|
||||
],
|
||||
]);
|
||||
DB::table('ticket_refunds')->insert([
|
||||
'ticket_id' => 502,
|
||||
'purchase_item_id' => 254,
|
||||
'created_by_user_id' => 7,
|
||||
'type' => 'total',
|
||||
'amount' => '100.00',
|
||||
'created_at' => '2026-09-14 10:00:00',
|
||||
'updated_at' => '2026-09-14 10:00:00',
|
||||
]);
|
||||
|
||||
$this->migration()->up();
|
||||
|
||||
$this->assertDatabaseHas('ticket_refunds', [
|
||||
'ticket_id' => 501,
|
||||
'purchase_item_id' => 254,
|
||||
'created_by_user_id' => null,
|
||||
'type' => 'partial',
|
||||
'amount' => 40,
|
||||
]);
|
||||
$this->assertSame(2, DB::table('ticket_refunds')->count());
|
||||
}
|
||||
|
||||
public function test_it_still_refuses_to_drop_an_amount_without_a_refunded_ticket(): void
|
||||
{
|
||||
DB::table('compra_items')->insert([
|
||||
'id' => 254,
|
||||
'precio_unitario' => '100.00',
|
||||
'total' => '100.00',
|
||||
'refunded_amount' => '40.00',
|
||||
]);
|
||||
|
||||
try {
|
||||
$this->migration()->up();
|
||||
$this->fail('The migration should preserve an amount that cannot be backfilled.');
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->assertStringContainsString('ítem 254', $exception->getMessage());
|
||||
$this->assertTrue(Schema::hasColumn('compra_items', 'refunded_amount'));
|
||||
}
|
||||
}
|
||||
|
||||
private function migration(): object
|
||||
{
|
||||
return require database_path(
|
||||
'migrations/2026_09_14_040000_remove_refunded_amount_from_purchase_items.php'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Notification;
|
||||
|
||||
use App\Domains\Notification\Models\EmailDelivery;
|
||||
use App\Domains\Notification\Services\IdempotentEmailDeliveryService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class IdempotentEmailDeliveryServiceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_it_sends_once_for_the_same_business_key(): void
|
||||
{
|
||||
$calls = 0;
|
||||
$service = app(IdempotentEmailDeliveryService::class);
|
||||
|
||||
$first = $service->sendOnce(
|
||||
'welcome:tenant:10',
|
||||
'welcome',
|
||||
'tenant',
|
||||
['user_id' => 10],
|
||||
'ada@example.com',
|
||||
function () use (&$calls): void {
|
||||
$calls++;
|
||||
},
|
||||
);
|
||||
$second = $service->sendOnce(
|
||||
'welcome:tenant:10',
|
||||
'welcome',
|
||||
'tenant',
|
||||
['user_id' => 10],
|
||||
'ada@example.com',
|
||||
function () use (&$calls): void {
|
||||
$calls++;
|
||||
},
|
||||
);
|
||||
|
||||
$this->assertTrue($first);
|
||||
$this->assertFalse($second);
|
||||
$this->assertSame(1, $calls);
|
||||
$this->assertDatabaseHas('email_deliveries', [
|
||||
'idempotency_key' => 'welcome:tenant:10',
|
||||
'status' => EmailDelivery::STATUS_SENT,
|
||||
'attempts' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_records_a_failure_and_allows_a_retry(): void
|
||||
{
|
||||
$service = app(IdempotentEmailDeliveryService::class);
|
||||
|
||||
try {
|
||||
$service->sendOnce(
|
||||
'purchase-confirmed:20',
|
||||
'purchase_confirmed',
|
||||
'tenant',
|
||||
['purchase_id' => 20],
|
||||
'buyer@example.com',
|
||||
fn () => throw new RuntimeException('Sensitive SMTP detail'),
|
||||
);
|
||||
$this->fail('The delivery exception was not rethrown.');
|
||||
} catch (RuntimeException) {
|
||||
$this->assertDatabaseHas('email_deliveries', [
|
||||
'idempotency_key' => 'purchase-confirmed:20',
|
||||
'status' => EmailDelivery::STATUS_FAILED,
|
||||
'attempts' => 1,
|
||||
'last_error' => RuntimeException::class,
|
||||
]);
|
||||
}
|
||||
|
||||
$sent = $service->sendOnce(
|
||||
'purchase-confirmed:20',
|
||||
'purchase_confirmed',
|
||||
'tenant',
|
||||
['purchase_id' => 20],
|
||||
'buyer@example.com',
|
||||
static function (): void {},
|
||||
);
|
||||
|
||||
$this->assertTrue($sent);
|
||||
$this->assertDatabaseHas('email_deliveries', [
|
||||
'idempotency_key' => 'purchase-confirmed:20',
|
||||
'status' => EmailDelivery::STATUS_SENT,
|
||||
'attempts' => 2,
|
||||
'last_error' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_recovers_an_expired_claim_but_not_an_active_one(): void
|
||||
{
|
||||
config(['mail.delivery_lease_seconds' => 300]);
|
||||
$service = app(IdempotentEmailDeliveryService::class);
|
||||
$delivery = EmailDelivery::query()->create([
|
||||
'idempotency_key' => 'password-reset:30',
|
||||
'email_type' => 'password_reset',
|
||||
'tenant_code' => 'tenant',
|
||||
'status' => EmailDelivery::STATUS_PROCESSING,
|
||||
'attempts' => 1,
|
||||
'context' => ['attempt_id' => 30],
|
||||
'recipient_fingerprint' => str_repeat('a', 64),
|
||||
'claim_token' => fake()->uuid(),
|
||||
'claimed_at' => now(),
|
||||
'lease_expires_at' => now()->addMinute(),
|
||||
]);
|
||||
|
||||
$activeClaim = $service->sendOnce(
|
||||
$delivery->idempotency_key,
|
||||
$delivery->email_type,
|
||||
$delivery->tenant_code,
|
||||
$delivery->context,
|
||||
'ada@example.com',
|
||||
static function (): void {},
|
||||
);
|
||||
$this->assertFalse($activeClaim);
|
||||
|
||||
$delivery->update(['lease_expires_at' => now()->subSecond()]);
|
||||
$expiredClaim = $service->sendOnce(
|
||||
$delivery->idempotency_key,
|
||||
$delivery->email_type,
|
||||
$delivery->tenant_code,
|
||||
$delivery->context,
|
||||
'ada@example.com',
|
||||
static function (): void {},
|
||||
);
|
||||
|
||||
$this->assertTrue($expiredClaim);
|
||||
$this->assertDatabaseHas('email_deliveries', [
|
||||
'idempotency_key' => 'password-reset:30',
|
||||
'status' => EmailDelivery::STATUS_SENT,
|
||||
'attempts' => 2,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user