Compare commits

...

51 Commits

Author SHA1 Message Date
559bf5d264 Merge branch 'fix/expiration_purchase_messages' of https://gitea.quo.ar/tbianchini/shopit-back into fix/expiration_purchase_messages 2026-08-21 08:58:55 -03:00
eafb02ffd5 fix(purchase): enhance handling of cart items for created and pending payment purchases 2026-08-21 08:58:51 -03:00
786cf2db52 fix(cart): propagate expired checkout purchase errors 2026-08-21 08:58:51 -03:00
cb56e33685 fix(purchase): unify expired checkout errors 2026-08-21 08:58:51 -03:00
dd81e3b3f7 feat: enhance sale detail retrieval by including trashed cart items and update related tests 2026-08-21 08:58:18 -03:00
4d51531c5d Merge branch 'fix/expiration_purchase_messages' of https://gitea.quo.ar/tbianchini/shopit-back into fix/expiration_purchase_messages 2026-08-21 08:55:01 -03:00
7fd8a00054 fix(purchase): enhance handling of cart items for created and pending payment purchases 2026-08-21 08:54:58 -03:00
23163a6eb8 fix(cart): propagate expired checkout purchase errors 2026-08-21 08:50:59 -03:00
944cf8ee18 fix(purchase): unify expired checkout errors 2026-08-21 08:50:59 -03:00
8c09ca1204 feat: update sales query to use cart quantity when purchase items are absent and enhance related tests 2026-08-21 08:48:27 -03:00
98d502a8ef fix(purchase): enhance handling of cart items for created and pending payment purchases 2026-08-20 17:02:50 -03:00
318e6559cb fix(cart): propagate expired checkout purchase errors 2026-08-20 17:01:21 -03:00
9fd34f900f fix(purchase): unify expired checkout errors 2026-08-20 17:01:06 -03:00
ae6149df84 feat: enable full cart editing for Desfile tenant and update related tests 2026-08-20 15:13:23 -03:00
1776cfe581 Revert "feat: add session partitioned cookie support and update related tests"
This reverts commit 5ad18694e1.
2026-08-20 15:12:41 -03:00
5ad18694e1 feat: add session partitioned cookie support and update related tests 2026-08-20 14:47:51 -03:00
6775fb110c feat: simplify cart restoration logic in ReleaseCheckoutService and SourceCartService 2026-08-20 13:53:04 -03:00
9c46eff880 feat: add checkout editing policy to tenants and update related logic across services and resources 2026-08-20 12:38:22 -03:00
c8ce3b0da3 feat(checkout): enforce editing policy on items 2026-08-20 10:56:19 -03:00
d36a929f8c feat(tenant): add checkout editing policy 2026-08-20 10:56:13 -03:00
2de02dfd31 feat: add item editing preparation and enhance payment intent handling in PurchaseController 2026-08-20 09:46:32 -03:00
f9a766dee1 feat: enhance purchase loading logic to include cart items when purchase items are empty 2026-08-20 08:48:03 -03:00
8bc57cf0ff fix: update import statements in EditCheckoutService for clarity and consistency 2026-08-19 17:22:02 -03:00
a78c5cee58 Merge branch 'dev' into homo 2026-08-19 17:03:08 -03:00
cc22e33799 feat: implement cart editing policies and update related services
- Introduced CartEditingPolicy enum to manage cart editing rules.
- Updated Tenant model to use cart_editing_policy instead of a boolean flag.
- Refactored PurchaseItemSnapshotFactory to include variant details.
- Added PurchaseResponseLoader service to streamline purchase loading.
- Enhanced SourceCartService with methods to sync item quantities and selections.
- Updated StartCheckoutService to utilize the new PurchaseResponseLoader.
- Created new API routes for editing purchase items.
- Added tests to validate cart editing policies and their effects on item updates.
- Migrated existing data to the new cart editing policy structure.
- Updated language files to reflect changes in cart editing messages.
2026-08-19 16:59:30 -03:00
5c0b3503b7 feat(purchase): implement purchase limit enforcement and custom exception handling 2026-08-19 16:48:32 -03:00
8537d2ed0a feat(catalog): implement maximum addable quantity logic and user quota sharing across variants 2026-08-19 16:48:32 -03:00
d97cc12af6 Merge branch 'feature/cart_editing_policy' into dev 2026-08-19 16:47:30 -03:00
7a19b3a97a Merge branch 'dev' into homo 2026-08-19 15:28:38 -03:00
a94ac7a473 Merge branch 'dev' of https://gitea.quo.ar/tbianchini/shopit-back into dev 2026-08-19 15:28:09 -03:00
161693509f feat(telepagos): enhance webhook handling 2026-08-19 15:26:44 -03:00
93c99afb13 feat(telepagos): enhance webhook handling and add TenantTransactionResetService 2026-08-19 15:23:22 -03:00
32d2b182c6 Merge branch 'feature/reserved_invitations' into dev 2026-08-19 14:33:38 -03:00
2632a80722 feat(invitation): implement InvitationPurchaseProvisioner and related migration and seeder updates 2026-08-19 14:33:08 -03:00
3cee9c28f8 Merge branch 'dev' into homo 2026-08-19 14:19:06 -03:00
2091b1361a Merge branch 'refactor/simplify_cart_snapshot' into dev 2026-08-19 14:18:17 -03:00
a2c5e687f9 feat(logging): record reservation cleanup attempts 2026-08-19 14:17:05 -03:00
172e14ae9b Squashed commit of the following:
commit 1dc4e29c69
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 13:58:03 2026 -0300

    refactor(reservations): unify expiration command

commit 093e894cc3
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 13:48:09 2026 -0300

    feat(cart): expire abandoned stock reservations

commit fdf0f3328f
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:53:12 2026 -0300

    refactor(stock): implement expiration for stock reservations and add configuration

commit 8d6bcdcc43
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:38:21 2026 -0300

    refactor(cart): invalidate payment on actual changes

commit 3206e293eb
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:24:48 2026 -0300

    refactor(cart): own checkout item editing

commit aed99bd05e
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:14:57 2026 -0300

    refactor(checkout): remove legacy purchase item reservations

commit f1649e0e4b
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:06:29 2026 -0300

    refactor(checkout): materialize purchase items on confirmation

commit e6c4b40a37
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:06:19 2026 -0300

    feat(inventory): add traceable cart stock reservations
2026-08-19 13:59:38 -03:00
58cbeae9d3 Squashed commit of the following:
commit 1dc4e29c69
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 13:58:03 2026 -0300

    refactor(reservations): unify expiration command

commit 093e894cc3
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 13:48:09 2026 -0300

    feat(cart): expire abandoned stock reservations

commit fdf0f3328f
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:53:12 2026 -0300

    refactor(stock): implement expiration for stock reservations and add configuration

commit 8d6bcdcc43
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:38:21 2026 -0300

    refactor(cart): invalidate payment on actual changes

commit 3206e293eb
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:24:48 2026 -0300

    refactor(cart): own checkout item editing

commit aed99bd05e
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:14:57 2026 -0300

    refactor(checkout): remove legacy purchase item reservations

commit f1649e0e4b
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:06:29 2026 -0300

    refactor(checkout): materialize purchase items on confirmation

commit e6c4b40a37
Author: ncoronel <ncoronel@quo.ar>
Date:   Wed Aug 19 12:06:19 2026 -0300

    feat(inventory): add traceable cart stock reservations
2026-08-19 13:59:25 -03:00
1dc4e29c69 refactor(reservations): unify expiration command 2026-08-19 13:58:03 -03:00
093e894cc3 feat(cart): expire abandoned stock reservations 2026-08-19 13:48:09 -03:00
fdf0f3328f refactor(stock): implement expiration for stock reservations and add configuration 2026-08-19 13:43:08 -03:00
8d6bcdcc43 refactor(cart): invalidate payment on actual changes 2026-08-19 13:43:08 -03:00
3206e293eb refactor(cart): own checkout item editing 2026-08-19 13:43:08 -03:00
aed99bd05e refactor(checkout): remove legacy purchase item reservations 2026-08-19 13:43:08 -03:00
f1649e0e4b refactor(checkout): materialize purchase items on confirmation 2026-08-19 13:43:08 -03:00
e6c4b40a37 feat(inventory): add traceable cart stock reservations 2026-08-19 13:43:08 -03:00
15878cd9ba fix(logging): update Telepagos log path to include date directory 2026-08-19 13:40:40 -03:00
d6574bfd0d feat(logging): implement dedicated logging for Telepagos events and update logging configuration 2026-08-19 13:37:21 -03:00
7cea8d3495 feat(cart): enhance item update functionality to support variant changes and improve cart editing policies 2026-08-19 10:46:19 -03:00
014b5bb012 feat(cart): implement cart editing policies and update related functionality 2026-08-19 10:15:37 -03:00
102 changed files with 4809 additions and 569 deletions

View File

@@ -8,6 +8,7 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
PURCHASE_QR_EXPIRATION_MINUTES=15
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
STOCK_RESERVATION_EXPIRATION_MINUTES=30
FRONTEND_URLS=http://localhost:4200
APP_LOCALE=es
@@ -31,10 +32,15 @@ AUTH_LOGIN_LOCK_MINUTES=15
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
LOG_CHANNEL=stack
LOG_CHANNEL=daily
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
LOG_DAILY_DAYS=14
TELEPAGOS_LOG_LEVEL=info
TELEPAGOS_LOG_DAYS=30
COMMANDS_LOG_LEVEL=info
COMMANDS_LOG_DAYS=30
DB_CONNECTION=mysql
DB_HOST=127.0.0.1

View File

@@ -2,7 +2,7 @@
"info": {
"_postman_id": "76fd6fd2-53b9-4d92-8e02-1ddcc6207fa2",
"name": "ShopIt API — Complete",
"description": "Colección canónica generada desde las rutas reales de Laravel. Incluye 123 operaciones HTTP, ejemplos de payload, filtros, archivos y tokens separados para Storefront, Admin App y Scanner.\n\nUso rápido:\n1. Ajustá `base_url` y las credenciales.\n2. Ejecutá el Login de la aplicación correspondiente; el token se guarda automáticamente.\n3. Ajustá los IDs y códigos de las variables de colección.\n\nRegeneración: `php postman/generate-shopit-collection.php`.",
"description": "Colección canónica generada desde las rutas reales de Laravel. Incluye 122 operaciones HTTP, ejemplos de payload, filtros, archivos y tokens separados para Storefront, Admin App y Scanner.\n\nUso rápido:\n1. Ajustá `base_url` y las credenciales.\n2. Ejecutá el Login de la aplicación correspondiente; el token se guarda automáticamente.\n3. Ajustá los IDs y códigos de las variables de colección.\n\nRegeneración: `php postman/generate-shopit-collection.php`.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
@@ -572,6 +572,60 @@
}
},
"response": []
},
{
"name": "Update Checkout Cart Item Cart",
"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}/checkout-carts/{cart}/items/{cartItem}`\n\nControlador: `App\\Domains\\Cart\\Controllers\\CartController@updateCheckoutItem`\n\nRequiere autenticación Sanctum.",
"url": {
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/checkout-carts/{{cart}}/items/{{cart_item_id}}",
"host": [
"{{base_url}}"
],
"path": [
"api",
"tenants",
"{{tenant_code}}",
"checkout-carts",
"{{cart}}",
"items",
"{{cart_item_id}}"
]
},
"body": {
"mode": "raw",
"raw": "{\n \"cantidad\": 2\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{token}}",
"type": "string"
}
]
}
},
"response": []
}
]
},
@@ -1155,7 +1209,7 @@
"response": []
},
{
"name": "Update Item Quantity Purchase",
"name": "Update Item Purchase",
"request": {
"method": "PATCH",
"header": [
@@ -1170,7 +1224,7 @@
"type": "text"
}
],
"description": "Ruta Laravel: `PATCH /api/tenants/{tenant:codigo}/compras/{compra}/items/{item}`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@updateItemQuantity`\n\nRequiere autenticación Sanctum.",
"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": [
@@ -1188,7 +1242,7 @@
},
"body": {
"mode": "raw",
"raw": "{\n \"quantity\": 2\n}",
"raw": "{\n \"quantity\": 2,\n \"variant_id\": {{variant_id}}\n}",
"options": {
"raw": {
"language": "json"
@@ -2160,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"
@@ -2226,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"
@@ -2266,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"

View 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());
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Cart\Controllers;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest;
@@ -77,6 +78,36 @@ class CartController extends Controller
]);
}
public function updateCheckoutItem(
UpdateCartItemQuantityRequest $request,
Tenant $tenant,
Cart $cart,
CartItem $cartItem,
): CartResource {
$updatesVariant = $request->exists('variant_id');
return CartResource::make(
$this->cartService->updateCheckoutItem(
$tenant,
$request,
$cart,
$cartItem->getKey(),
(int) $request->validated('cantidad'),
$updatesVariant
? ($request->validated('variant_id') !== null
? (int) $request->validated('variant_id')
: null)
: $cartItem->variant_id,
$updatesVariant,
),
)->additional([
'code' => $updatesVariant ? 'cart.item_updated' : 'cart.quantity_updated',
'message' => $updatesVariant
? __('api.cart.item_updated')
: __('api.cart.quantity_updated'),
]);
}
public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
{
return CartResource::make(
@@ -86,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'),
]);
}
}

