473 lines
17 KiB
PHP
473 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\FiestaFutbolInfantil\Services;
|
|
|
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
|
use App\Domains\Catalog\Models\Attribute;
|
|
use App\Domains\Catalog\Models\AttributeOption;
|
|
use App\Domains\Catalog\Models\CatalogItem;
|
|
use App\Domains\Catalog\Models\Category;
|
|
use App\Domains\Catalog\Models\Inventory;
|
|
use App\Domains\Catalog\Models\ItemAttribute;
|
|
use App\Domains\Catalog\Models\Variant;
|
|
use App\Domains\Catalog\Services\CatalogService;
|
|
use App\Domains\Event\Enums\EventDateStatus;
|
|
use App\Domains\Event\Models\EventDate;
|
|
use App\Domains\Tenant\Models\Tenant;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class FoodService
|
|
{
|
|
private const ATTRIBUTE_CODES = ['event_date', 'horario', 'servicio'];
|
|
|
|
private const ATTRIBUTE_SORT_ORDERS = [
|
|
'event_date' => 1,
|
|
'horario' => 2,
|
|
'servicio' => 3,
|
|
];
|
|
|
|
public function __construct(private readonly CatalogService $catalogService) {}
|
|
|
|
public function current(Tenant $tenant): ?CatalogItem
|
|
{
|
|
return CatalogItem::query()
|
|
->where('tenant_code', $tenant->codigo)
|
|
->where('slug', 'comida')
|
|
->with([
|
|
'variants.catalogItem',
|
|
'variants.inventory',
|
|
'variants.eventDate.rescheduledTo',
|
|
'variants.eventDate.changeHistory.destinationEventDate',
|
|
'variants.eventDates.rescheduledTo',
|
|
'variants.eventDates.changeHistory.destinationEventDate',
|
|
'variants.definitions.itemAttribute.attribute',
|
|
])
|
|
->first();
|
|
}
|
|
|
|
/**
|
|
* @param array<int, array<string, mixed>> $variants
|
|
*/
|
|
public function upsertMany(Tenant $tenant, array $variants): CatalogItem
|
|
{
|
|
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
|
|
$attributes = $this->attributes($tenant);
|
|
$food = $this->food($tenant, $variants);
|
|
$itemAttributes = $this->itemAttributes($food, $attributes);
|
|
|
|
$food->variants()->whereNull('precio')->update(['precio' => $food->precio]);
|
|
$existingVariants = $food->variants()
|
|
->whereNull('sales_disabled_at')
|
|
->whereNull('replaced_by_variant_id')
|
|
->with(['inventory', 'eventDate', 'eventDates', 'definitions.itemAttribute.attribute'])
|
|
->lockForUpdate()
|
|
->get()
|
|
->filter(fn (Variant $variant): bool => $this->hasCurrentDate($variant))
|
|
->values();
|
|
$resolvedVariants = $this->resolveVariants($variants, $attributes);
|
|
|
|
$this->validateCurrentEventDates($tenant, $resolvedVariants);
|
|
$this->validateCombinations($resolvedVariants, $existingVariants);
|
|
|
|
foreach ($resolvedVariants as $index => $data) {
|
|
$variant = isset($data['id'])
|
|
? $existingVariants->firstWhere('id', (int) $data['id'])
|
|
: null;
|
|
|
|
if (isset($data['id']) && $variant === null) {
|
|
throw ValidationException::withMessages([
|
|
"variants.{$index}.id" => ['La variante no pertenece al producto Comida.'],
|
|
]);
|
|
}
|
|
|
|
if ($variant === null) {
|
|
$this->createVariant($food, $itemAttributes, $data);
|
|
} else {
|
|
$this->updateVariant($variant, $itemAttributes, $data, $index);
|
|
}
|
|
}
|
|
|
|
$minimumPrice = $food->variants()
|
|
->whereNull('sales_disabled_at')
|
|
->whereNull('replaced_by_variant_id')
|
|
->with(['eventDate', 'eventDates'])
|
|
->get()
|
|
->filter(fn (Variant $variant): bool => $this->hasCurrentDate($variant))
|
|
->min('precio');
|
|
if ($minimumPrice !== null) {
|
|
$food->update(['precio' => $minimumPrice]);
|
|
}
|
|
|
|
return $food->fresh()->load([
|
|
'variants.catalogItem',
|
|
'variants.inventory',
|
|
'variants.eventDate.rescheduledTo',
|
|
'variants.eventDate.changeHistory.destinationEventDate',
|
|
'variants.eventDates.rescheduledTo',
|
|
'variants.eventDates.changeHistory.destinationEventDate',
|
|
'variants.definitions.itemAttribute.attribute',
|
|
]);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param array<int, array{id: int, stock: int}> $variants
|
|
*/
|
|
public function updateHistoricalStock(Tenant $tenant, array $variants): CatalogItem
|
|
{
|
|
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
|
|
$food = CatalogItem::query()
|
|
->where('tenant_code', $tenant->codigo)
|
|
->where('slug', 'comida')
|
|
->lockForUpdate()
|
|
->firstOrFail();
|
|
$variantIds = collect($variants)->pluck('id')->map(fn ($id): int => (int) $id);
|
|
$historicalVariants = $food->variants()
|
|
->whereIn('id', $variantIds)
|
|
->with(['inventory', 'eventDate', 'eventDates'])
|
|
->lockForUpdate()
|
|
->get()
|
|
->filter(fn (Variant $variant): bool => $this->hasHistoricalDate($variant))
|
|
->keyBy('id');
|
|
|
|
foreach ($variants as $index => $data) {
|
|
$variant = $historicalVariants->get((int) $data['id']);
|
|
if ($variant === null) {
|
|
throw ValidationException::withMessages([
|
|
"variants.{$index}.id" => [
|
|
'La variante no pertenece al historial de Comida.',
|
|
],
|
|
]);
|
|
}
|
|
|
|
$stock = (int) $data['stock'];
|
|
$inventory = $this->inventoryForHistoricalStockUpdate($variant);
|
|
if ($stock < $inventory->reserved_stock) {
|
|
throw ValidationException::withMessages([
|
|
"variants.{$index}.stock" => [
|
|
'El stock no puede ser menor que la cantidad actualmente reservada.',
|
|
],
|
|
]);
|
|
}
|
|
|
|
$inventory->update(['real_stock' => $stock]);
|
|
}
|
|
|
|
return $this->current($tenant) ?? $food;
|
|
});
|
|
}
|
|
|
|
private function inventoryForHistoricalStockUpdate(Variant $variant): Inventory
|
|
{
|
|
$inventory = Inventory::query()
|
|
->whereKey($variant->inventory_id)
|
|
->lockForUpdate()
|
|
->firstOrFail();
|
|
$variantsSharingInventory = Variant::query()
|
|
->where('inventory_id', $inventory->getKey())
|
|
->orderBy('id')
|
|
->lockForUpdate()
|
|
->get(['id']);
|
|
|
|
if ($variantsSharingInventory->count() === 1) {
|
|
return $inventory;
|
|
}
|
|
|
|
$historicalInventory = Inventory::query()->create([
|
|
'sold_units' => $inventory->sold_units,
|
|
'reserved_stock' => 0,
|
|
'real_stock' => $inventory->real_stock,
|
|
]);
|
|
$variant->update(['inventory_id' => $historicalInventory->getKey()]);
|
|
|
|
return $historicalInventory;
|
|
}
|
|
|
|
public function delete(Tenant $tenant, int $foodId): void
|
|
{
|
|
$variant = Variant::query()
|
|
->whereKey($foodId)
|
|
->whereNull('sales_disabled_at')
|
|
->whereNull('replaced_by_variant_id')
|
|
->with(['eventDate', 'eventDates'])
|
|
->whereHas('catalogItem', fn ($query) => $query
|
|
->where('tenant_code', $tenant->codigo)
|
|
->where('slug', 'comida'))
|
|
->firstOrFail();
|
|
|
|
abort_unless($this->hasCurrentDate($variant), 404);
|
|
|
|
$this->catalogService->deleteVariant($variant);
|
|
}
|
|
|
|
/** @return Collection<string, Attribute> */
|
|
private function attributes(Tenant $tenant): Collection
|
|
{
|
|
$attributes = Attribute::query()
|
|
->where('tenant_codigo', $tenant->codigo)
|
|
->whereIn('codigo', self::ATTRIBUTE_CODES)
|
|
->with('options')
|
|
->get()
|
|
->keyBy('codigo');
|
|
|
|
$missingCodes = collect(self::ATTRIBUTE_CODES)->diff($attributes->keys());
|
|
if ($missingCodes->isNotEmpty()) {
|
|
throw ValidationException::withMessages([
|
|
'variants' => [
|
|
'Faltan atributos requeridos para Comida: '.$missingCodes->implode(', ').'.',
|
|
],
|
|
]);
|
|
}
|
|
|
|
return $attributes;
|
|
}
|
|
|
|
/** @param array<int, array<string, mixed>> $variants */
|
|
private function food(Tenant $tenant, array $variants): CatalogItem
|
|
{
|
|
$category = Category::query()->firstOrCreate([
|
|
'tenant_code' => $tenant->codigo,
|
|
'nombre' => 'Comidas',
|
|
]);
|
|
$food = CatalogItem::withTrashed()
|
|
->where('tenant_code', $tenant->codigo)
|
|
->where('slug', 'comida')
|
|
->lockForUpdate()
|
|
->first();
|
|
|
|
if ($food !== null) {
|
|
if ($food->trashed()) {
|
|
$food->restore();
|
|
}
|
|
|
|
$food->update([
|
|
'category_id' => $category->id,
|
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
|
'has_tickets' => true,
|
|
]);
|
|
|
|
return $food;
|
|
}
|
|
|
|
return CatalogItem::query()->create([
|
|
'tenant_code' => $tenant->codigo,
|
|
'slug' => 'comida',
|
|
'nombre' => 'Comida',
|
|
'descripcion' => 'Comida',
|
|
'category_id' => $category->id,
|
|
'precio' => collect($variants)->min('price') ?? 0,
|
|
'inventory_policy' => InventoryPolicy::Tracked->value,
|
|
'has_tickets' => true,
|
|
'inventory_id' => null,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param Collection<string, Attribute> $attributes
|
|
* @return Collection<string, ItemAttribute>
|
|
*/
|
|
private function itemAttributes(CatalogItem $food, Collection $attributes): Collection
|
|
{
|
|
return $attributes->mapWithKeys(function (Attribute $attribute, string $code) use ($food): array {
|
|
$itemAttribute = $food->itemAttributes()->updateOrCreate(
|
|
['attribute_id' => $attribute->id],
|
|
[
|
|
'allow_multi_select' => false,
|
|
'sort_order' => self::ATTRIBUTE_SORT_ORDERS[$code],
|
|
],
|
|
);
|
|
|
|
return [$code => $itemAttribute];
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param array<int, array<string, mixed>> $variants
|
|
* @param Collection<string, Attribute> $attributes
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
private function resolveVariants(array $variants, Collection $attributes): array
|
|
{
|
|
return collect($variants)->map(function (array $variant, int $index) use ($attributes): array {
|
|
$schedule = $this->option($attributes['horario'], $variant['schedule'], "variants.{$index}.schedule");
|
|
$service = $this->option($attributes['servicio'], $variant['service'], "variants.{$index}.service");
|
|
|
|
return [
|
|
...$variant,
|
|
'event_date_id' => (int) $variant['event_date_id'],
|
|
'schedule' => $schedule->value,
|
|
'service' => $service->value,
|
|
'description' => (string) ($variant['description'] ?? ''),
|
|
'stock' => (int) $variant['stock'],
|
|
];
|
|
})->all();
|
|
}
|
|
|
|
private function option(Attribute $attribute, string $value, string $validationKey): AttributeOption
|
|
{
|
|
$option = $attribute->options->first(
|
|
fn (AttributeOption $option): bool => mb_strtolower(trim($option->value)) === mb_strtolower(trim($value))
|
|
);
|
|
|
|
if ($option === null) {
|
|
throw ValidationException::withMessages([
|
|
$validationKey => ["El valor seleccionado no es válido para {$attribute->nombre}."],
|
|
]);
|
|
}
|
|
|
|
return $option;
|
|
}
|
|
|
|
/** @param array<int, array<string, mixed>> $variants */
|
|
private function validateCurrentEventDates(Tenant $tenant, array $variants): void
|
|
{
|
|
$eventDates = EventDate::query()
|
|
->where('tenant_code', $tenant->codigo)
|
|
->whereIn('id', collect($variants)->pluck('event_date_id')->unique())
|
|
->get()
|
|
->keyBy('id');
|
|
|
|
foreach ($variants as $index => $variant) {
|
|
$eventDate = $eventDates->get($variant['event_date_id']);
|
|
|
|
if ($eventDate !== null && $this->isCurrentStatus($eventDate->status)) {
|
|
continue;
|
|
}
|
|
|
|
throw ValidationException::withMessages([
|
|
"variants.{$index}.event_date_id" => [
|
|
'La fecha seleccionada ya no está disponible.',
|
|
],
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param array<int, array<string, mixed>> $incoming
|
|
* @param Collection<int, Variant> $existing
|
|
*/
|
|
private function validateCombinations(array $incoming, Collection $existing): void
|
|
{
|
|
$incomingIds = collect($incoming)->pluck('id')->filter()->map(fn ($id): int => (int) $id);
|
|
$seen = [];
|
|
|
|
foreach ($existing->whereNotIn('id', $incomingIds) as $variant) {
|
|
$values = $variant->selectionValues();
|
|
$seen[$this->combinationKey(
|
|
(int) $variant->selectedEventDates()->first()?->id,
|
|
(string) $values->get('horario'),
|
|
(string) $values->get('servicio'),
|
|
)] = true;
|
|
}
|
|
|
|
foreach ($incoming as $index => $variant) {
|
|
$key = $this->combinationKey(
|
|
$variant['event_date_id'],
|
|
$variant['schedule'],
|
|
$variant['service'],
|
|
);
|
|
|
|
if (isset($seen[$key])) {
|
|
throw ValidationException::withMessages([
|
|
"variants.{$index}" => ['La combinación de fecha, horario y servicio ya existe.'],
|
|
]);
|
|
}
|
|
|
|
$seen[$key] = true;
|
|
}
|
|
}
|
|
|
|
/** @param Collection<string, ItemAttribute> $itemAttributes */
|
|
private function createVariant(CatalogItem $food, Collection $itemAttributes, array $data): void
|
|
{
|
|
$inventory = Inventory::query()->create(['real_stock' => $data['stock']]);
|
|
$variant = $food->variants()->create([
|
|
'event_date_id' => $data['event_date_id'],
|
|
'inventory_id' => $inventory->id,
|
|
'descripcion' => $data['description'],
|
|
'precio' => $data['price'],
|
|
]);
|
|
$variant->eventDates()->sync([$data['event_date_id']]);
|
|
$this->syncDefinitions($variant, $itemAttributes, $data);
|
|
}
|
|
|
|
/** @param Collection<string, ItemAttribute> $itemAttributes */
|
|
private function updateVariant(
|
|
Variant $variant,
|
|
Collection $itemAttributes,
|
|
array $data,
|
|
int $index,
|
|
): void {
|
|
$inventory = Inventory::query()
|
|
->whereKey($variant->inventory_id)
|
|
->lockForUpdate()
|
|
->firstOrFail();
|
|
|
|
if ($data['stock'] < $inventory->reserved_stock) {
|
|
throw ValidationException::withMessages([
|
|
"variants.{$index}.stock" => [
|
|
'El stock no puede ser menor que la cantidad actualmente reservada.',
|
|
],
|
|
]);
|
|
}
|
|
|
|
$variant->update([
|
|
'event_date_id' => $data['event_date_id'],
|
|
'descripcion' => $data['description'],
|
|
'precio' => $data['price'],
|
|
]);
|
|
$variant->eventDates()->sync([$data['event_date_id']]);
|
|
$inventory->update(['real_stock' => $data['stock']]);
|
|
$this->syncDefinitions($variant, $itemAttributes, $data);
|
|
}
|
|
|
|
/** @param Collection<string, ItemAttribute> $itemAttributes */
|
|
private function syncDefinitions(Variant $variant, Collection $itemAttributes, array $data): void
|
|
{
|
|
$definitionAttributes = $itemAttributes->toBase()->only(['horario', 'servicio']);
|
|
$variant->definitions()->whereIn('item_attribute_id', $definitionAttributes->pluck('id'))->delete();
|
|
$variant->definitions()->createMany([
|
|
[
|
|
'item_attribute_id' => $definitionAttributes['horario']->id,
|
|
'value' => $data['schedule'],
|
|
],
|
|
[
|
|
'item_attribute_id' => $definitionAttributes['servicio']->id,
|
|
'value' => $data['service'],
|
|
],
|
|
]);
|
|
}
|
|
|
|
private function combinationKey(int $eventDateId, string $schedule, string $service): string
|
|
{
|
|
return implode('|', [
|
|
$eventDateId,
|
|
mb_strtolower(trim($schedule)),
|
|
mb_strtolower(trim($service)),
|
|
]);
|
|
}
|
|
|
|
private function hasCurrentDate(Variant $variant): bool
|
|
{
|
|
$status = $variant->selectedEventDates()->first()?->status;
|
|
|
|
return $status === null || $this->isCurrentStatus($status);
|
|
}
|
|
|
|
private function hasHistoricalDate(Variant $variant): bool
|
|
{
|
|
return in_array(
|
|
$variant->selectedEventDates()->first()?->status,
|
|
[EventDateStatus::Rescheduled, EventDateStatus::Suspended, EventDateStatus::Completed],
|
|
true,
|
|
);
|
|
}
|
|
|
|
private function isCurrentStatus(EventDateStatus $status): bool
|
|
{
|
|
return in_array($status, [EventDateStatus::Scheduled, EventDateStatus::InProgress], true);
|
|
}
|
|
}
|