Compare commits
48 Commits
172e14ae9b
...
fix/expira
| Author | SHA1 | Date | |
|---|---|---|---|
| 559bf5d264 | |||
| eafb02ffd5 | |||
| 786cf2db52 | |||
| cb56e33685 | |||
| dd81e3b3f7 | |||
| 4d51531c5d | |||
| 7fd8a00054 | |||
| 23163a6eb8 | |||
| 944cf8ee18 | |||
| 8c09ca1204 | |||
| 98d502a8ef | |||
| 318e6559cb | |||
| 9fd34f900f | |||
| ae6149df84 | |||
| 1776cfe581 | |||
| 5ad18694e1 | |||
| 6775fb110c | |||
| 9c46eff880 | |||
| c8ce3b0da3 | |||
| d36a929f8c | |||
| 2de02dfd31 | |||
| f9a766dee1 | |||
| 8bc57cf0ff | |||
| a78c5cee58 | |||
| cc22e33799 | |||
| 5c0b3503b7 | |||
| 8537d2ed0a | |||
| d97cc12af6 | |||
| 7a19b3a97a | |||
| a94ac7a473 | |||
| 161693509f | |||
| 93c99afb13 | |||
| 32d2b182c6 | |||
| 2632a80722 | |||
| 3cee9c28f8 | |||
| 2091b1361a | |||
| a2c5e687f9 | |||
| 58cbeae9d3 | |||
| 1dc4e29c69 | |||
| 093e894cc3 | |||
| fdf0f3328f | |||
| 8d6bcdcc43 | |||
| 3206e293eb | |||
| aed99bd05e | |||
| f1649e0e4b | |||
| e6c4b40a37 | |||
| 7cea8d3495 | |||
| 014b5bb012 |
@@ -39,6 +39,8 @@ 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
|
||||
|
||||
@@ -1169,6 +1169,99 @@
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Prepare Item Editing Purchase",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
{
|
||||
"key": "Accept",
|
||||
"value": "application/json",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"description": "Ruta Laravel: `POST /api/tenants/{tenant:codigo}/compras/{compra}/edit-items`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@prepareItemEditing`\n\nRequiere autenticación Sanctum.",
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/edit-items",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"{{tenant_code}}",
|
||||
"compras",
|
||||
"{{purchase_id}}",
|
||||
"edit-items"
|
||||
]
|
||||
},
|
||||
"auth": {
|
||||
"type": "bearer",
|
||||
"bearer": [
|
||||
{
|
||||
"key": "token",
|
||||
"value": "{{token}}",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Update Item Purchase",
|
||||
"request": {
|
||||
"method": "PATCH",
|
||||
"header": [
|
||||
{
|
||||
"key": "Accept",
|
||||
"value": "application/json",
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"description": "Ruta Laravel: `PATCH /api/tenants/{tenant:codigo}/compras/{compra}/items/{item}`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@updateItem`\n\nRequiere autenticación Sanctum.",
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/items/{{purchase_item_id}}",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"tenants",
|
||||
"{{tenant_code}}",
|
||||
"compras",
|
||||
"{{purchase_id}}",
|
||||
"items",
|
||||
"{{purchase_item_id}}"
|
||||
]
|
||||
},
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"quantity\": 2,\n \"variant_id\": {{variant_id}}\n}",
|
||||
"options": {
|
||||
"raw": {
|
||||
"language": "json"
|
||||
}
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
"type": "bearer",
|
||||
"bearer": [
|
||||
{
|
||||
"key": "token",
|
||||
"value": "{{token}}",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Create Payment Intent Purchase",
|
||||
"request": {
|
||||
@@ -2121,7 +2214,7 @@
|
||||
},
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"client_id\": {{client_id}},\n \"codigo\": \"{{tenant_code}}\",\n \"nombre\": \"Tenant Demo\",\n \"dominio\": \"{{tenant_domain}}\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"secondary_color\": \"#2563EB\",\n \"danger_color\": \"#DC2626\",\n \"success_color\": \"#16A34A\",\n \"header_bg_color\": \"#FFFFFF\",\n \"footer_bg_color\": \"#111827\",\n \"header_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"footer_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"search_product_layout\": \"column_with_image\",\n \"search_group_layout\": \"paginated\",\n \"search_items_per_page\": 12,\n \"display_categories\": true,\n \"display_seach_bar\": true,\n \"display_cart\": true,\n \"cart_editing_enabled\": true,\n \"website_type_code\": \"shopit\"\n}",
|
||||
"raw": "{\n \"client_id\": {{client_id}},\n \"codigo\": \"{{tenant_code}}\",\n \"nombre\": \"Tenant Demo\",\n \"dominio\": \"{{tenant_domain}}\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"secondary_color\": \"#2563EB\",\n \"danger_color\": \"#DC2626\",\n \"success_color\": \"#16A34A\",\n \"header_bg_color\": \"#FFFFFF\",\n \"footer_bg_color\": \"#111827\",\n \"header_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"footer_logo\": \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==\",\n \"search_product_layout\": \"column_with_image\",\n \"search_group_layout\": \"paginated\",\n \"search_items_per_page\": 12,\n \"display_categories\": true,\n \"display_seach_bar\": true,\n \"display_cart\": true,\n \"cart_editing_policy\": \"full\",\n \"checkout_editing_policy\": \"full\",\n \"website_type_code\": \"shopit\"\n}",
|
||||
"options": {
|
||||
"raw": {
|
||||
"language": "json"
|
||||
@@ -2187,7 +2280,7 @@
|
||||
},
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_enabled\": true\n}",
|
||||
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_policy\": \"full\",\n \"checkout_editing_policy\": \"full\"\n}",
|
||||
"options": {
|
||||
"raw": {
|
||||
"language": "json"
|
||||
@@ -2227,7 +2320,7 @@
|
||||
},
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_enabled\": true\n}",
|
||||
"raw": "{\n \"nombre\": \"Tenant Demo Actualizado\",\n \"site_title\": \"ShopIt Demo\",\n \"primary_color\": \"#111827\",\n \"cart_editing_policy\": \"full\",\n \"checkout_editing_policy\": \"full\"\n}",
|
||||
"options": {
|
||||
"raw": {
|
||||
"language": "json"
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -117,4 +117,23 @@ class CartController extends Controller
|
||||
'message' => __('api.cart.item_removed'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function removeCheckoutItem(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
Cart $cart,
|
||||
CartItem $cartItem,
|
||||
): CartResource {
|
||||
return CartResource::make(
|
||||
$this->cartService->removeCheckoutItem(
|
||||
$tenant,
|
||||
$request,
|
||||
$cart,
|
||||
$cartItem->getKey(),
|
||||
),
|
||||
)->additional([
|
||||
'code' => 'cart.item_removed',
|
||||
'message' => __('api.cart.item_removed'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,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([
|
||||
@@ -181,10 +186,13 @@ 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,
|
||||
);
|
||||
|
||||
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
||||
@@ -222,6 +230,7 @@ class Cart extends Model
|
||||
}
|
||||
|
||||
$delta = $quantity - $item->cantidad;
|
||||
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
|
||||
|
||||
if ($delta > 0) {
|
||||
$otherVariantsQuantity = (int) $this->items()
|
||||
@@ -232,11 +241,11 @@ class Cart extends Model
|
||||
$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([
|
||||
@@ -355,6 +364,8 @@ class Cart extends Model
|
||||
CatalogItem|Variant $selectedItem,
|
||||
int $cartQuantity,
|
||||
?int $excludedPurchaseId = null,
|
||||
int $heldQuantity = 0,
|
||||
?int $maximumAddableCeiling = null,
|
||||
): void {
|
||||
if ($this->user_id === null) {
|
||||
return;
|
||||
@@ -369,6 +380,9 @@ class Cart extends Model
|
||||
$this->user_id,
|
||||
$cartQuantity,
|
||||
$excludedPurchaseId,
|
||||
$this->getKey(),
|
||||
$heldQuantity,
|
||||
$maximumAddableCeiling,
|
||||
field: 'cantidad',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace App\Domains\Cart\Resources;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
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;
|
||||
@@ -21,7 +23,13 @@ class CartItemResource extends JsonResource
|
||||
$selectedItem = $this->selectedItem();
|
||||
$imageUrl = null;
|
||||
$tenant = $request->route('tenant');
|
||||
$checkoutCart = $request->route('cart');
|
||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||
$includeVariants = $tenant instanceof Tenant
|
||||
&& ($checkoutCart instanceof Cart
|
||||
? $tenant->checkout_editing_policy
|
||||
: $tenant->cart_editing_policy)
|
||||
->allowsVariantChanges();
|
||||
|
||||
if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
|
||||
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
|
||||
@@ -39,14 +47,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),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ 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\Services\PurchaseStateGuard;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
@@ -20,6 +21,7 @@ class CartService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
public function show(Tenant $tenant, Request $request): Cart
|
||||
@@ -36,7 +38,7 @@ class CartService
|
||||
return $this->makeEmptyCart($tenant);
|
||||
}
|
||||
|
||||
return $this->loadCart($cart);
|
||||
return $this->loadCart($cart, $tenant);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,7 +57,7 @@ class CartService
|
||||
$cart->addItem($catalogItemId, $variantId, $quantity);
|
||||
|
||||
return [
|
||||
'cart' => $this->loadCart($cart),
|
||||
'cart' => $this->loadCart($cart, $tenant),
|
||||
'guest_token' => $resolvedIdentity['generated_guest_token'],
|
||||
];
|
||||
}
|
||||
@@ -68,11 +70,23 @@ 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(
|
||||
@@ -104,10 +118,6 @@ class CartService
|
||||
->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();
|
||||
@@ -116,10 +126,13 @@ class CartService
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart' => __('api.purchase.not_editable'),
|
||||
]);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if (! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
/** @var Cart|null $checkoutCart */
|
||||
@@ -149,7 +162,26 @@ class CartService
|
||||
|| ($updateVariant && $cartItem->variant_id !== $variantId);
|
||||
|
||||
if (! $hasChanges) {
|
||||
return $this->loadCart($checkoutCart);
|
||||
return $this->loadCart($checkoutCart, $tenant, true);
|
||||
}
|
||||
|
||||
if (
|
||||
(int) $cartItem->cantidad !== $quantity
|
||||
&& ! $tenant->checkout_editing_policy->allowsQuantityChanges()
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'cantidad' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
if (
|
||||
$updateVariant
|
||||
&& $cartItem->variant_id !== $variantId
|
||||
&& ! $tenant->checkout_editing_policy->allowsVariantChanges()
|
||||
) {
|
||||
throw ValidationException::withMessages([
|
||||
'variant_id' => __('api.cart.variant_change_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$checkoutCart->updateItem(
|
||||
@@ -172,31 +204,114 @@ class CartService
|
||||
]);
|
||||
$this->reservations->syncPurchaseExpiration($purchase);
|
||||
|
||||
return $this->loadCart($checkoutCart);
|
||||
return $this->loadCart($checkoutCart, $tenant, true);
|
||||
});
|
||||
}
|
||||
|
||||
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 removeCheckoutItem(
|
||||
Tenant $tenant,
|
||||
Request $request,
|
||||
Cart $cart,
|
||||
int $cartItemId,
|
||||
): Cart {
|
||||
if (! $tenant->checkout_editing_policy->allowsRemoval()) {
|
||||
throw ValidationException::withMessages([
|
||||
'cart_item' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$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): Cart {
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->where('cart_id', $cart->getKey())
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->where('user_id', $user->getKey())
|
||||
->whereDoesntHave('items')
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($purchase === null) {
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if (! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)) {
|
||||
throw new NotFoundHttpException('Checkout cart not found.');
|
||||
}
|
||||
|
||||
/** @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.');
|
||||
}
|
||||
|
||||
$checkoutCart->removeItem($cartItemId);
|
||||
$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, $tenant, true);
|
||||
});
|
||||
}
|
||||
|
||||
public function makeGuestTokenCookie(string $guestToken): Cookie
|
||||
{
|
||||
return cookie(
|
||||
'guest_token',
|
||||
$guestToken,
|
||||
60 * 24 * 180,
|
||||
'/',
|
||||
config('session.domain'),
|
||||
(bool) config('session.secure'),
|
||||
true,
|
||||
false,
|
||||
config('session.same_site'),
|
||||
$secure = (bool) config('session.secure');
|
||||
$sameSite = config('session.same_site');
|
||||
$partitioned = (bool) config('session.partitioned')
|
||||
|| ($secure && strtolower((string) $sameSite) === 'none');
|
||||
|
||||
return Cookie::create(
|
||||
name: 'guest_token',
|
||||
value: $guestToken,
|
||||
expire: now()->addDays(180),
|
||||
path: '/',
|
||||
domain: config('session.domain'),
|
||||
secure: $secure,
|
||||
httpOnly: true,
|
||||
raw: false,
|
||||
sameSite: $sameSite,
|
||||
partitioned: $partitioned,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -212,9 +327,9 @@ class CartService
|
||||
return $cart;
|
||||
}
|
||||
|
||||
protected function loadCart(Cart $cart): Cart
|
||||
protected function loadCart(Cart $cart, Tenant $tenant, bool $isCheckout = false): Cart
|
||||
{
|
||||
return $cart->fresh()->load([
|
||||
$relations = [
|
||||
'items.catalogItem.attachments',
|
||||
'items.catalogItem.inventory',
|
||||
'items.catalogItem.itemAttributes.attribute',
|
||||
@@ -223,7 +338,25 @@ class CartService
|
||||
'items.variant.definitions.itemAttribute.attribute.options',
|
||||
'items.variant.eventDates',
|
||||
'items.variant.eventDate',
|
||||
]);
|
||||
];
|
||||
|
||||
$editingPolicy = $isCheckout
|
||||
? $tenant->checkout_editing_policy
|
||||
: $tenant->cart_editing_policy;
|
||||
|
||||
if ($editingPolicy->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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -34,4 +34,4 @@ Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y
|
||||
|
||||
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.
|
||||
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`.
|
||||
|
||||
@@ -14,5 +14,6 @@ Route::prefix('tenants/{tenant:codigo}')
|
||||
Route::prefix('tenants/{tenant:codigo}')
|
||||
->middleware('auth:sanctum')
|
||||
->group(function (): void {
|
||||
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem']);
|
||||
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem'])->withTrashed();
|
||||
Route::delete('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'removeCheckoutItem'])->withTrashed();
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
'tenant_code',
|
||||
'code',
|
||||
'source_type',
|
||||
'category_id',
|
||||
'product_layout',
|
||||
@@ -33,6 +35,29 @@ class FeaturedGroup extends Model
|
||||
'source_type' => FeaturedGroupSource::Manual->value,
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (FeaturedGroup $featuredGroup): void {
|
||||
if (filled($featuredGroup->code)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$baseCode = Str::slug($featuredGroup->group_name) ?: 'group';
|
||||
$code = $baseCode;
|
||||
$suffix = 2;
|
||||
|
||||
while (static::query()
|
||||
->where('tenant_code', $featuredGroup->tenant_code)
|
||||
->where('code', $code)
|
||||
->exists()) {
|
||||
$code = "{$baseCode}-{$suffix}";
|
||||
$suffix++;
|
||||
}
|
||||
|
||||
$featuredGroup->code = $code;
|
||||
});
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -15,6 +15,7 @@ class OnTicketFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'category_id' => $this->category_id,
|
||||
'category_name' => $this->category->nombre,
|
||||
'group_name' => $this->group_name,
|
||||
|
||||
@@ -20,6 +20,7 @@ class CatalogFeaturedGroupResource extends JsonResource
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'code' => $this->code,
|
||||
'title' => $this->group_name,
|
||||
'layout' => $this->product_layout->value,
|
||||
'group_layout' => $this->group_layout->value,
|
||||
|
||||
@@ -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,
|
||||
@@ -167,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,
|
||||
];
|
||||
}
|
||||
@@ -186,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'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ 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
|
||||
{
|
||||
@@ -17,9 +19,33 @@ class ExpireStockReservationsService
|
||||
*/
|
||||
public function expireOverdue(): array
|
||||
{
|
||||
return [
|
||||
'purchases' => $this->checkout->expireOverduePurchases(),
|
||||
'cart_items' => $this->carts->expireOverdue(),
|
||||
];
|
||||
$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()
|
||||
|
||||
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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,20 @@ class TelepagosWebhookService
|
||||
$amount = $this->normalizeAmount($details['data']['amount'] ?? $details['amount'] ?? 0);
|
||||
$operationId = $details['data']['operation_id'] ?? $details['operation_id'] ?? null;
|
||||
|
||||
$paymentData = [
|
||||
'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,
|
||||
'concept' => $details['data']['concept'] ?? $details['concept'] ?? null,
|
||||
'operation' => $details['data']['operation'] ?? $details['operation'] ?? null,
|
||||
'operation_id' => $details['data']['operation_id'] ?? $details['operation_id'] ?? null,
|
||||
'transaction_id' => $details['data']['transaction_id'] ?? $details['transaction_id'] ?? null,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
'link_id' => $details['data']['link_id'] ?? $details['link_id'] ?? null,
|
||||
];
|
||||
|
||||
$transferenciaOperationIds = [1, 3, 11];
|
||||
$qrOperationIds = [31, 37, 47];
|
||||
|
||||
@@ -68,12 +82,16 @@ class TelepagosWebhookService
|
||||
->where('payment_method', 'transfer')
|
||||
->where('total', $amount)
|
||||
->latest()
|
||||
->limit(2)
|
||||
->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,
|
||||
@@ -163,18 +181,7 @@ class TelepagosWebhookService
|
||||
return;
|
||||
}
|
||||
|
||||
$paymentData = [
|
||||
'compra_id' => $compra->id,
|
||||
'cuit_buyer' => $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null,
|
||||
'cvu_buyer' => $details['data']['buyer']['cvu'] ?? $details['buyer']['cvu'] ?? null,
|
||||
'amount' => $amount,
|
||||
'concept' => $details['data']['concept'] ?? $details['concept'] ?? null,
|
||||
'operation' => $details['data']['operation'] ?? $details['operation'] ?? null,
|
||||
'operation_id' => $details['data']['operation_id'] ?? $details['operation_id'] ?? null,
|
||||
'transaction_id' => $details['data']['transaction_id'] ?? $details['transaction_id'] ?? null,
|
||||
'qr_order_id' => $qrOrderId,
|
||||
'link_id' => $details['data']['link_id'] ?? $details['link_id'] ?? null,
|
||||
];
|
||||
$paymentData['compra_id'] = $compra->id;
|
||||
|
||||
DB::transaction(function () use ($compra, $paymentData) {
|
||||
TelepagosPayment::create($paymentData);
|
||||
|
||||
@@ -4,11 +4,15 @@ 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\UpdatePurchaseItemRequest;
|
||||
use App\Domains\Purchase\Resources\PurchaseResource;
|
||||
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -50,21 +54,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',
|
||||
'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',
|
||||
])->loadCount('tickets');
|
||||
$compra->items->load('imageAttachment');
|
||||
$compra->loadMissing('items')->loadCount('tickets');
|
||||
$responses->load($compra);
|
||||
|
||||
return PurchaseResource::make($compra);
|
||||
}
|
||||
@@ -82,47 +81,100 @@ class PurchaseController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
public function updateItem(
|
||||
UpdatePurchaseItemRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseItem $item,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->updateItem(
|
||||
$compra,
|
||||
$item,
|
||||
$request->exists('quantity') ? (int) $request->validated('quantity') : null,
|
||||
$request->exists('variant_id') ? (int) $request->validated('variant_id') : null,
|
||||
$request->exists('variant_id'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
public function prepareItemEditing(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->prepareItemEditing($compra),
|
||||
);
|
||||
}
|
||||
|
||||
public function removeItem(
|
||||
Request $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
PurchaseItem $item,
|
||||
CheckoutService $checkoutService,
|
||||
): PurchaseResource {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
|
||||
return PurchaseResource::make(
|
||||
$checkoutService->removeItem($compra, $item),
|
||||
);
|
||||
}
|
||||
|
||||
public function paymentIntent(
|
||||
PaymentIntentRequest $request,
|
||||
Tenant $tenant,
|
||||
Purchase $compra,
|
||||
CheckoutService $checkoutService,
|
||||
PurchaseStateGuard $purchaseState,
|
||||
): JsonResponse {
|
||||
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
|
||||
$method = $request->validated('method');
|
||||
$totalAmount = $compra->calculateCurrentTotalAmount();
|
||||
$transferPayerDni = $method === 'transfer'
|
||||
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
|
||||
: null;
|
||||
|
||||
$purchaseUpdate = [
|
||||
'payment_method' => $method,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'expires_at' => now()->addMinutes(
|
||||
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
|
||||
),
|
||||
'total' => $totalAmount,
|
||||
];
|
||||
|
||||
if ($method === 'transfer') {
|
||||
$purchaseUpdate['transfer_payer_dni'] = preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'));
|
||||
}
|
||||
|
||||
$updated = DB::transaction(function () use ($compra, $purchaseUpdate): bool {
|
||||
$updated = DB::transaction(function () use ($compra, $method, $purchaseState, $transferPayerDni): bool {
|
||||
/** @var Purchase|null $purchase */
|
||||
$purchase = Purchase::query()
|
||||
->whereKey($compra->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($purchase === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if (
|
||||
$purchase === null
|
||||
|| ! in_array($purchase->status, [
|
||||
! in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)
|
||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$purchaseUpdate = [
|
||||
'payment_method' => $method,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'expires_at' => now()->addMinutes(
|
||||
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
|
||||
),
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
];
|
||||
|
||||
if ($transferPayerDni !== null) {
|
||||
$purchaseUpdate['transfer_payer_dni'] = $transferPayerDni;
|
||||
}
|
||||
$purchase->update($purchaseUpdate);
|
||||
|
||||
return true;
|
||||
@@ -135,6 +187,7 @@ class PurchaseController extends Controller
|
||||
}
|
||||
|
||||
$compra->refresh();
|
||||
$totalAmount = (float) $compra->total;
|
||||
$checkoutService->syncReservationExpiration($compra);
|
||||
|
||||
if ($method === 'transfer') {
|
||||
|
||||
13
app/Domains/Purchase/Exceptions/PurchaseExpiredException.php
Normal file
13
app/Domains/Purchase/Exceptions/PurchaseExpiredException.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class PurchaseExpiredException extends RuntimeException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(__('api.purchase.expired'));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -59,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',
|
||||
];
|
||||
}
|
||||
|
||||
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,6 +3,7 @@
|
||||
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;
|
||||
@@ -25,6 +26,14 @@ class PurchaseItemResource extends JsonResource
|
||||
: null;
|
||||
$attributes = $this->variant_attributes ?? [];
|
||||
|
||||
$catalogItem = $this->relationLoaded('sourceCatalogItem')
|
||||
? $this->sourceCatalogItem
|
||||
: null;
|
||||
$includeVariants = $tenant instanceof Tenant
|
||||
&& $tenant->checkout_editing_policy->allowsVariantChanges()
|
||||
&& $catalogItem !== null
|
||||
&& $catalogItem->relationLoaded('variants');
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'quantity' => (int) $this->cantidad,
|
||||
@@ -39,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(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -51,6 +67,9 @@ class PurchaseItemResource extends JsonResource
|
||||
$imageUrl = $displayImage
|
||||
? $this->resolveImageUrl($selectedItem, $catalogItem)
|
||||
: null;
|
||||
$includeVariants = $tenant instanceof Tenant
|
||||
&& $tenant->checkout_editing_policy->allowsVariantChanges()
|
||||
&& $catalogItem?->relationLoaded('variants');
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
@@ -66,6 +85,16 @@ class PurchaseItemResource extends JsonResource
|
||||
'imagen' => $imageUrl,
|
||||
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
|
||||
],
|
||||
'variants' => $this->when(
|
||||
$includeVariants,
|
||||
fn () => $catalogItem
|
||||
->visibleVariants($this->variant_id)
|
||||
->map(fn (Variant $availableVariant): array => $this->variantData(
|
||||
$catalogItem,
|
||||
$availableVariant,
|
||||
))
|
||||
->values(),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -132,4 +161,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),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,15 +21,18 @@ class PurchaseResource extends JsonResource
|
||||
$purchaseItems = $this->resource->relationLoaded('items')
|
||||
? $this->resource->getRelation('items')
|
||||
: collect();
|
||||
$cartItems = $purchaseItems->isEmpty()
|
||||
&& $this->resource->relationLoaded('cart')
|
||||
$cartItems = $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);
|
||||
: null;
|
||||
$usesCartItems = in_array($this->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true) && $cartItems !== null;
|
||||
$items = $usesCartItems ? $cartItems : $purchaseItems;
|
||||
$itemsSource = $usesCartItems
|
||||
? 'cart'
|
||||
: ($purchaseItems->isNotEmpty() ? 'purchase' : null);
|
||||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
||||
? (int) $this->resource->getAttribute('tickets_count')
|
||||
: null;
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Domains\Purchase\Services\Checkout;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -15,12 +16,14 @@ class CompleteCheckoutService
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
public function complete(Purchase $purchase): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->payment_method === null) {
|
||||
throw ValidationException::withMessages([
|
||||
@@ -45,6 +48,7 @@ class CompleteCheckoutService
|
||||
{
|
||||
return DB::transaction(function () use ($purchase): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
return $this->loadPurchase($purchase);
|
||||
@@ -70,6 +74,7 @@ class CompleteCheckoutService
|
||||
{
|
||||
DB::transaction(function () use ($purchase): void {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
return;
|
||||
|
||||
@@ -2,17 +2,34 @@
|
||||
|
||||
namespace App\Domains\Purchase\Services\Checkout;
|
||||
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class EditCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CatalogInventoryService $inventory,
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||
private readonly PurchaseResponseLoader $responses,
|
||||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
/** @param array<string, string> $customerData */
|
||||
public function updateCustomer(Purchase $purchase, array $customerData): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
$this->assertEditable($purchase);
|
||||
|
||||
$purchase->update($customerData);
|
||||
@@ -21,6 +38,257 @@ class EditCheckoutService
|
||||
});
|
||||
}
|
||||
|
||||
public function updateItem(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
?int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Purchase {
|
||||
return DB::transaction(function () use (
|
||||
$purchase,
|
||||
$purchaseItem,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
|
||||
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.purchase.not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
|
||||
$tenant = $purchase->tenant()->firstOrFail();
|
||||
$finalQuantity = $quantity ?? (int) $purchaseItem->cantidad;
|
||||
|
||||
if ($quantity !== null && ! $tenant->checkout_editing_policy->allowsQuantityChanges()) {
|
||||
throw ValidationException::withMessages([
|
||||
'quantity' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($updateVariant && ! $tenant->checkout_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([
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
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->purchaseState->assertNotExpired($purchase);
|
||||
$this->assertEditable($purchase);
|
||||
|
||||
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsModification()) {
|
||||
throw ValidationException::withMessages([
|
||||
'purchase' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$purchase->telepagosQr()->delete();
|
||||
$purchase->update([
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'payment_method' => null,
|
||||
'transfer_payer_dni' => null,
|
||||
'expires_at' => now()->addMinutes(
|
||||
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
||||
),
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $purchaseItem): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
$this->assertEditable($purchase);
|
||||
|
||||
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsRemoval()) {
|
||||
throw ValidationException::withMessages([
|
||||
'item' => __('api.cart.editing_disabled'),
|
||||
]);
|
||||
}
|
||||
|
||||
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
|
||||
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $purchaseItem);
|
||||
$this->inventory->release($selection, (int) $purchaseItem->cantidad);
|
||||
$this->sourceCart->removeItem($purchase, $purchaseItem);
|
||||
$purchaseItem->delete();
|
||||
$purchase->update([
|
||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||
]);
|
||||
|
||||
return $this->loadPurchase($purchase);
|
||||
});
|
||||
}
|
||||
|
||||
private function adjustReservation(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
int $quantity,
|
||||
int $difference,
|
||||
): void {
|
||||
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $purchaseItem);
|
||||
|
||||
try {
|
||||
if ($difference > 0) {
|
||||
$otherItemQuantity = (int) $purchase->items()
|
||||
->where('source_catalog_item_id', $purchaseItem->source_catalog_item_id)
|
||||
->whereKeyNot($purchaseItem->getKey())
|
||||
->sum('cantidad');
|
||||
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
|
||||
|
||||
$this->purchaseLimits->assertCanPurchase(
|
||||
$catalogItem,
|
||||
(int) $purchase->user_id,
|
||||
$otherItemQuantity + $quantity,
|
||||
$purchase->getKey(),
|
||||
);
|
||||
$this->inventory->reserve($selection, $difference);
|
||||
} else {
|
||||
$this->inventory->release($selection, abs($difference));
|
||||
}
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages([
|
||||
'quantity' => __('api.purchase.insufficient_stock'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function lockPurchaseItem(Purchase $purchase, PurchaseItem $item): PurchaseItem
|
||||
{
|
||||
/** @var PurchaseItem|null $lockedItem */
|
||||
$lockedItem = $purchase->items()
|
||||
->whereKey($item->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($lockedItem === null) {
|
||||
throw new NotFoundHttpException('Purchase item not found.');
|
||||
}
|
||||
|
||||
if ($lockedItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
|
||||
throw ValidationException::withMessages([
|
||||
'item' => __('api.purchase.item_not_editable'),
|
||||
]);
|
||||
}
|
||||
|
||||
return $lockedItem;
|
||||
}
|
||||
|
||||
private function assertEditable(Purchase $purchase): void
|
||||
{
|
||||
if (
|
||||
@@ -49,15 +317,6 @@ class EditCheckoutService
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
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',
|
||||
]);
|
||||
return $this->responses->load($purchase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,35 @@ 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>>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?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->cart_id !== null
|
||||
&& (
|
||||
in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)
|
||||
|| $purchase->items->isEmpty()
|
||||
)
|
||||
) {
|
||||
$purchase->load([
|
||||
'cart.items.catalogItem.inventory',
|
||||
'cart.items.catalogItem.attachments',
|
||||
'cart.items.variant.inventory',
|
||||
'cart.items.variant.attachments',
|
||||
'cart.items.variant.catalogItem',
|
||||
'cart.items.variant.definitions.itemAttribute.attribute',
|
||||
'cart.items.variant.eventDates',
|
||||
'cart.items.variant.eventDate',
|
||||
]);
|
||||
}
|
||||
|
||||
if (! $purchase->tenant->checkout_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',
|
||||
'cart.items.catalogItem.itemAttributes.attribute',
|
||||
'cart.items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
|
||||
'cart.items.catalogItem.variants.inventory',
|
||||
'cart.items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||
'cart.items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||
'cart.items.catalogItem.variants.eventDates',
|
||||
'cart.items.catalogItem.variants.eventDate',
|
||||
]);
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
}
|
||||
@@ -5,29 +5,33 @@ namespace App\Domains\Purchase\Services\Checkout;
|
||||
use App\Domains\Catalog\Models\StockReservation;
|
||||
use App\Domains\Catalog\Services\StockReservationService;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Throwable;
|
||||
|
||||
class ReleaseCheckoutService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
private readonly SourceCartService $sourceCart,
|
||||
private readonly PurchaseStateGuard $purchaseState,
|
||||
) {}
|
||||
|
||||
public function cancel(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: true);
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
public function cancelWithoutRestoringCart(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: false);
|
||||
return $this->release($purchase, Purchase::STATUS_CANCELLED);
|
||||
}
|
||||
|
||||
public function expire(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->release($purchase, Purchase::STATUS_EXPIRED, restoreCart: true);
|
||||
return $this->release($purchase, Purchase::STATUS_EXPIRED);
|
||||
}
|
||||
|
||||
public function expireOverdue(): int
|
||||
@@ -40,7 +44,21 @@ class ReleaseCheckoutService
|
||||
->where('expires_at', '<=', now())
|
||||
->orderBy('id')
|
||||
->eachById(function (Purchase $purchase) use (&$expiredCount): void {
|
||||
$purchase = $this->expire($purchase);
|
||||
try {
|
||||
$purchase = $this->expire($purchase);
|
||||
} catch (Throwable $exception) {
|
||||
Log::channel('commands')->error('Failed to expire overdue purchase.', [
|
||||
'command' => 'reservations:expire',
|
||||
'purchase_id' => $purchase->getKey(),
|
||||
'tenant_codigo' => $purchase->tenant_codigo,
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'status' => $purchase->status,
|
||||
'expires_at' => $purchase->expires_at,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_EXPIRED) {
|
||||
$expiredCount++;
|
||||
@@ -50,11 +68,15 @@ class ReleaseCheckoutService
|
||||
return $expiredCount;
|
||||
}
|
||||
|
||||
private function release(Purchase $purchase, string $targetStatus, bool $restoreCart): Purchase
|
||||
private function release(Purchase $purchase, string $targetStatus): Purchase
|
||||
{
|
||||
return DB::transaction(function () use ($purchase, $targetStatus, $restoreCart): Purchase {
|
||||
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
|
||||
$purchase = $this->lockPurchase($purchase);
|
||||
|
||||
if ($targetStatus !== Purchase::STATUS_EXPIRED) {
|
||||
$this->purchaseState->assertNotExpired($purchase);
|
||||
}
|
||||
|
||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
||||
return $this->loadPurchase($purchase);
|
||||
@@ -82,8 +104,7 @@ class ReleaseCheckoutService
|
||||
]);
|
||||
}
|
||||
|
||||
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
|
||||
$this->releaseCartReservations($purchase, $reservationReturnedToCart, $targetStatus);
|
||||
$this->releaseCartReservations($purchase, $targetStatus);
|
||||
|
||||
$purchase->update(['status' => $targetStatus]);
|
||||
|
||||
@@ -93,15 +114,8 @@ class ReleaseCheckoutService
|
||||
|
||||
private function releaseCartReservations(
|
||||
Purchase $purchase,
|
||||
bool $reservationReturnedToCart,
|
||||
string $targetStatus,
|
||||
): void {
|
||||
if ($reservationReturnedToCart) {
|
||||
$this->reservations->detachFromPurchase($purchase);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||
if ($cart === null) {
|
||||
return;
|
||||
|
||||
@@ -3,63 +3,90 @@
|
||||
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;
|
||||
|
||||
class SourceCartService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StockReservationService $reservations,
|
||||
) {}
|
||||
public function syncItemQuantity(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
int $quantity,
|
||||
): void {
|
||||
$sourceCart = $this->findSourceCart($purchase);
|
||||
|
||||
public function restore(Purchase $purchase): bool
|
||||
if ($sourceCart === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$sourceCart->items()
|
||||
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
|
||||
->where('variant_id', $purchaseItem->source_variant_id)
|
||||
->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 removeItem(Purchase $purchase, PurchaseItem $purchaseItem): void
|
||||
{
|
||||
$sourceCart = $this->findSourceCart($purchase);
|
||||
|
||||
if ($sourceCart === null) {
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
if ($sourceCart->origin === Cart::ORIGIN_DIRECT_CHECKOUT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var Cart|null $activeCart */
|
||||
$activeCart = Cart::query()
|
||||
->where('tenant_codigo', $purchase->tenant_codigo)
|
||||
->where('user_id', $purchase->user_id)
|
||||
->where('status', 'active')
|
||||
->where('id', '!=', $sourceCart->getKey())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($activeCart !== null) {
|
||||
$this->mergeIntoActiveCart($sourceCart, $activeCart);
|
||||
|
||||
$sourceCart->update([
|
||||
'status' => 'converted',
|
||||
'guest_token' => null,
|
||||
]);
|
||||
|
||||
if (! $sourceCart->trashed()) {
|
||||
$sourceCart->delete();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($sourceCart->trashed()) {
|
||||
$sourceCart->restore();
|
||||
}
|
||||
|
||||
$sourceCart->update([
|
||||
'status' => 'active',
|
||||
'user_id' => $purchase->user_id,
|
||||
'guest_token' => null,
|
||||
]);
|
||||
|
||||
return true;
|
||||
$sourceCart->items()
|
||||
->where('catalog_item_id', $purchaseItem->source_catalog_item_id)
|
||||
->where('variant_id', $purchaseItem->source_variant_id)
|
||||
->delete();
|
||||
}
|
||||
|
||||
public function finalize(Purchase $purchase): void
|
||||
@@ -89,30 +116,4 @@ class SourceCartService
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
}
|
||||
|
||||
private function mergeIntoActiveCart(Cart $sourceCart, Cart $activeCart): void
|
||||
{
|
||||
$sourceItems = $sourceCart->items()->lockForUpdate()->get();
|
||||
|
||||
foreach ($sourceItems as $sourceItem) {
|
||||
/** @var CartItem|null $activeItem */
|
||||
$activeItem = $activeCart->items()
|
||||
->where('catalog_item_id', $sourceItem->catalog_item_id)
|
||||
->where('variant_id', $sourceItem->variant_id)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
|
||||
if ($activeItem === null) {
|
||||
$activeItem = $activeCart->items()->create([
|
||||
'catalog_item_id' => $sourceItem->catalog_item_id,
|
||||
'variant_id' => $sourceItem->variant_id,
|
||||
'cantidad' => $sourceItem->cantidad,
|
||||
]);
|
||||
} else {
|
||||
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
|
||||
}
|
||||
|
||||
$this->reservations->transfer($sourceItem, $activeItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ class StartCheckoutService
|
||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||
private readonly CatalogSelectionResolver $selections,
|
||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||
private readonly PurchaseResponseLoader $responses,
|
||||
) {}
|
||||
|
||||
/** @param array<string, mixed> $purchaseData */
|
||||
@@ -119,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',
|
||||
);
|
||||
});
|
||||
@@ -242,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(
|
||||
@@ -311,6 +318,7 @@ class StartCheckoutService
|
||||
Tenant $tenant,
|
||||
int $userId,
|
||||
Collection $cartItems,
|
||||
int $cartId,
|
||||
): void {
|
||||
$quantities = $cartItems
|
||||
->groupBy('catalog_item_id')
|
||||
@@ -332,6 +340,8 @@ class StartCheckoutService
|
||||
$catalogItem,
|
||||
$userId,
|
||||
$quantity,
|
||||
excludedCartId: $cartId,
|
||||
heldQuantity: $quantity,
|
||||
field: 'cart_id',
|
||||
);
|
||||
}
|
||||
@@ -376,15 +386,6 @@ class StartCheckoutService
|
||||
|
||||
private function loadPurchase(Purchase $purchase): Purchase
|
||||
{
|
||||
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',
|
||||
]);
|
||||
return $this->responses->load($purchase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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;
|
||||
@@ -48,6 +49,32 @@ class CheckoutService
|
||||
return $this->editor->updateCustomer($purchase, $customerData);
|
||||
}
|
||||
|
||||
public function updateItem(
|
||||
Purchase $purchase,
|
||||
PurchaseItem $purchaseItem,
|
||||
?int $quantity,
|
||||
?int $variantId,
|
||||
bool $updateVariant,
|
||||
): Purchase {
|
||||
return $this->editor->updateItem(
|
||||
$purchase,
|
||||
$purchaseItem,
|
||||
$quantity,
|
||||
$variantId,
|
||||
$updateVariant,
|
||||
);
|
||||
}
|
||||
|
||||
public function prepareItemEditing(Purchase $purchase): Purchase
|
||||
{
|
||||
return $this->editor->prepareItemEditing($purchase);
|
||||
}
|
||||
|
||||
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
|
||||
{
|
||||
return $this->editor->removeItem($purchase, $purchaseItem);
|
||||
}
|
||||
|
||||
public function confirmPurchase(Purchase $purchase): void
|
||||
{
|
||||
$this->completer->confirm($purchase);
|
||||
|
||||
24
app/Domains/Purchase/Services/PurchaseStateGuard.php
Normal file
24
app/Domains/Purchase/Services/PurchaseStateGuard.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Purchase\Services;
|
||||
|
||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
|
||||
class PurchaseStateGuard
|
||||
{
|
||||
public function assertNotExpired(Purchase $purchase): void
|
||||
{
|
||||
$hasExpiredStatus = $purchase->status === Purchase::STATUS_EXPIRED;
|
||||
$hasExpiredByTime = in_array($purchase->status, [
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
], true)
|
||||
&& $purchase->expires_at !== null
|
||||
&& $purchase->expires_at->isPast();
|
||||
|
||||
if ($hasExpiredStatus || $hasExpiredByTime) {
|
||||
throw new PurchaseExpiredException;
|
||||
}
|
||||
}
|
||||
}
|
||||
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']);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,11 @@ 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
|
||||
{
|
||||
@@ -16,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 (
|
||||
@@ -23,6 +27,9 @@ class UserPurchaseLimitService
|
||||
$userId,
|
||||
$requestedQuantity,
|
||||
$excludedPurchaseId,
|
||||
$excludedCartId,
|
||||
$heldQuantity,
|
||||
$maximumAddableCeiling,
|
||||
$field,
|
||||
): void {
|
||||
/** @var CatalogItem $catalogItem */
|
||||
@@ -70,11 +77,95 @@ class UserPurchaseLimitService
|
||||
})
|
||||
->sum('cantidad');
|
||||
|
||||
if ($purchasedQuantity + $checkoutQuantity + $requestedQuantity > $limit) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
|
||||
]);
|
||||
$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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
|
||||
- `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`: restaura o finaliza el carrito fuente.
|
||||
- `SourceCartService`: sincroniza o finaliza el carrito de checkout asociado a la compra.
|
||||
- `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.
|
||||
|
||||
@@ -7,6 +7,9 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
|
||||
Route::get('compras', [PurchaseController::class, 'index']);
|
||||
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, 'updateItem']);
|
||||
Route::delete('compras/{compra}/items/{item}', [PurchaseController::class, 'removeItem']);
|
||||
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']);
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Domains\Sale\Resources\AdminApp;
|
||||
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/** @mixin Purchase */
|
||||
class SaleDetailResource extends JsonResource
|
||||
@@ -13,23 +15,44 @@ class SaleDetailResource extends JsonResource
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$items = $this->saleItems();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'items' => $this->items->map(fn (PurchaseItem $item): array => [
|
||||
'items' => $items->map(fn (PurchaseItem|CartItem $item): array => [
|
||||
'id' => $item->id,
|
||||
'product' => $item->item_nombre,
|
||||
'product' => $item instanceof PurchaseItem
|
||||
? $item->item_nombre
|
||||
: $item->selectedItem()?->getName(),
|
||||
'event_dates' => $this->eventDates($item),
|
||||
'quantity' => (int) $item->cantidad,
|
||||
'unit_price' => $this->formatMoney($item->precio_unitario),
|
||||
'total' => $this->formatMoney($item->total),
|
||||
'unit_price' => $this->formatMoney($this->unitPrice($item)),
|
||||
'total' => $this->formatMoney($this->lineTotal($item)),
|
||||
])->values(),
|
||||
'total' => $this->formatMoney($this->total),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function eventDates(PurchaseItem $item): array
|
||||
/** @return Collection<int, PurchaseItem|CartItem> */
|
||||
private function saleItems(): Collection
|
||||
{
|
||||
if ($this->items->isNotEmpty()) {
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
return $this->cart?->items ?? collect();
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function eventDates(PurchaseItem|CartItem $item): array
|
||||
{
|
||||
if ($item instanceof CartItem) {
|
||||
return $item->variant?->selectedEventDates()
|
||||
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
|
||||
->values()
|
||||
->all() ?? [];
|
||||
}
|
||||
|
||||
return collect($item->variant_attributes ?? [])
|
||||
->filter(fn (mixed $attribute): bool => is_array($attribute)
|
||||
&& mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
|
||||
@@ -43,6 +66,20 @@ class SaleDetailResource extends JsonResource
|
||||
->all();
|
||||
}
|
||||
|
||||
private function unitPrice(PurchaseItem|CartItem $item): float|int|string|null
|
||||
{
|
||||
return $item instanceof PurchaseItem
|
||||
? $item->precio_unitario
|
||||
: $item->selectedItem()?->getPrice();
|
||||
}
|
||||
|
||||
private function lineTotal(PurchaseItem|CartItem $item): float|int|string|null
|
||||
{
|
||||
return $item instanceof PurchaseItem
|
||||
? $item->total
|
||||
: ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
|
||||
}
|
||||
|
||||
private function formatMoney(float|int|string|null $amount): string
|
||||
{
|
||||
return number_format((float) ($amount ?? 0), 2, '.', '');
|
||||
|
||||
@@ -51,7 +51,14 @@ class AdminAppSaleService
|
||||
{
|
||||
return Purchase::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->with('items')
|
||||
->with([
|
||||
'items',
|
||||
'cart' => fn ($query) => $query->withTrashed(),
|
||||
'cart.items.catalogItem',
|
||||
'cart.items.variant.catalogItem',
|
||||
'cart.items.variant.eventDates',
|
||||
'cart.items.variant.eventDate',
|
||||
])
|
||||
->findOrFail($saleId);
|
||||
}
|
||||
|
||||
@@ -145,7 +152,18 @@ class AdminAppSaleService
|
||||
$filters['status'] ?? null,
|
||||
fn (Builder $query, string $status): Builder => $query->where('status', $status)
|
||||
)
|
||||
->withSum('items as quantity', 'cantidad')
|
||||
->select('compras.*')
|
||||
->selectRaw(
|
||||
'CASE WHEN compras.status IN (?, ?) '
|
||||
.'THEN (SELECT COALESCE(SUM(cart_items.cantidad), 0) FROM carrito_items AS cart_items '
|
||||
.'WHERE cart_items.cart_id = compras.cart_id) '
|
||||
.'ELSE (SELECT COALESCE(SUM(purchase_items.cantidad), 0) FROM compra_items AS purchase_items '
|
||||
.'WHERE purchase_items.compra_id = compras.id) END AS quantity',
|
||||
[
|
||||
Purchase::STATUS_CREATED,
|
||||
Purchase::STATUS_PENDING_PAYMENT,
|
||||
],
|
||||
)
|
||||
->withCount('tickets')
|
||||
->orderBy($sortColumns[$sortBy], $sortDirection)
|
||||
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
|
||||
@@ -171,8 +189,28 @@ class AdminAppSaleService
|
||||
|
||||
protected function saleForResponse(Purchase $sale): Purchase
|
||||
{
|
||||
return $sale->refresh()
|
||||
->loadSum('items as quantity', 'cantidad')
|
||||
->loadCount('tickets');
|
||||
/** @var Purchase */
|
||||
return Purchase::query()
|
||||
->select('compras.*')
|
||||
->selectRaw($this->quantityExpression())
|
||||
->withCount('tickets')
|
||||
->findOrFail($sale->getKey());
|
||||
}
|
||||
|
||||
protected function quantityExpression(): string
|
||||
{
|
||||
// El fallback se resuelve en SQL para poder ordenar por cantidad antes de paginar;
|
||||
// los ítems consolidados de la compra tienen prioridad sobre los del carrito de origen.
|
||||
return <<<'SQL'
|
||||
COALESCE(
|
||||
(SELECT SUM(compra_items.cantidad)
|
||||
FROM compra_items
|
||||
WHERE compra_items.compra_id = compras.id),
|
||||
(SELECT SUM(carrito_items.cantidad)
|
||||
FROM carrito_items
|
||||
WHERE carrito_items.cart_id = compras.cart_id),
|
||||
0
|
||||
) AS quantity
|
||||
SQL;
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ 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;
|
||||
@@ -26,6 +27,8 @@ use Illuminate\Support\Facades\Schema;
|
||||
'dominio',
|
||||
'base_path',
|
||||
'site_title',
|
||||
'address',
|
||||
'phone',
|
||||
'primary_color',
|
||||
'secondary_color',
|
||||
'danger_color',
|
||||
@@ -44,7 +47,8 @@ use Illuminate\Support\Facades\Schema;
|
||||
'display_categories',
|
||||
'display_seach_bar',
|
||||
'display_cart',
|
||||
'cart_editing_enabled',
|
||||
'cart_editing_policy',
|
||||
'checkout_editing_policy',
|
||||
'display_cart_item_images',
|
||||
'scanner_category_validation_enabled',
|
||||
'event_title',
|
||||
@@ -63,7 +67,8 @@ class Tenant extends Model
|
||||
'display_categories' => true,
|
||||
'display_seach_bar' => true,
|
||||
'display_cart' => true,
|
||||
'cart_editing_enabled' => true,
|
||||
'cart_editing_policy' => CartEditingPolicy::Full->value,
|
||||
'checkout_editing_policy' => CartEditingPolicy::Disabled->value,
|
||||
'display_cart_item_images' => true,
|
||||
'scanner_category_validation_enabled' => true,
|
||||
];
|
||||
@@ -114,7 +119,8 @@ class Tenant extends Model
|
||||
'display_categories' => 'boolean',
|
||||
'display_seach_bar' => 'boolean',
|
||||
'display_cart' => 'boolean',
|
||||
'cart_editing_enabled' => 'boolean',
|
||||
'cart_editing_policy' => CartEditingPolicy::class,
|
||||
'checkout_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;
|
||||
@@ -81,6 +82,8 @@ class StoreTenantRequest extends FormRequest
|
||||
->where('dominio', $this->input('dominio')),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'address' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'phone' => ['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})$/'],
|
||||
'secondary_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'danger_color' => ['required', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
@@ -107,7 +110,8 @@ class StoreTenantRequest extends FormRequest
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_enabled' => ['sometimes', 'boolean'],
|
||||
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'checkout_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||
'website_type_code' => [
|
||||
|
||||
@@ -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;
|
||||
@@ -102,6 +103,8 @@ class UpdateTenantRequest extends FormRequest
|
||||
->ignore($tenant?->id),
|
||||
],
|
||||
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'address' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'phone' => ['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})$/'],
|
||||
'secondary_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
'danger_color' => ['nullable', 'string', 'regex:/^#([a-fA-F0-9]{3,4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/'],
|
||||
@@ -128,7 +131,8 @@ class UpdateTenantRequest extends FormRequest
|
||||
'display_categories' => ['sometimes', 'boolean'],
|
||||
'display_seach_bar' => ['sometimes', 'boolean'],
|
||||
'display_cart' => ['sometimes', 'boolean'],
|
||||
'cart_editing_enabled' => ['sometimes', 'boolean'],
|
||||
'cart_editing_policy' => ['sometimes', Rule::enum(CartEditingPolicy::class)],
|
||||
'checkout_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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ class TenantResource extends JsonResource
|
||||
'site_title' => $this->site_title
|
||||
?? $this->websiteType?->site_title
|
||||
?? 'ShopitFront',
|
||||
'address' => $this->address,
|
||||
'phone' => $this->phone,
|
||||
'favicon' => ($this->favicon ?? $this->websiteType?->favicon)
|
||||
?->getTemporaryUrl(1440),
|
||||
'primary_color' => $this->primary_color,
|
||||
@@ -75,7 +77,8 @@ class TenantResource extends JsonResource
|
||||
'display_categories' => $this->display_categories,
|
||||
'display_seach_bar' => $this->display_seach_bar,
|
||||
'display_cart' => $this->display_cart,
|
||||
'cart_editing_enabled' => $this->cart_editing_enabled,
|
||||
'cart_editing_policy' => CartEditingPolicyResource::make($this->cart_editing_policy),
|
||||
'checkout_editing_policy' => CartEditingPolicyResource::make($this->checkout_editing_policy),
|
||||
'display_cart_item_images' => $this->display_cart_item_images,
|
||||
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled,
|
||||
'social_media' => $this->whenLoaded(
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
|
||||
use App\Domains\Ticket\Exceptions\TicketNotAvailableException;
|
||||
use App\Http\Middleware\EnsureAdminAppTenant;
|
||||
use App\Http\Middleware\EnsureScannerTenant;
|
||||
@@ -87,6 +89,30 @@ 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 (PurchaseExpiredException $exception, Request $request) {
|
||||
if (! $request->is('api/*')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'code' => 'purchase.expired',
|
||||
'message' => $exception->getMessage(),
|
||||
], 422);
|
||||
});
|
||||
$exceptions->render(function (ModelNotFoundException $exception, Request $request) {
|
||||
if (! $request->is('api/*')) {
|
||||
return null;
|
||||
|
||||
@@ -81,6 +81,14 @@ return [
|
||||
'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,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,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');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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('tenants', function (Blueprint $table): void {
|
||||
$table->string('checkout_editing_policy')
|
||||
->default('disabled')
|
||||
->after('cart_editing_policy');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn('checkout_editing_policy');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->string('address')->nullable()->after('site_title');
|
||||
$table->string('phone')->nullable()->after('address');
|
||||
});
|
||||
|
||||
DB::table('tenants')->update([
|
||||
'address' => 'Av. San Lorenzo 1542, Rosario',
|
||||
'phone' => '54 9 (0341) 6658247',
|
||||
]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table): void {
|
||||
$table->dropColumn(['address', 'phone']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('featured_groups', function (Blueprint $table): void {
|
||||
$table->string('code')->nullable()->after('tenant_code');
|
||||
});
|
||||
|
||||
$usedCodes = [];
|
||||
|
||||
DB::table('featured_groups')
|
||||
->select(['id', 'tenant_code', 'group_name'])
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->each(function (object $group) use (&$usedCodes): void {
|
||||
$baseCode = Str::slug($group->group_name) ?: "group-{$group->id}";
|
||||
$code = $baseCode;
|
||||
$suffix = 2;
|
||||
|
||||
while (isset($usedCodes[$group->tenant_code][$code])) {
|
||||
$code = "{$baseCode}-{$suffix}";
|
||||
$suffix++;
|
||||
}
|
||||
|
||||
$usedCodes[$group->tenant_code][$code] = true;
|
||||
|
||||
DB::table('featured_groups')
|
||||
->where('id', $group->id)
|
||||
->update(['code' => $code]);
|
||||
});
|
||||
|
||||
Schema::table('featured_groups', function (Blueprint $table): void {
|
||||
$table->string('code')->nullable(false)->change();
|
||||
$table->unique(['tenant_code', 'code']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('featured_groups', function (Blueprint $table): void {
|
||||
$table->dropUnique(['tenant_code', 'code']);
|
||||
$table->dropColumn('code');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const TENANT_CODE = 'desfile_pura_tendencia';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('tenants')
|
||||
->where('codigo', self::TENANT_CODE)
|
||||
->update(['cart_editing_policy' => 'full']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('tenants')
|
||||
->where('codigo', self::TENANT_CODE)
|
||||
->update(['cart_editing_policy' => 'disabled']);
|
||||
}
|
||||
};
|
||||
@@ -12,6 +12,7 @@ use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\FeaturedGroup;
|
||||
use App\Domains\Catalog\Services\CatalogService;
|
||||
use App\Domains\Client\Models\Client;
|
||||
use App\Domains\Desfile\Services\InvitationPurchaseProvisioner;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Domains\Tenant\Services\TenantService;
|
||||
use Illuminate\Database\Seeder;
|
||||
@@ -28,6 +29,7 @@ class DesfilePuraTendenciaSeeder extends Seeder
|
||||
public function __construct(
|
||||
private readonly TenantService $tenantService,
|
||||
private readonly CatalogService $catalogService,
|
||||
private readonly InvitationPurchaseProvisioner $invitationPurchaseProvisioner,
|
||||
) {}
|
||||
|
||||
public function run(): void
|
||||
@@ -41,15 +43,15 @@ class DesfilePuraTendenciaSeeder extends Seeder
|
||||
|
||||
if ($tenant) {
|
||||
$tenant->update(['client_id' => $client->id]);
|
||||
|
||||
return;
|
||||
} else {
|
||||
DB::transaction(function () use ($client): void {
|
||||
$this->createTenant($client);
|
||||
$this->createEventDate();
|
||||
$this->createEntryCatalog();
|
||||
});
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($client): void {
|
||||
$this->createTenant($client);
|
||||
$this->createEventDate();
|
||||
$this->createEntryCatalog();
|
||||
});
|
||||
$this->invitationPurchaseProvisioner->provision();
|
||||
}
|
||||
|
||||
private function createTenant(Client $client): void
|
||||
@@ -72,7 +74,8 @@ class DesfilePuraTendenciaSeeder extends Seeder
|
||||
'display_categories' => false,
|
||||
'display_seach_bar' => false,
|
||||
'display_cart' => true,
|
||||
'cart_editing_enabled' => false,
|
||||
'cart_editing_policy' => 'full',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
'display_cart_item_images' => false,
|
||||
'scanner_category_validation_enabled' => false,
|
||||
'website_type_code' => 'onticket',
|
||||
|
||||
@@ -75,6 +75,8 @@ class TenantSeeder extends Seeder
|
||||
'display_categories' => true,
|
||||
'display_seach_bar' => true,
|
||||
'display_cart' => true,
|
||||
'cart_editing_policy' => 'quantity_and_remove',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
'header_logo' => $this->uploadedImage('images/tennants/sonder/sonder_header.png', 'sonder_header.png'),
|
||||
'footer_logo' => $this->uploadedImage('images/tennants/sonder/sonder_footer.png', 'sonder_footer.png'),
|
||||
'social_media' => self::SOCIAL_MEDIA,
|
||||
@@ -131,6 +133,8 @@ class TenantSeeder extends Seeder
|
||||
'display_categories' => false,
|
||||
'display_seach_bar' => false,
|
||||
'display_cart' => true,
|
||||
'cart_editing_policy' => 'full',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
'header_logo' => $this->uploadedImage(
|
||||
'images/tennants/fiesta_futbol_infantil/futbol_infantil_header.png',
|
||||
'futbol_infantil_header.png',
|
||||
|
||||
@@ -22,6 +22,8 @@ return [
|
||||
'google_email_unverified' => 'The Google account must have a verified email.',
|
||||
],
|
||||
'cart' => [
|
||||
'editing_disabled' => 'Cart editing is disabled.',
|
||||
'variant_change_disabled' => 'Variant changes are disabled for this cart.',
|
||||
'item_added' => 'Product added to cart.',
|
||||
'quantity_updated' => 'Product quantity updated.',
|
||||
'item_updated' => 'Product updated.',
|
||||
@@ -34,6 +36,8 @@ return [
|
||||
'variant_required' => 'You must select a variant for this item.',
|
||||
],
|
||||
'purchase' => [
|
||||
'expired' => 'The purchase has expired. Please start a new purchase.',
|
||||
'variant_change_disabled' => 'Variant changes are disabled for this purchase.',
|
||||
'source_required' => 'A cart or direct item is required.',
|
||||
'payment_method_required' => 'The purchase payment method must be selected before finalizing.',
|
||||
'not_editable' => 'The purchase is no longer editable.',
|
||||
@@ -55,7 +59,7 @@ return [
|
||||
'not_available_for_review' => 'The purchase is no longer available for review.',
|
||||
],
|
||||
'purchase_limit' => [
|
||||
'exceeded' => 'You can purchase up to :max units of this product.',
|
||||
'exceeded' => '{0} You cannot add more units of “:product”.|{1} You can add up to :max more unit of “:product”.|[2,*] You can add up to :max more units of “:product”.',
|
||||
],
|
||||
'ticket' => [
|
||||
'not_available' => 'One or more tickets are not available.',
|
||||
|
||||
@@ -22,6 +22,8 @@ return [
|
||||
'google_email_unverified' => 'La cuenta de Google debe tener el email verificado.',
|
||||
],
|
||||
'cart' => [
|
||||
'editing_disabled' => 'La edición del carrito está deshabilitada.',
|
||||
'variant_change_disabled' => 'El cambio de variante está deshabilitado para este carrito.',
|
||||
'item_added' => 'Producto agregado al carrito.',
|
||||
'quantity_updated' => 'Cantidad de producto actualizada.',
|
||||
'item_updated' => 'Producto actualizado.',
|
||||
@@ -34,6 +36,8 @@ return [
|
||||
'variant_required' => 'Debe seleccionar una variante para este ítem.',
|
||||
],
|
||||
'purchase' => [
|
||||
'expired' => "La compra venci\u{00F3}. Inici\u{00E1} una nueva compra.",
|
||||
'variant_change_disabled' => 'El cambio de variante está deshabilitado para esta compra.',
|
||||
'source_required' => 'Se requiere un carrito o un producto directo.',
|
||||
'payment_method_required' => 'Debes seleccionar el método de pago antes de finalizar la compra.',
|
||||
'not_editable' => 'La compra ya no se puede modificar.',
|
||||
@@ -55,7 +59,7 @@ return [
|
||||
'not_available_for_review' => "La compra ya no est\u{00E1} disponible para revisi\u{00F3}n.",
|
||||
],
|
||||
'purchase_limit' => [
|
||||
'exceeded' => 'Podés comprar hasta :max unidades de este producto.',
|
||||
'exceeded' => '{0} No podés agregar más unidades de “:product”.|{1} Podés agregar hasta :max unidad más de “:product”.|[2,*] Podés agregar hasta :max unidades más de “:product”.',
|
||||
],
|
||||
'ticket' => [
|
||||
'not_available' => 'Uno o más tickets no están disponibles.',
|
||||
|
||||
@@ -84,7 +84,7 @@ function bodyFor(string $method, string $uri): ?array
|
||||
'POST api/tenants/{tenant:codigo}/catalog-items/{catalogItem}/variant-options' => ['selected_values' => ['color' => 'azul'], 'cart_item_id' => '{{cart_item_id}}'],
|
||||
'POST api/tenants/{tenant:codigo}/compras/start-checkout' => ['cart_id' => '{{cart_id}}'],
|
||||
'PATCH api/tenants/{tenant:codigo}/compras/{compra}/customer-data' => ['dni' => '30123456', 'telefono' => '+5491112345678', 'nombre_apellido' => 'Usuario Demo', 'email' => '{{user_email}}'],
|
||||
'PATCH api/tenants/{tenant:codigo}/checkout-carts/{cart}/items/{cartItem}' => ['cantidad' => 2],
|
||||
'PATCH api/tenants/{tenant:codigo}/compras/{compra}/items/{item}' => ['quantity' => 2, 'variant_id' => '{{variant_id}}'],
|
||||
'POST api/tenants/{tenant:codigo}/compras/{compra}/payment-intent' => ['method' => 'transfer', 'transfer_payer_dni' => '30123456'],
|
||||
'POST api/tenants/{tenant:codigo}/tickets/pdf' => ['ticket_ids' => [1]],
|
||||
'POST api/v1/adminapp/login' => ['email' => '{{admin_email}}', 'password' => '{{admin_password}}'],
|
||||
@@ -136,13 +136,13 @@ function bodyFor(string $method, string $uri): ?array
|
||||
'display_categories' => true,
|
||||
'display_seach_bar' => true,
|
||||
'display_cart' => true,
|
||||
'cart_editing_enabled' => true,
|
||||
'cart_editing_policy' => 'full',
|
||||
'website_type_code' => 'shopit',
|
||||
]);
|
||||
}
|
||||
|
||||
if (in_array($key, ['PUT api/tenants/{tenant}', 'PATCH api/tenants/{tenant}'], true)) {
|
||||
return jsonBody(['nombre' => 'Tenant Demo Actualizado', 'site_title' => 'ShopIt Demo', 'primary_color' => '#111827', 'cart_editing_enabled' => true]);
|
||||
return jsonBody(['nombre' => 'Tenant Demo Actualizado', 'site_title' => 'ShopIt Demo', 'primary_color' => '#111827', 'cart_editing_policy' => 'full']);
|
||||
}
|
||||
|
||||
if ($key === 'POST api/tenants/{tenant:codigo}/catalog-items') {
|
||||
@@ -244,7 +244,7 @@ function requestName(string $method, string $action, bool $multiMethod): string
|
||||
$verbs = [
|
||||
'index' => 'List', 'store' => 'Create', 'show' => 'Get', 'update' => 'Update',
|
||||
'destroy' => 'Delete', 'addItem' => 'Add Item', 'updateItemQuantity' => 'Update Item Quantity',
|
||||
'updateCheckoutItem' => 'Update Checkout Cart Item',
|
||||
'updateItem' => 'Update Item',
|
||||
'removeItem' => 'Remove Item', 'search' => 'Search', 'category' => 'Get Category',
|
||||
'featuredGroupItems' => 'List Featured Group Items', 'variantOptions' => 'Get Variant Options',
|
||||
'startCheckout' => 'Start Checkout', 'updateCustomerData' => 'Update Customer Data',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
use App\Domains\Auth\Services\AdminCredentialVerifier;
|
||||
use App\Domains\Catalog\Services\ExpireStockReservationsService;
|
||||
use App\Domains\Purchase\Services\TenantTransactionResetService;
|
||||
use Illuminate\Foundation\Inspiring;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Schedule;
|
||||
@@ -19,3 +21,64 @@ Artisan::command('reservations:expire', function (): void {
|
||||
Schedule::command('reservations:expire')
|
||||
->everyMinute()
|
||||
->withoutOverlapping();
|
||||
|
||||
Artisan::command(
|
||||
'tenants:reset-transactions
|
||||
{tenant : Código del tenant que se limpiará}
|
||||
{--dry-run : Mostrar el alcance sin modificar datos}
|
||||
{--force : Omitir la confirmación interactiva}',
|
||||
function (
|
||||
TenantTransactionResetService $resetService,
|
||||
AdminCredentialVerifier $adminCredentialVerifier,
|
||||
): int {
|
||||
$tenantCode = (string) $this->argument('tenant');
|
||||
|
||||
try {
|
||||
$preview = $resetService->preview($tenantCode);
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->warn("Se eliminarán los datos transaccionales de: {$tenantCode}");
|
||||
$this->table(
|
||||
['Dato', 'Cantidad'],
|
||||
collect($preview)->map(fn (int $count, string $label): array => [$label, $count])->values(),
|
||||
);
|
||||
$this->info('Los usuarios, el catálogo, los eventos y la configuración se conservarán.');
|
||||
|
||||
if ($this->option('dry-run')) {
|
||||
$this->comment('Vista previa finalizada; no se modificaron datos.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if (! $this->option('force') && ! $this->confirm('¿Confirmás esta limpieza irreversible?')) {
|
||||
$this->comment('Operación cancelada.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->warn('Autorización administrativa requerida.');
|
||||
$adminEmail = (string) $this->ask('Email del administrador');
|
||||
$adminPassword = (string) $this->secret('Contraseña del administrador');
|
||||
|
||||
if (! $adminCredentialVerifier->verify($adminEmail, $adminPassword)) {
|
||||
$this->error('Las credenciales no son válidas o el usuario no posee el rol admin.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$summary = $resetService->reset($tenantCode);
|
||||
|
||||
$this->info('Limpieza completada correctamente.');
|
||||
$this->table(
|
||||
['Resultado', 'Cantidad'],
|
||||
collect($summary)->map(fn (int $count, string $label): array => [$label, $count])->values(),
|
||||
);
|
||||
|
||||
return self::SUCCESS;
|
||||
},
|
||||
)->purpose('Delete tenant sales, carts, tickets and reservations while preserving users and catalog');
|
||||
|
||||
@@ -63,6 +63,7 @@ class CartControllerTest extends TestCase
|
||||
$this->assertTrue($guestTokenCookie->isSecure());
|
||||
$this->assertTrue($guestTokenCookie->isHttpOnly());
|
||||
$this->assertSame('none', $guestTokenCookie->getSameSite());
|
||||
$this->assertTrue($guestTokenCookie->isPartitioned());
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'catalog_item_id' => $item->id,
|
||||
@@ -202,6 +203,7 @@ class CartControllerTest extends TestCase
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.catalog_item_id', $item->id)
|
||||
->assertJsonPath('data.items.0.variant_id', $variant->id)
|
||||
->assertJsonPath('data.items.0.variants.0.id', $variant->id)
|
||||
->assertJsonPath('data.items.0.cantidad', 5)
|
||||
->assertJsonPath('data.subtotal', '125.00');
|
||||
|
||||
@@ -240,7 +242,15 @@ class CartControllerTest extends TestCase
|
||||
'cantidad' => 2,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('cantidad');
|
||||
->assertJsonValidationErrors('cantidad')
|
||||
->assertJsonPath('code', 'purchase.limit_exceeded')
|
||||
->assertJsonPath('catalog_item_id', $item->id)
|
||||
->assertJsonPath('catalog_item_name', $item->nombre)
|
||||
->assertJsonPath('maximum_addable_quantity', 1)
|
||||
->assertJsonPath(
|
||||
'message',
|
||||
"Podés agregar hasta 1 unidad más de “{$item->nombre}”.",
|
||||
);
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'catalog_item_id' => $item->id,
|
||||
@@ -476,6 +486,83 @@ class CartControllerTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_quantity_and_remove_policy_hides_variants_and_rejects_variant_changes(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$tenant->update(['cart_editing_policy' => 'quantity_and_remove']);
|
||||
[$item, $firstVariant] = $this->createVariantItem($tenant, 10, '15.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $item->variants()->create(['inventory_id' => $secondInventory->id]);
|
||||
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'catalog_item_id' => $item->id,
|
||||
'variant_id' => $firstVariant->id,
|
||||
'cantidad' => 1,
|
||||
])->assertJsonMissingPath('data.items.0.variants');
|
||||
$guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
|
||||
$cartItemId = $createResponse->json('data.items.0.id');
|
||||
|
||||
$this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||
json_encode(['cantidad' => 2]),
|
||||
)->assertOk()->assertJsonPath('data.items.0.cantidad', 2);
|
||||
|
||||
$this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||
json_encode(['cantidad' => 2, 'variant_id' => $secondVariant->id]),
|
||||
)->assertUnprocessable()->assertJsonValidationErrors('variant_id');
|
||||
|
||||
$this->call(
|
||||
'DELETE',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json'],
|
||||
)->assertOk()->assertJsonPath('data.items', []);
|
||||
}
|
||||
|
||||
public function test_disabled_policy_rejects_quantity_changes_and_removal(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
$tenant->update(['cart_editing_policy' => 'disabled']);
|
||||
$item = $this->createDirectItem($tenant, 10, '15.00');
|
||||
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||
'catalog_item_id' => $item->id,
|
||||
'cantidad' => 1,
|
||||
])->assertOk();
|
||||
$guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
|
||||
$cartItemId = $createResponse->json('data.items.0.id');
|
||||
|
||||
$this->call(
|
||||
'PATCH',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||
json_encode(['cantidad' => 2]),
|
||||
)->assertUnprocessable()->assertJsonValidationErrors('cantidad');
|
||||
|
||||
$this->call(
|
||||
'DELETE',
|
||||
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||
[],
|
||||
['guest_token' => $guestToken],
|
||||
[],
|
||||
['HTTP_Accept' => 'application/json'],
|
||||
)->assertUnprocessable()->assertJsonValidationErrors('cart_item');
|
||||
}
|
||||
|
||||
public function test_it_requires_a_variant_when_the_item_has_variant_inventory(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
|
||||
@@ -267,7 +267,8 @@ class BundleCatalogItemTest extends TestCase
|
||||
$this->getJson("/api/tenants/{$this->tenant->codigo}/catalog-items/{$bundleId}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.type', CatalogItemType::Bundle->value)
|
||||
->assertJsonPath('data.stock_tecnico', 4)
|
||||
->assertJsonPath('data.maximum_addable_quantity', 4)
|
||||
->assertJsonMissingPath('data.stock_tecnico')
|
||||
->assertJsonCount(1, 'data.components')
|
||||
->assertJsonPath('data.components.0.catalog_item_id', $component->id)
|
||||
->assertJsonPath('data.components.0.variant_id', null)
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace Tests\Feature\Catalog;
|
||||
|
||||
use App\Domains\Attachable\Enums\AttachmentType;
|
||||
use App\Domains\Attachable\Models\Attachment;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Catalog\Enums\FeaturedGroupSource;
|
||||
use App\Domains\Catalog\Enums\GroupLayout;
|
||||
use App\Domains\Catalog\Enums\ProductLayout;
|
||||
@@ -20,7 +22,7 @@ class CatalogControllerTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_row_and_column_with_cart_return_item_details_variants_and_technical_stock(): void
|
||||
public function test_row_and_column_with_cart_return_item_details_variants_and_maximum_quantity(): void
|
||||
{
|
||||
$tenant = $this->createTenant('catalog-index');
|
||||
$row = $this->createGroup($tenant, ProductLayout::Row, 'Row', 2);
|
||||
@@ -70,16 +72,54 @@ class CatalogControllerTest extends TestCase
|
||||
->assertJsonPath('0.items.0.nombre', 'Variants')
|
||||
->assertJsonPath('0.items.0.descripcion', 'Variants description')
|
||||
->assertJsonPath('0.items.0.precio', '100.00')
|
||||
->assertJsonPath('0.items.0.stock_tecnico', 7)
|
||||
->assertJsonPath('0.items.0.maximum_addable_quantity', 7)
|
||||
->assertJsonCount(2, '0.items.0.variants')
|
||||
->assertJsonPath('0.items.0.variants.0.stock_tecnico', 4)
|
||||
->assertJsonPath('0.items.0.variants.1.stock_tecnico', 3)
|
||||
->assertJsonMissing(['id' => $unavailableVariant->id, 'stock_tecnico' => 0])
|
||||
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4)
|
||||
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
|
||||
->assertJsonMissing(['id' => $unavailableVariant->id])
|
||||
->assertJsonPath('1.title', 'Row')
|
||||
->assertJsonPath('1.items.data.0.stock_tecnico', 8)
|
||||
->assertJsonPath('1.items.data.0.maximum_addable_quantity', 8)
|
||||
->assertJsonMissingPath('1.items.data.0.stock_tecnico')
|
||||
->assertJsonCount(0, '1.items.data.0.variants');
|
||||
}
|
||||
|
||||
public function test_maximum_addable_quantity_shares_the_authenticated_user_quota_between_variants(): void
|
||||
{
|
||||
$tenant = $this->createTenant('catalog-allowance');
|
||||
$group = $this->createGroup(
|
||||
$tenant,
|
||||
ProductLayout::ColumnWithCart,
|
||||
'Allowances',
|
||||
groupLayout: GroupLayout::Simple,
|
||||
);
|
||||
$user = User::factory()->create();
|
||||
$item = $this->createItem($tenant, 'Limited variants');
|
||||
$item->update(['max_units_per_user' => 5]);
|
||||
$firstVariant = $item->variants()->create([
|
||||
'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
|
||||
]);
|
||||
$secondVariant = $item->variants()->create([
|
||||
'inventory_id' => Inventory::query()->create(['real_stock' => 10])->id,
|
||||
]);
|
||||
$group->featuredItems()->create(['catalog_item_id' => $item->id]);
|
||||
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$cart->addItem($item->id, $firstVariant->id, 2);
|
||||
$cart->addItem($item->id, $secondVariant->id, 1);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/{$tenant->codigo}/catalog")
|
||||
->assertOk()
|
||||
->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 2)
|
||||
->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 2)
|
||||
->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico')
|
||||
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
|
||||
}
|
||||
|
||||
public function test_it_excludes_items_when_all_of_their_variants_are_out_of_stock(): void
|
||||
{
|
||||
$tenant = $this->createTenant('catalog-available-variants');
|
||||
|
||||
@@ -40,7 +40,8 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
|
||||
$response
|
||||
->assertOk()
|
||||
->assertJsonPath('data.stock_tecnico', 7)
|
||||
->assertJsonPath('data.maximum_addable_quantity', 7)
|
||||
->assertJsonMissingPath('data.stock_tecnico')
|
||||
->assertJsonCount(0, 'data.variants')
|
||||
->assertJsonCount(1, 'data.images');
|
||||
$response->assertJsonMissingPath('data.selected_variant');
|
||||
@@ -71,7 +72,8 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
->assertJsonCount(1, 'data.variants')
|
||||
->assertJsonPath('data.variants.0.id', $secondVariant->id)
|
||||
->assertJsonPath('data.selected_variant.id', $secondVariant->id)
|
||||
->assertJsonPath('data.selected_variant.stock_tecnico', 6)
|
||||
->assertJsonPath('data.selected_variant.maximum_addable_quantity', 6)
|
||||
->assertJsonMissingPath('data.selected_variant.stock_tecnico')
|
||||
->assertJsonCount(1, 'data.selected_variant.images');
|
||||
$response
|
||||
->assertJsonMissingPath('data.stock_tecnico')
|
||||
@@ -125,11 +127,11 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
$response
|
||||
->assertOk()
|
||||
->assertJsonPath('data.variants.0.id', $firstVariant->id)
|
||||
->assertJsonPath('data.variants.0.stock_tecnico', 4)
|
||||
->assertJsonPath('data.variants.0.maximum_addable_quantity', 4)
|
||||
->assertJsonPath('data.variants.0.values.size.value', 'S')
|
||||
->assertJsonPath('data.variants.0.values.size.label', 'Small')
|
||||
->assertJsonPath('data.variants.1.id', $secondVariant->id)
|
||||
->assertJsonPath('data.variants.1.stock_tecnico', 7)
|
||||
->assertJsonPath('data.variants.1.maximum_addable_quantity', 7)
|
||||
->assertJsonPath('data.variants.1.values.size.value', 'M')
|
||||
->assertJsonPath('data.variants.1.values.size.label', 'Medium')
|
||||
->assertJsonPath('data.attributes.0.codigo', 'size')
|
||||
@@ -137,7 +139,7 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
->assertJsonPath('data.attributes.0.options.1.value', 'M')
|
||||
->assertJsonCount(2, 'data.attributes.0.options')
|
||||
->assertJsonPath('data.selected_variant.id', $secondVariant->id)
|
||||
->assertJsonPath('data.selected_variant.stock_tecnico', 7)
|
||||
->assertJsonPath('data.selected_variant.maximum_addable_quantity', 7)
|
||||
->assertJsonPath('data.selected_variant.values.size.value', 'M')
|
||||
->assertJsonPath('data.selected_variant.values.size.label', 'Medium')
|
||||
->assertJsonCount(1, 'data.selected_variant.images');
|
||||
@@ -177,9 +179,11 @@ class CatalogItemDetailControllerTest extends TestCase
|
||||
$this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.selected_variant.id', $variant->id)
|
||||
->assertJsonPath('data.selected_variant.stock_tecnico', null)
|
||||
->assertJsonPath('data.selected_variant.maximum_addable_quantity', null)
|
||||
->assertJsonMissingPath('data.stock_tecnico')
|
||||
->assertJsonPath('data.variants.0.stock_tecnico', null);
|
||||
->assertJsonPath('data.variants.0.maximum_addable_quantity', null)
|
||||
->assertJsonMissingPath('data.selected_variant.stock_tecnico')
|
||||
->assertJsonMissingPath('data.variants.0.stock_tecnico');
|
||||
}
|
||||
|
||||
public function test_it_exposes_event_dates_as_a_dynamic_variant_attribute(): void
|
||||
|
||||
@@ -81,6 +81,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
|
||||
'is_featured' => true,
|
||||
])
|
||||
->assertCreated()
|
||||
->assertJsonPath('data.code', 'food')
|
||||
->assertJsonPath('data.category_name', 'Food')
|
||||
->assertJsonPath('data.group_name', 'Food')
|
||||
->assertJsonPath('data.is_featured', true)
|
||||
@@ -96,6 +97,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
|
||||
]);
|
||||
$this->assertDatabaseHas('featured_groups', [
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'code' => 'food',
|
||||
'source_type' => 'category',
|
||||
'category_id' => $categoryId,
|
||||
'product_layout' => 'row',
|
||||
@@ -130,6 +132,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
|
||||
'is_featured' => true,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.code', 'old-name')
|
||||
->assertJsonPath('data.category_name', 'New name')
|
||||
->assertJsonPath('data.group_name', 'New name')
|
||||
->assertJsonPath('data.is_featured', true)
|
||||
@@ -142,6 +145,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
|
||||
]);
|
||||
$this->assertDatabaseHas('featured_groups', [
|
||||
'id' => $group->id,
|
||||
'code' => 'old-name',
|
||||
'group_name' => 'New name',
|
||||
'product_layout' => 'row',
|
||||
'group_layout' => 'paginated',
|
||||
|
||||
@@ -14,6 +14,7 @@ use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Integration\Models\ClientIntegration;
|
||||
use App\Domains\Integration\Models\Integration;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\TelepagosPayment;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@@ -261,6 +262,84 @@ class TelepagosWebhookTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_transfer_webhook_records_unmatched_payment_when_multiple_purchases_match(): void
|
||||
{
|
||||
$tenant = $this->createTenant('ambiguous', 'Ambiguous', 'ambiguous.com.ar');
|
||||
$this->configureTelepagosIntegration($tenant);
|
||||
|
||||
$variant = $this->createVariantForTenant('ambiguous', 10, '50.00');
|
||||
$firstPurchase = $this->createPendingTransferPurchase(
|
||||
$tenant,
|
||||
User::factory()->create()->id,
|
||||
$variant->id,
|
||||
1,
|
||||
'12345678',
|
||||
);
|
||||
$secondPurchase = $this->createPendingTransferPurchase(
|
||||
$tenant,
|
||||
User::factory()->create()->id,
|
||||
$variant->id,
|
||||
1,
|
||||
'12345678',
|
||||
);
|
||||
$thirdPurchase = $this->createPendingTransferPurchase(
|
||||
$tenant,
|
||||
User::factory()->create()->id,
|
||||
$variant->id,
|
||||
1,
|
||||
'12345678',
|
||||
);
|
||||
|
||||
Http::fake([
|
||||
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
|
||||
'status' => 'ok',
|
||||
'token' => 'test-token',
|
||||
'expires_at' => now()->addHour()->toIso8601String(),
|
||||
]),
|
||||
'https://api.telepagos.com.ar/v2/payment/cashin/ambiguous' => Http::response([
|
||||
'status' => 'ok',
|
||||
'data' => [
|
||||
'amount' => 50,
|
||||
'operation_id' => 1,
|
||||
'transaction_id' => 'tx-ambiguous',
|
||||
'buyer' => [
|
||||
'cuit' => '20123456789',
|
||||
],
|
||||
],
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/webhooks/telepagos/ambiguous', [
|
||||
'id' => 'ambiguous',
|
||||
])->assertOk()->assertJsonPath('status', 'success');
|
||||
|
||||
$this->assertDatabaseHas('telepagos_payments', [
|
||||
'compra_id' => null,
|
||||
'amount' => 50,
|
||||
'operation_id' => 1,
|
||||
'transaction_id' => 'tx-ambiguous',
|
||||
]);
|
||||
$payment = TelepagosPayment::query()
|
||||
->where('transaction_id', 'tx-ambiguous')
|
||||
->firstOrFail();
|
||||
$this->assertEqualsCanonicalizing(
|
||||
[$firstPurchase->id, $secondPurchase->id, $thirdPurchase->id],
|
||||
$payment->matched_purchase_ids,
|
||||
);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $firstPurchase->id,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
]);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $secondPurchase->id,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
]);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $thirdPurchase->id,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_webhook_confirms_a_purchase_with_tickets_enabled(): void
|
||||
{
|
||||
$tenant = $this->createTenant('expired-ticket', 'Expired Ticket', 'expired-ticket.com.ar');
|
||||
|
||||
@@ -10,10 +10,10 @@ class AddCartEditingEnabledToTenantsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_it_disables_cart_editing_only_for_desfile(): void
|
||||
public function test_it_migrates_the_boolean_to_the_equivalent_policy(): void
|
||||
{
|
||||
$migration = require database_path(
|
||||
'migrations/2026_08_18_060000_add_cart_editing_enabled_to_tenants_table.php'
|
||||
'migrations/2026_08_19_000000_replace_cart_editing_enabled_with_policy.php'
|
||||
);
|
||||
|
||||
$migration->down();
|
||||
@@ -21,7 +21,17 @@ class AddCartEditingEnabledToTenantsTest extends TestCase
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'desfile_pura_tendencia',
|
||||
'cart_editing_enabled' => false,
|
||||
'cart_editing_policy' => 'disabled',
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'sonder',
|
||||
'cart_editing_policy' => 'quantity_and_remove',
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'fiesta_futbol_infantil',
|
||||
'cart_editing_policy' => 'full',
|
||||
]);
|
||||
|
||||
DB::table('tenants')->insert([
|
||||
@@ -32,7 +42,7 @@ class AddCartEditingEnabledToTenantsTest extends TestCase
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'cart-editing-default',
|
||||
'cart_editing_enabled' => true,
|
||||
'cart_editing_policy' => 'full',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Migrations;
|
||||
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AddCheckoutEditingPolicyToTenantsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_it_disables_checkout_editing_for_every_tenant(): void
|
||||
{
|
||||
Tenant::query()->where('codigo', 'sonder')->update([
|
||||
'cart_editing_policy' => 'disabled',
|
||||
]);
|
||||
Tenant::query()->where('codigo', 'fiesta_futbol_infantil')->update([
|
||||
'cart_editing_policy' => 'quantity_and_remove',
|
||||
]);
|
||||
|
||||
$migration = require database_path(
|
||||
'migrations/2026_08_20_000000_add_checkout_editing_policy_to_tenants.php'
|
||||
);
|
||||
|
||||
$migration->down();
|
||||
$migration->up();
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'sonder',
|
||||
'cart_editing_policy' => 'disabled',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
]);
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'fiesta_futbol_infantil',
|
||||
'cart_editing_policy' => 'quantity_and_remove',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Migrations;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class EnableFullCartEditingForDesfileTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_it_enables_quantity_variant_and_removal_changes_for_desfile(): void
|
||||
{
|
||||
$migration = require database_path(
|
||||
'migrations/2026_08_20_020000_enable_full_cart_editing_for_desfile.php'
|
||||
);
|
||||
|
||||
$migration->down();
|
||||
$migration->up();
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
'codigo' => 'desfile_pura_tendencia',
|
||||
'cart_editing_policy' => 'full',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Purchase;
|
||||
|
||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PurchaseExpiredExceptionResponseTest extends TestCase
|
||||
{
|
||||
public function test_it_returns_a_stable_api_error_for_an_expired_purchase(): void
|
||||
{
|
||||
Route::get('/api/test/purchase-expired', function (): never {
|
||||
throw new PurchaseExpiredException;
|
||||
});
|
||||
|
||||
$this->getJson('/api/test/purchase-expired')
|
||||
->assertUnprocessable()
|
||||
->assertExactJson([
|
||||
'code' => 'purchase.expired',
|
||||
'message' => __('api.purchase.expired'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -340,7 +340,11 @@ class StorePurchaseTest extends TestCase
|
||||
],
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('direct_items');
|
||||
->assertJsonValidationErrors('direct_items')
|
||||
->assertJsonPath('code', 'purchase.limit_exceeded')
|
||||
->assertJsonPath('catalog_item_id', $variant->catalog_item_id)
|
||||
->assertJsonPath('catalog_item_name', $variant->catalogItem->nombre)
|
||||
->assertJsonPath('maximum_addable_quantity', 1);
|
||||
|
||||
$this->actingAs($otherUser, 'sanctum')
|
||||
->postJson('/api/tenants/sonder/compras/start-checkout', [
|
||||
@@ -408,7 +412,7 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_restores_the_source_cart_when_checkout_is_cancelled(): void
|
||||
public function test_it_releases_and_closes_the_checkout_cart_when_purchase_is_cancelled(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
@@ -426,11 +430,10 @@ class StorePurchaseTest extends TestCase
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
||||
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
'deleted_at' => null,
|
||||
'status' => 'converted',
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
@@ -440,11 +443,16 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 3,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'purchase_id' => $purchase->id,
|
||||
'quantity' => 0,
|
||||
'status' => 'released',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_merges_the_checkout_cart_when_the_user_created_another_active_cart(): void
|
||||
public function test_it_keeps_a_new_active_cart_separate_when_checkout_is_cancelled(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
@@ -476,11 +484,15 @@ class StorePurchaseTest extends TestCase
|
||||
'cart_id' => $activeCartId,
|
||||
'catalog_item_id' => $variant->catalog_item_id,
|
||||
'variant_id' => $variant->id,
|
||||
'cantidad' => 3,
|
||||
'cantidad' => 1,
|
||||
]);
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
'status' => 'converted',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 3,
|
||||
'reserved_stock' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -561,7 +573,8 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
public function test_it_updates_a_checkout_cart_item_quantity_and_its_stock_reservation(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
@@ -605,9 +618,237 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_checkout_cart_editing_uses_checkout_policy_independently_from_cart_policy(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update([
|
||||
'cart_editing_policy' => 'full',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
]);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
|
||||
'cantidad' => 4,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('cantidad');
|
||||
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'id' => $itemId,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_removes_an_item_from_the_checkout_cart_when_the_policy_allows_it(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'quantity_and_remove']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$itemId = $purchase->cart->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->deleteJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items', [])
|
||||
->assertJsonPath('data.subtotal', '0.00');
|
||||
|
||||
$this->assertDatabaseMissing('carrito_items', ['id' => $itemId]);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $purchase->id,
|
||||
'total' => '0.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_changes_a_checkout_item_variant_and_moves_its_reservation(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '70.00',
|
||||
]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $firstVariant, 2);
|
||||
$itemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.source_variant_id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '70.00')
|
||||
->assertJsonPath('data.items.0.line_total', '140.00')
|
||||
->assertJsonPath('data.total', '140.00')
|
||||
->assertJsonPath('data.items.0.variants.0.id', $firstVariant->id)
|
||||
->assertJsonPath('data.items.0.variants.1.id', $secondVariant->id);
|
||||
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'catalog_item_id' => $firstVariant->catalog_item_id,
|
||||
'variant_id' => $secondVariant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseMissing('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'variant_id' => $firstVariant->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_checkout_variant_changes_when_the_policy_does_not_allow_them(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'quantity_and_remove']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $firstVariant, 2);
|
||||
$itemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('variant_id');
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'id' => $itemId,
|
||||
'source_variant_id' => $firstVariant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_checkout_variant_change_rolls_back_when_the_target_has_insufficient_stock(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 1]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '70.00',
|
||||
]);
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $firstVariant, 2);
|
||||
$itemId = $purchase->items->firstOrFail()->id;
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors('variant_id');
|
||||
|
||||
$this->assertDatabaseHas('compra_items', [
|
||||
'id' => $itemId,
|
||||
'source_variant_id' => $firstVariant->id,
|
||||
'cantidad' => 2,
|
||||
'precio_unitario' => '50.00',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 2,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $purchase->cart_id,
|
||||
'variant_id' => $firstVariant->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_changing_to_an_existing_checkout_variant_merges_purchase_and_cart_rows(): void
|
||||
{
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$firstVariant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||
$secondVariant = $firstVariant->catalogItem->variants()->create([
|
||||
'inventory_id' => $secondInventory->id,
|
||||
'precio' => '70.00',
|
||||
]);
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => 'sonder',
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
]);
|
||||
$cart->addItem($firstVariant->catalog_item_id, $firstVariant->id, 2);
|
||||
$cart->addItem($secondVariant->catalog_item_id, $secondVariant->id, 3);
|
||||
$purchase = app(CheckoutService::class)->startCheckout($tenant, $user->id, [
|
||||
'cart_id' => $cart->id,
|
||||
]);
|
||||
$sourceItem = $purchase->items->firstWhere('source_variant_id', $firstVariant->id);
|
||||
$this->assertNotNull($sourceItem);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$sourceItem->id}", [
|
||||
'variant_id' => $secondVariant->id,
|
||||
])
|
||||
->assertOk()
|
||||
->assertJsonCount(1, 'data.items')
|
||||
->assertJsonPath('data.items.0.source_variant_id', $secondVariant->id)
|
||||
->assertJsonPath('data.items.0.quantity', 5)
|
||||
->assertJsonPath('data.items.0.line_total', '350.00')
|
||||
->assertJsonPath('data.total', '350.00');
|
||||
|
||||
$this->assertDatabaseCount('compra_items', 1);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $firstVariant->inventory_id,
|
||||
'reserved_stock' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $secondInventory->id,
|
||||
'reserved_stock' => 5,
|
||||
]);
|
||||
$this->assertDatabaseCount('carrito_items', 1);
|
||||
$this->assertDatabaseHas('carrito_items', [
|
||||
'cart_id' => $cart->id,
|
||||
'variant_id' => $secondVariant->id,
|
||||
'cantidad' => 5,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_quantity_update_above_the_user_purchase_limit(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$variant->catalogItem->update(['max_units_per_user' => 3]);
|
||||
@@ -633,7 +874,8 @@ class StorePurchaseTest extends TestCase
|
||||
|
||||
public function test_it_invalidates_a_pending_payment_when_the_checkout_cart_changes(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$tenant->update(['checkout_editing_policy' => 'full']);
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
@@ -835,7 +1077,7 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_it_expires_an_abandoned_purchase_and_restores_its_cart(): void
|
||||
public function test_it_expires_an_abandoned_purchase_and_releases_its_checkout_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
@@ -861,21 +1103,20 @@ class StorePurchaseTest extends TestCase
|
||||
]);
|
||||
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchase->id]);
|
||||
$this->assertDatabaseHas('stock_reservations', [
|
||||
'purchase_id' => null,
|
||||
'quantity' => 3,
|
||||
'status' => 'active',
|
||||
'purchase_id' => $purchase->id,
|
||||
'quantity' => 0,
|
||||
'status' => 'expired',
|
||||
]);
|
||||
$this->assertDatabaseHas('inventories', [
|
||||
'id' => $variant->inventory_id,
|
||||
'real_stock' => 10,
|
||||
'reserved_stock' => 3,
|
||||
'reserved_stock' => 0,
|
||||
'sold_units' => 0,
|
||||
]);
|
||||
$this->assertDatabaseHas('carritos', [
|
||||
$this->assertSoftDeleted('carritos', [
|
||||
'id' => $purchase->cart_id,
|
||||
'user_id' => $user->id,
|
||||
'status' => 'active',
|
||||
'deleted_at' => null,
|
||||
'status' => 'converted',
|
||||
]);
|
||||
|
||||
$this->artisan('reservations:expire')
|
||||
@@ -884,6 +1125,43 @@ class StorePurchaseTest extends TestCase
|
||||
->assertSuccessful();
|
||||
}
|
||||
|
||||
public function test_it_continues_expiring_purchases_after_an_inconsistent_reservation(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create();
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
$inconsistentPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
|
||||
$validPurchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 1);
|
||||
|
||||
$inconsistentPurchase->items()->create([
|
||||
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||
'source_variant_id' => $variant->id,
|
||||
'nombre' => 'Inconsistent item',
|
||||
'slug' => 'inconsistent-item',
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => '50.00',
|
||||
'discount_total' => '0.00',
|
||||
'tax_total' => '0.00',
|
||||
'total' => '50.00',
|
||||
]);
|
||||
|
||||
$this->travel(31)->minutes();
|
||||
|
||||
$this->artisan('reservations:expire')
|
||||
->expectsOutput('Expired purchases: 1')
|
||||
->expectsOutput('Expired cart items: 0')
|
||||
->assertSuccessful();
|
||||
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $inconsistentPurchase->id,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
]);
|
||||
$this->assertDatabaseHas('compras', [
|
||||
'id' => $validPurchase->id,
|
||||
'status' => Purchase::STATUS_EXPIRED,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_cart_items_for_created_purchase(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
@@ -966,6 +1244,42 @@ class StorePurchaseTest extends TestCase
|
||||
->assertJsonPath('data.total', '100.00');
|
||||
}
|
||||
|
||||
public function test_created_and_pending_payment_purchase_details_use_the_current_cart_quantity(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
$user = User::factory()->create([
|
||||
'email' => 'buyer@example.com',
|
||||
]);
|
||||
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||
|
||||
foreach ([Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT] as $status) {
|
||||
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||
$purchase->items()->create([
|
||||
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||
'source_variant_id' => $variant->id,
|
||||
'item_nombre' => $variant->catalogItem->nombre,
|
||||
'descripcion' => $variant->catalogItem->descripcion,
|
||||
'slug' => $variant->catalogItem->slug,
|
||||
'variant_attributes' => [],
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => '50.00',
|
||||
'total' => '50.00',
|
||||
]);
|
||||
$purchase->cart->items()->update(['cantidad' => 3]);
|
||||
$purchase->update(['status' => $status]);
|
||||
|
||||
$this->actingAs($user, 'sanctum')
|
||||
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', $status)
|
||||
->assertJsonPath('data.items_source', 'cart')
|
||||
->assertJsonPath('data.items.0.quantity', 3)
|
||||
->assertJsonPath('data.items.0.line_total', '150.00')
|
||||
->assertJsonPath('data.subtotal', '150.00')
|
||||
->assertJsonPath('data.total', '150.00');
|
||||
}
|
||||
}
|
||||
|
||||
public function test_purchase_detail_uses_purchase_items_for_paid_purchase_even_without_cart(): void
|
||||
{
|
||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Tests\Feature\Sale;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Authorization\Enums\RoleCode;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Events\PurchasePaid;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
@@ -30,6 +31,83 @@ class AdminAppSaleControllerTest extends TestCase
|
||||
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
|
||||
}
|
||||
|
||||
public function test_sales_list_uses_cart_quantity_for_created_and_pending_payment_sales(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$catalogItem = CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'entrada-general',
|
||||
'nombre' => 'Entrada general',
|
||||
'precio' => '10000.00',
|
||||
]);
|
||||
|
||||
$createdCart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'checkout',
|
||||
]);
|
||||
CartItem::query()->create([
|
||||
'cart_id' => $createdCart->id,
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'cantidad' => 3,
|
||||
]);
|
||||
$createdPurchase = Purchase::query()->create([
|
||||
'cart_id' => $createdCart->id,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Purchase::STATUS_CREATED,
|
||||
'total' => '30000.00',
|
||||
]);
|
||||
PurchaseItem::query()->create([
|
||||
'compra_id' => $createdPurchase->id,
|
||||
'source_catalog_item_id' => $catalogItem->id,
|
||||
'item_nombre' => $catalogItem->nombre,
|
||||
'cantidad' => 1,
|
||||
'precio_unitario' => '10000.00',
|
||||
'total' => '10000.00',
|
||||
]);
|
||||
|
||||
$pendingCart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'checkout',
|
||||
]);
|
||||
CartItem::query()->create([
|
||||
'cart_id' => $pendingCart->id,
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'cantidad' => 4,
|
||||
]);
|
||||
$pendingPurchase = Purchase::query()->create([
|
||||
'cart_id' => $pendingCart->id,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => '40000.00',
|
||||
]);
|
||||
|
||||
$paidPurchase = Purchase::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Purchase::STATUS_PAID,
|
||||
'total' => '20000.00',
|
||||
]);
|
||||
PurchaseItem::query()->create([
|
||||
'compra_id' => $paidPurchase->id,
|
||||
'source_catalog_item_id' => $catalogItem->id,
|
||||
'item_nombre' => $catalogItem->nombre,
|
||||
'cantidad' => 2,
|
||||
'precio_unitario' => '10000.00',
|
||||
'total' => '20000.00',
|
||||
]);
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/sales?sort_by=id&sort_direction=asc')
|
||||
->assertOk()
|
||||
->assertJsonCount(3, 'data')
|
||||
->assertJsonPath('data.0.id', $createdPurchase->id)
|
||||
->assertJsonPath('data.0.quantity', 3)
|
||||
->assertJsonPath('data.1.id', $pendingPurchase->id)
|
||||
->assertJsonPath('data.1.quantity', 4)
|
||||
->assertJsonPath('data.2.id', $paidPurchase->id)
|
||||
->assertJsonPath('data.2.quantity', 2);
|
||||
}
|
||||
|
||||
public function test_authentication_is_required_to_read_a_sale_detail(): void
|
||||
{
|
||||
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized();
|
||||
@@ -71,6 +149,92 @@ class AdminAppSaleControllerTest extends TestCase
|
||||
->assertJsonPath('data.total', '40000.00');
|
||||
}
|
||||
|
||||
public function test_an_adminapp_user_can_read_cart_items_from_an_unconfirmed_sale(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$catalogItem = CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'entrada-general',
|
||||
'nombre' => 'Entrada general',
|
||||
'descripcion' => 'Acceso general',
|
||||
'precio' => '12500.00',
|
||||
]);
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'checkout',
|
||||
]);
|
||||
$cartItem = CartItem::query()->create([
|
||||
'cart_id' => $cart->id,
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$purchase = Purchase::query()->create([
|
||||
'cart_id' => $cart->id,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => '25000.00',
|
||||
]);
|
||||
|
||||
$this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.id', $cartItem->id)
|
||||
->assertJsonPath('data.items.0.product', 'Entrada general')
|
||||
->assertJsonPath('data.items.0.event_dates', [])
|
||||
->assertJsonPath('data.items.0.quantity', 2)
|
||||
->assertJsonPath('data.items.0.unit_price', '12500.00')
|
||||
->assertJsonPath('data.items.0.total', '25000.00');
|
||||
}
|
||||
|
||||
public function test_sales_list_uses_cart_quantity_until_purchase_items_exist(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||
|
||||
$catalogItem = CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'entrada-general',
|
||||
'nombre' => 'Entrada general',
|
||||
'descripcion' => 'Acceso general',
|
||||
'precio' => '12500.00',
|
||||
]);
|
||||
$cart = Cart::query()->create([
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => 'checkout',
|
||||
]);
|
||||
CartItem::query()->create([
|
||||
'cart_id' => $cart->id,
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'cantidad' => 3,
|
||||
]);
|
||||
$purchase = Purchase::query()->create([
|
||||
'cart_id' => $cart->id,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'total' => '37500.00',
|
||||
]);
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/sales')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.0.id', $purchase->id)
|
||||
->assertJsonPath('data.0.quantity', 3);
|
||||
|
||||
PurchaseItem::query()->create([
|
||||
'compra_id' => $purchase->id,
|
||||
'source_catalog_item_id' => $catalogItem->id,
|
||||
'nombre' => 'Entrada general',
|
||||
'item_nombre' => 'Entrada general',
|
||||
'cantidad' => 2,
|
||||
'precio_unitario' => '12500.00',
|
||||
'total' => '25000.00',
|
||||
]);
|
||||
|
||||
$this->getJson('/api/v1/adminapp/tenant/sales')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.0.quantity', 2);
|
||||
}
|
||||
|
||||
public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
|
||||
{
|
||||
$tenant = $this->createTenant('acme');
|
||||
@@ -202,6 +366,18 @@ class AdminAppSaleControllerTest extends TestCase
|
||||
'user_id' => $admin->id,
|
||||
'status' => 'converted',
|
||||
]);
|
||||
$catalogItem = CatalogItem::query()->create([
|
||||
'tenant_code' => $tenant->codigo,
|
||||
'slug' => 'entrada-general',
|
||||
'nombre' => 'Entrada general',
|
||||
'descripcion' => 'Acceso general',
|
||||
'precio' => '10000.00',
|
||||
]);
|
||||
CartItem::query()->create([
|
||||
'cart_id' => $cart->id,
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$cart->delete();
|
||||
$purchase = Purchase::query()->create([
|
||||
'cart_id' => $cart->id,
|
||||
@@ -212,11 +388,17 @@ class AdminAppSaleControllerTest extends TestCase
|
||||
|
||||
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED)
|
||||
->assertJsonPath('data.quantity', 2);
|
||||
|
||||
$this->assertSame(Purchase::STATUS_CANCELLED, $purchase->fresh()->status);
|
||||
$this->assertSoftDeleted('carritos', ['id' => $cart->id]);
|
||||
$this->assertSame('converted', Cart::withTrashed()->findOrFail($cart->id)->status);
|
||||
|
||||
$this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.product', 'Entrada general')
|
||||
->assertJsonPath('data.items.0.quantity', 2);
|
||||
}
|
||||
|
||||
public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void
|
||||
|
||||
@@ -44,7 +44,8 @@ class DesfilePuraTendenciaSeederTest extends TestCase
|
||||
'footer_bg_color' => '#D4441C',
|
||||
'display_categories' => false,
|
||||
'display_seach_bar' => false,
|
||||
'cart_editing_enabled' => false,
|
||||
'cart_editing_policy' => 'full',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
'display_cart_item_images' => false,
|
||||
'site_title' => 'Desfile Pura Tendencia',
|
||||
]);
|
||||
@@ -216,12 +217,18 @@ class DesfilePuraTendenciaSeederTest extends TestCase
|
||||
->whereIn('variant_id', (clone $variants)->pluck('id'))
|
||||
->count());
|
||||
$this->assertSame(330, (clone $variants)->whereNull('event_date_id')->count());
|
||||
$this->assertSame(330, DB::table('inventories')
|
||||
$this->assertSame(284, DB::table('inventories')
|
||||
->whereIn('id', (clone $variants)->pluck('inventory_id'))
|
||||
->where('real_stock', 1)
|
||||
->where('reserved_stock', 0)
|
||||
->where('sold_units', 0)
|
||||
->count());
|
||||
$this->assertSame(46, DB::table('inventories')
|
||||
->whereIn('id', (clone $variants)->pluck('inventory_id'))
|
||||
->where('real_stock', 0)
|
||||
->where('reserved_stock', 0)
|
||||
->where('sold_units', 1)
|
||||
->count());
|
||||
$this->assertDatabaseHas('variantes', [
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'descripcion' => 'Sector A - Fila 1 - Asiento 17 - VIP + LUNCH',
|
||||
@@ -247,7 +254,7 @@ class DesfilePuraTendenciaSeederTest extends TestCase
|
||||
'sector' => ['B', 'D'],
|
||||
'asiento' => ['17'],
|
||||
]));
|
||||
$this->assertSame(66, $this->variantCountForSelection($catalogItem->id, [
|
||||
$this->assertSame(50, $this->variantCountForSelection($catalogItem->id, [
|
||||
'tipo' => ['VIP + LUNCH'],
|
||||
'fila' => ['1'],
|
||||
]));
|
||||
@@ -255,6 +262,71 @@ class DesfilePuraTendenciaSeederTest extends TestCase
|
||||
'tipo' => ['NORMAL'],
|
||||
'fila' => ['5'],
|
||||
]));
|
||||
|
||||
$this->assertInvitationPurchase($catalogItem->id);
|
||||
|
||||
$this->seed(DesfilePuraTendenciaSeeder::class);
|
||||
|
||||
$this->assertInvitationPurchase($catalogItem->id);
|
||||
}
|
||||
|
||||
private function assertInvitationPurchase(int $catalogItemId): void
|
||||
{
|
||||
$user = DB::table('users')->where('email', 'invitados@puratendencia.com')->sole();
|
||||
|
||||
$this->assertSame('user', $user->rol_codigo);
|
||||
$this->assertSame('desfile_pura_tendencia', $user->tenant_codigo);
|
||||
|
||||
$purchase = DB::table('compras')
|
||||
->where('tenant_codigo', 'desfile_pura_tendencia')
|
||||
->where('user_id', $user->id)
|
||||
->where('payment_method', 'invitation')
|
||||
->sole();
|
||||
|
||||
$this->assertSame('paid', $purchase->status);
|
||||
$this->assertEquals(0, $purchase->total);
|
||||
|
||||
$items = DB::table('compra_items')->where('compra_id', $purchase->id);
|
||||
|
||||
$this->assertSame(46, (clone $items)->count());
|
||||
$this->assertSame(46, (clone $items)
|
||||
->where('precio_unitario', 0)
|
||||
->where('discount_total', 0)
|
||||
->where('tax_total', 0)
|
||||
->where('total', 0)
|
||||
->count());
|
||||
$this->assertSame(46, DB::table('tickets')
|
||||
->where('source_purchase_id', $purchase->id)
|
||||
->where('user_id', $user->id)
|
||||
->where('source_catalog_item_id', $catalogItemId)
|
||||
->count());
|
||||
$this->assertSame(46, DB::table('stock_reservations')
|
||||
->where('purchase_id', $purchase->id)
|
||||
->where('status', 'committed')
|
||||
->count());
|
||||
|
||||
foreach ([
|
||||
['sector' => 'A', 'fila' => '1', 'tipo' => 'NORMAL', 'count' => 16],
|
||||
['sector' => 'A', 'fila' => '3', 'tipo' => 'NORMAL', 'count' => 14],
|
||||
['sector' => 'C', 'fila' => '1', 'tipo' => 'VIP + LUNCH', 'count' => 16],
|
||||
] as $allocation) {
|
||||
$allocatedVariants = DB::table('variantes')
|
||||
->where('catalog_item_id', $catalogItemId)
|
||||
->whereIn('id', (clone $items)->pluck('source_variant_id'));
|
||||
|
||||
foreach (['sector', 'fila', 'tipo'] as $code) {
|
||||
$allocatedVariants->whereExists(fn ($query) => $query
|
||||
->selectRaw('1')
|
||||
->from('variant_values')
|
||||
->join('item_attributes', 'item_attributes.id', '=', 'variant_values.item_attribute_id')
|
||||
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||
->whereColumn('variant_values.variant_id', 'variantes.id')
|
||||
->where('attribute.codigo', $code)
|
||||
->where('variant_values.value', $allocation[$code]));
|
||||
}
|
||||
|
||||
$this->assertSame($allocation['count'], $allocatedVariants->count());
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, list<string>> $selection */
|
||||
|
||||
@@ -61,6 +61,8 @@ class TenantSeederTest extends TestCase
|
||||
->sole();
|
||||
|
||||
$this->assertSame('shopit', $sonder->website_type_code);
|
||||
$this->assertSame('quantity_and_remove', $sonder->cart_editing_policy->value);
|
||||
$this->assertSame('disabled', $sonder->checkout_editing_policy->value);
|
||||
|
||||
$carousel = $sonder->websiteExtras
|
||||
->firstWhere('websiteTypeExtra.codigo', 'carousel');
|
||||
@@ -81,6 +83,8 @@ class TenantSeederTest extends TestCase
|
||||
->sole();
|
||||
|
||||
$this->assertSame('onticket', $fiesta->website_type_code);
|
||||
$this->assertSame('full', $fiesta->cart_editing_policy->value);
|
||||
$this->assertSame('disabled', $fiesta->checkout_editing_policy->value);
|
||||
|
||||
$extras = $fiesta->websiteExtras->keyBy('websiteTypeExtra.codigo');
|
||||
$this->assertEqualsCanonicalizing(
|
||||
|
||||
@@ -59,6 +59,8 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
'codigo' => 'acme',
|
||||
'nombre' => 'Acme',
|
||||
'dominio' => 'acme.com',
|
||||
'address' => 'Calle Test 123, Rosario',
|
||||
'phone' => '+54 341 555 1234',
|
||||
'primary_color' => '#ff0000',
|
||||
'secondary_color' => '#00ff00',
|
||||
'danger_color' => '#0000ff',
|
||||
@@ -73,7 +75,8 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
'display_categories' => false,
|
||||
'display_seach_bar' => false,
|
||||
'display_cart' => false,
|
||||
'cart_editing_enabled' => false,
|
||||
'cart_editing_policy' => 'disabled',
|
||||
'checkout_editing_policy' => 'quantity_and_remove',
|
||||
'display_cart_item_images' => false,
|
||||
]);
|
||||
|
||||
@@ -83,6 +86,8 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
->assertOk()
|
||||
->assertJsonPath('data.codigo', 'acme')
|
||||
->assertJsonPath('data.dominio', 'acme.com')
|
||||
->assertJsonPath('data.address', 'Calle Test 123, Rosario')
|
||||
->assertJsonPath('data.phone', '+54 341 555 1234')
|
||||
->assertJsonPath('data.primary_color', '#ff0000')
|
||||
->assertJsonPath('data.secondary_color', '#00ff00')
|
||||
->assertJsonPath('data.danger_color', '#0000ff')
|
||||
@@ -91,7 +96,16 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
->assertJsonPath('data.display_categories', false)
|
||||
->assertJsonPath('data.display_seach_bar', false)
|
||||
->assertJsonPath('data.display_cart', false)
|
||||
->assertJsonPath('data.cart_editing_enabled', false)
|
||||
->assertJsonPath('data.cart_editing_policy.code', 'disabled')
|
||||
->assertJsonPath('data.cart_editing_policy.allow_modify', false)
|
||||
->assertJsonPath('data.cart_editing_policy.allow_delete', false)
|
||||
->assertJsonPath('data.cart_editing_policy.allow_update_quantity', false)
|
||||
->assertJsonPath('data.cart_editing_policy.allow_update_variant', false)
|
||||
->assertJsonPath('data.checkout_editing_policy.code', 'quantity_and_remove')
|
||||
->assertJsonPath('data.checkout_editing_policy.allow_modify', true)
|
||||
->assertJsonPath('data.checkout_editing_policy.allow_delete', true)
|
||||
->assertJsonPath('data.checkout_editing_policy.allow_update_quantity', true)
|
||||
->assertJsonPath('data.checkout_editing_policy.allow_update_variant', false)
|
||||
->assertJsonPath('data.display_cart_item_images', false)
|
||||
->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');
|
||||
|
||||
@@ -758,7 +772,8 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
|
||||
$response = $this->putJson("/api/tenants/{$tenant->codigo}", [
|
||||
'primary_color' => '#000000',
|
||||
'cart_editing_enabled' => false,
|
||||
'cart_editing_policy' => 'quantity_and_remove',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
'display_cart_item_images' => false,
|
||||
]);
|
||||
|
||||
@@ -767,7 +782,13 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
->assertJsonPath('data.codigo', 'acme')
|
||||
->assertJsonPath('data.nombre', 'Acme')
|
||||
->assertJsonPath('data.primary_color', '#000000')
|
||||
->assertJsonPath('data.cart_editing_enabled', false)
|
||||
->assertJsonPath('data.cart_editing_policy.code', 'quantity_and_remove')
|
||||
->assertJsonPath('data.cart_editing_policy.allow_modify', true)
|
||||
->assertJsonPath('data.cart_editing_policy.allow_delete', true)
|
||||
->assertJsonPath('data.cart_editing_policy.allow_update_quantity', true)
|
||||
->assertJsonPath('data.cart_editing_policy.allow_update_variant', false)
|
||||
->assertJsonPath('data.checkout_editing_policy.code', 'disabled')
|
||||
->assertJsonPath('data.checkout_editing_policy.allow_modify', false)
|
||||
->assertJsonPath('data.display_cart_item_images', false);
|
||||
|
||||
$this->assertDatabaseHas('tenants', [
|
||||
@@ -775,7 +796,8 @@ class BootstrapTenantControllerTest extends TestCase
|
||||
'codigo' => 'acme',
|
||||
'nombre' => 'Acme',
|
||||
'primary_color' => '#000000',
|
||||
'cart_editing_enabled' => false,
|
||||
'cart_editing_policy' => 'quantity_and_remove',
|
||||
'checkout_editing_policy' => 'disabled',
|
||||
'display_cart_item_images' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ namespace Tests\Unit\Catalog;
|
||||
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
||||
use App\Domains\Catalog\Services\ExpireStockReservationsService;
|
||||
use App\Domains\Purchase\Services\CheckoutService;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ExpireStockReservationsServiceTest extends TestCase
|
||||
@@ -23,6 +26,20 @@ class ExpireStockReservationsServiceTest extends TestCase
|
||||
->ordered()
|
||||
->andReturn(3);
|
||||
|
||||
$logger = \Mockery::mock(LoggerInterface::class);
|
||||
Log::shouldReceive('channel')
|
||||
->once()
|
||||
->with('commands')
|
||||
->andReturn($logger);
|
||||
$logger->shouldReceive('info')
|
||||
->once()
|
||||
->with('Stock reservation cleanup completed.', [
|
||||
'command' => 'reservations:expire',
|
||||
'expired_purchases' => 2,
|
||||
'expired_cart_items' => 3,
|
||||
'total_expired' => 5,
|
||||
]);
|
||||
|
||||
$result = (new ExpireStockReservationsService($checkout, $carts))->expireOverdue();
|
||||
|
||||
$this->assertSame([
|
||||
@@ -30,4 +47,32 @@ class ExpireStockReservationsServiceTest extends TestCase
|
||||
'cart_items' => 3,
|
||||
], $result);
|
||||
}
|
||||
|
||||
public function test_it_logs_failed_cleanup_attempts_and_rethrows_the_error(): void
|
||||
{
|
||||
$exception = new RuntimeException('Unable to clean carts.');
|
||||
$checkout = \Mockery::mock(CheckoutService::class);
|
||||
$checkout->shouldReceive('expireOverduePurchases')->once()->andReturn(2);
|
||||
|
||||
$carts = \Mockery::mock(ExpireCartReservationsService::class);
|
||||
$carts->shouldReceive('expireOverdue')->once()->andThrow($exception);
|
||||
|
||||
$logger = \Mockery::mock(LoggerInterface::class);
|
||||
Log::shouldReceive('channel')
|
||||
->once()
|
||||
->with('commands')
|
||||
->andReturn($logger);
|
||||
$logger->shouldReceive('error')
|
||||
->once()
|
||||
->with('Stock reservation cleanup failed.', [
|
||||
'command' => 'reservations:expire',
|
||||
'expired_purchases' => 2,
|
||||
'expired_cart_items' => null,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
|
||||
$this->expectExceptionObject($exception);
|
||||
|
||||
(new ExpireStockReservationsService($checkout, $carts))->expireOverdue();
|
||||
}
|
||||
}
|
||||
|
||||
56
tests/Unit/Purchase/PurchaseStateGuardTest.php
Normal file
56
tests/Unit/Purchase/PurchaseStateGuardTest.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Purchase;
|
||||
|
||||
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PurchaseStateGuardTest extends TestCase
|
||||
{
|
||||
private PurchaseStateGuard $guard;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->guard = new PurchaseStateGuard;
|
||||
}
|
||||
|
||||
public function test_it_rejects_a_purchase_with_expired_status(): void
|
||||
{
|
||||
$purchase = (new Purchase)->forceFill([
|
||||
'status' => Purchase::STATUS_EXPIRED,
|
||||
'expires_at' => null,
|
||||
]);
|
||||
|
||||
$this->expectException(PurchaseExpiredException::class);
|
||||
|
||||
$this->guard->assertNotExpired($purchase);
|
||||
}
|
||||
|
||||
public function test_it_rejects_an_active_purchase_when_its_deadline_has_passed(): void
|
||||
{
|
||||
$purchase = (new Purchase)->forceFill([
|
||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||
'expires_at' => now()->subMinute(),
|
||||
]);
|
||||
|
||||
$this->expectException(PurchaseExpiredException::class);
|
||||
|
||||
$this->guard->assertNotExpired($purchase);
|
||||
}
|
||||
|
||||
public function test_it_does_not_treat_a_paid_purchase_as_expired_by_time(): void
|
||||
{
|
||||
$purchase = (new Purchase)->forceFill([
|
||||
'status' => Purchase::STATUS_PAID,
|
||||
'expires_at' => now()->subMinute(),
|
||||
]);
|
||||
|
||||
$this->guard->assertNotExpired($purchase);
|
||||
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace Tests\Unit\Sale;
|
||||
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Cart\Models\CartItem;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Purchase\Models\Purchase;
|
||||
use App\Domains\Purchase\Models\PurchaseItem;
|
||||
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
|
||||
@@ -38,4 +41,39 @@ class SaleDetailResourceTest extends TestCase
|
||||
$this->assertSame('30000.00', $data['items'][0]['total']);
|
||||
$this->assertSame('30000.00', $data['total']);
|
||||
}
|
||||
|
||||
public function test_it_uses_the_associated_cart_items_when_the_purchase_has_no_items(): void
|
||||
{
|
||||
$catalogItem = (new CatalogItem)->forceFill([
|
||||
'id' => 21,
|
||||
'nombre' => 'Entrada general',
|
||||
'precio' => '12500.00',
|
||||
]);
|
||||
$cartItem = (new CartItem)->forceFill([
|
||||
'id' => 34,
|
||||
'catalog_item_id' => $catalogItem->id,
|
||||
'cantidad' => 2,
|
||||
]);
|
||||
$cartItem->setRelation('catalogItem', $catalogItem);
|
||||
$cartItem->setRelation('variant', null);
|
||||
|
||||
$cart = new Cart;
|
||||
$cart->setRelation('items', collect([$cartItem]));
|
||||
|
||||
$purchase = (new Purchase)->forceFill([
|
||||
'id' => 16,
|
||||
'total' => '25000.00',
|
||||
]);
|
||||
$purchase->setRelation('items', collect());
|
||||
$purchase->setRelation('cart', $cart);
|
||||
|
||||
$data = (new SaleDetailResource($purchase))->resolve(Request::create('/'));
|
||||
|
||||
$this->assertSame(34, $data['items'][0]['id']);
|
||||
$this->assertSame('Entrada general', $data['items'][0]['product']);
|
||||
$this->assertSame([], $data['items'][0]['event_dates']);
|
||||
$this->assertSame(2, $data['items'][0]['quantity']);
|
||||
$this->assertSame('12500.00', $data['items'][0]['unit_price']);
|
||||
$this->assertSame('25000.00', $data['items'][0]['total']);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user