View File

@@ -7,6 +7,8 @@ use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -24,6 +26,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
'user_id',
'guest_token',
'status',
'origin',
])]
class Cart extends Model
{
@@ -32,6 +35,10 @@ class Cart extends Model
protected $table = 'carritos';
public const ORIGIN_USER = 'user';
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
protected function casts(): array
{
return [
@@ -63,6 +70,12 @@ class Cart extends Model
return $this->hasMany(CartItem::class, 'cart_id');
}
/** @return HasMany<Purchase, $this> */
public function purchases(): HasMany
{
return $this->hasMany(Purchase::class, 'cart_id');
}
public function getTotalAmount(): float
{
$items = $this->relationLoaded('items')
@@ -90,9 +103,14 @@ class Cart extends Model
$cartQuantity = (int) $this->items()
->where('catalog_item_id', $catalogItemId)
->sum('cantidad');
$this->assertUserPurchaseLimit($selectedItem, $cartQuantity + $quantity);
$inventoryService = app(CatalogInventoryService::class);
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
$this->assertUserPurchaseLimit(
$selectedItem,
$cartQuantity + $quantity,
heldQuantity: $cartQuantity,
maximumAddableCeiling: $availableQuantity,
);
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
@@ -114,11 +132,12 @@ class Cart extends Model
'cantidad' => $quantity,
]);
} else {
app(StockReservationService::class)->ensure($item, $selectedItem);
$item->cantidad += $quantity;
$item->save();
}
$inventoryService->reserve($selectedItem, $quantity);
app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
return $item->fresh();
});
@@ -129,6 +148,7 @@ class Cart extends Model
int $quantity,
?int $variantId = null,
bool $updateVariant = false,
?int $excludedPurchaseId = null,
): CartItem {
if ($quantity <= 0) {
throw ValidationException::withMessages([
@@ -141,6 +161,7 @@ class Cart extends Model
$quantity,
$variantId,
$updateVariant,
$excludedPurchaseId,
): CartItem {
/** @var CartItem $item */
$item = $this->items()
@@ -165,12 +186,16 @@ class Cart extends Model
->where('catalog_item_id', $item->catalog_item_id)
->whereKeyNot($item->getKey())
->sum('cantidad');
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
$this->assertUserPurchaseLimit(
$nextSelection,
$otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$nextAvailableQuantity,
);
$inventoryService->release($currentSelection, $item->cantidad);
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
$availableQuantity = $inventoryService->availableQuantity($nextSelection);
if ($availableQuantity !== null && $availableQuantity < $quantity) {
@@ -186,11 +211,11 @@ class Cart extends Model
->lockForUpdate()
->first();
$inventoryService->reserve($nextSelection, $quantity);
if ($targetItem !== null) {
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
$targetItem->cantidad += $quantity;
$targetItem->save();
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
$item->delete();
return $targetItem->fresh();
@@ -199,11 +224,13 @@ class Cart extends Model
$item->variant_id = $variantId;
$item->cantidad = $quantity;
$item->save();
app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
return $item->fresh();
}
$delta = $quantity - $item->cantidad;
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0) {
$otherVariantsQuantity = (int) $this->items()
@@ -213,11 +240,12 @@ class Cart extends Model
$this->assertUserPurchaseLimit(
$currentSelection,
$otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$availableQuantity,
);
}
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad;
throw ValidationException::withMessages([
@@ -225,17 +253,17 @@ class Cart extends Model
]);
}
$item->cantidad = $quantity;
$item->save();
if ($delta > 0) {
$inventoryService->reserve($currentSelection, $delta);
app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
}
if ($delta < 0) {
$inventoryService->release($currentSelection, abs($delta));
app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
}
$item->cantidad = $quantity;
$item->save();
return $item->fresh();
});
}
@@ -254,7 +282,8 @@ class Cart extends Model
$item->variant_id,
true,
);
app(CatalogInventoryService::class)->release(
app(StockReservationService::class)->release(
$item,
$selectedItem,
$item->cantidad,
);
@@ -334,6 +363,9 @@ class Cart extends Model
private function assertUserPurchaseLimit(
CatalogItem|Variant $selectedItem,
int $cartQuantity,
?int $excludedPurchaseId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
): void {
if ($this->user_id === null) {
return;
@@ -347,6 +379,10 @@ class Cart extends Model
$catalogItem,
$this->user_id,
$cartQuantity,
$excludedPurchaseId,
$this->getKey(),
$heldQuantity,
$maximumAddableCeiling,
field: 'cantidad',
);
}

View File

@@ -3,11 +3,13 @@
namespace App\Domains\Cart\Models;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([
'cart_id',
@@ -55,4 +57,10 @@ class CartItem extends Model
{
return $this->variant ?? $this->catalogItem;
}
/** @return HasMany<StockReservation, $this> */
public function stockReservations(): HasMany
{
return $this->hasMany(StockReservation::class);
}
}

View File

@@ -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()),
'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
: $this->variant->inventory->availableStock(),
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes),
],
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
];
}

View File

@@ -4,15 +4,26 @@ namespace App\Domains\Cart\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CartService
{
public function __construct(
private readonly StockReservationService $reservations,
private readonly PurchaseStateGuard $purchaseState,
) {}
public function show(Tenant $tenant, Request $request): Cart
{
$resolvedIdentity = $this->resolveIdentity($request);
@@ -27,7 +38,7 @@ class CartService
return $this->makeEmptyCart($tenant);
}
return $this->loadCart($cart);
return $this->loadCart($cart, $tenant);
}
/**
@@ -46,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'],
];
}
@@ -59,34 +70,248 @@ class CartService
?int $variantId,
bool $updateVariant,
): Cart {
if ($updateVariant && ! $tenant->cart_editing_policy->allowsVariantChanges()) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_change_disabled'),
]);
}
if (! $updateVariant && ! $tenant->cart_editing_policy->allowsQuantityChanges()) {
throw ValidationException::withMessages([
'cantidad' => __('api.cart.editing_disabled'),
]);
}
$identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity);
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant);
return $this->loadCart($cart);
return $this->loadCart($cart, $tenant);
}
public function updateCheckoutItem(
Tenant $tenant,
Request $request,
Cart $cart,
int $cartItemId,
int $quantity,
?int $variantId,
bool $updateVariant,
): Cart {
$user = $request->user() ?? Auth::guard('sanctum')->user();
if (! $user instanceof User) {
throw new NotFoundHttpException('Checkout cart not found.');
}
return DB::transaction(function () use (
$tenant,
$user,
$cart,
$cartItemId,
$quantity,
$variantId,
$updateVariant,
): Cart {
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->where('cart_id', $cart->getKey())
->where('tenant_codigo', $tenant->codigo)
->where('user_id', $user->getKey())
->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.');
}
/** @var CartItem|null $cartItem */
$cartItem = $checkoutCart->items()
->whereKey($cartItemId)
->lockForUpdate()
->first();
if ($cartItem === null) {
throw new NotFoundHttpException('Checkout item not found.');
}
$hasChanges = (int) $cartItem->cantidad !== $quantity
|| ($updateVariant && $cartItem->variant_id !== $variantId);
if (! $hasChanges) {
return $this->loadCart($checkoutCart, $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(
$cartItemId,
$quantity,
$variantId,
$updateVariant,
$purchase->getKey(),
);
$purchase->telepagosQr()->delete();
$purchase->update([
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'transfer_payer_dni' => null,
'total' => $checkoutCart->getTotalAmount(),
'expires_at' => now()->addMinutes(
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
),
]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadCart($checkoutCart, $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,
);
}
@@ -102,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',
@@ -113,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);
}
/**

View File

@@ -0,0 +1,123 @@
<?php
namespace App\Domains\Cart\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\StockReservation;
use Illuminate\Support\Facades\DB;
class ExpireCartReservationsService
{
public function expireOverdue(): int
{
$expiredItems = 0;
$lastCartItemId = 0;
do {
$cartItemIds = StockReservation::query()
->where('status', StockReservation::STATUS_ACTIVE)
->whereNull('purchase_id')
->whereNotNull('cart_item_id')
->whereNotNull('expires_at')
->where('expires_at', '<=', now())
->where('cart_item_id', '>', $lastCartItemId)
->whereHas('cartItem.cart', fn ($query) => $query->where('status', 'active'))
->select('cart_item_id')
->distinct()
->orderBy('cart_item_id')
->limit(500)
->pluck('cart_item_id');
foreach ($cartItemIds as $cartItemId) {
$lastCartItemId = (int) $cartItemId;
if ($this->expireCartItem($lastCartItemId)) {
$expiredItems++;
}
}
} while ($cartItemIds->count() === 500);
return $expiredItems;
}
private function expireCartItem(int $cartItemId): bool
{
/** @var CartItem|null $candidate */
$candidate = CartItem::query()->select(['id', 'cart_id'])->find($cartItemId);
if ($candidate === null) {
return false;
}
return DB::transaction(function () use ($candidate, $cartItemId): bool {
/** @var Cart|null $cart */
$cart = Cart::query()
->whereKey($candidate->cart_id)
->where('status', 'active')
->lockForUpdate()
->first();
if ($cart === null) {
return false;
}
/** @var CartItem|null $cartItem */
$cartItem = $cart->items()
->whereKey($cartItemId)
->lockForUpdate()
->first();
if ($cartItem === null) {
return false;
}
$reservations = StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->orderBy('inventory_id')
->lockForUpdate()
->get();
if (
$reservations->isEmpty()
|| $reservations->contains(
fn (StockReservation $reservation): bool => $reservation->purchase_id !== null
|| $reservation->expires_at === null
|| $reservation->expires_at->isFuture(),
)
) {
return false;
}
$inventories = Inventory::query()
->whereKey($reservations->pluck('inventory_id'))
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
foreach ($reservations as $reservation) {
$inventory = $inventories->get($reservation->inventory_id)
?? throw new \InvalidArgumentException('No se encontro el inventario reservado.');
$inventory->release((int) $reservation->quantity);
$reservation->update([
'quantity' => 0,
'status' => StockReservation::STATUS_EXPIRED,
'expires_at' => null,
'released_at' => now(),
]);
}
$cartItem->delete();
if (! $cart->items()->exists()) {
$cart->update(['status' => 'expired']);
$cart->delete();
}
return true;
});
}
}

View File

