Compare commits

...

52 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
16bc657a31 refactor(catalog): add ticket_label to item attributes and update related logic 2026-08-19 11:23:41 -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
109 changed files with 4923 additions and 580 deletions

View File

@@ -8,6 +8,7 @@ PURCHASE_CHECKOUT_EXPIRATION_MINUTES=30
PURCHASE_QR_EXPIRATION_MINUTES=15 PURCHASE_QR_EXPIRATION_MINUTES=15
PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30 PURCHASE_TELEPAGOS_EXPIRATION_MINUTES=30
PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440 PURCHASE_TRANSFER_EXPIRATION_MINUTES=1440
STOCK_RESERVATION_EXPIRATION_MINUTES=30
FRONTEND_URLS=http://localhost:4200 FRONTEND_URLS=http://localhost:4200
APP_LOCALE=es APP_LOCALE=es
@@ -31,10 +32,15 @@ AUTH_LOGIN_LOCK_MINUTES=15
AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10 AUTH_LOGIN_RATE_LIMIT_PER_MINUTE=10
AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30 AUTH_LOGIN_IP_RATE_LIMIT_PER_MINUTE=30
LOG_CHANNEL=stack LOG_CHANNEL=daily
LOG_STACK=single LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug 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_CONNECTION=mysql
DB_HOST=127.0.0.1 DB_HOST=127.0.0.1

View File

