feat(entry): implement EntryController, EntryService, and EntryResource for managing entries
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Controllers;
|
||||
|
||||
use App\Domains\FiestaFutbolInfantil\Requests\UpsertEntriesRequest;
|
||||
use App\Domains\FiestaFutbolInfantil\Resources\EntryResource;
|
||||
use App\Domains\FiestaFutbolInfantil\Services\EntryService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class EntryController extends Controller
|
||||
{
|
||||
public function __construct(private readonly EntryService $entryService) {}
|
||||
|
||||
public function store(UpsertEntriesRequest $request): JsonResponse
|
||||
{
|
||||
$tenant = $request->user()->tenant()->firstOrFail();
|
||||
|
||||
abort_unless($tenant->codigo === 'fiesta_futbol_infantil', 404);
|
||||
|
||||
$entries = $this->entryService->upsertMany(
|
||||
$tenant,
|
||||
$request->validated('entries'),
|
||||
);
|
||||
|
||||
return EntryResource::collection($entries)
|
||||
->response()
|
||||
->setStatusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class UpsertEntriesRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$tenantCode = $this->user()?->tenant_codigo;
|
||||
|
||||
return [
|
||||
'entries' => ['required', 'array', 'min:1', 'max:100'],
|
||||
'entries.*' => ['required', 'array:id,title,description,event_date_ids,stock,price'],
|
||||
'entries.*.id' => [
|
||||
'sometimes',
|
||||
'nullable',
|
||||
'integer',
|
||||
'distinct',
|
||||
Rule::exists('catalog_items', 'id')->where(
|
||||
fn ($query) => $query
|
||||
->where('tenant_code', $tenantCode)
|
||||
->where('event_product_type', 'entrada')
|
||||
),
|
||||
],
|
||||
'entries.*.title' => ['required', 'string', 'max:255'],
|
||||
'entries.*.description' => ['sometimes', 'nullable', 'string'],
|
||||
'entries.*.event_date_ids' => ['required', 'array', 'min:1'],
|
||||
'entries.*.event_date_ids.*' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('event_dates', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_code', $tenantCode)
|
||||
),
|
||||
],
|
||||
'entries.*.stock' => ['required', 'integer', 'min:0'],
|
||||
'entries.*.price' => ['required', 'numeric', 'min:0', 'max:99999999.99'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<int, callable> */
|
||||
public function after(): array
|
||||
{
|
||||
return [
|
||||
function (Validator $validator): void {
|
||||
foreach ($this->input('entries', []) as $index => $entry) {
|
||||
if (! is_array($entry)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$dateIds = $entry['event_date_ids'] ?? [];
|
||||
|
||||
if (! is_array($dateIds)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (count($dateIds) !== count(array_unique($dateIds))) {
|
||||
$validator->errors()->add(
|
||||
"entries.{$index}.event_date_ids",
|
||||
'Las fechas de una entrada no pueden repetirse.',
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/FiestaFutbolInfantil/Resources/EntryResource.php
Normal file
26
app/Domains/FiestaFutbolInfantil/Resources/EntryResource.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?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 EntryResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$variant = $this->variants->sole();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->nombre,
|
||||
'description' => $this->descripcion,
|
||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||
'stock' => $variant->inventory->real_stock,
|
||||
'price' => $this->precio,
|
||||
];
|
||||
}
|
||||
}
|
||||
143
app/Domains/FiestaFutbolInfantil/Services/EntryService.php
Normal file
143
app/Domains/FiestaFutbolInfantil/Services/EntryService.php
Normal file
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||
|
||||
use App\Domains\Catalog\Enums\EventProductType;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class EntryService
|
||||
{
|
||||
public function __construct(private readonly CatalogService $catalogService) {}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $entries
|
||||
* @return Collection<int, CatalogItem>
|
||||
*/
|
||||
public function upsertMany(Tenant $tenant, array $entries): Collection
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $entries): Collection {
|
||||
$reservedSlugs = [];
|
||||
|
||||
return collect($entries)->map(function (array $entry, int $index) use ($tenant, &$reservedSlugs): CatalogItem {
|
||||
if (isset($entry['id'])) {
|
||||
return $this->update($tenant, $entry, $index);
|
||||
}
|
||||
|
||||
$slug = $this->uniqueSlug($tenant, $entry['title'], $reservedSlugs);
|
||||
$reservedSlugs[] = $slug;
|
||||
|
||||
return $this->catalogService->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => $slug,
|
||||
'nombre' => $entry['title'],
|
||||
'descripcion' => $entry['description'] ?? null,
|
||||
'precio' => $entry['price'],
|
||||
'event_product_type' => EventProductType::Entry->value,
|
||||
'has_tickets' => true,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'attribute_codes' => ['event_date'],
|
||||
'multi_select_attribute_codes' => ['event_date'],
|
||||
'variants' => [[
|
||||
'real_stock' => $entry['stock'],
|
||||
'event_date_ids' => array_values($entry['event_date_ids']),
|
||||
]],
|
||||
]);
|
||||
})->values();
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $entry */
|
||||
private function update(Tenant $tenant, array $entry, int $index): CatalogItem
|
||||
{
|
||||
$catalogItem = CatalogItem::query()
|
||||
->whereKey($entry['id'])
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('event_product_type', EventProductType::Entry->value)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
$variants = Variant::query()
|
||||
->where('catalog_item_id', $catalogItem->id)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
if ($variants->count() !== 1) {
|
||||
throw ValidationException::withMessages([
|
||||
"entries.{$index}.id" => [
|
||||
'La entrada no posee una única variante editable.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant = $variants->first();
|
||||
$inventory = Inventory::query()
|
||||
->whereKey($variant->inventory_id)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
if ((int) $entry['stock'] < $inventory->reserved_stock) {
|
||||
throw ValidationException::withMessages([
|
||||
"entries.{$index}.stock" => [
|
||||
'El stock no puede ser menor que la cantidad actualmente reservada.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$eventDateIds = collect($entry['event_date_ids'])
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
$catalogItem->update([
|
||||
'nombre' => $entry['title'],
|
||||
'descripcion' => $entry['description'] ?? null,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
]);
|
||||
$variant->update([
|
||||
'event_date_id' => $eventDateIds->count() === 1 ? $eventDateIds->first() : null,
|
||||
]);
|
||||
$variant->eventDates()->sync($eventDateIds->all());
|
||||
$catalogItem->itemAttributes()
|
||||
->whereHas('attribute', fn ($query) => $query->where('codigo', 'event_date'))
|
||||
->update(['allow_multi_select' => true]);
|
||||
$inventory->update(['real_stock' => $entry['stock']]);
|
||||
|
||||
return $catalogItem->load([
|
||||
'variants.inventory',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param array<int, string> $reservedSlugs */
|
||||
private function uniqueSlug(Tenant $tenant, string $title, array $reservedSlugs): string
|
||||
{
|
||||
$baseSlug = Str::slug($title) ?: 'entrada';
|
||||
$slug = $baseSlug;
|
||||
$suffix = 2;
|
||||
|
||||
while (
|
||||
in_array($slug, $reservedSlugs, true)
|
||||
|| CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', $slug)
|
||||
->exists()
|
||||
) {
|
||||
$slug = "{$baseSlug}-{$suffix}";
|
||||
$suffix++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
}
|
||||
11
app/Domains/FiestaFutbolInfantil/routes/api.php
Normal file
11
app/Domains/FiestaFutbolInfantil/routes/api.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1/adminapp/tenant')
|
||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||
->group(function (): void {
|
||||
Route::post('entries', [EntryController::class, 'store'])
|
||||
->name('adminapp.fiesta-futbol-infantil.entries.store');
|
||||
});
|
||||
Reference in New Issue
Block a user