@@ -34,6 +34,10 @@ class GuestCartMergeService
->first();
if ($userCart !== null) {
$userCart->items()
->orderBy('id')
->pluck('id')
->each(fn (int $itemId) => $userCart->removeItem($itemId));
$userCart->update([
'status' => 'converted',
]);

View File

@@ -7,11 +7,12 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
## Modelo
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems.
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; expone la selección efectiva.
- `CartItem`: referencia un `CatalogItem` y, opcionalmente, una `Variant`; sólo persiste la selección y cantidad, y expone siempre los datos vigentes del catálogo.
## Servicios
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado.
- `ExpireCartReservationsService`: libera las reservas vencidas de carritos activos y elimina los carritos que quedan vacíos.
- `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
## Endpoints
@@ -30,3 +31,7 @@ Bajo `/tenants/{tenant:codigo}`:
## Dependencias y reglas
Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y de `Auth` cuando existe usuario. Toda operación debe comprobar que carrito e ítem pertenecen al tenant actual.
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.

View File

@@ -10,3 +10,10 @@ Route::prefix('tenants/{tenant:codigo}')
Route::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']);
});
Route::prefix('tenants/{tenant:codigo}')
->middleware('auth:sanctum')
->group(function (): void {
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem'])->withTrashed();
Route::delete('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'removeCheckoutItem'])->withTrashed();
});

View File

@@ -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(
$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(
$items = $catalogService->categoryItems(
$tenant,
$category,
$tenant->search_items_per_page,
(int) $request->validated('page', 1),
)
)->additional([
);
$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(
$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;
}
}

View File

@@ -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 [

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Catalog\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
#[Fillable([
@@ -47,6 +48,12 @@ class Inventory extends Model
return $this->hasOne(Variant::class);
}
/** @return HasMany<StockReservation, $this> */
public function stockReservations(): HasMany
{
return $this->hasMany(StockReservation::class);
}
public function availableStock(): int
{
return max(0, $this->real_stock - $this->reserved_stock);

View File

@@ -0,0 +1,61 @@
<?php
namespace App\Domains\Catalog\Models;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'inventory_id',
'cart_item_id',
'purchase_id',
'quantity',
'status',
'expires_at',
'committed_at',
'released_at',
])]
class StockReservation extends Model
{
public const STATUS_ACTIVE = 'active';
public const STATUS_COMMITTED = 'committed';
public const STATUS_RELEASED = 'released';
public const STATUS_EXPIRED = 'expired';
protected function casts(): array
{
return [
'inventory_id' => 'integer',
'cart_item_id' => 'integer',
'purchase_id' => 'integer',
'quantity' => 'integer',
'expires_at' => 'datetime',
'committed_at' => 'datetime',
'released_at' => 'datetime',
];
}
/** @return BelongsTo<Inventory, $this> */
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
/** @return BelongsTo<CartItem, $this> */
public function cartItem(): BelongsTo
{
return $this->belongsTo(CartItem::class);
}
/** @return BelongsTo<Purchase, $this> */
public function purchase(): BelongsTo
{
return $this->belongsTo(Purchase::class);
}
}

View File

@@ -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,

View File

@@ -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,

View File

@@ -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
'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);
}
}

View File

@@ -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'),
);
}
}

View File

@@ -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
'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'),
);
}
}

View File

@@ -12,6 +12,19 @@ use Illuminate\Support\Facades\DB;
class CatalogInventoryService
{
/** @return array<int, int> */
public function requirementsFor(CatalogItem|Variant $selection, int $quantity = 1): array
{
if ($quantity <= 0) {
throw new \InvalidArgumentException('La cantidad debe ser mayor a cero.');
}
return array_map(
fn (array $requirement): int => $requirement['quantity'] * $quantity,
$this->inventoryRequirements($selection),
);
}
public function availableQuantity(CatalogItem|Variant $selection): ?int
{
if ($selection instanceof CatalogItem

View 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);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Cart\Services\ExpireCartReservationsService;
use App\Domains\Purchase\Services\CheckoutService;
use Illuminate\Support\Facades\Log;
use Throwable;
class ExpireStockReservationsService
{
public function __construct(
private readonly CheckoutService $checkout,
private readonly ExpireCartReservationsService $carts,
) {}
/**
* @return array{purchases: int, cart_items: int}
*/
public function expireOverdue(): array
{
$expiredPurchases = null;
$expiredCartItems = null;
try {
$expiredPurchases = $this->checkout->expireOverduePurchases();
$expiredCartItems = $this->carts->expireOverdue();
Log::channel('commands')->info('Stock reservation cleanup completed.', [
'command' => 'reservations:expire',
'expired_purchases' => $expiredPurchases,
'expired_cart_items' => $expiredCartItems,
'total_expired' => $expiredPurchases + $expiredCartItems,
]);
return [
'purchases' => $expiredPurchases,
'cart_items' => $expiredCartItems,
];
} catch (Throwable $exception) {
Log::channel('commands')->error('Stock reservation cleanup failed.', [
'command' => 'reservations:expire',
'expired_purchases' => $expiredPurchases,
'expired_cart_items' => $expiredCartItems,
'exception' => $exception,
]);
throw $exception;
}
}
}

View File

@@ -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()

View File

@@ -0,0 +1,230 @@
<?php
namespace App\Domains\Catalog\Services;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class StockReservationService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
) {}
public function reserve(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
{
DB::transaction(function () use ($cartItem, $selection, $quantity): void {
$this->inventory->reserve($selection, $quantity);
$this->recordIncrease($cartItem, $selection, $quantity);
});
}
public function release(
CartItem $cartItem,
CatalogItem|Variant $selection,
int $quantity,
string $releasedStatus = StockReservation::STATUS_RELEASED,
): void {
DB::transaction(function () use ($cartItem, $selection, $quantity, $releasedStatus): void {
$this->ensure($cartItem, $selection);
$this->inventory->release($selection, $quantity);
$this->recordDecrease($cartItem, $selection, $quantity, $releasedStatus);
});
}
public function commit(CartItem $cartItem, CatalogItem|Variant $selection): void
{
DB::transaction(function () use ($cartItem, $selection): void {
$this->ensure($cartItem, $selection);
$this->inventory->commit($selection, (int) $cartItem->cantidad);
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
foreach ($requirements as $inventoryId => $quantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
}
$reservation->update([
'status' => StockReservation::STATUS_COMMITTED,
'committed_at' => now(),
'expires_at' => null,
]);
}
});
}
public function ensure(CartItem $cartItem, CatalogItem|Variant $selection): void
{
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
foreach ($requirements as $inventoryId => $quantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null) {
StockReservation::query()->create([
'inventory_id' => $inventoryId,
'cart_item_id' => $cartItem->getKey(),
'quantity' => $quantity,
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
continue;
}
if ($reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
$reservation->update([
'quantity' => $quantity,
'status' => StockReservation::STATUS_ACTIVE,
'committed_at' => null,
'released_at' => null,
'expires_at' => $this->expiration(),
]);
}
}
}
public function attachToPurchase(
CartItem $cartItem,
CatalogItem|Variant $selection,
Purchase $purchase,
): void {
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
$this->ensure($cartItem, $selection);
StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->update([
'purchase_id' => $purchase->getKey(),
'expires_at' => $purchase->expires_at,
]);
});
}
public function detachFromPurchase(Purchase $purchase): void
{
StockReservation::query()
->where('purchase_id', $purchase->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->update([
'purchase_id' => null,
'expires_at' => $this->expiration(),
]);
}
public function syncPurchaseExpiration(Purchase $purchase): void
{
StockReservation::query()
->where('purchase_id', $purchase->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->update(['expires_at' => $purchase->expires_at]);
}
public function transfer(CartItem $source, CartItem $target): void
{
DB::transaction(function () use ($source, $target): void {
$sourceReservations = StockReservation::query()
->where('cart_item_id', $source->getKey())
->where('status', StockReservation::STATUS_ACTIVE)
->orderBy('inventory_id')
->lockForUpdate()
->get();
foreach ($sourceReservations as $sourceReservation) {
$targetReservation = $this->lockReservation($target, (int) $sourceReservation->inventory_id);
if ($targetReservation === null) {
$sourceItemQuantity = (int) $source->cantidad;
$targetItemQuantity = (int) $target->fresh()->cantidad;
$perItemQuantity = intdiv((int) $sourceReservation->quantity, $sourceItemQuantity);
$sourceReservation->update([
'cart_item_id' => $target->getKey(),
'purchase_id' => null,
'quantity' => $perItemQuantity * $targetItemQuantity,
'expires_at' => $this->expiration(),
]);
continue;
}
$targetReservation->update([
'quantity' => $targetReservation->quantity + $sourceReservation->quantity,
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
$sourceReservation->delete();
}
});
}
private function recordIncrease(CartItem $cartItem, CatalogItem|Variant $selection, int $quantity): void
{
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null) {
StockReservation::query()->create([
'inventory_id' => $inventoryId,
'cart_item_id' => $cartItem->getKey(),
'quantity' => $requiredQuantity,
'status' => StockReservation::STATUS_ACTIVE,
'expires_at' => $this->expiration(),
]);
continue;
}
$reservation->update([
'quantity' => ($reservation->status === StockReservation::STATUS_ACTIVE ? $reservation->quantity : 0) + $requiredQuantity,
'status' => StockReservation::STATUS_ACTIVE,
'committed_at' => null,
'released_at' => null,
'expires_at' => $this->expiration(),
]);
}
}
private function recordDecrease(
CartItem $cartItem,
CatalogItem|Variant $selection,
int $quantity,
string $releasedStatus,
): void {
foreach ($this->inventory->requirementsFor($selection, $quantity) as $inventoryId => $requiredQuantity) {
$reservation = $this->lockReservation($cartItem, $inventoryId);
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity < $requiredQuantity) {
throw new \InvalidArgumentException('La reserva de stock no alcanza para liberar la cantidad solicitada.');
}
$remaining = $reservation->quantity - $requiredQuantity;
$reservation->update([
'quantity' => $remaining,
'status' => $remaining === 0 ? $releasedStatus : StockReservation::STATUS_ACTIVE,
'released_at' => $remaining === 0 ? now() : null,
'expires_at' => $remaining === 0 ? null : $reservation->expires_at,
]);
}
}
private function lockReservation(CartItem $cartItem, int $inventoryId): ?StockReservation
{
return StockReservation::query()
->where('cart_item_id', $cartItem->getKey())
->where('inventory_id', $inventoryId)
->lockForUpdate()
->first();
}
private function expiration(): Carbon
{
return now()->addMinutes(
max(1, (int) config('catalog.stock_reservation_expiration_minutes', 30)),
);
}
}

View File

@@ -9,6 +9,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
- `CatalogItem` es la raíz del producto y se relaciona con tenant, categoría, marca, inventario, variantes, atributos, adjuntos y grupos destacados.
- `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
- `Inventory` administra stock disponible, reservado y comprado.
- `StockReservation` atribuye cada unidad reservada a un ítem de carrito y, durante checkout, a una compra, con estados `active`, `committed`, `released` y `expired`.
- `Category` soporta jerarquía y categorías globales o propias del tenant.
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
- `BundleComponent` representa los componentes de un paquete.
@@ -17,6 +18,7 @@ Modela y publica la oferta comercial del tenant: productos, variantes, categorí
- `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario.
- `StockReservationService`: mantiene el ledger de reservas sincronizado con `Inventory.reserved_stock`.
- `FeaturedGroupService`: pagina los ítems destacados para la tienda.
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets.

View 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,
]);
}
}

View File

@@ -81,9 +81,7 @@ class TelepagosIntegrationService extends BaseIntegrationService
'password' => $password,
]);
$data = $this->handleResponse($response, 'authentication', [
'username' => $username,
]);
$data = $this->handleResponse($response, 'authentication');
$token = $data['token'] ?? null;
$expiresAtStr = $data['expires_at'] ?? null;
@@ -110,7 +108,12 @@ class TelepagosIntegrationService extends BaseIntegrationService
$response = $this->client()->$method($endpoint, $data);
if ($response->status() === 401) {
Log::info('Telepagos 401 Unauthorized. Refreshing token and retrying...');
Log::channel('telepagos')->info('Telepagos request returned 401; refreshing token and retrying.', [
'method' => strtoupper($method),
'endpoint' => $endpoint,
'client_id' => $this->clientContext?->id,
'integration_code' => $this->integrationCode,
]);
$this->clearToken();
@@ -175,9 +178,11 @@ class TelepagosIntegrationService extends BaseIntegrationService
{
if ($response->failed() || $response->json('status') !== 'ok') {
$errorMessage = $response->json('message') ?? $response->body();
Log::error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
Log::channel('telepagos')->error("Telepagos {$actionDescription} failed: {$errorMessage}", array_merge([
'response_status' => $response->status(),
'response_body' => $response->json() ?? $response->body(),
'response_body' => $this->sanitizeForLog($response->json() ?? $response->body()),
'client_id' => $this->clientContext?->id,
'integration_code' => $this->integrationCode,
], $context));
throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}");
@@ -186,6 +191,30 @@ class TelepagosIntegrationService extends BaseIntegrationService
return $response->json() ?? [];
}
/**
* Remove credentials and tokens before serializing provider responses.
*/
protected function sanitizeForLog(mixed $value): mixed
{
if (! is_array($value)) {
return $value;
}
$sensitiveKeys = ['authorization', 'password', 'token', 'access_token', 'refresh_token'];
foreach ($value as $key => $item) {
if (in_array(strtolower((string) $key), $sensitiveKeys, true)) {
$value[$key] = '[REDACTED]';
continue;
}
$value[$key] = $this->sanitizeForLog($item);
}
return $value;
}
/**
* Clear the cached token.
*/

View File

@@ -24,6 +24,11 @@ class TelepagosWebhookService
*/
public function handleWebhook(Client $client, string $cashinId): void
{
Log::channel('telepagos')->info('Telepagos webhook received.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
]);
$telepagosService = new TelepagosIntegrationService;
$telepagosService->forClient($client);
@@ -34,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];
@@ -43,7 +62,10 @@ class TelepagosWebhookService
$cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null;
if (! $cuit) {
Log::warning("Telepagos webhook: CUIT not found for Transferencia cashin {$cashinId}");
Log::channel('telepagos')->warning('Telepagos webhook: CUIT not found for transfer.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
]);
return;
}
@@ -60,19 +82,31 @@ 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) {
Log::warning("Telepagos webhook: Expected one matching purchase for client {$client->code}, DNI {$dni}, amount {$amount} and cashin {$cashinId}; found {$purchases->count()}");
if ($purchases->count() > 1) {
TelepagosPayment::create($paymentData);
}
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'amount' => $amount,
'matches' => $purchases->count(),
]);
return;
}
} elseif (in_array((int) $operationId, $qrOperationIds, true)) {
if (! $qrOrderId) {
Log::warning("Telepagos webhook: qr_order_id not found for QR cashin {$cashinId}");
Log::channel('telepagos')->warning('Telepagos webhook: qr_order_id not present in provider response.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
]);
return;
}
@@ -80,7 +114,11 @@ class TelepagosWebhookService
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
if (! $telepagosQr) {
Log::warning("Telepagos webhook: QR {$qrOrderId} not found in database for cashin {$cashinId}");
Log::channel('telepagos')->warning('Telepagos webhook: QR not found in database.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'qr_order_id' => $qrOrderId,
]);
return;
}
@@ -88,13 +126,21 @@ class TelepagosWebhookService
$compra = $telepagosQr->compra;
if (! $compra) {
Log::warning("Telepagos webhook: Purchase not found for QR {$qrOrderId}");
Log::channel('telepagos')->warning('Telepagos webhook: Purchase not found for QR.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'qr_order_id' => $qrOrderId,
]);
return;
}
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) {
Log::warning("Telepagos webhook: Purchase {$compra->id} does not belong to client {$client->code}");
Log::channel('telepagos')->warning('Telepagos webhook: Purchase does not belong to client.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'purchase_id' => $compra->id,
]);
return;
}
@@ -102,7 +148,12 @@ class TelepagosWebhookService
if (! in_array($compra->status, [
Purchase::STATUS_PENDING_PAYMENT,
], true)) {
Log::warning("Telepagos webhook: Purchase {$compra->id} is not awaiting payment confirmation");
Log::channel('telepagos')->warning('Telepagos webhook: Purchase is not awaiting payment confirmation.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'purchase_id' => $compra->id,
'purchase_status' => $compra->status,
]);
return;
}
@@ -110,37 +161,45 @@ class TelepagosWebhookService
$totalAmount = $this->normalizeAmount($compra->getTotalAmount());
if ($amount !== $totalAmount) {
Log::warning("Telepagos webhook: Amount mismatch. Cashin amount: {$amount}, Purchase amount: {$totalAmount}");
Log::channel('telepagos')->warning('Telepagos webhook: Amount mismatch.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'purchase_id' => $compra->id,
'cashin_amount' => $amount,
'purchase_amount' => $totalAmount,
]);
return;
}
} else {
Log::warning("Telepagos webhook: Unknown operation_id {$operationId} for cashin {$cashinId}");
Log::channel('telepagos')->warning('Telepagos webhook: Unknown operation_id.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'operation_id' => $operationId,
]);
return;
}
$paymentData = [
'compra_id' => $compra->id,
'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);
$this->checkoutService->confirmPaidPurchase($compra);
});
Log::info("Telepagos webhook: Successfully processed cashin {$cashinId} for purchase {$compra->id}");
Log::channel('telepagos')->info('Telepagos webhook processed successfully.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'purchase_id' => $compra->id,
'transaction_id' => $paymentData['transaction_id'],
]);
} catch (Exception $e) {
Log::error('Telepagos webhook error: '.$e->getMessage());
Log::channel('telepagos')->error('Telepagos webhook processing failed.', [
'client_code' => $client->code,
'cashin_id' => $cashinId,
'error' => $e->getMessage(),
]);
throw $e;
}
}

View File

@@ -24,6 +24,10 @@ Gestiona integraciones externas disponibles y su configuración por cliente. Un
- Consulta y configuración por cliente bajo `/clients/{client}/integrations`.
- `POST /webhooks/telepagos/{client}` para notificaciones del proveedor.
## Logging de Telepagos
Los eventos de autenticación, QR, consultas de cuenta y procesamiento de webhooks se escriben en el canal diario `telepagos`, separado del log general. Los archivos se generan en `storage/logs/telepagos/telepagos-YYYY-MM-DD.log`; el nivel y la retención se configuran con `TELEPAGOS_LOG_LEVEL` y `TELEPAGOS_LOG_DAYS`. Tokens y credenciales se eliminan del contexto antes de registrar respuestas del proveedor.
## Dependencias y reglas
Se integra con `Client`, `Tenant` y con el checkout de `Purchase`. `Notification` utiliza `MailService`. El tenant conserva el contexto operativo y de branding, pero nunca es dueño de credenciales. Las credenciales no se exponen en respuestas ni logs; los webhooks deben validar su contrato antes de alterar una compra.

View File

@@ -8,9 +8,11 @@ use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Requests\PaymentIntentRequest;
use App\Domains\Purchase\Requests\StartCheckoutRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseItemQuantityRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseItemRequest;
use App\Domains\Purchase\Resources\PurchaseResource;
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
@@ -52,12 +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')->loadCount('tickets');
$compra->items->load('imageAttachment');
$responses->load($compra);
return PurchaseResource::make($compra);
}
@@ -75,8 +81,8 @@ class PurchaseController extends Controller
);
}
public function updateItemQuantity(
UpdatePurchaseItemQuantityRequest $request,
public function updateItem(
UpdatePurchaseItemRequest $request,
Tenant $tenant,
Purchase $compra,
PurchaseItem $item,
@@ -85,10 +91,12 @@ class PurchaseController extends Controller
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make(
$checkoutService->updateItemQuantity(
$checkoutService->updateItem(
$compra,
$item,
(int) $request->validated('quantity'),
$request->exists('quantity') ? (int) $request->validated('quantity') : null,
$request->exists('variant_id') ? (int) $request->validated('variant_id') : null,
$request->exists('variant_id'),
),
);
}
@@ -106,11 +114,54 @@ class PurchaseController extends Controller
);
}
public function paymentIntent(PaymentIntentRequest $request, Tenant $tenant, Purchase $compra): JsonResponse
{
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;
$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 (
! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
) {
return false;
}
$purchaseUpdate = [
'payment_method' => $method,
@@ -118,43 +169,26 @@ class PurchaseController extends Controller
'expires_at' => now()->addMinutes(
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
),
'total' => $totalAmount,
'total' => $purchase->calculateCurrentTotalAmount(),
];
if ($method === 'transfer') {
$purchaseUpdate['transfer_payer_dni'] = preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'));
if ($transferPayerDni !== null) {
$purchaseUpdate['transfer_payer_dni'] = $transferPayerDni;
}
$updated = DB::transaction(function () use ($compra, $purchaseUpdate): bool {
/** @var Purchase|null $purchase */
$purchase = Purchase::query()
->whereKey($compra->getKey())
->lockForUpdate()
->first();
if (
$purchase === null
|| ! in_array($purchase->status, [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
], true)
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) {
return false;
}
$purchase->update($purchaseUpdate);
return true;
});
if ($updated === 0) {
if (! $updated) {
throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_available_for_payment'),
]);
}
$compra->refresh();
$totalAmount = (float) $compra->total;
$checkoutService->syncReservationExpiration($compra);
if ($method === 'transfer') {
$telepagosService = new TelepagosIntegrationService;
@@ -163,6 +197,11 @@ class PurchaseController extends Controller
try {
$accountInfo = $telepagosService->getAccountInfo();
Log::channel('telepagos')->info('Telepagos account information retrieved.', [
'tenant_code' => $tenant->codigo,
'purchase_id' => $compra->id,
]);
return response()->json([
'payment_method' => 'transfer',
'transfer_data' => [
@@ -174,9 +213,10 @@ class PurchaseController extends Controller
],
]);
} catch (\Exception $e) {
Log::error('Unable to retrieve TelePagos account information.', [
Log::channel('telepagos')->error('Unable to retrieve TelePagos account information.', [
'tenant_code' => $tenant->codigo,
'purchase_id' => $compra->id,
'exception' => $e,
'error' => $e->getMessage(),
]);
return response()->json([
@@ -191,7 +231,11 @@ class PurchaseController extends Controller
$telepagosService->forTenant($tenant->codigo);
try {
Log::info("Generating QR for purchase ID: {$compra->id}, amount: {$totalAmount}");
Log::channel('telepagos')->info('Generating Telepagos QR.', [
'tenant_code' => $tenant->codigo,
'purchase_id' => $compra->id,
'amount' => $totalAmount,
]);
$qrResponse = $telepagosService->generateQr(
$totalAmount,
'Compra',
@@ -202,10 +246,17 @@ class PurchaseController extends Controller
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
'qr_code' => $qrResponse['qr_code'] ?? '',
]);
} catch (\Exception $e) {
Log::error('Unable to generate TelePagos QR code.', [
Log::channel('telepagos')->info('Telepagos QR generated successfully.', [
'tenant_code' => $tenant->codigo,
'purchase_id' => $compra->id,
'exception' => $e,
'qr_order_id' => $telepagosQr->qr_order_id,
]);
} catch (\Exception $e) {
Log::channel('telepagos')->error('Unable to generate TelePagos QR code.', [
'tenant_code' => $tenant->codigo,
'purchase_id' => $compra->id,
'error' => $e->getMessage(),
]);
return response()->json([

View 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'));
}
}

View File

@@ -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);
}
}

View File

@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Tenant\Models\Tenant;
@@ -116,6 +117,12 @@ class Purchase extends Model
return $this->hasMany(Ticket::class, 'source_purchase_id');
}
/** @return HasMany<StockReservation, $this> */
public function stockReservations(): HasMany
{
return $this->hasMany(StockReservation::class);
}
/**
* @return HasOne<TelepagosQr, $this>
*/
@@ -143,11 +150,16 @@ class Purchase extends Model
public function calculateCurrentTotalAmount(): float
{
if ($this->relationLoaded('items')) {
if ($this->relationLoaded('items') && $this->getRelation('items')->isNotEmpty()) {
return (float) $this->getRelation('items')->sum('total');
}
return (float) $this->items()->sum('total');
$itemsTotal = (float) $this->items()->sum('total');
if ($itemsTotal > 0 || $this->items()->exists()) {
return $itemsTotal;
}
return (float) ($this->cart?->getTotalAmount() ?? $this->total ?? 0);
}
protected function valueChangeTenantCode(): string

View File

@@ -3,6 +3,8 @@
namespace App\Domains\Purchase\Models;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -23,18 +25,11 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
'discount_total',
'tax_total',
'total',
'reservation_status',
])]
class PurchaseItem extends Model
{
use HasFactory;
public const RESERVATION_ACTIVE = 'active';
public const RESERVATION_COMMITTED = 'committed';
public const RESERVATION_RELEASED = 'released';
protected $table = 'compra_items';
protected function casts(): array
@@ -66,4 +61,16 @@ class PurchaseItem extends Model
{
return $this->belongsTo(Attachment::class, 'image_attachment_id');
}
/** @return BelongsTo<CatalogItem, $this> */
public function sourceCatalogItem(): BelongsTo
{
return $this->belongsTo(CatalogItem::class, 'source_catalog_item_id')->withTrashed();
}
/** @return BelongsTo<Variant, $this> */
public function sourceVariant(): BelongsTo
{
return $this->belongsTo(Variant::class, 'source_variant_id')->withTrashed();
}
}

View File

@@ -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',
];
}

View File

@@ -1,23 +0,0 @@
<?php
namespace App\Domains\Purchase\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePurchaseItemQuantityRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'quantity' => ['required', 'integer', 'min:1', 'max:100'],
];
}
}

View 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'],
];
}
}

View File

@@ -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,31 +67,34 @@ 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,
'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice),
'line_total' => $this->formatMoney($lineTotal),
'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id,
'product' => $catalogItem === null ? null : [
'id' => $catalogItem->id,
'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion,
'slug' => $catalogItem->slug,
'imagen' => $imageUrl,
],
'variant' => $variant === null ? null : [
'id' => $variant->id,
'attributes' => $this->resolveAttributes($variant),
],
'source_catalog_item_id' => $this->catalog_item_id,
'source_variant_id' => $this->variant_id,
'item_details' => $selectedItem === null ? null : [
'nombre' => $selectedItem->getName(),
'descripcion' => $selectedItem->getDescription(),
'slug' => $catalogItem?->slug,
'imagen' => $imageUrl,
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
],
'variants' => $this->when(
$includeVariants,
fn () => $catalogItem
->visibleVariants($this->variant_id)
->map(fn (Variant $availableVariant): array => $this->variantData(
$catalogItem,
$availableVariant,
))
->values(),
),
];
}
@@ -142,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),
];
}
}

View File

@@ -2,6 +2,7 @@
namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
@@ -17,26 +18,40 @@ class PurchaseResource extends JsonResource
*/
public function toArray(Request $request): array
{
$items = $this->resource->relationLoaded('items')
$purchaseItems = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items')
: collect();
$cartItems = $this->resource->relationLoaded('cart')
&& $this->resource->getRelation('cart')?->relationLoaded('items')
? $this->resource->getRelation('cart')->getRelation('items')
: 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;
$subtotal = $items->isNotEmpty()
? $items->reduce(
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemSubtotal($item),
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemSubtotal($item),
0.0,
)
: (float) ($this->total ?? 0);
$total = $items->isNotEmpty()
$total = $this->status === Purchase::STATUS_PAID && $this->total !== null
? (float) $this->total
: ($items->isNotEmpty()
? $items->reduce(
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item),
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
0.0,
)
: (float) ($this->total ?? 0);
: (float) ($this->total ?? 0));
return [
'id' => $this->id,
@@ -52,7 +67,7 @@ class PurchaseResource extends JsonResource
'telefono' => $this->telefono,
'nombre_apellido' => $this->nombre_apellido,
'email' => $this->email,
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
'items_source' => $itemsSource,
'items' => PurchaseItemResource::collection($items),
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0),
@@ -61,13 +76,21 @@ class PurchaseResource extends JsonResource
];
}
protected function resolveItemSubtotal(PurchaseItem $item): float
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
{
if ($item instanceof CartItem) {
return (float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
return (float) $item->precio_unitario * $item->cantidad;
}
protected function resolveItemTotal(PurchaseItem $item): float
protected function resolveItemTotal(PurchaseItem|CartItem $item): float
{
if ($item instanceof CartItem) {
return $this->resolveItemSubtotal($item);
}
return (float) ($item->total ?? 0);
}

View File

@@ -5,7 +5,6 @@ namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -79,13 +78,4 @@ class CatalogSelectionResolver
return $variant;
}
public function resolvePurchaseItem(Tenant $tenant, PurchaseItem $item): CatalogItem|Variant
{
return $this->resolve(
$tenant,
(int) $item->source_catalog_item_id,
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
);
}
}

View File

@@ -2,24 +2,28 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class CompleteCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly CatalogSelectionResolver $selections,
private readonly StockReservationService $reservations,
private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
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([
@@ -44,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);
@@ -59,6 +64,7 @@ class CompleteCheckoutService
}
$purchase->update(['expires_at' => null]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadPurchase($purchase);
});
@@ -68,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;
@@ -83,27 +90,53 @@ class CompleteCheckoutService
]);
}
$items = $purchase->items()
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
->lockForUpdate()
->get();
if ($purchase->items()->exists()) {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart?->status === 'converted' && $cart->trashed()) {
return;
}
foreach ($items as $item) {
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item);
try {
$this->inventory->commit($selection, (int) $item->cantidad);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$item->update([
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED,
$cart = $purchase->cart()->lockForUpdate()->first();
if ($cart === null || $cart->status !== 'checkout') {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
if ($cartItems->isEmpty()) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->loadCartItems($cartItems);
$purchase->items()->createMany(
$this->snapshots->fromCartItems($cartItems),
);
foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem();
if ($selection === null) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
try {
$this->reservations->commit($cartItem, $selection);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
}
$this->sourceCart->finalize($purchase);
});
}
@@ -126,6 +159,30 @@ class CompleteCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
/** @param Collection<int, CartItem> $cartItems */
private function loadCartItems(Collection $cartItems): void
{
$cartItems->load([
'catalogItem.inventory',
'catalogItem.attachments',
'variant.inventory',
'variant.attachments',
'variant.catalogItem',
'variant.definitions.itemAttribute.attribute',
'variant.eventDates',
'variant.eventDate',
]);
}
}

View File

@@ -6,6 +6,7 @@ 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;
@@ -18,6 +19,9 @@ class EditCheckoutService
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 */
@@ -25,6 +29,7 @@ class EditCheckoutService
{
return DB::transaction(function () use ($purchase, $customerData): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase);
$purchase->update($customerData);
@@ -33,13 +38,22 @@ class EditCheckoutService
});
}
public function updateItemQuantity(
public function updateItem(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase {
return DB::transaction(function () use (
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
): Purchase {
return DB::transaction(function () use ($purchase, $purchaseItem, $quantity): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
throw ValidationException::withMessages([
@@ -48,16 +62,40 @@ class EditCheckoutService
}
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
$difference = $quantity - (int) $purchaseItem->cantidad;
$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, $quantity, $difference);
$this->adjustReservation($purchase, $purchaseItem, $finalQuantity, $difference);
$purchaseItem->update([
'cantidad' => $quantity,
'total' => (float) $purchaseItem->precio_unitario * $quantity,
'cantidad' => $finalQuantity,
'total' => (float) $purchaseItem->precio_unitario * $finalQuantity,
]);
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $quantity);
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $finalQuantity);
}
}
$purchase->update([
@@ -68,12 +106,95 @@ class EditCheckoutService
});
}
private function changeItemVariant(
Purchase $purchase,
PurchaseItem $sourceItem,
int $variantId,
int $quantity,
): void {
$tenant = $purchase->tenant()->firstOrFail();
$currentSelection = $this->selections->resolvePurchaseItem($tenant, $sourceItem);
$targetSelection = $this->selections->resolve(
$tenant,
(int) $sourceItem->source_catalog_item_id,
$variantId,
'item',
);
if (! $targetSelection instanceof Variant) {
throw ValidationException::withMessages([
'variant_id' => __('api.cart.variant_required'),
]);
}
/** @var PurchaseItem|null $targetItem */
$targetItem = $purchase->items()
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
->where('source_variant_id', $targetSelection->id)
->whereKeyNot($sourceItem->getKey())
->lockForUpdate()
->first();
if ($targetItem !== null && $targetItem->reservation_status !== PurchaseItem::RESERVATION_ACTIVE) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.item_not_editable'),
]);
}
$otherItemQuantity = (int) $purchase->items()
->where('source_catalog_item_id', $sourceItem->source_catalog_item_id)
->whereKeyNot($sourceItem->getKey())
->sum('cantidad');
$this->purchaseLimits->assertCanPurchase(
$targetSelection->catalogItem,
(int) $purchase->user_id,
$otherItemQuantity + $quantity,
$purchase->getKey(),
'variant_id',
);
try {
$this->inventory->release($currentSelection, (int) $sourceItem->cantidad);
$this->inventory->reserve($targetSelection, $quantity);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.insufficient_stock'),
]);
}
$previousVariantId = $sourceItem->source_variant_id;
$finalQuantity = $quantity;
if ($targetItem !== null) {
$finalQuantity += (int) $targetItem->cantidad;
$targetItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
$sourceItem->delete();
} else {
$sourceItem->update($this->snapshots->fromVariant($targetSelection, $finalQuantity));
}
$this->sourceCart->syncItemSelection(
$purchase,
(int) $sourceItem->source_catalog_item_id,
$previousVariantId,
$targetSelection->id,
$finalQuantity,
);
}
public function prepareItemEditing(Purchase $purchase): Purchase
{
return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase);
$this->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,
@@ -88,6 +209,32 @@ class EditCheckoutService
});
}
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,
@@ -170,6 +317,6 @@ class EditCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $this->responses->load($purchase);
}
}

View File

@@ -5,11 +5,39 @@ namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Collection;
class PurchaseItemSnapshotFactory
{
/** @return array<string, mixed> */
public function fromVariant(Variant $variant, int $quantity): array
{
$variant->loadMissing([
'attachments',
'catalogItem.attachments',
'definitions.itemAttribute.attribute.options',
'eventDates',
'eventDate',
]);
$unitPrice = $variant->getPrice();
return [
'source_variant_id' => $variant->id,
'image_attachment_id' => $variant->attachments->first()?->id
?? $variant->catalogItem->attachments->first()?->id,
'nombre' => $variant->catalogItem->nombre,
'descripcion' => $variant->getDescription(),
'slug' => $variant->catalogItem->slug,
'item_nombre' => $variant->getName(),
'variant_attributes' => $this->snapshotAttributes($variant),
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
];
}
/**
* @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>>
@@ -38,7 +66,6 @@ class PurchaseItemSnapshotFactory
'discount_total' => null,
'tax_total' => null,
'total' => $unitPrice * $quantity,
'reservation_status' => PurchaseItem::RESERVATION_ACTIVE,
];
})
->all();

View File

@@ -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;
}
}

View File

@@ -2,33 +2,36 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use 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 CatalogInventoryService $inventory,
private readonly CatalogSelectionResolver $selections,
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
@@ -41,7 +44,21 @@ class ReleaseCheckoutService
->where('expires_at', '<=', now())
->orderBy('id')
->eachById(function (Purchase $purchase) use (&$expiredCount): void {
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++;
@@ -51,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);
@@ -77,34 +98,53 @@ class ReleaseCheckoutService
return $this->loadPurchase($purchase);
}
$items = $purchase->items()
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE)
->lockForUpdate()
->get();
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
foreach ($items as $item) {
if (! $reservationReturnedToCart) {
$this->releaseInventory($purchase, $item);
}
$item->update([
'reservation_status' => PurchaseItem::RESERVATION_RELEASED,
if ($purchase->items()->exists()) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
$this->releaseCartReservations($purchase, $targetStatus);
$purchase->update(['status' => $targetStatus]);
return $this->loadPurchase($purchase);
});
}
private function releaseInventory(Purchase $purchase, PurchaseItem $item): void
{
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item);
private function releaseCartReservations(
Purchase $purchase,
string $targetStatus,
): void {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null) {
return;
}
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$cartItems->load([
'catalogItem.inventory',
'catalogItem.bundleComponents.catalogItem.inventory',
'catalogItem.bundleComponents.variant.inventory',
'variant.inventory',
'variant.catalogItem',
]);
foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem();
if ($selection === null) {
continue;
}
try {
$this->inventory->release($selection, (int) $item->cantidad);
$this->reservations->release(
$cartItem,
$selection,
(int) $cartItem->cantidad,
$targetStatus === Purchase::STATUS_EXPIRED
? StockReservation::STATUS_EXPIRED
: StockReservation::STATUS_RELEASED,
);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
@@ -112,6 +152,12 @@ class ReleaseCheckoutService
}
}
if (! $cart->trashed()) {
$cart->update(['status' => 'converted']);
$cart->delete();
}
}
private function isAlreadyReleased(Purchase $purchase): bool
{
return in_array($purchase->status, [
@@ -129,6 +175,15 @@ class ReleaseCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $purchase->load([
'items.imageAttachment',
'cart.items.catalogItem.inventory',
'cart.items.catalogItem.attachments',
'cart.items.variant.inventory',
'cart.items.variant.attachments',
'cart.items.variant.definitions.itemAttribute.attribute',
'cart.items.variant.eventDates',
'cart.items.variant.eventDate',
]);
}
}

View File

@@ -3,57 +3,10 @@
namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
class SourceCartService
{
public function restore(Purchase $purchase): bool
{
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
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;
}
public function syncItemQuantity(
Purchase $purchase,
PurchaseItem $purchaseItem,
@@ -71,6 +24,71 @@ class SourceCartService
->update(['cantidad' => $quantity]);
}
public function syncItemSelection(
Purchase $purchase,
int $catalogItemId,
?int $previousVariantId,
int $newVariantId,
int $finalQuantity,
): void {
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
/** @var CartItem|null $previousItem */
$previousItem = $sourceCart->items()
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $previousVariantId)
->lockForUpdate()
->first();
/** @var CartItem|null $targetItem */
$targetItem = $sourceCart->items()
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $newVariantId)
->when($previousItem !== null, fn ($query) => $query->whereKeyNot($previousItem->getKey()))
->lockForUpdate()
->first();
if ($targetItem !== null) {
$targetItem->update(['cantidad' => $finalQuantity]);
$previousItem?->delete();
return;
}
if ($previousItem !== null) {
$previousItem->update([
'variant_id' => $newVariantId,
'cantidad' => $finalQuantity,
]);
return;
}
$sourceCart->items()->create([
'catalog_item_id' => $catalogItemId,
'variant_id' => $newVariantId,
'cantidad' => $finalQuantity,
]);
}
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): void
{
$sourceCart = $this->findSourceCart($purchase);
if ($sourceCart === null) {
return;
}
$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
{
$sourceCart = $this->findSourceCart($purchase);
@@ -98,28 +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) {
$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);
}
}
}
}

View File

@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Exceptions\InsufficientStockException;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
@@ -20,10 +21,11 @@ class StartCheckoutService
{
public function __construct(
private readonly CatalogInventoryService $inventory,
private readonly StockReservationService $reservations,
private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly InsufficientStockMessageBuilder $stockMessages,
private readonly PurchaseResponseLoader $responses,
) {}
/** @param array<string, mixed> $purchaseData */
@@ -118,10 +120,16 @@ class StartCheckoutService
->each(function (Collection $catalogLines) use ($userId): void {
/** @var CatalogItem $catalogItem */
$catalogItem = $catalogLines->first()['catalog_item'];
$availableQuantities = $catalogLines
->map(fn (array $line): ?int => $this->inventory->availableQuantity($line['selection']));
$maximumAddableCeiling = $availableQuantities->contains(null)
? null
: (int) $availableQuantities->sum();
$this->purchaseLimits->assertCanPurchase(
$catalogItem,
$userId,
(int) $catalogLines->sum('quantity'),
maximumAddableCeiling: $maximumAddableCeiling,
field: 'direct_items',
);
});
@@ -144,9 +152,24 @@ class StartCheckoutService
throw new InsufficientStockException($unavailableItems);
}
$cart = Cart::query()->create([
'tenant_codigo' => $tenant->codigo,
'user_id' => $userId,
'guest_token' => null,
'status' => 'checkout',
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
]);
$cartItems = collect();
foreach ($resolvedLines as $line) {
$cartItem = $cart->items()->create([
'catalog_item_id' => $line['catalog_item_id'],
'variant_id' => $line['variant_id'],
'cantidad' => $line['quantity'],
]);
try {
$this->inventory->reserve($line['selection'], $line['quantity']);
$this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
} catch (\InvalidArgumentException) {
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
@@ -154,6 +177,10 @@ class StartCheckoutService
$this->unavailableItem($line, $availableQuantity),
]);
}
$cartItem->setRelation('catalogItem', $line['catalog_item']);
$cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
$cartItems->push($cartItem);
}
$purchase = $this->createPurchase(
@@ -163,19 +190,16 @@ class StartCheckoutService
(float) $resolvedLines->sum(
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
),
null,
$cart->getKey(),
);
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem(
$line['selection'],
$line['catalog_item_id'],
$line['variant_id'],
$line['quantity'],
));
$purchase->items()->createMany(
$this->snapshots->fromCartItems($directCartItems),
foreach ($cartItems as $index => $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
$resolvedLines->get($index)['selection'],
$purchase,
);
}
return $this->loadPurchase($purchase);
}
@@ -225,7 +249,7 @@ class StartCheckoutService
$this->loadCartItems($cartItems);
$this->verifyTenantItems($tenant, $cartItems);
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems);
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
$cart->setRelation('items', $cartItems);
$purchase = $this->createPurchase(
@@ -235,7 +259,13 @@ class StartCheckoutService
$cart->getTotalAmount(),
$cart->getKey(),
);
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
foreach ($cartItems as $cartItem) {
$this->reservations->attachToPurchase(
$cartItem,
$cartItem->selectedItem(),
$purchase,
);
}
// The purchase owns the reservation until checkout finishes. The cart is
// retained so it can be restored if the purchase is cancelled or expires.
@@ -288,6 +318,7 @@ class StartCheckoutService
Tenant $tenant,
int $userId,
Collection $cartItems,
int $cartId,
): void {
$quantities = $cartItems
->groupBy('catalog_item_id')
@@ -309,6 +340,8 @@ class StartCheckoutService
$catalogItem,
$userId,
$quantity,
excludedCartId: $cartId,
heldQuantity: $quantity,
field: 'cart_id',
);
}
@@ -336,35 +369,6 @@ class StartCheckoutService
]);
}
private function makeDirectCartItem(
CatalogItem|Variant $selection,
int $catalogItemId,
?int $variantId,
int $quantity,
): CartItem {
$catalogItem = $selection instanceof Variant ? $selection->catalogItem : $selection;
$catalogItem->loadMissing(['inventory', 'attachments']);
if ($selection instanceof Variant) {
$selection->loadMissing([
'inventory',
'attachments',
'catalogItem',
'definitions.itemAttribute.attribute',
]);
}
$item = new CartItem([
'catalog_item_id' => $catalogItemId,
'variant_id' => $variantId,
'cantidad' => $quantity,
]);
$item->setRelation('catalogItem', $catalogItem);
$item->setRelation('variant', $selection instanceof Variant ? $selection : null);
return $item;
}
/** @param Collection<int, CartItem> $cartItems */
private function loadCartItems(Collection $cartItems): void
{
@@ -382,6 +386,6 @@ class StartCheckoutService
private function loadPurchase(Purchase $purchase): Purchase
{
return $purchase->load(['items.imageAttachment']);
return $this->responses->load($purchase);
}
}

View File

@@ -2,6 +2,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;
@@ -23,6 +24,7 @@ class CheckoutService
private readonly EditCheckoutService $editor,
private readonly CompleteCheckoutService $completer,
private readonly ReleaseCheckoutService $releaser,
private readonly StockReservationService $reservations,
) {}
/** @param array<string, mixed> $purchaseData */
@@ -47,12 +49,20 @@ class CheckoutService
return $this->editor->updateCustomer($purchase, $customerData);
}
public function updateItemQuantity(
public function updateItem(
Purchase $purchase,
PurchaseItem $purchaseItem,
int $quantity,
?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase {
return $this->editor->updateItemQuantity($purchase, $purchaseItem, $quantity);
return $this->editor->updateItem(
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
);
}
public function prepareItemEditing(Purchase $purchase): Purchase
@@ -60,6 +70,11 @@ class CheckoutService
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);
@@ -94,4 +109,9 @@ class CheckoutService
{
return $this->releaser->expireOverdue();
}
public function syncReservationExpiration(Purchase $purchase): void
{
$this->reservations->syncPurchaseExpiration($purchase);
}
}

View 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;
}
}
}

View 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']);
});
}
}

View File

@@ -2,11 +2,13 @@
namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class UserPurchaseLimitService
{
@@ -15,6 +17,9 @@ class UserPurchaseLimitService
int $userId,
int $requestedQuantity,
?int $excludedPurchaseId = null,
?int $excludedCartId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
string $field = 'quantity',
): void {
DB::transaction(function () use (
@@ -22,6 +27,9 @@ class UserPurchaseLimitService
$userId,
$requestedQuantity,
$excludedPurchaseId,
$excludedCartId,
$heldQuantity,
$maximumAddableCeiling,
$field,
): void {
/** @var CatalogItem $catalogItem */
@@ -52,11 +60,112 @@ class UserPurchaseLimitService
})
->sum('cantidad');
if ($purchasedQuantity + $requestedQuantity > $limit) {
throw ValidationException::withMessages([
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
]);
$checkoutQuantity = (int) CartItem::query()
->where('catalog_item_id', $catalogItem->getKey())
->whereHas('cart.purchases', function ($query) use ($userId, $excludedPurchaseId): void {
$query
->where('user_id', $userId)
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
])
->whereDoesntHave('items')
->when(
$excludedPurchaseId !== null,
fn ($query) => $query->whereKeyNot($excludedPurchaseId),
);
})
->sum('cantidad');
$reservedCartQuantity = (int) CartItem::query()
->where('catalog_item_id', $catalogItem->getKey())
->whereHas('cart', fn ($query) => $query
->where('user_id', $userId)
->where('status', 'active')
->when(
$excludedCartId !== null,
fn ($query) => $query->whereKeyNot($excludedCartId),
))
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active'))
->sum('cantidad');
if ($purchasedQuantity + $checkoutQuantity + $reservedCartQuantity + $requestedQuantity > $limit) {
$remainingQuota = max(
0,
$limit - $purchasedQuantity - $checkoutQuantity - $reservedCartQuantity,
);
$maximumAddableQuantity = max(0, $remainingQuota - $heldQuantity);
throw new PurchaseLimitExceededException(
$catalogItem,
$maximumAddableCeiling === null
? $maximumAddableQuantity
: min($maximumAddableQuantity, $maximumAddableCeiling),
$field,
);
}
});
}
/**
* @param Collection<int, CatalogItem> $catalogItems
* @return Collection<int, int|null>
*/
public function remainingByCatalogItem(Collection $catalogItems, ?int $userId): Collection
{
$limits = $catalogItems
->unique('id')
->mapWithKeys(fn (CatalogItem $item): array => [$item->getKey() => $item->max_units_per_user]);
if ($userId === null || $limits->filter(fn ($limit) => $limit !== null)->isEmpty()) {
return $limits->map(fn (): ?int => null);
}
$ids = $limits->keys();
$purchased = PurchaseItem::query()
->selectRaw('source_catalog_item_id, SUM(cantidad) AS quantity')
->whereIn('source_catalog_item_id', $ids)
->whereHas('purchase', fn ($query) => $query
->where('user_id', $userId)
->whereIn('status', [
Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT,
Purchase::STATUS_PAID,
]))
->groupBy('source_catalog_item_id')
->pluck('quantity', 'source_catalog_item_id');
$checkout = CartItem::query()
->selectRaw('catalog_item_id, SUM(cantidad) AS quantity')
->whereIn('catalog_item_id', $ids)
->whereHas('cart.purchases', fn ($query) => $query
->where('user_id', $userId)
->whereIn('status', [Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT])
->whereDoesntHave('items'))
->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id');
$reserved = CartItem::query()
->selectRaw('catalog_item_id, SUM(cantidad) AS quantity')
->whereIn('catalog_item_id', $ids)
->whereHas('cart', fn ($query) => $query
->where('user_id', $userId)
->where('status', 'active'))
->whereHas('stockReservations', fn ($query) => $query->where('status', 'active'))
->groupBy('catalog_item_id')
->pluck('quantity', 'catalog_item_id');
return $limits->map(function (?int $limit, int $catalogItemId) use ($purchased, $checkout, $reserved): ?int {
if ($limit === null) {
return null;
}
$used = (int) ($purchased[$catalogItemId] ?? 0)
+ (int) ($checkout[$catalogItemId] ?? 0)
+ (int) ($reserved[$catalogItemId] ?? 0);
return max(0, $limit - $used);
});
}
}

View File

@@ -2,12 +2,12 @@
## Propósito
Implementa el ciclo de compra y checkout: crea una compra desde el carrito, toma una instantánea de sus ítems, reserva inventario, permite ediciones, inicia el pago y confirma, cancela o vence la operación.
Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un carrito, mantiene sus líneas vivas contra catálogo durante el checkout, inicia el pago y materializa el snapshot definitivo al confirmar, o cancela y vence la operación.
## Modelo
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `paid`, `cancelled`, `rejected` y `expired`.
- `PurchaseItem`: snapshot del producto o variante, cantidad, precio y total al comprar.
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
- `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional.
@@ -15,13 +15,17 @@ Implementa el ciclo de compra y checkout: crea una compra desde el carrito, toma
`CheckoutService` es la fachada estable. Delega en:
- `StartCheckoutService`: inicia la compra desde el carrito.
- `EditCheckoutService`: modifica cliente o cantidades antes del cierre.
- `CompleteCheckoutService`: completa, envía a revisión o confirma el pago.
- `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, sin crear todavía `PurchaseItem`.
- `EditCheckoutService`: modifica los datos del comprador antes del cierre.
- `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago.
- `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes.
- `SourceCartService`: sincroniza, restaura o finaliza el carrito fuente.
- `SourceCartService`: 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.
Las cantidades y variantes se editan mediante el dominio Cart. El endpoint autenticado `PATCH /checkout-carts/{cart}/items/{cartItem}` valida que el carrito pertenezca al usuario y a una compra editable. Cuando existe un cambio real, invalida atómicamente el intento de pago anterior, recalcula el total y renueva la reserva; Purchase no expone operaciones sobre líneas antes de la confirmación.
`UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones.
## Endpoints

View File

@@ -8,7 +8,8 @@ Route::prefix('tenants/{tenant:codigo}')->middleware('auth:sanctum')->group(func
Route::post('compras/start-checkout', [PurchaseController::class, 'startCheckout']);
Route::get('compras/{compra}', [PurchaseController::class, 'show']);
Route::post('compras/{compra}/edit-items', [PurchaseController::class, 'prepareItemEditing']);
Route::patch('compras/{compra}/items/{item}', [PurchaseController::class, 'updateItemQuantity']);
Route::patch('compras/{compra}/items/{item}', [PurchaseController::class, 'updateItem']);
Route::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']);

View File

@@ -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, '.', '');

View File

@@ -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;
}
}

