feat(food): implement FoodController, FoodService, and related resources for managing food items and variants
refactor(catalog): add description and price fields to variants and update related resources feat(migration): add commercial overrides to variants with description and price fields test(food): add tests for FoodController and ensure correct seeding of food items and variants
This commit is contained in:
@@ -180,6 +180,11 @@ class CatalogItem extends Model
|
||||
return $this->nombre;
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion;
|
||||
}
|
||||
|
||||
public function isBundle(): bool
|
||||
{
|
||||
return $this->type === CatalogItemType::Bundle;
|
||||
|
||||
@@ -17,6 +17,8 @@ use Illuminate\Support\Collection;
|
||||
'catalog_item_id',
|
||||
'event_date_id',
|
||||
'inventory_id',
|
||||
'descripcion',
|
||||
'precio',
|
||||
])]
|
||||
class Variant extends Model
|
||||
{
|
||||
@@ -32,6 +34,7 @@ class Variant extends Model
|
||||
'catalog_item_id' => 'integer',
|
||||
'event_date_id' => 'integer',
|
||||
'inventory_id' => 'integer',
|
||||
'precio' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -97,7 +100,12 @@ class Variant extends Model
|
||||
|
||||
public function getPrice(): float
|
||||
{
|
||||
return $this->catalogItem->getPrice();
|
||||
return (float) ($this->precio ?? $this->catalogItem->precio);
|
||||
}
|
||||
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->descripcion ?? $this->catalogItem->descripcion;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
|
||||
@@ -88,6 +88,8 @@ class StoreCatalogItemRequest extends FormRequest
|
||||
'images.*' => ['required', new ImageOrBase64Rule],
|
||||
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
|
||||
'variants.*.real_stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'variants.*.descripcion' => ['sometimes', 'nullable', 'string'],
|
||||
'variants.*.precio' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:99999999.99'],
|
||||
'variants.*.event_date_id' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
|
||||
@@ -41,6 +41,8 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
|
||||
@@ -165,6 +165,8 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $eventDates->pluck('id')->values(),
|
||||
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $this->variantStock($variant),
|
||||
'values' => $values,
|
||||
];
|
||||
|
||||
@@ -42,6 +42,8 @@ class CatalogItemResource extends JsonResource
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'real_stock' => $variant->inventory?->real_stock,
|
||||
'values' => $variant->selectionValues(),
|
||||
'images' => $variant->attachments
|
||||
|
||||
@@ -37,6 +37,8 @@ class CatalogSearchItemResource extends JsonResource
|
||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
|
||||
@@ -554,6 +554,8 @@ class CatalogService
|
||||
$variant = $catalogItem->variants()->create([
|
||||
'inventory_id' => $inventory->id,
|
||||
'event_date_id' => $eventDateIds->count() === 1 ? $eventDateIds->first() : null,
|
||||
'descripcion' => $data['descripcion'] ?? null,
|
||||
'precio' => $data['precio'] ?? null,
|
||||
]);
|
||||
$variant->eventDates()->sync($eventDateIds->all());
|
||||
$variant->setRelation('catalogItem', $catalogItem);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Controllers;
|
||||
|
||||
use App\Domains\FiestaFutbolInfantil\Requests\UpsertFoodVariantsRequest;
|
||||
use App\Domains\FiestaFutbolInfantil\Resources\FoodResource;
|
||||
use App\Domains\FiestaFutbolInfantil\Services\FoodService;
|
||||
use App\Http\Controllers\Controller;
|
||||
|
||||
class FoodController extends Controller
|
||||
{
|
||||
public function __construct(private readonly FoodService $foodService) {}
|
||||
|
||||
public function store(UpsertFoodVariantsRequest $request): FoodResource
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
abort_unless($tenant->codigo === 'fiesta_futbol_infantil', 404);
|
||||
|
||||
return FoodResource::make(
|
||||
$this->foodService->upsertMany(
|
||||
$tenant,
|
||||
$request->validated('variants'),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class UpsertFoodVariantsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$tenantCode = $this->user()?->tenant_codigo;
|
||||
|
||||
return [
|
||||
'variants' => ['required', 'array', 'min:1', 'max:500'],
|
||||
'variants.*' => ['required', 'array:id,event_date_id,schedule,service,description,stock,price'],
|
||||
'variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
|
||||
'variants.*.event_date_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('event_dates', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'variants.*.schedule' => ['required', 'string', 'max:255'],
|
||||
'variants.*.service' => ['required', 'string', 'max:255'],
|
||||
'variants.*.description' => ['sometimes', 'nullable', 'string'],
|
||||
'variants.*.stock' => ['required', 'integer', 'min:0'],
|
||||
'variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<int, callable> */
|
||||
public function after(): array
|
||||
{
|
||||
return [
|
||||
function (Validator $validator): void {
|
||||
$seen = [];
|
||||
|
||||
foreach ($this->input('variants', []) as $index => $variant) {
|
||||
if (! is_array($variant)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = implode('|', [
|
||||
$variant['event_date_id'] ?? '',
|
||||
mb_strtolower(trim((string) ($variant['schedule'] ?? ''))),
|
||||
mb_strtolower(trim((string) ($variant['service'] ?? ''))),
|
||||
]);
|
||||
|
||||
if (isset($seen[$key])) {
|
||||
$validator->errors()->add(
|
||||
"variants.{$index}",
|
||||
'La combinación de fecha, horario y servicio no puede repetirse.',
|
||||
);
|
||||
}
|
||||
|
||||
$seen[$key] = true;
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
35
app/Domains/FiestaFutbolInfantil/Resources/FoodResource.php
Normal file
35
app/Domains/FiestaFutbolInfantil/Resources/FoodResource.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Resources;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CatalogItem */
|
||||
class FoodResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->nombre,
|
||||
'variants' => $this->variants->map(function ($variant): array {
|
||||
$values = $variant->selectionValues();
|
||||
$eventDate = $variant->selectedEventDates()->first();
|
||||
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'event_date_id' => $eventDate?->id,
|
||||
'event_date' => $eventDate?->date?->format('Y-m-d'),
|
||||
'schedule' => $values->get('horario'),
|
||||
'service' => $values->get('servicio'),
|
||||
'description' => $variant->descripcion,
|
||||
'stock' => $variant->inventory->real_stock,
|
||||
'price' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
];
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
}
|
||||
285
app/Domains/FiestaFutbolInfantil/Services/FoodService.php
Normal file
285
app/Domains/FiestaFutbolInfantil/Services/FoodService.php
Normal file
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||
|
||||
use App\Domains\Catalog\Enums\EventProductType;
|
||||
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\Inventory;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
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'];
|
||||
|
||||
/**
|
||||
* @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()
|
||||
->with(['inventory', 'eventDate', 'eventDates', 'definitions.itemAttribute.attribute'])
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$resolvedVariants = $this->resolveVariants($variants, $attributes);
|
||||
|
||||
$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()->min('precio');
|
||||
if ($minimumPrice !== null) {
|
||||
$food->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
return $food->fresh()->load([
|
||||
'variants.catalogItem',
|
||||
'variants.inventory',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
'variants.definitions.itemAttribute.attribute',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @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
|
||||
{
|
||||
$food = CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($food !== null) {
|
||||
$food->update([
|
||||
'event_product_type' => EventProductType::Product->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => false,
|
||||
]);
|
||||
|
||||
return $food;
|
||||
}
|
||||
|
||||
return CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'comida',
|
||||
'nombre' => 'Comida',
|
||||
'descripcion' => 'Comida',
|
||||
'precio' => collect($variants)->min('price') ?? 0,
|
||||
'event_product_type' => EventProductType::Product->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => false,
|
||||
'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()->firstOrCreate(
|
||||
['attribute_id' => $attribute->id],
|
||||
['allow_multi_select' => false],
|
||||
);
|
||||
|
||||
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>> $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->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)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
|
||||
use App\Domains\FiestaFutbolInfantil\Controllers\FoodController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
@@ -8,4 +9,6 @@ Route::prefix('v1/adminapp/tenant')
|
||||
->group(function (): void {
|
||||
Route::post('entries', [EntryController::class, 'store'])
|
||||
->name('adminapp.fiesta-futbol-infantil.entries.store');
|
||||
Route::post('foods', [FoodController::class, 'store'])
|
||||
->name('adminapp.fiesta-futbol-infantil.foods.store');
|
||||
});
|
||||
|
||||
@@ -64,7 +64,7 @@ class PurchaseItemResource extends JsonResource
|
||||
],
|
||||
'item_details' => $selectedItem === null ? null : [
|
||||
'nombre' => $selectedItem->getName(),
|
||||
'descripcion' => $catalogItem?->descripcion,
|
||||
'descripcion' => $selectedItem->getDescription(),
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
|
||||
],
|
||||
|
||||
@@ -27,7 +27,7 @@ class PurchaseItemSnapshotFactory
|
||||
'source_variant_id' => $item->variant_id,
|
||||
'image_attachment_id' => $this->firstImageAttachment($item)?->id,
|
||||
'nombre' => $item->catalogItem->nombre,
|
||||
'descripcion' => $item->catalogItem->descripcion,
|
||||
'descripcion' => $selectedItem?->getDescription(),
|
||||
'slug' => $item->catalogItem->slug,
|
||||
'item_nombre' => $selectedItem->getName(),
|
||||
'variant_attributes' => $item->variant === null
|
||||
|
||||
@@ -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('variantes', function (Blueprint $table): void {
|
||||
$table->text('descripcion')->nullable()->after('inventory_id');
|
||||
$table->decimal('precio', 10, 2)->nullable()->after('descripcion');
|
||||
});
|
||||
|
||||
DB::table('variantes')->orderBy('id')->each(function (object $variant): void {
|
||||
$price = DB::table('catalog_items')
|
||||
->where('id', $variant->catalog_item_id)
|
||||
->value('precio');
|
||||
|
||||
DB::table('variantes')->where('id', $variant->id)->update([
|
||||
'precio' => $price,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('variantes', function (Blueprint $table): void {
|
||||
$table->dropColumn(['descripcion', 'precio']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -73,13 +73,20 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
|
||||
$this->createProduct($tenant, [
|
||||
'slug' => 'comida',
|
||||
'nombre' => 'Comida',
|
||||
'precio' => 8000,
|
||||
'precio' => 4000,
|
||||
'attribute_codes' => ['event_date', 'horario', 'servicio'],
|
||||
'variants' => $dateIds
|
||||
'variants' => $eventDates
|
||||
->crossJoin(['Desayuno', 'Almuerzo', 'Cena'], ['Comedor', 'Vianda'])
|
||||
->map(fn (array $values): array => [
|
||||
'real_stock' => 0,
|
||||
'event_date_ids' => [(int) $values[0]],
|
||||
'event_date_ids' => [(int) $values[0]->id],
|
||||
'descripcion' => sprintf(
|
||||
'%s del %s - %s',
|
||||
$values[1],
|
||||
$values[0]->date->format('d/m/Y'),
|
||||
$values[2],
|
||||
),
|
||||
'precio' => $this->foodPrice($values[1]),
|
||||
'values' => ['horario' => $values[1], 'servicio' => $values[2]],
|
||||
])->all(),
|
||||
]);
|
||||
@@ -128,4 +135,14 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
|
||||
...$data,
|
||||
]);
|
||||
}
|
||||
|
||||
private function foodPrice(string $schedule): int
|
||||
{
|
||||
return match ($schedule) {
|
||||
'Desayuno' => 4000,
|
||||
'Almuerzo' => 10000,
|
||||
'Cena' => 8000,
|
||||
default => throw new RuntimeException("Horario de comida desconocido: {$schedule}"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
208
tests/Feature/FiestaFutbolInfantil/FoodControllerTest.php
Normal file
208
tests/Feature/FiestaFutbolInfantil/FoodControllerTest.php
Normal file
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\FiestaFutbolInfantil;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
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 FoodControllerTest 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->postJson('/api/v1/adminapp/tenant/foods', ['variants' => []])
|
||||
->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_it_creates_one_food_item_with_multiple_variants(): void
|
||||
{
|
||||
[$tenant, $firstDate, $secondDate] = $this->configuredTenant();
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->postJson('/api/v1/adminapp/tenant/foods', [
|
||||
'variants' => [
|
||||
$this->variantPayload($firstDate->id, 'Almuerzo', 'Comedor', 1700, 10000),
|
||||
$this->variantPayload($secondDate->id, 'Cena', 'Vianda', 900, 8000),
|
||||
],
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.name', 'Comida')
|
||||
->assertJsonCount(2, 'data.variants')
|
||||
->assertJsonPath('data.variants.0.schedule', 'Almuerzo')
|
||||
->assertJsonPath('data.variants.0.service', 'Comedor')
|
||||
->assertJsonPath('data.variants.0.stock', 1700)
|
||||
->assertJsonPath('data.variants.0.price', '10000.00')
|
||||
->assertJsonPath('data.variants.1.price', '8000.00');
|
||||
|
||||
$this->assertDatabaseCount('catalog_items', 1);
|
||||
$this->assertDatabaseCount('variantes', 2);
|
||||
$this->assertDatabaseCount('inventories', 2);
|
||||
$this->assertDatabaseCount('variant_event_dates', 2);
|
||||
$this->assertDatabaseCount('variant_values', 4);
|
||||
$this->assertDatabaseHas('catalog_items', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'comida',
|
||||
'nombre' => 'Comida',
|
||||
'precio' => 8000,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_updates_variants_with_an_id_and_creates_variants_without_one(): void
|
||||
{
|
||||
[$tenant, $firstDate, $secondDate] = $this->configuredTenant();
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$created = $this->postJson('/api/v1/adminapp/tenant/foods', [
|
||||
'variants' => [
|
||||
$this->variantPayload($firstDate->id, 'Almuerzo', 'Comedor', 100, 10000),
|
||||
],
|
||||
])->assertOk();
|
||||
$variantId = $created->json('data.variants.0.id');
|
||||
|
||||
$updated = $this->variantPayload($secondDate->id, 'Cena', 'Vianda', 80, 8500);
|
||||
$updated['id'] = $variantId;
|
||||
$updated['description'] = 'Cena para llevar';
|
||||
|
||||
$this->postJson('/api/v1/adminapp/tenant/foods', [
|
||||
'variants' => [
|
||||
$updated,
|
||||
$this->variantPayload($firstDate->id, 'Almuerzo', 'Vianda', 50, 9000),
|
||||
],
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonCount(2, 'data.variants')
|
||||
->assertJsonPath('data.variants.0.id', $variantId)
|
||||
->assertJsonPath('data.variants.0.event_date_id', $secondDate->id)
|
||||
->assertJsonPath('data.variants.0.schedule', 'Cena')
|
||||
->assertJsonPath('data.variants.0.service', 'Vianda')
|
||||
->assertJsonPath('data.variants.0.description', 'Cena para llevar')
|
||||
->assertJsonPath('data.variants.0.stock', 80)
|
||||
->assertJsonPath('data.variants.0.price', '8500.00');
|
||||
|
||||
$this->assertDatabaseCount('catalog_items', 1);
|
||||
$this->assertDatabaseCount('variantes', 2);
|
||||
$this->assertDatabaseHas('variantes', [
|
||||
'id' => $variantId,
|
||||
'event_date_id' => $secondDate->id,
|
||||
'descripcion' => 'Cena para llevar',
|
||||
'precio' => 8500,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_duplicate_combinations(): void
|
||||
{
|
||||
[$tenant, $firstDate] = $this->configuredTenant();
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$this->postJson('/api/v1/adminapp/tenant/foods', [
|
||||
'variants' => [
|
||||
$this->variantPayload($firstDate->id, 'Almuerzo', 'Comedor', 100, 10000),
|
||||
$this->variantPayload($firstDate->id, ' almuerzo ', ' comedor ', 100, 10000),
|
||||
],
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['variants.1']);
|
||||
|
||||
$this->assertDatabaseCount('catalog_items', 0);
|
||||
}
|
||||
|
||||
/** @return array{Tenant, mixed, mixed} */
|
||||
private function configuredTenant(): array
|
||||
{
|
||||
$tenant = Tenant::query()->create([
|
||||
'codigo' => 'fiesta_futbol_infantil',
|
||||
'nombre' => 'Fiesta Fútbol Infantil',
|
||||
'dominio' => 'fiesta.test',
|
||||
'website_type_code' => 'onticket',
|
||||
]);
|
||||
$eventDateAttribute = Attribute::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'codigo' => 'event_date',
|
||||
'nombre' => 'Fecha',
|
||||
'type' => FieldType::EventDate,
|
||||
'is_required' => true,
|
||||
]);
|
||||
$scheduleAttribute = Attribute::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'codigo' => 'horario',
|
||||
'nombre' => 'Horario',
|
||||
'type' => FieldType::Select,
|
||||
'is_required' => true,
|
||||
]);
|
||||
$scheduleAttribute->options()->createMany([
|
||||
['value' => 'Almuerzo', 'label' => 'Almuerzo', 'sort_order' => 1],
|
||||
['value' => 'Cena', 'label' => 'Cena', 'sort_order' => 2],
|
||||
]);
|
||||
$serviceAttribute = Attribute::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'codigo' => 'servicio',
|
||||
'nombre' => 'Servicio',
|
||||
'type' => FieldType::Select,
|
||||
'is_required' => true,
|
||||
]);
|
||||
$serviceAttribute->options()->createMany([
|
||||
['value' => 'Comedor', 'label' => 'Comedor', 'sort_order' => 1],
|
||||
['value' => 'Vianda', 'label' => 'Vianda', 'sort_order' => 2],
|
||||
]);
|
||||
$firstDate = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-09',
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
]);
|
||||
$secondDate = $tenant->eventDates()->create([
|
||||
'date' => '2026-10-10',
|
||||
'time_start' => '00:00',
|
||||
'time_end' => '23:59',
|
||||
]);
|
||||
|
||||
$this->assertNotNull($eventDateAttribute);
|
||||
|
||||
return [$tenant, $firstDate, $secondDate];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantPayload(
|
||||
int $eventDateId,
|
||||
string $schedule,
|
||||
string $service,
|
||||
int $stock,
|
||||
float $price,
|
||||
): array {
|
||||
return [
|
||||
'event_date_id' => $eventDateId,
|
||||
'schedule' => $schedule,
|
||||
'service' => $service,
|
||||
'description' => null,
|
||||
'stock' => $stock,
|
||||
'price' => $price,
|
||||
];
|
||||
}
|
||||
|
||||
private function createAdminAppUser(Tenant $tenant): User
|
||||
{
|
||||
return User::factory()->create([
|
||||
'rol_codigo' => RoleCode::AdminApp->value,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,21 @@ class FiestaFutbolInfantilProductSeederTest extends TestCase
|
||||
$abono->variants->map(fn ($variant): int => $variant->eventDates->count())->all(),
|
||||
);
|
||||
|
||||
$food = CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->with('variants')
|
||||
->sole();
|
||||
$this->assertSame('4000.00', $food->precio);
|
||||
$this->assertCount(24, $food->variants->pluck('descripcion')->unique());
|
||||
$this->assertEqualsCanonicalizing(
|
||||
['4000.00', '8000.00', '10000.00'],
|
||||
$food->variants->pluck('precio')->unique()->values()->all(),
|
||||
);
|
||||
$this->assertTrue($food->variants->every(
|
||||
fn ($variant): bool => $variant->descripcion !== null && $variant->precio !== null
|
||||
));
|
||||
|
||||
$featuredGroup = FeaturedGroup::query()->where('tenant_code', $tenant->codigo)->sole();
|
||||
$this->assertSame(FeaturedGroupSource::All, $featuredGroup->source_type);
|
||||
$this->assertNull($featuredGroup->category_id);
|
||||
|
||||
Reference in New Issue
Block a user