refactor(backend): reorganize domains into Core, Commerce, Ticketing and Shared
This commit is contained in:
302
app/Domains/Ticketing/Desfile/Services/EntryService.php
Normal file
302
app/Domains/Ticketing/Desfile/Services/EntryService.php
Normal file
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Services;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Attachable\Services\AttachmentService;
|
||||
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\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Throwable;
|
||||
|
||||
class EntryService
|
||||
{
|
||||
private const ATTRIBUTE_MAP = [
|
||||
'type' => 'tipo',
|
||||
'sector' => 'sector',
|
||||
'row' => 'fila',
|
||||
'seat' => 'asiento',
|
||||
];
|
||||
|
||||
private const ROW_ATTRIBUTE_MAP = [
|
||||
'type' => 'tipo',
|
||||
'sector' => 'sector',
|
||||
'row' => 'fila',
|
||||
];
|
||||
|
||||
public function __construct(private readonly AttachmentService $attachmentService) {}
|
||||
|
||||
public function current(Tenant $tenant): CatalogItem
|
||||
{
|
||||
return $this->entryQuery($tenant)
|
||||
->with([
|
||||
'allAttachments',
|
||||
'itemAttributes.attribute.options',
|
||||
'variants' => fn ($query) => $query->orderBy('id'),
|
||||
'variants.inventory',
|
||||
'variants.definitions.itemAttribute.attribute',
|
||||
])
|
||||
->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $rows
|
||||
*/
|
||||
public function syncRows(Tenant $tenant, array $rows): CatalogItem
|
||||
{
|
||||
DB::transaction(function () use ($tenant, $rows): void {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$itemAttributes = $this->itemAttributes($entry);
|
||||
$existingVariants = $entry->variants()
|
||||
->with(['inventory', 'definitions.itemAttribute.attribute'])
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$existingBySelection = $existingVariants->keyBy(
|
||||
fn (Variant $variant): string => $this->selectionKey($variant->selectionValues()->all()),
|
||||
);
|
||||
$desiredSelections = collect();
|
||||
|
||||
foreach (array_values($rows) as $index => $data) {
|
||||
$rowValues = $this->resolveRowValues($itemAttributes, $data, $index);
|
||||
|
||||
foreach (range(1, (int) $data['max_seat']) as $seat) {
|
||||
$values = [
|
||||
...$rowValues,
|
||||
'asiento' => $this->resolveAttributeValue(
|
||||
$itemAttributes,
|
||||
'asiento',
|
||||
(string) $seat,
|
||||
"rows.{$index}.max_seat",
|
||||
),
|
||||
];
|
||||
$selectionKey = $this->selectionKey($values);
|
||||
$desiredSelections->put($selectionKey, true);
|
||||
$variant = $existingBySelection->get($selectionKey);
|
||||
|
||||
if ($variant === null) {
|
||||
$variant = $entry->variants()->create([
|
||||
'inventory_id' => Inventory::query()->create(['real_stock' => 1])->id,
|
||||
'descripcion' => $this->description($values),
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
$variant->definitions()->createMany(
|
||||
collect($values)->map(
|
||||
fn (string $value, string $code): array => [
|
||||
'item_attribute_id' => $itemAttributes[$code]->id,
|
||||
'value' => $value,
|
||||
],
|
||||
)->values()->all(),
|
||||
);
|
||||
} else {
|
||||
$variant->update([
|
||||
'descripcion' => $this->description($values),
|
||||
'precio' => $data['price'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($existingVariants as $variant) {
|
||||
$selectionKey = $this->selectionKey($variant->selectionValues()->all());
|
||||
if ($desiredSelections->has($selectionKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->assertVariantCanChangeIdentity($variant, 'rows');
|
||||
$variant->delete();
|
||||
}
|
||||
|
||||
$minimumPrice = $entry->variants()->min('precio');
|
||||
if ($minimumPrice !== null) {
|
||||
$entry->update(['precio' => $minimumPrice]);
|
||||
}
|
||||
});
|
||||
|
||||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function replaceImage(
|
||||
Tenant $tenant,
|
||||
UploadedFile $image,
|
||||
bool $isEnabled,
|
||||
): CatalogItem {
|
||||
$attachment = $this->attachmentService->store($image, 'catalog-items');
|
||||
$previousAttachments = collect();
|
||||
|
||||
try {
|
||||
DB::transaction(function () use ($tenant, $attachment, $isEnabled, &$previousAttachments): void {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$previousAttachments = $entry->allAttachments()->get();
|
||||
$entry->allAttachments()->sync([
|
||||
$attachment->id => [
|
||||
'orden' => 0,
|
||||
'is_enabled' => $isEnabled,
|
||||
],
|
||||
]);
|
||||
});
|
||||
} catch (Throwable $throwable) {
|
||||
$this->deleteAttachmentQuietly($attachment);
|
||||
throw $throwable;
|
||||
}
|
||||
|
||||
$previousAttachments->each(fn (Attachment $previous) => $this->deleteIfUnused($previous));
|
||||
|
||||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function updateImage(Tenant $tenant, bool $isEnabled): CatalogItem
|
||||
{
|
||||
DB::transaction(function () use ($tenant, $isEnabled): void {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
||||
|
||||
$entry->allAttachments()->updateExistingPivot($attachment->id, [
|
||||
'is_enabled' => $isEnabled,
|
||||
]);
|
||||
});
|
||||
|
||||
return $this->current($tenant);
|
||||
}
|
||||
|
||||
public function deleteImage(Tenant $tenant): void
|
||||
{
|
||||
$attachment = DB::transaction(function () use ($tenant): Attachment {
|
||||
$entry = $this->entryQuery($tenant)->lockForUpdate()->firstOrFail();
|
||||
$attachment = $entry->allAttachments()->lockForUpdate()->firstOrFail();
|
||||
$entry->allAttachments()->detach($attachment->id);
|
||||
|
||||
return $attachment;
|
||||
});
|
||||
|
||||
$this->deleteIfUnused($attachment);
|
||||
}
|
||||
|
||||
/** @return Collection<string, ItemAttribute> */
|
||||
private function itemAttributes(CatalogItem $entry): Collection
|
||||
{
|
||||
$attributes = $entry->itemAttributes()
|
||||
->with('attribute.options')
|
||||
->get()
|
||||
->filter(fn (ItemAttribute $itemAttribute): bool => $itemAttribute->attribute !== null)
|
||||
->keyBy(fn (ItemAttribute $itemAttribute): string => $itemAttribute->attribute->codigo);
|
||||
$missing = collect(self::ATTRIBUTE_MAP)->diff($attributes->keys());
|
||||
|
||||
if ($missing->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'rows' => [
|
||||
'Faltan atributos requeridos para las entradas del desfile: '.$missing->implode(', ').'.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<string, ItemAttribute> $itemAttributes
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function resolveRowValues(Collection $itemAttributes, array $data, int $index): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach (self::ROW_ATTRIBUTE_MAP as $input => $code) {
|
||||
$values[$code] = $this->resolveAttributeValue(
|
||||
$itemAttributes,
|
||||
$code,
|
||||
(string) $data[$input],
|
||||
"rows.{$index}.{$input}",
|
||||
);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/** @param Collection<string, ItemAttribute> $itemAttributes */
|
||||
private function resolveAttributeValue(
|
||||
Collection $itemAttributes,
|
||||
string $code,
|
||||
string $requestedValue,
|
||||
string $errorKey,
|
||||
): string {
|
||||
$requestedValue = trim($requestedValue);
|
||||
$option = $itemAttributes[$code]->attribute->options->first(
|
||||
fn ($candidate): bool => $this->normalize($candidate->value) === $this->normalize($requestedValue),
|
||||
);
|
||||
|
||||
if ($option === null) {
|
||||
throw ValidationException::withMessages([
|
||||
$errorKey => ['La opción seleccionada no es válida.'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $option->value;
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $values */
|
||||
private function selectionKey(array $values): string
|
||||
{
|
||||
return collect(self::ATTRIBUTE_MAP)
|
||||
->map(fn (string $code): string => $this->normalize((string) ($values[$code] ?? '')))
|
||||
->implode('|');
|
||||
}
|
||||
|
||||
private function assertVariantCanChangeIdentity(Variant $variant, string $key): void
|
||||
{
|
||||
$inventory = $variant->inventory;
|
||||
|
||||
if (($inventory?->reserved_stock ?? 0) > 0 || ($inventory?->sold_units ?? 0) > 0) {
|
||||
throw ValidationException::withMessages([
|
||||
$key => [
|
||||
'No se puede modificar ni eliminar un asiento con ventas o reservas.',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, string> $values */
|
||||
private function description(array $values): string
|
||||
{
|
||||
return "Sector {$values['sector']} - Fila {$values['fila']} - Asiento {$values['asiento']} - {$values['tipo']}";
|
||||
}
|
||||
|
||||
private function normalize(string $value): string
|
||||
{
|
||||
return Str::ascii(mb_strtolower(trim($value)));
|
||||
}
|
||||
|
||||
/** @return Builder<CatalogItem> */
|
||||
private function entryQuery(Tenant $tenant): Builder
|
||||
{
|
||||
return CatalogItem::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
->where('slug', 'entrada');
|
||||
}
|
||||
|
||||
private function deleteIfUnused(Attachment $attachment): void
|
||||
{
|
||||
if (DB::table('catalog_items_attachments')->where('attachment_id', $attachment->id)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->deleteAttachmentQuietly($attachment);
|
||||
}
|
||||
|
||||
private function deleteAttachmentQuietly(Attachment $attachment): void
|
||||
{
|
||||
try {
|
||||
$this->attachmentService->delete($attachment);
|
||||
} catch (Throwable $throwable) {
|
||||
report($throwable);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Services;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
|
||||
class InvitationPurchaseProvisioner
|
||||
{
|
||||
public const TENANT_CODE = 'desfile_pura_tendencia';
|
||||
|
||||
public const USER_EMAIL = 'invitados@puratendencia.com';
|
||||
|
||||
private const PAYMENT_METHOD = 'invitation';
|
||||
|
||||
/**
|
||||
* @var list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>
|
||||
*/
|
||||
private const ALLOCATIONS = [
|
||||
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
|
||||
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
|
||||
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 17, 'type' => 'VIP + LUNCH'],
|
||||
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>|null $allocations
|
||||
*/
|
||||
public function provision(?array $allocations = null): void
|
||||
{
|
||||
if (! $this->prerequisitesExist()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($allocations): void {
|
||||
$now = now();
|
||||
$userId = $this->userId($now);
|
||||
$purchaseId = $this->purchaseId($userId, $now);
|
||||
$catalogItem = DB::table('catalog_items')
|
||||
->where('tenant_code', self::TENANT_CODE)
|
||||
->where('slug', 'entrada')
|
||||
->first();
|
||||
|
||||
if ($catalogItem === null) {
|
||||
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
|
||||
}
|
||||
|
||||
foreach ($allocations ?? self::ALLOCATIONS as $allocation) {
|
||||
foreach (range($allocation['first_seat'], $allocation['last_seat']) as $seat) {
|
||||
$variant = $this->variant(
|
||||
(int) $catalogItem->id,
|
||||
$allocation['sector'],
|
||||
$allocation['row'],
|
||||
$seat,
|
||||
$allocation['type'],
|
||||
);
|
||||
|
||||
$purchaseItemId = $this->createPurchaseItem(
|
||||
$purchaseId,
|
||||
$catalogItem,
|
||||
$variant,
|
||||
$allocation['sector'],
|
||||
$allocation['row'],
|
||||
$seat,
|
||||
$allocation['type'],
|
||||
$now,
|
||||
);
|
||||
$this->createTicketAndCommitStock(
|
||||
$purchaseId,
|
||||
$purchaseItemId,
|
||||
$userId,
|
||||
(int) $catalogItem->id,
|
||||
$variant,
|
||||
$now,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function prerequisitesExist(): bool
|
||||
{
|
||||
if (! DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! DB::table('roles')->where('codigo', 'user')->exists()) {
|
||||
throw new RuntimeException('No se encontró el rol de usuario común.');
|
||||
}
|
||||
|
||||
if (! DB::table('catalog_items')
|
||||
->where('tenant_code', self::TENANT_CODE)
|
||||
->where('slug', 'entrada')
|
||||
->exists()) {
|
||||
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function userId(DateTimeInterface $now): int
|
||||
{
|
||||
$user = DB::table('users')
|
||||
->where('active_email', self::USER_EMAIL)
|
||||
->where('rol_codigo', 'user')
|
||||
->whereNull('deleted_at')
|
||||
->first();
|
||||
|
||||
if ($user !== null) {
|
||||
if ($user->tenant_codigo !== self::TENANT_CODE) {
|
||||
throw new RuntimeException('El email de invitados ya pertenece a otro tenant.');
|
||||
}
|
||||
|
||||
DB::table('users')->where('id', $user->id)->update([
|
||||
'rol_codigo' => 'user',
|
||||
'nombre_apellido' => 'Invitados Pura Tendencia',
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
return (int) $user->id;
|
||||
}
|
||||
|
||||
return DB::table('users')->insertGetId([
|
||||
'rol_codigo' => 'user',
|
||||
'tenant_codigo' => self::TENANT_CODE,
|
||||
'nombre_apellido' => 'Invitados Pura Tendencia',
|
||||
'email' => self::USER_EMAIL,
|
||||
'email_verified_at' => $now,
|
||||
'password' => Hash::make(Str::random(64)),
|
||||
'dni' => null,
|
||||
'telefono' => null,
|
||||
'remember_token' => null,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
private function purchaseId(int $userId, DateTimeInterface $now): int
|
||||
{
|
||||
$purchaseId = DB::table('compras')
|
||||
->where('tenant_codigo', self::TENANT_CODE)
|
||||
->where('user_id', $userId)
|
||||
->where('payment_method', self::PAYMENT_METHOD)
|
||||
->value('id');
|
||||
|
||||
if ($purchaseId !== null) {
|
||||
DB::table('compras')->where('id', $purchaseId)->update([
|
||||
'status' => 'paid',
|
||||
'total' => 0,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
return (int) $purchaseId;
|
||||
}
|
||||
|
||||
return DB::table('compras')->insertGetId([
|
||||
'tenant_codigo' => self::TENANT_CODE,
|
||||
'user_id' => $userId,
|
||||
'cart_id' => null,
|
||||
'status' => 'paid',
|
||||
'payment_method' => self::PAYMENT_METHOD,
|
||||
'total' => 0,
|
||||
'dni' => null,
|
||||
'transfer_payer_dni' => null,
|
||||
'telefono' => null,
|
||||
'nombre_apellido' => 'Invitados Pura Tendencia',
|
||||
'email' => self::USER_EMAIL,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
private function variant(
|
||||
int $catalogItemId,
|
||||
string $sector,
|
||||
int $row,
|
||||
int $seat,
|
||||
string $type,
|
||||
): object {
|
||||
$variant = $this->findVariant($catalogItemId, $sector, $row, $seat);
|
||||
|
||||
if ($variant === null) {
|
||||
$variant = $this->createVariant($catalogItemId, $sector, $row, $seat, $type);
|
||||
}
|
||||
|
||||
$this->ensureAttributeOptions($catalogItemId, [
|
||||
'tipo' => $type,
|
||||
'sector' => $sector,
|
||||
'fila' => (string) $row,
|
||||
'asiento' => (string) $seat,
|
||||
]);
|
||||
|
||||
$typeValueId = DB::table('variant_values as variant_value')
|
||||
->join('item_attributes as item_attribute', 'item_attribute.id', '=', 'variant_value.item_attribute_id')
|
||||
->join('attribute', 'attribute.id', '=', 'item_attribute.attribute_id')
|
||||
->where('variant_value.variant_id', $variant->id)
|
||||
->where('attribute.codigo', 'tipo')
|
||||
->value('variant_value.id');
|
||||
|
||||
if ($typeValueId === null) {
|
||||
throw new RuntimeException("La variante {$variant->id} no tiene definido el tipo de entrada.");
|
||||
}
|
||||
|
||||
DB::table('variant_values')->where('id', $typeValueId)->update(['value' => $type]);
|
||||
DB::table('variantes')->where('id', $variant->id)->update([
|
||||
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
|
||||
]);
|
||||
|
||||
return DB::table('variantes')->where('id', $variant->id)->first();
|
||||
}
|
||||
|
||||
/** @param array<string, string> $values */
|
||||
private function ensureAttributeOptions(int $catalogItemId, array $values): void
|
||||
{
|
||||
$attributes = DB::table('item_attributes')
|
||||
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||
->where('item_attributes.catalog_item_id', $catalogItemId)
|
||||
->pluck('attribute.id', 'attribute.codigo');
|
||||
|
||||
foreach ($values as $code => $value) {
|
||||
$attributeId = $attributes[$code] ?? null;
|
||||
|
||||
if ($attributeId === null) {
|
||||
throw new RuntimeException("Falta el atributo {$code} en el catálogo de entradas.");
|
||||
}
|
||||
|
||||
if (DB::table('attribute_options')
|
||||
->where('attribute_id', $attributeId)
|
||||
->where('value', $value)
|
||||
->exists()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$lastSortOrder = (int) DB::table('attribute_options')
|
||||
->where('attribute_id', $attributeId)
|
||||
->max('sort_order');
|
||||
|
||||
DB::table('attribute_options')->insert([
|
||||
'attribute_id' => $attributeId,
|
||||
'validity_time_id' => null,
|
||||
'value' => $value,
|
||||
'label' => $value,
|
||||
'sort_order' => $lastSortOrder + 1,
|
||||
'metadata' => null,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function findVariant(int $catalogItemId, string $sector, int $row, int $seat): ?object
|
||||
{
|
||||
$query = DB::table('variantes')->where('catalog_item_id', $catalogItemId);
|
||||
|
||||
foreach (['sector' => $sector, 'fila' => (string) $row, 'asiento' => (string) $seat] as $code => $value) {
|
||||
$query->whereExists(fn ($subquery) => $subquery
|
||||
->selectRaw('1')
|
||||
->from('variant_values as selected_value')
|
||||
->join('item_attributes as selected_item_attribute', 'selected_item_attribute.id', '=', 'selected_value.item_attribute_id')
|
||||
->join('attribute as selected_attribute', 'selected_attribute.id', '=', 'selected_item_attribute.attribute_id')
|
||||
->whereColumn('selected_value.variant_id', 'variantes.id')
|
||||
->where('selected_attribute.codigo', $code)
|
||||
->where('selected_value.value', $value));
|
||||
}
|
||||
|
||||
return $query->first();
|
||||
}
|
||||
|
||||
private function createVariant(
|
||||
int $catalogItemId,
|
||||
string $sector,
|
||||
int $row,
|
||||
int $seat,
|
||||
string $type,
|
||||
): object {
|
||||
$itemAttributes = DB::table('item_attributes')
|
||||
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||
->where('item_attributes.catalog_item_id', $catalogItemId)
|
||||
->pluck('item_attributes.id', 'attribute.codigo');
|
||||
|
||||
foreach (['tipo', 'sector', 'fila', 'asiento'] as $requiredCode) {
|
||||
if (! isset($itemAttributes[$requiredCode])) {
|
||||
throw new RuntimeException("Falta el atributo {$requiredCode} en el catálogo de entradas.");
|
||||
}
|
||||
}
|
||||
|
||||
$inventoryId = DB::table('inventories')->insertGetId([
|
||||
'sold_units' => 0,
|
||||
'reserved_stock' => 0,
|
||||
'real_stock' => 1,
|
||||
]);
|
||||
$variantId = DB::table('variantes')->insertGetId([
|
||||
'catalog_item_id' => $catalogItemId,
|
||||
'event_date_id' => null,
|
||||
'inventory_id' => $inventoryId,
|
||||
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
|
||||
'precio' => $this->catalogPrice($sector, $row),
|
||||
]);
|
||||
|
||||
foreach (['tipo' => $type, 'sector' => $sector, 'fila' => (string) $row, 'asiento' => (string) $seat] as $code => $value) {
|
||||
DB::table('variant_values')->insert([
|
||||
'variant_id' => $variantId,
|
||||
'item_attribute_id' => $itemAttributes[$code],
|
||||
'value' => $value,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
return DB::table('variantes')->where('id', $variantId)->first();
|
||||
}
|
||||
|
||||
private function catalogPrice(string $sector, int $row): int
|
||||
{
|
||||
$prices = in_array($sector, ['A', 'C'], true)
|
||||
? [1 => 250000, 2 => 200000, 3 => 100000, 4 => 75000, 5 => 50000]
|
||||
: [1 => 240000, 2 => 190000, 3 => 90000, 4 => 65000, 5 => 40000];
|
||||
|
||||
return $prices[$row];
|
||||
}
|
||||
|
||||
private function createPurchaseItem(
|
||||
int $purchaseId,
|
||||
object $catalogItem,
|
||||
object $variant,
|
||||
string $sector,
|
||||
int $row,
|
||||
int $seat,
|
||||
string $type,
|
||||
DateTimeInterface $now,
|
||||
): int {
|
||||
$existingId = DB::table('compra_items')
|
||||
->where('compra_id', $purchaseId)
|
||||
->where('source_variant_id', $variant->id)
|
||||
->value('id');
|
||||
if ($existingId !== null) {
|
||||
return (int) $existingId;
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
['name' => 'Tipo', 'value' => $type],
|
||||
['name' => 'Sector', 'value' => $sector],
|
||||
['name' => 'Fila', 'value' => (string) $row],
|
||||
['name' => 'Asiento', 'value' => (string) $seat],
|
||||
];
|
||||
|
||||
return DB::table('compra_items')->insertGetId([
|
||||
'compra_id' => $purchaseId,
|
||||
'source_catalog_item_id' => $catalogItem->id,
|
||||
'source_variant_id' => $variant->id,
|
||||
'image_attachment_id' => DB::table('catalog_items_attachments')
|
||||
->where('catalog_item_id', $catalogItem->id)
|
||||
->whereNull('variant_id')
|
||||
->orderBy('orden')
|
||||
->value('attachment_id'),
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $variant->descripcion,
|
||||
'slug' => $catalogItem->slug,
|
||||
'item_nombre' => "Entrada (Sector {$sector}, Fila {$row}, Asiento {$seat})",
|
||||
'variant_attributes' => json_encode($attributes, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => 0,
|
||||
'discount_total' => 0,
|
||||
'tax_total' => 0,
|
||||
'total' => 0,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createTicketAndCommitStock(
|
||||
int $purchaseId,
|
||||
int $purchaseItemId,
|
||||
int $userId,
|
||||
int $catalogItemId,
|
||||
object $variant,
|
||||
DateTimeInterface $now,
|
||||
): void {
|
||||
$purchaseReference = Schema::hasColumn('tickets', 'source_purchase_item_id')
|
||||
? ['source_purchase_item_id' => $purchaseItemId]
|
||||
: ['source_purchase_id' => $purchaseId];
|
||||
|
||||
if (DB::table('tickets')
|
||||
->where($purchaseReference)
|
||||
->where('source_variant_id', $variant->id)
|
||||
->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->lockForUpdate()->first();
|
||||
|
||||
if ($inventory === null || $inventory->real_stock < 1 || $inventory->reserved_stock > 0) {
|
||||
throw new RuntimeException("El asiento {$variant->descripcion} ya no está disponible.");
|
||||
}
|
||||
|
||||
DB::table('inventories')->where('id', $inventory->id)->update([
|
||||
'real_stock' => $inventory->real_stock - 1,
|
||||
'sold_units' => $inventory->sold_units + 1,
|
||||
]);
|
||||
|
||||
$reservationId = DB::table('compras')->where('id', $purchaseId)->value('stock_reservation_id');
|
||||
if ($reservationId === null) {
|
||||
$reservationId = DB::table('stock_reservations')->insertGetId([
|
||||
'status' => 'committed',
|
||||
'committed_at' => $now,
|
||||
'released_at' => null,
|
||||
'expired_at' => null,
|
||||
'release_reason' => null,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
DB::table('compras')->where('id', $purchaseId)->update([
|
||||
'stock_reservation_id' => $reservationId,
|
||||
]);
|
||||
}
|
||||
|
||||
DB::table('stock_reservation_lines')->insert([
|
||||
'stock_reservation_id' => $reservationId,
|
||||
'inventory_id' => $inventory->id,
|
||||
'quantity' => 1,
|
||||
'tracks_inventory' => true,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
DB::table('tickets')->insert([
|
||||
'tenant_code' => self::TENANT_CODE,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'name' => null,
|
||||
'description' => null,
|
||||
...$purchaseReference,
|
||||
'source_catalog_item_id' => $catalogItemId,
|
||||
'source_variant_id' => $variant->id,
|
||||
'used_at' => null,
|
||||
'scanner_user_id' => null,
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user