View 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();
}
}

View File

@@ -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',
];

View File

@@ -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' => [

View File

@@ -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'],
];

View 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(),
];
}
}

View File

@@ -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(

View File

@@ -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;

5
config/catalog.php Normal file
View File

@@ -0,0 +1,5 @@
<?php
return [
'stock_reservation_expiration_minutes' => (int) env('STOCK_RESERVATION_EXPIRATION_MINUTES', 30),
];

View File

@@ -18,7 +18,7 @@ return [
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
'default' => env('LOG_CHANNEL', 'daily'),
/*
|--------------------------------------------------------------------------
@@ -73,6 +73,22 @@ return [
'replace_placeholders' => true,
],
'telepagos' => [
'driver' => 'daily',
'path' => storage_path('logs/telepagos/telepagos.log'),
'level' => env('TELEPAGOS_LOG_LEVEL', 'info'),
'days' => env('TELEPAGOS_LOG_DAYS', 30),
'replace_placeholders' => true,
],
'commands' => [
'driver' => 'daily',
'path' => storage_path('logs/commands/commands.log'),
'level' => env('COMMANDS_LOG_LEVEL', 'info'),
'days' => env('COMMANDS_LOG_DAYS', 30),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),

View File

@@ -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');
});
}
};

View File

@@ -0,0 +1,59 @@
<?php
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Services\StockReservationService;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('carritos', function (Blueprint $table): void {
$table->string('origin')->default('user')->after('status');
});
Schema::create('stock_reservations', function (Blueprint $table): void {
$table->id();
$table->foreignId('inventory_id')->constrained('inventories')->restrictOnDelete();
$table->foreignId('cart_item_id')->nullable()->constrained('carrito_items')->nullOnDelete();
$table->foreignId('purchase_id')->nullable()->constrained('compras')->cascadeOnDelete();
$table->unsignedInteger('quantity');
$table->string('status')->default('active');
$table->dateTime('expires_at')->nullable();
$table->dateTime('committed_at')->nullable();
$table->dateTime('released_at')->nullable();
$table->timestamps();
$table->unique(['cart_item_id', 'inventory_id']);
$table->index(['purchase_id', 'status']);
$table->index(['status', 'expires_at']);
});
CartItem::query()
->whereHas('cart', fn ($query) => $query->where('status', 'active'))
->with([
'catalogItem.inventory',
'catalogItem.bundleComponents.catalogItem.inventory',
'catalogItem.bundleComponents.variant.inventory',
'variant.inventory',
'variant.catalogItem',
])
->eachById(function (CartItem $cartItem): void {
$selection = $cartItem->selectedItem();
if ($selection !== null) {
app(StockReservationService::class)->ensure($cartItem, $selection);
}
});
}
public function down(): void
{
Schema::dropIfExists('stock_reservations');
Schema::table('carritos', function (Blueprint $table): void {
$table->dropColumn('origin');
});
}
};

View File

@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('compra_items', function (Blueprint $table): void {
$table->dropColumn('reservation_status');
});
}
public function down(): void
{
Schema::table('compra_items', function (Blueprint $table): void {
$table->string('reservation_status')
->default('committed')
->after('total');
});
}
};

View File

@@ -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.
}
};

View File

@@ -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();
});
}
};

View File

@@ -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');
});
}
};

View File

@@ -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');
});
}
};

View File

@@ -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']);
});
}
};

View File

@@ -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');
});
}
};

View File

@@ -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']);
}
};

View File

@@ -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,10 +43,7 @@ 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();
@@ -52,6 +51,9 @@ class DesfilePuraTendenciaSeeder extends Seeder
});
}
$this->invitationPurchaseProvisioner->provision();
}
private function createTenant(Client $client): void
{
$this->tenantService->create([
@@ -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',

View File

@@ -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',

View File

@@ -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,10 +36,11 @@ 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.',
'item_not_editable' => 'The purchase item is no longer editable.',
'insufficient_stock' => 'There is not enough stock available.',
'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.',
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
@@ -56,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.',

View File

@@ -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,10 +36,11 @@ 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.',
'item_not_editable' => 'El producto de la compra ya no se puede modificar.',
'insufficient_stock' => 'No hay suficiente stock disponible.',
'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.',
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
@@ -56,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.',

View File

@@ -8,7 +8,6 @@ declare(strict_types=1);
* Run from the backend root with:
* php postman/generate-shopit-collection.php
*/
$root = dirname(__DIR__);
chdir($root);
@@ -85,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}/compras/{compra}/items/{item}' => ['quantity' => 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}}'],
@@ -137,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') {
@@ -245,10 +244,11 @@ 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',
'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',
'prepareItemEditing' => 'Prepare Item Editing', 'paymentIntent' => 'Create Payment Intent',
'paymentIntent' => 'Create Payment Intent',
'submitForReview' => 'Submit for Review', 'cancel' => 'Cancel', 'complete' => 'Complete',
'downloadPdf' => 'Download PDF', 'downloadModificationsPdf' => 'Download Modifications PDF',
'modifications' => 'List Modifications', 'tickets' => 'List Tickets', 'confirm' => 'Confirm',