@@ -2,7 +2,7 @@
"info": { "info": {
"_postman_id": "76fd6fd2-53b9-4d92-8e02-1ddcc6207fa2", "_postman_id": "76fd6fd2-53b9-4d92-8e02-1ddcc6207fa2",
"name": "ShopIt API — Complete", "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" "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
}, },
"item": [ "item": [
@@ -572,6 +572,60 @@
} }
}, },
"response": [] "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": [] "response": []
}, },
{ {
"name": "Update Item Quantity Purchase", "name": "Update Item Purchase",
"request": { "request": {
"method": "PATCH", "method": "PATCH",
"header": [ "header": [
@@ -1170,7 +1224,7 @@
"type": "text" "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": { "url": {
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/items/{{purchase_item_id}}", "raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/items/{{purchase_item_id}}",
"host": [ "host": [
@@ -1188,7 +1242,7 @@
}, },
"body": { "body": {
"mode": "raw", "mode": "raw",
"raw": "{\n \"quantity\": 2\n}", "raw": "{\n \"quantity\": 2,\n \"variant_id\": {{variant_id}}\n}",
"options": { "options": {
"raw": { "raw": {
"language": "json" "language": "json"
@@ -2160,7 +2214,7 @@
}, },
"body": { "body": {
"mode": "raw", "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": { "options": {
"raw": { "raw": {
"language": "json" "language": "json"
@@ -2226,7 +2280,7 @@
}, },
"body": { "body": {
"mode": "raw", "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": { "options": {
"raw": { "raw": {
"language": "json" "language": "json"
@@ -2266,7 +2320,7 @@
}, },
"body": { "body": {
"mode": "raw", "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": { "options": {
"raw": { "raw": {
"language": "json" "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; namespace App\Domains\Cart\Controllers;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Cart\Requests\AddCartItemRequest; use App\Domains\Cart\Requests\AddCartItemRequest;
use App\Domains\Cart\Requests\UpdateCartItemQuantityRequest; 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 public function removeItem(Request $request, Tenant $tenant, CartItem $cartItem): CartResource
{ {
return CartResource::make( return CartResource::make(
@@ -86,4 +117,23 @@ class CartController extends Controller
'message' => __('api.cart.item_removed'), '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\Inventory;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService; 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\Purchase\Services\UserPurchaseLimitService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -24,6 +26,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
'user_id', 'user_id',
'guest_token', 'guest_token',
'status', 'status',
'origin',
])] ])]
class Cart extends Model class Cart extends Model
{ {
@@ -32,6 +35,10 @@ class Cart extends Model
protected $table = 'carritos'; protected $table = 'carritos';
public const ORIGIN_USER = 'user';
public const ORIGIN_DIRECT_CHECKOUT = 'direct_checkout';
protected function casts(): array protected function casts(): array
{ {
return [ return [
@@ -63,6 +70,12 @@ class Cart extends Model
return $this->hasMany(CartItem::class, 'cart_id'); 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 public function getTotalAmount(): float
{ {
$items = $this->relationLoaded('items') $items = $this->relationLoaded('items')
@@ -90,9 +103,14 @@ class Cart extends Model
$cartQuantity = (int) $this->items() $cartQuantity = (int) $this->items()
->where('catalog_item_id', $catalogItemId) ->where('catalog_item_id', $catalogItemId)
->sum('cantidad'); ->sum('cantidad');
$this->assertUserPurchaseLimit($selectedItem, $cartQuantity + $quantity);
$inventoryService = app(CatalogInventoryService::class); $inventoryService = app(CatalogInventoryService::class);
$availableQuantity = $inventoryService->availableQuantity($selectedItem); $availableQuantity = $inventoryService->availableQuantity($selectedItem);
$this->assertUserPurchaseLimit(
$selectedItem,
$cartQuantity + $quantity,
heldQuantity: $cartQuantity,
maximumAddableCeiling: $availableQuantity,
);
if ($availableQuantity !== null && $availableQuantity < $quantity) { if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -114,11 +132,12 @@ class Cart extends Model
'cantidad' => $quantity, 'cantidad' => $quantity,
]); ]);
} else { } else {
app(StockReservationService::class)->ensure($item, $selectedItem);
$item->cantidad += $quantity; $item->cantidad += $quantity;
$item->save(); $item->save();
} }
$inventoryService->reserve($selectedItem, $quantity); app(StockReservationService::class)->reserve($item, $selectedItem, $quantity);
return $item->fresh(); return $item->fresh();
}); });
@@ -129,6 +148,7 @@ class Cart extends Model
int $quantity, int $quantity,
?int $variantId = null, ?int $variantId = null,
bool $updateVariant = false, bool $updateVariant = false,
?int $excludedPurchaseId = null,
): CartItem { ): CartItem {
if ($quantity <= 0) { if ($quantity <= 0) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -141,6 +161,7 @@ class Cart extends Model
$quantity, $quantity,
$variantId, $variantId,
$updateVariant, $updateVariant,
$excludedPurchaseId,
): CartItem { ): CartItem {
/** @var CartItem $item */ /** @var CartItem $item */
$item = $this->items() $item = $this->items()
@@ -165,12 +186,16 @@ class Cart extends Model
->where('catalog_item_id', $item->catalog_item_id) ->where('catalog_item_id', $item->catalog_item_id)
->whereKeyNot($item->getKey()) ->whereKeyNot($item->getKey())
->sum('cantidad'); ->sum('cantidad');
$nextAvailableQuantity = $inventoryService->availableQuantity($nextSelection);
$this->assertUserPurchaseLimit( $this->assertUserPurchaseLimit(
$nextSelection, $nextSelection,
$otherVariantsQuantity + $quantity, $otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$nextAvailableQuantity,
); );
$inventoryService->release($currentSelection, $item->cantidad); app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
$availableQuantity = $inventoryService->availableQuantity($nextSelection); $availableQuantity = $inventoryService->availableQuantity($nextSelection);
if ($availableQuantity !== null && $availableQuantity < $quantity) { if ($availableQuantity !== null && $availableQuantity < $quantity) {
@@ -186,11 +211,11 @@ class Cart extends Model
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
$inventoryService->reserve($nextSelection, $quantity);
if ($targetItem !== null) { if ($targetItem !== null) {
app(StockReservationService::class)->ensure($targetItem, $nextSelection);
$targetItem->cantidad += $quantity; $targetItem->cantidad += $quantity;
$targetItem->save(); $targetItem->save();
app(StockReservationService::class)->reserve($targetItem, $nextSelection, $quantity);
$item->delete(); $item->delete();
return $targetItem->fresh(); return $targetItem->fresh();
@@ -199,11 +224,13 @@ class Cart extends Model
$item->variant_id = $variantId; $item->variant_id = $variantId;
$item->cantidad = $quantity; $item->cantidad = $quantity;
$item->save(); $item->save();
app(StockReservationService::class)->reserve($item, $nextSelection, $quantity);
return $item->fresh(); return $item->fresh();
} }
$delta = $quantity - $item->cantidad; $delta = $quantity - $item->cantidad;
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0) { if ($delta > 0) {
$otherVariantsQuantity = (int) $this->items() $otherVariantsQuantity = (int) $this->items()
@@ -213,11 +240,12 @@ class Cart extends Model
$this->assertUserPurchaseLimit( $this->assertUserPurchaseLimit(
$currentSelection, $currentSelection,
$otherVariantsQuantity + $quantity, $otherVariantsQuantity + $quantity,
$excludedPurchaseId,
$otherVariantsQuantity + $item->cantidad,
$availableQuantity,
); );
} }
$availableQuantity = $inventoryService->availableQuantity($currentSelection);
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) { if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad; $maxAvailable = $availableQuantity + $item->cantidad;
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -225,17 +253,17 @@ class Cart extends Model
]); ]);
} }
$item->cantidad = $quantity;
$item->save();
if ($delta > 0) { if ($delta > 0) {
$inventoryService->reserve($currentSelection, $delta); app(StockReservationService::class)->reserve($item, $currentSelection, $delta);
} }
if ($delta < 0) { if ($delta < 0) {
$inventoryService->release($currentSelection, abs($delta)); app(StockReservationService::class)->release($item, $currentSelection, abs($delta));
} }
$item->cantidad = $quantity;
$item->save();
return $item->fresh(); return $item->fresh();
}); });
} }
@@ -254,7 +282,8 @@ class Cart extends Model
$item->variant_id, $item->variant_id,
true, true,
); );
app(CatalogInventoryService::class)->release( app(StockReservationService::class)->release(
$item,
$selectedItem, $selectedItem,
$item->cantidad, $item->cantidad,
); );
@@ -334,6 +363,9 @@ class Cart extends Model
private function assertUserPurchaseLimit( private function assertUserPurchaseLimit(
CatalogItem|Variant $selectedItem, CatalogItem|Variant $selectedItem,
int $cartQuantity, int $cartQuantity,
?int $excludedPurchaseId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
): void { ): void {
if ($this->user_id === null) { if ($this->user_id === null) {
return; return;
@@ -347,6 +379,10 @@ class Cart extends Model
$catalogItem, $catalogItem,
$this->user_id, $this->user_id,
$cartQuantity, $cartQuantity,
$excludedPurchaseId,
$this->getKey(),
$heldQuantity,
$maximumAddableCeiling,
field: 'cantidad', field: 'cantidad',
); );
} }

View File

@@ -3,11 +3,13 @@
namespace App\Domains\Cart\Models; namespace App\Domains\Cart\Models;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([ #[Fillable([
'cart_id', 'cart_id',
@@ -55,4 +57,10 @@ class CartItem extends Model
{ {
return $this->variant ?? $this->catalogItem; 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; namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy; use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -21,7 +23,13 @@ class CartItemResource extends JsonResource
$selectedItem = $this->selectedItem(); $selectedItem = $this->selectedItem();
$imageUrl = null; $imageUrl = null;
$tenant = $request->route('tenant'); $tenant = $request->route('tenant');
$checkoutCart = $request->route('cart');
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images; $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')) { if ($displayImage && $selectedItem?->relationLoaded('attachments')) {
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440); $imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
@@ -39,14 +47,27 @@ class CartItemResource extends JsonResource
'variant_id' => $this->variant_id, 'variant_id' => $this->variant_id,
'nombre' => $selectedItem?->getName(), 'nombre' => $selectedItem?->getName(),
'imagen' => $imageUrl, 'imagen' => $imageUrl,
'variant' => $this->variant === null ? null : [ 'variant' => $this->variant === null ? null : $this->variantData($this->variant),
'id' => $this->variant->id, 'variants' => $this->when(
'precio' => $this->formatMoney($this->variant->getPrice()), $includeVariants,
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited fn () => $this->catalogItem
? null ->visibleVariants($this->variant_id)
: $this->variant->inventory->availableStock(), ->map(fn (Variant $variant): array => $this->variantData($variant))
'values' => $this->variant->selectorOptions($this->catalogItem->itemAttributes), ->values(),
], ),
];
}
/** @return array<string, mixed> */
protected function variantData(Variant $variant): array
{
return [
'id' => $variant->id,
'precio' => $this->formatMoney($variant->precio ?? $this->catalogItem->precio),
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null
: $variant->inventory->availableStock(),
'values' => $variant->selectorOptions($this->catalogItem->itemAttributes),
]; ];
} }

View File

@@ -4,15 +4,26 @@ namespace App\Domains\Cart\Services;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart; 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 App\Domains\Tenant\Models\Tenant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CartService class CartService
{ {
public function __construct(
private readonly StockReservationService $reservations,
private readonly PurchaseStateGuard $purchaseState,
) {}
public function show(Tenant $tenant, Request $request): Cart public function show(Tenant $tenant, Request $request): Cart
{ {
$resolvedIdentity = $this->resolveIdentity($request); $resolvedIdentity = $this->resolveIdentity($request);
@@ -27,7 +38,7 @@ class CartService
return $this->makeEmptyCart($tenant); return $this->makeEmptyCart($tenant);
} }
return $this->loadCart($cart); return $this->loadCart($cart, $tenant);
} }
/** /**
@@ -46,7 +57,7 @@ class CartService
$cart->addItem($catalogItemId, $variantId, $quantity); $cart->addItem($catalogItemId, $variantId, $quantity);
return [ return [
'cart' => $this->loadCart($cart), 'cart' => $this->loadCart($cart, $tenant),
'guest_token' => $resolvedIdentity['generated_guest_token'], 'guest_token' => $resolvedIdentity['generated_guest_token'],
]; ];
} }
@@ -59,34 +70,248 @@ class CartService
?int $variantId, ?int $variantId,
bool $updateVariant, bool $updateVariant,
): Cart { ): 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); $identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity); $cart = $this->findCartOrFail($tenant, $identity);
$cart->updateItem($cartItemId, $quantity, $variantId, $updateVariant); $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 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); $identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity); $cart = $this->findCartOrFail($tenant, $identity);
$cart->removeItem($cartItemId); $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 public function makeGuestTokenCookie(string $guestToken): Cookie
{ {
return cookie( $secure = (bool) config('session.secure');
'guest_token', $sameSite = config('session.same_site');
$guestToken, $partitioned = (bool) config('session.partitioned')
60 * 24 * 180, || ($secure && strtolower((string) $sameSite) === 'none');
'/',
config('session.domain'), return Cookie::create(
(bool) config('session.secure'), name: 'guest_token',
true, value: $guestToken,
false, expire: now()->addDays(180),
config('session.same_site'), path: '/',
domain: config('session.domain'),
secure: $secure,
httpOnly: true,
raw: false,
sameSite: $sameSite,
partitioned: $partitioned,
); );
} }
@@ -102,9 +327,9 @@ class CartService
return $cart; 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.attachments',
'items.catalogItem.inventory', 'items.catalogItem.inventory',
'items.catalogItem.itemAttributes.attribute', 'items.catalogItem.itemAttributes.attribute',
@@ -113,7 +338,25 @@ class CartService
'items.variant.definitions.itemAttribute.attribute.options', 'items.variant.definitions.itemAttribute.attribute.options',
'items.variant.eventDates', 'items.variant.eventDates',
'items.variant.eventDate', '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(); ->first();
if ($userCart !== null) { if ($userCart !== null) {
$userCart->items()
->orderBy('id')
->pluck('id')
->each(fn (int $itemId) => $userCart->removeItem($itemId));
$userCart->update([ $userCart->update([
'status' => 'converted', 'status' => 'converted',
]); ]);

View File

@@ -7,11 +7,12 @@ Gestiona el carrito activo de un tenant tanto para visitantes como para usuarios
## Modelo ## Modelo
- `Cart`: pertenece a un tenant y opcionalmente a un usuario; calcula el total y permite agregar, actualizar o quitar ítems. - `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 ## Servicios
- `CartService`: obtiene el carrito, modifica ítems y administra la cookie del token invitado. - `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. - `GuestCartMergeService`: incorpora el carrito invitado al usuario cuando este se autentica.
## Endpoints ## Endpoints
@@ -30,3 +31,7 @@ Bajo `/tenants/{tenant:codigo}`:
## Dependencias y reglas ## 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. 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::patch('cart/items/{cartItem}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{cartItem}', [CartController::class, 'removeItem']); 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\CatalogItemResource;
use App\Domains\Catalog\Resources\CatalogSearchItemResource; use App\Domains\Catalog\Resources\CatalogSearchItemResource;
use App\Domains\Catalog\Resources\CatalogVariantOptionsResource; use App\Domains\Catalog\Resources\CatalogVariantOptionsResource;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Catalog\Services\FeaturedGroupService; use App\Domains\Catalog\Services\FeaturedGroupService;
use App\Domains\Catalog\Services\VariantSelectionService; use App\Domains\Catalog\Services\VariantSelectionService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Auth;
class CatalogController extends Controller 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() $featuredGroups = FeaturedGroup::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
@@ -37,7 +40,7 @@ class CatalogController extends Controller
return response()->json($featuredGroups->map( return response()->json($featuredGroups->map(
fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource( fn (FeaturedGroup $featuredGroup): array => (new CatalogFeaturedGroupResource(
$featuredGroup, $featuredGroup,
$featuredGroupService->itemsResponse($featuredGroup, 1), $featuredGroupService->itemsResponse($featuredGroup, 1, $this->userId($request)),
))->resolve() ))->resolve()
)); ));
} }
@@ -46,15 +49,17 @@ class CatalogController extends Controller
SearchCatalogItemsRequest $request, SearchCatalogItemsRequest $request,
Tenant $tenant, Tenant $tenant,
CatalogService $catalogService, CatalogService $catalogService,
CatalogItemAllowanceService $allowances,
): AnonymousResourceCollection { ): AnonymousResourceCollection {
return CatalogSearchItemResource::collection( $items = $catalogService->search(
$catalogService->search( $tenant,
$tenant, $request->validated('q'),
$request->validated('q'), $tenant->search_items_per_page,
$tenant->search_items_per_page, (int) $request->validated('page', 1),
(int) $request->validated('page', 1),
)
); );
$allowances->attach($items->getCollection(), $this->userId($request));
return CatalogSearchItemResource::collection($items);
} }
public function category( public function category(
@@ -62,17 +67,19 @@ class CatalogController extends Controller
Tenant $tenant, Tenant $tenant,
Category $category, Category $category,
CatalogService $catalogService, CatalogService $catalogService,
CatalogItemAllowanceService $allowances,
): AnonymousResourceCollection { ): AnonymousResourceCollection {
abort_unless($category->tenant_code === $tenant->codigo, 404); abort_unless($category->tenant_code === $tenant->codigo, 404);
return CatalogSearchItemResource::collection( $items = $catalogService->categoryItems(
$catalogService->categoryItems( $tenant,
$tenant, $category,
$category, $tenant->search_items_per_page,
$tenant->search_items_per_page, (int) $request->validated('page', 1),
(int) $request->validated('page', 1), );
) $allowances->attach($items->getCollection(), $this->userId($request));
)->additional([
return CatalogSearchItemResource::collection($items)->additional([
'category' => [ 'category' => [
'id' => $category->id, 'id' => $category->id,
'nombre' => $category->nombre, 'nombre' => $category->nombre,
@@ -93,7 +100,11 @@ class CatalogController extends Controller
$page = (int) $request->validated('page', 1); $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( public function show(
@@ -101,17 +112,19 @@ class CatalogController extends Controller
Tenant $tenant, Tenant $tenant,
CatalogItem $catalogItem, CatalogItem $catalogItem,
CatalogService $catalogService, CatalogService $catalogService,
CatalogItemAllowanceService $allowances,
): CatalogItemDetailResource { ): CatalogItemDetailResource {
abort_unless($catalogItem->tenant_code === $tenant->codigo, 404); abort_unless($catalogItem->tenant_code === $tenant->codigo, 404);
$variantId = $request->validated('variant_id'); $variantId = $request->validated('variant_id');
return CatalogItemDetailResource::make( $item = $catalogService->getDetail(
$catalogService->getDetail( $catalogItem,
$catalogItem, $variantId === null ? null : (int) $variantId,
$variantId === null ? null : (int) $variantId,
)
); );
$allowances->attach(collect([$item]), $this->userId($request));
return CatalogItemDetailResource::make($item);
} }
public function variantOptions( public function variantOptions(
@@ -164,4 +177,11 @@ class CatalogController extends Controller
->response() ->response()
->setStatusCode(201); ->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\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
#[Fillable([ #[Fillable([
'tenant_code', 'tenant_code',
'code',
'source_type', 'source_type',
'category_id', 'category_id',
'product_layout', 'product_layout',
@@ -33,6 +35,29 @@ class FeaturedGroup extends Model
'source_type' => FeaturedGroupSource::Manual->value, '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 protected function casts(): array
{ {
return [ return [

View File

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

View File

@@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
'allow_multi_select', 'allow_multi_select',
'sort_order', 'sort_order',
'show_in_selector', 'show_in_selector',
'ticket_label',
])] ])]
class ItemAttribute extends Model class ItemAttribute extends Model
{ {

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 [ return [
'id' => $this->id, 'id' => $this->id,
'code' => $this->code,
'category_id' => $this->category_id, 'category_id' => $this->category_id,
'category_name' => $this->category->nombre, 'category_name' => $this->category->nombre,
'group_name' => $this->group_name, 'group_name' => $this->group_name,

View File

@@ -20,6 +20,7 @@ class CatalogFeaturedGroupResource extends JsonResource
{ {
return [ return [
'id' => $this->id, 'id' => $this->id,
'code' => $this->code,
'title' => $this->group_name, 'title' => $this->group_name,
'layout' => $this->product_layout->value, 'layout' => $this->product_layout->value,
'group_layout' => $this->group_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\CatalogItem;
use App\Domains\Catalog\Models\FeaturedGroup; use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -19,6 +20,7 @@ class CatalogFeaturedItemResource extends JsonResource
$catalogItem = $this->resource; $catalogItem = $this->resource;
/** @var FeaturedGroup $featuredGroup */ /** @var FeaturedGroup $featuredGroup */
$featuredGroup = $catalogItem->getRelation('featuredGroup'); $featuredGroup = $catalogItem->getRelation('featuredGroup');
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) { if ($featuredGroup->product_layout === ProductLayout::ColumnWithImage) {
return $this->columnWithImageData($catalogItem); return $this->columnWithImageData($catalogItem);
@@ -34,7 +36,10 @@ class CatalogFeaturedItemResource extends JsonResource
'nombre' => $catalogItem->nombre, 'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion, 'descripcion' => $catalogItem->descripcion,
'precio' => $catalogItem->precio, 'precio' => $catalogItem->precio,
'stock_tecnico' => $catalogItem->availableStock(), 'maximum_addable_quantity' => $this->maximumAddable(
$catalogItem->availableStock(),
$remainingUserQuota,
),
'variants' => $catalogItem->visibleVariants() 'variants' => $catalogItem->visibleVariants()
->map(fn (Variant $variant): array => [ ->map(fn (Variant $variant): array => [
'id' => $variant->id, '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(), 'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited 'maximum_addable_quantity' => $this->maximumAddable(
? null $catalogItem->inventory_policy === InventoryPolicy::Unlimited
: $variant->inventory->availableStock(), ? null
: $variant->inventory->availableStock(),
$remainingUserQuota,
),
'values' => $variant->selectorOptions($catalogItem->itemAttributes), 'values' => $variant->selectorOptions($catalogItem->itemAttributes),
]) ])
->values(), ->values(),
@@ -89,4 +97,10 @@ class CatalogFeaturedItemResource extends JsonResource
return $attachment?->getTemporaryUrl(1440); 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\CatalogItem;
use App\Domains\Catalog\Models\ItemAttribute; use App\Domains\Catalog\Models\ItemAttribute;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use App\Domains\Shared\Enums\FieldType; use App\Domains\Shared\Enums\FieldType;
use App\Domains\Ticket\Resources\ValidityTimeResource; use App\Domains\Ticket\Resources\ValidityTimeResource;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -37,9 +38,9 @@ class CatalogItemDetailResource extends JsonResource
'max_units_per_user' => $this->max_units_per_user, 'max_units_per_user' => $this->max_units_per_user,
'has_tickets' => $this->has_tickets, 'has_tickets' => $this->has_tickets,
'attributes' => $this->attributesData(), 'attributes' => $this->attributesData(),
'stock_tecnico' => $this->when( 'maximum_addable_quantity' => $this->when(
$selectedVariant === null, $selectedVariant === null,
fn () => $this->availableStock(), fn () => $this->maximumAddable($this->availableStock()),
), ),
'images' => $this->when( 'images' => $this->when(
$selectedVariant === null, $selectedVariant === null,
@@ -85,6 +86,7 @@ class CatalogItemDetailResource extends JsonResource
'nombre' => $attribute->nombre, 'nombre' => $attribute->nombre,
'sort_order' => $itemAttribute->sort_order, 'sort_order' => $itemAttribute->sort_order,
'show_in_selector' => $itemAttribute->show_in_selector, 'show_in_selector' => $itemAttribute->show_in_selector,
'ticket_label' => $itemAttribute->ticket_label,
'is_required' => $attribute->is_required, 'is_required' => $attribute->is_required,
'allow_multi_select' => $itemAttribute->allow_multi_select, 'allow_multi_select' => $itemAttribute->allow_multi_select,
'metadata_schema' => $attribute->metadata_schema, 'metadata_schema' => $attribute->metadata_schema,
@@ -166,7 +168,7 @@ class CatalogItemDetailResource extends JsonResource
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(), 'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $this->variantStock($variant), 'maximum_addable_quantity' => $this->maximumAddable($this->variantStock($variant)),
'values' => $values, 'values' => $values,
]; ];
} }
@@ -185,4 +187,12 @@ class CatalogItemDetailResource extends JsonResource
? null ? null
: $variant->inventory->availableStock(); : $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\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -26,7 +27,7 @@ class CatalogSearchItemResource extends JsonResource
'descripcion' => $this->descripcion, 'descripcion' => $this->descripcion,
'precio' => $this->precio, 'precio' => $this->precio,
'image' => $attachment?->getTemporaryUrl(1440), 'image' => $attachment?->getTemporaryUrl(1440),
'stock_tecnico' => $this->availableStock(), 'maximum_addable_quantity' => $this->maximumAddable($this->availableStock()),
'variants' => $this->visibleVariants() 'variants' => $this->visibleVariants()
->map(fn (Variant $variant): array => [ ->map(fn (Variant $variant): array => [
'id' => $variant->id, '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(), 'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'descripcion' => $variant->getDescription(), 'descripcion' => $variant->getDescription(),
'precio' => number_format($variant->getPrice(), 2, '.', ''), 'precio' => number_format($variant->getPrice(), 2, '.', ''),
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited 'maximum_addable_quantity' => $this->maximumAddable(
? null $this->inventory_policy === InventoryPolicy::Unlimited
: $variant->inventory?->availableStock(), ? null
: $variant->inventory?->availableStock(),
),
'values' => $variant->selectorOptions($this->itemAttributes), 'values' => $variant->selectorOptions($this->itemAttributes),
]) ])
->values(), ->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 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 public function availableQuantity(CatalogItem|Variant $selection): ?int
{ {
if ($selection instanceof CatalogItem 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

@@ -38,6 +38,7 @@ class CatalogService
$attributeCodes = $data['attribute_codes'] ?? []; $attributeCodes = $data['attribute_codes'] ?? [];
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? []; $multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
$hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? []; $hiddenAttributeCodes = $data['hidden_attribute_codes'] ?? [];
$ticketAttributeLabels = $data['ticket_attribute_labels'] ?? [];
$components = $data['components'] ?? []; $components = $data['components'] ?? [];
$hasDirectStock = array_key_exists('real_stock', $data); $hasDirectStock = array_key_exists('real_stock', $data);
$realStock = (int) ($data['real_stock'] ?? 0); $realStock = (int) ($data['real_stock'] ?? 0);
@@ -73,6 +74,14 @@ class CatalogService
]); ]);
} }
if (array_diff(array_keys($ticketAttributeLabels), $attributeCodes) !== []) {
throw ValidationException::withMessages([
'ticket_attribute_labels' => [
__('api.catalog.ticket_label_attribute_not_on_item'),
],
]);
}
$this->validateUniqueVariantCombinations($variants, $attributeCodes); $this->validateUniqueVariantCombinations($variants, $attributeCodes);
if ($type === CatalogItemType::Bundle) { if ($type === CatalogItemType::Bundle) {
@@ -98,6 +107,7 @@ class CatalogService
$data['attribute_codes'], $data['attribute_codes'],
$data['multi_select_attribute_codes'], $data['multi_select_attribute_codes'],
$data['hidden_attribute_codes'], $data['hidden_attribute_codes'],
$data['ticket_attribute_labels'],
$data['components'], $data['components'],
$data['real_stock'], $data['real_stock'],
$data['reserved_stock'], $data['reserved_stock'],
@@ -124,6 +134,7 @@ class CatalogService
$attributeCodes, $attributeCodes,
$multiSelectAttributeCodes, $multiSelectAttributeCodes,
$hiddenAttributeCodes, $hiddenAttributeCodes,
$ticketAttributeLabels,
) )
: []; : [];
@@ -461,6 +472,7 @@ class CatalogService
* @param array<int, string> $attributeCodes * @param array<int, string> $attributeCodes
* @param array<int, string> $multiSelectAttributeCodes * @param array<int, string> $multiSelectAttributeCodes
* @param array<int, string> $hiddenAttributeCodes * @param array<int, string> $hiddenAttributeCodes
* @param array<string, string> $ticketAttributeLabels
* @return array<string, ItemAttribute> * @return array<string, ItemAttribute>
*/ */
private function createItemAttributes( private function createItemAttributes(
@@ -468,6 +480,7 @@ class CatalogService
array $attributeCodes, array $attributeCodes,
array $multiSelectAttributeCodes = [], array $multiSelectAttributeCodes = [],
array $hiddenAttributeCodes = [], array $hiddenAttributeCodes = [],
array $ticketAttributeLabels = [],
): array { ): array {
$itemAttributes = []; $itemAttributes = [];
$attributeCodes = array_values(array_unique($attributeCodes)); $attributeCodes = array_values(array_unique($attributeCodes));
@@ -492,6 +505,7 @@ class CatalogService
'attribute_id' => $attribute->id, 'attribute_id' => $attribute->id,
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true), 'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true), 'show_in_selector' => ! in_array($attributeCode, $hiddenAttributeCodes, true),
'ticket_label' => $ticketAttributeLabels[$attributeCode] ?? null,
]); ]);
$itemAttributes[$attributeCode] = $itemAttribute; $itemAttributes[$attributeCode] = $itemAttribute;

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; private const ITEMS_PER_PAGE = 12;
/** @return array<array-key, mixed> */ /** @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) { if ($featuredGroup->group_layout !== GroupLayout::Paginated) {
$query = $this->itemsQuery($featuredGroup); $query = $this->itemsQuery($featuredGroup);
@@ -26,12 +30,14 @@ class FeaturedGroupService
$items = $query->get(); $items = $query->get();
$this->attachGroup($items, $featuredGroup); $this->attachGroup($items, $featuredGroup);
$this->allowances->attach($items, $userId);
return CatalogFeaturedItemResource::collection($items)->resolve(); return CatalogFeaturedItemResource::collection($items)->resolve();
} }
$paginator = $this->paginateItems($featuredGroup, $page); $paginator = $this->paginateItems($featuredGroup, $page);
$this->attachGroup($paginator->getCollection(), $featuredGroup); $this->attachGroup($paginator->getCollection(), $featuredGroup);
$this->allowances->attach($paginator->getCollection(), $userId);
return CatalogFeaturedItemResource::collection($paginator) return CatalogFeaturedItemResource::collection($paginator)
->response() ->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. - `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. - `Variant`, `ItemAttribute`, `Attribute`, `AttributeOption` y `VariantDefinition` describen opciones comercializables.
- `Inventory` administra stock disponible, reservado y comprado. - `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. - `Category` soporta jerarquía y categorías globales o propias del tenant.
- `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas. - `FeaturedGroup` y `FeaturedItem` organizan secciones destacadas.
- `BundleComponent` representa los componentes de un paquete. - `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. - `CatalogService`: alta, búsqueda, detalle, listado por categoría y eliminación.
- `CatalogInventoryService`: consulta, reserva, libera y confirma inventario. - `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. - `FeaturedGroupService`: pagina los ítems destacados para la tienda.
- `OnTicketFeaturedGroupService`: administra grupos destacados del panel para sitios de tickets. - `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, 'password' => $password,
]); ]);
$data = $this->handleResponse($response, 'authentication', [ $data = $this->handleResponse($response, 'authentication');
'username' => $username,
]);
$token = $data['token'] ?? null; $token = $data['token'] ?? null;
$expiresAtStr = $data['expires_at'] ?? null; $expiresAtStr = $data['expires_at'] ?? null;
@@ -110,7 +108,12 @@ class TelepagosIntegrationService extends BaseIntegrationService
$response = $this->client()->$method($endpoint, $data); $response = $this->client()->$method($endpoint, $data);
if ($response->status() === 401) { 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(); $this->clearToken();
@@ -175,9 +178,11 @@ class TelepagosIntegrationService extends BaseIntegrationService
{ {
if ($response->failed() || $response->json('status') !== 'ok') { if ($response->failed() || $response->json('status') !== 'ok') {
$errorMessage = $response->json('message') ?? $response->body(); $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_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)); ], $context));
throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}"); throw new Exception("Telepagos {$actionDescription} failed: {$errorMessage}");
@@ -186,6 +191,30 @@ class TelepagosIntegrationService extends BaseIntegrationService
return $response->json() ?? []; 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. * Clear the cached token.
*/ */

View File

@@ -24,6 +24,11 @@ class TelepagosWebhookService
*/ */
public function handleWebhook(Client $client, string $cashinId): void 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 = new TelepagosIntegrationService;
$telepagosService->forClient($client); $telepagosService->forClient($client);
@@ -34,6 +39,20 @@ class TelepagosWebhookService
$amount = $this->normalizeAmount($details['data']['amount'] ?? $details['amount'] ?? 0); $amount = $this->normalizeAmount($details['data']['amount'] ?? $details['amount'] ?? 0);
$operationId = $details['data']['operation_id'] ?? $details['operation_id'] ?? null; $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]; $transferenciaOperationIds = [1, 3, 11];
$qrOperationIds = [31, 37, 47]; $qrOperationIds = [31, 37, 47];
@@ -43,7 +62,10 @@ class TelepagosWebhookService
$cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null; $cuit = $details['data']['buyer']['cuit'] ?? $details['buyer']['cuit'] ?? null;
if (! $cuit) { 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; return;
} }
@@ -60,19 +82,31 @@ class TelepagosWebhookService
->where('payment_method', 'transfer') ->where('payment_method', 'transfer')
->where('total', $amount) ->where('total', $amount)
->latest() ->latest()
->limit(2)
->get(); ->get();
$paymentData['matched_purchase_ids'] = $purchases->pluck('id')->all();
$compra = $purchases->count() === 1 ? $purchases->first() : null; $compra = $purchases->count() === 1 ? $purchases->first() : null;
if (! $compra) { 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; return;
} }
} elseif (in_array((int) $operationId, $qrOperationIds, true)) { } elseif (in_array((int) $operationId, $qrOperationIds, true)) {
if (! $qrOrderId) { 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; return;
} }
@@ -80,7 +114,11 @@ class TelepagosWebhookService
$telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first(); $telepagosQr = TelepagosQr::where('qr_order_id', $qrOrderId)->first();
if (! $telepagosQr) { 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; return;
} }
@@ -88,13 +126,21 @@ class TelepagosWebhookService
$compra = $telepagosQr->compra; $compra = $telepagosQr->compra;
if (! $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; return;
} }
if (! $client->tenants()->where('codigo', $compra->tenant_codigo)->exists()) { 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; return;
} }
@@ -102,7 +148,12 @@ class TelepagosWebhookService
if (! in_array($compra->status, [ if (! in_array($compra->status, [
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_PENDING_PAYMENT,
], true)) { ], 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; return;
} }
@@ -110,37 +161,45 @@ class TelepagosWebhookService
$totalAmount = $this->normalizeAmount($compra->getTotalAmount()); $totalAmount = $this->normalizeAmount($compra->getTotalAmount());
if ($amount !== $totalAmount) { 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; return;
} }
} else { } 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; return;
} }
$paymentData = [ $paymentData['compra_id'] = $compra->id;
'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,
];
DB::transaction(function () use ($compra, $paymentData) { DB::transaction(function () use ($compra, $paymentData) {
TelepagosPayment::create($paymentData); TelepagosPayment::create($paymentData);
$this->checkoutService->confirmPaidPurchase($compra); $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) { } 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; 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`. - Consulta y configuración por cliente bajo `/clients/{client}/integrations`.
- `POST /webhooks/telepagos/{client}` para notificaciones del proveedor. - `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 ## 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. 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\PaymentIntentRequest;
use App\Domains\Purchase\Requests\StartCheckoutRequest; use App\Domains\Purchase\Requests\StartCheckoutRequest;
use App\Domains\Purchase\Requests\UpdatePurchaseCustomerRequest; 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\Resources\PurchaseResource;
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
use App\Domains\Purchase\Services\CheckoutService; use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -52,12 +54,16 @@ class PurchaseController extends Controller
return PurchaseResource::make($purchase)->response()->setStatusCode(201); 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 = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
$compra->loadMissing('items')->loadCount('tickets'); $compra->loadMissing('items')->loadCount('tickets');
$compra->items->load('imageAttachment'); $responses->load($compra);
return PurchaseResource::make($compra); return PurchaseResource::make($compra);
} }
@@ -75,8 +81,8 @@ class PurchaseController extends Controller
); );
} }
public function updateItemQuantity( public function updateItem(
UpdatePurchaseItemQuantityRequest $request, UpdatePurchaseItemRequest $request,
Tenant $tenant, Tenant $tenant,
Purchase $compra, Purchase $compra,
PurchaseItem $item, PurchaseItem $item,
@@ -85,10 +91,12 @@ class PurchaseController extends Controller
$compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra); $compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
return PurchaseResource::make( return PurchaseResource::make(
$checkoutService->updateItemQuantity( $checkoutService->updateItem(
$compra, $compra,
$item, $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,55 +114,81 @@ 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); $compra = $this->resolveScopedPurchase($tenant, $request->user()->id, $compra);
$method = $request->validated('method'); $method = $request->validated('method');
$totalAmount = $compra->calculateCurrentTotalAmount(); $transferPayerDni = $method === 'transfer'
? preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'))
: null;
$purchaseUpdate = [ $updated = DB::transaction(function () use ($compra, $method, $purchaseState, $transferPayerDni): bool {
'payment_method' => $method,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'expires_at' => now()->addMinutes(
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
),
'total' => $totalAmount,
];
if ($method === 'transfer') {
$purchaseUpdate['transfer_payer_dni'] = preg_replace('/\D+/', '', (string) $request->validated('transfer_payer_dni'));
}
$updated = DB::transaction(function () use ($compra, $purchaseUpdate): bool {
/** @var Purchase|null $purchase */ /** @var Purchase|null $purchase */
$purchase = Purchase::query() $purchase = Purchase::query()
->whereKey($compra->getKey()) ->whereKey($compra->getKey())
->lockForUpdate() ->lockForUpdate()
->first(); ->first();
if ($purchase === null) {
return false;
}
$purchaseState->assertNotExpired($purchase);
if ( if (
$purchase === null ! in_array($purchase->status, [
|| ! in_array($purchase->status, [
Purchase::STATUS_CREATED, Purchase::STATUS_CREATED,
Purchase::STATUS_PENDING_PAYMENT, Purchase::STATUS_PENDING_PAYMENT,
], true) ], true)
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
) { ) {
return false; return false;
} }
$purchaseUpdate = [
'payment_method' => $method,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'expires_at' => now()->addMinutes(
max(1, (int) config("purchase.payment_expiration_minutes.{$method}", 30))
),
'total' => $purchase->calculateCurrentTotalAmount(),
];
if ($transferPayerDni !== null) {
$purchaseUpdate['transfer_payer_dni'] = $transferPayerDni;
}
$purchase->update($purchaseUpdate); $purchase->update($purchaseUpdate);
return true; return true;
}); });
if ($updated === 0) { if (! $updated) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'purchase' => __('api.purchase.not_available_for_payment'), 'purchase' => __('api.purchase.not_available_for_payment'),
]); ]);
} }
$compra->refresh(); $compra->refresh();
$totalAmount = (float) $compra->total;
$checkoutService->syncReservationExpiration($compra);
if ($method === 'transfer') { if ($method === 'transfer') {
$telepagosService = new TelepagosIntegrationService; $telepagosService = new TelepagosIntegrationService;
@@ -163,6 +197,11 @@ class PurchaseController extends Controller
try { try {
$accountInfo = $telepagosService->getAccountInfo(); $accountInfo = $telepagosService->getAccountInfo();
Log::channel('telepagos')->info('Telepagos account information retrieved.', [
'tenant_code' => $tenant->codigo,
'purchase_id' => $compra->id,
]);
return response()->json([ return response()->json([
'payment_method' => 'transfer', 'payment_method' => 'transfer',
'transfer_data' => [ 'transfer_data' => [
@@ -174,9 +213,10 @@ class PurchaseController extends Controller
], ],
]); ]);
} catch (\Exception $e) { } 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, 'purchase_id' => $compra->id,
'exception' => $e, 'error' => $e->getMessage(),
]); ]);
return response()->json([ return response()->json([
@@ -191,7 +231,11 @@ class PurchaseController extends Controller
$telepagosService->forTenant($tenant->codigo); $telepagosService->forTenant($tenant->codigo);
try { 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( $qrResponse = $telepagosService->generateQr(
$totalAmount, $totalAmount,
'Compra', 'Compra',
@@ -202,10 +246,17 @@ class PurchaseController extends Controller
'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''), 'qr_order_id' => (string) ($qrResponse['qr_order_id'] ?? ''),
'qr_code' => $qrResponse['qr_code'] ?? '', '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, '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([ 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\Auth\Models\User;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\StockReservation;
use App\Domains\Logging\Models\Concerns\LogsValueChanges; use App\Domains\Logging\Models\Concerns\LogsValueChanges;
use App\Domains\Purchase\Events\PurchasePaid; use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
@@ -116,6 +117,12 @@ class Purchase extends Model
return $this->hasMany(Ticket::class, 'source_purchase_id'); 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> * @return HasOne<TelepagosQr, $this>
*/ */
@@ -143,11 +150,16 @@ class Purchase extends Model
public function calculateCurrentTotalAmount(): float 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->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 protected function valueChangeTenantCode(): string

View File

@@ -3,6 +3,8 @@
namespace App\Domains\Purchase\Models; namespace App\Domains\Purchase\Models;
use App\Domains\Attachable\Models\Attachment; 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\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -23,18 +25,11 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
'discount_total', 'discount_total',
'tax_total', 'tax_total',
'total', 'total',
'reservation_status',
])] ])]
class PurchaseItem extends Model class PurchaseItem extends Model
{ {
use HasFactory; use HasFactory;
public const RESERVATION_ACTIVE = 'active';
public const RESERVATION_COMMITTED = 'committed';
public const RESERVATION_RELEASED = 'released';
protected $table = 'compra_items'; protected $table = 'compra_items';
protected function casts(): array protected function casts(): array
@@ -66,4 +61,16 @@ class PurchaseItem extends Model
{ {
return $this->belongsTo(Attachment::class, 'image_attachment_id'); 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([ #[Fillable([
'compra_id', 'compra_id',
'matched_purchase_ids',
'cuit_buyer', 'cuit_buyer',
'cvu_buyer', 'cvu_buyer',
'amount', 'amount',
@@ -29,6 +30,7 @@ class TelepagosPayment extends Model
{ {
return [ return [
'compra_id' => 'integer', 'compra_id' => 'integer',
'matched_purchase_ids' => 'array',
'amount' => 'decimal:2', '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; namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
@@ -25,6 +26,14 @@ class PurchaseItemResource extends JsonResource
: null; : null;
$attributes = $this->variant_attributes ?? []; $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 [ return [
'id' => $this->id, 'id' => $this->id,
'quantity' => (int) $this->cantidad, 'quantity' => (int) $this->cantidad,
@@ -39,6 +48,13 @@ class PurchaseItemResource extends JsonResource
'imagen' => $imageUrl, 'imagen' => $imageUrl,
'attributes' => $attributes, '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 $imageUrl = $displayImage
? $this->resolveImageUrl($selectedItem, $catalogItem) ? $this->resolveImageUrl($selectedItem, $catalogItem)
: null; : null;
$includeVariants = $tenant instanceof Tenant
&& $tenant->checkout_editing_policy->allowsVariantChanges()
&& $catalogItem?->relationLoaded('variants');
return [ return [
'id' => $this->id, 'id' => $this->id,
'quantity' => $quantity, 'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice), 'unit_price' => $this->formatMoney($unitPrice),
'line_total' => $this->formatMoney($lineTotal), 'line_total' => $this->formatMoney($lineTotal),
'catalog_item_id' => $this->catalog_item_id, 'source_catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id, 'source_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),
],
'item_details' => $selectedItem === null ? null : [ 'item_details' => $selectedItem === null ? null : [
'nombre' => $selectedItem->getName(), 'nombre' => $selectedItem->getName(),
'descripcion' => $selectedItem->getDescription(), 'descripcion' => $selectedItem->getDescription(),
'slug' => $catalogItem?->slug,
'imagen' => $imageUrl, 'imagen' => $imageUrl,
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant), '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 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; namespace App\Domains\Purchase\Resources;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -17,26 +18,40 @@ class PurchaseResource extends JsonResource
*/ */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$items = $this->resource->relationLoaded('items') $purchaseItems = $this->resource->relationLoaded('items')
? $this->resource->getRelation('items') ? $this->resource->getRelation('items')
: collect(); : 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()) $ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
? (int) $this->resource->getAttribute('tickets_count') ? (int) $this->resource->getAttribute('tickets_count')
: null; : null;
$subtotal = $items->isNotEmpty() $subtotal = $items->isNotEmpty()
? $items->reduce( ? $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, 0.0,
) )
: (float) ($this->total ?? 0); : (float) ($this->total ?? 0);
$total = $items->isNotEmpty() $total = $this->status === Purchase::STATUS_PAID && $this->total !== null
? $items->reduce( ? (float) $this->total
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item), : ($items->isNotEmpty()
0.0, ? $items->reduce(
) fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
: (float) ($this->total ?? 0); 0.0,
)
: (float) ($this->total ?? 0));
return [ return [
'id' => $this->id, 'id' => $this->id,
@@ -52,7 +67,7 @@ class PurchaseResource extends JsonResource
'telefono' => $this->telefono, 'telefono' => $this->telefono,
'nombre_apellido' => $this->nombre_apellido, 'nombre_apellido' => $this->nombre_apellido,
'email' => $this->email, 'email' => $this->email,
'items_source' => $items->isNotEmpty() ? 'purchase' : null, 'items_source' => $itemsSource,
'items' => PurchaseItemResource::collection($items), 'items' => PurchaseItemResource::collection($items),
'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount), 'tickets_count' => $this->when($ticketsCount !== null, $ticketsCount),
'has_generated_tickets' => $this->when($ticketsCount !== null, $ticketsCount > 0), '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; 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); 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\CatalogItem;
use App\Domains\Catalog\Models\Inventory; use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -79,13 +78,4 @@ class CatalogSelectionResolver
return $variant; 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; 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\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Services\PurchaseStateGuard;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
class CompleteCheckoutService class CompleteCheckoutService
{ {
public function __construct( public function __construct(
private readonly CatalogInventoryService $inventory, private readonly StockReservationService $reservations,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart, private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly PurchaseStateGuard $purchaseState,
) {} ) {}
public function complete(Purchase $purchase): Purchase public function complete(Purchase $purchase): Purchase
{ {
return DB::transaction(function () use ($purchase): Purchase { return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
if ($purchase->payment_method === null) { if ($purchase->payment_method === null) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -44,6 +48,7 @@ class CompleteCheckoutService
{ {
return DB::transaction(function () use ($purchase): Purchase { return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
if ($purchase->status === Purchase::STATUS_PAID) { if ($purchase->status === Purchase::STATUS_PAID) {
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
@@ -59,6 +64,7 @@ class CompleteCheckoutService
} }
$purchase->update(['expires_at' => null]); $purchase->update(['expires_at' => null]);
$this->reservations->syncPurchaseExpiration($purchase);
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
}); });
@@ -68,6 +74,7 @@ class CompleteCheckoutService
{ {
DB::transaction(function () use ($purchase): void { DB::transaction(function () use ($purchase): void {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
if ($purchase->status === Purchase::STATUS_PAID) { if ($purchase->status === Purchase::STATUS_PAID) {
return; return;
@@ -83,25 +90,51 @@ class CompleteCheckoutService
]); ]);
} }
$items = $purchase->items() if ($purchase->items()->exists()) {
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE) $cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
->lockForUpdate() if ($cart?->status === 'converted' && $cart->trashed()) {
->get(); return;
}
foreach ($items as $item) { throw ValidationException::withMessages([
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item); 'items' => __('api.purchase.inconsistent_reservation'),
]);
}
try { $cart = $purchase->cart()->lockForUpdate()->first();
$this->inventory->commit($selection, (int) $item->cantidad); if ($cart === null || $cart->status !== 'checkout') {
} catch (\InvalidArgumentException) { 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([ throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'), 'items' => __('api.purchase.inconsistent_reservation'),
]); ]);
} }
$item->update([ try {
'reservation_status' => PurchaseItem::RESERVATION_COMMITTED, $this->reservations->commit($cartItem, $selection);
]); } catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
} }
$this->sourceCart->finalize($purchase); $this->sourceCart->finalize($purchase);
@@ -126,6 +159,30 @@ class CompleteCheckoutService
private function loadPurchase(Purchase $purchase): Purchase 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\Catalog\Services\CatalogInventoryService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\PurchaseStateGuard;
use App\Domains\Purchase\Services\UserPurchaseLimitService; use App\Domains\Purchase\Services\UserPurchaseLimitService;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
@@ -18,6 +19,9 @@ class EditCheckoutService
private readonly UserPurchaseLimitService $purchaseLimits, private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections, private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart, private readonly SourceCartService $sourceCart,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly PurchaseResponseLoader $responses,
private readonly PurchaseStateGuard $purchaseState,
) {} ) {}
/** @param array<string, string> $customerData */ /** @param array<string, string> $customerData */
@@ -25,6 +29,7 @@ class EditCheckoutService
{ {
return DB::transaction(function () use ($purchase, $customerData): Purchase { return DB::transaction(function () use ($purchase, $customerData): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase); $this->assertEditable($purchase);
$purchase->update($customerData); $purchase->update($customerData);
@@ -33,13 +38,22 @@ class EditCheckoutService
}); });
} }
public function updateItemQuantity( public function updateItem(
Purchase $purchase, Purchase $purchase,
PurchaseItem $purchaseItem, PurchaseItem $purchaseItem,
int $quantity, ?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase { ): Purchase {
return DB::transaction(function () use ($purchase, $purchaseItem, $quantity): Purchase { return DB::transaction(function () use (
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) { if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
@@ -48,16 +62,40 @@ class EditCheckoutService
} }
$purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem); $purchaseItem = $this->lockPurchaseItem($purchase, $purchaseItem);
$difference = $quantity - (int) $purchaseItem->cantidad; $tenant = $purchase->tenant()->firstOrFail();
$finalQuantity = $quantity ?? (int) $purchaseItem->cantidad;
if ($difference !== 0) { if ($quantity !== null && ! $tenant->checkout_editing_policy->allowsQuantityChanges()) {
$this->adjustReservation($purchase, $purchaseItem, $quantity, $difference); throw ValidationException::withMessages([
'quantity' => __('api.cart.editing_disabled'),
$purchaseItem->update([
'cantidad' => $quantity,
'total' => (float) $purchaseItem->precio_unitario * $quantity,
]); ]);
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $quantity); }
if ($updateVariant && ! $tenant->checkout_editing_policy->allowsVariantChanges()) {
throw ValidationException::withMessages([
'variant_id' => __('api.purchase.variant_change_disabled'),
]);
}
if ($updateVariant && $variantId !== $purchaseItem->source_variant_id) {
$this->changeItemVariant(
$purchase,
$purchaseItem,
(int) $variantId,
$finalQuantity,
);
} else {
$difference = $finalQuantity - (int) $purchaseItem->cantidad;
if ($difference !== 0) {
$this->adjustReservation($purchase, $purchaseItem, $finalQuantity, $difference);
$purchaseItem->update([
'cantidad' => $finalQuantity,
'total' => (float) $purchaseItem->precio_unitario * $finalQuantity,
]);
$this->sourceCart->syncItemQuantity($purchase, $purchaseItem, $finalQuantity);
}
} }
$purchase->update([ $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 public function prepareItemEditing(Purchase $purchase): Purchase
{ {
return DB::transaction(function () use ($purchase): Purchase { return DB::transaction(function () use ($purchase): Purchase {
$purchase = $this->lockPurchase($purchase); $purchase = $this->lockPurchase($purchase);
$this->purchaseState->assertNotExpired($purchase);
$this->assertEditable($purchase); $this->assertEditable($purchase);
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsModification()) {
throw ValidationException::withMessages([
'purchase' => __('api.cart.editing_disabled'),
]);
}
$purchase->telepagosQr()->delete(); $purchase->telepagosQr()->delete();
$purchase->update([ $purchase->update([
'status' => Purchase::STATUS_CREATED, '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( private function adjustReservation(
Purchase $purchase, Purchase $purchase,
PurchaseItem $purchaseItem, PurchaseItem $purchaseItem,
@@ -170,6 +317,6 @@ class EditCheckoutService
private function loadPurchase(Purchase $purchase): Purchase 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\Attachable\Models\Attachment;
use App\Domains\Cart\Models\CartItem; use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
class PurchaseItemSnapshotFactory 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 * @param Collection<int, CartItem> $cartItems
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
@@ -38,7 +66,6 @@ class PurchaseItemSnapshotFactory
'discount_total' => null, 'discount_total' => null,
'tax_total' => null, 'tax_total' => null,
'total' => $unitPrice * $quantity, 'total' => $unitPrice * $quantity,
'reservation_status' => PurchaseItem::RESERVATION_ACTIVE,
]; ];
}) })
->all(); ->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; 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\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Services\PurchaseStateGuard;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Throwable;
class ReleaseCheckoutService class ReleaseCheckoutService
{ {
public function __construct( public function __construct(
private readonly CatalogInventoryService $inventory, private readonly StockReservationService $reservations,
private readonly CatalogSelectionResolver $selections,
private readonly SourceCartService $sourceCart, private readonly SourceCartService $sourceCart,
private readonly PurchaseStateGuard $purchaseState,
) {} ) {}
public function cancel(Purchase $purchase): Purchase 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 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 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 public function expireOverdue(): int
@@ -41,7 +44,21 @@ class ReleaseCheckoutService
->where('expires_at', '<=', now()) ->where('expires_at', '<=', now())
->orderBy('id') ->orderBy('id')
->eachById(function (Purchase $purchase) use (&$expiredCount): void { ->eachById(function (Purchase $purchase) use (&$expiredCount): void {
$purchase = $this->expire($purchase); try {
$purchase = $this->expire($purchase);
} catch (Throwable $exception) {
Log::channel('commands')->error('Failed to expire overdue purchase.', [
'command' => 'reservations:expire',
'purchase_id' => $purchase->getKey(),
'tenant_codigo' => $purchase->tenant_codigo,
'cart_id' => $purchase->cart_id,
'status' => $purchase->status,
'expires_at' => $purchase->expires_at,
'exception' => $exception,
]);
return;
}
if ($purchase->status === Purchase::STATUS_EXPIRED) { if ($purchase->status === Purchase::STATUS_EXPIRED) {
$expiredCount++; $expiredCount++;
@@ -51,11 +68,15 @@ class ReleaseCheckoutService
return $expiredCount; 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); $purchase = $this->lockPurchase($purchase);
if ($targetStatus !== Purchase::STATUS_EXPIRED) {
$this->purchaseState->assertNotExpired($purchase);
}
if ($purchase->status === Purchase::STATUS_PAID) { if ($purchase->status === Purchase::STATUS_PAID) {
if ($targetStatus === Purchase::STATUS_EXPIRED) { if ($targetStatus === Purchase::STATUS_EXPIRED) {
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
@@ -77,38 +98,63 @@ class ReleaseCheckoutService
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
$items = $purchase->items() if ($purchase->items()->exists()) {
->where('reservation_status', PurchaseItem::RESERVATION_ACTIVE) throw ValidationException::withMessages([
->lockForUpdate() 'items' => __('api.purchase.inconsistent_reservation'),
->get();
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
foreach ($items as $item) {
if (! $reservationReturnedToCart) {
$this->releaseInventory($purchase, $item);
}
$item->update([
'reservation_status' => PurchaseItem::RESERVATION_RELEASED,
]); ]);
} }
$this->releaseCartReservations($purchase, $targetStatus);
$purchase->update(['status' => $targetStatus]); $purchase->update(['status' => $targetStatus]);
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
}); });
} }
private function releaseInventory(Purchase $purchase, PurchaseItem $item): void private function releaseCartReservations(
{ Purchase $purchase,
$selection = $this->selections->resolvePurchaseItem($purchase->tenant, $item); string $targetStatus,
): void {
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
if ($cart === null) {
return;
}
try { $cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
$this->inventory->release($selection, (int) $item->cantidad); $cartItems->load([
} catch (\InvalidArgumentException) { 'catalogItem.inventory',
throw ValidationException::withMessages([ 'catalogItem.bundleComponents.catalogItem.inventory',
'items' => __('api.purchase.inconsistent_reservation'), 'catalogItem.bundleComponents.variant.inventory',
]); 'variant.inventory',
'variant.catalogItem',
]);
foreach ($cartItems as $cartItem) {
$selection = $cartItem->selectedItem();
if ($selection === null) {
continue;
}
try {
$this->reservations->release(
$cartItem,
$selection,
(int) $cartItem->cantidad,
$targetStatus === Purchase::STATUS_EXPIRED
? StockReservation::STATUS_EXPIRED
: StockReservation::STATUS_RELEASED,
);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages([
'items' => __('api.purchase.inconsistent_reservation'),
]);
}
}
if (! $cart->trashed()) {
$cart->update(['status' => 'converted']);
$cart->delete();
} }
} }
@@ -129,6 +175,15 @@ class ReleaseCheckoutService
private function loadPurchase(Purchase $purchase): Purchase 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; namespace App\Domains\Purchase\Services\Checkout;
use App\Domains\Cart\Models\Cart; use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
class SourceCartService 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( public function syncItemQuantity(
Purchase $purchase, Purchase $purchase,
PurchaseItem $purchaseItem, PurchaseItem $purchaseItem,
@@ -71,6 +24,71 @@ class SourceCartService
->update(['cantidad' => $quantity]); ->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 public function finalize(Purchase $purchase): void
{ {
$sourceCart = $this->findSourceCart($purchase); $sourceCart = $this->findSourceCart($purchase);
@@ -98,28 +116,4 @@ class SourceCartService
->lockForUpdate() ->lockForUpdate()
->first(); ->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\CatalogItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService; use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Exceptions\InsufficientStockException; use App\Domains\Purchase\Exceptions\InsufficientStockException;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\UserPurchaseLimitService; use App\Domains\Purchase\Services\UserPurchaseLimitService;
@@ -20,10 +21,11 @@ class StartCheckoutService
{ {
public function __construct( public function __construct(
private readonly CatalogInventoryService $inventory, private readonly CatalogInventoryService $inventory,
private readonly StockReservationService $reservations,
private readonly UserPurchaseLimitService $purchaseLimits, private readonly UserPurchaseLimitService $purchaseLimits,
private readonly CatalogSelectionResolver $selections, private readonly CatalogSelectionResolver $selections,
private readonly PurchaseItemSnapshotFactory $snapshots,
private readonly InsufficientStockMessageBuilder $stockMessages, private readonly InsufficientStockMessageBuilder $stockMessages,
private readonly PurchaseResponseLoader $responses,
) {} ) {}
/** @param array<string, mixed> $purchaseData */ /** @param array<string, mixed> $purchaseData */
@@ -118,10 +120,16 @@ class StartCheckoutService
->each(function (Collection $catalogLines) use ($userId): void { ->each(function (Collection $catalogLines) use ($userId): void {
/** @var CatalogItem $catalogItem */ /** @var CatalogItem $catalogItem */
$catalogItem = $catalogLines->first()['catalog_item']; $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( $this->purchaseLimits->assertCanPurchase(
$catalogItem, $catalogItem,
$userId, $userId,
(int) $catalogLines->sum('quantity'), (int) $catalogLines->sum('quantity'),
maximumAddableCeiling: $maximumAddableCeiling,
field: 'direct_items', field: 'direct_items',
); );
}); });
@@ -144,9 +152,24 @@ class StartCheckoutService
throw new InsufficientStockException($unavailableItems); 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) { foreach ($resolvedLines as $line) {
$cartItem = $cart->items()->create([
'catalog_item_id' => $line['catalog_item_id'],
'variant_id' => $line['variant_id'],
'cantidad' => $line['quantity'],
]);
try { try {
$this->inventory->reserve($line['selection'], $line['quantity']); $this->reservations->reserve($cartItem, $line['selection'], $line['quantity']);
} catch (\InvalidArgumentException) { } catch (\InvalidArgumentException) {
$availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0; $availableQuantity = $this->inventory->availableQuantity($line['selection']) ?? 0;
@@ -154,6 +177,10 @@ class StartCheckoutService
$this->unavailableItem($line, $availableQuantity), $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( $purchase = $this->createPurchase(
@@ -163,19 +190,16 @@ class StartCheckoutService
(float) $resolvedLines->sum( (float) $resolvedLines->sum(
fn (array $line): float => $line['selection']->getPrice() * $line['quantity'], fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
), ),
null, $cart->getKey(),
); );
$directCartItems = $resolvedLines->map(fn (array $line): CartItem => $this->makeDirectCartItem( foreach ($cartItems as $index => $cartItem) {
$line['selection'], $this->reservations->attachToPurchase(
$line['catalog_item_id'], $cartItem,
$line['variant_id'], $resolvedLines->get($index)['selection'],
$line['quantity'], $purchase,
)); );
}
$purchase->items()->createMany(
$this->snapshots->fromCartItems($directCartItems),
);
return $this->loadPurchase($purchase); return $this->loadPurchase($purchase);
} }
@@ -225,7 +249,7 @@ class StartCheckoutService
$this->loadCartItems($cartItems); $this->loadCartItems($cartItems);
$this->verifyTenantItems($tenant, $cartItems); $this->verifyTenantItems($tenant, $cartItems);
$this->assertCartPurchaseLimits($tenant, $userId, $cartItems); $this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
$cart->setRelation('items', $cartItems); $cart->setRelation('items', $cartItems);
$purchase = $this->createPurchase( $purchase = $this->createPurchase(
@@ -235,7 +259,13 @@ class StartCheckoutService
$cart->getTotalAmount(), $cart->getTotalAmount(),
$cart->getKey(), $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 // The purchase owns the reservation until checkout finishes. The cart is
// retained so it can be restored if the purchase is cancelled or expires. // retained so it can be restored if the purchase is cancelled or expires.
@@ -288,6 +318,7 @@ class StartCheckoutService
Tenant $tenant, Tenant $tenant,
int $userId, int $userId,
Collection $cartItems, Collection $cartItems,
int $cartId,
): void { ): void {
$quantities = $cartItems $quantities = $cartItems
->groupBy('catalog_item_id') ->groupBy('catalog_item_id')
@@ -309,6 +340,8 @@ class StartCheckoutService
$catalogItem, $catalogItem,
$userId, $userId,
$quantity, $quantity,
excludedCartId: $cartId,
heldQuantity: $quantity,
field: 'cart_id', 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 */ /** @param Collection<int, CartItem> $cartItems */
private function loadCartItems(Collection $cartItems): void private function loadCartItems(Collection $cartItems): void
{ {
@@ -382,6 +386,6 @@ class StartCheckoutService
private function loadPurchase(Purchase $purchase): Purchase 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; namespace App\Domains\Purchase\Services;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService; use App\Domains\Purchase\Services\Checkout\CompleteCheckoutService;
@@ -23,6 +24,7 @@ class CheckoutService
private readonly EditCheckoutService $editor, private readonly EditCheckoutService $editor,
private readonly CompleteCheckoutService $completer, private readonly CompleteCheckoutService $completer,
private readonly ReleaseCheckoutService $releaser, private readonly ReleaseCheckoutService $releaser,
private readonly StockReservationService $reservations,
) {} ) {}
/** @param array<string, mixed> $purchaseData */ /** @param array<string, mixed> $purchaseData */
@@ -47,12 +49,20 @@ class CheckoutService
return $this->editor->updateCustomer($purchase, $customerData); return $this->editor->updateCustomer($purchase, $customerData);
} }
public function updateItemQuantity( public function updateItem(
Purchase $purchase, Purchase $purchase,
PurchaseItem $purchaseItem, PurchaseItem $purchaseItem,
int $quantity, ?int $quantity,
?int $variantId,
bool $updateVariant,
): Purchase { ): Purchase {
return $this->editor->updateItemQuantity($purchase, $purchaseItem, $quantity); return $this->editor->updateItem(
$purchase,
$purchaseItem,
$quantity,
$variantId,
$updateVariant,
);
} }
public function prepareItemEditing(Purchase $purchase): Purchase public function prepareItemEditing(Purchase $purchase): Purchase
@@ -60,6 +70,11 @@ class CheckoutService
return $this->editor->prepareItemEditing($purchase); return $this->editor->prepareItemEditing($purchase);
} }
public function removeItem(Purchase $purchase, PurchaseItem $purchaseItem): Purchase
{
return $this->editor->removeItem($purchase, $purchaseItem);
}
public function confirmPurchase(Purchase $purchase): void public function confirmPurchase(Purchase $purchase): void
{ {
$this->completer->confirm($purchase); $this->completer->confirm($purchase);
@@ -94,4 +109,9 @@ class CheckoutService
{ {
return $this->releaser->expireOverdue(); 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; namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class UserPurchaseLimitService class UserPurchaseLimitService
{ {
@@ -15,6 +17,9 @@ class UserPurchaseLimitService
int $userId, int $userId,
int $requestedQuantity, int $requestedQuantity,
?int $excludedPurchaseId = null, ?int $excludedPurchaseId = null,
?int $excludedCartId = null,
int $heldQuantity = 0,
?int $maximumAddableCeiling = null,
string $field = 'quantity', string $field = 'quantity',
): void { ): void {
DB::transaction(function () use ( DB::transaction(function () use (
@@ -22,6 +27,9 @@ class UserPurchaseLimitService
$userId, $userId,
$requestedQuantity, $requestedQuantity,
$excludedPurchaseId, $excludedPurchaseId,
$excludedCartId,
$heldQuantity,
$maximumAddableCeiling,
$field, $field,
): void { ): void {
/** @var CatalogItem $catalogItem */ /** @var CatalogItem $catalogItem */
@@ -52,11 +60,112 @@ class UserPurchaseLimitService
}) })
->sum('cantidad'); ->sum('cantidad');
if ($purchasedQuantity + $requestedQuantity > $limit) { $checkoutQuantity = (int) CartItem::query()
throw ValidationException::withMessages([ ->where('catalog_item_id', $catalogItem->getKey())
$field => __('api.purchase_limit.exceeded', ['max' => $limit]), ->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 ## 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 ## Modelo
- `Purchase`: raíz de la compra; estados `created`, `pending_payment`, `paid`, `cancelled`, `rejected` y `expired`. - `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. - `TelepagosQr` y `TelepagosPayment`: datos del QR e intentos/resultados del proveedor.
- `PurchasePaid`: evento emitido una sola vez al pasar a pagada bajo bloqueo transaccional. - `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: `CheckoutService` es la fachada estable. Delega en:
- `StartCheckoutService`: inicia la compra desde el carrito. - `StartCheckoutService`: inicia la compra desde el carrito o crea un carrito técnico para compra directa, sin crear todavía `PurchaseItem`.
- `EditCheckoutService`: modifica cliente o cantidades antes del cierre. - `EditCheckoutService`: modifica los datos del comprador antes del cierre.
- `CompleteCheckoutService`: completa, envía a revisión o confirma el pago. - `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar el pago.
- `ReleaseCheckoutService`: cancela, vence y procesa vencimientos pendientes. - `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. - `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. `UserPurchaseLimitService` controla límites de compra y `CheckoutService` conserva el punto de entrada para controladores e integraciones.
## Endpoints ## 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::post('compras/start-checkout', [PurchaseController::class, 'startCheckout']);
Route::get('compras/{compra}', [PurchaseController::class, 'show']); Route::get('compras/{compra}', [PurchaseController::class, 'show']);
Route::post('compras/{compra}/edit-items', [PurchaseController::class, 'prepareItemEditing']); 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::patch('compras/{compra}/customer-data', [PurchaseController::class, 'updateCustomerData']);
Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']); Route::post('compras/{compra}/payment-intent', [PurchaseController::class, 'paymentIntent']);
Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']); Route::post('compras/{compra}/complete', [PurchaseController::class, 'complete']);

View File

@@ -2,10 +2,12 @@
namespace App\Domains\Sale\Resources\AdminApp; namespace App\Domains\Sale\Resources\AdminApp;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem; use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
/** @mixin Purchase */ /** @mixin Purchase */
class SaleDetailResource extends JsonResource class SaleDetailResource extends JsonResource
@@ -13,23 +15,44 @@ class SaleDetailResource extends JsonResource
/** @return array<string, mixed> */ /** @return array<string, mixed> */
public function toArray(Request $request): array public function toArray(Request $request): array
{ {
$items = $this->saleItems();
return [ return [
'id' => $this->id, 'id' => $this->id,
'items' => $this->items->map(fn (PurchaseItem $item): array => [ 'items' => $items->map(fn (PurchaseItem|CartItem $item): array => [
'id' => $item->id, 'id' => $item->id,
'product' => $item->item_nombre, 'product' => $item instanceof PurchaseItem
? $item->item_nombre
: $item->selectedItem()?->getName(),
'event_dates' => $this->eventDates($item), 'event_dates' => $this->eventDates($item),
'quantity' => (int) $item->cantidad, 'quantity' => (int) $item->cantidad,
'unit_price' => $this->formatMoney($item->precio_unitario), 'unit_price' => $this->formatMoney($this->unitPrice($item)),
'total' => $this->formatMoney($item->total), 'total' => $this->formatMoney($this->lineTotal($item)),
])->values(), ])->values(),
'total' => $this->formatMoney($this->total), 'total' => $this->formatMoney($this->total),
]; ];
} }
/** @return list<string> */ /** @return Collection<int, PurchaseItem|CartItem> */
private function eventDates(PurchaseItem $item): array 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 ?? []) return collect($item->variant_attributes ?? [])
->filter(fn (mixed $attribute): bool => is_array($attribute) ->filter(fn (mixed $attribute): bool => is_array($attribute)
&& mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha') && mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
@@ -43,6 +66,20 @@ class SaleDetailResource extends JsonResource
->all(); ->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 private function formatMoney(float|int|string|null $amount): string
{ {
return number_format((float) ($amount ?? 0), 2, '.', ''); return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -51,7 +51,14 @@ class AdminAppSaleService
{ {
return Purchase::query() return Purchase::query()
->where('tenant_codigo', $tenant->codigo) ->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); ->findOrFail($saleId);
} }
@@ -145,7 +152,18 @@ class AdminAppSaleService
$filters['status'] ?? null, $filters['status'] ?? null,
fn (Builder $query, string $status): Builder => $query->where('status', $status) 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') ->withCount('tickets')
->orderBy($sortColumns[$sortBy], $sortDirection) ->orderBy($sortColumns[$sortBy], $sortDirection)
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id')); ->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
@@ -171,8 +189,28 @@ class AdminAppSaleService
protected function saleForResponse(Purchase $sale): Purchase protected function saleForResponse(Purchase $sale): Purchase
{ {
return $sale->refresh() /** @var Purchase */
->loadSum('items as quantity', 'cantidad') return Purchase::query()
->loadCount('tickets'); ->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\Event\Models\EventDate;
use App\Domains\Menu\Models\Menu; use App\Domains\Menu\Models\Menu;
use App\Domains\Menu\Models\TenantMenu; use App\Domains\Menu\Models\TenantMenu;
use App\Domains\Tenant\Enums\CartEditingPolicy;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -26,6 +27,8 @@ use Illuminate\Support\Facades\Schema;
'dominio', 'dominio',
'base_path', 'base_path',
'site_title', 'site_title',
'address',
'phone',
'primary_color', 'primary_color',
'secondary_color', 'secondary_color',
'danger_color', 'danger_color',
@@ -44,7 +47,8 @@ use Illuminate\Support\Facades\Schema;
'display_categories', 'display_categories',
'display_seach_bar', 'display_seach_bar',
'display_cart', 'display_cart',
'cart_editing_enabled', 'cart_editing_policy',
'checkout_editing_policy',
'display_cart_item_images', 'display_cart_item_images',
'scanner_category_validation_enabled', 'scanner_category_validation_enabled',
'event_title', 'event_title',
@@ -63,7 +67,8 @@ class Tenant extends Model
'display_categories' => true, 'display_categories' => true,
'display_seach_bar' => true, 'display_seach_bar' => true,
'display_cart' => 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, 'display_cart_item_images' => true,
'scanner_category_validation_enabled' => true, 'scanner_category_validation_enabled' => true,
]; ];
@@ -114,7 +119,8 @@ class Tenant extends Model
'display_categories' => 'boolean', 'display_categories' => 'boolean',
'display_seach_bar' => 'boolean', 'display_seach_bar' => 'boolean',
'display_cart' => 'boolean', 'display_cart' => 'boolean',
'cart_editing_enabled' => 'boolean', 'cart_editing_policy' => CartEditingPolicy::class,
'checkout_editing_policy' => CartEditingPolicy::class,
'display_cart_item_images' => 'boolean', 'display_cart_item_images' => 'boolean',
'scanner_category_validation_enabled' => '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\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout; use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Shared\Rules\ImageOrBase64Rule; use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Enums\CartEditingPolicy;
use App\Domains\Tenant\Services\WebsiteExtraService; use App\Domains\Tenant\Services\WebsiteExtraService;
use App\Domains\Tenant\Support\TenantDomainNormalizer; use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Closure; use Closure;
@@ -81,6 +82,8 @@ class StoreTenantRequest extends FormRequest
->where('dominio', $this->input('dominio')), ->where('dominio', $this->input('dominio')),
], ],
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'], '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})$/'], '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})$/'], '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})$/'], '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_categories' => ['sometimes', 'boolean'],
'display_seach_bar' => ['sometimes', 'boolean'], 'display_seach_bar' => ['sometimes', 'boolean'],
'display_cart' => ['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'], 'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['sometimes', 'boolean'], 'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
'website_type_code' => [ '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\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout; use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Shared\Rules\ImageOrBase64Rule; use App\Domains\Shared\Rules\ImageOrBase64Rule;
use App\Domains\Tenant\Enums\CartEditingPolicy;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Support\TenantDomainNormalizer; use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Closure; use Closure;
@@ -102,6 +103,8 @@ class UpdateTenantRequest extends FormRequest
->ignore($tenant?->id), ->ignore($tenant?->id),
], ],
'site_title' => ['sometimes', 'nullable', 'string', 'max:255'], '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})$/'], '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})$/'], '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})$/'], '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_categories' => ['sometimes', 'boolean'],
'display_seach_bar' => ['sometimes', 'boolean'], 'display_seach_bar' => ['sometimes', 'boolean'],
'display_cart' => ['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'], 'display_cart_item_images' => ['sometimes', 'boolean'],
'scanner_category_validation_enabled' => ['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 'site_title' => $this->site_title
?? $this->websiteType?->site_title ?? $this->websiteType?->site_title
?? 'ShopitFront', ?? 'ShopitFront',
'address' => $this->address,
'phone' => $this->phone,
'favicon' => ($this->favicon ?? $this->websiteType?->favicon) 'favicon' => ($this->favicon ?? $this->websiteType?->favicon)
?->getTemporaryUrl(1440), ?->getTemporaryUrl(1440),
'primary_color' => $this->primary_color, 'primary_color' => $this->primary_color,
@@ -75,7 +77,8 @@ class TenantResource extends JsonResource
'display_categories' => $this->display_categories, 'display_categories' => $this->display_categories,
'display_seach_bar' => $this->display_seach_bar, 'display_seach_bar' => $this->display_seach_bar,
'display_cart' => $this->display_cart, '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, 'display_cart_item_images' => $this->display_cart_item_images,
'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled, 'scanner_category_validation_enabled' => $this->scanner_category_validation_enabled,
'social_media' => $this->whenLoaded( 'social_media' => $this->whenLoaded(

View File

@@ -29,19 +29,27 @@ class TicketPresentationResolver
return $catalogItem->nombre; return $catalogItem->nombre;
} }
$properties = $variant->selectionOptions() $itemAttributes = $variant->catalogItem->itemAttributes;
->flatMap(function (array $option): array { $properties = $variant->selectionOptions($itemAttributes)
if (array_is_list($option)) { ->map(function (array $option, string $attributeCode) use ($itemAttributes): ?string {
return collect($option) $labels = collect(array_is_list($option) ? $option : [$option])
->pluck('label') ->pluck('label')
->filter(fn ($label): bool => is_string($label) && $label !== '') ->filter(fn ($label): bool => is_string($label) && $label !== '')
->all(); ->implode(', ');
if ($labels === '') {
return null;
} }
$label = $option['label'] ?? null; $ticketLabel = $itemAttributes->first(
fn ($itemAttribute): bool => $itemAttribute->attribute?->codigo === $attributeCode,
)?->ticket_label;
return is_string($label) && $label !== '' ? [$label] : []; return is_string($ticketLabel) && trim($ticketLabel) !== ''
? trim($ticketLabel).' '.$labels
: $labels;
}) })
->filter()
->values(); ->values();
return $properties->isEmpty() return $properties->isEmpty()

View File

@@ -2,6 +2,8 @@
use App\Domains\Auth\Exceptions\AccountLockedException; use App\Domains\Auth\Exceptions\AccountLockedException;
use App\Domains\Purchase\Exceptions\InsufficientStockException; 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\Domains\Ticket\Exceptions\TicketNotAvailableException;
use App\Http\Middleware\EnsureAdminAppTenant; use App\Http\Middleware\EnsureAdminAppTenant;
use App\Http\Middleware\EnsureScannerTenant; use App\Http\Middleware\EnsureScannerTenant;
@@ -87,6 +89,30 @@ return Application::configure(basePath: dirname(__DIR__))
'unavailable_items' => $exception->unavailableItems, 'unavailable_items' => $exception->unavailableItems,
], 422); ], 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) { $exceptions->render(function (ModelNotFoundException $exception, Request $request) {
if (! $request->is('api/*')) { if (! $request->is('api/*')) {
return null; 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, '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' => [ 'slack' => [
'driver' => 'slack', 'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'), '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,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('item_attributes', function (Blueprint $table): void {
$table->string('ticket_label', 100)->nullable()->after('show_in_selector');
});
foreach (['sector' => 'Lado', 'fila' => 'Fila', 'asiento' => 'Asiento'] as $code => $label) {
$itemAttributeIds = DB::table('item_attributes')
->join('catalog_items', 'catalog_items.id', '=', 'item_attributes.catalog_item_id')
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
->where('catalog_items.tenant_code', 'desfile_pura_tendencia')
->where('attribute.codigo', $code)
->pluck('item_attributes.id');
DB::table('item_attributes')
->whereIn('id', $itemAttributeIds)
->update(['ticket_label' => $label]);
}
}
public function down(): void
{
Schema::table('item_attributes', function (Blueprint $table): void {
$table->dropColumn('ticket_label');
});
}
};

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\Models\FeaturedGroup;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Client\Models\Client; use App\Domains\Client\Models\Client;
use App\Domains\Desfile\Services\InvitationPurchaseProvisioner;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantService; use App\Domains\Tenant\Services\TenantService;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
@@ -28,6 +29,7 @@ class DesfilePuraTendenciaSeeder extends Seeder
public function __construct( public function __construct(
private readonly TenantService $tenantService, private readonly TenantService $tenantService,
private readonly CatalogService $catalogService, private readonly CatalogService $catalogService,
private readonly InvitationPurchaseProvisioner $invitationPurchaseProvisioner,
) {} ) {}
public function run(): void public function run(): void
@@ -41,15 +43,15 @@ class DesfilePuraTendenciaSeeder extends Seeder
if ($tenant) { if ($tenant) {
$tenant->update(['client_id' => $client->id]); $tenant->update(['client_id' => $client->id]);
} else {
return; DB::transaction(function () use ($client): void {
$this->createTenant($client);
$this->createEventDate();
$this->createEntryCatalog();
});
} }
DB::transaction(function () use ($client): void { $this->invitationPurchaseProvisioner->provision();
$this->createTenant($client);
$this->createEventDate();
$this->createEntryCatalog();
});
} }
private function createTenant(Client $client): void private function createTenant(Client $client): void
@@ -72,7 +74,8 @@ class DesfilePuraTendenciaSeeder extends Seeder
'display_categories' => false, 'display_categories' => false,
'display_seach_bar' => false, 'display_seach_bar' => false,
'display_cart' => true, 'display_cart' => true,
'cart_editing_enabled' => false, 'cart_editing_policy' => 'full',
'checkout_editing_policy' => 'disabled',
'display_cart_item_images' => false, 'display_cart_item_images' => false,
'scanner_category_validation_enabled' => false, 'scanner_category_validation_enabled' => false,
'website_type_code' => 'onticket', 'website_type_code' => 'onticket',
@@ -170,6 +173,11 @@ class DesfilePuraTendenciaSeeder extends Seeder
'inventory_subject' => InventorySubject::Seat->value, 'inventory_subject' => InventorySubject::Seat->value,
'has_tickets' => true, 'has_tickets' => true,
'attribute_codes' => array_keys($attributes), 'attribute_codes' => array_keys($attributes),
'ticket_attribute_labels' => [
'sector' => 'Lado',
'fila' => 'Fila',
'asiento' => 'Asiento',
],
'variants' => $this->entryVariants(), 'variants' => $this->entryVariants(),
'images' => [ 'images' => [
$this->uploadedImage( $this->uploadedImage(

View File

@@ -75,6 +75,8 @@ class TenantSeeder extends Seeder
'display_categories' => true, 'display_categories' => true,
'display_seach_bar' => true, 'display_seach_bar' => true,
'display_cart' => 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'), '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'), 'footer_logo' => $this->uploadedImage('images/tennants/sonder/sonder_footer.png', 'sonder_footer.png'),
'social_media' => self::SOCIAL_MEDIA, 'social_media' => self::SOCIAL_MEDIA,
@@ -131,6 +133,8 @@ class TenantSeeder extends Seeder
'display_categories' => false, 'display_categories' => false,
'display_seach_bar' => false, 'display_seach_bar' => false,
'display_cart' => true, 'display_cart' => true,
'cart_editing_policy' => 'full',
'checkout_editing_policy' => 'disabled',
'header_logo' => $this->uploadedImage( 'header_logo' => $this->uploadedImage(
'images/tennants/fiesta_futbol_infantil/futbol_infantil_header.png', 'images/tennants/fiesta_futbol_infantil/futbol_infantil_header.png',
'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.', 'google_email_unverified' => 'The Google account must have a verified email.',
], ],
'cart' => [ 'cart' => [
'editing_disabled' => 'Cart editing is disabled.',
'variant_change_disabled' => 'Variant changes are disabled for this cart.',
'item_added' => 'Product added to cart.', 'item_added' => 'Product added to cart.',
'quantity_updated' => 'Product quantity updated.', 'quantity_updated' => 'Product quantity updated.',
'item_updated' => 'Product updated.', 'item_updated' => 'Product updated.',
@@ -34,10 +36,11 @@ return [
'variant_required' => 'You must select a variant for this item.', 'variant_required' => 'You must select a variant for this item.',
], ],
'purchase' => [ '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.', 'source_required' => 'A cart or direct item is required.',
'payment_method_required' => 'The purchase payment method must be selected before finalizing.', 'payment_method_required' => 'The purchase payment method must be selected before finalizing.',
'not_editable' => 'The purchase is no longer editable.', '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.', 'insufficient_stock' => 'There is not enough stock available.',
'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.', 'cannot_confirm' => 'A cancelled, rejected, or expired purchase cannot be confirmed.',
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.', '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.', 'not_available_for_review' => 'The purchase is no longer available for review.',
], ],
'purchase_limit' => [ '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' => [ 'ticket' => [
'not_available' => 'One or more tickets are not available.', 'not_available' => 'One or more tickets are not available.',
@@ -112,6 +115,7 @@ return [
'event_date_attribute_required' => 'The event_date attribute is required for event date variants.', 'event_date_attribute_required' => 'The event_date attribute is required for event date variants.',
'multi_select_attribute_not_on_item' => 'Multi-select attributes must also be present in attribute_codes.', 'multi_select_attribute_not_on_item' => 'Multi-select attributes must also be present in attribute_codes.',
'hidden_attribute_not_on_item' => 'Hidden attributes must also be present in attribute_codes.', 'hidden_attribute_not_on_item' => 'Hidden attributes must also be present in attribute_codes.',
'ticket_label_attribute_not_on_item' => 'Ticket-label attributes must also be present in attribute_codes.',
'event_date_selection_required' => 'At least one event date must be selected.', 'event_date_selection_required' => 'At least one event date must be selected.',
'single_event_date_required' => 'Exactly one event date must be selected.', 'single_event_date_required' => 'Exactly one event date must be selected.',
'event_date_wrong_tenant' => 'Every event date must belong to the catalog item tenant.', 'event_date_wrong_tenant' => 'Every event date must belong to the catalog item tenant.',

View File

@@ -22,6 +22,8 @@ return [
'google_email_unverified' => 'La cuenta de Google debe tener el email verificado.', 'google_email_unverified' => 'La cuenta de Google debe tener el email verificado.',
], ],
'cart' => [ '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.', 'item_added' => 'Producto agregado al carrito.',
'quantity_updated' => 'Cantidad de producto actualizada.', 'quantity_updated' => 'Cantidad de producto actualizada.',
'item_updated' => 'Producto actualizado.', 'item_updated' => 'Producto actualizado.',
@@ -34,10 +36,11 @@ return [
'variant_required' => 'Debe seleccionar una variante para este ítem.', 'variant_required' => 'Debe seleccionar una variante para este ítem.',
], ],
'purchase' => [ '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.', '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.', 'payment_method_required' => 'Debes seleccionar el método de pago antes de finalizar la compra.',
'not_editable' => 'La compra ya no se puede modificar.', '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.', 'insufficient_stock' => 'No hay suficiente stock disponible.',
'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.', 'cannot_confirm' => 'Una compra cancelada, rechazada o vencida no se puede confirmar.',
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.', '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.", 'not_available_for_review' => "La compra ya no est\u{00E1} disponible para revisi\u{00F3}n.",
], ],
'purchase_limit' => [ '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' => [ 'ticket' => [
'not_available' => 'Uno o más tickets no están disponibles.', 'not_available' => 'Uno o más tickets no están disponibles.',
@@ -112,6 +115,7 @@ return [
'event_date_attribute_required' => 'El atributo event_date es obligatorio para las variantes con fecha de evento.', 'event_date_attribute_required' => 'El atributo event_date es obligatorio para las variantes con fecha de evento.',
'multi_select_attribute_not_on_item' => 'Los atributos multiselección también deben estar incluidos en attribute_codes.', 'multi_select_attribute_not_on_item' => 'Los atributos multiselección también deben estar incluidos en attribute_codes.',
'hidden_attribute_not_on_item' => 'Los atributos ocultos también deben estar incluidos en attribute_codes.', 'hidden_attribute_not_on_item' => 'Los atributos ocultos también deben estar incluidos en attribute_codes.',
'ticket_label_attribute_not_on_item' => 'Los atributos con etiqueta de ticket también deben estar incluidos en attribute_codes.',
'event_date_selection_required' => 'Debe seleccionar al menos una fecha de evento.', 'event_date_selection_required' => 'Debe seleccionar al menos una fecha de evento.',
'single_event_date_required' => 'Debe seleccionar exactamente una fecha de evento.', 'single_event_date_required' => 'Debe seleccionar exactamente una fecha de evento.',
'event_date_wrong_tenant' => 'Todas las fechas del evento deben pertenecer al tenant del ítem de catálogo.', 'event_date_wrong_tenant' => 'Todas las fechas del evento deben pertenecer al tenant del ítem de catálogo.',

View File

@@ -8,7 +8,6 @@ declare(strict_types=1);
* Run from the backend root with: * Run from the backend root with:
* php postman/generate-shopit-collection.php * php postman/generate-shopit-collection.php
*/ */
$root = dirname(__DIR__); $root = dirname(__DIR__);
chdir($root); chdir($root);
@@ -38,7 +37,7 @@ function jsonBody(array $payload): array
} }
/** @param array<string, string> $fields /** @param array<string, string> $fields
* @return array<string, mixed> * @return array<string, mixed>
*/ */
function formDataBody(array $fields, array $fileFields = []): array function formDataBody(array $fields, array $fileFields = []): array
{ {
@@ -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}/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}}'], '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}/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}/compras/{compra}/payment-intent' => ['method' => 'transfer', 'transfer_payer_dni' => '30123456'],
'POST api/tenants/{tenant:codigo}/tickets/pdf' => ['ticket_ids' => [1]], 'POST api/tenants/{tenant:codigo}/tickets/pdf' => ['ticket_ids' => [1]],
'POST api/v1/adminapp/login' => ['email' => '{{admin_email}}', 'password' => '{{admin_password}}'], '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_categories' => true,
'display_seach_bar' => true, 'display_seach_bar' => true,
'display_cart' => true, 'display_cart' => true,
'cart_editing_enabled' => true, 'cart_editing_policy' => 'full',
'website_type_code' => 'shopit', 'website_type_code' => 'shopit',
]); ]);
} }
if (in_array($key, ['PUT api/tenants/{tenant}', 'PATCH api/tenants/{tenant}'], true)) { 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') { if ($key === 'POST api/tenants/{tenant:codigo}/catalog-items') {
@@ -245,10 +244,11 @@ function requestName(string $method, string $action, bool $multiMethod): string
$verbs = [ $verbs = [
'index' => 'List', 'store' => 'Create', 'show' => 'Get', 'update' => 'Update', 'index' => 'List', 'store' => 'Create', 'show' => 'Get', 'update' => 'Update',
'destroy' => 'Delete', 'addItem' => 'Add Item', 'updateItemQuantity' => 'Update Item Quantity', 'destroy' => 'Delete', 'addItem' => 'Add Item', 'updateItemQuantity' => 'Update Item Quantity',
'updateItem' => 'Update Item',
'removeItem' => 'Remove Item', 'search' => 'Search', 'category' => 'Get Category', 'removeItem' => 'Remove Item', 'search' => 'Search', 'category' => 'Get Category',
'featuredGroupItems' => 'List Featured Group Items', 'variantOptions' => 'Get Variant Options', 'featuredGroupItems' => 'List Featured Group Items', 'variantOptions' => 'Get Variant Options',
'startCheckout' => 'Start Checkout', 'updateCustomerData' => 'Update Customer Data', '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', 'submitForReview' => 'Submit for Review', 'cancel' => 'Cancel', 'complete' => 'Complete',
'downloadPdf' => 'Download PDF', 'downloadModificationsPdf' => 'Download Modifications PDF', 'downloadPdf' => 'Download PDF', 'downloadModificationsPdf' => 'Download Modifications PDF',
'modifications' => 'List Modifications', 'tickets' => 'List Tickets', 'confirm' => 'Confirm', 'modifications' => 'List Modifications', 'tickets' => 'List Tickets', 'confirm' => 'Confirm',

View File

@@ -1,6 +1,8 @@
<?php <?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\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule; use Illuminate\Support\Facades\Schedule;
@@ -9,13 +11,74 @@ Artisan::command('inspire', function () {
$this->comment(Inspiring::quote()); $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote'); })->purpose('Display an inspiring quote');
Artisan::command('purchases:expire', function (): void { Artisan::command('reservations:expire', function (): void {
$expiredCount = app(CheckoutService::class) $expired = app(ExpireStockReservationsService::class)->expireOverdue();
->expireOverduePurchases();
$this->info("Expired purchases: {$expiredCount}"); $this->info("Expired purchases: {$expired['purchases']}");
})->purpose('Release stock reservations from 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() ->everyMinute()
->withoutOverlapping(); ->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->isSecure());
$this->assertTrue($guestTokenCookie->isHttpOnly()); $this->assertTrue($guestTokenCookie->isHttpOnly());
$this->assertSame('none', $guestTokenCookie->getSameSite()); $this->assertSame('none', $guestTokenCookie->getSameSite());
$this->assertTrue($guestTokenCookie->isPartitioned());
$this->assertDatabaseHas('carrito_items', [ $this->assertDatabaseHas('carrito_items', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
@@ -73,6 +74,87 @@ class CartControllerTest extends TestCase
'id' => $item->inventory_id, 'id' => $item->inventory_id,
'reserved_stock' => 2, '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 public function test_it_filters_item_images_when_the_tenant_disables_them(): void
@@ -121,6 +203,7 @@ class CartControllerTest extends TestCase
->assertOk() ->assertOk()
->assertJsonPath('data.items.0.catalog_item_id', $item->id) ->assertJsonPath('data.items.0.catalog_item_id', $item->id)
->assertJsonPath('data.items.0.variant_id', $variant->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.items.0.cantidad', 5)
->assertJsonPath('data.subtotal', '125.00'); ->assertJsonPath('data.subtotal', '125.00');
@@ -129,6 +212,12 @@ class CartControllerTest extends TestCase
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 5, '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 public function test_authenticated_cart_respects_previous_purchases_and_repeated_additions(): void
@@ -153,7 +242,15 @@ class CartControllerTest extends TestCase
'cantidad' => 2, 'cantidad' => 2,
]) ])
->assertUnprocessable() ->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', [ $this->assertDatabaseHas('carrito_items', [
'catalog_item_id' => $item->id, 'catalog_item_id' => $item->id,
@@ -283,6 +380,12 @@ class CartControllerTest extends TestCase
'id' => $variant->inventory_id, 'id' => $variant->inventory_id,
'reserved_stock' => 0, '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 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 public function test_it_requires_a_variant_when_the_item_has_variant_inventory(): void
{ {
$tenant = $this->createTenant('acme'); $tenant = $this->createTenant('acme');
@@ -506,7 +686,6 @@ class CartControllerTest extends TestCase
'cantidad' => $quantity, 'cantidad' => $quantity,
'precio_unitario' => $item->precio, 'precio_unitario' => $item->precio,
'total' => (float) $item->precio * $quantity, '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}") $this->getJson("/api/tenants/{$this->tenant->codigo}/catalog-items/{$bundleId}")
->assertOk() ->assertOk()
->assertJsonPath('data.type', CatalogItemType::Bundle->value) ->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') ->assertJsonCount(1, 'data.components')
->assertJsonPath('data.components.0.catalog_item_id', $component->id) ->assertJsonPath('data.components.0.catalog_item_id', $component->id)
->assertJsonPath('data.components.0.variant_id', null) ->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\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; 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\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout; use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout; use App\Domains\Catalog\Enums\ProductLayout;
@@ -20,7 +22,7 @@ class CatalogControllerTest extends TestCase
{ {
use RefreshDatabase; 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'); $tenant = $this->createTenant('catalog-index');
$row = $this->createGroup($tenant, ProductLayout::Row, 'Row', 2); $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.nombre', 'Variants')
->assertJsonPath('0.items.0.descripcion', 'Variants description') ->assertJsonPath('0.items.0.descripcion', 'Variants description')
->assertJsonPath('0.items.0.precio', '100.00') ->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') ->assertJsonCount(2, '0.items.0.variants')
->assertJsonPath('0.items.0.variants.0.stock_tecnico', 4) ->assertJsonPath('0.items.0.variants.0.maximum_addable_quantity', 4)
->assertJsonPath('0.items.0.variants.1.stock_tecnico', 3) ->assertJsonPath('0.items.0.variants.1.maximum_addable_quantity', 3)
->assertJsonMissing(['id' => $unavailableVariant->id, 'stock_tecnico' => 0]) ->assertJsonMissing(['id' => $unavailableVariant->id])
->assertJsonPath('1.title', 'Row') ->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'); ->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 public function test_it_excludes_items_when_all_of_their_variants_are_out_of_stock(): void
{ {
$tenant = $this->createTenant('catalog-available-variants'); $tenant = $this->createTenant('catalog-available-variants');

View File

@@ -40,7 +40,8 @@ class CatalogItemDetailControllerTest extends TestCase
$response $response
->assertOk() ->assertOk()
->assertJsonPath('data.stock_tecnico', 7) ->assertJsonPath('data.maximum_addable_quantity', 7)
->assertJsonMissingPath('data.stock_tecnico')
->assertJsonCount(0, 'data.variants') ->assertJsonCount(0, 'data.variants')
->assertJsonCount(1, 'data.images'); ->assertJsonCount(1, 'data.images');
$response->assertJsonMissingPath('data.selected_variant'); $response->assertJsonMissingPath('data.selected_variant');
@@ -71,7 +72,8 @@ class CatalogItemDetailControllerTest extends TestCase
->assertJsonCount(1, 'data.variants') ->assertJsonCount(1, 'data.variants')
->assertJsonPath('data.variants.0.id', $secondVariant->id) ->assertJsonPath('data.variants.0.id', $secondVariant->id)
->assertJsonPath('data.selected_variant.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'); ->assertJsonCount(1, 'data.selected_variant.images');
$response $response
->assertJsonMissingPath('data.stock_tecnico') ->assertJsonMissingPath('data.stock_tecnico')
@@ -125,11 +127,11 @@ class CatalogItemDetailControllerTest extends TestCase
$response $response
->assertOk() ->assertOk()
->assertJsonPath('data.variants.0.id', $firstVariant->id) ->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.value', 'S')
->assertJsonPath('data.variants.0.values.size.label', 'Small') ->assertJsonPath('data.variants.0.values.size.label', 'Small')
->assertJsonPath('data.variants.1.id', $secondVariant->id) ->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.value', 'M')
->assertJsonPath('data.variants.1.values.size.label', 'Medium') ->assertJsonPath('data.variants.1.values.size.label', 'Medium')
->assertJsonPath('data.attributes.0.codigo', 'size') ->assertJsonPath('data.attributes.0.codigo', 'size')
@@ -137,7 +139,7 @@ class CatalogItemDetailControllerTest extends TestCase
->assertJsonPath('data.attributes.0.options.1.value', 'M') ->assertJsonPath('data.attributes.0.options.1.value', 'M')
->assertJsonCount(2, 'data.attributes.0.options') ->assertJsonCount(2, 'data.attributes.0.options')
->assertJsonPath('data.selected_variant.id', $secondVariant->id) ->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.value', 'M')
->assertJsonPath('data.selected_variant.values.size.label', 'Medium') ->assertJsonPath('data.selected_variant.values.size.label', 'Medium')
->assertJsonCount(1, 'data.selected_variant.images'); ->assertJsonCount(1, 'data.selected_variant.images');
@@ -177,9 +179,11 @@ class CatalogItemDetailControllerTest extends TestCase
$this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}") $this->getJson("/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}")
->assertOk() ->assertOk()
->assertJsonPath('data.selected_variant.id', $variant->id) ->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') ->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 public function test_it_exposes_event_dates_as_a_dynamic_variant_attribute(): void

View File

@@ -26,6 +26,7 @@ class CatalogSchemaTest extends TestCase
$this->assertTrue(Schema::hasTable('item_attributes')); $this->assertTrue(Schema::hasTable('item_attributes'));
$this->assertTrue(Schema::hasColumn('item_attributes', 'sort_order')); $this->assertTrue(Schema::hasColumn('item_attributes', 'sort_order'));
$this->assertTrue(Schema::hasColumn('item_attributes', 'show_in_selector')); $this->assertTrue(Schema::hasColumn('item_attributes', 'show_in_selector'));
$this->assertTrue(Schema::hasColumn('item_attributes', 'ticket_label'));
$this->assertTrue(Schema::hasTable('variant_values')); $this->assertTrue(Schema::hasTable('variant_values'));
} }

View File

@@ -196,6 +196,26 @@ class CatalogServiceTest extends TestCase
$this->assertFalse($item->itemAttributes->sole()->show_in_selector); $this->assertFalse($item->itemAttributes->sole()->show_in_selector);
} }
public function test_it_can_configure_an_attribute_label_for_ticket_names(): void
{
$attribute = $this->createAttribute('sector');
$item = $this->service->create([
'tenant_code' => $this->tenant->codigo,
'slug' => 'ticket-labeled-attribute-item',
'nombre' => 'Ticket labeled attribute item',
'precio' => 100,
'attribute_codes' => [$attribute->codigo],
'ticket_attribute_labels' => [$attribute->codigo => 'Lado'],
'variants' => [[
'real_stock' => 5,
'values' => [$attribute->codigo => 'A'],
]],
]);
$this->assertSame('Lado', $item->itemAttributes->sole()->ticket_label);
}
public function test_it_allows_the_same_event_date_with_different_attribute_values(): void public function test_it_allows_the_same_event_date_with_different_attribute_values(): void
{ {
$sector = $this->createAttribute('sector'); $sector = $this->createAttribute('sector');

View File

@@ -81,6 +81,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
'is_featured' => true, 'is_featured' => true,
]) ])
->assertCreated() ->assertCreated()
->assertJsonPath('data.code', 'food')
->assertJsonPath('data.category_name', 'Food') ->assertJsonPath('data.category_name', 'Food')
->assertJsonPath('data.group_name', 'Food') ->assertJsonPath('data.group_name', 'Food')
->assertJsonPath('data.is_featured', true) ->assertJsonPath('data.is_featured', true)
@@ -96,6 +97,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
]); ]);
$this->assertDatabaseHas('featured_groups', [ $this->assertDatabaseHas('featured_groups', [
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'code' => 'food',
'source_type' => 'category', 'source_type' => 'category',
'category_id' => $categoryId, 'category_id' => $categoryId,
'product_layout' => 'row', 'product_layout' => 'row',
@@ -130,6 +132,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
'is_featured' => true, 'is_featured' => true,
]) ])
->assertOk() ->assertOk()
->assertJsonPath('data.code', 'old-name')
->assertJsonPath('data.category_name', 'New name') ->assertJsonPath('data.category_name', 'New name')
->assertJsonPath('data.group_name', 'New name') ->assertJsonPath('data.group_name', 'New name')
->assertJsonPath('data.is_featured', true) ->assertJsonPath('data.is_featured', true)
@@ -142,6 +145,7 @@ class OnTicketFeaturedGroupControllerTest extends TestCase
]); ]);
$this->assertDatabaseHas('featured_groups', [ $this->assertDatabaseHas('featured_groups', [
'id' => $group->id, 'id' => $group->id,
'code' => 'old-name',
'group_name' => 'New name', 'group_name' => 'New name',
'product_layout' => 'row', 'product_layout' => 'row',
'group_layout' => 'paginated', 'group_layout' => 'paginated',

View File

@@ -285,15 +285,21 @@ class IntegrationServiceTest extends TestCase
'https://api.telepagos.com.ar/v2/auth/token' => Http::response([ 'https://api.telepagos.com.ar/v2/auth/token' => Http::response([
'status' => 'error', 'status' => 'error',
'message' => 'Invalid credentials', 'message' => 'Invalid credentials',
'token' => 'must-not-be-logged',
], 401), ], 401),
]); ]);
Log::shouldReceive('channel')->once()->with('telepagos')->andReturnSelf();
Log::shouldReceive('error') Log::shouldReceive('error')
->once() ->once()
->with('Telepagos authentication failed: Invalid credentials', \Mockery::on(function ($context) { ->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_status'] === 401
&& $context['response_body'] === ['status' => 'error', 'message' => 'Invalid credentials']; && $context['response_body'] === [
'status' => 'error',
'message' => 'Invalid credentials',
'token' => '[REDACTED]',
];
})); }));
$service = new TelepagosIntegrationService('telepagos'); $service = new TelepagosIntegrationService('telepagos');
@@ -442,6 +448,7 @@ class IntegrationServiceTest extends TestCase
], 422), ], 422),
]); ]);
Log::shouldReceive('channel')->once()->with('telepagos')->andReturnSelf();
Log::shouldReceive('error') Log::shouldReceive('error')
->once() ->once()
->with('Telepagos QR generation failed: Importe inválido', \Mockery::on(function ($context) { ->with('Telepagos QR generation failed: Importe inválido', \Mockery::on(function ($context) {
@@ -555,6 +562,7 @@ class IntegrationServiceTest extends TestCase
], 404), ], 404),
]); ]);
Log::shouldReceive('channel')->once()->with('telepagos')->andReturnSelf();
Log::shouldReceive('error') Log::shouldReceive('error')
->once() ->once()
->with('Telepagos get cash-in details failed: Cashin no encontrado', \Mockery::on(function ($context) { ->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\ClientIntegration;
use App\Domains\Integration\Models\Integration; use App\Domains\Integration\Models\Integration;
use App\Domains\Purchase\Models\Purchase; use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\TelepagosPayment;
use App\Domains\Purchase\Services\CheckoutService; use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -193,12 +194,14 @@ class TelepagosWebhookTest extends TestCase
'sold_units' => 1, 'sold_units' => 1,
]); ]);
$this->assertDatabaseHas('compra_items', [ $this->assertDatabaseMissing('compra_items', [
'compra_id' => $newerPurchase->id, 'compra_id' => $newerPurchase->id,
'source_catalog_item_id' => $variant->catalog_item_id, ]);
'source_variant_id' => $variant->id, $this->assertDatabaseHas('stock_reservations', [
'cantidad' => 2, 'purchase_id' => $newerPurchase->id,
'reservation_status' => 'active', 'inventory_id' => $variant->inventory_id,
'quantity' => 2,
'status' => 'active',
]); ]);
$this->assertSoftDeleted('carritos', [ $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 public function test_webhook_confirms_a_purchase_with_tickets_enabled(): void
{ {
$tenant = $this->createTenant('expired-ticket', 'Expired Ticket', 'expired-ticket.com.ar'); $tenant = $this->createTenant('expired-ticket', 'Expired Ticket', 'expired-ticket.com.ar');

View File

@@ -10,10 +10,10 @@ class AddCartEditingEnabledToTenantsTest extends TestCase
{ {
use RefreshDatabase; 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( $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(); $migration->down();
@@ -21,7 +21,17 @@ class AddCartEditingEnabledToTenantsTest extends TestCase
$this->assertDatabaseHas('tenants', [ $this->assertDatabaseHas('tenants', [
'codigo' => 'desfile_pura_tendencia', '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([ DB::table('tenants')->insert([
@@ -32,7 +42,7 @@ class AddCartEditingEnabledToTenantsTest extends TestCase
$this->assertDatabaseHas('tenants', [ $this->assertDatabaseHas('tenants', [
'codigo' => 'cart-editing-default', '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', 'variant_id'));
$this->assertFalse(Schema::hasColumn('compra_items', 'buyable_type')); $this->assertFalse(Schema::hasColumn('compra_items', 'buyable_type'));
$this->assertFalse(Schema::hasColumn('compra_items', 'buyable_id')); $this->assertFalse(Schema::hasColumn('compra_items', 'buyable_id'));
$this->assertFalse(Schema::hasColumn('compra_items', 'reservation_status'));
$this->assertDatabaseHas('compra_items', [ $this->assertDatabaseHas('compra_items', [
'compra_id' => $purchase->id, 'compra_id' => $purchase->id,
'source_catalog_item_id' => $catalogItem->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'),
]);
}
}

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