Compare commits
42 Commits
tenant/des
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bc57cf0ff | |||
| a78c5cee58 | |||
| cc22e33799 | |||
| 5c0b3503b7 | |||
| 8537d2ed0a | |||
| d97cc12af6 | |||
| 7a19b3a97a | |||
| a94ac7a473 | |||
| 161693509f | |||
| 93c99afb13 | |||
| 32d2b182c6 | |||
| 2632a80722 | |||
| 3cee9c28f8 | |||
| 2091b1361a | |||
| a2c5e687f9 | |||
| 172e14ae9b | |||
| 58cbeae9d3 | |||
| 1dc4e29c69 | |||
| 093e894cc3 | |||
| fdf0f3328f | |||
| 8d6bcdcc43 | |||
| 3206e293eb | |||
| aed99bd05e | |||
| f1649e0e4b | |||
| e6c4b40a37 | |||
| 15878cd9ba | |||
| d6574bfd0d | |||
| 16bc657a31 | |||
| 7cea8d3495 | |||
| 014b5bb012 | |||
| 67e6211857 | |||
| 58471cb13d | |||
| 864bed0113 | |||
| ced7d594e8 | |||
| 38e87fff6c | |||
| a8973f6171 | |||
| 8e26611097 | |||
| 817d0de6d2 | |||
| a2298c9de2 | |||
| d73b4d1daf | |||
| e6785eb5af | |||
| 1a3f564afd |
@@ -8,6 +8,7 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
|
||||
PURCHASE_QR_EXPIRATION_MINUTES=15
|
||||
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
|
||||
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
|
||||
STOCK_RESERVATION_EXPIRATION_MINUTES=30
|
||||
FRONTEND_URLS=http://localhost:4200
|
||||
|
||||
APP_LOCALE=es
|
||||
@@ -31,10 +32,15 @@ AUTH_LOGIN_LOCK_MINUTES=15
|
||||
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
|
||||
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_CHANNEL=daily
|
||||
LOG_STACK=single
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
LOG_DAILY_DAYS=14
|
||||
TELEPAGOS_LOG_LEVEL=info
|
||||
TELEPAGOS_LOG_DAYS=30
|
||||
COMMANDS_LOG_LEVEL=info
|
||||
COMMANDS_LOG_DAYS=30
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
22
app/Domains/Auth/Services/AdminCredentialVerifier.php
Normal file
22
app/Domains/Auth/Services/AdminCredentialVerifier.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Auth\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class AdminCredentialVerifier
|
||||
{
|
||||
public function verify(string $email, string $password): bool
|
||||
{
|
||||
$admin = User::query()
|
||||
->where('email', mb_strtolower(trim($email)))
|
||||
->where('rol_codigo', RoleCode::Admin->value)
|
||||
->first();
|
||||
|
||||
return $admin !== null
|
||||
&& ! $admin->locked_until?->isFuture()
|
||||
&& Hash::check($password, $admin->getAuthPassword());
|
||||
}
|
||||
}
|
||||
@@ -155,16 +155,19 @@ class GoogleAuthService
|
||||
$parts = parse_url($returnUrl);
|
||||
if (! is_array($parts)
|
||||
|| ! isset($parts['scheme'], $parts['host'])
|
||||
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|
||||
|| ($parts['path'] ?? '') !== '') {
|
||||
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$scheme = strtolower($parts['scheme']);
|
||||
$host = TenantDomainNormalizer::normalize($parts['host']);
|
||||
$tenantDomain = TenantDomainNormalizer::normalize($tenant->dominio);
|
||||
$returnPath = TenantDomainNormalizer::normalizePath($parts['path'] ?? '/');
|
||||
|
||||
if ($host === null || $tenantDomain === null || $host !== $tenantDomain) {
|
||||
if ($host === null
|
||||
|| $tenantDomain === null
|
||||
|| $host !== $tenantDomain
|
||||
|| $returnPath !== $tenant->base_path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -14,14 +14,15 @@ class TenantBootstrapService
|
||||
|
||||
public function get(string $domain, string $path = '/'): Tenant
|
||||
{
|
||||
$candidateKeys = TenantDomainNormalizer::tenantKeyCandidates($domain, $path);
|
||||
$tenantsByDomain = Tenant::query()
|
||||
->whereIn('dominio', $candidateKeys)
|
||||
$candidateBasePaths = TenantDomainNormalizer::basePathCandidates($path);
|
||||
$tenantsByBasePath = Tenant::query()
|
||||
->where('dominio', $domain)
|
||||
->whereIn('base_path', $candidateBasePaths)
|
||||
->get()
|
||||
->keyBy('dominio');
|
||||
->keyBy('base_path');
|
||||
|
||||
$tenant = collect($candidateKeys)
|
||||
->map(fn (string $candidate): ?Tenant => $tenantsByDomain->get($candidate))
|
||||
$tenant = collect($candidateBasePaths)
|
||||
->map(fn (string $candidate): ?Tenant => $tenantsByBasePath->get($candidate))
|
||||
->first(fn (?Tenant $candidate): bool => $candidate !== null);
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Cart\Controllers;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Cart\Requests\AddCartItemRequest;
|
||||
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
|
||||
@@ -77,6 +78,36 @@ class CartController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateCheckoutItem(
|
||||
UpdateCartItemQuantityRequest $request,
|
||||
Tenant $tenant,
|
||||
Cart $cart,
|
||||
CartItem $cartItem,
|
||||
): CartResource {
|
||||
$updatesVariant = $request->exists('variant_id');
|
||||
|
||||
return CartResource::make(
|
||||
$this->cartService->updateCheckoutItem(
|
||||
$tenant,
|
||||
$request,
|
||||
$cart,
|
||||
$cartItem->getKey(),
|
||||
(int) $request->validated('cantidad'),
|
||||
$updatesVariant
|
||||
? ($request->validated('variant_id') !== null
|
||||
? (int) $request->validated('variant_id')
|
||||
: null)
|
||||
: $cartItem->variant_id,
|
||||
$updatesVariant,
|
||||
),
|
||||
)->additional([
|
||||
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
|
||||
'message' => $updatesVariant
|
||||
? __('api.cart.item_updated')
|
||||
: __('api.cart.quantity_updated'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
|
||||
{
|
||||
return CartResource::make(
|
||||
|
||||
@@ -7,6 +7,8 @@ use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
@@ -24,6 +26,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
'user_id',
|
||||
'guest_token',
|
||||
'status',
|
||||
'origin',
|
||||
])]
|
||||
class Cart extends Model
|
||||
{
|
||||
@@ -32,6 +35,10 @@ class Cart extends Model
|
||||
|
||||
protected $table = 'carritos';
|
||||
|
||||
public const ORIGIN_USER = 'user';
|
||||
|
||||
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
@@ -63,6 +70,12 @@ class Cart extends Model
|
||||
return $this->hasMany(CartItem::class, 'cart_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Purchase, $this> */
|
||||
public function purchases(): HasMany
|
||||
{
|
||||
return $this->hasMany(Purchase::class, 'cart_id');
|
||||
}
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
$items = $this->relationLoaded('items')
|
||||
@@ -90,9 +103,14 @@ class Cart extends Model
|
||||
$cartQuantity = (int) $this->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->sum('cantidad');
|
||||
$this->assertUserPurchaseLimit($selectedItem, $cartQuantity + $quantity);
|
||||
$inventoryService = app(CatalogInventoryService::class);
|
||||
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
|
||||
$this->assertUserPurchaseLimit(
|
||||
$selectedItem,
|
||||
$cartQuantity + $quantity,
|
||||
heldQuantity: $cartQuantity,
|
||||
maximumAddableCeiling: $availableQuantity,
|
||||
);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -114,11 +132,12 @@ class Cart extends Model
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
} else {
|
||||
app(StockReservationService::class)->ensure($item, $selectedItem);
|
||||
$item->cantidad += $quantity;
|
||||
$item->save();
|
||||
}
|
||||
|
||||
$inventoryService->reserve($selectedItem, $quantity);
|
||||
app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
@@ -129,6 +148,7 @@ class Cart extends Model
|
||||
int $quantity,
|
||||
?int $variantId = null,
|
||||
bool $updateVariant = false,
|
||||
?int $excludedPurchaseId = null,
|
||||
): CartItem {
|
||||
if ($quantity <= 0) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -141,6 +161,7 @@ class Cart extends Model
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
$excludedPurchaseId,
|
||||
): CartItem {
|
||||
/** @var CartItem $item */
|
||||
$item = $this->items()
|
||||
@@ -165,12 +186,16 @@ class Cart extends Model
|
||||
->where('catalog_item_id', $item->catalog_item_id)
|
||||
->whereKeyNot($item->getKey())
|
||||
->sum('cantidad');
|
||||
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||
$this->assertUserPurchaseLimit(
|
||||
$nextSelection,
|
||||
$otherVariantsQuantity + $quantity,
|
||||
$excludedPurchaseId,
|
||||
$otherVariantsQuantity + $item->cantidad,
|
||||
$nextAvailableQuantity,
|
||||
);
|
||||
|
||||
$inventoryService->release($currentSelection, $item->cantidad);
|
||||
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
||||
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
|
||||
|
||||
if ($availableQuantity !== null && $availableQuantity < $quantity) {
|
||||
@@ -186,11 +211,11 @@ class Cart extends Model
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
$inventoryService->reserve($nextSelection, $quantity);
|
||||
|
||||
if ($targetItem !== null) {
|
||||
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
|
||||
$targetItem->cantidad += $quantity;
|
||||
$targetItem->save();
|
||||
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
|
||||
$item->delete();
|
||||
|
||||
return $targetItem->fresh();
|
||||
@@ -199,11 +224,13 @@ class Cart extends Model
|
||||
$item->variant_id = $variantId;
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
|
||||
|
||||
return $item->fresh();
|
||||
}
|
||||
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
||||
|
||||
if ($delta > 0) {
|
||||
$otherVariantsQuantity = (int) $this->items()
|
||||
@@ -213,11 +240,12 @@ class Cart extends Model
|
||||
$this->assertUserPurchaseLimit(
|
||||
$currentSelection,
|
||||
$otherVariantsQuantity + $quantity,
|
||||
$excludedPurchaseId,
|
||||
$otherVariantsQuantity + $item->cantidad,
|
||||
$availableQuantity,
|
||||
);
|
||||
}
|
||||
|
||||
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
||||
|
||||
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
|
||||
$maxAvailable = $availableQuantity + $item->cantidad;
|
||||
throw ValidationException::withMessages([
|
||||
@@ -225,17 +253,17 @@ class Cart extends Model
|
||||
]);
|
||||
}
|
||||
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
|
||||
if ($delta > 0) {
|
||||
$inventoryService->reserve($currentSelection, $delta);
|
||||
app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
|
||||
}
|
||||
|
||||
if ($delta < 0) {
|
||||
$inventoryService->release($currentSelection, abs($delta));
|
||||
app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
|
||||
}
|
||||
|
||||
$item->cantidad = $quantity;
|
||||
$item->save();
|
||||
|
||||
return $item->fresh();
|
||||
});
|
||||
}
|
||||
@@ -254,7 +282,8 @@ class Cart extends Model
|
||||
$item->variant_id,
|
||||
true,
|
||||
);
|
||||
app(CatalogInventoryService::class)->release(
|
||||
app(StockReservationService::class)->release(
|
||||
$item,
|
||||
$selectedItem,
|
||||
$item->cantidad,
|
||||
);
|
||||
@@ -334,6 +363,9 @@ class Cart extends Model
|
||||
private function assertUserPurchaseLimit(
|
||||
CatalogItem|Variant $selectedItem,
|
||||
int $cartQuantity,
|
||||
?int $excludedPurchaseId = null,
|
||||
int $heldQuantity = 0,
|
||||
?int $maximumAddableCeiling = null,
|
||||
): void {
|
||||
if ($this->user_id === null) {
|
||||
return;
|
||||
@@ -347,6 +379,10 @@ class Cart extends Model
|
||||
$catalogItem,
|
||||
$this->user_id,
|
||||
$cartQuantity,
|
||||
$excludedPurchaseId,
|
||||
$this->getKey(),
|
||||
$heldQuantity,
|
||||
$maximumAddableCeiling,
|
||||
field: 'cantidad',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
namespace App\Domains\Cart\Models;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
@@ -55,4 +57,10 @@ class CartItem extends Model
|
||||
{
|
||||
return $this->variant ?? $this->catalogItem;
|
||||
}
|
||||
|
||||
/** @return HasMany<StockReservation, $this> */
|
||||
public function stockReservations(): HasMany
|
||||
{
|
||||
return $this->hasMany(StockReservation::class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -19,12 +21,16 @@ class CartItemResource extends JsonResource
|
||||
{
|
||||
$selectedItem = $this->selectedItem();
|
||||
$imageUrl = null;
|
||||
$tenant = $request->route('tenant');
|
||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||
$includeVariants = $tenant instanceof Tenant
|
||||
&& $tenant->cart_editing_policy->allowsVariantChanges();
|
||||
|
||||
if ($selectedItem?->relationLoaded('attachments')) {
|
||||
if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||
if ($displayImage && $imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
@@ -36,14 +42,27 @@ class CartItemResource extends JsonResource
|
||||
'variant_id' => $this->variant_id,
|
||||
'nombre' => $selectedItem?->getName(),
|
||||
'imagen' => $imageUrl,
|
||||
'variant' => $this->variant === null ? null : [
|
||||
'id' => $this->variant->id,
|
||||
'precio' => $this->formatMoney($this->variant->getPrice()),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $this->variant->inventory->availableStock(),
|
||||
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
],
|
||||
'variant' => $this->variant === null ? null : $this->variantData($this->variant),
|
||||
'variants' => $this->when(
|
||||
$includeVariants,
|
||||
fn () => $this->catalogItem
|
||||
->visibleVariants($this->variant_id)
|
||||
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||
->values(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
protected function variantData(Variant $variant): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'precio' => $this->formatMoney($variant->precio ?? $this->catalogItem->precio),
|
||||
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -4,15 +4,24 @@ namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CartService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
) {}
|
||||
|
||||
public function show(Tenant $tenant, Request $request): Cart
|
||||
{
|
||||
$resolvedIdentity = $this->resolveIdentity($request);
|
||||
@@ -27,7 +36,7 @@ class CartService
|
||||
return $this->makeEmptyCart($tenant);
|
||||
}
|
||||
|
||||
return $this->loadCart($cart);
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,7 +55,7 @@ class CartService
|
||||
$cart->addItem($catalogItemId, $variantId, $quantity);
|
||||
|
||||
return [
|
||||
'cart' => $this->loadCart($cart),
|
||||
'cart' => $this->loadCart($cart, $tenant),
|
||||
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
||||
];
|
||||
}
|
||||
@@ -59,20 +68,139 @@ class CartService
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Cart {
|
||||
if ($updateVariant && ! $tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.variant_change_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $updateVariant && ! $tenant->cart_editing_policy->allowsQuantityChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
public function updateCheckoutItem(
|
||||
Tenant $tenant,
|
||||
Request $request,
|
||||
Cart $cart,
|
||||
int $cartItemId,
|
||||
int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Cart {
|
||||
$user = $request->user() ?? Auth::guard('sanctum')->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use (
|
||||
$tenant,
|
||||
$user,
|
||||
$cart,
|
||||
$cartItemId,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
): Cart {
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->where('cart_id', $cart->getKey())
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $user->getKey())
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
])
|
||||
->whereDoesntHave('items')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($purchase === null) {
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart' => __('api.purchase.not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var Cart|null $checkoutCart */
|
||||
$checkoutCart = Cart::query()
|
||||
->whereKey($cart->getKey())
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $user->getKey())
|
||||
->where('status', 'checkout')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($checkoutCart === null) {
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
/** @var CartItem|null $cartItem */
|
||||
$cartItem = $checkoutCart->items()
|
||||
->whereKey($cartItemId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($cartItem === null) {
|
||||
throw new NotFoundHttpException('Checkout item not found.');
|
||||
}
|
||||
|
||||
$hasChanges = (int) $cartItem->cantidad !== $quantity
|
||||
|| ($updateVariant && $cartItem->variant_id !== $variantId);
|
||||
|
||||
if (! $hasChanges) {
|
||||
return $this->loadCart($checkoutCart);
|
||||
}
|
||||
|
||||
$checkoutCart->updateItem(
|
||||
$cartItemId,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
$purchase->getKey(),
|
||||
);
|
||||
|
||||
$purchase->telepagosQr()->delete();
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'transfer_payer_dni' => null,
|
||||
'total' => $checkoutCart->getTotalAmount(),
|
||||
'expires_at' => now()->addMinutes(
|
||||
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
||||
),
|
||||
]);
|
||||
$this->reservations->syncPurchaseExpiration($purchase);
|
||||
|
||||
return $this->loadCart($checkoutCart);
|
||||
});
|
||||
}
|
||||
|
||||
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
||||
{
|
||||
if (! $tenant->cart_editing_policy->allowsRemoval()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_item' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$identity = $this->requireIdentity($request);
|
||||
$cart = $this->findCartOrFail($tenant, $identity);
|
||||
$cart->removeItem($cartItemId);
|
||||
|
||||
return $this->loadCart($cart);
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
public function makeGuestTokenCookie(string $guestToken): Cookie
|
||||
@@ -102,9 +230,9 @@ class CartService
|
||||
return $cart;
|
||||
}
|
||||
|
||||
protected function loadCart(Cart $cart): Cart
|
||||
protected function loadCart(Cart $cart, Tenant $tenant): Cart
|
||||
{
|
||||
return $cart->fresh()->load([
|
||||
$relations = [
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.catalogItem.itemAttributes.attribute',
|
||||
@@ -113,7 +241,21 @@ class CartService
|
||||
'items.variant.definitions.itemAttribute.attribute.options',
|
||||
'items.variant.eventDates',
|
||||
'items.variant.eventDate',
|
||||
]);
|
||||
];
|
||||
|
||||
if ($tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||
$relations = [
|
||||
...$relations,
|
||||
'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
|
||||
'items.catalogItem.variants.inventory',
|
||||
'items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'items.catalogItem.variants.eventDates',
|
||||
'items.catalogItem.variants.eventDate',
|
||||
];
|
||||
}
|
||||
|
||||
return $cart->fresh()->load($relations);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
123
app/Domains/Cart/Services/ExpireCartReservationsService.php
Normal file
123
app/Domains/Cart/Services/ExpireCartReservationsService.php
Normal file
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Cart\Services;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ExpireCartReservationsService
|
||||
{
|
||||
public function expireOverdue(): int
|
||||
{
|
||||
$expiredItems = 0;
|
||||
$lastCartItemId = 0;
|
||||
|
||||
do {
|
||||
$cartItemIds = StockReservation::query()
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->whereNull('purchase_id')
|
||||
->whereNotNull('cart_item_id')
|
||||
->whereNotNull('expires_at')
|
||||
->where('expires_at', '<=', now())
|
||||
->where('cart_item_id', '>', $lastCartItemId)
|
||||
->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
|
||||
->select('cart_item_id')
|
||||
->distinct()
|
||||
->orderBy('cart_item_id')
|
||||
->limit(500)
|
||||
->pluck('cart_item_id');
|
||||
|
||||
foreach ($cartItemIds as $cartItemId) {
|
||||
$lastCartItemId = (int) $cartItemId;
|
||||
|
||||
if ($this->expireCartItem($lastCartItemId)) {
|
||||
$expiredItems++;
|
||||
}
|
||||
}
|
||||
} while ($cartItemIds->count() === 500);
|
||||
|
||||
return $expiredItems;
|
||||
}
|
||||
|
||||
private function expireCartItem(int $cartItemId): bool
|
||||
{
|
||||
/** @var CartItem|null $candidate */
|
||||
$candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
|
||||
if ($candidate === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($candidate, $cartItemId): bool {
|
||||
/** @var Cart|null $cart */
|
||||
$cart = Cart::query()
|
||||
->whereKey($candidate->cart_id)
|
||||
->where('status', 'active')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($cart === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var CartItem|null $cartItem */
|
||||
$cartItem = $cart->items()
|
||||
->whereKey($cartItemId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($cartItem === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$reservations = StockReservation::query()
|
||||
->where('cart_item_id', $cartItem->getKey())
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->orderBy('inventory_id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
if (
|
||||
$reservations->isEmpty()
|
||||
|| $reservations->contains(
|
||||
fn (StockReservation $reservation): bool => $reservation->purchase_id !== null
|
||||
|| $reservation->expires_at === null
|
||||
|| $reservation->expires_at->isFuture(),
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$inventories = Inventory::query()
|
||||
->whereKey($reservations->pluck('inventory_id'))
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->get()
|
||||
->keyBy('id');
|
||||
|
||||
foreach ($reservations as $reservation) {
|
||||
$inventory = $inventories->get($reservation->inventory_id)
|
||||
?? throw new \InvalidArgumentException('No se encontro el inventario reservado.');
|
||||
|
||||
$inventory->release((int) $reservation->quantity);
|
||||
$reservation->update([
|
||||
'quantity' => 0,
|
||||
'status' => StockReservation::STATUS_EXPIRED,
|
||||
'expires_at' => null,
|
||||
'released_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItem->delete();
|
||||
|
||||
if (! $cart->items()->exists()) {
|
||||
$cart->update(['status' => 'expired']);
|
||||
$cart->delete();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,10 @@ class GuestCartMergeService
|
||||
->first();
|
||||
|
||||
if ($userCart !== null) {
|
||||
$userCart->items()
|
||||
->orderBy('id')
|
||||
->pluck('id')
|
||||
->each(fn (int $itemId) => $userCart->removeItem($itemId));
|
||||
$userCart->update([
|
||||
'status' => 'converted',
|
||||
]);
|
||||
|
||||
@@ -7,11 +7,12 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
|
||||
## Modelo
|
||||
|
||||
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
|
||||
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; expone la selección efectiva.
|
||||
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo.
|
||||
|
||||
## Servicios
|
||||
|
||||
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
|
||||
- `ExpireCartReservationsService`: libera las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
|
||||
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
|
||||
|
||||
## Endpoints
|
||||
@@ -30,3 +31,7 @@ Bajo `/tenants/{tenant:codigo}`:
|
||||
## Dependencias y reglas
|
||||
|
||||
Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual.
|
||||
|
||||
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
|
||||
|
||||
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.
|
||||
|
||||
@@ -10,3 +10,9 @@ Route::prefix('tenants/{tenant:codigo}')
|
||||
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
|
||||
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
|
||||
});
|
||||
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware('auth:sanctum')
|
||||
->group(function (): void {
|
||||
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem']);
|
||||
});
|
||||
|
||||
@@ -17,17 +17,20 @@ use App\Domains\Catalog\Resources\CatalogItemDetailResource;
|
||||
use App\Domains\Catalog\Resources\CatalogItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogSearchItemResource;
|
||||
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
|
||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Catalog\Services\FeaturedGroupService;
|
||||
use App\Domains\Catalog\Services\VariantSelectionService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CatalogController extends Controller
|
||||
{
|
||||
public function index(Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
|
||||
public function index(Request $request, Tenant $tenant, FeaturedGroupService $featuredGroupService): JsonResponse
|
||||
{
|
||||
$featuredGroups = FeaturedGroup::query()
|
||||
->where('tenant_code', $tenant->codigo)
|
||||
@@ -37,7 +40,7 @@ class CatalogController extends Controller
|
||||
return response()->json($featuredGroups->map(
|
||||
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
|
||||
$featuredGroup,
|
||||
$featuredGroupService->itemsResponse($featuredGroup, 1),
|
||||
$featuredGroupService->itemsResponse($featuredGroup, 1, $this->userId($request)),
|
||||
))->resolve()
|
||||
));
|
||||
}
|
||||
@@ -46,15 +49,17 @@ class CatalogController extends Controller
|
||||
SearchCatalogItemsRequest $request,
|
||||
Tenant $tenant,
|
||||
CatalogService $catalogService,
|
||||
CatalogItemAllowanceService $allowances,
|
||||
): AnonymousResourceCollection {
|
||||
return CatalogSearchItemResource::collection(
|
||||
$catalogService->search(
|
||||
$tenant,
|
||||
$request->validated('q'),
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
)
|
||||
$items = $catalogService->search(
|
||||
$tenant,
|
||||
$request->validated('q'),
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
);
|
||||
$allowances->attach($items->getCollection(), $this->userId($request));
|
||||
|
||||
return CatalogSearchItemResource::collection($items);
|
||||
}
|
||||
|
||||
public function category(
|
||||
@@ -62,17 +67,19 @@ class CatalogController extends Controller
|
||||
Tenant $tenant,
|
||||
Category $category,
|
||||
CatalogService $catalogService,
|
||||
CatalogItemAllowanceService $allowances,
|
||||
): AnonymousResourceCollection {
|
||||
abort_unless($category->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
return CatalogSearchItemResource::collection(
|
||||
$catalogService->categoryItems(
|
||||
$tenant,
|
||||
$category,
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
)
|
||||
)->additional([
|
||||
$items = $catalogService->categoryItems(
|
||||
$tenant,
|
||||
$category,
|
||||
$tenant->search_items_per_page,
|
||||
(int) $request->validated('page', 1),
|
||||
);
|
||||
$allowances->attach($items->getCollection(), $this->userId($request));
|
||||
|
||||
return CatalogSearchItemResource::collection($items)->additional([
|
||||
'category' => [
|
||||
'id' => $category->id,
|
||||
'nombre' => $category->nombre,
|
||||
@@ -93,7 +100,11 @@ class CatalogController extends Controller
|
||||
|
||||
$page = (int) $request->validated('page', 1);
|
||||
|
||||
return response()->json($featuredGroupService->itemsResponse($featuredGroup, $page));
|
||||
return response()->json($featuredGroupService->itemsResponse(
|
||||
$featuredGroup,
|
||||
$page,
|
||||
$this->userId($request),
|
||||
));
|
||||
}
|
||||
|
||||
public function show(
|
||||
@@ -101,17 +112,19 @@ class CatalogController extends Controller
|
||||
Tenant $tenant,
|
||||
CatalogItem $catalogItem,
|
||||
CatalogService $catalogService,
|
||||
CatalogItemAllowanceService $allowances,
|
||||
): CatalogItemDetailResource {
|
||||
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
|
||||
|
||||
$variantId = $request->validated('variant_id');
|
||||
|
||||
return CatalogItemDetailResource::make(
|
||||
$catalogService->getDetail(
|
||||
$catalogItem,
|
||||
$variantId === null ? null : (int) $variantId,
|
||||
)
|
||||
$item = $catalogService->getDetail(
|
||||
$catalogItem,
|
||||
$variantId === null ? null : (int) $variantId,
|
||||
);
|
||||
$allowances->attach(collect([$item]), $this->userId($request));
|
||||
|
||||
return CatalogItemDetailResource::make($item);
|
||||
}
|
||||
|
||||
public function variantOptions(
|
||||
@@ -164,4 +177,11 @@ class CatalogController extends Controller
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
private function userId(Request $request): ?int
|
||||
{
|
||||
$userId = $request->user()?->getAuthIdentifier() ?? Auth::guard('sanctum')->id();
|
||||
|
||||
return $userId === null ? null : (int) $userId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Catalog\Models;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
#[Fillable([
|
||||
@@ -47,6 +48,12 @@ class Inventory extends Model
|
||||
return $this->hasOne(Variant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<StockReservation, $this> */
|
||||
public function stockReservations(): HasMany
|
||||
{
|
||||
return $this->hasMany(StockReservation::class);
|
||||
}
|
||||
|
||||
public function availableStock(): int
|
||||
{
|
||||
return max(0, $this->real_stock - $this->reserved_stock);
|
||||
|
||||
@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'allow_multi_select',
|
||||
'sort_order',
|
||||
'show_in_selector',
|
||||
'ticket_label',
|
||||
])]
|
||||
class ItemAttribute extends Model
|
||||
{
|
||||
|
||||
61
app/Domains/Catalog/Models/StockReservation.php
Normal file
61
app/Domains/Catalog/Models/StockReservation.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Models;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'inventory_id',
|
||||
'cart_item_id',
|
||||
'purchase_id',
|
||||
'quantity',
|
||||
'status',
|
||||
'expires_at',
|
||||
'committed_at',
|
||||
'released_at',
|
||||
])]
|
||||
class StockReservation extends Model
|
||||
{
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public const STATUS_COMMITTED = 'committed';
|
||||
|
||||
public const STATUS_RELEASED = 'released';
|
||||
|
||||
public const STATUS_EXPIRED = 'expired';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'inventory_id' => 'integer',
|
||||
'cart_item_id' => 'integer',
|
||||
'purchase_id' => 'integer',
|
||||
'quantity' => 'integer',
|
||||
'expires_at' => 'datetime',
|
||||
'committed_at' => 'datetime',
|
||||
'released_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Inventory, $this> */
|
||||
public function inventory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inventory::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CartItem, $this> */
|
||||
public function cartItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CartItem::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Purchase, $this> */
|
||||
public function purchase(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Purchase::class);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -19,6 +20,7 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
$catalogItem = $this->resource;
|
||||
/** @var FeaturedGroup $featuredGroup */
|
||||
$featuredGroup = $catalogItem->getRelation('featuredGroup');
|
||||
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||
|
||||
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
|
||||
return $this->columnWithImageData($catalogItem);
|
||||
@@ -34,7 +36,10 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'precio' => $catalogItem->precio,
|
||||
'stock_tecnico' => $catalogItem->availableStock(),
|
||||
'maximum_addable_quantity' => $this->maximumAddable(
|
||||
$catalogItem->availableStock(),
|
||||
$remainingUserQuota,
|
||||
),
|
||||
'variants' => $catalogItem->visibleVariants()
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
@@ -44,9 +49,12 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'maximum_addable_quantity' => $this->maximumAddable(
|
||||
$catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
$remainingUserQuota,
|
||||
),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
@@ -89,4 +97,10 @@ class CatalogFeaturedItemResource extends JsonResource
|
||||
|
||||
return $attachment?->getTemporaryUrl(1440);
|
||||
}
|
||||
|
||||
private function maximumAddable(?int $stock, ?int $remainingUserQuota): ?int
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)
|
||||
->maximumAddableQuantity($stock, $remainingUserQuota);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\ItemAttribute;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Ticket\Resources\ValidityTimeResource;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -37,9 +38,9 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'max_units_per_user' => $this->max_units_per_user,
|
||||
'has_tickets' => $this->has_tickets,
|
||||
'attributes' => $this->attributesData(),
|
||||
'stock_tecnico' => $this->when(
|
||||
'maximum_addable_quantity' => $this->when(
|
||||
$selectedVariant === null,
|
||||
fn () => $this->availableStock(),
|
||||
fn () => $this->maximumAddable($this->availableStock()),
|
||||
),
|
||||
'images' => $this->when(
|
||||
$selectedVariant === null,
|
||||
@@ -85,6 +86,7 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'nombre' => $attribute->nombre,
|
||||
'sort_order' => $itemAttribute->sort_order,
|
||||
'show_in_selector' => $itemAttribute->show_in_selector,
|
||||
'ticket_label' => $itemAttribute->ticket_label,
|
||||
'is_required' => $attribute->is_required,
|
||||
'allow_multi_select' => $itemAttribute->allow_multi_select,
|
||||
'metadata_schema' => $attribute->metadata_schema,
|
||||
@@ -166,7 +168,7 @@ class CatalogItemDetailResource extends JsonResource
|
||||
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $this->variantStock($variant),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($this->variantStock($variant)),
|
||||
'values' => $values,
|
||||
];
|
||||
}
|
||||
@@ -185,4 +187,12 @@ class CatalogItemDetailResource extends JsonResource
|
||||
? null
|
||||
: $variant->inventory->availableStock();
|
||||
}
|
||||
|
||||
private function maximumAddable(?int $stock): ?int
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
|
||||
$stock,
|
||||
$this->getAttribute('remaining_user_quota'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Catalog\Resources;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -26,7 +27,7 @@ class CatalogSearchItemResource extends JsonResource
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'image' => $attachment?->getTemporaryUrl(1440),
|
||||
'stock_tecnico' => $this->availableStock(),
|
||||
'maximum_addable_quantity' => $this->maximumAddable($this->availableStock()),
|
||||
'variants' => $this->visibleVariants()
|
||||
->map(fn (Variant $variant): array => [
|
||||
'id' => $variant->id,
|
||||
@@ -36,12 +37,22 @@ class CatalogSearchItemResource extends JsonResource
|
||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
'maximum_addable_quantity' => $this->maximumAddable(
|
||||
$this->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory?->availableStock(),
|
||||
),
|
||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||
])
|
||||
->values(),
|
||||
];
|
||||
}
|
||||
|
||||
private function maximumAddable(?int $stock): ?int
|
||||
{
|
||||
return app(CatalogItemAllowanceService::class)->maximumAddableQuantity(
|
||||
$stock,
|
||||
$this->getAttribute('remaining_user_quota'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,19 @@ use Illuminate\Support\Facades\DB;
|
||||
|
||||
class CatalogInventoryService
|
||||
{
|
||||
/** @return array<int, int> */
|
||||
public function requirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
|
||||
{
|
||||
if ($quantity <= 0) {
|
||||
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
|
||||
}
|
||||
|
||||
return array_map(
|
||||
fn (array $requirement): int => $requirement['quantity'] * $quantity,
|
||||
$this->inventoryRequirements($selection),
|
||||
);
|
||||
}
|
||||
|
||||
public function availableQuantity(CatalogItem|Variant $selection): ?int
|
||||
{
|
||||
if ($selection instanceof CatalogItem
|
||||
|
||||
40
app/Domains/Catalog/Services/CatalogItemAllowanceService.php
Normal file
40
app/Domains/Catalog/Services/CatalogItemAllowanceService.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CatalogItemAllowanceService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
) {}
|
||||
|
||||
/** @param Collection<int, CatalogItem> $catalogItems */
|
||||
public function attach(Collection $catalogItems, ?int $userId): void
|
||||
{
|
||||
$remaining = $this->purchaseLimits->remainingByCatalogItem($catalogItems, $userId);
|
||||
|
||||
foreach ($catalogItems as $catalogItem) {
|
||||
$catalogItem->setAttribute(
|
||||
'remaining_user_quota',
|
||||
$remaining->get($catalogItem->getKey()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function maximumAddableQuantity(?int $availableStock, ?int $remainingUserQuota): ?int
|
||||
{
|
||||
if ($availableStock === null) {
|
||||
return $remainingUserQuota;
|
||||
}
|
||||
|
||||
if ($remainingUserQuota === null) {
|
||||
return $availableStock;
|
||||
}
|
||||
|
||||
return min($availableStock, $remainingUserQuota);
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ class CatalogService
|
||||
$attributeCodes = $data['attribute_codes'] ?? [];
|
||||
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
|
||||
$hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? [];
|
||||
$ticketAttributeLabels = $data['ticket_attribute_labels'] ?? [];
|
||||
$components = $data['components'] ?? [];
|
||||
$hasDirectStock = array_key_exists('real_stock', $data);
|
||||
$realStock = (int) ($data['real_stock'] ?? 0);
|
||||
@@ -73,6 +74,14 @@ class CatalogService
|
||||
]);
|
||||
}
|
||||
|
||||
if (array_diff(array_keys($ticketAttributeLabels), $attributeCodes) !== []) {
|
||||
throw ValidationException::withMessages([
|
||||
'ticket_attribute_labels' => [
|
||||
__('api.catalog.ticket_label_attribute_not_on_item'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->validateUniqueVariantCombinations($variants, $attributeCodes);
|
||||
|
||||
if ($type === CatalogItemType::Bundle) {
|
||||
@@ -98,6 +107,7 @@ class CatalogService
|
||||
$data['attribute_codes'],
|
||||
$data['multi_select_attribute_codes'],
|
||||
$data['hidden_attribute_codes'],
|
||||
$data['ticket_attribute_labels'],
|
||||
$data['components'],
|
||||
$data['real_stock'],
|
||||
$data['reserved_stock'],
|
||||
@@ -124,6 +134,7 @@ class CatalogService
|
||||
$attributeCodes,
|
||||
$multiSelectAttributeCodes,
|
||||
$hiddenAttributeCodes,
|
||||
$ticketAttributeLabels,
|
||||
)
|
||||
: [];
|
||||
|
||||
@@ -461,6 +472,7 @@ class CatalogService
|
||||
* @param array<int, string> $attributeCodes
|
||||
* @param array<int, string> $multiSelectAttributeCodes
|
||||
* @param array<int, string> $hiddenAttributeCodes
|
||||
* @param array<string, string> $ticketAttributeLabels
|
||||
* @return array<string, ItemAttribute>
|
||||
*/
|
||||
private function createItemAttributes(
|
||||
@@ -468,6 +480,7 @@ class CatalogService
|
||||
array $attributeCodes,
|
||||
array $multiSelectAttributeCodes = [],
|
||||
array $hiddenAttributeCodes = [],
|
||||
array $ticketAttributeLabels = [],
|
||||
): array {
|
||||
$itemAttributes = [];
|
||||
$attributeCodes = array_values(array_unique($attributeCodes));
|
||||
@@ -492,6 +505,7 @@ class CatalogService
|
||||
'attribute_id' => $attribute->id,
|
||||
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
|
||||
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
|
||||
'ticket_label' => $ticketAttributeLabels[$attributeCode] ?? null,
|
||||
]);
|
||||
|
||||
$itemAttributes[$attributeCode] = $itemAttribute;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
class ExpireStockReservationsService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutService $checkout,
|
||||
private readonly ExpireCartReservationsService $carts,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{purchases: int, cart_items: int}
|
||||
*/
|
||||
public function expireOverdue(): array
|
||||
{
|
||||
$expiredPurchases = null;
|
||||
$expiredCartItems = null;
|
||||
|
||||
try {
|
||||
$expiredPurchases = $this->checkout->expireOverduePurchases();
|
||||
$expiredCartItems = $this->carts->expireOverdue();
|
||||
|
||||
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
||||
'command' => 'reservations:expire',
|
||||
'expired_purchases' => $expiredPurchases,
|
||||
'expired_cart_items' => $expiredCartItems,
|
||||
'total_expired' => $expiredPurchases + $expiredCartItems,
|
||||
]);
|
||||
|
||||
return [
|
||||
'purchases' => $expiredPurchases,
|
||||
'cart_items' => $expiredCartItems,
|
||||
];
|
||||
} catch (Throwable $exception) {
|
||||
Log::channel('commands')->error('Stock reservation cleanup failed.', [
|
||||
'command' => 'reservations:expire',
|
||||
'expired_purchases' => $expiredPurchases,
|
||||
'expired_cart_items' => $expiredCartItems,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,11 @@ class FeaturedGroupService
|
||||
private const ITEMS_PER_PAGE = 12;
|
||||
|
||||
/** @return array<array-key, mixed> */
|
||||
public function itemsResponse(FeaturedGroup $featuredGroup, int $page): array
|
||||
public function __construct(
|
||||
private readonly CatalogItemAllowanceService $allowances,
|
||||
) {}
|
||||
|
||||
public function itemsResponse(FeaturedGroup $featuredGroup, int $page, ?int $userId = null): array
|
||||
{
|
||||
if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
|
||||
$query = $this->itemsQuery($featuredGroup);
|
||||
@@ -26,12 +30,14 @@ class FeaturedGroupService
|
||||
|
||||
$items = $query->get();
|
||||
$this->attachGroup($items, $featuredGroup);
|
||||
$this->allowances->attach($items, $userId);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($items)->resolve();
|
||||
}
|
||||
|
||||
$paginator = $this->paginateItems($featuredGroup, $page);
|
||||
$this->attachGroup($paginator->getCollection(), $featuredGroup);
|
||||
$this->allowances->attach($paginator->getCollection(), $userId);
|
||||
|
||||
return CatalogFeaturedItemResource::collection($paginator)
|
||||
->response()
|
||||
|
||||
230
app/Domains/Catalog/Services/StockReservationService.php
Normal file
230
app/Domains/Catalog/Services/StockReservationService.php
Normal file
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class StockReservationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $inventory,
|
||||
) {}
|
||||
|
||||
public function reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
||||
{
|
||||
DB::transaction(function () use ($cartItem, $selection, $quantity): void {
|
||||
$this->inventory->reserve($selection, $quantity);
|
||||
$this->recordIncrease($cartItem, $selection, $quantity);
|
||||
});
|
||||
}
|
||||
|
||||
public function release(
|
||||
CartItem $cartItem,
|
||||
CatalogItem|Variant $selection,
|
||||
int $quantity,
|
||||
string $releasedStatus = StockReservation::STATUS_RELEASED,
|
||||
): void {
|
||||
DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
|
||||
$this->ensure($cartItem, $selection);
|
||||
$this->inventory->release($selection, $quantity);
|
||||
$this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
|
||||
});
|
||||
}
|
||||
|
||||
public function commit(CartItem $cartItem, CatalogItem|Variant $selection): void
|
||||
{
|
||||
DB::transaction(function () use ($cartItem, $selection): void {
|
||||
$this->ensure($cartItem, $selection);
|
||||
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
||||
|
||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
||||
foreach ($requirements as $inventoryId => $quantity) {
|
||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
||||
}
|
||||
|
||||
$reservation->update([
|
||||
'status' => StockReservation::STATUS_COMMITTED,
|
||||
'committed_at' => now(),
|
||||
'expires_at' => null,
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function ensure(CartItem $cartItem, CatalogItem|Variant $selection): void
|
||||
{
|
||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
||||
|
||||
foreach ($requirements as $inventoryId => $quantity) {
|
||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||
|
||||
if ($reservation === null) {
|
||||
StockReservation::query()->create([
|
||||
'inventory_id' => $inventoryId,
|
||||
'cart_item_id' => $cartItem->getKey(),
|
||||
'quantity' => $quantity,
|
||||
'status' => StockReservation::STATUS_ACTIVE,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
||||
$reservation->update([
|
||||
'quantity' => $quantity,
|
||||
'status' => StockReservation::STATUS_ACTIVE,
|
||||
'committed_at' => null,
|
||||
'released_at' => null,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function attachToPurchase(
|
||||
CartItem $cartItem,
|
||||
CatalogItem|Variant $selection,
|
||||
Purchase $purchase,
|
||||
): void {
|
||||
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
||||
$this->ensure($cartItem, $selection);
|
||||
StockReservation::query()
|
||||
->where('cart_item_id', $cartItem->getKey())
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->update([
|
||||
'purchase_id' => $purchase->getKey(),
|
||||
'expires_at' => $purchase->expires_at,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
public function detachFromPurchase(Purchase $purchase): void
|
||||
{
|
||||
StockReservation::query()
|
||||
->where('purchase_id', $purchase->getKey())
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->update([
|
||||
'purchase_id' => null,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function syncPurchaseExpiration(Purchase $purchase): void
|
||||
{
|
||||
StockReservation::query()
|
||||
->where('purchase_id', $purchase->getKey())
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->update(['expires_at' => $purchase->expires_at]);
|
||||
}
|
||||
|
||||
public function transfer(CartItem $source, CartItem $target): void
|
||||
{
|
||||
DB::transaction(function () use ($source, $target): void {
|
||||
$sourceReservations = StockReservation::query()
|
||||
->where('cart_item_id', $source->getKey())
|
||||
->where('status', StockReservation::STATUS_ACTIVE)
|
||||
->orderBy('inventory_id')
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
|
||||
foreach ($sourceReservations as $sourceReservation) {
|
||||
$targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
|
||||
|
||||
if ($targetReservation === null) {
|
||||
$sourceItemQuantity = (int) $source->cantidad;
|
||||
$targetItemQuantity = (int) $target->fresh()->cantidad;
|
||||
$perItemQuantity = intdiv((int) $sourceReservation->quantity, $sourceItemQuantity);
|
||||
$sourceReservation->update([
|
||||
'cart_item_id' => $target->getKey(),
|
||||
'purchase_id' => null,
|
||||
'quantity' => $perItemQuantity * $targetItemQuantity,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$targetReservation->update([
|
||||
'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
|
||||
'status' => StockReservation::STATUS_ACTIVE,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
$sourceReservation->delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
|
||||
{
|
||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||
|
||||
if ($reservation === null) {
|
||||
StockReservation::query()->create([
|
||||
'inventory_id' => $inventoryId,
|
||||
'cart_item_id' => $cartItem->getKey(),
|
||||
'quantity' => $requiredQuantity,
|
||||
'status' => StockReservation::STATUS_ACTIVE,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$reservation->update([
|
||||
'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
|
||||
'status' => StockReservation::STATUS_ACTIVE,
|
||||
'committed_at' => null,
|
||||
'released_at' => null,
|
||||
'expires_at' => $this->expiration(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function recordDecrease(
|
||||
CartItem $cartItem,
|
||||
CatalogItem|Variant $selection,
|
||||
int $quantity,
|
||||
string $releasedStatus,
|
||||
): void {
|
||||
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
|
||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity < $requiredQuantity) {
|
||||
throw new \InvalidArgumentException('La reserva de stock no alcanza para liberar la cantidad solicitada.');
|
||||
}
|
||||
|
||||
$remaining = $reservation->quantity - $requiredQuantity;
|
||||
$reservation->update([
|
||||
'quantity' => $remaining,
|
||||
'status' => $remaining === 0 ? $releasedStatus : StockReservation::STATUS_ACTIVE,
|
||||
'released_at' => $remaining === 0 ? now() : null,
|
||||
'expires_at' => $remaining === 0 ? null : $reservation->expires_at,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function lockReservation(CartItem $cartItem, int $inventoryId): ?StockReservation
|
||||
{
|
||||
return StockReservation::query()
|
||||
->where('cart_item_id', $cartItem->getKey())
|
||||
->where('inventory_id', $inventoryId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
}
|
||||
|
||||
private function expiration(): Carbon
|
||||
{
|
||||
return now()->addMinutes(
|
||||
max(1, (int) config('catalog.stock_reservation_expiration_minutes', 30)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
||||
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
|
||||
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
|
||||
- `Inventory` administra stock disponible, reservado y comprado.
|
||||
- `StockReservation` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
|
||||
- `Category` soporta jerarquía y categorías globales o propias del tenant.
|
||||
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
|
||||
- `BundleComponent` representa los componentes de un paquete.
|
||||
@@ -17,6 +18,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
|
||||
|
||||
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
|
||||
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
|
||||
- `StockReservationService`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
|
||||
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
|
||||
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.
|
||||
|
||||
|
||||
47
app/Domains/Client/Controllers/ClientController.php
Normal file
47
app/Domains/Client/Controllers/ClientController.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Client\Requests\StoreClientRequest;
|
||||
use App\Domains\Client\Requests\UpdateClientRequest;
|
||||
use App\Domains\Client\Resources\ClientResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
class ClientController extends Controller
|
||||
{
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
return ClientResource::collection(
|
||||
Client::query()->with('tenants')->latest()->paginateFromRequest()
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StoreClientRequest $request): JsonResponse
|
||||
{
|
||||
return ClientResource::make(
|
||||
Client::query()->create($request->validated())->load('tenants')
|
||||
)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Client $client): ClientResource
|
||||
{
|
||||
return ClientResource::make($client->load('tenants'));
|
||||
}
|
||||
|
||||
public function update(UpdateClientRequest $request, Client $client): ClientResource
|
||||
{
|
||||
$client->update($request->validated());
|
||||
|
||||
return ClientResource::make($client->fresh()->load('tenants'));
|
||||
}
|
||||
|
||||
public function destroy(Client $client): Response
|
||||
{
|
||||
$client->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
30
app/Domains/Client/Models/Client.php
Normal file
30
app/Domains/Client/Models/Client.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Models;
|
||||
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable(['code', 'name'])]
|
||||
class Client extends Model
|
||||
{
|
||||
public function getRouteKeyName(): string
|
||||
{
|
||||
return 'code';
|
||||
}
|
||||
|
||||
/** @return HasMany<Tenant, $this> */
|
||||
public function tenants(): HasMany
|
||||
{
|
||||
return $this->hasMany(Tenant::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<ClientIntegration, $this> */
|
||||
public function integrations(): HasMany
|
||||
{
|
||||
return $this->hasMany(ClientIntegration::class);
|
||||
}
|
||||
}
|
||||
22
app/Domains/Client/Requests/StoreClientRequest.php
Normal file
22
app/Domains/Client/Requests/StoreClientRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'code' => ['required', 'string', 'max:255', Rule::unique('clients', 'code')],
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Client/Requests/UpdateClientRequest.php
Normal file
26
app/Domains/Client/Requests/UpdateClientRequest.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Requests;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateClientRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var Client|null $client */
|
||||
$client = $this->route('client');
|
||||
|
||||
return [
|
||||
'code' => ['sometimes', 'string', 'max:255', Rule::unique('clients', 'code')->ignore($client?->id)],
|
||||
'name' => ['sometimes', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
}
|
||||
26
app/Domains/Client/Resources/ClientResource.php
Normal file
26
app/Domains/Client/Resources/ClientResource.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Client\Resources;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin Client */
|
||||
class ClientResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'name' => $this->name,
|
||||
'tenants' => $this->whenLoaded('tenants', fn () => $this->tenants->map(fn ($tenant): array => [
|
||||
'id' => $tenant->id,
|
||||
'codigo' => $tenant->codigo,
|
||||
'nombre' => $tenant->nombre,
|
||||
'dominio' => $tenant->dominio,
|
||||
])),
|
||||
];
|
||||
}
|
||||
}
|
||||
6
app/Domains/Client/routes/api.php
Normal file
6
app/Domains/Client/routes/api.php
Normal file
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Client\Controllers\ClientController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::apiResource('clients', ClientController::class);
|
||||
417
app/Domains/Desfile/Services/InvitationPurchaseProvisioner.php
Normal file
417
app/Domains/Desfile/Services/InvitationPurchaseProvisioner.php
Normal file
@@ -0,0 +1,417 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Desfile\Services;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
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, seats: int, type: string}>
|
||||
*/
|
||||
private const ALLOCATIONS = [
|
||||
['sector' => 'A', 'row' => 1, 'seats' => 16, 'type' => 'NORMAL'],
|
||||
['sector' => 'A', 'row' => 3, 'seats' => 14, 'type' => 'NORMAL'],
|
||||
['sector' => 'C', 'row' => 1, 'seats' => 16, 'type' => 'VIP + LUNCH'],
|
||||
];
|
||||
|
||||
public function provision(): void
|
||||
{
|
||||
if (! $this->prerequisitesExist()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function (): 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 (self::ALLOCATIONS as $allocation) {
|
||||
foreach (range(1, $allocation['seats']) as $seat) {
|
||||
$variant = $this->variant(
|
||||
(int) $catalogItem->id,
|
||||
$allocation['sector'],
|
||||
$allocation['row'],
|
||||
$seat,
|
||||
$allocation['type'],
|
||||
);
|
||||
|
||||
$this->createPurchaseItem(
|
||||
$purchaseId,
|
||||
$catalogItem,
|
||||
$variant,
|
||||
$allocation['sector'],
|
||||
$allocation['row'],
|
||||
$seat,
|
||||
$allocation['type'],
|
||||
$now,
|
||||
);
|
||||
$this->createTicketAndCommitStock(
|
||||
$purchaseId,
|
||||
$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('email', self::USER_EMAIL)->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',
|
||||
'expires_at' => null,
|
||||
'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,
|
||||
'expires_at' => null,
|
||||
'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,
|
||||
): void {
|
||||
if (DB::table('compra_items')
|
||||
->where('compra_id', $purchaseId)
|
||||
->where('source_variant_id', $variant->id)
|
||||
->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
['name' => 'Tipo', 'value' => $type],
|
||||
['name' => 'Sector', 'value' => $sector],
|
||||
['name' => 'Fila', 'value' => (string) $row],
|
||||
['name' => 'Asiento', 'value' => (string) $seat],
|
||||
];
|
||||
|
||||
DB::table('compra_items')->insert([
|
||||
'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 $userId,
|
||||
int $catalogItemId,
|
||||
object $variant,
|
||||
DateTimeInterface $now,
|
||||
): void {
|
||||
if (DB::table('tickets')
|
||||
->where('source_purchase_id', $purchaseId)
|
||||
->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,
|
||||
]);
|
||||
|
||||
DB::table('stock_reservations')->insert([
|
||||
'inventory_id' => $inventory->id,
|
||||
'cart_item_id' => null,
|
||||
'purchase_id' => $purchaseId,
|
||||
'quantity' => 1,
|
||||
'status' => 'committed',
|
||||
'expires_at' => null,
|
||||
'committed_at' => $now,
|
||||
'released_at' => null,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
DB::table('tickets')->insert([
|
||||
'tenant_code' => self::TENANT_CODE,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'name' => null,
|
||||
'description' => null,
|
||||
'source_purchase_id' => $purchaseId,
|
||||
'source_catalog_item_id' => $catalogItemId,
|
||||
'source_variant_id' => $variant->id,
|
||||
'used_at' => null,
|
||||
'scanner_user_id' => null,
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreClientIntegrationRequest;
|
||||
use App\Domains\Integration\Services\ClientIntegrationService;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class ClientIntegrationController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClientIntegrationService $clientIntegrationService,
|
||||
) {}
|
||||
|
||||
public function index(Client $client): JsonResponse
|
||||
{
|
||||
return response()->json($this->clientIntegrationService->getAllForClient($client));
|
||||
}
|
||||
|
||||
public function show(Client $client, string $integrationCode): JsonResponse
|
||||
{
|
||||
$integration = $this->clientIntegrationService->getClientIntegration($client, $integrationCode);
|
||||
|
||||
if (! $integration) {
|
||||
return response()->json([
|
||||
'code' => 'integration.not_configured',
|
||||
'message' => __('api.integration.not_configured'),
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function store(
|
||||
StoreClientIntegrationRequest $request,
|
||||
Client $client,
|
||||
string $integrationCode,
|
||||
): JsonResponse {
|
||||
$integration = Integration::query()
|
||||
->where('integration_code', $integrationCode)
|
||||
->firstOrFail();
|
||||
|
||||
try {
|
||||
$this->clientIntegrationService->updateOrCreateIntegration(
|
||||
$client,
|
||||
$integration,
|
||||
$request->input('integration_data', []),
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.configured',
|
||||
'message' => __('api.integration.configured'),
|
||||
]);
|
||||
} catch (\Exception $exception) {
|
||||
return response()->json([
|
||||
'code' => 'integration.validation_failed',
|
||||
'message' => __('api.integration.validation_failed', ['error' => $exception->getMessage()]),
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Requests\TelepagosWebhookRequest;
|
||||
use App\Domains\Integration\Services\TelepagosWebhookService;
|
||||
use App\Http\Controllers\Controller;
|
||||
@@ -12,12 +13,12 @@ class TelepagosWebhookController extends Controller
|
||||
/**
|
||||
* Handle the incoming Telepagos webhook.
|
||||
*/
|
||||
public function handle(TelepagosWebhookRequest $request, string $tenantCodigo, TelepagosWebhookService $service): JsonResponse
|
||||
public function handle(TelepagosWebhookRequest $request, Client $client, TelepagosWebhookService $service): JsonResponse
|
||||
{
|
||||
try {
|
||||
$cashinId = $request->validated('id');
|
||||
|
||||
$service->handleWebhook($tenantCodigo, $cashinId);
|
||||
$service->handleWebhook($client, $cashinId);
|
||||
|
||||
return response()->json(['status' => 'success']);
|
||||
} catch (\Exception $e) {
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Controllers;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Requests\StoreTenantIntegrationRequest;
|
||||
use App\Domains\Integration\Services\TenantIntegrationService;
|
||||
use Illuminate\Routing\Controller;
|
||||
|
||||
class TenantIntegrationController extends Controller
|
||||
{
|
||||
protected TenantIntegrationService $tenantIntegrationService;
|
||||
|
||||
public function __construct(TenantIntegrationService $tenantIntegrationService)
|
||||
{
|
||||
$this->tenantIntegrationService = $tenantIntegrationService;
|
||||
}
|
||||
|
||||
public function index(string $tenantCode)
|
||||
{
|
||||
return response()->json($this->tenantIntegrationService->getAllForTenant($tenantCode));
|
||||
}
|
||||
|
||||
public function show(string $tenantCode, string $integrationCode)
|
||||
{
|
||||
$integration = $this->tenantIntegrationService->getTenantIntegration($tenantCode, $integrationCode);
|
||||
|
||||
if (! $integration) {
|
||||
return response()->json([
|
||||
'code' => 'integration.not_configured',
|
||||
'message' => __('api.integration.not_configured'),
|
||||
], 404);
|
||||
}
|
||||
|
||||
return response()->json($integration);
|
||||
}
|
||||
|
||||
public function store(StoreTenantIntegrationRequest $request, string $tenantCode, string $integrationCode)
|
||||
{
|
||||
$integration = Integration::where('integration_code', $integrationCode)->firstOrFail();
|
||||
|
||||
try {
|
||||
$this->tenantIntegrationService->updateOrCreateIntegration(
|
||||
$tenantCode,
|
||||
$integration,
|
||||
$request->input('integration_data', [])
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'code' => 'integration.configured',
|
||||
'message' => __('api.integration.configured'),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return response()->json([
|
||||
'code' => 'integration.validation_failed',
|
||||
'message' => __('api.integration.validation_failed', ['error' => $e->getMessage()]),
|
||||
], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,18 @@
|
||||
|
||||
namespace App\Domains\Integration\Models;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Casts\EncryptedIntegrationData;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class TenantIntegration extends Model
|
||||
class ClientIntegration extends Model
|
||||
{
|
||||
protected $table = 'tenant_integration';
|
||||
protected $hidden = ['integration_data'];
|
||||
|
||||
protected $fillable = [
|
||||
'client_id',
|
||||
'integration_code',
|
||||
'tenant_code',
|
||||
'integration_data',
|
||||
];
|
||||
|
||||
@@ -19,7 +21,14 @@ class TenantIntegration extends Model
|
||||
'integration_data' => EncryptedIntegrationData::class,
|
||||
];
|
||||
|
||||
public function integration()
|
||||
/** @return BelongsTo<Client, $this> */
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Client::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Integration, $this> */
|
||||
public function integration(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Integration::class, 'integration_code', 'integration_code');
|
||||
}
|
||||
@@ -13,16 +13,16 @@ class Integration extends Model
|
||||
'name',
|
||||
'url',
|
||||
'integration_data_schema',
|
||||
'requires_tenant_configuration',
|
||||
'requires_client_configuration',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'integration_data_schema' => 'array',
|
||||
'requires_tenant_configuration' => 'boolean',
|
||||
'requires_client_configuration' => 'boolean',
|
||||
];
|
||||
|
||||
public function tenantIntegrations()
|
||||
|
||||
public function clientIntegrations()
|
||||
{
|
||||
return $this->hasMany(TenantIntegration::class, 'integration_code', 'integration_code');
|
||||
return $this->hasMany(ClientIntegration::class, 'integration_code', 'integration_code');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use App\Domains\Integration\Models\Integration;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class StoreTenantIntegrationRequest extends FormRequest
|
||||
class StoreClientIntegrationRequest extends FormRequest
|
||||
{
|
||||
protected ?Integration $integrationModel = null;
|
||||
|
||||
@@ -15,10 +15,12 @@ class StoreTenantIntegrationRequest extends FormRequest
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function prepareForValidation()
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$integrationCode = $this->route('integration_code');
|
||||
$this->integrationModel = Integration::where('integration_code', $integrationCode)->first();
|
||||
$this->integrationModel = Integration::query()
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
|
||||
if (! $this->integrationModel) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -31,11 +33,8 @@ class StoreTenantIntegrationRequest extends FormRequest
|
||||
{
|
||||
$rules = [];
|
||||
|
||||
// Dynamic validation rules based on the integration data schema
|
||||
if ($this->integrationModel && $this->integrationModel->integration_data_schema) {
|
||||
foreach ($this->integrationModel->integration_data_schema as $field => $rule) {
|
||||
$rules['integration_data.'.$field] = $rule;
|
||||
}
|
||||
foreach ($this->integrationModel?->integration_data_schema ?? [] as $field => $rule) {
|
||||
$rules['integration_data.'.$field] = $rule;
|
||||
}
|
||||
|
||||
return $rules;
|
||||
@@ -18,7 +18,7 @@ class StoreIntegrationRequest extends FormRequest
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_tenant_configuration' => ['sometimes', 'boolean'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,14 +14,14 @@ class UpdateIntegrationRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
$integration = $this->route('integration');
|
||||
|
||||
|
||||
return [
|
||||
'name' => ['sometimes', 'required', 'string', 'max:255'],
|
||||
'url' => ['nullable', 'url', 'max:255'],
|
||||
'integration_data_schema' => ['nullable', 'array'],
|
||||
'requires_tenant_configuration' => ['sometimes', 'boolean'],
|
||||
'requires_client_configuration' => ['sometimes', 'boolean'],
|
||||
// the code shouldn't ideally be updatable, but if it is:
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,' . ($integration->id ?? '')],
|
||||
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,'.($integration->id ?? '')],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,58 +2,54 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Exception;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
abstract class BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* The unique code of the integration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $integrationCode;
|
||||
|
||||
/**
|
||||
* The current tenant code.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $tenantCode;
|
||||
|
||||
protected ?Tenant $tenant = null;
|
||||
|
||||
protected ?Client $clientContext = null;
|
||||
|
||||
/**
|
||||
* The integration model instance.
|
||||
*
|
||||
* @var Integration|null
|
||||
*/
|
||||
protected ?Integration $integration = null;
|
||||
|
||||
/**
|
||||
* The tenant-specific integration model instance.
|
||||
*
|
||||
* @var TenantIntegration|null
|
||||
* The client-owned integration configuration.
|
||||
*/
|
||||
protected ?TenantIntegration $tenantIntegration = null;
|
||||
protected ?ClientIntegration $clientIntegration = null;
|
||||
|
||||
/**
|
||||
* Set the integration code.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
* @return $this
|
||||
*/
|
||||
public function setIntegrationCode(string $integrationCode): self
|
||||
{
|
||||
$this->integrationCode = $integrationCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the integration code.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getIntegrationCode(): string
|
||||
{
|
||||
@@ -63,53 +59,69 @@ abstract class BaseIntegrationService
|
||||
/**
|
||||
* Set the tenant code and load the integration models.
|
||||
*
|
||||
* @param string $tenantCode
|
||||
* @return $this
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function forTenant(string $tenantCode): self
|
||||
{
|
||||
$this->tenantCode = $tenantCode;
|
||||
$this->tenant = Tenant::query()->with('client')->where('codigo', $tenantCode)->firstOrFail();
|
||||
$this->clientContext = $this->tenant->client;
|
||||
$this->loadIntegration();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function forClient(Client|string $client): self
|
||||
{
|
||||
$this->clientContext = $client instanceof Client
|
||||
? $client
|
||||
: Client::query()->where('code', $client)->firstOrFail();
|
||||
$this->tenant = null;
|
||||
$this->loadIntegration();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the Integration and TenantIntegration models.
|
||||
* Load the integration definition and its client-owned configuration.
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function loadIntegration(): void
|
||||
{
|
||||
if (empty($this->integrationCode)) {
|
||||
throw new Exception("Integration code is not set.");
|
||||
throw new Exception('Integration code is not set.');
|
||||
}
|
||||
|
||||
$this->integration = Integration::where('integration_code', $this->integrationCode)->first();
|
||||
if (!$this->integration) {
|
||||
if (! $this->integration) {
|
||||
throw new Exception("Integration with code '{$this->integrationCode}' not found.");
|
||||
}
|
||||
|
||||
$this->tenantIntegration = TenantIntegration::where('tenant_code', $this->tenantCode)
|
||||
if (! $this->clientContext) {
|
||||
throw new Exception('Client context is not set.');
|
||||
}
|
||||
|
||||
$this->clientIntegration = ClientIntegration::where('client_id', $this->clientContext->id)
|
||||
->where('integration_code', $this->integrationCode)
|
||||
->first();
|
||||
|
||||
if (!$this->tenantIntegration && $this->integration->requires_tenant_configuration) {
|
||||
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
|
||||
if (! $this->clientIntegration && $this->integration->requires_client_configuration) {
|
||||
throw new Exception("Client '{$this->clientContext->code}' does not have integration '{$this->integrationCode}' configured.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the request URL.
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getUrl(string $path = ''): string
|
||||
{
|
||||
if (!$this->integration) {
|
||||
throw new Exception("Integration is not loaded. Call forTenant() first.");
|
||||
if (! $this->integration) {
|
||||
throw new Exception('Integration is not loaded. Call forTenant() or forClient() first.');
|
||||
}
|
||||
|
||||
$baseUrl = rtrim($this->integration->url, '/');
|
||||
@@ -119,25 +131,20 @@ abstract class BaseIntegrationService
|
||||
}
|
||||
|
||||
/**
|
||||
* Get integration setting by key from tenant's integration data.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
* @return mixed
|
||||
* Get an integration setting from the client-owned configuration.
|
||||
*/
|
||||
protected function getIntegrationSetting(string $key, mixed $default = null): mixed
|
||||
{
|
||||
if (!$this->tenantIntegration || !$this->tenantIntegration->integration_data) {
|
||||
if (! $this->clientIntegration || ! $this->clientIntegration->integration_data) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $this->tenantIntegration->integration_data[$key] ?? $default;
|
||||
return $this->clientIntegration->integration_data[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a pre-configured HTTP client builder.
|
||||
*
|
||||
* @return PendingRequest
|
||||
* @throws Exception
|
||||
*/
|
||||
public function client(): PendingRequest
|
||||
@@ -148,17 +155,13 @@ abstract class BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Get the headers for the integration.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
abstract public function getHeaders(): array;
|
||||
|
||||
/**
|
||||
* Hook called after the integration is configured for the tenant.
|
||||
* Hook called after the integration is configured for the client.
|
||||
* Can be used to validate credentials or perform initial setups.
|
||||
* Throw an Exception on failure.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function onSetup(): void
|
||||
{
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ClientIntegrationService
|
||||
{
|
||||
public function getClientIntegration(Client $client, string $integrationCode): ?ClientIntegration
|
||||
{
|
||||
return $client->integrations()
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
}
|
||||
|
||||
/** @return Collection<int, ClientIntegration> */
|
||||
public function getAllForClient(Client $client): Collection
|
||||
{
|
||||
return $client->integrations()->with('integration')->get();
|
||||
}
|
||||
|
||||
public function updateOrCreateIntegration(
|
||||
Client $client,
|
||||
Integration $integration,
|
||||
array $data,
|
||||
): ClientIntegration {
|
||||
return DB::transaction(function () use ($client, $integration, $data): ClientIntegration {
|
||||
$clientIntegration = ClientIntegration::query()->updateOrCreate(
|
||||
[
|
||||
'client_id' => $client->id,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
['integration_data' => $data],
|
||||
);
|
||||
|
||||
$service = $this->resolveService($integration->integration_code);
|
||||
$service?->forClient($client)->onSetup();
|
||||
|
||||
return $clientIntegration;
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveService(string $integrationCode): ?BaseIntegrationService
|
||||
{
|
||||
return match ($integrationCode) {
|
||||
'email' => new MailService,
|
||||
'telepagos', 'telepagos_homo' => new TelepagosIntegrationService($integrationCode),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Mail\Factory as MailFactory;
|
||||
use Illuminate\Contracts\Mail\Mailer;
|
||||
@@ -27,9 +27,7 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
private ?Mailer $mailer = null;
|
||||
|
||||
private ?Tenant $tenant = null;
|
||||
|
||||
private bool $usesTenantMailer = false;
|
||||
private bool $usesClientMailer = false;
|
||||
|
||||
public function __construct(?MailFactory $mailFactory = null)
|
||||
{
|
||||
@@ -40,16 +38,28 @@ class MailService extends BaseIntegrationService
|
||||
{
|
||||
parent::forTenant($tenantCode);
|
||||
|
||||
$this->tenant = Tenant::query()
|
||||
->where('codigo', $tenantCode)
|
||||
->firstOrFail();
|
||||
|
||||
if ($this->tenantIntegration) {
|
||||
if ($this->clientIntegration) {
|
||||
$this->mailer = $this->resolveMailer();
|
||||
$this->usesTenantMailer = true;
|
||||
$this->usesClientMailer = true;
|
||||
} else {
|
||||
$this->mailer = $this->mailFactory->mailer();
|
||||
$this->usesTenantMailer = false;
|
||||
$this->usesClientMailer = false;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function forClient(Client|string $client): self
|
||||
{
|
||||
parent::forClient($client);
|
||||
$this->tenant = $this->clientContext?->tenants()->first();
|
||||
|
||||
if ($this->clientIntegration) {
|
||||
$this->mailer = $this->resolveMailer();
|
||||
$this->usesClientMailer = true;
|
||||
} else {
|
||||
$this->mailer = $this->mailFactory->mailer();
|
||||
$this->usesClientMailer = false;
|
||||
}
|
||||
|
||||
return $this;
|
||||
@@ -63,7 +73,7 @@ class MailService extends BaseIntegrationService
|
||||
public function send(string|array $recipient, string $subject, string $content): void
|
||||
{
|
||||
if (! $this->mailer || ! $this->tenant) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() primero.');
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
|
||||
}
|
||||
|
||||
$this->tenant->loadMissing(['headerLogo', 'footerLogo']);
|
||||
@@ -91,43 +101,50 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
public function mailerName(): string
|
||||
{
|
||||
return $this->usesTenantMailer
|
||||
? 'tenant-smtp'
|
||||
return $this->usesClientMailer
|
||||
? 'client-smtp'
|
||||
: (string) config('mail.default');
|
||||
}
|
||||
|
||||
public function onSetup(): void
|
||||
{
|
||||
if (! $this->tenant) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() primero.');
|
||||
if (! $this->mailer || ! $this->clientContext) {
|
||||
throw new Exception('MailService no está configurado. Llamá a forTenant() o forClient() primero.');
|
||||
}
|
||||
|
||||
$recipient = $this->getIntegrationSetting('MAIL_FROM_ADDRESS');
|
||||
|
||||
if (! is_string($recipient) || $recipient === '') {
|
||||
throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del tenant.');
|
||||
throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del cliente.');
|
||||
}
|
||||
|
||||
$this->send(
|
||||
$recipient,
|
||||
'Configuración de correo validada',
|
||||
'<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
|
||||
.'<p>La integración SMTP de '.e($this->tenant->nombre).' fue configurada correctamente.</p>'
|
||||
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>',
|
||||
$subject = 'Configuración de correo validada';
|
||||
$content = '<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
|
||||
.'<p>La integración SMTP de '.e($this->clientContext->name).' fue configurada correctamente.</p>'
|
||||
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>';
|
||||
|
||||
if ($this->tenant) {
|
||||
$this->send($recipient, $subject, $content);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->mailer->to($recipient)->send(
|
||||
(new Mailable)->subject($subject)->html($content)
|
||||
);
|
||||
}
|
||||
|
||||
private function resolveMailer(): Mailer
|
||||
{
|
||||
$data = $this->tenantIntegration?->integration_data;
|
||||
$data = $this->clientIntegration?->integration_data;
|
||||
|
||||
if (! is_array($data)) {
|
||||
throw new InvalidArgumentException('La configuración SMTP del tenant no es válida.');
|
||||
throw new InvalidArgumentException('La configuración SMTP del cliente no es válida.');
|
||||
}
|
||||
|
||||
foreach (self::REQUIRED_SMTP_FIELDS as $field) {
|
||||
if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') {
|
||||
throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del tenant.");
|
||||
throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del cliente.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +154,7 @@ class MailService extends BaseIntegrationService
|
||||
}
|
||||
|
||||
$mailer = $this->mailFactory->build([
|
||||
'name' => "tenant-smtp-{$this->tenantCode}",
|
||||
'name' => 'client-smtp-'.$this->clientContext?->id,
|
||||
'transport' => 'smtp',
|
||||
'scheme' => $data['MAIL_SCHEME'] ?? null,
|
||||
'host' => $data['MAIL_HOST'],
|
||||
@@ -150,7 +167,7 @@ class MailService extends BaseIntegrationService
|
||||
|
||||
$mailer->alwaysFrom(
|
||||
$data['MAIL_FROM_ADDRESS'],
|
||||
$data['MAIL_FROM_NAME'] ?? $this->tenant?->nombre,
|
||||
$data['MAIL_FROM_NAME'] ?? $this->clientContext?->name,
|
||||
);
|
||||
|
||||
return $mailer;
|
||||
|
||||
@@ -2,39 +2,37 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class TelepagosIntegrationService extends BaseIntegrationService
|
||||
{
|
||||
/**
|
||||
* TelepagosIntegrationService constructor.
|
||||
*
|
||||
* @param string $integrationCode
|
||||
*/
|
||||
public function __construct(string $integrationCode = 'telepagos')
|
||||
{
|
||||
// Force homologation code if not in production and using default
|
||||
if ($integrationCode === 'telepagos' && !app()->environment('production')) {
|
||||
if ($integrationCode === 'telepagos' && ! app()->environment('production')) {
|
||||
$integrationCode = 'telepagos_homo';
|
||||
}
|
||||
|
||||
|
||||
$this->integrationCode = $integrationCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the headers for Telepagos integration.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return [
|
||||
'Authorization' => 'Bearer ' . $this->getToken(),
|
||||
'Authorization' => 'Bearer '.$this->getToken(),
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'application/json',
|
||||
];
|
||||
@@ -43,16 +41,15 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get a valid token, either from cache or by performing a login.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getToken(): string
|
||||
{
|
||||
if (!$this->tenantIntegration) {
|
||||
throw new Exception("Tenant integration is not loaded. Call forTenant() first.");
|
||||
if (! $this->clientIntegration || ! $this->clientContext) {
|
||||
throw new Exception('Client integration is not loaded. Call forTenant() or forClient() first.');
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
|
||||
$token = Cache::get($cacheKey);
|
||||
|
||||
@@ -66,7 +63,6 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Authenticate with Telepagos and cache the returned token.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function login(): string
|
||||
@@ -75,7 +71,7 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
$password = $this->getIntegrationSetting('password');
|
||||
|
||||
if (empty($username) || empty($password)) {
|
||||
throw new Exception("Missing username or password in Telepagos integration settings.");
|
||||
throw new Exception('Missing username or password in Telepagos integration settings.');
|
||||
}
|
||||
|
||||
$url = $this->getUrl('/v2/auth/token');
|
||||
@@ -85,22 +81,20 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
$data = $this->handleResponse($response, 'authentication', [
|
||||
'username' => $username,
|
||||
]);
|
||||
$data = $this->handleResponse($response, 'authentication');
|
||||
|
||||
$token = $data['token'] ?? null;
|
||||
$expiresAtStr = $data['expires_at'] ?? null;
|
||||
|
||||
if (!$token || !$expiresAtStr) {
|
||||
throw new Exception("Telepagos authentication response is missing token or expires_at.");
|
||||
if (! $token || ! $expiresAtStr) {
|
||||
throw new Exception('Telepagos authentication response is missing token or expires_at.');
|
||||
}
|
||||
|
||||
$expiresAt = Carbon::parse($expiresAtStr);
|
||||
// Calculate TTL and subtract a buffer of 60 seconds
|
||||
$ttlSeconds = max(1, $expiresAt->diffInSeconds(now()) - 60);
|
||||
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
Cache::put($cacheKey, $token, $ttlSeconds);
|
||||
|
||||
return $token;
|
||||
@@ -108,21 +102,21 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
|
||||
/**
|
||||
* Send a request to Telepagos, handling 401 Unauthorized for token refresh.
|
||||
*
|
||||
* @param string $method
|
||||
* @param string $endpoint
|
||||
* @param array $data
|
||||
* @return \Illuminate\Http\Client\Response
|
||||
*/
|
||||
protected function sendRequest(string $method, string $endpoint, array $data = []): \Illuminate\Http\Client\Response
|
||||
protected function sendRequest(string $method, string $endpoint, array $data = []): Response
|
||||
{
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
|
||||
if ($response->status() === 401) {
|
||||
Log::info("Telepagos 401 Unauthorized. Refreshing token and retrying...");
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos request returned 401; refreshing token and retrying.', [
|
||||
'method' => strtoupper($method),
|
||||
'endpoint' => $endpoint,
|
||||
'client_id' => $this->clientContext?->id,
|
||||
'integration_code' => $this->integrationCode,
|
||||
]);
|
||||
|
||||
$this->clearToken();
|
||||
|
||||
|
||||
$response = $this->client()->$method($endpoint, $data);
|
||||
}
|
||||
|
||||
@@ -132,10 +126,6 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Generate a QR code for cash-in.
|
||||
*
|
||||
* @param float $amount
|
||||
* @param string $concept
|
||||
* @param string $description
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function generateQr(float $amount, string $concept, string $description): array
|
||||
@@ -154,8 +144,8 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get the details of a cash-in payment.
|
||||
*
|
||||
* @param int $cashinId
|
||||
* @return array
|
||||
* @param int $cashinId
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCashinDetails(string $cashinId): array
|
||||
@@ -170,31 +160,29 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
/**
|
||||
* Get the account info.
|
||||
*
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getAccountInfo(): array
|
||||
{
|
||||
$response = $this->sendRequest('get', '/v2/account/info');
|
||||
|
||||
return $this->handleResponse($response, 'get account info');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the Telepagos API response, logging any failures and throwing Exceptions.
|
||||
*
|
||||
* @param \Illuminate\Http\Client\Response $response
|
||||
* @param string $actionDescription
|
||||
* @param array $context
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function handleResponse(\Illuminate\Http\Client\Response $response, string $actionDescription, array $context = []): array
|
||||
protected function handleResponse(Response $response, string $actionDescription, array $context = []): array
|
||||
{
|
||||
if ($response->failed() || $response->json('status') !== 'ok') {
|
||||
$errorMessage = $response->json('message') ?? $response->body();
|
||||
Log::error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
|
||||
Log::channel('telepagos')->error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
|
||||
'response_status' => $response->status(),
|
||||
'response_body' => $response->json() ?? $response->body(),
|
||||
'response_body' => $this->sanitizeForLog($response->json() ?? $response->body()),
|
||||
'client_id' => $this->clientContext?->id,
|
||||
'integration_code' => $this->integrationCode,
|
||||
], $context));
|
||||
|
||||
throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}");
|
||||
@@ -203,21 +191,46 @@ class TelepagosIntegrationService extends BaseIntegrationService
|
||||
return $response->json() ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove credentials and tokens before serializing provider responses.
|
||||
*/
|
||||
protected function sanitizeForLog(mixed $value): mixed
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$sensitiveKeys = ['authorization', 'password', 'token', 'access_token', 'refresh_token'];
|
||||
|
||||
foreach ($value as $key => $item) {
|
||||
if (in_array(strtolower((string) $key), $sensitiveKeys, true)) {
|
||||
$value[$key] = '[REDACTED]';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$value[$key] = $this->sanitizeForLog($item);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the cached token.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clearToken(): void
|
||||
{
|
||||
$cacheKey = "integration_token:{$this->tenantCode}:{$this->integrationCode}";
|
||||
if (! $this->clientContext) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cacheKey = "integration_token:{$this->clientContext->id}:{$this->integrationCode}";
|
||||
Cache::forget($cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform initial setup validation for Telepagos.
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onSetup(): void
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\TelepagosPayment;
|
||||
use App\Domains\Purchase\Models\TelepagosQr;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -22,12 +22,15 @@ class TelepagosWebhookService
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function handleWebhook(string $tenantCodigo, string $cashinId): void
|
||||
public function handleWebhook(Client $client, string $cashinId): void
|
||||
{
|
||||
$tenant = Tenant::where('codigo', $tenantCodigo)->firstOrFail();
|
||||
Log::channel('telepagos')->info('Telepagos webhook received.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
$telepagosService->forClient($client);
|
||||
|
||||
try {
|
||||
$details = $telepagosService->getCashinDetails($cashinId);
|
||||
@@ -36,84 +39,9 @@ class TelepagosWebhookService
|
||||
$amount = $this->normalizeAmount($details['data']['amount'] ?? $details['amount'] ?? 0);
|
||||
$operationId = $details['data']['operation_id'] ?? $details['operation_id'] ?? null;
|
||||
|
||||
$transferenciaOperationIds = [1, 3, 11];
|
||||
$qrOperationIds = [31, 37, 47];
|
||||
|
||||
$compra = null;
|
||||
|
||||
if (in_array((int) $operationId, $transferenciaOperationIds, true)) {
|
||||
$cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null;
|
||||
|
||||
if (! $cuit) {
|
||||
Log::warning("Telepagos webhook: CUIT not found for Transferencia cashin {$cashinId}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$dni = substr($cuit, 2, -1);
|
||||
|
||||
$compra = Purchase::where('tenant_codigo', $tenantCodigo)
|
||||
->where('transfer_payer_dni', $dni)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
])
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
if (! $compra) {
|
||||
Log::warning("Telepagos webhook: No matching purchase found for DNI {$dni} and amount {$amount} for cashin {$cashinId}");
|
||||
|
||||
return;
|
||||
}
|
||||
} elseif (in_array((int) $operationId, $qrOperationIds, true)) {
|
||||
if (! $qrOrderId) {
|
||||
Log::warning("Telepagos webhook: qr_order_id not found for QR cashin {$cashinId}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
|
||||
|
||||
if (! $telepagosQr) {
|
||||
Log::warning("Telepagos webhook: QR {$qrOrderId} not found in database for cashin {$cashinId}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$compra = $telepagosQr->compra;
|
||||
|
||||
if (! $compra) {
|
||||
Log::warning("Telepagos webhook: Purchase not found for QR {$qrOrderId}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array($compra->status, [
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
Log::warning("Telepagos webhook: Purchase {$compra->id} is not awaiting payment confirmation");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$totalAmount = $this->normalizeAmount($compra->getTotalAmount());
|
||||
|
||||
if ($amount !== $totalAmount) {
|
||||
Log::warning("Telepagos webhook: Amount mismatch. Cashin amount: {$amount}, Purchase amount: {$totalAmount}");
|
||||
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
Log::warning("Telepagos webhook: Unknown operation_id {$operationId} for cashin {$cashinId}");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$paymentData = [
|
||||
'compra_id' => $compra->id,
|
||||
'compra_id' => null,
|
||||
'matched_purchase_ids' => null,
|
||||
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
|
||||
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
|
||||
'amount' => $amount,
|
||||
@@ -125,14 +53,153 @@ class TelepagosWebhookService
|
||||
'link_id' => $details['data']['link_id'] ?? $details['link_id'] ?? null,
|
||||
];
|
||||
|
||||
$transferenciaOperationIds = [1, 3, 11];
|
||||
$qrOperationIds = [31, 37, 47];
|
||||
|
||||
$compra = null;
|
||||
|
||||
if (in_array((int) $operationId, $transferenciaOperationIds, true)) {
|
||||
$cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null;
|
||||
|
||||
if (! $cuit) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: CUIT not found for transfer.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$dni = substr($cuit, 2, -1);
|
||||
|
||||
$tenantCodes = $client->tenants()->pluck('codigo');
|
||||
$purchases = Purchase::whereIn('tenant_codigo', $tenantCodes)
|
||||
->where('transfer_payer_dni', $dni)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
])
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->latest()
|
||||
->get();
|
||||
|
||||
$paymentData['matched_purchase_ids'] = $purchases->pluck('id')->all();
|
||||
$compra = $purchases->count() === 1 ? $purchases->first() : null;
|
||||
|
||||
if (! $compra) {
|
||||
if ($purchases->count() > 1) {
|
||||
TelepagosPayment::create($paymentData);
|
||||
}
|
||||
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'amount' => $amount,
|
||||
'matches' => $purchases->count(),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
} elseif (in_array((int) $operationId, $qrOperationIds, true)) {
|
||||
if (! $qrOrderId) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: qr_order_id not present in provider response.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
|
||||
|
||||
if (! $telepagosQr) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: QR not found in database.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$compra = $telepagosQr->compra;
|
||||
|
||||
if (! $compra) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Purchase not found for QR.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Purchase does not belong to client.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! in_array($compra->status, [
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Purchase is not awaiting payment confirmation.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
'purchase_status' => $compra->status,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$totalAmount = $this->normalizeAmount($compra->getTotalAmount());
|
||||
|
||||
if ($amount !== $totalAmount) {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Amount mismatch.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
'cashin_amount' => $amount,
|
||||
'purchase_amount' => $totalAmount,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
Log::channel('telepagos')->warning('Telepagos webhook: Unknown operation_id.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'operation_id' => $operationId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$paymentData['compra_id'] = $compra->id;
|
||||
|
||||
DB::transaction(function () use ($compra, $paymentData) {
|
||||
TelepagosPayment::create($paymentData);
|
||||
$this->checkoutService->confirmPaidPurchase($compra);
|
||||
});
|
||||
|
||||
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
|
||||
Log::channel('telepagos')->info('Telepagos webhook processed successfully.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'purchase_id' => $compra->id,
|
||||
'transaction_id' => $paymentData['transaction_id'],
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
Log::error('Telepagos webhook error: '.$e->getMessage());
|
||||
Log::channel('telepagos')->error('Telepagos webhook processing failed.', [
|
||||
'client_code' => $client->code,
|
||||
'cashin_id' => $cashinId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Integration\Services;
|
||||
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Integration\Models\TenantIntegration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class TenantIntegrationService
|
||||
{
|
||||
public function getTenantIntegration(string $tenantCode, string $integrationCode): ?TenantIntegration
|
||||
{
|
||||
return TenantIntegration::where('tenant_code', $tenantCode)
|
||||
->where('integration_code', $integrationCode)
|
||||
->first();
|
||||
}
|
||||
|
||||
public function getAllForTenant(string $tenantCode)
|
||||
{
|
||||
return TenantIntegration::with('integration')
|
||||
->where('tenant_code', $tenantCode)
|
||||
->get();
|
||||
}
|
||||
|
||||
public function updateOrCreateIntegration(string $tenantCode, Integration $integration, array $data): TenantIntegration
|
||||
{
|
||||
return DB::transaction(function () use ($tenantCode, $integration, $data) {
|
||||
$tenantIntegration = TenantIntegration::updateOrCreate(
|
||||
[
|
||||
'tenant_code' => $tenantCode,
|
||||
'integration_code' => $integration->integration_code,
|
||||
],
|
||||
[
|
||||
'integration_data' => $data,
|
||||
]
|
||||
);
|
||||
|
||||
$service = $this->resolveService($integration->integration_code);
|
||||
if ($service) {
|
||||
$service->forTenant($tenantCode)->onSetup();
|
||||
}
|
||||
|
||||
return $tenantIntegration;
|
||||
});
|
||||
}
|
||||
|
||||
protected function resolveService(string $integrationCode): ?BaseIntegrationService
|
||||
{
|
||||
switch ($integrationCode) {
|
||||
case 'email':
|
||||
return new MailService;
|
||||
case 'telepagos':
|
||||
case 'telepagos_homo':
|
||||
return new TelepagosIntegrationService($integrationCode);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,18 @@
|
||||
|
||||
## Propósito
|
||||
|
||||
Gestiona integraciones externas disponibles y su configuración por tenant. Incluye correo y pagos mediante Telepagos.
|
||||
Gestiona integraciones externas disponibles y su configuración por cliente. Un cliente puede agrupar múltiples tenants que comparten las mismas credenciales. Incluye correo y pagos mediante Telepagos.
|
||||
|
||||
## Modelo y seguridad
|
||||
|
||||
- `Integration`: definición global de una integración.
|
||||
- `TenantIntegration`: configuración y credenciales de una integración para un tenant.
|
||||
- `ClientIntegration`: configuración y credenciales de una integración para un cliente.
|
||||
- `EncryptedIntegrationData`: cast que protege los datos sensibles persistidos.
|
||||
- `TenantIntegrationService`: consulta y configura integraciones del tenant.
|
||||
- `ClientIntegrationService`: consulta y configura integraciones del cliente.
|
||||
|
||||
## Servicios externos
|
||||
|
||||
- `BaseIntegrationService`: base para resolver configuración, URL y cliente del tenant.
|
||||
- `BaseIntegrationService`: resuelve el cliente desde el tenant operativo y carga exclusivamente la configuración del cliente.
|
||||
- `MailService`: envío de correo usando la integración configurada.
|
||||
- `TelepagosIntegrationService`: autenticación, caché de token, generación de QR y consulta de cobros.
|
||||
- `TelepagosWebhookService`: procesa notificaciones recibidas desde Telepagos.
|
||||
@@ -21,9 +21,13 @@ Gestiona integraciones externas disponibles y su configuración por tenant. Incl
|
||||
## Endpoints
|
||||
|
||||
- CRUD global bajo `/integrations`.
|
||||
- Consulta y configuración por tenant bajo `/{tenant_code}/integrations`.
|
||||
- `POST /webhooks/telepagos/{tenant_codigo}` para notificaciones del proveedor.
|
||||
- Consulta y configuración por cliente bajo `/clients/{client}/integrations`.
|
||||
- `POST /webhooks/telepagos/{client}` para notificaciones del proveedor.
|
||||
|
||||
## Logging de Telepagos
|
||||
|
||||
Los eventos de autenticación, QR, consultas de cuenta y procesamiento de webhooks se escriben en el canal diario `telepagos`, separado del log general. Los archivos se generan en `storage/logs/telepagos/telepagos-YYYY-MM-DD.log`; el nivel y la retención se configuran con `TELEPAGOS_LOG_LEVEL` y `TELEPAGOS_LOG_DAYS`. Tokens y credenciales se eliminan del contexto antes de registrar respuestas del proveedor.
|
||||
|
||||
## Dependencias y reglas
|
||||
|
||||
Se integra con `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. Las credenciales no deben exponerse en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
Se integra con `Client`, `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. El tenant conserva el contexto operativo y de branding, pero nunca es dueño de credenciales. Las credenciales no se exponen en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Integration\Controllers\ClientIntegrationController;
|
||||
use App\Domains\Integration\Controllers\IntegrationController;
|
||||
use App\Domains\Integration\Controllers\TenantIntegrationController;
|
||||
use App\Domains\Integration\Controllers\TelepagosWebhookController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::group(['prefix' => 'integrations'], function () {
|
||||
@@ -12,10 +13,10 @@ Route::group(['prefix' => 'integrations'], function () {
|
||||
Route::delete('/{integration}', [IntegrationController::class, 'destroy']);
|
||||
});
|
||||
|
||||
Route::group(['prefix' => '{tenant_code}/integrations'], function () {
|
||||
Route::get('/', [TenantIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [TenantIntegrationController::class, 'show']);
|
||||
Route::post('/{integration_code}', [TenantIntegrationController::class, 'store']);
|
||||
Route::group(['prefix' => 'clients/{client}/integrations'], function () {
|
||||
Route::get('/', [ClientIntegrationController::class, 'index']);
|
||||
Route::get('/{integration_code}', [ClientIntegrationController::class, 'show']);
|
||||
Route::put('/{integration_code}', [ClientIntegrationController::class, 'store']);
|
||||
});
|
||||
|
||||
Route::post('webhooks/telepagos/{tenant_codigo}', [\App\Domains\Integration\Controllers\TelepagosWebhookController::class, 'handle']);
|
||||
Route::post('webhooks/telepagos/{client}', [TelepagosWebhookController::class, 'handle']);
|
||||
|
||||
@@ -61,6 +61,10 @@ class NotificationMailService
|
||||
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
|
||||
default => $tenant->dominio,
|
||||
};
|
||||
$recoveryBasePath = $channel === PasswordResetRequested::CHANNEL_STOREFRONT
|
||||
&& $tenant->base_path !== '/'
|
||||
? $tenant->base_path
|
||||
: '';
|
||||
$recoveryQuery = ['email' => $attempt->user->email];
|
||||
if (
|
||||
$channel === PasswordResetRequested::CHANNEL_SCANNER
|
||||
@@ -70,7 +74,7 @@ class NotificationMailService
|
||||
}
|
||||
$recoveryUrl = $recoveryDomain === null
|
||||
? null
|
||||
: 'https://'.$recoveryDomain.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
||||
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
|
||||
|
||||
$this->mailService
|
||||
->forTenant($tenantCode)
|
||||
|
||||
@@ -4,12 +4,12 @@ namespace App\Domains\Purchase\Controllers;
|
||||
|
||||
use App\Domains\Integration\Services\TelepagosIntegrationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Purchase\Requests\PaymentIntentRequest;
|
||||
use App\Domains\Purchase\Requests\StartCheckoutRequest;
|
||||
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest;
|
||||
use App\Domains\Purchase\Requests\UpdatePurchaseItemQuantityRequest;
|
||||
use App\Domains\Purchase\Requests\UpdatePurchaseItemRequest;
|
||||
use App\Domains\Purchase\Resources\PurchaseResource;
|
||||
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
@@ -52,12 +52,16 @@ class PurchaseController extends Controller
|
||||
return PurchaseResource::make($purchase)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Request $request, Tenant $tenant, Purchase $compra): PurchaseResource
|
||||
{
|
||||
public function show(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseResponseLoader $responses,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
$compra->loadMissing('items')->loadCount('tickets');
|
||||
$compra->items->load('imageAttachment');
|
||||
$responses->load($compra);
|
||||
|
||||
return PurchaseResource::make($compra);
|
||||
}
|
||||
@@ -75,8 +79,8 @@ class PurchaseController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function updateItemQuantity(
|
||||
UpdatePurchaseItemQuantityRequest $request,
|
||||
public function updateItem(
|
||||
UpdatePurchaseItemRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseItem $item,
|
||||
@@ -85,10 +89,12 @@ class PurchaseController extends Controller
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->updateItemQuantity(
|
||||
$checkoutService->updateItem(
|
||||
$compra,
|
||||
$item,
|
||||
(int) $request->validated('quantity'),
|
||||
$request->exists('quantity') ? (int) $request->validated('quantity') : null,
|
||||
$request->exists('variant_id') ? (int) $request->validated('variant_id') : null,
|
||||
$request->exists('variant_id'),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -98,16 +104,7 @@ class PurchaseController extends Controller
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->prepareItemEditing($compra),
|
||||
);
|
||||
}
|
||||
|
||||
public function paymentIntent(PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
|
||||
{
|
||||
): JsonResponse {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
$method = $request->validated('method');
|
||||
$totalAmount = $compra->calculateCurrentTotalAmount();
|
||||
@@ -148,13 +145,14 @@ class PurchaseController extends Controller
|
||||
return true;
|
||||
});
|
||||
|
||||
if ($updated === 0) {
|
||||
if (! $updated) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_available_for_payment'),
|
||||
]);
|
||||
}
|
||||
|
||||
$compra->refresh();
|
||||
$checkoutService->syncReservationExpiration($compra);
|
||||
|
||||
if ($method === 'transfer') {
|
||||
$telepagosService = new TelepagosIntegrationService;
|
||||
@@ -163,6 +161,11 @@ class PurchaseController extends Controller
|
||||
try {
|
||||
$accountInfo = $telepagosService->getAccountInfo();
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos account information retrieved.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'payment_method' => 'transfer',
|
||||
'transfer_data' => [
|
||||
@@ -174,9 +177,10 @@ class PurchaseController extends Controller
|
||||
],
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Unable to retrieve TelePagos account information.', [
|
||||
Log::channel('telepagos')->error('Unable to retrieve TelePagos account information.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'exception' => $e,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
@@ -191,7 +195,11 @@ class PurchaseController extends Controller
|
||||
$telepagosService->forTenant($tenant->codigo);
|
||||
|
||||
try {
|
||||
Log::info("Generating QR for purchase ID: {$compra->id}, amount: {$totalAmount}");
|
||||
Log::channel('telepagos')->info('Generating Telepagos QR.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'amount' => $totalAmount,
|
||||
]);
|
||||
$qrResponse = $telepagosService->generateQr(
|
||||
$totalAmount,
|
||||
'Compra',
|
||||
@@ -202,10 +210,17 @@ class PurchaseController extends Controller
|
||||
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
|
||||
'qr_code' => $qrResponse['qr_code'] ?? '',
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Unable to generate TelePagos QR code.', [
|
||||
|
||||
Log::channel('telepagos')->info('Telepagos QR generated successfully.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'exception' => $e,
|
||||
'qr_order_id' => $telepagosQr->qr_order_id,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::channel('telepagos')->error('Unable to generate TelePagos QR code.', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'purchase_id' => $compra->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Exceptions;
|
||||
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PurchaseLimitExceededException extends ValidationException
|
||||
{
|
||||
public readonly int $catalogItemId;
|
||||
|
||||
public readonly string $catalogItemName;
|
||||
|
||||
public readonly int $maximumAddableQuantity;
|
||||
|
||||
public function __construct(CatalogItem $catalogItem, int $maximumAddableQuantity, string $field)
|
||||
{
|
||||
$this->catalogItemId = (int) $catalogItem->getKey();
|
||||
$this->catalogItemName = $catalogItem->nombre;
|
||||
$this->maximumAddableQuantity = $maximumAddableQuantity;
|
||||
|
||||
parent::__construct(validator([], []));
|
||||
|
||||
$message = trans_choice('api.purchase_limit.exceeded', $maximumAddableQuantity, [
|
||||
'max' => $maximumAddableQuantity,
|
||||
'product' => $this->catalogItemName,
|
||||
]);
|
||||
$this->message = $message;
|
||||
$this->validator->errors()->add($field, $message);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
@@ -116,6 +117,12 @@ class Purchase extends Model
|
||||
return $this->hasMany(Ticket::class, 'source_purchase_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<StockReservation, $this> */
|
||||
public function stockReservations(): HasMany
|
||||
{
|
||||
return $this->hasMany(StockReservation::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasOne<TelepagosQr, $this>
|
||||
*/
|
||||
@@ -143,11 +150,16 @@ class Purchase extends Model
|
||||
|
||||
public function calculateCurrentTotalAmount(): float
|
||||
{
|
||||
if ($this->relationLoaded('items')) {
|
||||
if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) {
|
||||
return (float) $this->getRelation('items')->sum('total');
|
||||
}
|
||||
|
||||
return (float) $this->items()->sum('total');
|
||||
$itemsTotal = (float) $this->items()->sum('total');
|
||||
if ($itemsTotal > 0 || $this->items()->exists()) {
|
||||
return $itemsTotal;
|
||||
}
|
||||
|
||||
return (float) ($this->cart?->getTotalAmount() ?? $this->total ?? 0);
|
||||
}
|
||||
|
||||
protected function valueChangeTenantCode(): string
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -23,18 +25,11 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
'discount_total',
|
||||
'tax_total',
|
||||
'total',
|
||||
'reservation_status',
|
||||
])]
|
||||
class PurchaseItem extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public const RESERVATION_ACTIVE = 'active';
|
||||
|
||||
public const RESERVATION_COMMITTED = 'committed';
|
||||
|
||||
public const RESERVATION_RELEASED = 'released';
|
||||
|
||||
protected $table = 'compra_items';
|
||||
|
||||
protected function casts(): array
|
||||
@@ -66,4 +61,16 @@ class PurchaseItem extends Model
|
||||
{
|
||||
return $this->belongsTo(Attachment::class, 'image_attachment_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<CatalogItem, $this> */
|
||||
public function sourceCatalogItem(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Variant, $this> */
|
||||
public function sourceVariant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Variant::class, 'source_variant_id')->withTrashed();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'compra_id',
|
||||
'matched_purchase_ids',
|
||||
'cuit_buyer',
|
||||
'cvu_buyer',
|
||||
'amount',
|
||||
@@ -29,6 +30,7 @@ class TelepagosPayment extends Model
|
||||
{
|
||||
return [
|
||||
'compra_id' => 'integer',
|
||||
'matched_purchase_ids' => 'array',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdatePurchaseItemQuantityRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'quantity' => ['required', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Domains/Purchase/Requests/UpdatePurchaseItemRequest.php
Normal file
22
app/Domains/Purchase/Requests/UpdatePurchaseItemRequest.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdatePurchaseItemRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'quantity' => ['sometimes', 'required_without:variant_id', 'integer', 'min:1', 'max:100'],
|
||||
'variant_id' => ['sometimes', 'required_without:quantity', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
namespace App\Domains\Purchase\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
@@ -15,10 +17,23 @@ class PurchaseItemResource extends JsonResource
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$tenant = $request->route('tenant');
|
||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||
|
||||
if ($this->resource instanceof PurchaseItem) {
|
||||
$imageUrl = $this->imageAttachment?->getTemporaryUrl(1440);
|
||||
$imageUrl = $displayImage
|
||||
? $this->imageAttachment?->getTemporaryUrl(1440)
|
||||
: null;
|
||||
$attributes = $this->variant_attributes ?? [];
|
||||
|
||||
$catalogItem = $this->relationLoaded('sourceCatalogItem')
|
||||
? $this->sourceCatalogItem
|
||||
: null;
|
||||
$includeVariants = $tenant instanceof Tenant
|
||||
&& $tenant->cart_editing_policy->allowsVariantChanges()
|
||||
&& $catalogItem !== null
|
||||
&& $catalogItem->relationLoaded('variants');
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'quantity' => (int) $this->cantidad,
|
||||
@@ -33,6 +48,13 @@ class PurchaseItemResource extends JsonResource
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $attributes,
|
||||
],
|
||||
'variants' => $this->when(
|
||||
$includeVariants,
|
||||
fn () => $catalogItem
|
||||
->visibleVariants($this->source_variant_id)
|
||||
->map(fn (Variant $variant): array => $this->variantData($catalogItem, $variant))
|
||||
->values(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -42,29 +64,21 @@ class PurchaseItemResource extends JsonResource
|
||||
$quantity = (int) ($this->cantidad ?? 0);
|
||||
$unitPrice = $this->resolveUnitPrice($selectedItem);
|
||||
$lineTotal = $unitPrice * $quantity;
|
||||
$imageUrl = $this->resolveImageUrl($selectedItem, $catalogItem);
|
||||
$imageUrl = $displayImage
|
||||
? $this->resolveImageUrl($selectedItem, $catalogItem)
|
||||
: null;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'quantity' => $quantity,
|
||||
'unit_price' => $this->formatMoney($unitPrice),
|
||||
'line_total' => $this->formatMoney($lineTotal),
|
||||
'catalog_item_id' => $this->catalog_item_id,
|
||||
'variant_id' => $this->variant_id,
|
||||
'product' => $catalogItem === null ? null : [
|
||||
'id' => $catalogItem->id,
|
||||
'nombre' => $catalogItem->nombre,
|
||||
'descripcion' => $catalogItem->descripcion,
|
||||
'slug' => $catalogItem->slug,
|
||||
'imagen' => $imageUrl,
|
||||
],
|
||||
'variant' => $variant === null ? null : [
|
||||
'id' => $variant->id,
|
||||
'attributes' => $this->resolveAttributes($variant),
|
||||
],
|
||||
'source_catalog_item_id' => $this->catalog_item_id,
|
||||
'source_variant_id' => $this->variant_id,
|
||||
'item_details' => $selectedItem === null ? null : [
|
||||
'nombre' => $selectedItem->getName(),
|
||||
'descripcion' => $selectedItem->getDescription(),
|
||||
'slug' => $catalogItem?->slug,
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
|
||||
],
|
||||
@@ -134,4 +148,17 @@ class PurchaseItemResource extends JsonResource
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
||||
{
|
||||
return [
|
||||
'id' => $variant->id,
|
||||
'precio' => $this->formatMoney($variant->precio ?? $catalogItem->precio),
|
||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||
? null
|
||||
: $variant->inventory->availableStock(),
|
||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domains\Purchase\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -17,26 +18,37 @@ class PurchaseResource extends JsonResource
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$items = $this->resource->relationLoaded('items')
|
||||
$purchaseItems = $this->resource->relationLoaded('items')
|
||||
? $this->resource->getRelation('items')
|
||||
: collect();
|
||||
$cartItems = $purchaseItems->isEmpty()
|
||||
&& $this->resource->relationLoaded('cart')
|
||||
&& $this->resource->getRelation('cart')?->relationLoaded('items')
|
||||
? $this->resource->getRelation('cart')->getRelation('items')
|
||||
: collect();
|
||||
$items = $purchaseItems->isNotEmpty() ? $purchaseItems : $cartItems;
|
||||
$itemsSource = $purchaseItems->isNotEmpty()
|
||||
? 'purchase'
|
||||
: ($cartItems->isNotEmpty() ? 'cart' : null);
|
||||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
||||
? (int) $this->resource->getAttribute('tickets_count')
|
||||
: null;
|
||||
|
||||
$subtotal = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemSubtotal($item),
|
||||
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemSubtotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
|
||||
$total = $items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0);
|
||||
$total = $this->status === Purchase::STATUS_PAID && $this->total !== null
|
||||
? (float) $this->total
|
||||
: ($items->isNotEmpty()
|
||||
? $items->reduce(
|
||||
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
|
||||
0.0,
|
||||
)
|
||||
: (float) ($this->total ?? 0));
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
@@ -52,7 +64,7 @@ class PurchaseResource extends JsonResource
|
||||
'telefono' => $this->telefono,
|
||||
'nombre_apellido' => $this->nombre_apellido,
|
||||
'email' => $this->email,
|
||||
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
|
||||
'items_source' => $itemsSource,
|
||||
'items' => PurchaseItemResource::collection($items),
|
||||
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
|
||||
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
|
||||
@@ -61,13 +73,21 @@ class PurchaseResource extends JsonResource
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveItemSubtotal(PurchaseItem $item): float
|
||||
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
|
||||
{
|
||||
if ($item instanceof CartItem) {
|
||||
return (float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
|
||||
}
|
||||
|
||||
return (float) $item->precio_unitario * $item->cantidad;
|
||||
}
|
||||
|
||||
protected function resolveItemTotal(PurchaseItem $item): float
|
||||
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
|
||||
{
|
||||
if ($item instanceof CartItem) {
|
||||
return $this->resolveItemSubtotal($item);
|
||||
}
|
||||
|
||||
return (float) ($item->total ?? 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ namespace App\Domains\Purchase\Services\Checkout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Inventory;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
@@ -79,13 +78,4 @@ class CatalogSelectionResolver
|
||||
|
||||
return $variant;
|
||||
}
|
||||
|
||||
public function resolvePurchaseItem(Tenant $tenant, PurchaseItem $item): CatalogItem|Variant
|
||||
{
|
||||
return $this->resolve(
|
||||
$tenant,
|
||||
(int) $item->source_catalog_item_id,
|
||||
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,18 +2,19 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class CompleteCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $inventory,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
) {}
|
||||
|
||||
public function complete(Purchase $purchase): Purchase
|
||||
@@ -59,6 +60,7 @@ class CompleteCheckoutService
|
||||
}
|
||||
|
||||
$purchase->update(['expires_at' => null]);
|
||||
$this->reservations->syncPurchaseExpiration($purchase);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
@@ -83,25 +85,51 @@ class CompleteCheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
$items = $purchase->items()
|
||||
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
if ($purchase->items()->exists()) {
|
||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||
if ($cart?->status === 'converted' && $cart->trashed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($items as $item) {
|
||||
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item);
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
$this->inventory->commit($selection, (int) $item->cantidad);
|
||||
} catch (\InvalidArgumentException) {
|
||||
$cart = $purchase->cart()->lockForUpdate()->first();
|
||||
if ($cart === null || $cart->status !== 'checkout') {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||
if ($cartItems->isEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$this->loadCartItems($cartItems);
|
||||
$purchase->items()->createMany(
|
||||
$this->snapshots->fromCartItems($cartItems),
|
||||
);
|
||||
|
||||
foreach ($cartItems as $cartItem) {
|
||||
$selection = $cartItem->selectedItem();
|
||||
if ($selection === null) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$item->update([
|
||||
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED,
|
||||
]);
|
||||
try {
|
||||
$this->reservations->commit($cartItem, $selection);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$this->sourceCart->finalize($purchase);
|
||||
@@ -126,6 +154,30 @@ class CompleteCheckoutService
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $purchase->load(['items.imageAttachment']);
|
||||
return $purchase->load([
|
||||
'items.imageAttachment',
|
||||
'cart.items.catalogItem.inventory',
|
||||
'cart.items.catalogItem.attachments',
|
||||
'cart.items.variant.inventory',
|
||||
'cart.items.variant.attachments',
|
||||
'cart.items.variant.definitions.itemAttribute.attribute',
|
||||
'cart.items.variant.eventDates',
|
||||
'cart.items.variant.eventDate',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param Collection<int, CartItem> $cartItems */
|
||||
private function loadCartItems(Collection $cartItems): void
|
||||
{
|
||||
$cartItems->load([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.attachments',
|
||||
'variant.inventory',
|
||||
'variant.attachments',
|
||||
'variant.catalogItem',
|
||||
'variant.definitions.itemAttribute.attribute',
|
||||
'variant.eventDates',
|
||||
'variant.eventDate',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ class EditCheckoutService
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
private readonly PurchaseResponseLoader $responses,
|
||||
) {}
|
||||
|
||||
/** @param array<string, string> $customerData */
|
||||
@@ -33,12 +35,20 @@ class EditCheckoutService
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItemQuantity(
|
||||
public function updateItem(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
int $quantity,
|
||||
?int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Purchase {
|
||||
return DB::transaction(function () use ($purchase, $purchaseItem, $quantity): Purchase {
|
||||
return DB::transaction(function () use (
|
||||
$purchase,
|
||||
$purchaseItem,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
|
||||
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
|
||||
@@ -48,16 +58,40 @@ class EditCheckoutService
|
||||
}
|
||||
|
||||
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
|
||||
$difference = $quantity - (int) $purchaseItem->cantidad;
|
||||
$tenant = $purchase->tenant()->firstOrFail();
|
||||
$finalQuantity = $quantity ?? (int) $purchaseItem->cantidad;
|
||||
|
||||
if ($difference !== 0) {
|
||||
$this->adjustReservation($purchase, $purchaseItem, $quantity, $difference);
|
||||
|
||||
$purchaseItem->update([
|
||||
'cantidad' => $quantity,
|
||||
'total' => (float) $purchaseItem->precio_unitario * $quantity,
|
||||
if ($quantity !== null && ! $tenant->cart_editing_policy->allowsQuantityChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'quantity' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $quantity);
|
||||
}
|
||||
|
||||
if ($updateVariant && ! $tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.purchase.variant_change_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($updateVariant && $variantId !== $purchaseItem->source_variant_id) {
|
||||
$this->changeItemVariant(
|
||||
$purchase,
|
||||
$purchaseItem,
|
||||
(int) $variantId,
|
||||
$finalQuantity,
|
||||
);
|
||||
} else {
|
||||
$difference = $finalQuantity - (int) $purchaseItem->cantidad;
|
||||
|
||||
if ($difference !== 0) {
|
||||
$this->adjustReservation($purchase, $purchaseItem, $finalQuantity, $difference);
|
||||
|
||||
$purchaseItem->update([
|
||||
'cantidad' => $finalQuantity,
|
||||
'total' => (float) $purchaseItem->precio_unitario * $finalQuantity,
|
||||
]);
|
||||
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $finalQuantity);
|
||||
}
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
@@ -68,12 +102,94 @@ class EditCheckoutService
|
||||
});
|
||||
}
|
||||
|
||||
private function changeItemVariant(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $sourceItem,
|
||||
int $variantId,
|
||||
int $quantity,
|
||||
): void {
|
||||
$tenant = $purchase->tenant()->firstOrFail();
|
||||
$currentSelection = $this->selections->resolvePurchaseItem($tenant, $sourceItem);
|
||||
$targetSelection = $this->selections->resolve(
|
||||
$tenant,
|
||||
(int) $sourceItem->source_catalog_item_id,
|
||||
$variantId,
|
||||
'item',
|
||||
);
|
||||
|
||||
if (! $targetSelection instanceof Variant) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.variant_required'),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @var PurchaseItem|null $targetItem */
|
||||
$targetItem = $purchase->items()
|
||||
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
|
||||
->where('source_variant_id', $targetSelection->id)
|
||||
->whereKeyNot($sourceItem->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($targetItem !== null && $targetItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.purchase.item_not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
$otherItemQuantity = (int) $purchase->items()
|
||||
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
|
||||
->whereKeyNot($sourceItem->getKey())
|
||||
->sum('cantidad');
|
||||
$this->purchaseLimits->assertCanPurchase(
|
||||
$targetSelection->catalogItem,
|
||||
(int) $purchase->user_id,
|
||||
$otherItemQuantity + $quantity,
|
||||
$purchase->getKey(),
|
||||
'variant_id',
|
||||
);
|
||||
|
||||
try {
|
||||
$this->inventory->release($currentSelection, (int) $sourceItem->cantidad);
|
||||
$this->inventory->reserve($targetSelection, $quantity);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.purchase.insufficient_stock'),
|
||||
]);
|
||||
}
|
||||
|
||||
$previousVariantId = $sourceItem->source_variant_id;
|
||||
$finalQuantity = $quantity;
|
||||
|
||||
if ($targetItem !== null) {
|
||||
$finalQuantity += (int) $targetItem->cantidad;
|
||||
$targetItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
|
||||
$sourceItem->delete();
|
||||
} else {
|
||||
$sourceItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
|
||||
}
|
||||
|
||||
$this->sourceCart->syncItemSelection(
|
||||
$purchase,
|
||||
(int) $sourceItem->source_catalog_item_id,
|
||||
$previousVariantId,
|
||||
$targetSelection->id,
|
||||
$finalQuantity,
|
||||
);
|
||||
}
|
||||
|
||||
public function prepareItemEditing(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->assertEditable($purchase);
|
||||
|
||||
if (! $purchase->tenant()->firstOrFail()->cart_editing_policy->allowsModification()) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$purchase->telepagosQr()->delete();
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
@@ -170,6 +286,6 @@ class EditCheckoutService
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $purchase->load(['items.imageAttachment']);
|
||||
return $this->responses->load($purchase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,39 @@ namespace App\Domains\Purchase\Services\Checkout;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class PurchaseItemSnapshotFactory
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function fromVariant(Variant $variant, int $quantity): array
|
||||
{
|
||||
$variant->loadMissing([
|
||||
'attachments',
|
||||
'catalogItem.attachments',
|
||||
'definitions.itemAttribute.attribute.options',
|
||||
'eventDates',
|
||||
'eventDate',
|
||||
]);
|
||||
$unitPrice = $variant->getPrice();
|
||||
|
||||
return [
|
||||
'source_variant_id' => $variant->id,
|
||||
'image_attachment_id' => $variant->attachments->first()?->id
|
||||
?? $variant->catalogItem->attachments->first()?->id,
|
||||
'nombre' => $variant->catalogItem->nombre,
|
||||
'descripcion' => $variant->getDescription(),
|
||||
'slug' => $variant->catalogItem->slug,
|
||||
'item_nombre' => $variant->getName(),
|
||||
'variant_attributes' => $this->snapshotAttributes($variant),
|
||||
'cantidad' => $quantity,
|
||||
'precio_unitario' => $unitPrice,
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => $unitPrice * $quantity,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CartItem> $cartItems
|
||||
* @return array<int, array<string, mixed>>
|
||||
@@ -38,7 +66,6 @@ class PurchaseItemSnapshotFactory
|
||||
'discount_total' => null,
|
||||
'tax_total' => null,
|
||||
'total' => $unitPrice * $quantity,
|
||||
'reservation_status' => PurchaseItem::RESERVATION_ACTIVE,
|
||||
];
|
||||
})
|
||||
->all();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
|
||||
class PurchaseResponseLoader
|
||||
{
|
||||
public function load(Purchase $purchase): Purchase
|
||||
{
|
||||
$purchase->load(['tenant', 'items.imageAttachment']);
|
||||
|
||||
if (! $purchase->tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||
return $purchase;
|
||||
}
|
||||
|
||||
$purchase->load([
|
||||
'items.sourceCatalogItem.itemAttributes.attribute',
|
||||
'items.sourceCatalogItem.variants' => fn ($query) => $query->orderBy('id'),
|
||||
'items.sourceCatalogItem.variants.inventory',
|
||||
'items.sourceCatalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'items.sourceCatalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'items.sourceCatalogItem.variants.eventDates',
|
||||
'items.sourceCatalogItem.variants.eventDate',
|
||||
]);
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,16 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ReleaseCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $inventory,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
) {}
|
||||
|
||||
@@ -77,38 +76,71 @@ class ReleaseCheckoutService
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
|
||||
$items = $purchase->items()
|
||||
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
|
||||
->lockForUpdate()
|
||||
->get();
|
||||
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
|
||||
|
||||
foreach ($items as $item) {
|
||||
if (! $reservationReturnedToCart) {
|
||||
$this->releaseInventory($purchase, $item);
|
||||
}
|
||||
|
||||
$item->update([
|
||||
'reservation_status' => PurchaseItem::RESERVATION_RELEASED,
|
||||
if ($purchase->items()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
|
||||
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
|
||||
$this->releaseCartReservations($purchase, $reservationReturnedToCart, $targetStatus);
|
||||
|
||||
$purchase->update(['status' => $targetStatus]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
private function releaseInventory(Purchase $purchase, PurchaseItem $item): void
|
||||
{
|
||||
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item);
|
||||
private function releaseCartReservations(
|
||||
Purchase $purchase,
|
||||
bool $reservationReturnedToCart,
|
||||
string $targetStatus,
|
||||
): void {
|
||||
if ($reservationReturnedToCart) {
|
||||
$this->reservations->detachFromPurchase($purchase);
|
||||
|
||||
try {
|
||||
$this->inventory->release($selection, (int) $item->cantidad);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||
if ($cart === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||
$cartItems->load([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.variant.inventory',
|
||||
'variant.inventory',
|
||||
'variant.catalogItem',
|
||||
]);
|
||||
|
||||
foreach ($cartItems as $cartItem) {
|
||||
$selection = $cartItem->selectedItem();
|
||||
if ($selection === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->reservations->release(
|
||||
$cartItem,
|
||||
$selection,
|
||||
(int) $cartItem->cantidad,
|
||||
$targetStatus === Purchase::STATUS_EXPIRED
|
||||
? StockReservation::STATUS_EXPIRED
|
||||
: StockReservation::STATUS_RELEASED,
|
||||
);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'items' => __('api.purchase.inconsistent_reservation'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (! $cart->trashed()) {
|
||||
$cart->update(['status' => 'converted']);
|
||||
$cart->delete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +161,15 @@ class ReleaseCheckoutService
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $purchase->load(['items.imageAttachment']);
|
||||
return $purchase->load([
|
||||
'items.imageAttachment',
|
||||
'cart.items.catalogItem.inventory',
|
||||
'cart.items.catalogItem.attachments',
|
||||
'cart.items.variant.inventory',
|
||||
'cart.items.variant.attachments',
|
||||
'cart.items.variant.definitions.itemAttribute.attribute',
|
||||
'cart.items.variant.eventDates',
|
||||
'cart.items.variant.eventDate',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,15 @@ namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
|
||||
class SourceCartService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
) {}
|
||||
|
||||
public function restore(Purchase $purchase): bool
|
||||
{
|
||||
$sourceCart = $this->findSourceCart($purchase);
|
||||
@@ -17,6 +21,10 @@ class SourceCartService
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($sourceCart->origin === Cart::ORIGIN_DIRECT_CHECKOUT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var Cart|null $activeCart */
|
||||
$activeCart = Cart::query()
|
||||
->where('tenant_codigo', $purchase->tenant_codigo)
|
||||
@@ -71,6 +79,57 @@ class SourceCartService
|
||||
->update(['cantidad' => $quantity]);
|
||||
}
|
||||
|
||||
public function syncItemSelection(
|
||||
Purchase $purchase,
|
||||
int $catalogItemId,
|
||||
?int $previousVariantId,
|
||||
int $newVariantId,
|
||||
int $finalQuantity,
|
||||
): void {
|
||||
$sourceCart = $this->findSourceCart($purchase);
|
||||
|
||||
if ($sourceCart === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var CartItem|null $previousItem */
|
||||
$previousItem = $sourceCart->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->where('variant_id', $previousVariantId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
/** @var CartItem|null $targetItem */
|
||||
$targetItem = $sourceCart->items()
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->where('variant_id', $newVariantId)
|
||||
->when($previousItem !== null, fn ($query) => $query->whereKeyNot($previousItem->getKey()))
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($targetItem !== null) {
|
||||
$targetItem->update(['cantidad' => $finalQuantity]);
|
||||
$previousItem?->delete();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($previousItem !== null) {
|
||||
$previousItem->update([
|
||||
'variant_id' => $newVariantId,
|
||||
'cantidad' => $finalQuantity,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$sourceCart->items()->create([
|
||||
'catalog_item_id' => $catalogItemId,
|
||||
'variant_id' => $newVariantId,
|
||||
'cantidad' => $finalQuantity,
|
||||
]);
|
||||
}
|
||||
|
||||
public function finalize(Purchase $purchase): void
|
||||
{
|
||||
$sourceCart = $this->findSourceCart($purchase);
|
||||
@@ -112,7 +171,7 @@ class SourceCartService
|
||||
->first();
|
||||
|
||||
if ($activeItem === null) {
|
||||
$activeCart->items()->create([
|
||||
$activeItem = $activeCart->items()->create([
|
||||
'catalog_item_id' => $sourceItem->catalog_item_id,
|
||||
'variant_id' => $sourceItem->variant_id,
|
||||
'cantidad' => $sourceItem->cantidad,
|
||||
@@ -120,6 +179,8 @@ class SourceCartService
|
||||
} else {
|
||||
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
|
||||
}
|
||||
|
||||
$this->reservations->transfer($sourceItem, $activeItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
@@ -20,10 +21,11 @@ class StartCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $inventory,
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||
private readonly PurchaseResponseLoader $responses,
|
||||
) {}
|
||||
|
||||
/** @param array<string, mixed> $purchaseData */
|
||||
@@ -118,10 +120,16 @@ class StartCheckoutService
|
||||
->each(function (Collection $catalogLines) use ($userId): void {
|
||||
/** @var CatalogItem $catalogItem */
|
||||
$catalogItem = $catalogLines->first()['catalog_item'];
|
||||
$availableQuantities = $catalogLines
|
||||
->map(fn (array $line): ?int => $this->inventory->availableQuantity($line['selection']));
|
||||
$maximumAddableCeiling = $availableQuantities->contains(null)
|
||||
? null
|
||||
: (int) $availableQuantities->sum();
|
||||
$this->purchaseLimits->assertCanPurchase(
|
||||
$catalogItem,
|
||||
$userId,
|
||||
(int) $catalogLines->sum('quantity'),
|
||||
maximumAddableCeiling: $maximumAddableCeiling,
|
||||
field: 'direct_items',
|
||||
);
|
||||
});
|
||||
@@ -144,9 +152,24 @@ class StartCheckoutService
|
||||
throw new InsufficientStockException($unavailableItems);
|
||||
}
|
||||
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $userId,
|
||||
'guest_token' => null,
|
||||
'status' => 'checkout',
|
||||
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
|
||||
]);
|
||||
|
||||
$cartItems = collect();
|
||||
foreach ($resolvedLines as $line) {
|
||||
$cartItem = $cart->items()->create([
|
||||
'catalog_item_id' => $line['catalog_item_id'],
|
||||
'variant_id' => $line['variant_id'],
|
||||
'cantidad' => $line['quantity'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$this->inventory->reserve($line['selection'], $line['quantity']);
|
||||
$this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
|
||||
} catch (\InvalidArgumentException) {
|
||||
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
|
||||
|
||||
@@ -154,6 +177,10 @@ class StartCheckoutService
|
||||
$this->unavailableItem($line, $availableQuantity),
|
||||
]);
|
||||
}
|
||||
|
||||
$cartItem->setRelation('catalogItem', $line['catalog_item']);
|
||||
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
|
||||
$cartItems->push($cartItem);
|
||||
}
|
||||
|
||||
$purchase = $this->createPurchase(
|
||||
@@ -163,19 +190,16 @@ class StartCheckoutService
|
||||
(float) $resolvedLines->sum(
|
||||
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
|
||||
),
|
||||
null,
|
||||
$cart->getKey(),
|
||||
);
|
||||
|
||||
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem(
|
||||
$line['selection'],
|
||||
$line['catalog_item_id'],
|
||||
$line['variant_id'],
|
||||
$line['quantity'],
|
||||
));
|
||||
|
||||
$purchase->items()->createMany(
|
||||
$this->snapshots->fromCartItems($directCartItems),
|
||||
);
|
||||
foreach ($cartItems as $index => $cartItem) {
|
||||
$this->reservations->attachToPurchase(
|
||||
$cartItem,
|
||||
$resolvedLines->get($index)['selection'],
|
||||
$purchase,
|
||||
);
|
||||
}
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
}
|
||||
@@ -225,7 +249,7 @@ class StartCheckoutService
|
||||
|
||||
$this->loadCartItems($cartItems);
|
||||
$this->verifyTenantItems($tenant, $cartItems);
|
||||
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems);
|
||||
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
|
||||
$cart->setRelation('items', $cartItems);
|
||||
|
||||
$purchase = $this->createPurchase(
|
||||
@@ -235,7 +259,13 @@ class StartCheckoutService
|
||||
$cart->getTotalAmount(),
|
||||
$cart->getKey(),
|
||||
);
|
||||
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||
foreach ($cartItems as $cartItem) {
|
||||
$this->reservations->attachToPurchase(
|
||||
$cartItem,
|
||||
$cartItem->selectedItem(),
|
||||
$purchase,
|
||||
);
|
||||
}
|
||||
|
||||
// The purchase owns the reservation until checkout finishes. The cart is
|
||||
// retained so it can be restored if the purchase is cancelled or expires.
|
||||
@@ -288,6 +318,7 @@ class StartCheckoutService
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
Collection $cartItems,
|
||||
int $cartId,
|
||||
): void {
|
||||
$quantities = $cartItems
|
||||
->groupBy('catalog_item_id')
|
||||
@@ -309,6 +340,8 @@ class StartCheckoutService
|
||||
$catalogItem,
|
||||
$userId,
|
||||
$quantity,
|
||||
excludedCartId: $cartId,
|
||||
heldQuantity: $quantity,
|
||||
field: 'cart_id',
|
||||
);
|
||||
}
|
||||
@@ -336,35 +369,6 @@ class StartCheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
private function makeDirectCartItem(
|
||||
CatalogItem|Variant $selection,
|
||||
int $catalogItemId,
|
||||
?int $variantId,
|
||||
int $quantity,
|
||||
): CartItem {
|
||||
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
|
||||
$catalogItem->loadMissing(['inventory', 'attachments']);
|
||||
|
||||
if ($selection instanceof Variant) {
|
||||
$selection->loadMissing([
|
||||
'inventory',
|
||||
'attachments',
|
||||
'catalogItem',
|
||||
'definitions.itemAttribute.attribute',
|
||||
]);
|
||||
}
|
||||
|
||||
$item = new CartItem([
|
||||
'catalog_item_id' => $catalogItemId,
|
||||
'variant_id' => $variantId,
|
||||
'cantidad' => $quantity,
|
||||
]);
|
||||
$item->setRelation('catalogItem', $catalogItem);
|
||||
$item->setRelation('variant', $selection instanceof Variant ? $selection : null);
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/** @param Collection<int, CartItem> $cartItems */
|
||||
private function loadCartItems(Collection $cartItems): void
|
||||
{
|
||||
@@ -382,6 +386,6 @@ class StartCheckoutService
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
return $purchase->load(['items.imageAttachment']);
|
||||
return $this->responses->load($purchase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
|
||||
use App\Domains\Purchase\Services\Checkout\EditCheckoutService;
|
||||
use App\Domains\Purchase\Services\Checkout\ReleaseCheckoutService;
|
||||
@@ -23,6 +23,7 @@ class CheckoutService
|
||||
private readonly EditCheckoutService $editor,
|
||||
private readonly CompleteCheckoutService $completer,
|
||||
private readonly ReleaseCheckoutService $releaser,
|
||||
private readonly StockReservationService $reservations,
|
||||
) {}
|
||||
|
||||
/** @param array<string, mixed> $purchaseData */
|
||||
@@ -47,12 +48,20 @@ class CheckoutService
|
||||
return $this->editor->updateCustomer($purchase, $customerData);
|
||||
}
|
||||
|
||||
public function updateItemQuantity(
|
||||
public function updateItem(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
int $quantity,
|
||||
?int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Purchase {
|
||||
return $this->editor->updateItemQuantity($purchase, $purchaseItem, $quantity);
|
||||
return $this->editor->updateItem(
|
||||
$purchase,
|
||||
$purchaseItem,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
);
|
||||
}
|
||||
|
||||
public function prepareItemEditing(Purchase $purchase): Purchase
|
||||
@@ -94,4 +103,9 @@ class CheckoutService
|
||||
{
|
||||
return $this->releaser->expireOverdue();
|
||||
}
|
||||
|
||||
public function syncReservationExpiration(Purchase $purchase): void
|
||||
{
|
||||
$this->reservations->syncPurchaseExpiration($purchase);
|
||||
}
|
||||
}
|
||||
|
||||
145
app/Domains/Purchase/Services/TenantTransactionResetService.php
Normal file
145
app/Domains/Purchase/Services/TenantTransactionResetService.php
Normal file
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class TenantTransactionResetService
|
||||
{
|
||||
/** @return array<string, int> */
|
||||
public function preview(string $tenantCode): array
|
||||
{
|
||||
$this->ensureTenantExists($tenantCode);
|
||||
$scope = $this->scope($tenantCode);
|
||||
|
||||
return [
|
||||
'users_preserved' => DB::table('users')->where('tenant_codigo', $tenantCode)->count(),
|
||||
'purchases' => $scope['purchase_ids']->count(),
|
||||
'purchase_items' => DB::table('compra_items')->whereIn('compra_id', $scope['purchase_ids'])->count(),
|
||||
'telepagos_payments' => DB::table('telepagos_payments')->whereIn('compra_id', $scope['purchase_ids'])->count(),
|
||||
'telepagos_qr' => DB::table('telepagos_qr')->whereIn('compra_id', $scope['purchase_ids'])->count(),
|
||||
'carts' => $scope['cart_ids']->count(),
|
||||
'cart_items' => $scope['cart_item_ids']->count(),
|
||||
'tickets' => DB::table('tickets')->where('tenant_code', $tenantCode)->count(),
|
||||
'stock_reservations' => $this->reservationQuery($scope)->count(),
|
||||
'purchase_changes' => DB::table('value_changes')
|
||||
->where('tenant_code', $tenantCode)
|
||||
->where('trackable_type', Purchase::class)
|
||||
->count(),
|
||||
'inventories' => $scope['inventory_ids']->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, int> */
|
||||
public function reset(string $tenantCode): array
|
||||
{
|
||||
$this->ensureTenantExists($tenantCode);
|
||||
|
||||
return DB::transaction(function () use ($tenantCode): array {
|
||||
$scope = $this->scope($tenantCode);
|
||||
$purchaseItems = DB::table('compra_items')->whereIn('compra_id', $scope['purchase_ids'])->count();
|
||||
$cartItems = $scope['cart_item_ids']->count();
|
||||
$telepagosPayments = DB::table('telepagos_payments')->whereIn('compra_id', $scope['purchase_ids'])->count();
|
||||
$telepagosQr = DB::table('telepagos_qr')->whereIn('compra_id', $scope['purchase_ids'])->count();
|
||||
$summary = [
|
||||
'stock_reservations_deleted' => $this->reservationQuery($scope)->delete(),
|
||||
'tickets_deleted' => DB::table('tickets')->where('tenant_code', $tenantCode)->delete(),
|
||||
'purchase_changes_deleted' => DB::table('value_changes')
|
||||
->where('tenant_code', $tenantCode)
|
||||
->where('trackable_type', Purchase::class)
|
||||
->delete(),
|
||||
'purchases_deleted' => DB::table('compras')->whereIn('id', $scope['purchase_ids'])->delete(),
|
||||
'purchase_items_deleted' => $purchaseItems,
|
||||
'telepagos_payments_deleted' => $telepagosPayments,
|
||||
'telepagos_qr_deleted' => $telepagosQr,
|
||||
'carts_deleted' => DB::table('carritos')->whereIn('id', $scope['cart_ids'])->delete(),
|
||||
'cart_items_deleted' => $cartItems,
|
||||
'inventories_reset' => $scope['inventory_ids']->count(),
|
||||
'users_preserved' => DB::table('users')->where('tenant_codigo', $tenantCode)->count(),
|
||||
];
|
||||
|
||||
DB::table('inventories')
|
||||
->whereIn('id', $scope['inventory_ids'])
|
||||
->update([
|
||||
'real_stock' => DB::raw('real_stock + sold_units'),
|
||||
'reserved_stock' => 0,
|
||||
'sold_units' => 0,
|
||||
]);
|
||||
|
||||
return $summary;
|
||||
});
|
||||
}
|
||||
|
||||
private function ensureTenantExists(string $tenantCode): void
|
||||
{
|
||||
if (! DB::table('tenants')->where('codigo', $tenantCode)->exists()) {
|
||||
throw new InvalidArgumentException("El tenant {$tenantCode} no existe.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* purchase_ids: Collection<int, int>,
|
||||
* cart_ids: Collection<int, int>,
|
||||
* cart_item_ids: Collection<int, int>,
|
||||
* inventory_ids: Collection<int, int>
|
||||
* }
|
||||
*/
|
||||
private function scope(string $tenantCode): array
|
||||
{
|
||||
$catalogItemIds = DB::table('catalog_items')
|
||||
->where('tenant_code', $tenantCode)
|
||||
->pluck('id');
|
||||
$purchaseIds = DB::table('compras')
|
||||
->where('tenant_codigo', $tenantCode)
|
||||
->pluck('id');
|
||||
$cartIds = DB::table('carritos')
|
||||
->where('tenant_codigo', $tenantCode)
|
||||
->pluck('id');
|
||||
$cartItemIds = DB::table('carrito_items')
|
||||
->whereIn('cart_id', $cartIds)
|
||||
->pluck('id');
|
||||
$inventoryIds = DB::table('variantes')
|
||||
->whereIn('catalog_item_id', $catalogItemIds)
|
||||
->whereNotNull('inventory_id')
|
||||
->pluck('inventory_id')
|
||||
->merge(
|
||||
DB::table('catalog_items')
|
||||
->whereIn('id', $catalogItemIds)
|
||||
->whereNotNull('inventory_id')
|
||||
->pluck('inventory_id'),
|
||||
)
|
||||
->map(fn ($id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
|
||||
return [
|
||||
'purchase_ids' => $purchaseIds->map(fn ($id): int => (int) $id),
|
||||
'cart_ids' => $cartIds->map(fn ($id): int => (int) $id),
|
||||
'cart_item_ids' => $cartItemIds->map(fn ($id): int => (int) $id),
|
||||
'inventory_ids' => $inventoryIds,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* purchase_ids: Collection<int, int>,
|
||||
* cart_ids: Collection<int, int>,
|
||||
* cart_item_ids: Collection<int, int>,
|
||||
* inventory_ids: Collection<int, int>
|
||||
* } $scope
|
||||
*/
|
||||
private function reservationQuery(array $scope): Builder
|
||||
{
|
||||
return DB::table('stock_reservations')
|
||||
->where(function (Builder $query) use ($scope): void {
|
||||
$query->whereIn('inventory_id', $scope['inventory_ids'])
|
||||
->orWhereIn('purchase_id', $scope['purchase_ids'])
|
||||
->orWhereIn('cart_item_id', $scope['cart_item_ids']);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class UserPurchaseLimitService
|
||||
{
|
||||
@@ -15,6 +17,9 @@ class UserPurchaseLimitService
|
||||
int $userId,
|
||||
int $requestedQuantity,
|
||||
?int $excludedPurchaseId = null,
|
||||
?int $excludedCartId = null,
|
||||
int $heldQuantity = 0,
|
||||
?int $maximumAddableCeiling = null,
|
||||
string $field = 'quantity',
|
||||
): void {
|
||||
DB::transaction(function () use (
|
||||
@@ -22,6 +27,9 @@ class UserPurchaseLimitService
|
||||
$userId,
|
||||
$requestedQuantity,
|
||||
$excludedPurchaseId,
|
||||
$excludedCartId,
|
||||
$heldQuantity,
|
||||
$maximumAddableCeiling,
|
||||
$field,
|
||||
): void {
|
||||
/** @var CatalogItem $catalogItem */
|
||||
@@ -52,11 +60,112 @@ class UserPurchaseLimitService
|
||||
})
|
||||
->sum('cantidad');
|
||||
|
||||
if ($purchasedQuantity + $requestedQuantity > $limit) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
|
||||
]);
|
||||
$checkoutQuantity = (int) CartItem::query()
|
||||
->where('catalog_item_id', $catalogItem->getKey())
|
||||
->whereHas('cart.purchases', function ($query) use ($userId, $excludedPurchaseId): void {
|
||||
$query
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
])
|
||||
->whereDoesntHave('items')
|
||||
->when(
|
||||
$excludedPurchaseId !== null,
|
||||
fn ($query) => $query->whereKeyNot($excludedPurchaseId),
|
||||
);
|
||||
})
|
||||
->sum('cantidad');
|
||||
|
||||
$reservedCartQuantity = (int) CartItem::query()
|
||||
->where('catalog_item_id', $catalogItem->getKey())
|
||||
->whereHas('cart', fn ($query) => $query
|
||||
->where('user_id', $userId)
|
||||
->where('status', 'active')
|
||||
->when(
|
||||
$excludedCartId !== null,
|
||||
fn ($query) => $query->whereKeyNot($excludedCartId),
|
||||
))
|
||||
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active'))
|
||||
->sum('cantidad');
|
||||
|
||||
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
|
||||
$remainingQuota = max(
|
||||
0,
|
||||
$limit - $purchasedQuantity - $checkoutQuantity - $reservedCartQuantity,
|
||||
);
|
||||
|
||||
$maximumAddableQuantity = max(0, $remainingQuota - $heldQuantity);
|
||||
|
||||
throw new PurchaseLimitExceededException(
|
||||
$catalogItem,
|
||||
$maximumAddableCeiling === null
|
||||
? $maximumAddableQuantity
|
||||
: min($maximumAddableQuantity, $maximumAddableCeiling),
|
||||
$field,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, CatalogItem> $catalogItems
|
||||
* @return Collection<int, int|null>
|
||||
*/
|
||||
public function remainingByCatalogItem(Collection $catalogItems, ?int $userId): Collection
|
||||
{
|
||||
$limits = $catalogItems
|
||||
->unique('id')
|
||||
->mapWithKeys(fn (CatalogItem $item): array => [$item->getKey() => $item->max_units_per_user]);
|
||||
|
||||
if ($userId === null || $limits->filter(fn ($limit) => $limit !== null)->isEmpty()) {
|
||||
return $limits->map(fn (): ?int => null);
|
||||
}
|
||||
|
||||
$ids = $limits->keys();
|
||||
$purchased = PurchaseItem::query()
|
||||
->selectRaw('source_catalog_item_id, SUM(cantidad) AS quantity')
|
||||
->whereIn('source_catalog_item_id', $ids)
|
||||
->whereHas('purchase', fn ($query) => $query
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
Purchase::STATUS_PAID,
|
||||
]))
|
||||
->groupBy('source_catalog_item_id')
|
||||
->pluck('quantity', 'source_catalog_item_id');
|
||||
|
||||
$checkout = CartItem::query()
|
||||
->selectRaw('catalog_item_id, SUM(cantidad) AS quantity')
|
||||
->whereIn('catalog_item_id', $ids)
|
||||
->whereHas('cart.purchases', fn ($query) => $query
|
||||
->where('user_id', $userId)
|
||||
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
|
||||
->whereDoesntHave('items'))
|
||||
->groupBy('catalog_item_id')
|
||||
->pluck('quantity', 'catalog_item_id');
|
||||
|
||||
$reserved = CartItem::query()
|
||||
->selectRaw('catalog_item_id, SUM(cantidad) AS quantity')
|
||||
->whereIn('catalog_item_id', $ids)
|
||||
->whereHas('cart', fn ($query) => $query
|
||||
->where('user_id', $userId)
|
||||
->where('status', 'active'))
|
||||
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active'))
|
||||
->groupBy('catalog_item_id')
|
||||
->pluck('quantity', 'catalog_item_id');
|
||||
|
||||
return $limits->map(function (?int $limit, int $catalogItemId) use ($purchased, $checkout, $reserved): ?int {
|
||||
if ($limit === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$used = (int) ($purchased[$catalogItemId] ?? 0)
|
||||
+ (int) ($checkout[$catalogItemId] ?? 0)
|
||||
+ (int) ($reserved[$catalogItemId] ?? 0);
|
||||
|
||||
return max(0, $limit - $used);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
## Propósito
|
||||
|
||||
Implementa el ciclo de compra y checkout: crea una compra desde el carrito, toma una instantánea de sus ítems, reserva inventario, permite ediciones, inicia el pago y confirma, cancela o vence la operación.
|
||||
Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un carrito, mantiene sus líneas vivas contra catálogo durante el checkout, inicia el pago y materializa el snapshot definitivo al confirmar, o cancela y vence la operación.
|
||||
|
||||
## Modelo
|
||||
|
||||
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `paid`, `cancelled`, `rejected` y `expired`.
|
||||
- `PurchaseItem`: snapshot del producto o variante, cantidad, precio y total al comprar.
|
||||
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
|
||||
- `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
|
||||
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
|
||||
|
||||
@@ -15,13 +15,17 @@ Implementa el ciclo de compra y checkout: crea una compra desde el carrito, toma
|
||||
|
||||
`CheckoutService` es la fachada estable. Delega en:
|
||||
|
||||
- `StartCheckoutService`: inicia la compra desde el carrito.
|
||||
- `EditCheckoutService`: modifica cliente o cantidades antes del cierre.
|
||||
- `CompleteCheckoutService`: completa, envía a revisión o confirma el pago.
|
||||
- `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, sin crear todavía `PurchaseItem`.
|
||||
- `EditCheckoutService`: modifica los datos del comprador antes del cierre.
|
||||
- `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago.
|
||||
- `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes.
|
||||
- `SourceCartService`: sincroniza, restaura o finaliza el carrito fuente.
|
||||
- `SourceCartService`: restaura o finaliza el carrito fuente.
|
||||
- `CatalogSelectionResolver` y `PurchaseItemSnapshotFactory`: resuelven selecciones y generan snapshots.
|
||||
|
||||
Durante `created` y `pending_payment`, `PurchaseResource` publica las líneas del carrito con `items_source=cart`; una compra materializada publica `items_source=purchase`. Los datos descriptivos y económicos del checkout se resuelven siempre desde el catálogo vigente.
|
||||
|
||||
Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, recalcula el total y renueva la reserva; Purchase no expone operaciones sobre líneas antes de la confirmación.
|
||||
|
||||
`UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones.
|
||||
|
||||
## Endpoints
|
||||
|
||||
@@ -8,7 +8,7 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
|
||||
Route::post('compras/start-checkout', [PurchaseController::class, 'startCheckout']);
|
||||
Route::get('compras/{compra}', [PurchaseController::class, 'show']);
|
||||
Route::post('compras/{compra}/edit-items', [PurchaseController::class, 'prepareItemEditing']);
|
||||
Route::patch('compras/{compra}/items/{item}', [PurchaseController::class, 'updateItemQuantity']);
|
||||
Route::patch('compras/{compra}/items/{item}', [PurchaseController::class, 'updateItem']);
|
||||
Route::patch('compras/{compra}/customer-data', [PurchaseController::class, 'updateCustomerData']);
|
||||
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
|
||||
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);
|
||||
|
||||
32
app/Domains/Tenant/Enums/CartEditingPolicy.php
Normal file
32
app/Domains/Tenant/Enums/CartEditingPolicy.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Enums;
|
||||
|
||||
enum CartEditingPolicy: string
|
||||
{
|
||||
case Disabled = 'disabled';
|
||||
case QuantityAndRemove = 'quantity_and_remove';
|
||||
case Full = 'full';
|
||||
|
||||
public function allowsQuantityChanges(): bool
|
||||
{
|
||||
return $this !== self::Disabled;
|
||||
}
|
||||
|
||||
public function allowsRemoval(): bool
|
||||
{
|
||||
return $this !== self::Disabled;
|
||||
}
|
||||
|
||||
public function allowsVariantChanges(): bool
|
||||
{
|
||||
return $this === self::Full;
|
||||
}
|
||||
|
||||
public function allowsModification(): bool
|
||||
{
|
||||
return $this->allowsRemoval()
|
||||
|| $this->allowsQuantityChanges()
|
||||
|| $this->allowsVariantChanges();
|
||||
}
|
||||
}
|
||||
@@ -7,20 +7,25 @@ use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Category;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Menu\Models\Menu;
|
||||
use App\Domains\Menu\Models\TenantMenu;
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
#[Fillable([
|
||||
'client_id',
|
||||
'codigo',
|
||||
'nombre',
|
||||
'dominio',
|
||||
'base_path',
|
||||
'site_title',
|
||||
'primary_color',
|
||||
'secondary_color',
|
||||
@@ -40,6 +45,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'display_categories',
|
||||
'display_seach_bar',
|
||||
'display_cart',
|
||||
'cart_editing_policy',
|
||||
'display_cart_item_images',
|
||||
'scanner_category_validation_enabled',
|
||||
'event_title',
|
||||
'event_location',
|
||||
@@ -50,12 +57,15 @@ class Tenant extends Model
|
||||
use HasFactory;
|
||||
|
||||
protected $attributes = [
|
||||
'base_path' => '/',
|
||||
'search_product_layout' => ProductLayout::ColumnWithImage->value,
|
||||
'search_group_layout' => GroupLayout::Paginated->value,
|
||||
'search_items_per_page' => 12,
|
||||
'display_categories' => true,
|
||||
'display_seach_bar' => true,
|
||||
'display_cart' => true,
|
||||
'cart_editing_policy' => CartEditingPolicy::Full->value,
|
||||
'display_cart_item_images' => true,
|
||||
'scanner_category_validation_enabled' => true,
|
||||
];
|
||||
|
||||
@@ -64,6 +74,28 @@ class Tenant extends Model
|
||||
return 'codigo';
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (Tenant $tenant): void {
|
||||
if ($tenant->client_id !== null || ! Schema::hasTable('clients')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$client = Client::query()->firstOrCreate(
|
||||
['code' => $tenant->codigo],
|
||||
['name' => $tenant->nombre],
|
||||
);
|
||||
|
||||
$tenant->client()->associate($client);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Client, $this> */
|
||||
public function client(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Client::class);
|
||||
}
|
||||
|
||||
public function requiresScannerCategoryValidation(): bool
|
||||
{
|
||||
return $this->scanner_category_validation_enabled;
|
||||
@@ -83,6 +115,8 @@ class Tenant extends Model
|
||||
'display_categories' => 'boolean',
|
||||
'display_seach_bar' => 'boolean',
|
||||
'display_cart' => 'boolean',
|
||||
'cart_editing_policy' => CartEditingPolicy::class,
|
||||
'display_cart_item_images' => 'boolean',
|
||||
'scanner_category_validation_enabled' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Requests;
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
use App\Domains\Tenant\Services\WebsiteExtraService;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Closure;
|
||||
@@ -15,6 +16,8 @@ class StoreTenantRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidBasePath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -23,13 +26,21 @@ class StoreTenantRequest extends FormRequest
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$rawDomain = $this->input('dominio');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
|
||||
$hasExplicitBasePath = $this->has('base_path');
|
||||
$rawBasePath = $hasExplicitBasePath
|
||||
? $this->input('base_path')
|
||||
: TenantDomainNormalizer::pathFromDomain($rawDomain);
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$normalizedBasePath = TenantDomainNormalizer::normalizePath($rawBasePath);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
$this->hasInvalidBasePath = ($hasExplicitBasePath && ! is_string($rawBasePath))
|
||||
|| $normalizedBasePath === null;
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
'base_path' => $normalizedBasePath,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -41,6 +52,7 @@ class StoreTenantRequest extends FormRequest
|
||||
$logoRule = ['required', new ImageOrBase64Rule];
|
||||
|
||||
return array_merge([
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => ['required', 'string', 'max:255', Rule::unique('tenants', 'codigo')],
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'dominio' => [
|
||||
@@ -53,7 +65,21 @@ class StoreTenantRequest extends FormRequest
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'dominio'),
|
||||
Rule::unique('tenants', 'dominio')
|
||||
->where('base_path', $this->input('base_path')),
|
||||
],
|
||||
'base_path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidBasePath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'base_path')
|
||||
->where('dominio', $this->input('dominio')),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'primary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
@@ -82,6 +108,8 @@ class StoreTenantRequest extends FormRequest
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
'website_type_code' => [
|
||||
'required_with:extras',
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Tenant\Requests;
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
use App\Domains\Shared\Rules\ImageOrBase64Rule;
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Support\TenantDomainNormalizer;
|
||||
use Closure;
|
||||
@@ -15,6 +16,8 @@ class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
protected bool $hasInvalidDomain = false;
|
||||
|
||||
protected bool $hasInvalidBasePath = false;
|
||||
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
@@ -24,14 +27,29 @@ class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
if ($this->has('dominio')) {
|
||||
$rawDomain = $this->input('dominio');
|
||||
$normalizedDomain = TenantDomainNormalizer::normalizeTenantKey($rawDomain);
|
||||
$normalizedDomain = TenantDomainNormalizer::normalize($rawDomain);
|
||||
$embeddedBasePath = TenantDomainNormalizer::pathFromDomain($rawDomain);
|
||||
|
||||
$this->hasInvalidDomain = TenantDomainNormalizer::hasValue($rawDomain)
|
||||
&& $normalizedDomain === null;
|
||||
&& ($normalizedDomain === null || $embeddedBasePath === null);
|
||||
|
||||
$this->merge([
|
||||
'dominio' => $normalizedDomain,
|
||||
]);
|
||||
|
||||
if (! $this->has('base_path') && $embeddedBasePath !== null && $embeddedBasePath !== '/') {
|
||||
$this->merge(['base_path' => $embeddedBasePath]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->has('base_path')) {
|
||||
$rawBasePath = $this->input('base_path');
|
||||
$normalizedBasePath = TenantDomainNormalizer::normalizePath($rawBasePath);
|
||||
|
||||
$this->hasInvalidBasePath = ! is_string($rawBasePath)
|
||||
|| $normalizedBasePath === null;
|
||||
|
||||
$this->merge(['base_path' => $normalizedBasePath]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +60,13 @@ class UpdateTenantRequest extends FormRequest
|
||||
{
|
||||
/** @var Tenant|null $tenant */
|
||||
$tenant = $this->route('tenant');
|
||||
$domain = $this->input('dominio', $tenant?->dominio);
|
||||
$basePath = $this->input('base_path', $tenant?->base_path ?? '/');
|
||||
|
||||
$logoRule = ['nullable', new ImageOrBase64Rule];
|
||||
|
||||
return [
|
||||
'client_id' => ['sometimes', 'integer', Rule::exists('clients', 'id')],
|
||||
'codigo' => [
|
||||
'nullable',
|
||||
'string',
|
||||
@@ -63,7 +84,23 @@ class UpdateTenantRequest extends FormRequest
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'dominio')->ignore($tenant?->id),
|
||||
Rule::unique('tenants', 'dominio')
|
||||
->where('base_path', $basePath)
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'base_path' => [
|
||||
'bail',
|
||||
function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if ($this->hasInvalidBasePath) {
|
||||
$fail("The {$attribute} field must contain a valid URL path.");
|
||||
}
|
||||
},
|
||||
'nullable',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('tenants', 'base_path')
|
||||
->where('dominio', $domain)
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'primary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
@@ -92,6 +129,8 @@ class UpdateTenantRequest extends FormRequest
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
23
app/Domains/Tenant/Resources/CartEditingPolicyResource.php
Normal file
23
app/Domains/Tenant/Resources/CartEditingPolicyResource.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Tenant\Resources;
|
||||
|
||||
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/** @mixin CartEditingPolicy */
|
||||
class CartEditingPolicyResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, bool|string> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'code' => $this->resource->value,
|
||||
'allow_modify' => $this->resource->allowsModification(),
|
||||
'allow_delete' => $this->resource->allowsRemoval(),
|
||||
'allow_update_quantity' => $this->resource->allowsQuantityChanges(),
|
||||
'allow_update_variant' => $this->resource->allowsVariantChanges(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,11 @@ class TenantResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'client_id' => $this->client_id,
|
||||
'codigo' => $this->codigo,
|
||||
'nombre' => $this->nombre,
|
||||
'dominio' => $this->dominio,
|
||||
'base_path' => $this->base_path,
|
||||
'site_title' => $this->site_title
|
||||
?? $this->websiteType?->site_title
|
||||
?? 'ShopitFront',
|
||||
@@ -73,6 +75,8 @@ class TenantResource extends JsonResource
|
||||
'display_categories' => $this->display_categories,
|
||||
'display_seach_bar' => $this->display_seach_bar,
|
||||
'display_cart' => $this->display_cart,
|
||||
'cart_editing_policy' => CartEditingPolicyResource::make($this->cart_editing_policy),
|
||||
'display_cart_item_images' => $this->display_cart_item_images,
|
||||
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled,
|
||||
'social_media' => $this->whenLoaded(
|
||||
'socialMedia',
|
||||
|
||||
@@ -42,13 +42,7 @@ class TenantDomainNormalizer
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($path === null && is_string($domain)) {
|
||||
$decodedDomain = trim(urldecode($domain));
|
||||
$candidate = str_contains($decodedDomain, '://')
|
||||
? $decodedDomain
|
||||
: "//{$decodedDomain}";
|
||||
$path = parse_url($candidate, PHP_URL_PATH) ?: '/';
|
||||
}
|
||||
$path ??= self::pathFromDomain($domain);
|
||||
|
||||
$normalizedPath = self::normalizePath($path);
|
||||
|
||||
@@ -59,6 +53,25 @@ class TenantDomainNormalizer
|
||||
return $host.($normalizedPath === '/' ? '' : $normalizedPath);
|
||||
}
|
||||
|
||||
public static function pathFromDomain(mixed $domain): ?string
|
||||
{
|
||||
if (! is_string($domain)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decodedDomain = trim(urldecode($domain));
|
||||
|
||||
if ($decodedDomain === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$candidate = str_contains($decodedDomain, '://')
|
||||
? $decodedDomain
|
||||
: "//{$decodedDomain}";
|
||||
|
||||
return self::normalizePath(parse_url($candidate, PHP_URL_PATH) ?: '/');
|
||||
}
|
||||
|
||||
public static function normalizePath(mixed $path): ?string
|
||||
{
|
||||
if (! is_string($path)) {
|
||||
@@ -98,9 +111,23 @@ class TenantDomainNormalizer
|
||||
public static function tenantKeyCandidates(mixed $domain, mixed $path): array
|
||||
{
|
||||
$host = self::normalize($domain);
|
||||
|
||||
if ($host === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_map(
|
||||
static fn (string $basePath): string => $host.($basePath === '/' ? '' : $basePath),
|
||||
self::basePathCandidates($path),
|
||||
);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public static function basePathCandidates(mixed $path): array
|
||||
{
|
||||
$normalizedPath = self::normalizePath($path);
|
||||
|
||||
if ($host === null || $normalizedPath === null) {
|
||||
if ($normalizedPath === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -111,11 +138,11 @@ class TenantDomainNormalizer
|
||||
$candidates = [];
|
||||
|
||||
while ($segments !== []) {
|
||||
$candidates[] = $host.'/'.implode('/', $segments);
|
||||
$candidates[] = '/'.implode('/', $segments);
|
||||
array_pop($segments);
|
||||
}
|
||||
|
||||
$candidates[] = $host;
|
||||
$candidates[] = '/';
|
||||
|
||||
return $candidates;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ Es la raíz del modelo multi-tenant. Gestiona organizaciones/sitios, tipos de we
|
||||
|
||||
## Modelo
|
||||
|
||||
- `Tenant`: entidad principal, resuelta en rutas por `codigo`; relaciona catálogo, fechas, redes, menús y configuración visual.
|
||||
- `Tenant`: entidad principal, resuelta en rutas por `codigo`; relaciona catálogo, fechas, redes, menús y configuración visual. Su ubicación pública se representa con `dominio` y `base_path` (`/` para la raíz).
|
||||
- `WebsiteType`: plantilla o tipo de sitio disponible.
|
||||
- `WebsiteTypeExtra`: definición de un extra y su configuración admitida.
|
||||
- `WebsiteExtra`: valor resuelto y estado del extra para un tenant.
|
||||
@@ -20,6 +20,8 @@ Es la raíz del modelo multi-tenant. Gestiona organizaciones/sitios, tipos de we
|
||||
- `WebsiteExtraService`: construye reglas dinámicas, crea, actualiza y habilita/deshabilita extras.
|
||||
- `TenantDomainNormalizer`: normaliza dominios antes de resolver el tenant.
|
||||
|
||||
El par `(dominio, base_path)` es único. Un mismo dominio puede alojar el tenant raíz y otros tenants en prefijos diferentes. El bootstrap compara segmentos completos del path y selecciona el prefijo más específico.
|
||||
|
||||
## Endpoints
|
||||
|
||||
- Recurso REST público/administrativo `/tenants`.
|
||||
|
||||
@@ -29,19 +29,27 @@ class TicketPresentationResolver
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
$properties = $variant->selectionOptions()
|
||||
->flatMap(function (array $option): array {
|
||||
if (array_is_list($option)) {
|
||||
return collect($option)
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->all();
|
||||
$itemAttributes = $variant->catalogItem->itemAttributes;
|
||||
$properties = $variant->selectionOptions($itemAttributes)
|
||||
->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
|
||||
$labels = collect(array_is_list($option) ? $option : [$option])
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->implode(', ');
|
||||
|
||||
if ($labels === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$label = $option['label'] ?? null;
|
||||
$ticketLabel = $itemAttributes->first(
|
||||
fn ($itemAttribute): bool => $itemAttribute->attribute?->codigo === $attributeCode,
|
||||
)?->ticket_label;
|
||||
|
||||
return is_string($label) && $label !== '' ? [$label] : [];
|
||||
return is_string($ticketLabel) && trim($ticketLabel) !== ''
|
||||
? trim($ticketLabel).' '.$labels
|
||||
: $labels;
|
||||
})
|
||||
->filter()
|
||||
->values();
|
||||
|
||||
return $properties->isEmpty()
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
|
||||
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
|
||||
use App\Http\Middleware\EnsureAdminAppTenant;
|
||||
use App\Http\Middleware\EnsureScannerTenant;
|
||||
@@ -87,6 +88,20 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
'unavailable_items' => $exception->unavailableItems,
|
||||
], 422);
|
||||
});
|
||||
$exceptions->render(function (PurchaseLimitExceededException $exception, Request $request) {
|
||||
if (! $request->is('api/*')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'code' => 'purchase.limit_exceeded',
|
||||
'message' => $exception->getMessage(),
|
||||
'errors' => $exception->errors(),
|
||||
'catalog_item_id' => $exception->catalogItemId,
|
||||
'catalog_item_name' => $exception->catalogItemName,
|
||||
'maximum_addable_quantity' => $exception->maximumAddableQuantity,
|
||||
], 422);
|
||||
});
|
||||
$exceptions->render(function (ModelNotFoundException $exception, Request $request) {
|
||||
if (! $request->is('api/*')) {
|
||||
return null;
|
||||
|
||||
5
config/catalog.php
Normal file
5
config/catalog.php
Normal file
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'stock_reservation_expiration_minutes' => (int) env('STOCK_RESERVATION_EXPIRATION_MINUTES', 30),
|
||||
];
|
||||
@@ -18,7 +18,7 @@ return [
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('LOG_CHANNEL', 'stack'),
|
||||
'default' => env('LOG_CHANNEL', 'daily'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
@@ -73,6 +73,22 @@ return [
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'telepagos' => [
|
||||
'driver' => 'daily',
|
||||
'path' => storage_path('logs/telepagos/telepagos.log'),
|
||||
'level' => env('TELEPAGOS_LOG_LEVEL', 'info'),
|
||||
'days' => env('TELEPAGOS_LOG_DAYS', 30),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'commands' => [
|
||||
'driver' => 'daily',
|
||||
'path' => storage_path('logs/commands/commands.log'),
|
||||
'level' => env('COMMANDS_LOG_LEVEL', 'info'),
|
||||
'days' => env('COMMANDS_LOG_DAYS', 30),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'slack' => [
|
||||
'driver' => 'slack',
|
||||
'url' => env('LOG_SLACK_WEBHOOK_URL'),
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('clients', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('code')->unique();
|
||||
$table->string('name');
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->foreignId('client_id')->nullable()->after('id')->constrained('clients')->restrictOnDelete();
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->select(['id', 'codigo', 'nombre', 'created_at', 'updated_at'])
|
||||
->orderBy('id')
|
||||
->each(function (object $tenant): void {
|
||||
$clientId = DB::table('clients')->insertGetId([
|
||||
'code' => $tenant->codigo,
|
||||
'name' => $tenant->nombre,
|
||||
'created_at' => $tenant->created_at ?? now(),
|
||||
'updated_at' => $tenant->updated_at ?? now(),
|
||||
]);
|
||||
|
||||
DB::table('tenants')->where('id', $tenant->id)->update(['client_id' => $clientId]);
|
||||
});
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->unsignedBigInteger('client_id')->nullable(false)->change();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropConstrainedForeignId('client_id');
|
||||
});
|
||||
|
||||
Schema::dropIfExists('clients');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('client_integrations', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('client_id')->constrained('clients')->cascadeOnDelete();
|
||||
$table->string('integration_code');
|
||||
$table->longText('integration_data')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('integration_code')
|
||||
->references('integration_code')
|
||||
->on('integrations')
|
||||
->cascadeOnDelete();
|
||||
$table->unique(['client_id', 'integration_code']);
|
||||
});
|
||||
|
||||
DB::table('tenant_integration')
|
||||
->join('tenants', 'tenants.codigo', '=', 'tenant_integration.tenant_code')
|
||||
->select([
|
||||
'tenants.client_id',
|
||||
'tenant_integration.integration_code',
|
||||
'tenant_integration.integration_data',
|
||||
'tenant_integration.created_at',
|
||||
'tenant_integration.updated_at',
|
||||
])
|
||||
->orderBy('tenant_integration.id')
|
||||
->each(function (object $configuration): void {
|
||||
DB::table('client_integrations')->updateOrInsert(
|
||||
[
|
||||
'client_id' => $configuration->client_id,
|
||||
'integration_code' => $configuration->integration_code,
|
||||
],
|
||||
[
|
||||
'integration_data' => $configuration->integration_data,
|
||||
'created_at' => $configuration->created_at,
|
||||
'updated_at' => $configuration->updated_at,
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
Schema::table('integrations', function (Blueprint $table): void {
|
||||
$table->boolean('requires_client_configuration')->default(true);
|
||||
});
|
||||
|
||||
DB::table('integrations')->update([
|
||||
'requires_client_configuration' => DB::raw('requires_tenant_configuration'),
|
||||
]);
|
||||
|
||||
Schema::table('integrations', function (Blueprint $table): void {
|
||||
$table->dropColumn('requires_tenant_configuration');
|
||||
});
|
||||
|
||||
Schema::dropIfExists('tenant_integration');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('integrations', function (Blueprint $table): void {
|
||||
$table->boolean('requires_tenant_configuration')->default(true);
|
||||
});
|
||||
|
||||
DB::table('integrations')->update([
|
||||
'requires_tenant_configuration' => DB::raw('requires_client_configuration'),
|
||||
]);
|
||||
|
||||
Schema::table('integrations', function (Blueprint $table): void {
|
||||
$table->dropColumn('requires_client_configuration');
|
||||
});
|
||||
|
||||
Schema::create('tenant_integration', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('integration_code');
|
||||
$table->string('tenant_code');
|
||||
$table->longText('integration_data')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('integration_code')->references('integration_code')->on('integrations')->cascadeOnDelete();
|
||||
$table->foreign('tenant_code')->references('codigo')->on('tenants')->cascadeOnDelete();
|
||||
$table->unique(['integration_code', 'tenant_code']);
|
||||
});
|
||||
|
||||
DB::table('client_integrations')
|
||||
->join('tenants', 'tenants.client_id', '=', 'client_integrations.client_id')
|
||||
->select([
|
||||
'tenants.codigo as tenant_code',
|
||||
'client_integrations.integration_code',
|
||||
'client_integrations.integration_data',
|
||||
'client_integrations.created_at',
|
||||
'client_integrations.updated_at',
|
||||
])
|
||||
->orderBy('client_integrations.id')
|
||||
->each(function (object $configuration): void {
|
||||
DB::table('tenant_integration')->insert((array) $configuration);
|
||||
});
|
||||
|
||||
Schema::dropIfExists('client_integrations');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const CLIENT_CODE = 'onticket';
|
||||
|
||||
private const TENANT_CODES = [
|
||||
'fiesta_futbol_infantil',
|
||||
'desfile_pura_tendencia',
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$now = now();
|
||||
|
||||
$clientId = DB::table('clients')->where('code', self::CLIENT_CODE)->value('id');
|
||||
|
||||
if ($clientId === null) {
|
||||
$clientId = DB::table('clients')->insertGetId([
|
||||
'code' => self::CLIENT_CODE,
|
||||
'name' => 'OnTicket',
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
} else {
|
||||
DB::table('clients')->where('id', $clientId)->update([
|
||||
'name' => 'OnTicket',
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
$tenants = DB::table('tenants')
|
||||
->whereIn('codigo', self::TENANT_CODES)
|
||||
->orderByRaw("CASE codigo WHEN 'fiesta_futbol_infantil' THEN 0 ELSE 1 END")
|
||||
->get(['codigo', 'client_id']);
|
||||
|
||||
foreach ($tenants as $tenant) {
|
||||
DB::table('client_integrations')
|
||||
->where('client_id', $tenant->client_id)
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->each(function (object $integration) use ($clientId): void {
|
||||
DB::table('client_integrations')->insertOrIgnore([
|
||||
'client_id' => $clientId,
|
||||
'integration_code' => $integration->integration_code,
|
||||
'integration_data' => $integration->integration_data,
|
||||
'created_at' => $integration->created_at,
|
||||
'updated_at' => $integration->updated_at,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
DB::table('tenants')
|
||||
->whereIn('codigo', self::TENANT_CODES)
|
||||
->update(['client_id' => $clientId]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
foreach (self::TENANT_CODES as $tenantCode) {
|
||||
$tenant = DB::table('tenants')->where('codigo', $tenantCode)->first(['id']);
|
||||
|
||||
if (! $tenant) {
|
||||
continue;
|
||||
}
|
||||
|
||||
DB::table('clients')->insertOrIgnore([
|
||||
'code' => $tenantCode,
|
||||
'name' => $tenantCode === 'fiesta_futbol_infantil'
|
||||
? 'Fiesta Fútbol Infantil'
|
||||
: 'Desfile Pura Tendencia',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$individualClientId = DB::table('clients')->where('code', $tenantCode)->value('id');
|
||||
$sharedClientId = DB::table('clients')->where('code', self::CLIENT_CODE)->value('id');
|
||||
|
||||
DB::table('client_integrations')
|
||||
->where('client_id', $sharedClientId)
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->each(function (object $integration) use ($individualClientId): void {
|
||||
DB::table('client_integrations')->insertOrIgnore([
|
||||
'client_id' => $individualClientId,
|
||||
'integration_code' => $integration->integration_code,
|
||||
'integration_data' => $integration->integration_data,
|
||||
'created_at' => $integration->created_at,
|
||||
'updated_at' => $integration->updated_at,
|
||||
]);
|
||||
});
|
||||
|
||||
DB::table('tenants')->where('id', $tenant->id)->update([
|
||||
'client_id' => $individualClientId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const DESFILE_TENANT_CODE = 'desfile_pura_tendencia';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->boolean('cart_editing_enabled')->default(true)->after('display_cart');
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->where('codigo', self::DESFILE_TENANT_CODE)
|
||||
->update(['cart_editing_enabled' => false]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn('cart_editing_enabled');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$locations = DB::table('tenants')
|
||||
->select(['id', 'dominio'])
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->mapWithKeys(function (object $tenant): array {
|
||||
[$domain, $basePath] = $this->splitTenantLocation($tenant->dominio, $tenant->id);
|
||||
|
||||
return [$tenant->id => compact('domain', 'basePath')];
|
||||
});
|
||||
$duplicates = $locations
|
||||
->groupBy(fn (array $location): string => $location['domain'].'|'.$location['basePath'])
|
||||
->filter(fn ($matches): bool => $matches->count() > 1);
|
||||
|
||||
if ($duplicates->isNotEmpty()) {
|
||||
throw new RuntimeException(
|
||||
'Cannot create the tenant domain/base-path unique index; duplicates exist: '
|
||||
.$duplicates->keys()->implode(', ')
|
||||
);
|
||||
}
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->string('base_path')->default('/')->after('dominio');
|
||||
$table->dropUnique('tenants_dominio_unique');
|
||||
});
|
||||
|
||||
foreach ($locations as $tenantId => $location) {
|
||||
DB::table('tenants')
|
||||
->where('id', $tenantId)
|
||||
->update([
|
||||
'dominio' => $location['domain'],
|
||||
'base_path' => $location['basePath'],
|
||||
]);
|
||||
}
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->unique(
|
||||
['dominio', 'base_path'],
|
||||
'tenants_dominio_base_path_unique',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropUnique('tenants_dominio_base_path_unique');
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->select(['id', 'dominio', 'base_path'])
|
||||
->orderBy('id')
|
||||
->each(function (object $tenant): void {
|
||||
$tenantKey = $tenant->dominio.($tenant->base_path === '/' ? '' : $tenant->base_path);
|
||||
|
||||
DB::table('tenants')
|
||||
->where('id', $tenant->id)
|
||||
->update(['dominio' => $tenantKey]);
|
||||
});
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropColumn('base_path');
|
||||
$table->unique('dominio', 'tenants_dominio_unique');
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{string, string} */
|
||||
private function splitTenantLocation(mixed $value, int $tenantId): array
|
||||
{
|
||||
if (! is_string($value) || trim(urldecode($value)) === '') {
|
||||
throw new RuntimeException("Cannot migrate tenant location for tenant {$tenantId}.");
|
||||
}
|
||||
|
||||
$decodedValue = trim(urldecode($value));
|
||||
$candidate = str_contains($decodedValue, '://')
|
||||
? $decodedValue
|
||||
: "//{$decodedValue}";
|
||||
$host = parse_url($candidate, PHP_URL_HOST);
|
||||
$path = parse_url($candidate, PHP_URL_PATH) ?: '/';
|
||||
|
||||
if (! is_string($host) || $host === '') {
|
||||
throw new RuntimeException("Cannot migrate tenant location '{$value}' for tenant {$tenantId}.");
|
||||
}
|
||||
|
||||
$segments = array_values(array_filter(
|
||||
explode('/', preg_replace('#/+#', '/', $path) ?? ''),
|
||||
static fn (string $segment): bool => $segment !== '',
|
||||
));
|
||||
|
||||
if (array_intersect($segments, ['.', '..']) !== []) {
|
||||
throw new RuntimeException("Cannot migrate tenant base path '{$path}' for tenant {$tenantId}.");
|
||||
}
|
||||
|
||||
return [
|
||||
strtolower($host),
|
||||
$segments === [] ? '/' : '/'.implode('/', $segments),
|
||||
];
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const DESFILE_TENANT_CODE = 'desfile_pura_tendencia';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->boolean('display_cart_item_images')->default(true)->after('cart_editing_enabled');
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->where('codigo', self::DESFILE_TENANT_CODE)
|
||||
->update(['display_cart_item_images' => false]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn('display_cart_item_images');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/** @var array<string, string> */
|
||||
private const TENANT_POLICIES = [
|
||||
'sonder' => 'quantity_and_remove',
|
||||
'fiesta_futbol_infantil' => 'full',
|
||||
'desfile_pura_tendencia' => 'disabled',
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->string('cart_editing_policy')
|
||||
->default('full')
|
||||
->after('display_cart');
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->where('cart_editing_enabled', false)
|
||||
->update(['cart_editing_policy' => 'disabled']);
|
||||
|
||||
foreach (self::TENANT_POLICIES as $tenantCode => $policy) {
|
||||
DB::table('tenants')
|
||||
->where('codigo', $tenantCode)
|
||||
->update(['cart_editing_policy' => $policy]);
|
||||
}
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn('cart_editing_enabled');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->boolean('cart_editing_enabled')
|
||||
->default(true)
|
||||
->after('display_cart');
|
||||
});
|
||||
|
||||
DB::table('tenants')
|
||||
->where('cart_editing_policy', 'disabled')
|
||||
->update(['cart_editing_enabled' => false]);
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn('cart_editing_policy');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('carritos', function (Blueprint $table): void {
|
||||
$table->string('origin')->default('user')->after('status');
|
||||
});
|
||||
|
||||
Schema::create('stock_reservations', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('inventory_id')->constrained('inventories')->restrictOnDelete();
|
||||
$table->foreignId('cart_item_id')->nullable()->constrained('carrito_items')->nullOnDelete();
|
||||
$table->foreignId('purchase_id')->nullable()->constrained('compras')->cascadeOnDelete();
|
||||
$table->unsignedInteger('quantity');
|
||||
$table->string('status')->default('active');
|
||||
$table->dateTime('expires_at')->nullable();
|
||||
$table->dateTime('committed_at')->nullable();
|
||||
$table->dateTime('released_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['cart_item_id', 'inventory_id']);
|
||||
$table->index(['purchase_id', 'status']);
|
||||
$table->index(['status', 'expires_at']);
|
||||
});
|
||||
|
||||
CartItem::query()
|
||||
->whereHas('cart', fn ($query) => $query->where('status', 'active'))
|
||||
->with([
|
||||
'catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.catalogItem.inventory',
|
||||
'catalogItem.bundleComponents.variant.inventory',
|
||||
'variant.inventory',
|
||||
'variant.catalogItem',
|
||||
])
|
||||
->eachById(function (CartItem $cartItem): void {
|
||||
$selection = $cartItem->selectedItem();
|
||||
if ($selection !== null) {
|
||||
app(StockReservationService::class)->ensure($cartItem, $selection);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('stock_reservations');
|
||||
|
||||
Schema::table('carritos', function (Blueprint $table): void {
|
||||
$table->dropColumn('origin');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('item_attributes', function (Blueprint $table): void {
|
||||
$table->string('ticket_label', 100)->nullable()->after('show_in_selector');
|
||||
});
|
||||
|
||||
foreach (['sector' => 'Lado', 'fila' => 'Fila', 'asiento' => 'Asiento'] as $code => $label) {
|
||||
$itemAttributeIds = DB::table('item_attributes')
|
||||
->join('catalog_items', 'catalog_items.id', '=', 'item_attributes.catalog_item_id')
|
||||
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||
->where('catalog_items.tenant_code', 'desfile_pura_tendencia')
|
||||
->where('attribute.codigo', $code)
|
||||
->pluck('item_attributes.id');
|
||||
|
||||
DB::table('item_attributes')
|
||||
->whereIn('id', $itemAttributeIds)
|
||||
->update(['ticket_label' => $label]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('item_attributes', function (Blueprint $table): void {
|
||||
$table->dropColumn('ticket_label');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table): void {
|
||||
$table->dropColumn('reservation_status');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('compra_items', function (Blueprint $table): void {
|
||||
$table->string('reservation_status')
|
||||
->default('committed')
|
||||
->after('total');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Desfile\Services\InvitationPurchaseProvisioner;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
app(InvitationPurchaseProvisioner::class)->provision();
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// Intentionally irreversible: issued invitation tickets may already be used.
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||
$table->foreignId('compra_id')->nullable()->change();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||
$table->foreignId('compra_id')->nullable(false)->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||
$table->json('matched_purchase_ids')->nullable()->after('compra_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||
$table->dropColumn('matched_purchase_ids');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -27,6 +27,7 @@ class DatabaseSeeder extends Seeder
|
||||
AuthorizationSeeder::class,
|
||||
SocialMediaSeeder::class,
|
||||
TenantSeeder::class,
|
||||
DesfilePuraTendenciaSeeder::class,
|
||||
AttributeSeeder::class,
|
||||
CategorySeeder::class,
|
||||
BrandSeeder::class,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user