View File

@@ -1,6 +1,8 @@
<?php
use App\Domains\Purchase\Services\CheckoutService;
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;
@@ -9,13 +11,74 @@ Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
Artisan::command('purchases:expire', function (): void {
$expiredCount = app(CheckoutService::class)
->expireOverduePurchases();
Artisan::command('reservations:expire', function (): void {
$expired = app(ExpireStockReservationsService::class)->expireOverdue();
$this->info("Expired purchases: {$expiredCount}");
})->purpose('Release stock reservations from expired purchases');
$this->info("Expired purchases: {$expired['purchases']}");
$this->info("Expired cart items: {$expired['cart_items']}");
})->purpose('Release expired stock reservations from purchases and abandoned carts');
Schedule::command('purchases:expire')
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');

View File

@@ -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,
@@ -73,6 +74,87 @@ class CartControllerTest extends TestCase
'id' => $item->inventory_id,
'reserved_stock' => 2,
]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $item->inventory_id,
'quantity' => 2,
'status' => 'active',
]);
}
public function test_it_sets_the_configured_expiration_when_creating_a_stock_reservation(): void
{
config()->set('catalog.stock_reservation_expiration_minutes', 45);
$now = now()->startOfSecond();
$this->travelTo($now);
$tenant = $this->createTenant('acme');
$item = $this->createDirectItem($tenant, 10, '49.90');
$this->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $item->id,
'cantidad' => 2,
])->assertOk();
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $item->inventory_id,
'quantity' => 2,
'status' => 'active',
'expires_at' => $now->copy()->addMinutes(45)->toDateTimeString(),
]);
$this->travelBack();
}
public function test_it_expires_abandoned_cart_reservations_and_removes_empty_carts(): void
{
config()->set('catalog.stock_reservation_expiration_minutes', 30);
$tenant = $this->createTenant('acme');
$item = $this->createDirectItem($tenant, 10, '49.90');
$response = $this->postJson('/api/tenants/acme/cart/items', [
'catalog_item_id' => $item->id,
'cantidad' => 2,
])->assertOk();
$cartId = $response->json('data.id');
$cartItemId = $response->json('data.items.0.id');
$this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart items: 0')
->assertSuccessful();
$this->travel(31)->minutes();
$this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart items: 1')
->assertSuccessful();
$this->assertDatabaseHas('inventories', [
'id' => $item->inventory_id,
'real_stock' => 10,
'reserved_stock' => 0,
]);
$this->assertDatabaseMissing('carrito_items', ['id' => $cartItemId]);
$this->assertSoftDeleted('carritos', [
'id' => $cartId,
'status' => 'expired',
]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $item->inventory_id,
'cart_item_id' => null,
'purchase_id' => null,
'quantity' => 0,
'status' => 'expired',
'expires_at' => null,
]);
$this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart items: 0')
->assertSuccessful();
$this->travelBack();
}
public function test_it_filters_item_images_when_the_tenant_disables_them(): void
@@ -121,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');
@@ -129,6 +212,12 @@ class CartControllerTest extends TestCase
'id' => $variant->inventory_id,
'reserved_stock' => 5,
]);
$this->assertDatabaseHas('stock_reservations', [
'cart_item_id' => $response->json('data.items.0.id'),
'inventory_id' => $variant->inventory_id,
'quantity' => 5,
'status' => 'active',
]);
}
public function test_authenticated_cart_respects_previous_purchases_and_repeated_additions(): void
@@ -153,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,
@@ -283,6 +380,12 @@ class CartControllerTest extends TestCase
'id' => $variant->inventory_id,
'reserved_stock' => 0,
]);
$this->assertDatabaseHas('stock_reservations', [
'cart_item_id' => null,
'inventory_id' => $variant->inventory_id,
'quantity' => 0,
'status' => 'released',
]);
}
public function test_it_changes_an_item_variant_and_moves_the_stock_reservation(): void
@@ -383,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');
@@ -506,7 +686,6 @@ class CartControllerTest extends TestCase
'cantidad' => $quantity,
'precio_unitario' => $item->precio,
'total' => (float) $item->precio * $quantity,
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED,
]);
}

