Add tests for ticket validity and event date formatting
- Create TicketValiditySchemaTest to verify database schema for ticket validity. - Update CatalogModelsTest to include tests for event date attributes and selection options. - Introduce EventDateTextFormatterTest for formatting event dates in Spanish. - Refactor EventModelsTest to include validity time relationships. - Add SaleDetailResourceTest to ensure correct serialization of purchase items. - Enhance TicketTest with validity time checks and status management. - Implement ValidityTimeResourceTest to validate resource output for different validity types. - Add ValidityTimeTest to verify casting and validity checks for validity time types.
This commit is contained in:
@@ -0,0 +1,298 @@
|
||||
<?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\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AccommodationService
|
||||
{
|
||||
private const ATTRIBUTE_CODE = 'tipo_alojamiento';
|
||||
|
||||
public function __construct(private readonly CatalogService $catalogService) {}
|
||||
|
||||
public function current(Tenant $tenant): ?CatalogItem
|
||||
{
|
||||
return CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'alojamiento')
|
||||
->with([
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.catalogItem',
|
||||
'variants.inventory',
|
||||
'variants.definitions',
|
||||
])
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(Tenant $tenant, int $accommodationId): void
|
||||
{
|
||||
$variant = Variant::query()
|
||||
->whereKey($accommodationId)
|
||||
->whereHas('catalogItem', fn ($query) => $query
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'alojamiento'))
|
||||
->firstOrFail();
|
||||
|
||||
$this->catalogService->deleteVariant($variant);
|
||||
}
|
||||
|
||||
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,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
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,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'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)));
|
||||
}
|
||||
}
|
||||
177
app/Domains/FiestaFutbolInfantil/Services/EntryService.php
Normal file
177
app/Domains/FiestaFutbolInfantil/Services/EntryService.php
Normal file
@@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
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 App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
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) {}
|
||||
|
||||
/** @return Collection<int, CatalogItem> */
|
||||
public function all(Tenant $tenant): Collection
|
||||
{
|
||||
return CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
||||
->with([
|
||||
'variants.inventory',
|
||||
'variants.eventDate',
|
||||
'variants.eventDates',
|
||||
])
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 = [];
|
||||
$category = Category::query()->firstOrCreate([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Entradas',
|
||||
]);
|
||||
|
||||
return collect($entries)->map(function (array $entry, int $index) use ($tenant, $category, &$reservedSlugs): CatalogItem {
|
||||
if (isset($entry['id'])) {
|
||||
return $this->update($tenant, $category, $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,
|
||||
'category_id' => $category->id,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'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();
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(Tenant $tenant, int $entryId): void
|
||||
{
|
||||
$entry = CatalogItem::query()
|
||||
->whereKey($entryId)
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
||||
->firstOrFail();
|
||||
|
||||
$this->catalogService->delete($entry);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $entry */
|
||||
private function update(Tenant $tenant, Category $category, array $entry, int $index): CatalogItem
|
||||
{
|
||||
$catalogItem = CatalogItem::query()
|
||||
->whereKey($entry['id'])
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Entradas'))
|
||||
->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,
|
||||
'category_id' => $category->id,
|
||||
'precio' => $entry['price'],
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'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;
|
||||
}
|
||||
}
|
||||
331
app/Domains/FiestaFutbolInfantil/Services/FoodService.php
Normal file
331
app/Domains/FiestaFutbolInfantil/Services/FoodService.php
Normal file
@@ -0,0 +1,331 @@
|
||||
<?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\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
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',
|
||||
'variants.eventDates',
|
||||
'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()
|
||||
->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',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(Tenant $tenant, int $foodId): void
|
||||
{
|
||||
$variant = Variant::query()
|
||||
->whereKey($foodId)
|
||||
->whereHas('catalogItem', fn ($query) => $query
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida'))
|
||||
->firstOrFail();
|
||||
|
||||
$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::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'comida')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($food !== null) {
|
||||
$food->update([
|
||||
'category_id' => $category->id,
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
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,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'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>> $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)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
443
app/Domains/FiestaFutbolInfantil/Services/MerchandiseService.php
Normal file
443
app/Domains/FiestaFutbolInfantil/Services/MerchandiseService.php
Normal file
@@ -0,0 +1,443 @@
|
||||
<?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\Tenant\Models\Tenant;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class MerchandiseService
|
||||
{
|
||||
private const ATTRIBUTE_CODES = ['color', 'talle'];
|
||||
|
||||
public function __construct(private readonly CatalogService $catalogService) {}
|
||||
|
||||
/** @return Collection<int, CatalogItem> */
|
||||
public function all(Tenant $tenant): Collection
|
||||
{
|
||||
return CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('category', fn ($query) => $query->where('nombre', 'Merchandising'))
|
||||
->with([
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.catalogItem',
|
||||
'variants.inventory',
|
||||
'variants.definitions',
|
||||
])
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @return Collection<int, CatalogItem>
|
||||
*/
|
||||
public function upsertMany(Tenant $tenant, array $items): Collection
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $items): Collection {
|
||||
$attributes = $this->attributes($tenant);
|
||||
$category = Category::query()->firstOrCreate([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'nombre' => 'Merchandising',
|
||||
]);
|
||||
$reservedSlugs = [];
|
||||
|
||||
return collect($items)->map(function (array $data, int $index) use (
|
||||
$tenant,
|
||||
$attributes,
|
||||
$category,
|
||||
&$reservedSlugs,
|
||||
): CatalogItem {
|
||||
$item = isset($data['id'])
|
||||
? $this->existingItem($tenant, $category, (int) $data['id'], $index)
|
||||
: $this->createItem($tenant, $category, $data, $reservedSlugs);
|
||||
|
||||
if (! isset($data['id'])) {
|
||||
$reservedSlugs[] = $item->slug;
|
||||
}
|
||||
|
||||
$item->update([
|
||||
'nombre' => trim($data['title']),
|
||||
'descripcion' => $data['description'] ?? null,
|
||||
'category_id' => $category->id,
|
||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
]);
|
||||
|
||||
$itemAttributes = $this->itemAttributes($item, $attributes);
|
||||
$existingVariants = $item->variants()
|
||||
->with(['inventory', 'definitions'])
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$variants = $this->resolveVariants($data['variants'], $attributes, $index);
|
||||
|
||||
$this->validateCombinations($variants, $existingVariants, $itemAttributes, $index);
|
||||
|
||||
foreach ($variants as $variantIndex => $variantData) {
|
||||
$variant = isset($variantData['id'])
|
||||
? $existingVariants->firstWhere('id', (int) $variantData['id'])
|
||||
: null;
|
||||
|
||||
if (isset($variantData['id']) && $variant === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"items.{$index}.variants.{$variantIndex}.id" => [
|
||||
'La variante no pertenece al artículo de merchandising.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($variant === null) {
|
||||
$this->createVariant($item, $itemAttributes, $variantData);
|
||||
} else {
|
||||
$this->updateVariant($variant, $itemAttributes, $variantData, $index, $variantIndex);
|
||||
}
|
||||
}
|
||||
|
||||
$minimumPrice = $item->variants()->min('precio');
|
||||
if ($minimumPrice !== null) {
|
||||
$item->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
|
||||
return $item->fresh()->load([
|
||||
'itemAttributes.attribute.options',
|
||||
'variants.catalogItem',
|
||||
'variants.inventory',
|
||||
'variants.definitions',
|
||||
]);
|
||||
})->values();
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(Tenant $tenant, int $merchandiseId): void
|
||||
{
|
||||
$variant = Variant::query()
|
||||
->whereKey($merchandiseId)
|
||||
->whereHas('catalogItem', fn ($query) => $query
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->whereHas('category', fn ($categoryQuery) => $categoryQuery
|
||||
->where('nombre', 'Merchandising')))
|
||||
->firstOrFail();
|
||||
|
||||
$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')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('codigo');
|
||||
|
||||
$missingCodes = collect(self::ATTRIBUTE_CODES)->diff($attributes->keys());
|
||||
if ($missingCodes->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => [
|
||||
'Faltan atributos requeridos para merchandising: '.$missingCodes->implode(', ').'.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
private function existingItem(
|
||||
Tenant $tenant,
|
||||
Category $category,
|
||||
int $itemId,
|
||||
int $index,
|
||||
): CatalogItem {
|
||||
$item = CatalogItem::query()
|
||||
->whereKey($itemId)
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('category_id', $category->id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($item === null) {
|
||||
throw ValidationException::withMessages([
|
||||
"items.{$index}.id" => ['El artículo no pertenece al merchandising del tenant.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<int, string> $reservedSlugs
|
||||
*/
|
||||
private function createItem(
|
||||
Tenant $tenant,
|
||||
Category $category,
|
||||
array $data,
|
||||
array $reservedSlugs,
|
||||
): CatalogItem {
|
||||
return CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => $this->uniqueSlug($tenant, $data['title'], $reservedSlugs),
|
||||
'nombre' => trim($data['title']),
|
||||
'descripcion' => $data['description'] ?? null,
|
||||
'category_id' => $category->id,
|
||||
'precio' => collect($data['variants'])->min('price') ?? 0,
|
||||
'max_units_per_user' => (int) $data['max_units_per_user'],
|
||||
'inventory_policy' => InventoryPolicy::Tracked->value,
|
||||
'has_tickets' => true,
|
||||
'ticket_generation_policy' => TicketGenerationPolicy::OnePerUnit->value,
|
||||
'inventory_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<string, Attribute> $attributes
|
||||
* @return Collection<string, ItemAttribute>
|
||||
*/
|
||||
private function itemAttributes(CatalogItem $item, Collection $attributes): Collection
|
||||
{
|
||||
return $attributes->mapWithKeys(function (Attribute $attribute, string $code) use ($item): array {
|
||||
$itemAttribute = $item->itemAttributes()->firstOrCreate(
|
||||
['attribute_id' => $attribute->id],
|
||||
['allow_multi_select' => false],
|
||||
);
|
||||
|
||||
if ($itemAttribute->allow_multi_select) {
|
||||
$itemAttribute->update(['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, int $itemIndex): array
|
||||
{
|
||||
return collect($variants)->map(function (array $variant, int $variantIndex) use (
|
||||
$attributes,
|
||||
$itemIndex,
|
||||
): array {
|
||||
$color = $this->resolveColor($attributes['color'], $variant['color']);
|
||||
$size = $this->existingOption(
|
||||
$attributes['talle'],
|
||||
$variant['size'],
|
||||
"items.{$itemIndex}.variants.{$variantIndex}.size",
|
||||
);
|
||||
|
||||
return [
|
||||
...$variant,
|
||||
'color' => $color->value,
|
||||
'size' => $size->value,
|
||||
'stock' => (int) $variant['stock'],
|
||||
];
|
||||
})->all();
|
||||
}
|
||||
|
||||
private function resolveColor(Attribute $attribute, string $color): AttributeOption
|
||||
{
|
||||
$option = $this->findOption($attribute, $color);
|
||||
if ($option !== null) {
|
||||
return $option;
|
||||
}
|
||||
|
||||
$label = trim($color);
|
||||
$option = $attribute->options()->create([
|
||||
'value' => $this->valueCode($label),
|
||||
'label' => $label,
|
||||
'sort_order' => ((int) $attribute->options->max('sort_order')) + 1,
|
||||
]);
|
||||
$attribute->options->push($option);
|
||||
|
||||
return $option;
|
||||
}
|
||||
|
||||
private function existingOption(
|
||||
Attribute $attribute,
|
||||
string $value,
|
||||
string $validationKey,
|
||||
): AttributeOption {
|
||||
$option = $this->findOption($attribute, $value);
|
||||
|
||||
if ($option === null) {
|
||||
throw ValidationException::withMessages([
|
||||
$validationKey => ["El valor seleccionado no es válido para {$attribute->nombre}."],
|
||||
]);
|
||||
}
|
||||
|
||||
return $option;
|
||||
}
|
||||
|
||||
private function findOption(Attribute $attribute, string $value): ?AttributeOption
|
||||
{
|
||||
$key = $this->optionKey($value);
|
||||
|
||||
return $attribute->options->first(
|
||||
fn (AttributeOption $option): bool => $this->optionKey($option->value) === $key
|
||||
|| $this->optionKey($option->label) === $key
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $incoming
|
||||
* @param Collection<int, Variant> $existing
|
||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
||||
*/
|
||||
private function validateCombinations(
|
||||
array $incoming,
|
||||
Collection $existing,
|
||||
Collection $itemAttributes,
|
||||
int $itemIndex,
|
||||
): void {
|
||||
$incomingIds = collect($incoming)->pluck('id')->filter()->map(fn ($id): int => (int) $id);
|
||||
$seen = [];
|
||||
|
||||
foreach ($existing->whereNotIn('id', $incomingIds) as $variant) {
|
||||
$values = $variant->definitions->keyBy('item_attribute_id');
|
||||
$color = $values->get($itemAttributes['color']->id)?->value;
|
||||
$size = $values->get($itemAttributes['talle']->id)?->value;
|
||||
|
||||
if ($color !== null && $size !== null) {
|
||||
$seen[$this->combinationKey($color, $size)] = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($incoming as $variantIndex => $variant) {
|
||||
$key = $this->combinationKey($variant['color'], $variant['size']);
|
||||
|
||||
if (isset($seen[$key])) {
|
||||
throw ValidationException::withMessages([
|
||||
"items.{$itemIndex}.variants.{$variantIndex}" => [
|
||||
'La combinación de color y talle ya existe para el artículo.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[$key] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function createVariant(
|
||||
CatalogItem $item,
|
||||
Collection $itemAttributes,
|
||||
array $data,
|
||||
): void {
|
||||
$inventory = Inventory::query()->create(['real_stock' => $data['stock']]);
|
||||
$variant = $item->variants()->create([
|
||||
'inventory_id' => $inventory->id,
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
$this->syncDefinitions($variant, $itemAttributes, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function updateVariant(
|
||||
Variant $variant,
|
||||
Collection $itemAttributes,
|
||||
array $data,
|
||||
int $itemIndex,
|
||||
int $variantIndex,
|
||||
): void {
|
||||
$inventory = Inventory::query()
|
||||
->whereKey($variant->inventory_id)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
|
||||
if ($data['stock'] < $inventory->reserved_stock) {
|
||||
throw ValidationException::withMessages([
|
||||
"items.{$itemIndex}.variants.{$variantIndex}.stock" => [
|
||||
'El stock no puede ser menor que la cantidad actualmente reservada.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->update(['precio' => $data['price']]);
|
||||
$inventory->update(['real_stock' => $data['stock']]);
|
||||
$this->syncDefinitions($variant, $itemAttributes, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
private function syncDefinitions(
|
||||
Variant $variant,
|
||||
Collection $itemAttributes,
|
||||
array $data,
|
||||
): void {
|
||||
$variant->definitions()
|
||||
->whereIn('item_attribute_id', $itemAttributes->pluck('id'))
|
||||
->delete();
|
||||
$variant->definitions()->createMany([
|
||||
[
|
||||
'item_attribute_id' => $itemAttributes['color']->id,
|
||||
'value' => $data['color'],
|
||||
],
|
||||
[
|
||||
'item_attribute_id' => $itemAttributes['talle']->id,
|
||||
'value' => $data['size'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param array<int, string> $reservedSlugs */
|
||||
private function uniqueSlug(Tenant $tenant, string $title, array $reservedSlugs): string
|
||||
{
|
||||
$baseSlug = Str::slug($title) ?: 'merchandising';
|
||||
$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;
|
||||
}
|
||||
|
||||
private function combinationKey(string $color, string $size): string
|
||||
{
|
||||
return $this->optionKey($color).'|'.$this->optionKey($size);
|
||||
}
|
||||
|
||||
private function optionKey(string $value): string
|
||||
{
|
||||
return Str::ascii(mb_strtolower((string) preg_replace('/[_\s]+/u', ' ', trim($value))));
|
||||
}
|
||||
|
||||
private function valueCode(string $value): string
|
||||
{
|
||||
return mb_strtolower((string) preg_replace('/\s+/u', '_', trim($value)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user