feat(accommodation): implement AccommodationController, AccommodationService, and UpsertAccommodationVariantsRequest for managing accommodations
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Controllers;
|
||||
|
||||
use App\Domains\FiestaFutbolInfantil\Requests\UpsertAccommodationVariantsRequest;
|
||||
use App\Domains\FiestaFutbolInfantil\Resources\AccommodationResource;
|
||||
use App\Domains\FiestaFutbolInfantil\Services\AccommodationService;
|
||||
use App\Http\Controllers\Controller;
|
||||
|
||||
class AccommodationController extends Controller
|
||||
{
|
||||
public function __construct(private readonly AccommodationService $accommodationService) {}
|
||||
|
||||
public function store(UpsertAccommodationVariantsRequest $request): AccommodationResource
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
abort_unless($tenant->codigo === 'fiesta_futbol_infantil', 404);
|
||||
|
||||
return AccommodationResource::make(
|
||||
$this->accommodationService->upsertMany(
|
||||
$tenant,
|
||||
$request->validated('variants'),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpsertAccommodationVariantsRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'variants' => ['required', 'array', 'min:1', 'max:500'],
|
||||
'variants.*' => ['required', 'array:id,title,description,stock,price'],
|
||||
'variants.*.id' => ['sometimes', 'nullable', 'integer', 'distinct'],
|
||||
'variants.*.title' => ['required', 'string', 'max:255'],
|
||||
'variants.*.description' => ['sometimes', 'nullable', 'string'],
|
||||
'variants.*.stock' => ['required', 'integer', 'min:0'],
|
||||
'variants.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?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 AccommodationResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$typeAttribute = $this->itemAttributes
|
||||
->first(fn ($itemAttribute) => $itemAttribute->attribute?->codigo === 'tipo_alojamiento');
|
||||
$options = $typeAttribute?->attribute?->options?->keyBy('value') ?? collect();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->nombre,
|
||||
'variants' => $this->variants->map(function ($variant) use ($typeAttribute, $options): array {
|
||||
$value = $variant->definitions
|
||||
->firstWhere('item_attribute_id', $typeAttribute?->id)
|
||||
?->value;
|
||||
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'title' => $options->get($value)?->label ?? $value,
|
||||
'value' => $value,
|
||||
'description' => $variant->descripcion,
|
||||
'stock' => $variant->inventory->real_stock,
|
||||
'price' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
];
|
||||
})->values(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
<?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\Category;
|
||||
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 AccommodationService
|
||||
{
|
||||
private const ATTRIBUTE_CODE = 'tipo_alojamiento';
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $variants
|
||||
*/
|
||||
public function upsertMany(Tenant $tenant, array $variants): CatalogItem
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $variants): CatalogItem {
|
||||
$attribute = $this->attribute($tenant);
|
||||
$accommodation = $this->accommodation($tenant, $variants);
|
||||
$itemAttribute = $accommodation->itemAttributes()->firstOrCreate(
|
||||
['attribute_id' => $attribute->id],
|
||||
['allow_multi_select' => false],
|
||||
);
|
||||
$existingVariants = $accommodation->variants()
|
||||
->with(['inventory', 'definitions'])
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$resolvedVariants = $this->resolveVariants($variants);
|
||||
|
||||
$this->validateValues($resolvedVariants, $existingVariants, $itemAttribute);
|
||||
|
||||
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 Alojamiento.'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($variant === null) {
|
||||
$this->createVariant($attribute, $accommodation, $itemAttribute, $data);
|
||||
} else {
|
||||
$this->updateVariant($attribute, $variant, $itemAttribute, $data, $index);
|
||||
}
|
||||
}
|
||||
|
||||
$minimumPrice = $accommodation->variants()->min('precio');
|
||||
if ($minimumPrice !== null) {
|
||||
$accommodation->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
return $accommodation->fresh()->load([
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.catalogItem',
|
||||
'variants.inventory',
|
||||
'variants.definitions',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
private function attribute(Tenant $tenant): Attribute
|
||||
{
|
||||
$attribute = Attribute::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('codigo', self::ATTRIBUTE_CODE)
|
||||
->with('options')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($attribute === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'variants' => ['Falta el atributo requerido tipo_alojamiento.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $attribute;
|
||||
}
|
||||
|
||||
/** @param array<int, array<string, mixed>> $variants */
|
||||
private function accommodation(Tenant $tenant, array $variants): CatalogItem
|
||||
{
|
||||
$category = Category::query()->firstOrCreate([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Alojamientos',
|
||||
]);
|
||||
$accommodation = CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'alojamiento')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($accommodation !== null) {
|
||||
$accommodation->update([
|
||||
'category_id' => $category->id,
|
||||
'event_product_type' => EventProductType::Product->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => false,
|
||||
]);
|
||||
|
||||
return $accommodation;
|
||||
}
|
||||
|
||||
return CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'alojamiento',
|
||||
'nombre' => 'Alojamiento',
|
||||
'descripcion' => 'Alojamiento',
|
||||
'category_id' => $category->id,
|
||||
'precio' => collect($variants)->min('price') ?? 0,
|
||||
'event_product_type' => EventProductType::Product->value,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => false,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $variants
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function resolveVariants(array $variants): array
|
||||
{
|
||||
return collect($variants)->map(fn (array $variant): array => [
|
||||
...$variant,
|
||||
'title' => trim($variant['title']),
|
||||
'value' => $this->valueCode($variant['title']),
|
||||
'description' => $variant['description'] ?? null,
|
||||
'stock' => (int) $variant['stock'],
|
||||
])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $incoming
|
||||
* @param Collection<int, Variant> $existing
|
||||
*/
|
||||
private function validateValues(array $incoming, Collection $existing, ItemAttribute $itemAttribute): void
|
||||
{
|
||||
$incomingIds = collect($incoming)->pluck('id')->filter()->map(fn ($id): int => (int) $id);
|
||||
$seen = [];
|
||||
|
||||
foreach ($existing->whereNotIn('id', $incomingIds) as $variant) {
|
||||
$value = $variant->definitions->firstWhere('item_attribute_id', $itemAttribute->id)?->value;
|
||||
if ($value !== null) {
|
||||
$seen[mb_strtolower(trim($value))] = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($incoming as $index => $variant) {
|
||||
$value = $variant['value'];
|
||||
|
||||
if (isset($seen[$value])) {
|
||||
throw ValidationException::withMessages([
|
||||
"variants.{$index}.title" => ['Ya existe un tipo de alojamiento con ese título.'],
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[$value] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
private function createVariant(
|
||||
Attribute $attribute,
|
||||
CatalogItem $accommodation,
|
||||
ItemAttribute $itemAttribute,
|
||||
array $data,
|
||||
): void {
|
||||
$this->createOption($attribute, $data['value'], $data['title']);
|
||||
|
||||
$inventory = Inventory::query()->create(['real_stock' => $data['stock']]);
|
||||
$variant = $accommodation->variants()->create([
|
||||
'inventory_id' => $inventory->id,
|
||||
'descripcion' => $data['description'],
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
$variant->definitions()->create([
|
||||
'item_attribute_id' => $itemAttribute->id,
|
||||
'value' => $data['value'],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data */
|
||||
private function updateVariant(
|
||||
Attribute $attribute,
|
||||
Variant $variant,
|
||||
ItemAttribute $itemAttribute,
|
||||
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.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$definition = $variant->definitions
|
||||
->firstWhere('item_attribute_id', $itemAttribute->id);
|
||||
$option = $definition === null
|
||||
? null
|
||||
: $attribute->options->firstWhere('value', $definition->value);
|
||||
|
||||
if ($option === null) {
|
||||
$this->createOption($attribute, $data['value'], $data['title']);
|
||||
} else {
|
||||
$option->update([
|
||||
'value' => $data['value'],
|
||||
'label' => $data['title'],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->update([
|
||||
'descripcion' => $data['description'],
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
$inventory->update(['real_stock' => $data['stock']]);
|
||||
$variant->definitions()->updateOrCreate(
|
||||
['item_attribute_id' => $itemAttribute->id],
|
||||
['value' => $data['value']],
|
||||
);
|
||||
}
|
||||
|
||||
private function createOption(Attribute $attribute, string $value, string $label): AttributeOption
|
||||
{
|
||||
$existing = $attribute->options->first(
|
||||
fn (AttributeOption $option): bool => mb_strtolower($option->value) === $value
|
||||
);
|
||||
|
||||
if ($existing !== null) {
|
||||
$existing->update(['label' => $label]);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$option = $attribute->options()->create([
|
||||
'value' => $value,
|
||||
'label' => $label,
|
||||
'sort_order' => ((int) $attribute->options->max('sort_order')) + 1,
|
||||
]);
|
||||
$attribute->options->push($option);
|
||||
|
||||
return $option;
|
||||
}
|
||||
|
||||
private function valueCode(string $title): string
|
||||
{
|
||||
return mb_strtolower((string) preg_replace('/\s+/u', '_', trim($title)));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController;
|
||||
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
|
||||
use App\Domains\FiestaFutbolInfantil\Controllers\FoodController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
@@ -11,4 +12,6 @@ Route::prefix('v1/adminapp/tenant')
|
||||
->name('adminapp.fiesta-futbol-infantil.entries.store');
|
||||
Route::post('foods', [FoodController::class, 'store'])
|
||||
->name('adminapp.fiesta-futbol-infantil.foods.store');
|
||||
Route::post('accommodations', [AccommodationController::class, 'store'])
|
||||
->name('adminapp.fiesta-futbol-infantil.accommodations.store');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user