View File

@@ -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)

View File

@@ -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');

View File

@@ -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

View File

@@ -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',

View File

@@ -285,15 +285,21 @@ class IntegrationServiceTest extends TestCase
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
'status' => 'error',
'message' => 'Invalid credentials',
'token' => 'must-not-be-logged',
], 401),
]);
Log::shouldReceive('channel')->once()->with('telepagos')->andReturnSelf();
Log::shouldReceive('error')
->once()
->with('Telepagos authentication failed: Invalid credentials', \Mockery::on(function ($context) {
return $context['username'] === 'tele_user'
return ! array_key_exists('username', $context)
&& $context['response_status'] === 401
&& $context['response_body'] === ['status' => 'error', 'message' => 'Invalid credentials'];
&& $context['response_body'] === [
'status' => 'error',
'message' => 'Invalid credentials',
'token' => '[REDACTED]',
];
}));
$service = new TelepagosIntegrationService('telepagos');
@@ -442,6 +448,7 @@ class IntegrationServiceTest extends TestCase
], 422),
]);
Log::shouldReceive('channel')->once()->with('telepagos')->andReturnSelf();
Log::shouldReceive('error')
->once()
->with('Telepagos QR generation failed: Importe inválido', \Mockery::on(function ($context) {
@@ -555,6 +562,7 @@ class IntegrationServiceTest extends TestCase
], 404),
]);
Log::shouldReceive('channel')->once()->with('telepagos')->andReturnSelf();
Log::shouldReceive('error')
->once()
->with('Telepagos get cash-in details failed: Cashin no encontrado', \Mockery::on(function ($context) {

View File

@@ -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;
@@ -193,12 +194,14 @@ class TelepagosWebhookTest extends TestCase
'sold_units' => 1,
]);
$this->assertDatabaseHas('compra_items', [
$this->assertDatabaseMissing('compra_items', [
'compra_id' => $newerPurchase->id,
'source_catalog_item_id' => $variant->catalog_item_id,
'source_variant_id' => $variant->id,
'cantidad' => 2,
'reservation_status' => 'active',
]);
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $newerPurchase->id,
'inventory_id' => $variant->inventory_id,
'quantity' => 2,
'status' => 'active',
]);
$this->assertSoftDeleted('carritos', [
@@ -259,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');

View File

@@ -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',
]);
}
}

