Compare commits
93 Commits
58cbeae9d3
...
feature/al
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c646f3560 | |||
| 98bfc0d5e9 | |||
| d9635d47ba | |||
| e27f7bb166 | |||
| 2323994f30 | |||
| a73b628bb4 | |||
| 2fd6851b40 | |||
| ceb1d1f1af | |||
| 885ab2a6e3 | |||
| 47196a572a | |||
| 45bba9516d | |||
| c6da71894e | |||
| 75d3c819d9 | |||
| bd6d672df2 | |||
| 6b06028771 | |||
| 0aa423e90e | |||
| e7bf2f887a | |||
| 80a02fdc52 | |||
| 4162e2c1cc | |||
| 8d01620fa8 | |||
| f8b8bab474 | |||
| 53d1415b18 | |||
| 6ff9119086 | |||
| 24e000b423 | |||
| c69ebe5f7c | |||
| c3a2da607d | |||
| d1c4acc7ae | |||
| f8c4cc7428 | |||
| 21cfbe2a46 | |||
| abc060ab25 | |||
| 80adbd9ca9 | |||
| 12c10bbe06 | |||
| 36eb41a18a | |||
| 1dd2366957 | |||
| e8bcaa2026 | |||
| 5548fe8511 | |||
| dc0fbe06b8 | |||
| afd69b8393 | |||
| a34d5cba1a | |||
| 1650176aa0 | |||
| 79e721ae63 | |||
| 4e7e42d16e | |||
| 3a2dc8b7e0 | |||
| 0510c1aa12 | |||
| 9d870be294 | |||
| 559bf5d264 | |||
| eafb02ffd5 | |||
| 786cf2db52 | |||
| cb56e33685 | |||
| dd81e3b3f7 | |||
| 4d51531c5d | |||
| 7fd8a00054 | |||
| 23163a6eb8 | |||
| 944cf8ee18 | |||
| 8c09ca1204 | |||
| 98d502a8ef | |||
| 318e6559cb | |||
| 9fd34f900f | |||
| ae6149df84 | |||
| 1776cfe581 | |||
| 5ad18694e1 | |||
| 6775fb110c | |||
| 9c46eff880 | |||
| c8ce3b0da3 | |||
| d36a929f8c | |||
| 2de02dfd31 | |||
| f9a766dee1 | |||
| 8bc57cf0ff | |||
| a78c5cee58 | |||
| cc22e33799 | |||
| 5c0b3503b7 | |||
| 8537d2ed0a | |||
| d97cc12af6 | |||
| 7a19b3a97a | |||
| a94ac7a473 | |||
| 161693509f | |||
| 93c99afb13 | |||
| 32d2b182c6 | |||
| 2632a80722 | |||
| 3cee9c28f8 | |||
| 2091b1361a | |||
| a2c5e687f9 | |||
| 172e14ae9b | |||
| 1dc4e29c69 | |||
| 093e894cc3 | |||
| fdf0f3328f | |||
| 8d6bcdcc43 | |||
| 3206e293eb | |||
| aed99bd05e | |||
| f1649e0e4b | |||
| e6c4b40a37 | |||
| 7cea8d3495 | |||
| 014b5bb012 |
@@ -39,6 +39,8 @@ LOG_LEVEL=debug
|
|||||||
LOG_DAILY_DAYS=14
|
LOG_DAILY_DAYS=14
|
||||||
TELEPAGOS_LOG_LEVEL=info
|
TELEPAGOS_LOG_LEVEL=info
|
||||||
TELEPAGOS_LOG_DAYS=30
|
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
|
||||||
|
|||||||
@@ -1169,6 +1169,99 @@
|
|||||||
},
|
},
|
||||||
"response": []
|
"response": []
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "Prepare Item Editing Purchase",
|
||||||
|
"request": {
|
||||||
|
"method": "POST",
|
||||||
|
"header": [
|
||||||
|
{
|
||||||
|
"key": "Accept",
|
||||||
|
"value": "application/json",
|
||||||
|
"type": "text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Ruta Laravel: `POST /api/tenants/{tenant:codigo}/compras/{compra}/edit-items`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@prepareItemEditing`\n\nRequiere autenticación Sanctum.",
|
||||||
|
"url": {
|
||||||
|
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/edit-items",
|
||||||
|
"host": [
|
||||||
|
"{{base_url}}"
|
||||||
|
],
|
||||||
|
"path": [
|
||||||
|
"api",
|
||||||
|
"tenants",
|
||||||
|
"{{tenant_code}}",
|
||||||
|
"compras",
|
||||||
|
"{{purchase_id}}",
|
||||||
|
"edit-items"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"auth": {
|
||||||
|
"type": "bearer",
|
||||||
|
"bearer": [
|
||||||
|
{
|
||||||
|
"key": "token",
|
||||||
|
"value": "{{token}}",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"response": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Update Item Purchase",
|
||||||
|
"request": {
|
||||||
|
"method": "PATCH",
|
||||||
|
"header": [
|
||||||
|
{
|
||||||
|
"key": "Accept",
|
||||||
|
"value": "application/json",
|
||||||
|
"type": "text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "Content-Type",
|
||||||
|
"value": "application/json",
|
||||||
|
"type": "text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Ruta Laravel: `PATCH /api/tenants/{tenant:codigo}/compras/{compra}/items/{item}`\n\nControlador: `App\\Domains\\Purchase\\Controllers\\PurchaseController@updateItem`\n\nRequiere autenticación Sanctum.",
|
||||||
|
"url": {
|
||||||
|
"raw": "{{base_url}}/api/tenants/{{tenant_code}}/compras/{{purchase_id}}/items/{{purchase_item_id}}",
|
||||||
|
"host": [
|
||||||
|
"{{base_url}}"
|
||||||
|
],
|
||||||
|
"path": [
|
||||||
|
"api",
|
||||||
|
"tenants",
|
||||||
|
"{{tenant_code}}",
|
||||||
|
"compras",
|
||||||
|
"{{purchase_id}}",
|
||||||
|
"items",
|
||||||
|
"{{purchase_item_id}}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"body": {
|
||||||
|
"mode": "raw",
|
||||||
|
"raw": "{\n \"quantity\": 2,\n \"variant_id\": {{variant_id}}\n}",
|
||||||
|
"options": {
|
||||||
|
"raw": {
|
||||||
|
"language": "json"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"auth": {
|
||||||
|
"type": "bearer",
|
||||||
|
"bearer": [
|
||||||
|
{
|
||||||
|
"key": "token",
|
||||||
|
"value": "{{token}}",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"response": []
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "Create Payment Intent Purchase",
|
"name": "Create Payment Intent Purchase",
|
||||||
"request": {
|
"request": {
|
||||||
@@ -2121,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"
|
||||||
@@ -2187,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"
|
||||||
@@ -2227,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"
|
||||||
|
|||||||
22
app/Domains/Auth/Services/AdminCredentialVerifier.php
Normal file
22
app/Domains/Auth/Services/AdminCredentialVerifier.php
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Auth\Services;
|
||||||
|
|
||||||
|
use App\Domains\Auth\Models\User;
|
||||||
|
use App\Domains\Authorization\Enums\RoleCode;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
|
||||||
|
class AdminCredentialVerifier
|
||||||
|
{
|
||||||
|
public function verify(string $email, string $password): bool
|
||||||
|
{
|
||||||
|
$admin = User::query()
|
||||||
|
->where('email', mb_strtolower(trim($email)))
|
||||||
|
->where('rol_codigo', RoleCode::Admin->value)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
return $admin !== null
|
||||||
|
&& ! $admin->locked_until?->isFuture()
|
||||||
|
&& Hash::check($password, $admin->getAuthPassword());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
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;
|
||||||
@@ -78,36 +77,6 @@ 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(
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|||||||
'guest_token',
|
'guest_token',
|
||||||
'status',
|
'status',
|
||||||
'origin',
|
'origin',
|
||||||
|
'current_purchase_id',
|
||||||
])]
|
])]
|
||||||
class Cart extends Model
|
class Cart extends Model
|
||||||
{
|
{
|
||||||
@@ -43,6 +44,7 @@ class Cart extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'user_id' => 'integer',
|
'user_id' => 'integer',
|
||||||
|
'current_purchase_id' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +78,12 @@ class Cart extends Model
|
|||||||
return $this->hasMany(Purchase::class, 'cart_id');
|
return $this->hasMany(Purchase::class, 'cart_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return BelongsTo<Purchase, $this> */
|
||||||
|
public function currentPurchase(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Purchase::class, 'current_purchase_id');
|
||||||
|
}
|
||||||
|
|
||||||
public function getTotalAmount(): float
|
public function getTotalAmount(): float
|
||||||
{
|
{
|
||||||
$items = $this->relationLoaded('items')
|
$items = $this->relationLoaded('items')
|
||||||
@@ -98,14 +106,19 @@ class Cart extends Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
|
||||||
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
$this->invalidateCurrentCheckout();
|
||||||
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
|
||||||
$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([
|
||||||
@@ -158,6 +171,8 @@ class Cart extends Model
|
|||||||
$updateVariant,
|
$updateVariant,
|
||||||
$excludedPurchaseId,
|
$excludedPurchaseId,
|
||||||
): CartItem {
|
): CartItem {
|
||||||
|
$this->invalidateCurrentCheckout();
|
||||||
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
->where('id', $cartItemId)
|
->where('id', $cartItemId)
|
||||||
@@ -181,10 +196,13 @@ 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,
|
$excludedPurchaseId,
|
||||||
|
$otherVariantsQuantity + $item->cantidad,
|
||||||
|
$nextAvailableQuantity,
|
||||||
);
|
);
|
||||||
|
|
||||||
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
app(StockReservationService::class)->release($item, $currentSelection, $item->cantidad);
|
||||||
@@ -222,6 +240,7 @@ class Cart extends Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
$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()
|
||||||
@@ -232,11 +251,11 @@ class Cart extends Model
|
|||||||
$currentSelection,
|
$currentSelection,
|
||||||
$otherVariantsQuantity + $quantity,
|
$otherVariantsQuantity + $quantity,
|
||||||
$excludedPurchaseId,
|
$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([
|
||||||
@@ -262,6 +281,8 @@ class Cart extends Model
|
|||||||
public function removeItem(int $cartItemId): void
|
public function removeItem(int $cartItemId): void
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($cartItemId): void {
|
DB::transaction(function () use ($cartItemId): void {
|
||||||
|
$this->invalidateCurrentCheckout();
|
||||||
|
|
||||||
/** @var CartItem $item */
|
/** @var CartItem $item */
|
||||||
$item = $this->items()
|
$item = $this->items()
|
||||||
->where('id', $cartItemId)
|
->where('id', $cartItemId)
|
||||||
@@ -282,6 +303,58 @@ class Cart extends Model
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function invalidateCurrentCheckout(): void
|
||||||
|
{
|
||||||
|
$candidatePurchaseId = self::query()
|
||||||
|
->whereKey($this->getKey())
|
||||||
|
->value('current_purchase_id');
|
||||||
|
$currentPurchase = $candidatePurchaseId === null
|
||||||
|
? null
|
||||||
|
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
|
||||||
|
|
||||||
|
/** @var self $cart */
|
||||||
|
$cart = self::query()->lockForUpdate()->findOrFail($this->getKey());
|
||||||
|
|
||||||
|
if ($cart->current_purchase_id !== $candidatePurchaseId) {
|
||||||
|
if ($cart->current_purchase_id !== null) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'cart' => __('api.purchase.checkout_in_progress'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->current_purchase_id = null;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($currentPurchase === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($currentPurchase->status === Purchase::STATUS_PAID) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'cart' => __('api.cart.editing_disabled'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($currentPurchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
$currentPurchase->update([
|
||||||
|
'status' => Purchase::STATUS_SUPERSEDED,
|
||||||
|
'expires_at' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
app(StockReservationService::class)->detachFromPurchase($currentPurchase);
|
||||||
|
self::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $currentPurchase->getKey())
|
||||||
|
->update(['current_purchase_id' => null]);
|
||||||
|
$this->current_purchase_id = null;
|
||||||
|
}
|
||||||
|
|
||||||
protected function resolveScopedItem(
|
protected function resolveScopedItem(
|
||||||
int $catalogItemId,
|
int $catalogItemId,
|
||||||
?int $variantId,
|
?int $variantId,
|
||||||
@@ -355,6 +428,8 @@ class Cart extends Model
|
|||||||
CatalogItem|Variant $selectedItem,
|
CatalogItem|Variant $selectedItem,
|
||||||
int $cartQuantity,
|
int $cartQuantity,
|
||||||
?int $excludedPurchaseId = null,
|
?int $excludedPurchaseId = null,
|
||||||
|
int $heldQuantity = 0,
|
||||||
|
?int $maximumAddableCeiling = null,
|
||||||
): void {
|
): void {
|
||||||
if ($this->user_id === null) {
|
if ($this->user_id === null) {
|
||||||
return;
|
return;
|
||||||
@@ -369,6 +444,9 @@ class Cart extends Model
|
|||||||
$this->user_id,
|
$this->user_id,
|
||||||
$cartQuantity,
|
$cartQuantity,
|
||||||
$excludedPurchaseId,
|
$excludedPurchaseId,
|
||||||
|
$this->getKey(),
|
||||||
|
$heldQuantity,
|
||||||
|
$maximumAddableCeiling,
|
||||||
field: 'cantidad',
|
field: 'cantidad',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Domains\Cart\Resources;
|
|||||||
|
|
||||||
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;
|
||||||
@@ -22,6 +23,8 @@ class CartItemResource extends JsonResource
|
|||||||
$imageUrl = null;
|
$imageUrl = null;
|
||||||
$tenant = $request->route('tenant');
|
$tenant = $request->route('tenant');
|
||||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||||
|
$includeVariants = $tenant instanceof Tenant
|
||||||
|
&& $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 +42,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),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,9 @@ 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\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 Illuminate\Validation\ValidationException;
|
||||||
use Symfony\Component\HttpFoundation\Cookie;
|
use Symfony\Component\HttpFoundation\Cookie;
|
||||||
@@ -18,10 +14,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|||||||
|
|
||||||
class CartService
|
class CartService
|
||||||
{
|
{
|
||||||
public function __construct(
|
|
||||||
private readonly StockReservationService $reservations,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function show(Tenant $tenant, Request $request): Cart
|
public function show(Tenant $tenant, Request $request): Cart
|
||||||
{
|
{
|
||||||
$resolvedIdentity = $this->resolveIdentity($request);
|
$resolvedIdentity = $this->resolveIdentity($request);
|
||||||
@@ -36,7 +28,7 @@ class CartService
|
|||||||
return $this->makeEmptyCart($tenant);
|
return $this->makeEmptyCart($tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->loadCart($cart);
|
return $this->loadCart($cart, $tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -55,7 +47,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'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -68,135 +60,58 @@ 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())
|
|
||||||
->whereIn('status', [
|
|
||||||
Purchase::STATUS_CREATED,
|
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
|
||||||
])
|
|
||||||
->whereDoesntHave('items')
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($purchase === null) {
|
|
||||||
throw new NotFoundHttpException('Checkout cart not found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'cart' => __('api.purchase.not_editable'),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var Cart|null $checkoutCart */
|
|
||||||
$checkoutCart = Cart::query()
|
|
||||||
->whereKey($cart->getKey())
|
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
|
||||||
->where('user_id', $user->getKey())
|
|
||||||
->where('status', 'checkout')
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($checkoutCart === null) {
|
|
||||||
throw new NotFoundHttpException('Checkout cart not found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var CartItem|null $cartItem */
|
|
||||||
$cartItem = $checkoutCart->items()
|
|
||||||
->whereKey($cartItemId)
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($cartItem === null) {
|
|
||||||
throw new NotFoundHttpException('Checkout item not found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$hasChanges = (int) $cartItem->cantidad !== $quantity
|
|
||||||
|| ($updateVariant && $cartItem->variant_id !== $variantId);
|
|
||||||
|
|
||||||
if (! $hasChanges) {
|
|
||||||
return $this->loadCart($checkoutCart);
|
|
||||||
}
|
|
||||||
|
|
||||||
$checkoutCart->updateItem(
|
|
||||||
$cartItemId,
|
|
||||||
$quantity,
|
|
||||||
$variantId,
|
|
||||||
$updateVariant,
|
|
||||||
$purchase->getKey(),
|
|
||||||
);
|
|
||||||
|
|
||||||
$purchase->telepagosQr()->delete();
|
|
||||||
$purchase->update([
|
|
||||||
'status' => Purchase::STATUS_CREATED,
|
|
||||||
'payment_method' => null,
|
|
||||||
'transfer_payer_dni' => null,
|
|
||||||
'total' => $checkoutCart->getTotalAmount(),
|
|
||||||
'expires_at' => now()->addMinutes(
|
|
||||||
max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
|
|
||||||
),
|
|
||||||
]);
|
|
||||||
$this->reservations->syncPurchaseExpiration($purchase);
|
|
||||||
|
|
||||||
return $this->loadCart($checkoutCart);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function removeItem(Tenant $tenant, Request $request, int $cartItemId): Cart
|
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 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,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,9 +127,9 @@ class CartService
|
|||||||
return $cart;
|
return $cart;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function loadCart(Cart $cart): Cart
|
protected function loadCart(Cart $cart, Tenant $tenant): Cart
|
||||||
{
|
{
|
||||||
return $cart->fresh()->load([
|
$relations = [
|
||||||
'items.catalogItem.attachments',
|
'items.catalogItem.attachments',
|
||||||
'items.catalogItem.inventory',
|
'items.catalogItem.inventory',
|
||||||
'items.catalogItem.itemAttributes.attribute',
|
'items.catalogItem.itemAttributes.attribute',
|
||||||
@@ -223,7 +138,21 @@ 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',
|
||||||
]);
|
];
|
||||||
|
|
||||||
|
if ($tenant->cart_editing_policy->allowsVariantChanges()) {
|
||||||
|
$relations = [
|
||||||
|
...$relations,
|
||||||
|
'items.catalogItem.variants' => fn ($query) => $query->orderBy('id'),
|
||||||
|
'items.catalogItem.variants.inventory',
|
||||||
|
'items.catalogItem.variants.definitions' => fn ($query) => $query->orderBy('id'),
|
||||||
|
'items.catalogItem.variants.definitions.itemAttribute.attribute.options',
|
||||||
|
'items.catalogItem.variants.eventDates',
|
||||||
|
'items.catalogItem.variants.eventDate',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cart->fresh()->load($relations);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -34,4 +34,4 @@ Depende de `Catalog` para productos y variantes, de `Tenant` para aislar datos y
|
|||||||
|
|
||||||
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
|
Un carrito puede pasar a `checkout`. Las compras directas usan un carrito técnico con `origin=direct_checkout`; los carritos normales conservan `origin=user` y pueden restaurarse al cancelar o vencer la compra.
|
||||||
|
|
||||||
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío.
|
El comando unificado `php artisan reservations:expire` procesa primero las compras vencidas y luego las reservas activas sin compra cuyo `expires_at` haya vencido. Se ejecuta cada minuto mediante el scheduler, conserva la fila de reserva con estado `expired`, elimina el ítem abandonado y elimina lógicamente el carrito cuando queda vacío. Cada intento registra sus resultados o su error en el log diario `storage/logs/commands/commands-AAAA-MM-DD.log`.
|
||||||
|
|||||||
@@ -10,9 +10,3 @@ 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']);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -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,23 @@ 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));
|
||||||
|
abort_unless($allowances->availability(
|
||||||
|
$item->availableStock(),
|
||||||
|
$item->getAttribute('remaining_user_quota'),
|
||||||
|
)->isVisible(), 404);
|
||||||
|
|
||||||
|
return CatalogItemDetailResource::make($item);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function variantOptions(
|
public function variantOptions(
|
||||||
@@ -164,4 +181,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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
10
app/Domains/Catalog/Enums/AvailabilityEffect.php
Normal file
10
app/Domains/Catalog/Enums/AvailabilityEffect.php
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Enums;
|
||||||
|
|
||||||
|
enum AvailabilityEffect: string
|
||||||
|
{
|
||||||
|
case Hide = 'hide';
|
||||||
|
case Restrict = 'restrict';
|
||||||
|
case Notice = 'notice';
|
||||||
|
}
|
||||||
11
app/Domains/Catalog/Enums/CatalogAction.php
Normal file
11
app/Domains/Catalog/Enums/CatalogAction.php
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Enums;
|
||||||
|
|
||||||
|
enum CatalogAction: string
|
||||||
|
{
|
||||||
|
case SelectVariant = 'select_variant';
|
||||||
|
case ChangeQuantity = 'change_quantity';
|
||||||
|
case AddToCart = 'add_to_cart';
|
||||||
|
case BuyNow = 'buy_now';
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
'tenant_code',
|
'tenant_code',
|
||||||
'categoria_id',
|
'categoria_id',
|
||||||
'nombre',
|
'nombre',
|
||||||
|
'is_enabled',
|
||||||
])]
|
])]
|
||||||
class Category extends Model
|
class Category extends Model
|
||||||
{
|
{
|
||||||
@@ -22,6 +23,10 @@ class Category extends Model
|
|||||||
|
|
||||||
protected $table = 'categorias';
|
protected $table = 'categorias';
|
||||||
|
|
||||||
|
protected $attributes = [
|
||||||
|
'is_enabled' => true,
|
||||||
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array<string, string>
|
* @return array<string, string>
|
||||||
*/
|
*/
|
||||||
@@ -29,6 +34,7 @@ class Category extends Model
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'categoria_id' => 'integer',
|
'categoria_id' => 'integer',
|
||||||
|
'is_enabled' => 'boolean',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 [
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
@@ -28,27 +29,36 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
return $this->ticketSelectorData($catalogItem);
|
return $this->ticketSelectorData($catalogItem);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||||
|
$availableStock = $catalogItem->availableStock();
|
||||||
|
|
||||||
$data = [
|
$data = [
|
||||||
'id' => $catalogItem->id,
|
'id' => $catalogItem->id,
|
||||||
'type' => $catalogItem->type->value,
|
'type' => $catalogItem->type->value,
|
||||||
'nombre' => $catalogItem->nombre,
|
'nombre' => $catalogItem->nombre,
|
||||||
'descripcion' => $catalogItem->descripcion,
|
'descripcion' => $catalogItem->descripcion,
|
||||||
'precio' => $catalogItem->precio,
|
'precio' => $catalogItem->precio,
|
||||||
'stock_tecnico' => $catalogItem->availableStock(),
|
'availability' => $this->availability($availableStock, $remainingUserQuota),
|
||||||
'variants' => $catalogItem->visibleVariants()
|
'variants' => $catalogItem->variants
|
||||||
->map(fn (Variant $variant): array => [
|
->map(function (Variant $variant) use ($catalogItem): array {
|
||||||
'id' => $variant->id,
|
$variantStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
'event_date_id' => $variant->event_date_id,
|
|
||||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
|
||||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
|
||||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
|
||||||
'descripcion' => $variant->getDescription(),
|
|
||||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
|
||||||
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
|
||||||
? null
|
? null
|
||||||
: $variant->inventory->availableStock(),
|
: $variant->inventory->availableStock();
|
||||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
$availability = $this->availability($variantStock, null);
|
||||||
])
|
|
||||||
|
return [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'event_date_id' => $variant->event_date_id,
|
||||||
|
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||||
|
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||||
|
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||||
|
'descripcion' => $variant->getDescription(),
|
||||||
|
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
|
'availability' => $availability,
|
||||||
|
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->filter(fn (array $variant): bool => $variant['availability']['state'] === 'visible')
|
||||||
->values(),
|
->values(),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -58,6 +68,9 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function ticketSelectorData(CatalogItem $catalogItem): array
|
private function ticketSelectorData(CatalogItem $catalogItem): array
|
||||||
{
|
{
|
||||||
|
$availableStock = $catalogItem->availableStock();
|
||||||
|
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $catalogItem->id,
|
'id' => $catalogItem->id,
|
||||||
'type' => $catalogItem->type->value,
|
'type' => $catalogItem->type->value,
|
||||||
@@ -65,18 +78,23 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
'descripcion' => $catalogItem->descripcion,
|
'descripcion' => $catalogItem->descripcion,
|
||||||
'precio' => $catalogItem->precio,
|
'precio' => $catalogItem->precio,
|
||||||
'image' => $this->firstImageUrl($catalogItem),
|
'image' => $this->firstImageUrl($catalogItem),
|
||||||
|
'availability' => $this->availability($availableStock, $remainingUserQuota),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function columnWithImageData(CatalogItem $catalogItem): array
|
private function columnWithImageData(CatalogItem $catalogItem): array
|
||||||
{
|
{
|
||||||
|
$availableStock = $catalogItem->availableStock();
|
||||||
|
$remainingUserQuota = $catalogItem->getAttribute('remaining_user_quota');
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $catalogItem->id,
|
'id' => $catalogItem->id,
|
||||||
'type' => $catalogItem->type->value,
|
'type' => $catalogItem->type->value,
|
||||||
'nombre' => $catalogItem->nombre,
|
'nombre' => $catalogItem->nombre,
|
||||||
'precio' => $catalogItem->precio,
|
'precio' => $catalogItem->precio,
|
||||||
'image' => $this->firstImageUrl($catalogItem),
|
'image' => $this->firstImageUrl($catalogItem),
|
||||||
|
'availability' => $this->availability($availableStock, $remainingUserQuota),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,4 +107,14 @@ class CatalogFeaturedItemResource extends JsonResource
|
|||||||
|
|
||||||
return $attachment?->getTemporaryUrl(1440);
|
return $attachment?->getTemporaryUrl(1440);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function availability(
|
||||||
|
?int $stock,
|
||||||
|
?int $remainingUserQuota,
|
||||||
|
): array {
|
||||||
|
return app(CatalogItemAllowanceService::class)
|
||||||
|
->availability($stock, $remainingUserQuota)
|
||||||
|
->toArray();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,16 +38,14 @@ 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(
|
'availability' => $this->availability($this->availableStock()),
|
||||||
$selectedVariant === null,
|
|
||||||
fn () => $this->availableStock(),
|
|
||||||
),
|
|
||||||
'images' => $this->when(
|
'images' => $this->when(
|
||||||
$selectedVariant === null,
|
$selectedVariant === null,
|
||||||
fn () => $this->imageUrls($this->attachments),
|
fn () => $this->imageUrls($this->attachments),
|
||||||
),
|
),
|
||||||
'variants' => $this->visibleVariants()
|
'variants' => $this->variants
|
||||||
->map(fn (Variant $variant): array => $this->variantData($variant))
|
->map(fn (Variant $variant): array => $this->variantData($variant))
|
||||||
|
->filter(fn (array $variant): bool => $variant['availability']['state'] === 'visible')
|
||||||
->values(),
|
->values(),
|
||||||
'selected_variant' => $this->when(
|
'selected_variant' => $this->when(
|
||||||
$selectedVariant !== null,
|
$selectedVariant !== null,
|
||||||
@@ -158,6 +157,11 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
{
|
{
|
||||||
$values = $variant->selectionOptions($this->itemAttributes);
|
$values = $variant->selectionOptions($this->itemAttributes);
|
||||||
$eventDates = $variant->selectedEventDates();
|
$eventDates = $variant->selectedEventDates();
|
||||||
|
$variantStock = $this->variantStock($variant);
|
||||||
|
$availability = $this->availability(
|
||||||
|
$variantStock,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
@@ -167,7 +171,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),
|
'availability' => $availability,
|
||||||
'values' => $values,
|
'values' => $values,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -186,4 +190,15 @@ class CatalogItemDetailResource extends JsonResource
|
|||||||
? null
|
? null
|
||||||
: $variant->inventory->availableStock();
|
: $variant->inventory->availableStock();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function availability(
|
||||||
|
?int $stock,
|
||||||
|
bool $includeUserQuota = true,
|
||||||
|
): array {
|
||||||
|
return app(CatalogItemAllowanceService::class)->availability(
|
||||||
|
$stock,
|
||||||
|
$includeUserQuota ? $this->getAttribute('remaining_user_quota') : null,
|
||||||
|
)->toArray();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
@@ -14,6 +15,7 @@ class CatalogSearchItemResource extends JsonResource
|
|||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
|
$availableStock = $this->availableStock();
|
||||||
$attachment = $this->attachments->first()
|
$attachment = $this->attachments->first()
|
||||||
?? $this->variants
|
?? $this->variants
|
||||||
->flatMap(fn (Variant $variant) => $variant->attachments)
|
->flatMap(fn (Variant $variant) => $variant->attachments)
|
||||||
@@ -26,22 +28,42 @@ 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(),
|
'availability' => $this->availability($availableStock),
|
||||||
'variants' => $this->visibleVariants()
|
'variants' => $this->variants
|
||||||
->map(fn (Variant $variant): array => [
|
->map(function (Variant $variant): array {
|
||||||
'id' => $variant->id,
|
$variantStock = $this->inventory_policy === InventoryPolicy::Unlimited
|
||||||
'event_date_id' => $variant->event_date_id,
|
|
||||||
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
|
||||||
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
|
||||||
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
|
||||||
'descripcion' => $variant->getDescription(),
|
|
||||||
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
|
||||||
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
|
|
||||||
? null
|
? null
|
||||||
: $variant->inventory?->availableStock(),
|
: $variant->inventory?->availableStock();
|
||||||
'values' => $variant->selectorOptions($this->itemAttributes),
|
$availability = $this->availability(
|
||||||
])
|
$variantStock,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $variant->id,
|
||||||
|
'event_date_id' => $variant->event_date_id,
|
||||||
|
'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
|
||||||
|
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
|
||||||
|
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
|
||||||
|
'descripcion' => $variant->getDescription(),
|
||||||
|
'precio' => number_format($variant->getPrice(), 2, '.', ''),
|
||||||
|
'availability' => $availability,
|
||||||
|
'values' => $variant->selectorOptions($this->itemAttributes),
|
||||||
|
];
|
||||||
|
})
|
||||||
|
->filter(fn (array $variant): bool => $variant['availability']['state'] === 'visible')
|
||||||
->values(),
|
->values(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
private function availability(
|
||||||
|
?int $stock,
|
||||||
|
bool $includeUserQuota = true,
|
||||||
|
): array {
|
||||||
|
return app(CatalogItemAllowanceService::class)->availability(
|
||||||
|
$stock,
|
||||||
|
$includeUserQuota ? $this->getAttribute('remaining_user_quota') : null,
|
||||||
|
)->toArray();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
63
app/Domains/Catalog/Services/AvailabilityDecision.php
Normal file
63
app/Domains/Catalog/Services/AvailabilityDecision.php
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\CatalogAction;
|
||||||
|
|
||||||
|
final readonly class AvailabilityDecision
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param list<CatalogAction> $allowedActions
|
||||||
|
* @param list<array{code: string, message: string}> $reasons
|
||||||
|
*/
|
||||||
|
private function __construct(
|
||||||
|
private bool $visible,
|
||||||
|
private ?int $maximumQuantity,
|
||||||
|
private array $allowedActions,
|
||||||
|
private array $reasons,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @param list<array{code: string, message: string}> $reasons */
|
||||||
|
public static function hidden(array $reasons): self
|
||||||
|
{
|
||||||
|
return new self(false, null, [], $reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<CatalogAction> $allowedActions
|
||||||
|
* @param list<array{code: string, message: string}> $reasons
|
||||||
|
*/
|
||||||
|
public static function visible(
|
||||||
|
?int $maximumQuantity,
|
||||||
|
array $allowedActions,
|
||||||
|
array $reasons,
|
||||||
|
): self {
|
||||||
|
return new self(true, $maximumQuantity, $allowedActions, $reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isVisible(): bool
|
||||||
|
{
|
||||||
|
return $this->visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
if (! $this->visible) {
|
||||||
|
return [
|
||||||
|
'state' => 'hidden',
|
||||||
|
'reasons' => $this->reasons,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'state' => 'visible',
|
||||||
|
'maximum_quantity' => $this->maximumQuantity,
|
||||||
|
'allowed_actions' => array_map(
|
||||||
|
fn (CatalogAction $action): string => $action->value,
|
||||||
|
$this->allowedActions,
|
||||||
|
),
|
||||||
|
'reasons' => $this->reasons,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
26
app/Domains/Catalog/Services/AvailabilityPolicyResolver.php
Normal file
26
app/Domains/Catalog/Services/AvailabilityPolicyResolver.php
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\AvailabilityEffect;
|
||||||
|
use App\Domains\Catalog\Enums\CatalogAction;
|
||||||
|
|
||||||
|
final class AvailabilityPolicyResolver
|
||||||
|
{
|
||||||
|
/** @return array{effect: AvailabilityEffect, denied_actions: list<CatalogAction>} */
|
||||||
|
public function resolve(string $restrictionCode): array
|
||||||
|
{
|
||||||
|
/** @var array{effect?: string, denied_actions?: list<string>} $configured */
|
||||||
|
$configured = config("catalog.availability.rules.{$restrictionCode}", []);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'effect' => AvailabilityEffect::from(
|
||||||
|
$configured['effect'] ?? AvailabilityEffect::Notice->value,
|
||||||
|
),
|
||||||
|
'denied_actions' => array_map(
|
||||||
|
fn (string $action): CatalogAction => CatalogAction::from($action),
|
||||||
|
$configured['denied_actions'] ?? [],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
126
app/Domains/Catalog/Services/CatalogItemAllowanceService.php
Normal file
126
app/Domains/Catalog/Services/CatalogItemAllowanceService.php
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\AvailabilityEffect;
|
||||||
|
use App\Domains\Catalog\Enums\CatalogAction;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
|
||||||
|
class CatalogItemAllowanceService
|
||||||
|
{
|
||||||
|
private const USER_QUOTA_REACHED_MESSAGE = 'Alcanzaste el cupo máximo permitido para este producto.';
|
||||||
|
|
||||||
|
private const OUT_OF_STOCK_MESSAGE = 'Este producto no tiene stock disponible.';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||||
|
private readonly AvailabilityPolicyResolver $policies,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function availability(
|
||||||
|
?int $availableStock,
|
||||||
|
?int $remainingUserQuota,
|
||||||
|
): AvailabilityDecision {
|
||||||
|
$reasons = [];
|
||||||
|
|
||||||
|
if ($remainingUserQuota !== null && $remainingUserQuota <= 0) {
|
||||||
|
$reasons[] = [
|
||||||
|
'code' => 'user_quota_reached',
|
||||||
|
'message' => self::USER_QUOTA_REACHED_MESSAGE,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($availableStock !== null && $availableStock <= 0) {
|
||||||
|
$reasons[] = [
|
||||||
|
'code' => 'out_of_stock',
|
||||||
|
'message' => self::OUT_OF_STOCK_MESSAGE,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->decision(
|
||||||
|
$this->maximumAddableQuantity($availableStock, $remainingUserQuota),
|
||||||
|
$reasons,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function purchaseLimitExceededAvailability(
|
||||||
|
int $maximumQuantity,
|
||||||
|
string $message,
|
||||||
|
): AvailabilityDecision {
|
||||||
|
$reasons = [];
|
||||||
|
|
||||||
|
if ($maximumQuantity <= 0) {
|
||||||
|
$reasons[] = [
|
||||||
|
'code' => 'user_quota_reached',
|
||||||
|
'message' => self::USER_QUOTA_REACHED_MESSAGE,
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
$reasons[] = [
|
||||||
|
'code' => 'requested_quantity_exceeds_user_quota',
|
||||||
|
'message' => $message,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->decision($maximumQuantity, $reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{code: string, message: string}> $reasons
|
||||||
|
*/
|
||||||
|
private function decision(?int $maximumQuantity, array $reasons): AvailabilityDecision
|
||||||
|
{
|
||||||
|
/** @var list<string> $configuredActions */
|
||||||
|
$configuredActions = config('catalog.availability.default_actions', []);
|
||||||
|
$allowedActions = collect($configuredActions)
|
||||||
|
->map(fn (string $action): CatalogAction => CatalogAction::from($action));
|
||||||
|
|
||||||
|
foreach ($reasons as $reason) {
|
||||||
|
$policy = $this->policies->resolve($reason['code']);
|
||||||
|
|
||||||
|
if ($policy['effect'] === AvailabilityEffect::Hide) {
|
||||||
|
return AvailabilityDecision::hidden($reasons);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($policy['effect'] === AvailabilityEffect::Restrict) {
|
||||||
|
$deniedActions = $policy['denied_actions'];
|
||||||
|
$allowedActions = $allowedActions->reject(
|
||||||
|
fn (CatalogAction $action): bool => in_array($action, $deniedActions, true),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return AvailabilityDecision::visible(
|
||||||
|
$maximumQuantity,
|
||||||
|
$allowedActions->values()->all(),
|
||||||
|
$reasons,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,10 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|||||||
|
|
||||||
class CatalogService
|
class CatalogService
|
||||||
{
|
{
|
||||||
public function __construct(protected AttachmentService $attachmentService) {}
|
public function __construct(
|
||||||
|
protected AttachmentService $attachmentService,
|
||||||
|
private readonly VisibleCatalogItemsQuery $visibleCatalogItems,
|
||||||
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $data
|
* @param array<string, mixed> $data
|
||||||
@@ -229,9 +232,8 @@ class CatalogService
|
|||||||
$containsPattern = "%{$normalizedTerm}%";
|
$containsPattern = "%{$normalizedTerm}%";
|
||||||
$startsWithPattern = "{$normalizedTerm}%";
|
$startsWithPattern = "{$normalizedTerm}%";
|
||||||
|
|
||||||
$paginator = CatalogItem::query()
|
$query = CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->whereVariantsAvailable()
|
|
||||||
->where(function (Builder $query) use ($containsPattern): void {
|
->where(function (Builder $query) use ($containsPattern): void {
|
||||||
$query
|
$query
|
||||||
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
->whereRaw('LOWER(nombre) LIKE ?', [$containsPattern])
|
||||||
@@ -258,7 +260,10 @@ class CatalogService
|
|||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
])
|
]);
|
||||||
|
|
||||||
|
$paginator = $this->visibleCatalogItems
|
||||||
|
->apply($query)
|
||||||
->orderByRaw(
|
->orderByRaw(
|
||||||
'CASE WHEN LOWER(nombre) = ? THEN 0 WHEN LOWER(nombre) LIKE ? THEN 1 ELSE 2 END',
|
'CASE WHEN LOWER(nombre) = ? THEN 0 WHEN LOWER(nombre) LIKE ? THEN 1 ELSE 2 END',
|
||||||
[$normalizedTerm, $startsWithPattern],
|
[$normalizedTerm, $startsWithPattern],
|
||||||
@@ -278,10 +283,9 @@ class CatalogService
|
|||||||
int $perPage,
|
int $perPage,
|
||||||
int $page,
|
int $page,
|
||||||
): LengthAwarePaginator {
|
): LengthAwarePaginator {
|
||||||
return CatalogItem::query()
|
$query = CatalogItem::query()
|
||||||
->where('tenant_code', $tenant->codigo)
|
->where('tenant_code', $tenant->codigo)
|
||||||
->where('category_id', $category->id)
|
->where('category_id', $category->id)
|
||||||
->whereVariantsAvailable()
|
|
||||||
->with([
|
->with([
|
||||||
'attachments',
|
'attachments',
|
||||||
'inventory',
|
'inventory',
|
||||||
@@ -293,7 +297,10 @@ class CatalogService
|
|||||||
'variants.definitions.itemAttribute.attribute.options',
|
'variants.definitions.itemAttribute.attribute.options',
|
||||||
'bundleComponents.catalogItem',
|
'bundleComponents.catalogItem',
|
||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
])
|
]);
|
||||||
|
|
||||||
|
return $this->visibleCatalogItems
|
||||||
|
->apply($query)
|
||||||
->orderBy('nombre')
|
->orderBy('nombre')
|
||||||
->paginate(perPage: $perPage, pageName: 'page', page: $page);
|
->paginate(perPage: $perPage, pageName: 'page', page: $page);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ namespace App\Domains\Catalog\Services;
|
|||||||
|
|
||||||
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
use App\Domains\Cart\Services\ExpireCartReservationsService;
|
||||||
use App\Domains\Purchase\Services\CheckoutService;
|
use App\Domains\Purchase\Services\CheckoutService;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
class ExpireStockReservationsService
|
class ExpireStockReservationsService
|
||||||
{
|
{
|
||||||
@@ -17,9 +19,33 @@ class ExpireStockReservationsService
|
|||||||
*/
|
*/
|
||||||
public function expireOverdue(): array
|
public function expireOverdue(): array
|
||||||
{
|
{
|
||||||
return [
|
$expiredPurchases = null;
|
||||||
'purchases' => $this->checkout->expireOverduePurchases(),
|
$expiredCartItems = null;
|
||||||
'cart_items' => $this->carts->expireOverdue(),
|
|
||||||
];
|
try {
|
||||||
|
$expiredPurchases = $this->checkout->expireOverduePurchases();
|
||||||
|
$expiredCartItems = $this->carts->expireOverdue();
|
||||||
|
|
||||||
|
Log::channel('commands')->info('Stock reservation cleanup completed.', [
|
||||||
|
'command' => 'reservations:expire',
|
||||||
|
'expired_purchases' => $expiredPurchases,
|
||||||
|
'expired_cart_items' => $expiredCartItems,
|
||||||
|
'total_expired' => $expiredPurchases + $expiredCartItems,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'purchases' => $expiredPurchases,
|
||||||
|
'cart_items' => $expiredCartItems,
|
||||||
|
];
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
Log::channel('commands')->error('Stock reservation cleanup failed.', [
|
||||||
|
'command' => 'reservations:expire',
|
||||||
|
'expired_purchases' => $expiredPurchases,
|
||||||
|
'expired_cart_items' => $expiredCartItems,
|
||||||
|
'exception' => $exception,
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw $exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,12 @@ 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,
|
||||||
|
private readonly VisibleCatalogItemsQuery $visibleCatalogItems,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
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 +31,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()
|
||||||
@@ -43,7 +50,15 @@ class FeaturedGroupService
|
|||||||
{
|
{
|
||||||
$query = CatalogItem::query()
|
$query = CatalogItem::query()
|
||||||
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
|
->where('catalog_items.tenant_code', $featuredGroup->tenant_code)
|
||||||
->whereVariantsAvailable()
|
->where(function (Builder $query): void {
|
||||||
|
$query
|
||||||
|
->whereDoesntHave('category')
|
||||||
|
->orWhereHas(
|
||||||
|
'category',
|
||||||
|
fn (Builder $categoryQuery): Builder => $categoryQuery
|
||||||
|
->where('is_enabled', true),
|
||||||
|
);
|
||||||
|
})
|
||||||
->with([
|
->with([
|
||||||
'inventory',
|
'inventory',
|
||||||
'attachments',
|
'attachments',
|
||||||
@@ -57,6 +72,8 @@ class FeaturedGroupService
|
|||||||
'bundleComponents.variant.catalogItem',
|
'bundleComponents.variant.catalogItem',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
$query = $this->visibleCatalogItems->apply($query);
|
||||||
|
|
||||||
return match ($featuredGroup->source_type) {
|
return match ($featuredGroup->source_type) {
|
||||||
FeaturedGroupSource::Manual => $query
|
FeaturedGroupSource::Manual => $query
|
||||||
->select('catalog_items.*')
|
->select('catalog_items.*')
|
||||||
|
|||||||
@@ -37,16 +37,24 @@ class StockReservationService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function commit(CartItem $cartItem, CatalogItem|Variant $selection): void
|
public function commit(
|
||||||
{
|
CartItem $cartItem,
|
||||||
DB::transaction(function () use ($cartItem, $selection): void {
|
CatalogItem|Variant $selection,
|
||||||
|
Purchase $purchase,
|
||||||
|
): void {
|
||||||
|
DB::transaction(function () use ($cartItem, $selection, $purchase): void {
|
||||||
$this->ensure($cartItem, $selection);
|
$this->ensure($cartItem, $selection);
|
||||||
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
$this->inventory->commit($selection, (int) $cartItem->cantidad);
|
||||||
|
|
||||||
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
$requirements = $this->inventory->requirementsFor($selection, (int) $cartItem->cantidad);
|
||||||
foreach ($requirements as $inventoryId => $quantity) {
|
foreach ($requirements as $inventoryId => $quantity) {
|
||||||
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
$reservation = $this->lockReservation($cartItem, $inventoryId);
|
||||||
if ($reservation === null || $reservation->status !== StockReservation::STATUS_ACTIVE || $reservation->quantity !== $quantity) {
|
if (
|
||||||
|
$reservation === null
|
||||||
|
|| $reservation->status !== StockReservation::STATUS_ACTIVE
|
||||||
|
|| $reservation->purchase_id !== $purchase->getKey()
|
||||||
|
|| $reservation->quantity !== $quantity
|
||||||
|
) {
|
||||||
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
throw new \InvalidArgumentException('La reserva de stock no coincide con el item del carrito.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +126,37 @@ class StockReservationService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function restore(CartItem $cartItem, CatalogItem|Variant $selection): void
|
||||||
|
{
|
||||||
|
DB::transaction(function () use ($cartItem, $selection): void {
|
||||||
|
$requirements = $this->inventory->requirementsFor(
|
||||||
|
$selection,
|
||||||
|
(int) $cartItem->cantidad,
|
||||||
|
);
|
||||||
|
$activeReservations = StockReservation::query()
|
||||||
|
->where('cart_item_id', $cartItem->getKey())
|
||||||
|
->where('status', StockReservation::STATUS_ACTIVE)
|
||||||
|
->lockForUpdate()
|
||||||
|
->get()
|
||||||
|
->keyBy('inventory_id');
|
||||||
|
|
||||||
|
$hasCompleteReservation = collect($requirements)->every(
|
||||||
|
fn (int $quantity, int $inventoryId): bool => (int) ($activeReservations->get($inventoryId)?->quantity ?? 0) === $quantity,
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($hasCompleteReservation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($activeReservations->isNotEmpty()) {
|
||||||
|
throw new \InvalidArgumentException('La reserva de stock del carrito es inconsistente.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->inventory->reserve($selection, (int) $cartItem->cantidad);
|
||||||
|
$this->recordIncrease($cartItem, $selection, (int) $cartItem->cantidad);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public function syncPurchaseExpiration(Purchase $purchase): void
|
public function syncPurchaseExpiration(Purchase $purchase): void
|
||||||
{
|
{
|
||||||
StockReservation::query()
|
StockReservation::query()
|
||||||
|
|||||||
@@ -10,6 +10,10 @@ use Illuminate\Support\Collection;
|
|||||||
|
|
||||||
class VariantSelectionService
|
class VariantSelectionService
|
||||||
{
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly CatalogItemAllowanceService $allowances,
|
||||||
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string, mixed> $selectedValues
|
* @param array<string, mixed> $selectedValues
|
||||||
* @return array<string, mixed>
|
* @return array<string, mixed>
|
||||||
@@ -188,13 +192,17 @@ class VariantSelectionService
|
|||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
private function variantData(CatalogItem $catalogItem, Variant $variant): array
|
||||||
{
|
{
|
||||||
|
$availableStock = $catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
||||||
|
? null
|
||||||
|
: $variant->inventory?->availableStock();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $variant->id,
|
'id' => $variant->id,
|
||||||
'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
|
'availability' => $this->allowances
|
||||||
? null
|
->availability($availableStock, null)
|
||||||
: $variant->inventory?->availableStock(),
|
->toArray(),
|
||||||
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
'values' => $variant->selectorOptions($catalogItem->itemAttributes),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
81
app/Domains/Catalog/Services/VisibleCatalogItemsQuery.php
Normal file
81
app/Domains/Catalog/Services/VisibleCatalogItemsQuery.php
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Catalog\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Enums\AvailabilityEffect;
|
||||||
|
use App\Domains\Catalog\Enums\CatalogItemType;
|
||||||
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
|
|
||||||
|
final class VisibleCatalogItemsQuery
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly AvailabilityPolicyResolver $policies,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @param Builder<CatalogItem> $query */
|
||||||
|
public function apply(Builder $query): Builder
|
||||||
|
{
|
||||||
|
if ($this->policies->resolve('out_of_stock')['effect'] !== AvailabilityEffect::Hide) {
|
||||||
|
return $query;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->where(function (Builder $query): void {
|
||||||
|
$query
|
||||||
|
->where(fn (Builder $query) => $this->applyStandardItemAvailability($query))
|
||||||
|
->orWhere(fn (Builder $query) => $this->applyBundleAvailability($query));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<CatalogItem> $query */
|
||||||
|
private function applyStandardItemAvailability(Builder $query): Builder
|
||||||
|
{
|
||||||
|
return $query
|
||||||
|
->where('catalog_items.type', CatalogItemType::Standard->value)
|
||||||
|
->where(function (Builder $query): void {
|
||||||
|
$query
|
||||||
|
->where('catalog_items.inventory_policy', InventoryPolicy::Unlimited->value)
|
||||||
|
->orWhereHas(
|
||||||
|
'inventory',
|
||||||
|
fn (Builder $query): Builder => $query
|
||||||
|
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock'),
|
||||||
|
)
|
||||||
|
->orWhereHas(
|
||||||
|
'variants.inventory',
|
||||||
|
fn (Builder $query): Builder => $query
|
||||||
|
->whereColumn('inventories.real_stock', '>', 'inventories.reserved_stock'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<CatalogItem> $query */
|
||||||
|
private function applyBundleAvailability(Builder $query): Builder
|
||||||
|
{
|
||||||
|
return $query
|
||||||
|
->where('catalog_items.type', CatalogItemType::Bundle->value)
|
||||||
|
->whereRaw(<<<'SQL'
|
||||||
|
NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM bundle_components AS availability_components
|
||||||
|
INNER JOIN catalog_items AS availability_items
|
||||||
|
ON availability_items.id = availability_components.component_catalog_item_id
|
||||||
|
LEFT JOIN variantes AS availability_variants
|
||||||
|
ON availability_variants.id = availability_components.component_variant_id
|
||||||
|
INNER JOIN inventories AS availability_inventories
|
||||||
|
ON availability_inventories.id = COALESCE(
|
||||||
|
availability_variants.inventory_id,
|
||||||
|
availability_items.inventory_id
|
||||||
|
)
|
||||||
|
WHERE availability_components.bundle_catalog_item_id = catalog_items.id
|
||||||
|
AND availability_items.inventory_policy = ?
|
||||||
|
GROUP BY availability_inventories.id,
|
||||||
|
availability_inventories.real_stock,
|
||||||
|
availability_inventories.reserved_stock
|
||||||
|
HAVING availability_inventories.real_stock
|
||||||
|
- availability_inventories.reserved_stock
|
||||||
|
< SUM(availability_components.quantity)
|
||||||
|
)
|
||||||
|
SQL, [InventoryPolicy::Tracked->value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
421
app/Domains/Desfile/Services/InvitationPurchaseProvisioner.php
Normal file
421
app/Domains/Desfile/Services/InvitationPurchaseProvisioner.php
Normal file
@@ -0,0 +1,421 @@
|
|||||||
|
<?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, first_seat: int, last_seat: int, type: string}>
|
||||||
|
*/
|
||||||
|
private const ALLOCATIONS = [
|
||||||
|
['sector' => 'A', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'NORMAL'],
|
||||||
|
['sector' => 'A', 'row' => 3, 'first_seat' => 1, 'last_seat' => 14, 'type' => 'NORMAL'],
|
||||||
|
['sector' => 'C', 'row' => 1, 'first_seat' => 1, 'last_seat' => 16, 'type' => 'VIP + LUNCH'],
|
||||||
|
['sector' => 'C', 'row' => 3, 'first_seat' => 6, 'last_seat' => 7, 'type' => 'NORMAL'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param list<array{sector: string, row: int, first_seat: int, last_seat: int, type: string}>|null $allocations
|
||||||
|
*/
|
||||||
|
public function provision(?array $allocations = null): void
|
||||||
|
{
|
||||||
|
if (! $this->prerequisitesExist()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($allocations): void {
|
||||||
|
$now = now();
|
||||||
|
$userId = $this->userId($now);
|
||||||
|
$purchaseId = $this->purchaseId($userId, $now);
|
||||||
|
$catalogItem = DB::table('catalog_items')
|
||||||
|
->where('tenant_code', self::TENANT_CODE)
|
||||||
|
->where('slug', 'entrada')
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if ($catalogItem === null) {
|
||||||
|
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($allocations ?? self::ALLOCATIONS as $allocation) {
|
||||||
|
foreach (range($allocation['first_seat'], $allocation['last_seat']) as $seat) {
|
||||||
|
$variant = $this->variant(
|
||||||
|
(int) $catalogItem->id,
|
||||||
|
$allocation['sector'],
|
||||||
|
$allocation['row'],
|
||||||
|
$seat,
|
||||||
|
$allocation['type'],
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->createPurchaseItem(
|
||||||
|
$purchaseId,
|
||||||
|
$catalogItem,
|
||||||
|
$variant,
|
||||||
|
$allocation['sector'],
|
||||||
|
$allocation['row'],
|
||||||
|
$seat,
|
||||||
|
$allocation['type'],
|
||||||
|
$now,
|
||||||
|
);
|
||||||
|
$this->createTicketAndCommitStock(
|
||||||
|
$purchaseId,
|
||||||
|
$userId,
|
||||||
|
(int) $catalogItem->id,
|
||||||
|
$variant,
|
||||||
|
$now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function prerequisitesExist(): bool
|
||||||
|
{
|
||||||
|
if (! DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! DB::table('roles')->where('codigo', 'user')->exists()) {
|
||||||
|
throw new RuntimeException('No se encontró el rol de usuario común.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! DB::table('catalog_items')
|
||||||
|
->where('tenant_code', self::TENANT_CODE)
|
||||||
|
->where('slug', 'entrada')
|
||||||
|
->exists()) {
|
||||||
|
throw new RuntimeException('No se encontró el catálogo de entradas del desfile.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function userId(DateTimeInterface $now): int
|
||||||
|
{
|
||||||
|
$user = DB::table('users')->where('email', self::USER_EMAIL)->first();
|
||||||
|
|
||||||
|
if ($user !== null) {
|
||||||
|
if ($user->tenant_codigo !== self::TENANT_CODE) {
|
||||||
|
throw new RuntimeException('El email de invitados ya pertenece a otro tenant.');
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::table('users')->where('id', $user->id)->update([
|
||||||
|
'rol_codigo' => 'user',
|
||||||
|
'nombre_apellido' => 'Invitados Pura Tendencia',
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (int) $user->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::table('users')->insertGetId([
|
||||||
|
'rol_codigo' => 'user',
|
||||||
|
'tenant_codigo' => self::TENANT_CODE,
|
||||||
|
'nombre_apellido' => 'Invitados Pura Tendencia',
|
||||||
|
'email' => self::USER_EMAIL,
|
||||||
|
'email_verified_at' => $now,
|
||||||
|
'password' => Hash::make(Str::random(64)),
|
||||||
|
'dni' => null,
|
||||||
|
'telefono' => null,
|
||||||
|
'remember_token' => null,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function purchaseId(int $userId, DateTimeInterface $now): int
|
||||||
|
{
|
||||||
|
$purchaseId = DB::table('compras')
|
||||||
|
->where('tenant_codigo', self::TENANT_CODE)
|
||||||
|
->where('user_id', $userId)
|
||||||
|
->where('payment_method', self::PAYMENT_METHOD)
|
||||||
|
->value('id');
|
||||||
|
|
||||||
|
if ($purchaseId !== null) {
|
||||||
|
DB::table('compras')->where('id', $purchaseId)->update([
|
||||||
|
'status' => 'paid',
|
||||||
|
'expires_at' => null,
|
||||||
|
'total' => 0,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (int) $purchaseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::table('compras')->insertGetId([
|
||||||
|
'tenant_codigo' => self::TENANT_CODE,
|
||||||
|
'user_id' => $userId,
|
||||||
|
'cart_id' => null,
|
||||||
|
'status' => 'paid',
|
||||||
|
'payment_method' => self::PAYMENT_METHOD,
|
||||||
|
'expires_at' => null,
|
||||||
|
'total' => 0,
|
||||||
|
'dni' => null,
|
||||||
|
'transfer_payer_dni' => null,
|
||||||
|
'telefono' => null,
|
||||||
|
'nombre_apellido' => 'Invitados Pura Tendencia',
|
||||||
|
'email' => self::USER_EMAIL,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function variant(
|
||||||
|
int $catalogItemId,
|
||||||
|
string $sector,
|
||||||
|
int $row,
|
||||||
|
int $seat,
|
||||||
|
string $type,
|
||||||
|
): object {
|
||||||
|
$variant = $this->findVariant($catalogItemId, $sector, $row, $seat);
|
||||||
|
|
||||||
|
if ($variant === null) {
|
||||||
|
$variant = $this->createVariant($catalogItemId, $sector, $row, $seat, $type);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->ensureAttributeOptions($catalogItemId, [
|
||||||
|
'tipo' => $type,
|
||||||
|
'sector' => $sector,
|
||||||
|
'fila' => (string) $row,
|
||||||
|
'asiento' => (string) $seat,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$typeValueId = DB::table('variant_values as variant_value')
|
||||||
|
->join('item_attributes as item_attribute', 'item_attribute.id', '=', 'variant_value.item_attribute_id')
|
||||||
|
->join('attribute', 'attribute.id', '=', 'item_attribute.attribute_id')
|
||||||
|
->where('variant_value.variant_id', $variant->id)
|
||||||
|
->where('attribute.codigo', 'tipo')
|
||||||
|
->value('variant_value.id');
|
||||||
|
|
||||||
|
if ($typeValueId === null) {
|
||||||
|
throw new RuntimeException("La variante {$variant->id} no tiene definido el tipo de entrada.");
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::table('variant_values')->where('id', $typeValueId)->update(['value' => $type]);
|
||||||
|
DB::table('variantes')->where('id', $variant->id)->update([
|
||||||
|
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
|
||||||
|
]);
|
||||||
|
|
||||||
|
return DB::table('variantes')->where('id', $variant->id)->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, string> $values */
|
||||||
|
private function ensureAttributeOptions(int $catalogItemId, array $values): void
|
||||||
|
{
|
||||||
|
$attributes = DB::table('item_attributes')
|
||||||
|
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||||
|
->where('item_attributes.catalog_item_id', $catalogItemId)
|
||||||
|
->pluck('attribute.id', 'attribute.codigo');
|
||||||
|
|
||||||
|
foreach ($values as $code => $value) {
|
||||||
|
$attributeId = $attributes[$code] ?? null;
|
||||||
|
|
||||||
|
if ($attributeId === null) {
|
||||||
|
throw new RuntimeException("Falta el atributo {$code} en el catálogo de entradas.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (DB::table('attribute_options')
|
||||||
|
->where('attribute_id', $attributeId)
|
||||||
|
->where('value', $value)
|
||||||
|
->exists()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lastSortOrder = (int) DB::table('attribute_options')
|
||||||
|
->where('attribute_id', $attributeId)
|
||||||
|
->max('sort_order');
|
||||||
|
|
||||||
|
DB::table('attribute_options')->insert([
|
||||||
|
'attribute_id' => $attributeId,
|
||||||
|
'validity_time_id' => null,
|
||||||
|
'value' => $value,
|
||||||
|
'label' => $value,
|
||||||
|
'sort_order' => $lastSortOrder + 1,
|
||||||
|
'metadata' => null,
|
||||||
|
'created_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function findVariant(int $catalogItemId, string $sector, int $row, int $seat): ?object
|
||||||
|
{
|
||||||
|
$query = DB::table('variantes')->where('catalog_item_id', $catalogItemId);
|
||||||
|
|
||||||
|
foreach (['sector' => $sector, 'fila' => (string) $row, 'asiento' => (string) $seat] as $code => $value) {
|
||||||
|
$query->whereExists(fn ($subquery) => $subquery
|
||||||
|
->selectRaw('1')
|
||||||
|
->from('variant_values as selected_value')
|
||||||
|
->join('item_attributes as selected_item_attribute', 'selected_item_attribute.id', '=', 'selected_value.item_attribute_id')
|
||||||
|
->join('attribute as selected_attribute', 'selected_attribute.id', '=', 'selected_item_attribute.attribute_id')
|
||||||
|
->whereColumn('selected_value.variant_id', 'variantes.id')
|
||||||
|
->where('selected_attribute.codigo', $code)
|
||||||
|
->where('selected_value.value', $value));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createVariant(
|
||||||
|
int $catalogItemId,
|
||||||
|
string $sector,
|
||||||
|
int $row,
|
||||||
|
int $seat,
|
||||||
|
string $type,
|
||||||
|
): object {
|
||||||
|
$itemAttributes = DB::table('item_attributes')
|
||||||
|
->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
|
||||||
|
->where('item_attributes.catalog_item_id', $catalogItemId)
|
||||||
|
->pluck('item_attributes.id', 'attribute.codigo');
|
||||||
|
|
||||||
|
foreach (['tipo', 'sector', 'fila', 'asiento'] as $requiredCode) {
|
||||||
|
if (! isset($itemAttributes[$requiredCode])) {
|
||||||
|
throw new RuntimeException("Falta el atributo {$requiredCode} en el catálogo de entradas.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventoryId = DB::table('inventories')->insertGetId([
|
||||||
|
'sold_units' => 0,
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
'real_stock' => 1,
|
||||||
|
]);
|
||||||
|
$variantId = DB::table('variantes')->insertGetId([
|
||||||
|
'catalog_item_id' => $catalogItemId,
|
||||||
|
'event_date_id' => null,
|
||||||
|
'inventory_id' => $inventoryId,
|
||||||
|
'descripcion' => "Sector {$sector} - Fila {$row} - Asiento {$seat} - {$type}",
|
||||||
|
'precio' => $this->catalogPrice($sector, $row),
|
||||||
|
]);
|
||||||
|
|
||||||
|
foreach (['tipo' => $type, 'sector' => $sector, 'fila' => (string) $row, 'asiento' => (string) $seat] as $code => $value) {
|
||||||
|
DB::table('variant_values')->insert([
|
||||||
|
'variant_id' => $variantId,
|
||||||
|
'item_attribute_id' => $itemAttributes[$code],
|
||||||
|
'value' => $value,
|
||||||
|
'created_at' => now(),
|
||||||
|
'updated_at' => now(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::table('variantes')->where('id', $variantId)->first();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function catalogPrice(string $sector, int $row): int
|
||||||
|
{
|
||||||
|
$prices = in_array($sector, ['A', 'C'], true)
|
||||||
|
? [1 => 250000, 2 => 200000, 3 => 100000, 4 => 75000, 5 => 50000]
|
||||||
|
: [1 => 240000, 2 => 190000, 3 => 90000, 4 => 65000, 5 => 40000];
|
||||||
|
|
||||||
|
return $prices[$row];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createPurchaseItem(
|
||||||
|
int $purchaseId,
|
||||||
|
object $catalogItem,
|
||||||
|
object $variant,
|
||||||
|
string $sector,
|
||||||
|
int $row,
|
||||||
|
int $seat,
|
||||||
|
string $type,
|
||||||
|
DateTimeInterface $now,
|
||||||
|
): void {
|
||||||
|
if (DB::table('compra_items')
|
||||||
|
->where('compra_id', $purchaseId)
|
||||||
|
->where('source_variant_id', $variant->id)
|
||||||
|
->exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$attributes = [
|
||||||
|
['name' => 'Tipo', 'value' => $type],
|
||||||
|
['name' => 'Sector', 'value' => $sector],
|
||||||
|
['name' => 'Fila', 'value' => (string) $row],
|
||||||
|
['name' => 'Asiento', 'value' => (string) $seat],
|
||||||
|
];
|
||||||
|
|
||||||
|
DB::table('compra_items')->insert([
|
||||||
|
'compra_id' => $purchaseId,
|
||||||
|
'source_catalog_item_id' => $catalogItem->id,
|
||||||
|
'source_variant_id' => $variant->id,
|
||||||
|
'image_attachment_id' => DB::table('catalog_items_attachments')
|
||||||
|
->where('catalog_item_id', $catalogItem->id)
|
||||||
|
->whereNull('variant_id')
|
||||||
|
->orderBy('orden')
|
||||||
|
->value('attachment_id'),
|
||||||
|
'nombre' => $catalogItem->nombre,
|
||||||
|
'descripcion' => $variant->descripcion,
|
||||||
|
'slug' => $catalogItem->slug,
|
||||||
|
'item_nombre' => "Entrada (Sector {$sector}, Fila {$row}, Asiento {$seat})",
|
||||||
|
'variant_attributes' => json_encode($attributes, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||||
|
'cantidad' => 1,
|
||||||
|
'precio_unitario' => 0,
|
||||||
|
'discount_total' => 0,
|
||||||
|
'tax_total' => 0,
|
||||||
|
'total' => 0,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createTicketAndCommitStock(
|
||||||
|
int $purchaseId,
|
||||||
|
int $userId,
|
||||||
|
int $catalogItemId,
|
||||||
|
object $variant,
|
||||||
|
DateTimeInterface $now,
|
||||||
|
): void {
|
||||||
|
if (DB::table('tickets')
|
||||||
|
->where('source_purchase_id', $purchaseId)
|
||||||
|
->where('source_variant_id', $variant->id)
|
||||||
|
->exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$inventory = DB::table('inventories')->where('id', $variant->inventory_id)->lockForUpdate()->first();
|
||||||
|
|
||||||
|
if ($inventory === null || $inventory->real_stock < 1 || $inventory->reserved_stock > 0) {
|
||||||
|
throw new RuntimeException("El asiento {$variant->descripcion} ya no está disponible.");
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::table('inventories')->where('id', $inventory->id)->update([
|
||||||
|
'real_stock' => $inventory->real_stock - 1,
|
||||||
|
'sold_units' => $inventory->sold_units + 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
DB::table('stock_reservations')->insert([
|
||||||
|
'inventory_id' => $inventory->id,
|
||||||
|
'cart_item_id' => null,
|
||||||
|
'purchase_id' => $purchaseId,
|
||||||
|
'quantity' => 1,
|
||||||
|
'status' => 'committed',
|
||||||
|
'expires_at' => null,
|
||||||
|
'committed_at' => $now,
|
||||||
|
'released_at' => null,
|
||||||
|
'created_at' => $now,
|
||||||
|
'updated_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
|
DB::table('tickets')->insert([
|
||||||
|
'tenant_code' => self::TENANT_CODE,
|
||||||
|
'ticket' => (string) Str::uuid(),
|
||||||
|
'name' => null,
|
||||||
|
'description' => null,
|
||||||
|
'source_purchase_id' => $purchaseId,
|
||||||
|
'source_catalog_item_id' => $catalogItemId,
|
||||||
|
'source_variant_id' => $variant->id,
|
||||||
|
'used_at' => null,
|
||||||
|
'scanner_user_id' => null,
|
||||||
|
'user_id' => $userId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\FiestaFutbolInfantil\Controllers;
|
||||||
|
|
||||||
|
use App\Domains\FiestaFutbolInfantil\Enums\FiestaCategory;
|
||||||
|
use App\Domains\FiestaFutbolInfantil\Requests\UpdateCategoryVisibilityRequest;
|
||||||
|
use App\Domains\FiestaFutbolInfantil\Services\CategoryVisibilityService;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class CategoryVisibilityController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(private readonly CategoryVisibilityService $visibilityService) {}
|
||||||
|
|
||||||
|
public function show(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$category = $this->category($request);
|
||||||
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'data' => [
|
||||||
|
'is_enabled' => $this->visibilityService->isEnabled($tenant, $category),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(UpdateCategoryVisibilityRequest $request): JsonResponse
|
||||||
|
{
|
||||||
|
$category = $this->category($request);
|
||||||
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
$model = $this->visibilityService->update(
|
||||||
|
$tenant,
|
||||||
|
$category,
|
||||||
|
$request->boolean('is_enabled'),
|
||||||
|
);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'data' => [
|
||||||
|
'is_enabled' => $model->is_enabled,
|
||||||
|
],
|
||||||
|
'message' => $model->is_enabled
|
||||||
|
? 'Mostrar en sitio web se activo correctamente'
|
||||||
|
: 'Mostrar en sitio web se desactivo correctamente',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function category(Request $request): FiestaCategory
|
||||||
|
{
|
||||||
|
return FiestaCategory::from((string) $request->route('category'));
|
||||||
|
}
|
||||||
|
}
|
||||||
21
app/Domains/FiestaFutbolInfantil/Enums/FiestaCategory.php
Normal file
21
app/Domains/FiestaFutbolInfantil/Enums/FiestaCategory.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\FiestaFutbolInfantil\Enums;
|
||||||
|
|
||||||
|
enum FiestaCategory: string
|
||||||
|
{
|
||||||
|
case Entries = 'entries';
|
||||||
|
case Foods = 'foods';
|
||||||
|
case Accommodations = 'accommodations';
|
||||||
|
case Merchandise = 'merchandise';
|
||||||
|
|
||||||
|
public function categoryName(): string
|
||||||
|
{
|
||||||
|
return match ($this) {
|
||||||
|
self::Entries => 'Entradas',
|
||||||
|
self::Foods => 'Comidas',
|
||||||
|
self::Accommodations => 'Alojamientos',
|
||||||
|
self::Merchandise => 'Merchandising',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\FiestaFutbolInfantil\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class UpdateCategoryVisibilityRequest extends FormRequest
|
||||||
|
{
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'is_enabled' => ['required', 'boolean'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\FiestaFutbolInfantil\Services;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
|
use App\Domains\FiestaFutbolInfantil\Enums\FiestaCategory;
|
||||||
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
|
|
||||||
|
class CategoryVisibilityService
|
||||||
|
{
|
||||||
|
public function isEnabled(Tenant $tenant, FiestaCategory $category): bool
|
||||||
|
{
|
||||||
|
return Category::query()
|
||||||
|
->where('tenant_code', $tenant->codigo)
|
||||||
|
->where('nombre', $category->categoryName())
|
||||||
|
->value('is_enabled') ?? true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(Tenant $tenant, FiestaCategory $category, bool $isEnabled): Category
|
||||||
|
{
|
||||||
|
$model = Category::query()->firstOrCreate([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'nombre' => $category->categoryName(),
|
||||||
|
]);
|
||||||
|
$model->update(['is_enabled' => $isEnabled]);
|
||||||
|
|
||||||
|
return $model;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController;
|
use App\Domains\FiestaFutbolInfantil\Controllers\AccommodationController;
|
||||||
|
use App\Domains\FiestaFutbolInfantil\Controllers\CategoryVisibilityController;
|
||||||
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
|
use App\Domains\FiestaFutbolInfantil\Controllers\EntryController;
|
||||||
use App\Domains\FiestaFutbolInfantil\Controllers\FoodController;
|
use App\Domains\FiestaFutbolInfantil\Controllers\FoodController;
|
||||||
use App\Domains\FiestaFutbolInfantil\Controllers\MerchandiseController;
|
use App\Domains\FiestaFutbolInfantil\Controllers\MerchandiseController;
|
||||||
@@ -9,6 +10,20 @@ use Illuminate\Support\Facades\Route;
|
|||||||
Route::prefix('v1/adminapp/tenant')
|
Route::prefix('v1/adminapp/tenant')
|
||||||
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
->middleware(['auth:sanctum', 'adminapp.tenant'])
|
||||||
->group(function (): void {
|
->group(function (): void {
|
||||||
|
$visibilityRoutes = static function (string $endpoint, string $category, string $menuCode): void {
|
||||||
|
Route::get("{$endpoint}/visibility", [CategoryVisibilityController::class, 'show'])
|
||||||
|
->defaults('category', $category)
|
||||||
|
->middleware("tenant.menu:{$menuCode}");
|
||||||
|
Route::patch("{$endpoint}/visibility", [CategoryVisibilityController::class, 'update'])
|
||||||
|
->defaults('category', $category)
|
||||||
|
->middleware("tenant.menu:{$menuCode}");
|
||||||
|
};
|
||||||
|
|
||||||
|
$visibilityRoutes('entries', 'entries', 'adminapp.fiesta-futbol-infantil.entradas');
|
||||||
|
$visibilityRoutes('foods', 'foods', 'adminapp.fiesta-futbol-infantil.comida');
|
||||||
|
$visibilityRoutes('accommodations', 'accommodations', 'adminapp.fiesta-futbol-infantil.alojamientos');
|
||||||
|
$visibilityRoutes('merchandise', 'merchandise', 'adminapp.fiesta-futbol-infantil.merchandising');
|
||||||
|
|
||||||
Route::get('entries', [EntryController::class, 'index'])
|
Route::get('entries', [EntryController::class, 'index'])
|
||||||
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
|
->middleware('tenant.menu:adminapp.fiesta-futbol-infantil.entradas')
|
||||||
->name('adminapp.fiesta-futbol-infantil.entries.index');
|
->name('adminapp.fiesta-futbol-infantil.entries.index');
|
||||||
|
|||||||
@@ -12,10 +12,12 @@ class SaleFormService
|
|||||||
$names = [
|
$names = [
|
||||||
Purchase::STATUS_CREATED => 'Creada',
|
Purchase::STATUS_CREATED => 'Creada',
|
||||||
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
|
Purchase::STATUS_PENDING_PAYMENT => 'Esperando pago',
|
||||||
|
Purchase::STATUS_IN_REVIEW => 'En revisión',
|
||||||
Purchase::STATUS_PAID => 'Confirmada',
|
Purchase::STATUS_PAID => 'Confirmada',
|
||||||
Purchase::STATUS_CANCELLED => 'Cancelada',
|
Purchase::STATUS_CANCELLED => 'Cancelada',
|
||||||
Purchase::STATUS_REJECTED => 'Rechazada',
|
Purchase::STATUS_REJECTED => 'Rechazada',
|
||||||
Purchase::STATUS_EXPIRED => 'Vencida',
|
Purchase::STATUS_EXPIRED => 'Vencida',
|
||||||
|
Purchase::STATUS_SUPERSEDED => 'Reemplazada',
|
||||||
];
|
];
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -39,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];
|
||||||
|
|
||||||
@@ -64,16 +78,21 @@ class TelepagosWebhookService
|
|||||||
->whereIn('status', [
|
->whereIn('status', [
|
||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
])
|
])
|
||||||
->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) {
|
||||||
|
if ($purchases->count() > 1) {
|
||||||
|
TelepagosPayment::create($paymentData);
|
||||||
|
}
|
||||||
|
|
||||||
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
|
Log::channel('telepagos')->warning('Telepagos webhook: Expected exactly one matching purchase.', [
|
||||||
'client_code' => $client->code,
|
'client_code' => $client->code,
|
||||||
'cashin_id' => $cashinId,
|
'cashin_id' => $cashinId,
|
||||||
@@ -163,18 +182,7 @@ class TelepagosWebhookService
|
|||||||
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);
|
||||||
|
|||||||
@@ -8,7 +8,9 @@ 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\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;
|
||||||
@@ -22,13 +24,22 @@ class PurchaseController extends Controller
|
|||||||
{
|
{
|
||||||
public function index(Request $request, Tenant $tenant): JsonResponse
|
public function index(Request $request, Tenant $tenant): JsonResponse
|
||||||
{
|
{
|
||||||
|
$statusParam = $request->query('status');
|
||||||
|
$statuses = is_string($statusParam)
|
||||||
|
? collect(explode(',', $statusParam))
|
||||||
|
->map(fn (string $status): string => trim($status))
|
||||||
|
->filter()
|
||||||
|
->unique()
|
||||||
|
->values()
|
||||||
|
->all()
|
||||||
|
: [];
|
||||||
|
|
||||||
return PurchaseResource::collection(
|
return PurchaseResource::collection(
|
||||||
Purchase::query()
|
Purchase::query()
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('user_id', $request->user()->id)
|
->where('user_id', $request->user()->id)
|
||||||
->when($request->query('status'), function ($query, $status) {
|
->when($statuses !== [], fn ($query) => $query->whereIn('status', $statuses))
|
||||||
$query->where('status', $status);
|
->orderBy('status')
|
||||||
})
|
|
||||||
->latest()
|
->latest()
|
||||||
->paginateFromRequest()
|
->paginateFromRequest()
|
||||||
)->response();
|
)->response();
|
||||||
@@ -50,21 +61,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([
|
$compra->loadMissing('items')->loadCount('tickets');
|
||||||
'items',
|
$responses->load($compra);
|
||||||
'cart.items.catalogItem.inventory',
|
|
||||||
'cart.items.catalogItem.attachments',
|
|
||||||
'cart.items.variant.inventory',
|
|
||||||
'cart.items.variant.attachments',
|
|
||||||
'cart.items.variant.definitions.itemAttribute.attribute',
|
|
||||||
'cart.items.variant.eventDates',
|
|
||||||
'cart.items.variant.eventDate',
|
|
||||||
])->loadCount('tickets');
|
|
||||||
$compra->items->load('imageAttachment');
|
|
||||||
|
|
||||||
return PurchaseResource::make($compra);
|
return PurchaseResource::make($compra);
|
||||||
}
|
}
|
||||||
@@ -87,42 +93,50 @@ class PurchaseController extends Controller
|
|||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
Purchase $compra,
|
Purchase $compra,
|
||||||
CheckoutService $checkoutService,
|
CheckoutService $checkoutService,
|
||||||
|
PurchaseStateGuard $purchaseState,
|
||||||
): JsonResponse {
|
): 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$purchaseState->lockCurrentCart($purchase);
|
||||||
|
|
||||||
|
$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;
|
||||||
@@ -135,6 +149,7 @@ class PurchaseController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
$compra->refresh();
|
$compra->refresh();
|
||||||
|
$totalAmount = (float) $compra->total;
|
||||||
$checkoutService->syncReservationExpiration($compra);
|
$checkoutService->syncReservationExpiration($compra);
|
||||||
|
|
||||||
if ($method === 'transfer') {
|
if ($method === 'transfer') {
|
||||||
|
|||||||
13
app/Domains/Purchase/Exceptions/PurchaseExpiredException.php
Normal file
13
app/Domains/Purchase/Exceptions/PurchaseExpiredException.php
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Exceptions;
|
||||||
|
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class PurchaseExpiredException extends RuntimeException
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct(__('api.purchase.expired'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Exceptions;
|
||||||
|
|
||||||
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
class PurchaseLimitExceededException extends ValidationException
|
||||||
|
{
|
||||||
|
public readonly int $catalogItemId;
|
||||||
|
|
||||||
|
public readonly string $catalogItemName;
|
||||||
|
|
||||||
|
public readonly int $maximumAddableQuantity;
|
||||||
|
|
||||||
|
public function __construct(CatalogItem $catalogItem, int $maximumAddableQuantity, string $field)
|
||||||
|
{
|
||||||
|
$this->catalogItemId = (int) $catalogItem->getKey();
|
||||||
|
$this->catalogItemName = $catalogItem->nombre;
|
||||||
|
$this->maximumAddableQuantity = $maximumAddableQuantity;
|
||||||
|
|
||||||
|
parent::__construct(validator([], []));
|
||||||
|
|
||||||
|
$message = trans_choice('api.purchase_limit.exceeded', $maximumAddableQuantity, [
|
||||||
|
'max' => $maximumAddableQuantity,
|
||||||
|
'product' => $this->catalogItemName,
|
||||||
|
]);
|
||||||
|
$this->message = $message;
|
||||||
|
$this->validator->errors()->add($field, $message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,6 +39,8 @@ class Purchase extends Model
|
|||||||
|
|
||||||
public const STATUS_PENDING_PAYMENT = 'pending_payment';
|
public const STATUS_PENDING_PAYMENT = 'pending_payment';
|
||||||
|
|
||||||
|
public const STATUS_IN_REVIEW = 'in_review';
|
||||||
|
|
||||||
public const STATUS_PAID = 'paid';
|
public const STATUS_PAID = 'paid';
|
||||||
|
|
||||||
public const STATUS_CANCELLED = 'cancelled';
|
public const STATUS_CANCELLED = 'cancelled';
|
||||||
@@ -47,16 +49,20 @@ class Purchase extends Model
|
|||||||
|
|
||||||
public const STATUS_EXPIRED = 'expired';
|
public const STATUS_EXPIRED = 'expired';
|
||||||
|
|
||||||
|
public const STATUS_SUPERSEDED = 'superseded';
|
||||||
|
|
||||||
/** @return list<string> */
|
/** @return list<string> */
|
||||||
public static function statuses(): array
|
public static function statuses(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
self::STATUS_CREATED,
|
self::STATUS_CREATED,
|
||||||
self::STATUS_PENDING_PAYMENT,
|
self::STATUS_PENDING_PAYMENT,
|
||||||
|
self::STATUS_IN_REVIEW,
|
||||||
self::STATUS_PAID,
|
self::STATUS_PAID,
|
||||||
self::STATUS_CANCELLED,
|
self::STATUS_CANCELLED,
|
||||||
self::STATUS_REJECTED,
|
self::STATUS_REJECTED,
|
||||||
self::STATUS_EXPIRED,
|
self::STATUS_EXPIRED,
|
||||||
|
self::STATUS_SUPERSEDED,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,12 +160,7 @@ class Purchase extends Model
|
|||||||
return (float) $this->getRelation('items')->sum('total');
|
return (float) $this->getRelation('items')->sum('total');
|
||||||
}
|
}
|
||||||
|
|
||||||
$itemsTotal = (float) $this->items()->sum('total');
|
return (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
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -59,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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,12 @@
|
|||||||
|
|
||||||
namespace App\Domains\Purchase\Resources;
|
namespace App\Domains\Purchase\Resources;
|
||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
|
||||||
use App\Domains\Catalog\Models\CatalogItem;
|
|
||||||
use App\Domains\Catalog\Models\Variant;
|
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
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;
|
||||||
|
|
||||||
/** @mixin PurchaseItem|CartItem */
|
/** @mixin PurchaseItem */
|
||||||
class PurchaseItemResource extends JsonResource
|
class PurchaseItemResource extends JsonResource
|
||||||
{
|
{
|
||||||
/** @return array<string, mixed> */
|
/** @return array<string, mixed> */
|
||||||
@@ -19,115 +16,27 @@ class PurchaseItemResource extends JsonResource
|
|||||||
$tenant = $request->route('tenant');
|
$tenant = $request->route('tenant');
|
||||||
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
$displayImage = ! $tenant instanceof Tenant || $tenant->display_cart_item_images;
|
||||||
|
|
||||||
if ($this->resource instanceof PurchaseItem) {
|
|
||||||
$imageUrl = $displayImage
|
|
||||||
? $this->imageAttachment?->getTemporaryUrl(1440)
|
|
||||||
: null;
|
|
||||||
$attributes = $this->variant_attributes ?? [];
|
|
||||||
|
|
||||||
return [
|
|
||||||
'id' => $this->id,
|
|
||||||
'quantity' => (int) $this->cantidad,
|
|
||||||
'unit_price' => $this->formatMoney($this->precio_unitario),
|
|
||||||
'line_total' => $this->formatMoney($this->total),
|
|
||||||
'source_catalog_item_id' => $this->source_catalog_item_id,
|
|
||||||
'source_variant_id' => $this->source_variant_id,
|
|
||||||
'item_details' => [
|
|
||||||
'nombre' => $this->item_nombre,
|
|
||||||
'descripcion' => $this->descripcion,
|
|
||||||
'slug' => $this->slug,
|
|
||||||
'imagen' => $imageUrl,
|
|
||||||
'attributes' => $attributes,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
$selectedItem = $this->selectedItem();
|
|
||||||
$catalogItem = $this->catalogItem;
|
|
||||||
$variant = $this->variant;
|
|
||||||
$quantity = (int) ($this->cantidad ?? 0);
|
|
||||||
$unitPrice = $this->resolveUnitPrice($selectedItem);
|
|
||||||
$lineTotal = $unitPrice * $quantity;
|
|
||||||
$imageUrl = $displayImage
|
$imageUrl = $displayImage
|
||||||
? $this->resolveImageUrl($selectedItem, $catalogItem)
|
? $this->imageAttachment?->getTemporaryUrl(1440)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'id' => $this->id,
|
'id' => $this->id,
|
||||||
'quantity' => $quantity,
|
'quantity' => (int) $this->cantidad,
|
||||||
'unit_price' => $this->formatMoney($unitPrice),
|
'unit_price' => $this->formatMoney($this->precio_unitario),
|
||||||
'line_total' => $this->formatMoney($lineTotal),
|
'line_total' => $this->formatMoney($this->total),
|
||||||
'source_catalog_item_id' => $this->catalog_item_id,
|
'source_catalog_item_id' => $this->source_catalog_item_id,
|
||||||
'source_variant_id' => $this->variant_id,
|
'source_variant_id' => $this->source_variant_id,
|
||||||
'item_details' => $selectedItem === null ? null : [
|
'item_details' => [
|
||||||
'nombre' => $selectedItem->getName(),
|
'nombre' => $this->item_nombre,
|
||||||
'descripcion' => $selectedItem->getDescription(),
|
'descripcion' => $this->descripcion,
|
||||||
'slug' => $catalogItem?->slug,
|
'slug' => $this->slug,
|
||||||
'imagen' => $imageUrl,
|
'imagen' => $imageUrl,
|
||||||
'attributes' => $variant === null ? [] : $this->resolveAttributes($variant),
|
'attributes' => $this->variant_attributes ?? [],
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function resolveUnitPrice(CatalogItem|Variant|null $selectedItem): float
|
|
||||||
{
|
|
||||||
return (float) ($selectedItem?->getPrice() ?? 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
private function resolveImageUrl(
|
|
||||||
CatalogItem|Variant|null $selectedItem,
|
|
||||||
?CatalogItem $catalogItem,
|
|
||||||
): ?string {
|
|
||||||
$attachment = $selectedItem?->relationLoaded('attachments')
|
|
||||||
? $selectedItem->attachments->first()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
if ($attachment === null && $catalogItem?->relationLoaded('attachments')) {
|
|
||||||
$attachment = $catalogItem->attachments->first();
|
|
||||||
}
|
|
||||||
|
|
||||||
return $attachment?->getTemporaryUrl(1440);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return array<int, array{name: string, value: mixed}> */
|
|
||||||
private function resolveAttributes(Variant $variant): array
|
|
||||||
{
|
|
||||||
if (! $variant->relationLoaded('definitions')) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$attributes = $variant->definitions
|
|
||||||
->groupBy('item_attribute_id')
|
|
||||||
->map(function ($definitions): array {
|
|
||||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
|
||||||
$values = $definitions->pluck('value')->values();
|
|
||||||
|
|
||||||
return [
|
|
||||||
'name' => (string) ($itemAttribute?->attribute?->nombre ?? ''),
|
|
||||||
'value' => $itemAttribute?->allow_multi_select
|
|
||||||
? $values->all()
|
|
||||||
: $values->first(),
|
|
||||||
];
|
|
||||||
})
|
|
||||||
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
|
|
||||||
->values();
|
|
||||||
|
|
||||||
$eventDates = $variant->relationLoaded('eventDates')
|
|
||||||
? $variant->selectedEventDates()
|
|
||||||
: collect();
|
|
||||||
if ($eventDates->isNotEmpty()) {
|
|
||||||
$attributes->prepend([
|
|
||||||
'name' => 'Fecha',
|
|
||||||
'value' => $eventDates
|
|
||||||
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
|
|
||||||
->values()
|
|
||||||
->all(),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $attributes->all();
|
|
||||||
}
|
|
||||||
|
|
||||||
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, '.', '');
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
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;
|
||||||
@@ -18,25 +17,16 @@ class PurchaseResource extends JsonResource
|
|||||||
*/
|
*/
|
||||||
public function toArray(Request $request): array
|
public function toArray(Request $request): array
|
||||||
{
|
{
|
||||||
$purchaseItems = $this->resource->relationLoaded('items')
|
$items = $this->resource->relationLoaded('items')
|
||||||
? $this->resource->getRelation('items')
|
? $this->resource->getRelation('items')
|
||||||
: collect();
|
: collect();
|
||||||
$cartItems = $purchaseItems->isEmpty()
|
|
||||||
&& $this->resource->relationLoaded('cart')
|
|
||||||
&& $this->resource->getRelation('cart')?->relationLoaded('items')
|
|
||||||
? $this->resource->getRelation('cart')->getRelation('items')
|
|
||||||
: collect();
|
|
||||||
$items = $purchaseItems->isNotEmpty() ? $purchaseItems : $cartItems;
|
|
||||||
$itemsSource = $purchaseItems->isNotEmpty()
|
|
||||||
? 'purchase'
|
|
||||||
: ($cartItems->isNotEmpty() ? 'cart' : null);
|
|
||||||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
$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|CartItem $item): float => $carry + $this->resolveItemSubtotal($item),
|
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemSubtotal($item),
|
||||||
0.0,
|
0.0,
|
||||||
)
|
)
|
||||||
: (float) ($this->total ?? 0);
|
: (float) ($this->total ?? 0);
|
||||||
@@ -45,7 +35,7 @@ class PurchaseResource extends JsonResource
|
|||||||
? (float) $this->total
|
? (float) $this->total
|
||||||
: ($items->isNotEmpty()
|
: ($items->isNotEmpty()
|
||||||
? $items->reduce(
|
? $items->reduce(
|
||||||
fn (float $carry, PurchaseItem|CartItem $item): float => $carry + $this->resolveItemTotal($item),
|
fn (float $carry, PurchaseItem $item): float => $carry + $this->resolveItemTotal($item),
|
||||||
0.0,
|
0.0,
|
||||||
)
|
)
|
||||||
: (float) ($this->total ?? 0));
|
: (float) ($this->total ?? 0));
|
||||||
@@ -64,7 +54,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' => $itemsSource,
|
'items_source' => $items->isNotEmpty() ? 'purchase' : null,
|
||||||
'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),
|
||||||
@@ -73,21 +63,13 @@ class PurchaseResource extends JsonResource
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function resolveItemSubtotal(PurchaseItem|CartItem $item): float
|
protected function resolveItemSubtotal(PurchaseItem $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|CartItem $item): float
|
protected function resolveItemTotal(PurchaseItem $item): float
|
||||||
{
|
{
|
||||||
if ($item instanceof CartItem) {
|
|
||||||
return $this->resolveItemSubtotal($item);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (float) ($item->total ?? 0);
|
return (float) ($item->total ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Purchase\Services\Checkout;
|
|||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\Cart\Models\CartItem;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -14,13 +15,14 @@ class CompleteCheckoutService
|
|||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly StockReservationService $reservations,
|
private readonly StockReservationService $reservations,
|
||||||
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([
|
||||||
@@ -32,6 +34,8 @@ class CompleteCheckoutService
|
|||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->purchaseState->lockCurrentCart($purchase);
|
||||||
|
|
||||||
$purchase->update([
|
$purchase->update([
|
||||||
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||||
'total' => $purchase->calculateCurrentTotalAmount(),
|
'total' => $purchase->calculateCurrentTotalAmount(),
|
||||||
@@ -45,11 +49,18 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($purchase->status === Purchase::STATUS_IN_REVIEW) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->purchaseState->lockCurrentCart($purchase);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|
$purchase->status !== Purchase::STATUS_PENDING_PAYMENT
|
||||||
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
|| ($purchase->expires_at !== null && $purchase->expires_at->isPast())
|
||||||
@@ -59,7 +70,10 @@ class CompleteCheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$purchase->update(['expires_at' => null]);
|
$purchase->update([
|
||||||
|
'status' => Purchase::STATUS_IN_REVIEW,
|
||||||
|
'expires_at' => null,
|
||||||
|
]);
|
||||||
$this->reservations->syncPurchaseExpiration($purchase);
|
$this->reservations->syncPurchaseExpiration($purchase);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
@@ -70,6 +84,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;
|
||||||
@@ -79,25 +94,26 @@ class CompleteCheckoutService
|
|||||||
Purchase::STATUS_CANCELLED,
|
Purchase::STATUS_CANCELLED,
|
||||||
Purchase::STATUS_REJECTED,
|
Purchase::STATUS_REJECTED,
|
||||||
Purchase::STATUS_EXPIRED,
|
Purchase::STATUS_EXPIRED,
|
||||||
|
Purchase::STATUS_SUPERSEDED,
|
||||||
], true)) {
|
], true)) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'purchase' => __('api.purchase.cannot_confirm'),
|
'purchase' => __('api.purchase.cannot_confirm'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($purchase->items()->exists()) {
|
if (! $purchase->items()->exists()) {
|
||||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
|
||||||
if ($cart?->status === 'converted' && $cart->trashed()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$cart = $purchase->cart()->lockForUpdate()->first();
|
$cart = $this->purchaseState->lockCurrentCart($purchase);
|
||||||
if ($cart === null || $cart->status !== 'checkout') {
|
|
||||||
|
if ($cart->status === 'converted' && $cart->trashed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! in_array($cart->status, ['active', 'checkout'], true)) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
]);
|
]);
|
||||||
@@ -110,10 +126,32 @@ class CompleteCheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$snapshotQuantities = $purchase->items()
|
||||||
|
->lockForUpdate()
|
||||||
|
->get(['source_catalog_item_id', 'source_variant_id', 'cantidad'])
|
||||||
|
->groupBy(fn ($item): string => $this->itemKey(
|
||||||
|
(int) $item->source_catalog_item_id,
|
||||||
|
$item->source_variant_id === null ? null : (int) $item->source_variant_id,
|
||||||
|
))
|
||||||
|
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
|
||||||
|
->sortKeys()
|
||||||
|
->all();
|
||||||
|
$cartQuantities = $cartItems
|
||||||
|
->groupBy(fn (CartItem $item): string => $this->itemKey(
|
||||||
|
(int) $item->catalog_item_id,
|
||||||
|
$item->variant_id === null ? null : (int) $item->variant_id,
|
||||||
|
))
|
||||||
|
->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
|
||||||
|
->sortKeys()
|
||||||
|
->all();
|
||||||
|
|
||||||
|
if ($snapshotQuantities !== $cartQuantities) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
$this->loadCartItems($cartItems);
|
$this->loadCartItems($cartItems);
|
||||||
$purchase->items()->createMany(
|
|
||||||
$this->snapshots->fromCartItems($cartItems),
|
|
||||||
);
|
|
||||||
|
|
||||||
foreach ($cartItems as $cartItem) {
|
foreach ($cartItems as $cartItem) {
|
||||||
$selection = $cartItem->selectedItem();
|
$selection = $cartItem->selectedItem();
|
||||||
@@ -124,7 +162,7 @@ class CompleteCheckoutService
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$this->reservations->commit($cartItem, $selection);
|
$this->reservations->commit($cartItem, $selection, $purchase);
|
||||||
} catch (\InvalidArgumentException) {
|
} catch (\InvalidArgumentException) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
'items' => __('api.purchase.inconsistent_reservation'),
|
||||||
@@ -140,9 +178,11 @@ class CompleteCheckoutService
|
|||||||
{
|
{
|
||||||
return in_array($purchase->status, [
|
return in_array($purchase->status, [
|
||||||
Purchase::STATUS_PAID,
|
Purchase::STATUS_PAID,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
Purchase::STATUS_CANCELLED,
|
Purchase::STATUS_CANCELLED,
|
||||||
Purchase::STATUS_REJECTED,
|
Purchase::STATUS_REJECTED,
|
||||||
Purchase::STATUS_EXPIRED,
|
Purchase::STATUS_EXPIRED,
|
||||||
|
Purchase::STATUS_SUPERSEDED,
|
||||||
], true);
|
], true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,16 +194,12 @@ class CompleteCheckoutService
|
|||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
private function loadPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load([
|
return $purchase->load(['items.imageAttachment']);
|
||||||
'items.imageAttachment',
|
}
|
||||||
'cart.items.catalogItem.inventory',
|
|
||||||
'cart.items.catalogItem.attachments',
|
private function itemKey(int $catalogItemId, ?int $variantId): string
|
||||||
'cart.items.variant.inventory',
|
{
|
||||||
'cart.items.variant.attachments',
|
return $catalogItemId.':'.($variantId ?? 'none');
|
||||||
'cart.items.variant.definitions.itemAttribute.attribute',
|
|
||||||
'cart.items.variant.eventDates',
|
|
||||||
'cart.items.variant.eventDate',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param Collection<int, CartItem> $cartItems */
|
/** @param Collection<int, CartItem> $cartItems */
|
||||||
|
|||||||
@@ -3,61 +3,39 @@
|
|||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Purchase\Services\Checkout;
|
||||||
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
class EditCheckoutService
|
class EditCheckoutService
|
||||||
{
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly PurchaseResponseLoader $responses,
|
||||||
|
private readonly PurchaseStateGuard $purchaseState,
|
||||||
|
) {}
|
||||||
|
|
||||||
/** @param array<string, string> $customerData */
|
/** @param array<string, string> $customerData */
|
||||||
public function updateCustomer(Purchase $purchase, array $customerData): Purchase
|
public function updateCustomer(Purchase $purchase, array $customerData): Purchase
|
||||||
{
|
{
|
||||||
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
/** @var Purchase $purchase */
|
||||||
$this->assertEditable($purchase);
|
$purchase = Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
|
|
||||||
|
if (! in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'purchase' => __('api.purchase.not_editable'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->purchaseState->lockCurrentCart($purchase);
|
||||||
|
|
||||||
$purchase->update($customerData);
|
$purchase->update($customerData);
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->responses->load($purchase);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private function assertEditable(Purchase $purchase): void
|
|
||||||
{
|
|
||||||
if (
|
|
||||||
! in_array($purchase->status, [
|
|
||||||
Purchase::STATUS_CREATED,
|
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
|
||||||
], true)
|
|
||||||
|| $this->hasExpired($purchase)
|
|
||||||
) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'purchase' => __('api.purchase.not_editable'),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function hasExpired(Purchase $purchase): bool
|
|
||||||
{
|
|
||||||
return $purchase->expires_at !== null && $purchase->expires_at->isPast();
|
|
||||||
}
|
|
||||||
|
|
||||||
private function lockPurchase(Purchase $purchase): Purchase
|
|
||||||
{
|
|
||||||
/** @var Purchase */
|
|
||||||
return Purchase::query()->lockForUpdate()->findOrFail($purchase->getKey());
|
|
||||||
}
|
|
||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
|
||||||
{
|
|
||||||
return $purchase->load([
|
|
||||||
'items.imageAttachment',
|
|
||||||
'cart.items.catalogItem.inventory',
|
|
||||||
'cart.items.catalogItem.attachments',
|
|
||||||
'cart.items.variant.inventory',
|
|
||||||
'cart.items.variant.attachments',
|
|
||||||
'cart.items.variant.definitions.itemAttribute.attribute',
|
|
||||||
'cart.items.variant.eventDates',
|
|
||||||
'cart.items.variant.eventDate',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Services\Checkout;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
|
||||||
|
class PurchaseResponseLoader
|
||||||
|
{
|
||||||
|
public function load(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
return $purchase->load(['tenant', 'items.imageAttachment']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,32 +2,34 @@
|
|||||||
|
|
||||||
namespace App\Domains\Purchase\Services\Checkout;
|
namespace App\Domains\Purchase\Services\Checkout;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
use App\Domains\Catalog\Models\StockReservation;
|
use App\Domains\Catalog\Models\StockReservation;
|
||||||
use App\Domains\Catalog\Services\StockReservationService;
|
use App\Domains\Catalog\Services\StockReservationService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
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 StockReservationService $reservations,
|
private readonly StockReservationService $reservations,
|
||||||
private readonly SourceCartService $sourceCart,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
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 cancelFromAdmin(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $this->release($purchase, Purchase::STATUS_CANCELLED, restoreCart: false);
|
return $this->release($purchase, Purchase::STATUS_CANCELLED, allowInReviewCancellation: true);
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -40,7 +42,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++;
|
||||||
@@ -50,9 +66,16 @@ class ReleaseCheckoutService
|
|||||||
return $expiredCount;
|
return $expiredCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function release(Purchase $purchase, string $targetStatus, bool $restoreCart): Purchase
|
private function release(
|
||||||
{
|
Purchase $purchase,
|
||||||
return DB::transaction(function () use ($purchase, $targetStatus, $restoreCart): Purchase {
|
string $targetStatus,
|
||||||
|
bool $allowInReviewCancellation = false,
|
||||||
|
): Purchase {
|
||||||
|
return DB::transaction(function () use (
|
||||||
|
$purchase,
|
||||||
|
$targetStatus,
|
||||||
|
$allowInReviewCancellation,
|
||||||
|
): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
@@ -65,6 +88,14 @@ class ReleaseCheckoutService
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
$purchase->status === Purchase::STATUS_IN_REVIEW
|
||||||
|
&& $targetStatus === Purchase::STATUS_CANCELLED
|
||||||
|
&& ! $allowInReviewCancellation
|
||||||
|
) {
|
||||||
|
return $this->createNewCartWithoutCancelling($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
if ($this->isAlreadyReleased($purchase)) {
|
if ($this->isAlreadyReleased($purchase)) {
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
@@ -76,14 +107,7 @@ class ReleaseCheckoutService
|
|||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($purchase->items()->exists()) {
|
$this->releasePurchaseReservations($purchase, $targetStatus);
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'items' => __('api.purchase.inconsistent_reservation'),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$reservationReturnedToCart = $restoreCart && $this->sourceCart->restore($purchase);
|
|
||||||
$this->releaseCartReservations($purchase, $reservationReturnedToCart, $targetStatus);
|
|
||||||
|
|
||||||
$purchase->update(['status' => $targetStatus]);
|
$purchase->update(['status' => $targetStatus]);
|
||||||
|
|
||||||
@@ -91,19 +115,24 @@ class ReleaseCheckoutService
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private function releaseCartReservations(
|
private function releasePurchaseReservations(Purchase $purchase, string $targetStatus): void
|
||||||
Purchase $purchase,
|
{
|
||||||
bool $reservationReturnedToCart,
|
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
string $targetStatus,
|
if ($cart === null) {
|
||||||
): void {
|
return;
|
||||||
if ($reservationReturnedToCart) {
|
}
|
||||||
|
|
||||||
|
if ($cart->status === 'active') {
|
||||||
$this->reservations->detachFromPurchase($purchase);
|
$this->reservations->detachFromPurchase($purchase);
|
||||||
|
Cart::query()
|
||||||
|
->whereKey($cart->getKey())
|
||||||
|
->where('current_purchase_id', $purchase->getKey())
|
||||||
|
->update(['current_purchase_id' => null]);
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
if ($cart->status !== 'checkout') {
|
||||||
if ($cart === null) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,12 +173,40 @@ class ReleaseCheckoutService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function createNewCartWithoutCancelling(Purchase $purchase): Purchase
|
||||||
|
{
|
||||||
|
return DB::transaction(function () use ($purchase): Purchase {
|
||||||
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
|
if ($purchase->status !== Purchase::STATUS_IN_REVIEW || $purchase->user_id === null) {
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Cart|null $sourceCart */
|
||||||
|
$sourceCart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
|
if ($sourceCart !== null && ! $sourceCart->trashed() && $sourceCart->status === 'active') {
|
||||||
|
$sourceCart->update(['status' => 'checkout']);
|
||||||
|
}
|
||||||
|
|
||||||
|
Cart::query()->firstOrCreate([
|
||||||
|
'tenant_codigo' => $purchase->tenant_codigo,
|
||||||
|
'user_id' => $purchase->user_id,
|
||||||
|
'guest_token' => null,
|
||||||
|
'status' => 'active',
|
||||||
|
'origin' => Cart::ORIGIN_USER,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->loadPurchase($purchase);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private function isAlreadyReleased(Purchase $purchase): bool
|
private function isAlreadyReleased(Purchase $purchase): bool
|
||||||
{
|
{
|
||||||
return in_array($purchase->status, [
|
return in_array($purchase->status, [
|
||||||
Purchase::STATUS_CANCELLED,
|
Purchase::STATUS_CANCELLED,
|
||||||
Purchase::STATUS_REJECTED,
|
Purchase::STATUS_REJECTED,
|
||||||
Purchase::STATUS_EXPIRED,
|
Purchase::STATUS_EXPIRED,
|
||||||
|
Purchase::STATUS_SUPERSEDED,
|
||||||
], true);
|
], true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,15 +218,6 @@ class ReleaseCheckoutService
|
|||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
private function loadPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load([
|
return $purchase->load(['items.imageAttachment']);
|
||||||
'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',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,65 +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\Catalog\Services\StockReservationService;
|
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
|
||||||
class SourceCartService
|
class SourceCartService
|
||||||
{
|
{
|
||||||
public function __construct(
|
|
||||||
private readonly StockReservationService $reservations,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function restore(Purchase $purchase): bool
|
|
||||||
{
|
|
||||||
$sourceCart = $this->findSourceCart($purchase);
|
|
||||||
|
|
||||||
if ($sourceCart === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($sourceCart->origin === Cart::ORIGIN_DIRECT_CHECKOUT) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var Cart|null $activeCart */
|
|
||||||
$activeCart = Cart::query()
|
|
||||||
->where('tenant_codigo', $purchase->tenant_codigo)
|
|
||||||
->where('user_id', $purchase->user_id)
|
|
||||||
->where('status', 'active')
|
|
||||||
->where('id', '!=', $sourceCart->getKey())
|
|
||||||
->lockForUpdate()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if ($activeCart !== null) {
|
|
||||||
$this->mergeIntoActiveCart($sourceCart, $activeCart);
|
|
||||||
|
|
||||||
$sourceCart->update([
|
|
||||||
'status' => 'converted',
|
|
||||||
'guest_token' => null,
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (! $sourceCart->trashed()) {
|
|
||||||
$sourceCart->delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($sourceCart->trashed()) {
|
|
||||||
$sourceCart->restore();
|
|
||||||
}
|
|
||||||
|
|
||||||
$sourceCart->update([
|
|
||||||
'status' => 'active',
|
|
||||||
'user_id' => $purchase->user_id,
|
|
||||||
'guest_token' => null,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function finalize(Purchase $purchase): void
|
public function finalize(Purchase $purchase): void
|
||||||
{
|
{
|
||||||
$sourceCart = $this->findSourceCart($purchase);
|
$sourceCart = $this->findSourceCart($purchase);
|
||||||
@@ -89,30 +34,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) {
|
|
||||||
$activeItem = $activeCart->items()->create([
|
|
||||||
'catalog_item_id' => $sourceItem->catalog_item_id,
|
|
||||||
'variant_id' => $sourceItem->variant_id,
|
|
||||||
'cantidad' => $sourceItem->cantidad,
|
|
||||||
]);
|
|
||||||
} else {
|
|
||||||
$activeItem->increment('cantidad', (int) $sourceItem->cantidad);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->reservations->transfer($sourceItem, $activeItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ class StartCheckoutService
|
|||||||
private readonly UserPurchaseLimitService $purchaseLimits,
|
private readonly UserPurchaseLimitService $purchaseLimits,
|
||||||
private readonly CatalogSelectionResolver $selections,
|
private readonly CatalogSelectionResolver $selections,
|
||||||
private readonly InsufficientStockMessageBuilder $stockMessages,
|
private readonly InsufficientStockMessageBuilder $stockMessages,
|
||||||
|
private readonly PurchaseResponseLoader $responses,
|
||||||
|
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, mixed> $purchaseData */
|
/** @param array<string, mixed> $purchaseData */
|
||||||
@@ -119,10 +121,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',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -185,6 +193,11 @@ class StartCheckoutService
|
|||||||
),
|
),
|
||||||
$cart->getKey(),
|
$cart->getKey(),
|
||||||
);
|
);
|
||||||
|
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
||||||
|
|
||||||
|
$cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
|
||||||
|
$this->loadCartItems($cartItems);
|
||||||
|
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||||
|
|
||||||
foreach ($cartItems as $index => $cartItem) {
|
foreach ($cartItems as $index => $cartItem) {
|
||||||
$this->reservations->attachToPurchase(
|
$this->reservations->attachToPurchase(
|
||||||
@@ -242,7 +255,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(
|
||||||
@@ -252,6 +265,9 @@ class StartCheckoutService
|
|||||||
$cart->getTotalAmount(),
|
$cart->getTotalAmount(),
|
||||||
$cart->getKey(),
|
$cart->getKey(),
|
||||||
);
|
);
|
||||||
|
$cart->update(['current_purchase_id' => $purchase->getKey()]);
|
||||||
|
$purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));
|
||||||
|
|
||||||
foreach ($cartItems as $cartItem) {
|
foreach ($cartItems as $cartItem) {
|
||||||
$this->reservations->attachToPurchase(
|
$this->reservations->attachToPurchase(
|
||||||
$cartItem,
|
$cartItem,
|
||||||
@@ -260,21 +276,57 @@ class StartCheckoutService
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The purchase owns the reservation until checkout finishes. The cart is
|
|
||||||
// retained so it can be restored if the purchase is cancelled or expires.
|
|
||||||
$cart->update([
|
|
||||||
'status' => 'checkout',
|
|
||||||
'guest_token' => null,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function resolveCart(Tenant $tenant, int $userId, int $cartId): Cart
|
private function resolveCart(Tenant $tenant, int $userId, int $cartId): Cart
|
||||||
{
|
{
|
||||||
|
/** @var Cart|null $candidate */
|
||||||
|
$candidate = Cart::query()->find($cartId);
|
||||||
|
|
||||||
|
$this->assertCartCanCheckout($candidate, $tenant, $userId);
|
||||||
|
|
||||||
|
$candidatePurchaseId = $candidate->current_purchase_id;
|
||||||
|
$currentPurchase = $candidatePurchaseId === null
|
||||||
|
? null
|
||||||
|
: Purchase::query()->lockForUpdate()->find($candidatePurchaseId);
|
||||||
|
|
||||||
/** @var Cart|null $cart */
|
/** @var Cart|null $cart */
|
||||||
$cart = Cart::query()->lockForUpdate()->find($cartId);
|
$cart = Cart::query()->lockForUpdate()->find($cartId);
|
||||||
|
|
||||||
|
$this->assertCartCanCheckout($cart, $tenant, $userId);
|
||||||
|
|
||||||
|
if ($cart->current_purchase_id !== $candidatePurchaseId) {
|
||||||
|
if ($cart->current_purchase_id !== null) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'cart_id' => __('api.purchase.checkout_in_progress'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$currentPurchase = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($currentPurchase?->status === Purchase::STATUS_PAID) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'cart_id' => __('api.purchase.checkout_in_progress'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($currentPurchase !== null && in_array($currentPurchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
$currentPurchase->update([
|
||||||
|
'status' => Purchase::STATUS_SUPERSEDED,
|
||||||
|
'expires_at' => null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cart;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function assertCartCanCheckout(?Cart $cart, Tenant $tenant, int $userId): void
|
||||||
|
{
|
||||||
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
|
if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
|
||||||
throw new NotFoundHttpException('Cart not found for tenant.');
|
throw new NotFoundHttpException('Cart not found for tenant.');
|
||||||
}
|
}
|
||||||
@@ -284,8 +336,6 @@ class StartCheckoutService
|
|||||||
'cart_id' => __('api.purchase.inactive_cart'),
|
'cart_id' => __('api.purchase.inactive_cart'),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $cart;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param Collection<int, CartItem> $cartItems */
|
/** @param Collection<int, CartItem> $cartItems */
|
||||||
@@ -311,6 +361,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')
|
||||||
@@ -332,6 +383,8 @@ class StartCheckoutService
|
|||||||
$catalogItem,
|
$catalogItem,
|
||||||
$userId,
|
$userId,
|
||||||
$quantity,
|
$quantity,
|
||||||
|
excludedCartId: $cartId,
|
||||||
|
heldQuantity: $quantity,
|
||||||
field: 'cart_id',
|
field: 'cart_id',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -376,15 +429,6 @@ class StartCheckoutService
|
|||||||
|
|
||||||
private function loadPurchase(Purchase $purchase): Purchase
|
private function loadPurchase(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $purchase->load([
|
return $this->responses->load($purchase);
|
||||||
'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',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,9 +68,9 @@ class CheckoutService
|
|||||||
return $this->releaser->cancel($purchase);
|
return $this->releaser->cancel($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function cancelPurchaseWithoutRestoringCart(Purchase $purchase): Purchase
|
public function cancelPurchaseFromAdmin(Purchase $purchase): Purchase
|
||||||
{
|
{
|
||||||
return $this->releaser->cancelWithoutRestoringCart($purchase);
|
return $this->releaser->cancelFromAdmin($purchase);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function expirePurchase(Purchase $purchase): Purchase
|
public function expirePurchase(Purchase $purchase): Purchase
|
||||||
|
|||||||
40
app/Domains/Purchase/Services/PurchaseStateGuard.php
Normal file
40
app/Domains/Purchase/Services/PurchaseStateGuard.php
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
|
use App\Domains\Cart\Models\Cart;
|
||||||
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function lockCurrentCart(Purchase $purchase): Cart
|
||||||
|
{
|
||||||
|
/** @var Cart|null $cart */
|
||||||
|
$cart = $purchase->cart()->withTrashed()->lockForUpdate()->first();
|
||||||
|
|
||||||
|
if ($cart === null || $cart->current_purchase_id !== $purchase->getKey()) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'purchase' => __('api.purchase.not_current'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $cart;
|
||||||
|
}
|
||||||
|
}
|
||||||
145
app/Domains/Purchase/Services/TenantTransactionResetService.php
Normal file
145
app/Domains/Purchase/Services/TenantTransactionResetService.php
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
|
||||||
|
class TenantTransactionResetService
|
||||||
|
{
|
||||||
|
/** @return array<string, int> */
|
||||||
|
public function preview(string $tenantCode): array
|
||||||
|
{
|
||||||
|
$this->ensureTenantExists($tenantCode);
|
||||||
|
$scope = $this->scope($tenantCode);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'users_preserved' => DB::table('users')->where('tenant_codigo', $tenantCode)->count(),
|
||||||
|
'purchases' => $scope['purchase_ids']->count(),
|
||||||
|
'purchase_items' => DB::table('compra_items')->whereIn('compra_id', $scope['purchase_ids'])->count(),
|
||||||
|
'telepagos_payments' => DB::table('telepagos_payments')->whereIn('compra_id', $scope['purchase_ids'])->count(),
|
||||||
|
'telepagos_qr' => DB::table('telepagos_qr')->whereIn('compra_id', $scope['purchase_ids'])->count(),
|
||||||
|
'carts' => $scope['cart_ids']->count(),
|
||||||
|
'cart_items' => $scope['cart_item_ids']->count(),
|
||||||
|
'tickets' => DB::table('tickets')->where('tenant_code', $tenantCode)->count(),
|
||||||
|
'stock_reservations' => $this->reservationQuery($scope)->count(),
|
||||||
|
'purchase_changes' => DB::table('value_changes')
|
||||||
|
->where('tenant_code', $tenantCode)
|
||||||
|
->where('trackable_type', Purchase::class)
|
||||||
|
->count(),
|
||||||
|
'inventories' => $scope['inventory_ids']->count(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, int> */
|
||||||
|
public function reset(string $tenantCode): array
|
||||||
|
{
|
||||||
|
$this->ensureTenantExists($tenantCode);
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($tenantCode): array {
|
||||||
|
$scope = $this->scope($tenantCode);
|
||||||
|
$purchaseItems = DB::table('compra_items')->whereIn('compra_id', $scope['purchase_ids'])->count();
|
||||||
|
$cartItems = $scope['cart_item_ids']->count();
|
||||||
|
$telepagosPayments = DB::table('telepagos_payments')->whereIn('compra_id', $scope['purchase_ids'])->count();
|
||||||
|
$telepagosQr = DB::table('telepagos_qr')->whereIn('compra_id', $scope['purchase_ids'])->count();
|
||||||
|
$summary = [
|
||||||
|
'stock_reservations_deleted' => $this->reservationQuery($scope)->delete(),
|
||||||
|
'tickets_deleted' => DB::table('tickets')->where('tenant_code', $tenantCode)->delete(),
|
||||||
|
'purchase_changes_deleted' => DB::table('value_changes')
|
||||||
|
->where('tenant_code', $tenantCode)
|
||||||
|
->where('trackable_type', Purchase::class)
|
||||||
|
->delete(),
|
||||||
|
'purchases_deleted' => DB::table('compras')->whereIn('id', $scope['purchase_ids'])->delete(),
|
||||||
|
'purchase_items_deleted' => $purchaseItems,
|
||||||
|
'telepagos_payments_deleted' => $telepagosPayments,
|
||||||
|
'telepagos_qr_deleted' => $telepagosQr,
|
||||||
|
'carts_deleted' => DB::table('carritos')->whereIn('id', $scope['cart_ids'])->delete(),
|
||||||
|
'cart_items_deleted' => $cartItems,
|
||||||
|
'inventories_reset' => $scope['inventory_ids']->count(),
|
||||||
|
'users_preserved' => DB::table('users')->where('tenant_codigo', $tenantCode)->count(),
|
||||||
|
];
|
||||||
|
|
||||||
|
DB::table('inventories')
|
||||||
|
->whereIn('id', $scope['inventory_ids'])
|
||||||
|
->update([
|
||||||
|
'real_stock' => DB::raw('real_stock + sold_units'),
|
||||||
|
'reserved_stock' => 0,
|
||||||
|
'sold_units' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $summary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureTenantExists(string $tenantCode): void
|
||||||
|
{
|
||||||
|
if (! DB::table('tenants')->where('codigo', $tenantCode)->exists()) {
|
||||||
|
throw new InvalidArgumentException("El tenant {$tenantCode} no existe.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{
|
||||||
|
* purchase_ids: Collection<int, int>,
|
||||||
|
* cart_ids: Collection<int, int>,
|
||||||
|
* cart_item_ids: Collection<int, int>,
|
||||||
|
* inventory_ids: Collection<int, int>
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
private function scope(string $tenantCode): array
|
||||||
|
{
|
||||||
|
$catalogItemIds = DB::table('catalog_items')
|
||||||
|
->where('tenant_code', $tenantCode)
|
||||||
|
->pluck('id');
|
||||||
|
$purchaseIds = DB::table('compras')
|
||||||
|
->where('tenant_codigo', $tenantCode)
|
||||||
|
->pluck('id');
|
||||||
|
$cartIds = DB::table('carritos')
|
||||||
|
->where('tenant_codigo', $tenantCode)
|
||||||
|
->pluck('id');
|
||||||
|
$cartItemIds = DB::table('carrito_items')
|
||||||
|
->whereIn('cart_id', $cartIds)
|
||||||
|
->pluck('id');
|
||||||
|
$inventoryIds = DB::table('variantes')
|
||||||
|
->whereIn('catalog_item_id', $catalogItemIds)
|
||||||
|
->whereNotNull('inventory_id')
|
||||||
|
->pluck('inventory_id')
|
||||||
|
->merge(
|
||||||
|
DB::table('catalog_items')
|
||||||
|
->whereIn('id', $catalogItemIds)
|
||||||
|
->whereNotNull('inventory_id')
|
||||||
|
->pluck('inventory_id'),
|
||||||
|
)
|
||||||
|
->map(fn ($id): int => (int) $id)
|
||||||
|
->unique()
|
||||||
|
->values();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'purchase_ids' => $purchaseIds->map(fn ($id): int => (int) $id),
|
||||||
|
'cart_ids' => $cartIds->map(fn ($id): int => (int) $id),
|
||||||
|
'cart_item_ids' => $cartItemIds->map(fn ($id): int => (int) $id),
|
||||||
|
'inventory_ids' => $inventoryIds,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{
|
||||||
|
* purchase_ids: Collection<int, int>,
|
||||||
|
* cart_ids: Collection<int, int>,
|
||||||
|
* cart_item_ids: Collection<int, int>,
|
||||||
|
* inventory_ids: Collection<int, int>
|
||||||
|
* } $scope
|
||||||
|
*/
|
||||||
|
private function reservationQuery(array $scope): Builder
|
||||||
|
{
|
||||||
|
return DB::table('stock_reservations')
|
||||||
|
->where(function (Builder $query) use ($scope): void {
|
||||||
|
$query->whereIn('inventory_id', $scope['inventory_ids'])
|
||||||
|
->orWhereIn('purchase_id', $scope['purchase_ids'])
|
||||||
|
->orWhereIn('cart_item_id', $scope['cart_item_ids']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,11 @@ namespace App\Domains\Purchase\Services;
|
|||||||
|
|
||||||
use App\Domains\Cart\Models\CartItem;
|
use App\Domains\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
|
||||||
{
|
{
|
||||||
@@ -16,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 (
|
||||||
@@ -23,6 +27,9 @@ class UserPurchaseLimitService
|
|||||||
$userId,
|
$userId,
|
||||||
$requestedQuantity,
|
$requestedQuantity,
|
||||||
$excludedPurchaseId,
|
$excludedPurchaseId,
|
||||||
|
$excludedCartId,
|
||||||
|
$heldQuantity,
|
||||||
|
$maximumAddableCeiling,
|
||||||
$field,
|
$field,
|
||||||
): void {
|
): void {
|
||||||
/** @var CatalogItem $catalogItem */
|
/** @var CatalogItem $catalogItem */
|
||||||
@@ -44,6 +51,7 @@ class UserPurchaseLimitService
|
|||||||
->whereIn('status', [
|
->whereIn('status', [
|
||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
Purchase::STATUS_PAID,
|
Purchase::STATUS_PAID,
|
||||||
])
|
])
|
||||||
->when(
|
->when(
|
||||||
@@ -61,6 +69,7 @@ class UserPurchaseLimitService
|
|||||||
->whereIn('status', [
|
->whereIn('status', [
|
||||||
Purchase::STATUS_CREATED,
|
Purchase::STATUS_CREATED,
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
])
|
])
|
||||||
->whereDoesntHave('items')
|
->whereDoesntHave('items')
|
||||||
->when(
|
->when(
|
||||||
@@ -70,11 +79,104 @@ class UserPurchaseLimitService
|
|||||||
})
|
})
|
||||||
->sum('cantidad');
|
->sum('cantidad');
|
||||||
|
|
||||||
if ($purchasedQuantity + $checkoutQuantity + $requestedQuantity > $limit) {
|
$reservedCartQuantity = (int) CartItem::query()
|
||||||
throw ValidationException::withMessages([
|
->where('catalog_item_id', $catalogItem->getKey())
|
||||||
$field => __('api.purchase_limit.exceeded', ['max' => $limit]),
|
->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')
|
||||||
|
->whereNull('purchase_id'))
|
||||||
|
->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_IN_REVIEW,
|
||||||
|
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,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
|
])
|
||||||
|
->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')
|
||||||
|
->whereNull('purchase_id'))
|
||||||
|
->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);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
|
|||||||
|
|
||||||
## 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`, `in_review`, `paid`, `cancelled`, `rejected` y `expired`.
|
||||||
- `PurchaseItem`: snapshot definitivo del producto o variante, creado recién al confirmar la compra.
|
- `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.
|
||||||
@@ -19,10 +19,10 @@ Implementa el ciclo de compra y checkout: crea la cabecera de compra desde un ca
|
|||||||
- `EditCheckoutService`: modifica los datos del comprador antes del cierre.
|
- `EditCheckoutService`: modifica los datos del comprador antes del cierre.
|
||||||
- `CompleteCheckoutService`: completa, envía a revisión o materializa los `PurchaseItem` al confirmar 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`: 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.
|
Al informar una transferencia, la compra pasa de `pending_payment` a `in_review` y deja de vencer. Si el comprador abandona el checkout durante la revisión, la compra y sus reservas permanecen intactas y se crea un carrito activo nuevo para que pueda seguir comprando. Adminapp puede confirmar o anular explícitamente la compra en revisión.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
namespace App\Domains\Sale\Controllers\AdminApp;
|
namespace App\Domains\Sale\Controllers\AdminApp;
|
||||||
|
|
||||||
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
use App\Domains\Sale\Requests\AdminAppSaleIndexRequest;
|
||||||
|
use App\Domains\Sale\Requests\AdminAppSaleModificationPdfRequest;
|
||||||
|
use App\Domains\Sale\Requests\AdminAppSalePdfRequest;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
|
use App\Domains\Sale\Resources\AdminApp\SaleDetailResource;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
|
use App\Domains\Sale\Resources\AdminApp\SaleModificationResource;
|
||||||
use App\Domains\Sale\Resources\AdminApp\SaleResource;
|
use App\Domains\Sale\Resources\AdminApp\SaleResource;
|
||||||
@@ -71,23 +73,25 @@ class SaleController extends Controller
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function downloadPdf(AdminAppSaleIndexRequest $request): Response
|
public function downloadPdf(AdminAppSalePdfRequest $request): Response
|
||||||
{
|
{
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
return $this->salePdfService->downloadSales(
|
return $this->salePdfService->downloadSales(
|
||||||
$tenant,
|
$tenant,
|
||||||
$this->saleService->salesForExport($tenant, $request->validated()),
|
$this->saleService->salesForExport($tenant, $request->validated()),
|
||||||
|
$request->validated('timezone'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function downloadModificationsPdf(Request $request): Response
|
public function downloadModificationsPdf(AdminAppSaleModificationPdfRequest $request): Response
|
||||||
{
|
{
|
||||||
$tenant = $request->user()->tenant()->firstOrFail();
|
$tenant = $request->user()->tenant()->firstOrFail();
|
||||||
|
|
||||||
return $this->salePdfService->downloadModifications(
|
return $this->salePdfService->downloadModifications(
|
||||||
$tenant,
|
$tenant,
|
||||||
$this->saleService->modificationsForExport($tenant),
|
$this->saleService->modificationsForExport($tenant),
|
||||||
|
$request->validated('timezone'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Sale\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Shared\Rules\ValidTimezone;
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class AdminAppSaleModificationPdfRequest extends FormRequest
|
||||||
|
{
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, list<string>> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'timezone' => ['required', 'string', new ValidTimezone],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
17
app/Domains/Sale/Requests/AdminAppSalePdfRequest.php
Normal file
17
app/Domains/Sale/Requests/AdminAppSalePdfRequest.php
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Sale\Requests;
|
||||||
|
|
||||||
|
use App\Domains\Shared\Rules\ValidTimezone;
|
||||||
|
|
||||||
|
class AdminAppSalePdfRequest extends AdminAppSaleIndexRequest
|
||||||
|
{
|
||||||
|
/** @return array<string, list<string>> */
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
...parent::rules(),
|
||||||
|
'timezone' => ['required', 'string', new ValidTimezone],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ class SaleModificationResource extends JsonResource
|
|||||||
'attribute' => $this->attribute,
|
'attribute' => $this->attribute,
|
||||||
'old_value' => $this->old_value,
|
'old_value' => $this->old_value,
|
||||||
'new_value' => $this->new_value,
|
'new_value' => $this->new_value,
|
||||||
|
'changed_at' => $this->changed_at->utc()->toIso8601String(),
|
||||||
'date' => $this->changed_at->format('Y-m-d'),
|
'date' => $this->changed_at->format('Y-m-d'),
|
||||||
'time' => $this->changed_at->format('H:i:s'),
|
'time' => $this->changed_at->format('H:i:s'),
|
||||||
'actor_type' => $this->actor_type->value,
|
'actor_type' => $this->actor_type->value,
|
||||||
|
|||||||
@@ -13,12 +13,14 @@ use Illuminate\Support\Collection;
|
|||||||
class AdminAppSalePdfService
|
class AdminAppSalePdfService
|
||||||
{
|
{
|
||||||
/** @param Collection<int, Purchase> $sales */
|
/** @param Collection<int, Purchase> $sales */
|
||||||
public function downloadSales(Tenant $tenant, Collection $sales): Response
|
public function downloadSales(Tenant $tenant, Collection $sales, string $timeZone): Response
|
||||||
{
|
{
|
||||||
|
$generatedAt = now();
|
||||||
$pdf = Pdf::loadView('pdf.adminapp.sales', [
|
$pdf = Pdf::loadView('pdf.adminapp.sales', [
|
||||||
'tenant' => $tenant,
|
'tenant' => $tenant,
|
||||||
'sales' => $sales,
|
'sales' => $sales,
|
||||||
'generatedAt' => now(),
|
'generatedAt' => $generatedAt,
|
||||||
|
'timeZone' => $timeZone,
|
||||||
'confirmedSalesTotal' => number_format(
|
'confirmedSalesTotal' => number_format(
|
||||||
(float) $sales->where('status', Purchase::STATUS_PAID)->sum('total'),
|
(float) $sales->where('status', Purchase::STATUS_PAID)->sum('total'),
|
||||||
2,
|
2,
|
||||||
@@ -30,23 +32,30 @@ class AdminAppSalePdfService
|
|||||||
$this->addPageNumbers($pdf);
|
$this->addPageNumbers($pdf);
|
||||||
|
|
||||||
return $pdf->download(
|
return $pdf->download(
|
||||||
'ventas_'.$tenant->codigo.'_'.now()->format('Ymd_His').'.pdf'
|
'ventas_'.$tenant->codigo.'_'
|
||||||
|
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param Collection<int, ValueChange> $modifications */
|
/** @param Collection<int, ValueChange> $modifications */
|
||||||
public function downloadModifications(Tenant $tenant, Collection $modifications): Response
|
public function downloadModifications(
|
||||||
{
|
Tenant $tenant,
|
||||||
|
Collection $modifications,
|
||||||
|
string $timeZone,
|
||||||
|
): Response {
|
||||||
|
$generatedAt = now();
|
||||||
$pdf = Pdf::loadView('pdf.adminapp.sale-modifications', [
|
$pdf = Pdf::loadView('pdf.adminapp.sale-modifications', [
|
||||||
'tenant' => $tenant,
|
'tenant' => $tenant,
|
||||||
'modifications' => $modifications,
|
'modifications' => $modifications,
|
||||||
'generatedAt' => now(),
|
'generatedAt' => $generatedAt,
|
||||||
|
'timeZone' => $timeZone,
|
||||||
])->setPaper('a4', 'landscape');
|
])->setPaper('a4', 'landscape');
|
||||||
|
|
||||||
$this->addPageNumbers($pdf);
|
$this->addPageNumbers($pdf);
|
||||||
|
|
||||||
return $pdf->download(
|
return $pdf->download(
|
||||||
'historial_modificaciones_'.$tenant->codigo.'_'.now()->format('Ymd_His').'.pdf'
|
'historial_modificaciones_'.$tenant->codigo.'_'
|
||||||
|
.$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ class AdminAppSaleService
|
|||||||
$sale = $this->findForTenant($tenant, $saleId);
|
$sale = $this->findForTenant($tenant, $saleId);
|
||||||
|
|
||||||
return $this->saleForResponse(
|
return $this->saleForResponse(
|
||||||
$this->checkoutService->cancelPurchaseWithoutRestoringCart($sale)
|
$this->checkoutService->cancelPurchaseFromAdmin($sale)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,6 +126,7 @@ class AdminAppSaleService
|
|||||||
|
|
||||||
return Purchase::query()
|
return Purchase::query()
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
|
->where('status', '!=', Purchase::STATUS_SUPERSEDED)
|
||||||
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
|
->when($filters['q'] ?? null, function (Builder $query, string $search): void {
|
||||||
$term = trim($search);
|
$term = trim($search);
|
||||||
|
|
||||||
@@ -143,9 +144,19 @@ class AdminAppSaleService
|
|||||||
)
|
)
|
||||||
->when(
|
->when(
|
||||||
$filters['status'] ?? null,
|
$filters['status'] ?? null,
|
||||||
fn (Builder $query, string $status): Builder => $query->where('status', $status)
|
fn (Builder $query, string $status): Builder => $status === Purchase::STATUS_PENDING_PAYMENT
|
||||||
|
? $query->whereIn('status', [
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
Purchase::STATUS_IN_REVIEW,
|
||||||
|
])
|
||||||
|
: $query->where('status', $status)
|
||||||
|
)
|
||||||
|
->select('compras.*')
|
||||||
|
->selectRaw(
|
||||||
|
'(SELECT COALESCE(SUM(purchase_items.cantidad), 0) '
|
||||||
|
.'FROM compra_items AS purchase_items '
|
||||||
|
.'WHERE purchase_items.compra_id = compras.id) AS quantity',
|
||||||
)
|
)
|
||||||
->withSum('items as quantity', 'cantidad')
|
|
||||||
->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 +182,23 @@ 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
|
||||||
|
{
|
||||||
|
return <<<'SQL'
|
||||||
|
COALESCE(
|
||||||
|
(SELECT SUM(compra_items.cantidad)
|
||||||
|
FROM compra_items
|
||||||
|
WHERE compra_items.compra_id = compras.id),
|
||||||
|
0
|
||||||
|
) AS quantity
|
||||||
|
SQL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
24
app/Domains/Shared/Rules/ValidTimezone.php
Normal file
24
app/Domains/Shared/Rules/ValidTimezone.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Shared\Rules;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
use DateTimeZone;
|
||||||
|
use Exception;
|
||||||
|
use Illuminate\Contracts\Validation\ValidationRule;
|
||||||
|
|
||||||
|
class ValidTimezone implements ValidationRule
|
||||||
|
{
|
||||||
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||||
|
{
|
||||||
|
if (! is_string($value)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
new DateTimeZone($value);
|
||||||
|
} catch (Exception) {
|
||||||
|
$fail(__('validation.timezone'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
32
app/Domains/Tenant/Enums/CartEditingPolicy.php
Normal file
32
app/Domains/Tenant/Enums/CartEditingPolicy.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Tenant\Enums;
|
||||||
|
|
||||||
|
enum CartEditingPolicy: string
|
||||||
|
{
|
||||||
|
case Disabled = 'disabled';
|
||||||
|
case QuantityAndRemove = 'quantity_and_remove';
|
||||||
|
case Full = 'full';
|
||||||
|
|
||||||
|
public function allowsQuantityChanges(): bool
|
||||||
|
{
|
||||||
|
return $this !== self::Disabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function allowsRemoval(): bool
|
||||||
|
{
|
||||||
|
return $this !== self::Disabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function allowsVariantChanges(): bool
|
||||||
|
{
|
||||||
|
return $this === self::Full;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function allowsModification(): bool
|
||||||
|
{
|
||||||
|
return $this->allowsRemoval()
|
||||||
|
|| $this->allowsQuantityChanges()
|
||||||
|
|| $this->allowsVariantChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ use App\Domains\Client\Models\Client;
|
|||||||
use App\Domains\Event\Models\EventDate;
|
use App\Domains\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',
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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,11 @@ 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::in([CartEditingPolicy::Disabled->value]),
|
||||||
|
],
|
||||||
'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' => [
|
||||||
|
|||||||
@@ -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,11 @@ 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::in([CartEditingPolicy::Disabled->value]),
|
||||||
|
],
|
||||||
'display_cart_item_images' => ['sometimes', 'boolean'],
|
'display_cart_item_images' => ['sometimes', 'boolean'],
|
||||||
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
'scanner_category_validation_enabled' => ['sometimes', 'boolean'],
|
||||||
];
|
];
|
||||||
|
|||||||
23
app/Domains/Tenant/Resources/CartEditingPolicyResource.php
Normal file
23
app/Domains/Tenant/Resources/CartEditingPolicyResource.php
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Tenant\Resources;
|
||||||
|
|
||||||
|
use App\Domains\Tenant\Enums\CartEditingPolicy;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
|
/** @mixin CartEditingPolicy */
|
||||||
|
class CartEditingPolicyResource extends JsonResource
|
||||||
|
{
|
||||||
|
/** @return array<string, bool|string> */
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'code' => $this->resource->value,
|
||||||
|
'allow_modify' => $this->resource->allowsModification(),
|
||||||
|
'allow_delete' => $this->resource->allowsRemoval(),
|
||||||
|
'allow_update_quantity' => $this->resource->allowsQuantityChanges(),
|
||||||
|
'allow_update_variant' => $this->resource->allowsVariantChanges(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,8 @@ class TenantResource extends JsonResource
|
|||||||
'site_title' => $this->site_title
|
'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(
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||||
|
use App\Domains\Catalog\Services\CatalogItemAllowanceService;
|
||||||
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 +90,34 @@ 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,
|
||||||
|
'availability' => app(CatalogItemAllowanceService::class)
|
||||||
|
->purchaseLimitExceededAvailability(
|
||||||
|
$exception->maximumAddableQuantity,
|
||||||
|
$exception->getMessage(),
|
||||||
|
)->toArray(),
|
||||||
|
], 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;
|
||||||
|
|||||||
@@ -2,4 +2,33 @@
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
'stock_reservation_expiration_minutes' => (int) env('STOCK_RESERVATION_EXPIRATION_MINUTES', 30),
|
'stock_reservation_expiration_minutes' => (int) env('STOCK_RESERVATION_EXPIRATION_MINUTES', 30),
|
||||||
|
'availability' => [
|
||||||
|
'default_actions' => [
|
||||||
|
'select_variant',
|
||||||
|
'change_quantity',
|
||||||
|
'add_to_cart',
|
||||||
|
'buy_now',
|
||||||
|
],
|
||||||
|
'rules' => [
|
||||||
|
'user_quota_reached' => [
|
||||||
|
'effect' => 'restrict',
|
||||||
|
'denied_actions' => [
|
||||||
|
'select_variant',
|
||||||
|
'change_quantity',
|
||||||
|
'add_to_cart',
|
||||||
|
'buy_now',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'out_of_stock' => [
|
||||||
|
'effect' => 'hide',
|
||||||
|
],
|
||||||
|
'requested_quantity_exceeds_user_quota' => [
|
||||||
|
'effect' => 'restrict',
|
||||||
|
'denied_actions' => [
|
||||||
|
'add_to_cart',
|
||||||
|
'buy_now',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -81,6 +81,14 @@ return [
|
|||||||
'replace_placeholders' => true,
|
'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'),
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/** @var array<string, string> */
|
||||||
|
private const TENANT_POLICIES = [
|
||||||
|
'sonder' => 'quantity_and_remove',
|
||||||
|
'fiesta_futbol_infantil' => 'full',
|
||||||
|
'desfile_pura_tendencia' => 'disabled',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->string('cart_editing_policy')
|
||||||
|
->default('full')
|
||||||
|
->after('display_cart');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('cart_editing_enabled', false)
|
||||||
|
->update(['cart_editing_policy' => 'disabled']);
|
||||||
|
|
||||||
|
foreach (self::TENANT_POLICIES as $tenantCode => $policy) {
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('codigo', $tenantCode)
|
||||||
|
->update(['cart_editing_policy' => $policy]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('cart_editing_enabled');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->boolean('cart_editing_enabled')
|
||||||
|
->default(true)
|
||||||
|
->after('display_cart');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('cart_editing_policy', 'disabled')
|
||||||
|
->update(['cart_editing_enabled' => false]);
|
||||||
|
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('cart_editing_policy');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Desfile\Services\InvitationPurchaseProvisioner;
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
app(InvitationPurchaseProvisioner::class)->provision();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// Intentionally irreversible: issued invitation tickets may already be used.
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||||
|
$table->foreignId('compra_id')->nullable()->change();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||||
|
$table->foreignId('compra_id')->nullable(false)->change();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||||
|
$table->json('matched_purchase_ids')->nullable()->after('compra_id');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('telepagos_payments', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('matched_purchase_ids');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->string('checkout_editing_policy')
|
||||||
|
->default('disabled')
|
||||||
|
->after('cart_editing_policy');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('checkout_editing_policy');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->string('address')->nullable()->after('site_title');
|
||||||
|
$table->string('phone')->nullable()->after('address');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('tenants')->update([
|
||||||
|
'address' => 'Av. San Lorenzo 1542, Rosario',
|
||||||
|
'phone' => '54 9 (0341) 6658247',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('tenants', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn(['address', 'phone']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('featured_groups', function (Blueprint $table): void {
|
||||||
|
$table->string('code')->nullable()->after('tenant_code');
|
||||||
|
});
|
||||||
|
|
||||||
|
$usedCodes = [];
|
||||||
|
|
||||||
|
DB::table('featured_groups')
|
||||||
|
->select(['id', 'tenant_code', 'group_name'])
|
||||||
|
->orderBy('id')
|
||||||
|
->get()
|
||||||
|
->each(function (object $group) use (&$usedCodes): void {
|
||||||
|
$baseCode = Str::slug($group->group_name) ?: "group-{$group->id}";
|
||||||
|
$code = $baseCode;
|
||||||
|
$suffix = 2;
|
||||||
|
|
||||||
|
while (isset($usedCodes[$group->tenant_code][$code])) {
|
||||||
|
$code = "{$baseCode}-{$suffix}";
|
||||||
|
$suffix++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$usedCodes[$group->tenant_code][$code] = true;
|
||||||
|
|
||||||
|
DB::table('featured_groups')
|
||||||
|
->where('id', $group->id)
|
||||||
|
->update(['code' => $code]);
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('featured_groups', function (Blueprint $table): void {
|
||||||
|
$table->string('code')->nullable(false)->change();
|
||||||
|
$table->unique(['tenant_code', 'code']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('featured_groups', function (Blueprint $table): void {
|
||||||
|
$table->dropUnique(['tenant_code', 'code']);
|
||||||
|
$table->dropColumn('code');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
private const TENANT_CODE = 'desfile_pura_tendencia';
|
||||||
|
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('codigo', self::TENANT_CODE)
|
||||||
|
->update(['cart_editing_policy' => 'full']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
DB::table('tenants')
|
||||||
|
->where('codigo', self::TENANT_CODE)
|
||||||
|
->update(['cart_editing_policy' => 'disabled']);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
DB::table('tenants')->update([
|
||||||
|
'checkout_editing_policy' => 'disabled',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// Checkout editing stays disabled because previous tenant values cannot
|
||||||
|
// be reconstructed after normalization.
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<?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('carritos', function (Blueprint $table): void {
|
||||||
|
$table->foreignId('current_purchase_id')
|
||||||
|
->nullable()
|
||||||
|
->after('origin')
|
||||||
|
->constrained('compras')
|
||||||
|
->nullOnDelete();
|
||||||
|
$table->unique('current_purchase_id', 'carts_current_purchase_unique');
|
||||||
|
});
|
||||||
|
|
||||||
|
DB::table('carritos')
|
||||||
|
->select('id')
|
||||||
|
->orderBy('id')
|
||||||
|
->each(function (object $cart): void {
|
||||||
|
$purchaseId = DB::table('compras')
|
||||||
|
->where('cart_id', $cart->id)
|
||||||
|
->whereIn('status', ['created', 'pending_payment'])
|
||||||
|
->latest('id')
|
||||||
|
->value('id');
|
||||||
|
|
||||||
|
if ($purchaseId !== null) {
|
||||||
|
DB::table('carritos')
|
||||||
|
->where('id', $cart->id)
|
||||||
|
->update(['current_purchase_id' => $purchaseId]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('carritos', function (Blueprint $table): void {
|
||||||
|
$table->dropUnique('carts_current_purchase_unique');
|
||||||
|
$table->dropConstrainedForeignId('current_purchase_id');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<?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([
|
||||||
|
[
|
||||||
|
'sector' => 'C',
|
||||||
|
'row' => 3,
|
||||||
|
'first_seat' => 6,
|
||||||
|
'last_seat' => 7,
|
||||||
|
'type' => 'NORMAL',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
// Intentionally irreversible: issued invitation tickets may already be used.
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('categorias', function (Blueprint $table): void {
|
||||||
|
$table->boolean('is_enabled')->default(true)->after('nombre');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('categorias', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('is_enabled');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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',
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
@@ -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,12 +36,15 @@ 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.',
|
||||||
'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, expired, or superseded purchase cannot be confirmed.',
|
||||||
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
|
'inconsistent_reservation' => 'The purchase has an inconsistent stock reservation.',
|
||||||
|
'not_current' => 'The purchase is no longer the cart\'s current checkout.',
|
||||||
'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.',
|
'paid_cannot_cancel' => 'A paid purchase cannot be cancelled.',
|
||||||
'stock' => [
|
'stock' => [
|
||||||
'seat_unavailable' => 'Seat :selection is no longer available.',
|
'seat_unavailable' => 'Seat :selection is no longer available.',
|
||||||
@@ -51,11 +56,12 @@ return [
|
|||||||
'catalog_item_missing' => 'One or more catalog items could not be loaded.',
|
'catalog_item_missing' => 'One or more catalog items could not be loaded.',
|
||||||
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
|
'catalog_item_wrong_tenant' => 'One or more catalog items do not belong to the tenant.',
|
||||||
'inactive_cart' => 'The selected cart is no longer active.',
|
'inactive_cart' => 'The selected cart is no longer active.',
|
||||||
|
'checkout_in_progress' => 'The cart already has a purchase in progress.',
|
||||||
'not_available_for_payment' => 'The purchase is no longer available for payment.',
|
'not_available_for_payment' => 'The purchase is no longer available for payment.',
|
||||||
'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.',
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ return [
|
|||||||
'required_with' => 'The :attribute field is required when :values is present.',
|
'required_with' => 'The :attribute field is required when :values is present.',
|
||||||
'required_without' => 'The :attribute field is required when :values is not present.',
|
'required_without' => 'The :attribute field is required when :values is not present.',
|
||||||
'string' => 'The :attribute must be a string.',
|
'string' => 'The :attribute must be a string.',
|
||||||
|
'timezone' => 'The timezone sent by the browser is invalid.',
|
||||||
'unique' => 'The :attribute has already been taken.',
|
'unique' => 'The :attribute has already been taken.',
|
||||||
'url' => 'The :attribute must be a valid URL.',
|
'url' => 'The :attribute must be a valid URL.',
|
||||||
'uuid' => 'The :attribute must be a valid UUID.',
|
'uuid' => 'The :attribute must be a valid UUID.',
|
||||||
@@ -52,6 +53,7 @@ return [
|
|||||||
'password_confirmation' => 'password confirmation',
|
'password_confirmation' => 'password confirmation',
|
||||||
'telefono' => 'phone number',
|
'telefono' => 'phone number',
|
||||||
'tenant_codigo' => 'tenant',
|
'tenant_codigo' => 'tenant',
|
||||||
|
'timezone' => 'timezone',
|
||||||
'variant_id' => 'variant',
|
'variant_id' => 'variant',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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,12 +36,15 @@ 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.',
|
||||||
'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, vencida o reemplazada no se puede confirmar.',
|
||||||
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
|
'inconsistent_reservation' => 'La compra tiene una reserva de stock inconsistente.',
|
||||||
|
'not_current' => 'La compra ya no es el checkout actual del carrito.',
|
||||||
'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.',
|
'paid_cannot_cancel' => 'Una compra pagada no se puede cancelar.',
|
||||||
'stock' => [
|
'stock' => [
|
||||||
'seat_unavailable' => 'El asiento :selection ya no está disponible.',
|
'seat_unavailable' => 'El asiento :selection ya no está disponible.',
|
||||||
@@ -51,11 +56,12 @@ return [
|
|||||||
'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.',
|
'catalog_item_missing' => 'No se pudieron cargar uno o más productos del catálogo.',
|
||||||
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
|
'catalog_item_wrong_tenant' => 'Uno o más productos no pertenecen al tenant.',
|
||||||
'inactive_cart' => 'El carrito seleccionado ya no está activo.',
|
'inactive_cart' => 'El carrito seleccionado ya no está activo.',
|
||||||
|
'checkout_in_progress' => 'El carrito ya tiene una compra en curso.',
|
||||||
'not_available_for_payment' => 'La compra ya no está disponible para el pago.',
|
'not_available_for_payment' => 'La compra ya no está disponible para el pago.',
|
||||||
'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.',
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ return [
|
|||||||
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
|
'required_with' => 'El campo :attribute es obligatorio cuando :values está presente.',
|
||||||
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.',
|
'required_without' => 'El campo :attribute es obligatorio cuando :values no está presente.',
|
||||||
'string' => ':Attribute debe ser texto.',
|
'string' => ':Attribute debe ser texto.',
|
||||||
|
'timezone' => 'La zona horaria enviada por el navegador no es válida.',
|
||||||
'unique' => 'El :attribute ya está en uso.',
|
'unique' => 'El :attribute ya está en uso.',
|
||||||
'url' => ':Attribute debe ser una URL válida.',
|
'url' => ':Attribute debe ser una URL válida.',
|
||||||
'uuid' => ':Attribute debe ser un UUID válido.',
|
'uuid' => ':Attribute debe ser un UUID válido.',
|
||||||
@@ -52,6 +53,7 @@ return [
|
|||||||
'password_confirmation' => 'confirmación de contraseña',
|
'password_confirmation' => 'confirmación de contraseña',
|
||||||
'telefono' => 'teléfono',
|
'telefono' => 'teléfono',
|
||||||
'tenant_codigo' => 'tenant',
|
'tenant_codigo' => 'tenant',
|
||||||
|
'timezone' => 'zona horaria',
|
||||||
'variant_id' => 'variante',
|
'variant_id' => 'variante',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ function bodyFor(string $method, string $uri): ?array
|
|||||||
'POST api/tenants/{tenant:codigo}/catalog-items/{catalogItem}/variant-options' => ['selected_values' => ['color' => 'azul'], 'cart_item_id' => '{{cart_item_id}}'],
|
'POST api/tenants/{tenant:codigo}/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}/checkout-carts/{cart}/items/{cartItem}' => ['cantidad' => 2],
|
'PATCH api/tenants/{tenant:codigo}/compras/{compra}/items/{item}' => ['quantity' => 2, 'variant_id' => '{{variant_id}}'],
|
||||||
'POST api/tenants/{tenant:codigo}/compras/{compra}/payment-intent' => ['method' => 'transfer', 'transfer_payer_dni' => '30123456'],
|
'POST api/tenants/{tenant:codigo}/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}}'],
|
||||||
@@ -136,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') {
|
||||||
@@ -244,7 +244,7 @@ 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',
|
||||||
'updateCheckoutItem' => 'Update Checkout Cart Item',
|
'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',
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Historial de modificaciones de ventas</h1>
|
<h1>Historial de modificaciones de ventas</h1>
|
||||||
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->format('d/m/Y H:i') }}</p>
|
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
|
||||||
|
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
@@ -44,8 +44,8 @@
|
|||||||
@forelse ($modifications as $modification)
|
@forelse ($modifications as $modification)
|
||||||
@php($sale = $modification->trackable)
|
@php($sale = $modification->trackable)
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{ $modification->changed_at->format('d/m/Y') }}</td>
|
<td>{{ $modification->changed_at->copy()->timezone($timeZone)->format('d/m/Y') }}</td>
|
||||||
<td>{{ $modification->changed_at->format('H:i:s') }}</td>
|
<td>{{ $modification->changed_at->copy()->timezone($timeZone)->format('H:i:s') }}</td>
|
||||||
<td>#{{ $modification->trackable_id }}</td>
|
<td>#{{ $modification->trackable_id }}</td>
|
||||||
<td>{{ $sale?->nombre_apellido ?: 'Sin nombre' }}</td>
|
<td>{{ $sale?->nombre_apellido ?: 'Sin nombre' }}</td>
|
||||||
<td>{{ $modification->attribute }}</td>
|
<td>{{ $modification->attribute }}</td>
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Historial de ventas</h1>
|
<h1>Historial de ventas</h1>
|
||||||
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->format('d/m/Y H:i') }}</p>
|
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
|
||||||
|
|
||||||
<div class="summary">
|
<div class="summary">
|
||||||
Total de ventas confirmadas en este reporte: <strong>${{ number_format((float) $confirmedSalesTotal, 2, ',', '.') }}</strong>
|
Total de ventas confirmadas en este reporte: <strong>${{ number_format((float) $confirmedSalesTotal, 2, ',', '.') }}</strong>
|
||||||
@@ -44,7 +44,7 @@
|
|||||||
@forelse ($sales as $sale)
|
@forelse ($sales as $sale)
|
||||||
<tr>
|
<tr>
|
||||||
<td>#{{ $sale->id }}</td>
|
<td>#{{ $sale->id }}</td>
|
||||||
<td>{{ $sale->created_at?->format('d/m/Y H:i') ?? '-' }}</td>
|
<td>{{ $sale->created_at?->copy()->timezone($timeZone)->format('d/m/Y H:i') ?? '-' }}</td>
|
||||||
<td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td>
|
<td>{{ $sale->nombre_apellido ?: 'Sin nombre' }}</td>
|
||||||
<td class="center">{{ (int) ($sale->quantity ?? 0) }}</td>
|
<td class="center">{{ (int) ($sale->quantity ?? 0) }}</td>
|
||||||
<td>{{ match ($sale->status) {
|
<td>{{ match ($sale->status) {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Domains\Auth\Services\AdminCredentialVerifier;
|
||||||
use App\Domains\Catalog\Services\ExpireStockReservationsService;
|
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;
|
||||||
@@ -19,3 +21,64 @@ Artisan::command('reservations:expire', function (): void {
|
|||||||
Schedule::command('reservations: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');
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -202,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');
|
||||||
|
|
||||||
@@ -240,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('availability.maximum_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,
|
||||||
@@ -476,6 +486,83 @@ class CartControllerTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_quantity_and_remove_policy_hides_variants_and_rejects_variant_changes(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
$tenant->update(['cart_editing_policy' => 'quantity_and_remove']);
|
||||||
|
[$item, $firstVariant] = $this->createVariantItem($tenant, 10, '15.00');
|
||||||
|
$secondInventory = Inventory::query()->create(['real_stock' => 10]);
|
||||||
|
$secondVariant = $item->variants()->create(['inventory_id' => $secondInventory->id]);
|
||||||
|
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'variant_id' => $firstVariant->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
])->assertJsonMissingPath('data.items.0.variants');
|
||||||
|
$guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
|
||||||
|
$cartItemId = $createResponse->json('data.items.0.id');
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'PATCH',
|
||||||
|
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||||
|
json_encode(['cantidad' => 2]),
|
||||||
|
)->assertOk()->assertJsonPath('data.items.0.cantidad', 2);
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'PATCH',
|
||||||
|
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||||
|
json_encode(['cantidad' => 2, 'variant_id' => $secondVariant->id]),
|
||||||
|
)->assertUnprocessable()->assertJsonValidationErrors('variant_id');
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'DELETE',
|
||||||
|
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json'],
|
||||||
|
)->assertOk()->assertJsonPath('data.items', []);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_disabled_policy_rejects_quantity_changes_and_removal(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
$tenant->update(['cart_editing_policy' => 'disabled']);
|
||||||
|
$item = $this->createDirectItem($tenant, 10, '15.00');
|
||||||
|
$createResponse = $this->postJson('/api/tenants/acme/cart/items', [
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'cantidad' => 1,
|
||||||
|
])->assertOk();
|
||||||
|
$guestToken = $createResponse->getCookie('guest_token', false)?->getValue();
|
||||||
|
$cartItemId = $createResponse->json('data.items.0.id');
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'PATCH',
|
||||||
|
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
|
||||||
|
json_encode(['cantidad' => 2]),
|
||||||
|
)->assertUnprocessable()->assertJsonValidationErrors('cantidad');
|
||||||
|
|
||||||
|
$this->call(
|
||||||
|
'DELETE',
|
||||||
|
"/api/tenants/acme/cart/items/{$cartItemId}",
|
||||||
|
[],
|
||||||
|
['guest_token' => $guestToken],
|
||||||
|
[],
|
||||||
|
['HTTP_Accept' => 'application/json'],
|
||||||
|
)->assertUnprocessable()->assertJsonValidationErrors('cart_item');
|
||||||
|
}
|
||||||
|
|
||||||
public function test_it_requires_a_variant_when_the_item_has_variant_inventory(): void
|
public function test_it_requires_a_variant_when_the_item_has_variant_inventory(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('acme');
|
$tenant = $this->createTenant('acme');
|
||||||
|
|||||||
@@ -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.availability.maximum_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)
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -39,7 +41,7 @@ class CatalogControllerTest extends TestCase
|
|||||||
$directItem = $this->createItem($tenant, 'Direct', $directInventory);
|
$directItem = $this->createItem($tenant, 'Direct', $directInventory);
|
||||||
$row->featuredItems()->create(['catalog_item_id' => $directItem->id]);
|
$row->featuredItems()->create(['catalog_item_id' => $directItem->id]);
|
||||||
|
|
||||||
$variantItem = $this->createItem($tenant, 'Variants');
|
$variantItem = $this->createItem($tenant, 'Variants', withoutInventory: true);
|
||||||
$firstInventory = Inventory::query()->create([
|
$firstInventory = Inventory::query()->create([
|
||||||
'real_stock' => 5,
|
'real_stock' => 5,
|
||||||
'reserved_stock' => 1,
|
'reserved_stock' => 1,
|
||||||
@@ -54,7 +56,7 @@ class CatalogControllerTest extends TestCase
|
|||||||
]);
|
]);
|
||||||
$variantItem->variants()->create(['inventory_id' => $firstInventory->id]);
|
$variantItem->variants()->create(['inventory_id' => $firstInventory->id]);
|
||||||
$variantItem->variants()->create(['inventory_id' => $secondInventory->id]);
|
$variantItem->variants()->create(['inventory_id' => $secondInventory->id]);
|
||||||
$unavailableVariant = $variantItem->variants()->create([
|
$variantItem->variants()->create([
|
||||||
'inventory_id' => $unavailableInventory->id,
|
'inventory_id' => $unavailableInventory->id,
|
||||||
]);
|
]);
|
||||||
$cart->featuredItems()->create(['catalog_item_id' => $variantItem->id]);
|
$cart->featuredItems()->create(['catalog_item_id' => $variantItem->id]);
|
||||||
@@ -70,17 +72,64 @@ 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.availability.state', 'visible')
|
||||||
|
->assertJsonPath('0.items.0.availability.maximum_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.availability.maximum_quantity', 4)
|
||||||
->assertJsonPath('0.items.0.variants.1.stock_tecnico', 3)
|
->assertJsonPath('0.items.0.variants.0.availability.state', 'visible')
|
||||||
->assertJsonMissing(['id' => $unavailableVariant->id, 'stock_tecnico' => 0])
|
->assertJsonPath('0.items.0.variants.1.availability.maximum_quantity', 3)
|
||||||
->assertJsonPath('1.title', 'Row')
|
->assertJsonPath('1.title', 'Row')
|
||||||
->assertJsonPath('1.items.data.0.stock_tecnico', 8)
|
->assertJsonPath('1.items.data.0.availability.maximum_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_it_excludes_items_when_all_of_their_variants_are_out_of_stock(): void
|
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', withoutInventory: true);
|
||||||
|
$item->update(['max_units_per_user' => 3]);
|
||||||
|
$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.availability.maximum_quantity', 0)
|
||||||
|
->assertJsonPath('0.items.0.availability.allowed_actions', [])
|
||||||
|
->assertJsonPath(
|
||||||
|
'0.items.0.availability.reasons.0.message',
|
||||||
|
'Alcanzaste el cupo máximo permitido para este producto.',
|
||||||
|
)
|
||||||
|
->assertJsonPath('0.items.0.variants.0.availability.maximum_quantity', 8)
|
||||||
|
->assertJsonPath('0.items.0.variants.1.availability.maximum_quantity', 9)
|
||||||
|
->assertJsonCount(0, '0.items.0.variants.0.availability.reasons')
|
||||||
|
->assertJsonCount(0, '0.items.0.variants.1.availability.reasons')
|
||||||
|
->assertJsonMissingPath('0.items.0.variants.0.stock_tecnico')
|
||||||
|
->assertJsonMissingPath('0.items.0.variants.1.stock_tecnico');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_hides_out_of_stock_items_before_building_the_group_response(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('catalog-available-variants');
|
$tenant = $this->createTenant('catalog-available-variants');
|
||||||
$group = $this->createGroup(
|
$group = $this->createGroup(
|
||||||
@@ -90,7 +139,7 @@ class CatalogControllerTest extends TestCase
|
|||||||
groupLayout: GroupLayout::SimpleVertical,
|
groupLayout: GroupLayout::SimpleVertical,
|
||||||
);
|
);
|
||||||
|
|
||||||
$unavailableItem = $this->createItem($tenant, 'Unavailable');
|
$unavailableItem = $this->createItem($tenant, 'Unavailable', withoutInventory: true);
|
||||||
$unavailableInventory = Inventory::query()->create([
|
$unavailableInventory = Inventory::query()->create([
|
||||||
'real_stock' => 4,
|
'real_stock' => 4,
|
||||||
'reserved_stock' => 4,
|
'reserved_stock' => 4,
|
||||||
@@ -98,7 +147,7 @@ class CatalogControllerTest extends TestCase
|
|||||||
$unavailableItem->variants()->create(['inventory_id' => $unavailableInventory->id]);
|
$unavailableItem->variants()->create(['inventory_id' => $unavailableInventory->id]);
|
||||||
$group->featuredItems()->create(['catalog_item_id' => $unavailableItem->id]);
|
$group->featuredItems()->create(['catalog_item_id' => $unavailableItem->id]);
|
||||||
|
|
||||||
$availableItem = $this->createItem($tenant, 'Available');
|
$availableItem = $this->createItem($tenant, 'Available', withoutInventory: true);
|
||||||
$availableInventory = Inventory::query()->create([
|
$availableInventory = Inventory::query()->create([
|
||||||
'real_stock' => 4,
|
'real_stock' => 4,
|
||||||
'reserved_stock' => 3,
|
'reserved_stock' => 3,
|
||||||
@@ -110,7 +159,7 @@ class CatalogControllerTest extends TestCase
|
|||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(1, '0.items')
|
->assertJsonCount(1, '0.items')
|
||||||
->assertJsonPath('0.items.0.nombre', 'Available')
|
->assertJsonPath('0.items.0.nombre', 'Available')
|
||||||
->assertJsonMissing(['nombre' => 'Unavailable']);
|
->assertJsonCount(0, '0.items.0.availability.reasons');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_column_with_image_uses_item_image_then_variant_image_then_null(): void
|
public function test_column_with_image_uses_item_image_then_variant_image_then_null(): void
|
||||||
@@ -127,8 +176,8 @@ class CatalogControllerTest extends TestCase
|
|||||||
'order' => 0,
|
'order' => 0,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$variantItem = $this->createItem($tenant, 'Variant image');
|
$variantItem = $this->createItem($tenant, 'Variant image', withoutInventory: true);
|
||||||
$variantInventory = Inventory::query()->create();
|
$variantInventory = Inventory::query()->create(['real_stock' => 1]);
|
||||||
$variant = $variantItem->variants()->create(['inventory_id' => $variantInventory->id]);
|
$variant = $variantItem->variants()->create(['inventory_id' => $variantInventory->id]);
|
||||||
$variantImage = $this->createAttachment('variant');
|
$variantImage = $this->createAttachment('variant');
|
||||||
$variant->attachments()->attach($variantImage, ['orden' => 0]);
|
$variant->attachments()->attach($variantImage, ['orden' => 0]);
|
||||||
@@ -308,6 +357,53 @@ class CatalogControllerTest extends TestCase
|
|||||||
->assertJsonPath('1.items.meta.total', 2);
|
->assertJsonPath('1.items.meta.total', 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_index_excludes_items_from_disabled_categories(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('catalog-disabled-category');
|
||||||
|
$group = $this->createGroup(
|
||||||
|
$tenant,
|
||||||
|
ProductLayout::Row,
|
||||||
|
'All products',
|
||||||
|
groupLayout: GroupLayout::Simple,
|
||||||
|
);
|
||||||
|
$enabledCategory = Category::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'nombre' => 'Enabled',
|
||||||
|
]);
|
||||||
|
$disabledCategory = Category::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'nombre' => 'Disabled',
|
||||||
|
'is_enabled' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$enabledItem = $this->createItem($tenant, 'Enabled item');
|
||||||
|
$enabledItem->category()->associate($enabledCategory)->save();
|
||||||
|
$disabledItem = $this->createItem($tenant, 'Disabled item');
|
||||||
|
$disabledItem->category()->associate($disabledCategory)->save();
|
||||||
|
$uncategorizedItem = $this->createItem($tenant, 'Uncategorized item');
|
||||||
|
|
||||||
|
foreach ([$enabledItem, $disabledItem, $uncategorizedItem] as $order => $item) {
|
||||||
|
$group->featuredItems()->create([
|
||||||
|
'catalog_item_id' => $item->id,
|
||||||
|
'order' => $order,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->getJson("/api/tenants/{$tenant->codigo}/catalog")
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonCount(2, '0.items')
|
||||||
|
->assertJsonPath('0.items.0.nombre', 'Enabled item')
|
||||||
|
->assertJsonPath('0.items.1.nombre', 'Uncategorized item')
|
||||||
|
->assertJsonMissing(['nombre' => 'Disabled item']);
|
||||||
|
|
||||||
|
$this->getJson(
|
||||||
|
"/api/tenants/{$tenant->codigo}/catalog/featured-groups/{$group->id}/items"
|
||||||
|
)
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonCount(2)
|
||||||
|
->assertJsonMissing(['nombre' => 'Disabled item']);
|
||||||
|
}
|
||||||
|
|
||||||
private function createGroup(
|
private function createGroup(
|
||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
ProductLayout $layout,
|
ProductLayout $layout,
|
||||||
@@ -328,7 +424,12 @@ class CatalogControllerTest extends TestCase
|
|||||||
Tenant $tenant,
|
Tenant $tenant,
|
||||||
string $name,
|
string $name,
|
||||||
?Inventory $inventory = null,
|
?Inventory $inventory = null,
|
||||||
|
bool $withoutInventory = false,
|
||||||
): CatalogItem {
|
): CatalogItem {
|
||||||
|
$inventory ??= $withoutInventory
|
||||||
|
? null
|
||||||
|
: Inventory::query()->create(['real_stock' => 10]);
|
||||||
|
|
||||||
return CatalogItem::query()->create([
|
return CatalogItem::query()->create([
|
||||||
'tenant_code' => $tenant->codigo,
|
'tenant_code' => $tenant->codigo,
|
||||||
'inventory_id' => $inventory?->id,
|
'inventory_id' => $inventory?->id,
|
||||||
|
|||||||
@@ -40,14 +40,26 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
|
|
||||||
$response
|
$response
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonPath('data.stock_tecnico', 7)
|
->assertJsonPath('data.availability.maximum_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');
|
||||||
$this->assertStringContainsString($itemImage->path, $response->json('data.images.0'));
|
$this->assertStringContainsString($itemImage->path, $response->json('data.images.0'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_it_filters_unavailable_variants_and_selects_the_first_available_one(): void
|
public function test_it_does_not_return_an_out_of_stock_product_detail(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('detail-hidden');
|
||||||
|
$inventory = Inventory::query()->create(['real_stock' => 0]);
|
||||||
|
$item = $this->createItem($tenant, 'Hidden item', $inventory);
|
||||||
|
|
||||||
|
$this->getJson(
|
||||||
|
"/api/tenants/{$tenant->codigo}/catalog-items/{$item->id}",
|
||||||
|
)->assertNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_hides_unavailable_variants_and_selects_the_first_available_one(): void
|
||||||
{
|
{
|
||||||
Storage::fake('s3');
|
Storage::fake('s3');
|
||||||
$tenant = $this->createTenant('detail-default');
|
$tenant = $this->createTenant('detail-default');
|
||||||
@@ -70,8 +82,10 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonCount(1, 'data.variants')
|
->assertJsonCount(1, 'data.variants')
|
||||||
->assertJsonPath('data.variants.0.id', $secondVariant->id)
|
->assertJsonPath('data.variants.0.id', $secondVariant->id)
|
||||||
|
->assertJsonPath('data.variants.0.availability.state', 'visible')
|
||||||
->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.availability.maximum_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 +139,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.availability.maximum_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.availability.maximum_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 +151,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.availability.maximum_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 +191,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.availability.maximum_quantity', null)
|
||||||
->assertJsonMissingPath('data.stock_tecnico')
|
->assertJsonMissingPath('data.stock_tecnico')
|
||||||
->assertJsonPath('data.variants.0.stock_tecnico', null);
|
->assertJsonPath('data.variants.0.availability.maximum_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
|
||||||
@@ -344,6 +360,9 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.resolved_variant', null)
|
->assertJsonPath('data.resolved_variant', null)
|
||||||
->assertJsonCount(3, 'data.variants')
|
->assertJsonCount(3, 'data.variants')
|
||||||
->assertJsonPath('data.variants.0.id', $first->id)
|
->assertJsonPath('data.variants.0.id', $first->id)
|
||||||
|
->assertJsonPath('data.variants.0.availability.state', 'visible')
|
||||||
|
->assertJsonPath('data.variants.0.availability.maximum_quantity', 1)
|
||||||
|
->assertJsonPath('data.variants.0.availability.allowed_actions.2', 'add_to_cart')
|
||||||
->assertJsonPath('data.variants.0.values.sector.value', 'A')
|
->assertJsonPath('data.variants.0.values.sector.value', 'A')
|
||||||
->assertJsonPath('data.variants.0.values.seat.value', '1')
|
->assertJsonPath('data.variants.0.values.seat.value', '1')
|
||||||
->assertJsonCount(2, 'data.selectors')
|
->assertJsonCount(2, 'data.selectors')
|
||||||
@@ -411,7 +430,9 @@ class CatalogItemDetailControllerTest extends TestCase
|
|||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonPath('data.selected_values.sector', 'VIP')
|
->assertJsonPath('data.selected_values.sector', 'VIP')
|
||||||
->assertJsonPath('data.selected_values.seat', 'A-12')
|
->assertJsonPath('data.selected_values.seat', 'A-12')
|
||||||
->assertJsonPath('data.resolved_variant.id', $variant->id);
|
->assertJsonPath('data.resolved_variant.id', $variant->id)
|
||||||
|
->assertJsonPath('data.resolved_variant.availability.state', 'hidden')
|
||||||
|
->assertJsonMissingPath('data.resolved_variant.availability.allowed_actions');
|
||||||
}
|
}
|
||||||
|
|
||||||
private function createItem(
|
private function createItem(
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ 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\Catalog\Models\CatalogItem;
|
use App\Domains\Catalog\Models\CatalogItem;
|
||||||
|
use App\Domains\Catalog\Models\Category;
|
||||||
use App\Domains\Catalog\Models\Inventory;
|
use App\Domains\Catalog\Models\Inventory;
|
||||||
use App\Domains\Tenant\Models\Tenant;
|
use App\Domains\Tenant\Models\Tenant;
|
||||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
@@ -15,6 +16,21 @@ class CatalogSchemaTest extends TestCase
|
|||||||
{
|
{
|
||||||
use RefreshDatabase;
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_categories_are_enabled_by_default(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(Schema::hasColumn('categorias', 'is_enabled'));
|
||||||
|
|
||||||
|
$category = Category::query()->create([
|
||||||
|
'nombre' => 'Enabled category',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertTrue($category->is_enabled);
|
||||||
|
$this->assertDatabaseHas('categorias', [
|
||||||
|
'id' => $category->id,
|
||||||
|
'is_enabled' => true,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_legacy_product_tables_are_replaced_by_catalog_tables(): void
|
public function test_legacy_product_tables_are_replaced_by_catalog_tables(): void
|
||||||
{
|
{
|
||||||
$this->assertFalse(Schema::hasTable('productos'));
|
$this->assertFalse(Schema::hasTable('productos'));
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ class CatalogSearchTest extends TestCase
|
|||||||
$this->createCatalogItem($tenant, "Running {$number}");
|
$this->createCatalogItem($tenant, "Running {$number}");
|
||||||
}
|
}
|
||||||
$exactMatch = $this->createCatalogItem($tenant, 'Running');
|
$exactMatch = $this->createCatalogItem($tenant, 'Running');
|
||||||
|
$outOfStockMatch = $this->createCatalogItem($tenant, 'Running unavailable');
|
||||||
|
$outOfStockMatch->inventory->update(['real_stock' => 0]);
|
||||||
$this->createCatalogItem($tenant, 'Unrelated');
|
$this->createCatalogItem($tenant, 'Unrelated');
|
||||||
$this->createCatalogItem($otherTenant, 'Running foreign');
|
$this->createCatalogItem($otherTenant, 'Running foreign');
|
||||||
|
|
||||||
@@ -76,6 +78,7 @@ class CatalogSearchTest extends TestCase
|
|||||||
->assertJsonPath('meta.total', 6)
|
->assertJsonPath('meta.total', 6)
|
||||||
->assertJsonCount(4, 'data')
|
->assertJsonCount(4, 'data')
|
||||||
->assertJsonPath('data.0.id', $exactMatch->id)
|
->assertJsonPath('data.0.id', $exactMatch->id)
|
||||||
|
->assertJsonMissing(['nombre' => 'Running unavailable'])
|
||||||
->assertJsonMissing(['nombre' => 'Running foreign'])
|
->assertJsonMissing(['nombre' => 'Running foreign'])
|
||||||
->assertJsonMissing(['nombre' => 'Unrelated']);
|
->assertJsonMissing(['nombre' => 'Unrelated']);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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',
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user