View File

@@ -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',
]);
}
}

View File

@@ -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',
]);
}
}

View File

@@ -71,6 +71,7 @@ class PurchaseCatalogItemTest extends TestCase
$this->assertFalse(Schema::hasColumn('compra_items', 'variant_id'));
$this->assertFalse(Schema::hasColumn('compra_items', 'buyable_type'));
$this->assertFalse(Schema::hasColumn('compra_items', 'buyable_id'));
$this->assertFalse(Schema::hasColumn('compra_items', 'reservation_status'));
$this->assertDatabaseHas('compra_items', [
'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->id,

View File

@@ -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'),
]);
}
}

View File

@@ -30,7 +30,7 @@ class StorePurchaseTest extends TestCase
Queue::fake();
}
public function test_it_creates_an_independent_purchase_snapshot_from_cart(): void
public function test_it_starts_checkout_from_cart_without_materializing_purchase_items(): void
{
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$tenant->update([
@@ -90,7 +90,7 @@ class StorePurchaseTest extends TestCase
$response->assertJsonPath('data.email', null);
$response->assertJsonPath('data.tenant_codigo', 'sonder');
$response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
$response->assertJsonPath('data.items_source', 'purchase');
$response->assertJsonPath('data.items_source', 'cart');
$response->assertJsonCount(1, 'data.items');
$response->assertJsonPath('data.subtotal', '100.00');
$response->assertJsonPath('data.total', '100.00');
@@ -109,12 +109,12 @@ class StorePurchaseTest extends TestCase
'status' => Purchase::STATUS_CREATED,
'total' => 100,
]);
$this->assertDatabaseHas('compra_items', [
'compra_id' => $purchaseId,
'source_catalog_item_id' => $catalogItem->id,
'source_variant_id' => $variant->id,
'cantidad' => 2,
'reservation_status' => 'active',
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchaseId]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $inventory->id,
'purchase_id' => $purchaseId,
'quantity' => 2,
'status' => 'active',
]);
$this->assertDatabaseHas('carritos', [
'id' => $cartId,
@@ -133,9 +133,22 @@ class StorePurchaseTest extends TestCase
'real_stock' => 10,
'reserved_stock' => 2,
]);
$catalogItem->update([
'nombre' => 'Updated Product',
'precio' => '75.00',
]);
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/sonder/compras/{$purchaseId}")
->assertOk()
->assertJsonPath('data.items_source', 'cart')
->assertJsonPath('data.items.0.item_details.nombre', 'Updated Product')
->assertJsonPath('data.items.0.unit_price', '75.00')
->assertJsonPath('data.total', '150.00');
}
public function test_it_creates_a_direct_purchase_without_creating_or_changing_a_cart(): void
public function test_it_creates_a_direct_purchase_with_a_technical_checkout_cart(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
@@ -152,18 +165,23 @@ class StorePurchaseTest extends TestCase
],
])
->assertCreated()
->assertJsonPath('data.cart_id', null)
->assertJsonPath('data.items_source', 'purchase')
->assertJsonPath('data.items_source', 'cart')
->assertJsonPath('data.items.0.quantity', 3)
->assertJsonPath('data.total', '150.00');
$this->assertDatabaseCount('carritos', 0);
$this->assertDatabaseHas('compra_items', [
$this->assertDatabaseHas('carritos', [
'id' => $response->json('data.cart_id'),
'status' => 'checkout',
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
]);
$this->assertDatabaseMissing('compra_items', [
'compra_id' => $response->json('data.id'),
'source_catalog_item_id' => $variant->catalog_item_id,
'source_variant_id' => $variant->id,
'cantidad' => 3,
'reservation_status' => 'active',
]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $variant->inventory_id,
'purchase_id' => $response->json('data.id'),
'quantity' => 3,
'status' => 'active',
]);
$this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id,
@@ -176,9 +194,9 @@ class StorePurchaseTest extends TestCase
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
$this->assertDatabaseHas('compra_items', [
'compra_id' => $response->json('data.id'),
'reservation_status' => 'released',
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $response->json('data.id'),
'status' => 'released',
]);
$this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id,
@@ -215,7 +233,7 @@ class StorePurchaseTest extends TestCase
],
])
->assertCreated()
->assertJsonPath('data.cart_id', null)
->assertJsonPath('data.items_source', 'cart')
->assertJsonCount(2, 'data.items')
->assertJsonPath('data.items.0.source_variant_id', $firstVariant->id)
->assertJsonPath('data.items.1.source_variant_id', $secondVariant->id)
@@ -223,18 +241,22 @@ class StorePurchaseTest extends TestCase
$purchaseId = $response->json('data.id');
$this->assertDatabaseCount('carritos', 0);
$this->assertDatabaseHas('compra_items', [
'compra_id' => $purchaseId,
'source_variant_id' => $firstVariant->id,
'cantidad' => 1,
'reservation_status' => 'active',
$this->assertDatabaseHas('carritos', [
'id' => $response->json('data.cart_id'),
'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
]);
$this->assertDatabaseHas('compra_items', [
'compra_id' => $purchaseId,
'source_variant_id' => $secondVariant->id,
'cantidad' => 1,
'reservation_status' => 'active',
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchaseId]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $firstVariant->inventory_id,
'purchase_id' => $purchaseId,
'quantity' => 1,
'status' => 'active',
]);
$this->assertDatabaseHas('stock_reservations', [
'inventory_id' => $secondVariant->inventory_id,
'purchase_id' => $purchaseId,
'quantity' => 1,
'status' => 'active',
]);
$this->assertDatabaseHas('inventories', [
'id' => $firstVariant->inventory_id,
@@ -318,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', [
@@ -386,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();
@@ -404,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,
@@ -418,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();
@@ -454,15 +484,19 @@ 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,
]);
}
public function test_it_creates_purchase_items_before_checkout_and_updates_customer_data(): void
public function test_it_keeps_cart_items_during_checkout_and_updates_customer_data(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
@@ -479,7 +513,7 @@ class StorePurchaseTest extends TestCase
],
])
->assertCreated()
->assertJsonPath('data.items_source', 'purchase')
->assertJsonPath('data.items_source', 'cart')
->assertJsonCount(1, 'data.items')
->assertJsonPath('data.items.0.quantity', 2)
->assertJsonPath('data.dni', null)
@@ -537,23 +571,22 @@ class StorePurchaseTest extends TestCase
]);
}
public function test_it_updates_a_created_purchase_item_quantity_and_its_stock_reservation(): void
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);
$itemId = $purchase->items->firstOrFail()->id;
$itemId = $purchase->cart->items->firstOrFail()->id;
$this->actingAs($user, 'sanctum')
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
'quantity' => 4,
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
'cantidad' => 4,
])
->assertOk()
->assertJsonPath('data.items.0.quantity', 4)
->assertJsonPath('data.items.0.line_total', '200.00')
->assertJsonPath('data.subtotal', '200.00')
->assertJsonPath('data.total', '200.00');
->assertJsonPath('data.items.0.cantidad', 4)
->assertJsonPath('data.subtotal', '200.00');
$this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id,
@@ -567,12 +600,17 @@ class StorePurchaseTest extends TestCase
]);
$this->actingAs($user, 'sanctum')
->patchJson("/api/tenants/sonder/compras/{$purchase->id}/items/{$itemId}", [
'quantity' => 1,
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
'cantidad' => 1,
])
->assertOk()
->assertJsonPath('data.items.0.quantity', 1)
->assertJsonPath('data.total', '50.00');
->assertJsonPath('data.items.0.cantidad', 1)
->assertJsonPath('data.subtotal', '50.00');
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'total' => '50.00',
]);
$this->assertDatabaseHas('inventories', [
'id' => $variant->inventory_id,
@@ -580,23 +618,251 @@ class StorePurchaseTest extends TestCase
]);
}
public function test_it_rejects_a_quantity_update_above_the_user_purchase_limit(): void
public function test_checkout_cart_editing_uses_checkout_policy_independently_from_cart_policy(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$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');
$variant->catalogItem->update(['max_units_per_user' => 3]);
$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}", [
'quantity' => 4,
'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('quantity');
->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
{
$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]);
$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,
]);
@@ -606,9 +872,10 @@ class StorePurchaseTest extends TestCase
]);
}
public function test_it_reopens_a_pending_purchase_before_editing_items(): void
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);
@@ -620,17 +887,20 @@ class StorePurchaseTest extends TestCase
'qr_order_id' => 'stale-order',
'qr_code' => 'stale-qr',
]);
$itemId = $purchase->cart->items->firstOrFail()->id;
$this->actingAs($user, 'sanctum')
->postJson("/api/tenants/sonder/compras/{$purchase->id}/edit-items")
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
'cantidad' => 3,
])
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CREATED)
->assertJsonPath('data.payment_method', null);
->assertJsonPath('data.items.0.cantidad', 3);
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'status' => Purchase::STATUS_CREATED,
'payment_method' => null,
'total' => '150.00',
]);
$this->assertDatabaseMissing('telepagos_qr', [
'compra_id' => $purchase->id,
@@ -638,6 +908,39 @@ class StorePurchaseTest extends TestCase
]);
}
public function test_a_no_op_checkout_cart_update_keeps_the_pending_payment_intact(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create();
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
$purchase->update([
'status' => Purchase::STATUS_PENDING_PAYMENT,
'payment_method' => 'qr',
]);
$purchase->telepagosQr()->create([
'qr_order_id' => 'current-order',
'qr_code' => 'current-qr',
]);
$itemId = $purchase->cart->items->firstOrFail()->id;
$this->actingAs($user, 'sanctum')
->patchJson("/api/tenants/sonder/checkout-carts/{$purchase->cart_id}/items/{$itemId}", [
'cantidad' => 2,
])
->assertOk();
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'payment_method' => 'qr',
]);
$this->assertDatabaseHas('telepagos_qr', [
'compra_id' => $purchase->id,
'qr_order_id' => 'current-order',
]);
}
public function test_start_checkout_rejects_customer_data(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
@@ -774,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();
@@ -789,37 +1092,77 @@ class StorePurchaseTest extends TestCase
$this->travel(31)->minutes();
$this->artisan('purchases:expire')
$this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 1')
->expectsOutput('Expired cart items: 0')
->assertSuccessful();
$this->assertDatabaseHas('compras', [
'id' => $purchase->id,
'status' => Purchase::STATUS_EXPIRED,
]);
$this->assertDatabaseHas('compra_items', [
'compra_id' => $purchase->id,
'reservation_status' => 'released',
$this->assertDatabaseMissing('compra_items', ['compra_id' => $purchase->id]);
$this->assertDatabaseHas('stock_reservations', [
'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('purchases:expire')
$this->artisan('reservations:expire')
->expectsOutput('Expired purchases: 0')
->expectsOutput('Expired cart items: 0')
->assertSuccessful();
}
public function test_purchase_detail_uses_purchase_items_for_created_purchase(): void
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');
$user = User::factory()->create([
@@ -832,7 +1175,7 @@ class StorePurchaseTest extends TestCase
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_CREATED)
->assertJsonPath('data.items_source', 'purchase')
->assertJsonPath('data.items_source', 'cart')
->assertJsonCount(1, 'data.items')
->assertJsonPath('data.items.0.quantity', 2)
->assertJsonPath('data.items.0.unit_price', '50.00')
@@ -863,7 +1206,7 @@ class StorePurchaseTest extends TestCase
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$purchase->items()->firstOrFail()->update(['image_attachment_id' => $image->id]);
$variant->catalogItem->attachments()->attach($image->id, ['orden' => 0]);
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
@@ -871,7 +1214,7 @@ class StorePurchaseTest extends TestCase
->assertJsonPath('data.items.0.item_details.imagen', null);
}
public function test_purchase_detail_uses_purchase_items_for_pending_payment_purchase(): void
public function test_purchase_detail_uses_cart_items_for_pending_payment_purchase(): void
{
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
$user = User::factory()->create([
@@ -890,7 +1233,7 @@ class StorePurchaseTest extends TestCase
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
->assertOk()
->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
->assertJsonPath('data.items_source', 'purchase')
->assertJsonPath('data.items_source', 'cart')
->assertJsonCount(1, 'data.items')
->assertJsonPath('data.items.0.quantity', 2)
->assertJsonPath('data.items.0.unit_price', '50.00')
@@ -901,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');
@@ -925,6 +1304,12 @@ class StorePurchaseTest extends TestCase
'reserved_stock' => 0,
'sold_units' => 2,
]);
$this->assertDatabaseHas('stock_reservations', [
'purchase_id' => $purchase->id,
'inventory_id' => $variant->inventory_id,
'quantity' => 2,
'status' => 'committed',
]);
$this->assertSoftDeleted('carritos', [
'id' => $purchase->cart_id,
@@ -956,7 +1341,9 @@ class StorePurchaseTest extends TestCase
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
$purchase->update(['cart_id' => null]);
$purchase->update(['payment_method' => 'transfer']);
app(CheckoutService::class)->confirmPurchase($purchase);
$purchase->refresh()->update(['cart_id' => null]);
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/sonder/compras/{$purchase->id}")

View File

@@ -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

View File

@@ -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 */

View File

@@ -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(

View File

@@ -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,
]);
}

View File

@@ -0,0 +1,78 @@
<?php
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
{
public function test_it_expires_purchases_before_abandoned_cart_items(): void
{
$checkout = \Mockery::mock(CheckoutService::class);
$checkout->shouldReceive('expireOverduePurchases')
->once()
->ordered()
->andReturn(2);
$carts = \Mockery::mock(ExpireCartReservationsService::class);
$carts->shouldReceive('expireOverdue')
->once()
->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([
'purchases' => 2,
'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();
}
}

Some files were not shown because too many files have changed in this diff Show More