Compare commits
16 Commits
6775fb110c
...
fix/expira
| Author | SHA1 | Date | |
|---|---|---|---|
| 559bf5d264 | |||
| eafb02ffd5 | |||
| 786cf2db52 | |||
| cb56e33685 | |||
| dd81e3b3f7 | |||
| 4d51531c5d | |||
| 7fd8a00054 | |||
| 23163a6eb8 | |||
| 944cf8ee18 | |||
| 8c09ca1204 | |||
| 98d502a8ef | |||
| 318e6559cb | |||
| 9fd34f900f | |||
| ae6149df84 | |||
| 1776cfe581 | |||
| 5ad18694e1 |
@@ -7,6 +7,7 @@ use App\Domains\Cart\Models\Cart;
|
|||||||
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 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;
|
||||||
@@ -20,6 +21,7 @@ class CartService
|
|||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly StockReservationService $reservations,
|
private readonly StockReservationService $reservations,
|
||||||
|
private readonly PurchaseStateGuard $purchaseState,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function show(Tenant $tenant, Request $request): Cart
|
public function show(Tenant $tenant, Request $request): Cart
|
||||||
@@ -116,10 +118,6 @@ class CartService
|
|||||||
->where('cart_id', $cart->getKey())
|
->where('cart_id', $cart->getKey())
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('user_id', $user->getKey())
|
->where('user_id', $user->getKey())
|
||||||
->whereIn('status', [
|
|
||||||
Purchase::STATUS_CREATED,
|
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
|
||||||
])
|
|
||||||
->whereDoesntHave('items')
|
->whereDoesntHave('items')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
@@ -128,10 +126,13 @@ class CartService
|
|||||||
throw new NotFoundHttpException('Checkout cart not found.');
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'cart' => __('api.purchase.not_editable'),
|
if (! in_array($purchase->status, [
|
||||||
]);
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @var Cart|null $checkoutCart */
|
/** @var Cart|null $checkoutCart */
|
||||||
@@ -246,10 +247,6 @@ class CartService
|
|||||||
->where('cart_id', $cart->getKey())
|
->where('cart_id', $cart->getKey())
|
||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->where('user_id', $user->getKey())
|
->where('user_id', $user->getKey())
|
||||||
->whereIn('status', [
|
|
||||||
Purchase::STATUS_CREATED,
|
|
||||||
Purchase::STATUS_PENDING_PAYMENT,
|
|
||||||
])
|
|
||||||
->whereDoesntHave('items')
|
->whereDoesntHave('items')
|
||||||
->lockForUpdate()
|
->lockForUpdate()
|
||||||
->first();
|
->first();
|
||||||
@@ -258,10 +255,13 @@ class CartService
|
|||||||
throw new NotFoundHttpException('Checkout cart not found.');
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($purchase->expires_at !== null && $purchase->expires_at->isPast()) {
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'cart' => __('api.purchase.not_editable'),
|
if (! in_array($purchase->status, [
|
||||||
]);
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)) {
|
||||||
|
throw new NotFoundHttpException('Checkout cart not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @var Cart|null $checkoutCart */
|
/** @var Cart|null $checkoutCart */
|
||||||
@@ -296,16 +296,22 @@ class CartService
|
|||||||
|
|
||||||
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,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,6 @@ Route::prefix('tenants/{tenant:codigo}')
|
|||||||
Route::prefix('tenants/{tenant:codigo}')
|
Route::prefix('tenants/{tenant:codigo}')
|
||||||
->middleware('auth:sanctum')
|
->middleware('auth:sanctum')
|
||||||
->group(function (): void {
|
->group(function (): void {
|
||||||
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem']);
|
Route::patch('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'updateCheckoutItem'])->withTrashed();
|
||||||
Route::delete('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'removeCheckoutItem']);
|
Route::delete('checkout-carts/{cart}/items/{cartItem}', [CartController::class, 'removeCheckoutItem'])->withTrashed();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use App\Domains\Purchase\Requests\UpdatePurchaseItemRequest;
|
|||||||
use App\Domains\Purchase\Resources\PurchaseResource;
|
use App\Domains\Purchase\Resources\PurchaseResource;
|
||||||
use App\Domains\Purchase\Services\Checkout\PurchaseResponseLoader;
|
use App\Domains\Purchase\Services\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;
|
||||||
@@ -132,42 +133,48 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$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;
|
||||||
@@ -180,6 +187,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'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,15 +21,18 @@ class PurchaseResource extends JsonResource
|
|||||||
$purchaseItems = $this->resource->relationLoaded('items')
|
$purchaseItems = $this->resource->relationLoaded('items')
|
||||||
? $this->resource->getRelation('items')
|
? $this->resource->getRelation('items')
|
||||||
: collect();
|
: collect();
|
||||||
$cartItems = $purchaseItems->isEmpty()
|
$cartItems = $this->resource->relationLoaded('cart')
|
||||||
&& $this->resource->relationLoaded('cart')
|
|
||||||
&& $this->resource->getRelation('cart')?->relationLoaded('items')
|
&& $this->resource->getRelation('cart')?->relationLoaded('items')
|
||||||
? $this->resource->getRelation('cart')->getRelation('items')
|
? $this->resource->getRelation('cart')->getRelation('items')
|
||||||
: collect();
|
: null;
|
||||||
$items = $purchaseItems->isNotEmpty() ? $purchaseItems : $cartItems;
|
$usesCartItems = in_array($this->status, [
|
||||||
$itemsSource = $purchaseItems->isNotEmpty()
|
Purchase::STATUS_CREATED,
|
||||||
? 'purchase'
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
: ($cartItems->isNotEmpty() ? 'cart' : null);
|
], true) && $cartItems !== null;
|
||||||
|
$items = $usesCartItems ? $cartItems : $purchaseItems;
|
||||||
|
$itemsSource = $usesCartItems
|
||||||
|
? 'cart'
|
||||||
|
: ($purchaseItems->isNotEmpty() ? 'purchase' : null);
|
||||||
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
$ticketsCount = array_key_exists('tickets_count', $this->resource->getAttributes())
|
||||||
? (int) $this->resource->getAttribute('tickets_count')
|
? (int) $this->resource->getAttribute('tickets_count')
|
||||||
: null;
|
: null;
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -15,12 +16,14 @@ class CompleteCheckoutService
|
|||||||
private readonly StockReservationService $reservations,
|
private readonly StockReservationService $reservations,
|
||||||
private readonly SourceCartService $sourceCart,
|
private readonly SourceCartService $sourceCart,
|
||||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
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([
|
||||||
@@ -45,6 +48,7 @@ class CompleteCheckoutService
|
|||||||
{
|
{
|
||||||
return DB::transaction(function () use ($purchase): Purchase {
|
return DB::transaction(function () use ($purchase): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
|
|
||||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
@@ -70,6 +74,7 @@ class CompleteCheckoutService
|
|||||||
{
|
{
|
||||||
DB::transaction(function () use ($purchase): void {
|
DB::transaction(function () use ($purchase): void {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
|
|
||||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use App\Domains\Catalog\Models\Variant;
|
|||||||
use App\Domains\Catalog\Services\CatalogInventoryService;
|
use App\Domains\Catalog\Services\CatalogInventoryService;
|
||||||
use App\Domains\Purchase\Models\Purchase;
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
use App\Domains\Purchase\Models\PurchaseItem;
|
use App\Domains\Purchase\Models\PurchaseItem;
|
||||||
|
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||||
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
use App\Domains\Purchase\Services\UserPurchaseLimitService;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -20,6 +21,7 @@ class EditCheckoutService
|
|||||||
private readonly SourceCartService $sourceCart,
|
private readonly SourceCartService $sourceCart,
|
||||||
private readonly PurchaseItemSnapshotFactory $snapshots,
|
private readonly PurchaseItemSnapshotFactory $snapshots,
|
||||||
private readonly PurchaseResponseLoader $responses,
|
private readonly PurchaseResponseLoader $responses,
|
||||||
|
private readonly PurchaseStateGuard $purchaseState,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @param array<string, string> $customerData */
|
/** @param array<string, string> $customerData */
|
||||||
@@ -27,6 +29,7 @@ class EditCheckoutService
|
|||||||
{
|
{
|
||||||
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
return DB::transaction(function () use ($purchase, $customerData): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
$this->assertEditable($purchase);
|
$this->assertEditable($purchase);
|
||||||
|
|
||||||
$purchase->update($customerData);
|
$purchase->update($customerData);
|
||||||
@@ -50,6 +53,7 @@ class EditCheckoutService
|
|||||||
$updateVariant,
|
$updateVariant,
|
||||||
): Purchase {
|
): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
|
|
||||||
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
|
if ($purchase->status !== Purchase::STATUS_CREATED || $this->hasExpired($purchase)) {
|
||||||
throw ValidationException::withMessages([
|
throw ValidationException::withMessages([
|
||||||
@@ -182,6 +186,7 @@ class EditCheckoutService
|
|||||||
{
|
{
|
||||||
return DB::transaction(function () use ($purchase): Purchase {
|
return DB::transaction(function () use ($purchase): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
$this->assertEditable($purchase);
|
$this->assertEditable($purchase);
|
||||||
|
|
||||||
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsModification()) {
|
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsModification()) {
|
||||||
@@ -208,6 +213,7 @@ class EditCheckoutService
|
|||||||
{
|
{
|
||||||
return DB::transaction(function () use ($purchase, $purchaseItem): Purchase {
|
return DB::transaction(function () use ($purchase, $purchaseItem): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
$this->assertEditable($purchase);
|
$this->assertEditable($purchase);
|
||||||
|
|
||||||
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsRemoval()) {
|
if (! $purchase->tenant()->firstOrFail()->checkout_editing_policy->allowsRemoval()) {
|
||||||
|
|||||||
@@ -10,7 +10,16 @@ class PurchaseResponseLoader
|
|||||||
{
|
{
|
||||||
$purchase->load(['tenant', 'items.imageAttachment']);
|
$purchase->load(['tenant', 'items.imageAttachment']);
|
||||||
|
|
||||||
if ($purchase->items->isEmpty() && $purchase->cart_id !== null) {
|
if (
|
||||||
|
$purchase->cart_id !== null
|
||||||
|
&& (
|
||||||
|
in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)
|
||||||
|
|| $purchase->items->isEmpty()
|
||||||
|
)
|
||||||
|
) {
|
||||||
$purchase->load([
|
$purchase->load([
|
||||||
'cart.items.catalogItem.inventory',
|
'cart.items.catalogItem.inventory',
|
||||||
'cart.items.catalogItem.attachments',
|
'cart.items.catalogItem.attachments',
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace App\Domains\Purchase\Services\Checkout;
|
|||||||
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 App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
@@ -14,6 +15,8 @@ class ReleaseCheckoutService
|
|||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private readonly StockReservationService $reservations,
|
private readonly StockReservationService $reservations,
|
||||||
|
private readonly SourceCartService $sourceCart,
|
||||||
|
private readonly PurchaseStateGuard $purchaseState,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function cancel(Purchase $purchase): Purchase
|
public function cancel(Purchase $purchase): Purchase
|
||||||
@@ -70,6 +73,10 @@ class ReleaseCheckoutService
|
|||||||
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
|
return DB::transaction(function () use ($purchase, $targetStatus): Purchase {
|
||||||
$purchase = $this->lockPurchase($purchase);
|
$purchase = $this->lockPurchase($purchase);
|
||||||
|
|
||||||
|
if ($targetStatus !== Purchase::STATUS_EXPIRED) {
|
||||||
|
$this->purchaseState->assertNotExpired($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
if ($purchase->status === Purchase::STATUS_PAID) {
|
if ($purchase->status === Purchase::STATUS_PAID) {
|
||||||
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
if ($targetStatus === Purchase::STATUS_EXPIRED) {
|
||||||
return $this->loadPurchase($purchase);
|
return $this->loadPurchase($purchase);
|
||||||
|
|||||||
24
app/Domains/Purchase/Services/PurchaseStateGuard.php
Normal file
24
app/Domains/Purchase/Services/PurchaseStateGuard.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Domains\Purchase\Services;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
|
||||||
|
class PurchaseStateGuard
|
||||||
|
{
|
||||||
|
public function assertNotExpired(Purchase $purchase): void
|
||||||
|
{
|
||||||
|
$hasExpiredStatus = $purchase->status === Purchase::STATUS_EXPIRED;
|
||||||
|
$hasExpiredByTime = in_array($purchase->status, [
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
], true)
|
||||||
|
&& $purchase->expires_at !== null
|
||||||
|
&& $purchase->expires_at->isPast();
|
||||||
|
|
||||||
|
if ($hasExpiredStatus || $hasExpiredByTime) {
|
||||||
|
throw new PurchaseExpiredException;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ class AdminAppSaleService
|
|||||||
->where('tenant_codigo', $tenant->codigo)
|
->where('tenant_codigo', $tenant->codigo)
|
||||||
->with([
|
->with([
|
||||||
'items',
|
'items',
|
||||||
|
'cart' => fn ($query) => $query->withTrashed(),
|
||||||
'cart.items.catalogItem',
|
'cart.items.catalogItem',
|
||||||
'cart.items.variant.catalogItem',
|
'cart.items.variant.catalogItem',
|
||||||
'cart.items.variant.eventDates',
|
'cart.items.variant.eventDates',
|
||||||
@@ -151,7 +152,18 @@ class AdminAppSaleService
|
|||||||
$filters['status'] ?? null,
|
$filters['status'] ?? null,
|
||||||
fn (Builder $query, string $status): Builder => $query->where('status', $status)
|
fn (Builder $query, string $status): Builder => $query->where('status', $status)
|
||||||
)
|
)
|
||||||
->withSum('items as quantity', 'cantidad')
|
->select('compras.*')
|
||||||
|
->selectRaw(
|
||||||
|
'CASE WHEN compras.status IN (?, ?) '
|
||||||
|
.'THEN (SELECT COALESCE(SUM(cart_items.cantidad), 0) FROM carrito_items AS cart_items '
|
||||||
|
.'WHERE cart_items.cart_id = compras.cart_id) '
|
||||||
|
.'ELSE (SELECT COALESCE(SUM(purchase_items.cantidad), 0) FROM compra_items AS purchase_items '
|
||||||
|
.'WHERE purchase_items.compra_id = compras.id) END AS quantity',
|
||||||
|
[
|
||||||
|
Purchase::STATUS_CREATED,
|
||||||
|
Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
],
|
||||||
|
)
|
||||||
->withCount('tickets')
|
->withCount('tickets')
|
||||||
->orderBy($sortColumns[$sortBy], $sortDirection)
|
->orderBy($sortColumns[$sortBy], $sortDirection)
|
||||||
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
|
->when($sortBy !== 'id', fn (Builder $query): Builder => $query->orderByDesc('id'));
|
||||||
@@ -177,8 +189,28 @@ class AdminAppSaleService
|
|||||||
|
|
||||||
protected function saleForResponse(Purchase $sale): Purchase
|
protected function saleForResponse(Purchase $sale): Purchase
|
||||||
{
|
{
|
||||||
return $sale->refresh()
|
/** @var Purchase */
|
||||||
->loadSum('items as quantity', 'cantidad')
|
return Purchase::query()
|
||||||
->loadCount('tickets');
|
->select('compras.*')
|
||||||
|
->selectRaw($this->quantityExpression())
|
||||||
|
->withCount('tickets')
|
||||||
|
->findOrFail($sale->getKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function quantityExpression(): string
|
||||||
|
{
|
||||||
|
// El fallback se resuelve en SQL para poder ordenar por cantidad antes de paginar;
|
||||||
|
// los ítems consolidados de la compra tienen prioridad sobre los del carrito de origen.
|
||||||
|
return <<<'SQL'
|
||||||
|
COALESCE(
|
||||||
|
(SELECT SUM(compra_items.cantidad)
|
||||||
|
FROM compra_items
|
||||||
|
WHERE compra_items.compra_id = compras.id),
|
||||||
|
(SELECT SUM(carrito_items.cantidad)
|
||||||
|
FROM carrito_items
|
||||||
|
WHERE carrito_items.cart_id = compras.cart_id),
|
||||||
|
0
|
||||||
|
) AS quantity
|
||||||
|
SQL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use App\Domains\Auth\Exceptions\AccountLockedException;
|
use App\Domains\Auth\Exceptions\AccountLockedException;
|
||||||
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
use App\Domains\Purchase\Exceptions\InsufficientStockException;
|
||||||
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
use App\Domains\Purchase\Exceptions\PurchaseLimitExceededException;
|
use App\Domains\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;
|
||||||
@@ -102,6 +103,16 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||||||
'maximum_addable_quantity' => $exception->maximumAddableQuantity,
|
'maximum_addable_quantity' => $exception->maximumAddableQuantity,
|
||||||
], 422);
|
], 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;
|
||||||
|
|||||||
@@ -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']);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -74,7 +74,7 @@ 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_policy' => 'disabled',
|
'cart_editing_policy' => 'full',
|
||||||
'checkout_editing_policy' => 'disabled',
|
'checkout_editing_policy' => 'disabled',
|
||||||
'display_cart_item_images' => false,
|
'display_cart_item_images' => false,
|
||||||
'scanner_category_validation_enabled' => false,
|
'scanner_category_validation_enabled' => false,
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ 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.',
|
'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.',
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ 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.',
|
'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.',
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Migrations;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class EnableFullCartEditingForDesfileTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_it_enables_quantity_variant_and_removal_changes_for_desfile(): void
|
||||||
|
{
|
||||||
|
$migration = require database_path(
|
||||||
|
'migrations/2026_08_20_020000_enable_full_cart_editing_for_desfile.php'
|
||||||
|
);
|
||||||
|
|
||||||
|
$migration->down();
|
||||||
|
$migration->up();
|
||||||
|
|
||||||
|
$this->assertDatabaseHas('tenants', [
|
||||||
|
'codigo' => 'desfile_pura_tendencia',
|
||||||
|
'cart_editing_policy' => 'full',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature\Purchase;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class PurchaseExpiredExceptionResponseTest extends TestCase
|
||||||
|
{
|
||||||
|
public function test_it_returns_a_stable_api_error_for_an_expired_purchase(): void
|
||||||
|
{
|
||||||
|
Route::get('/api/test/purchase-expired', function (): never {
|
||||||
|
throw new PurchaseExpiredException;
|
||||||
|
});
|
||||||
|
|
||||||
|
$this->getJson('/api/test/purchase-expired')
|
||||||
|
->assertUnprocessable()
|
||||||
|
->assertExactJson([
|
||||||
|
'code' => 'purchase.expired',
|
||||||
|
'message' => __('api.purchase.expired'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1244,6 +1244,42 @@ class StorePurchaseTest extends TestCase
|
|||||||
->assertJsonPath('data.total', '100.00');
|
->assertJsonPath('data.total', '100.00');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_created_and_pending_payment_purchase_details_use_the_current_cart_quantity(): void
|
||||||
|
{
|
||||||
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
|
$user = User::factory()->create([
|
||||||
|
'email' => 'buyer@example.com',
|
||||||
|
]);
|
||||||
|
$variant = $this->createVariantForTenant('sonder', 10, '50.00');
|
||||||
|
|
||||||
|
foreach ([Purchase::STATUS_CREATED, Purchase::STATUS_PENDING_PAYMENT] as $status) {
|
||||||
|
$purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);
|
||||||
|
$purchase->items()->create([
|
||||||
|
'source_catalog_item_id' => $variant->catalog_item_id,
|
||||||
|
'source_variant_id' => $variant->id,
|
||||||
|
'item_nombre' => $variant->catalogItem->nombre,
|
||||||
|
'descripcion' => $variant->catalogItem->descripcion,
|
||||||
|
'slug' => $variant->catalogItem->slug,
|
||||||
|
'variant_attributes' => [],
|
||||||
|
'cantidad' => 1,
|
||||||
|
'precio_unitario' => '50.00',
|
||||||
|
'total' => '50.00',
|
||||||
|
]);
|
||||||
|
$purchase->cart->items()->update(['cantidad' => 3]);
|
||||||
|
$purchase->update(['status' => $status]);
|
||||||
|
|
||||||
|
$this->actingAs($user, 'sanctum')
|
||||||
|
->getJson("/api/tenants/sonder/compras/{$purchase->id}")
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.status', $status)
|
||||||
|
->assertJsonPath('data.items_source', 'cart')
|
||||||
|
->assertJsonPath('data.items.0.quantity', 3)
|
||||||
|
->assertJsonPath('data.items.0.line_total', '150.00')
|
||||||
|
->assertJsonPath('data.subtotal', '150.00')
|
||||||
|
->assertJsonPath('data.total', '150.00');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function test_purchase_detail_uses_purchase_items_for_paid_purchase_even_without_cart(): void
|
public function test_purchase_detail_uses_purchase_items_for_paid_purchase_even_without_cart(): void
|
||||||
{
|
{
|
||||||
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
$this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
|
||||||
|
|||||||
@@ -31,6 +31,83 @@ class AdminAppSaleControllerTest extends TestCase
|
|||||||
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
|
WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_sales_list_uses_cart_quantity_for_created_and_pending_payment_sales(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$catalogItem = CatalogItem::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'slug' => 'entrada-general',
|
||||||
|
'nombre' => 'Entrada general',
|
||||||
|
'precio' => '10000.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$createdCart = Cart::query()->create([
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => 'checkout',
|
||||||
|
]);
|
||||||
|
CartItem::query()->create([
|
||||||
|
'cart_id' => $createdCart->id,
|
||||||
|
'catalog_item_id' => $catalogItem->id,
|
||||||
|
'cantidad' => 3,
|
||||||
|
]);
|
||||||
|
$createdPurchase = Purchase::query()->create([
|
||||||
|
'cart_id' => $createdCart->id,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => Purchase::STATUS_CREATED,
|
||||||
|
'total' => '30000.00',
|
||||||
|
]);
|
||||||
|
PurchaseItem::query()->create([
|
||||||
|
'compra_id' => $createdPurchase->id,
|
||||||
|
'source_catalog_item_id' => $catalogItem->id,
|
||||||
|
'item_nombre' => $catalogItem->nombre,
|
||||||
|
'cantidad' => 1,
|
||||||
|
'precio_unitario' => '10000.00',
|
||||||
|
'total' => '10000.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$pendingCart = Cart::query()->create([
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => 'checkout',
|
||||||
|
]);
|
||||||
|
CartItem::query()->create([
|
||||||
|
'cart_id' => $pendingCart->id,
|
||||||
|
'catalog_item_id' => $catalogItem->id,
|
||||||
|
'cantidad' => 4,
|
||||||
|
]);
|
||||||
|
$pendingPurchase = Purchase::query()->create([
|
||||||
|
'cart_id' => $pendingCart->id,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
'total' => '40000.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$paidPurchase = Purchase::query()->create([
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => Purchase::STATUS_PAID,
|
||||||
|
'total' => '20000.00',
|
||||||
|
]);
|
||||||
|
PurchaseItem::query()->create([
|
||||||
|
'compra_id' => $paidPurchase->id,
|
||||||
|
'source_catalog_item_id' => $catalogItem->id,
|
||||||
|
'item_nombre' => $catalogItem->nombre,
|
||||||
|
'cantidad' => 2,
|
||||||
|
'precio_unitario' => '10000.00',
|
||||||
|
'total' => '20000.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/tenant/sales?sort_by=id&sort_direction=asc')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonCount(3, 'data')
|
||||||
|
->assertJsonPath('data.0.id', $createdPurchase->id)
|
||||||
|
->assertJsonPath('data.0.quantity', 3)
|
||||||
|
->assertJsonPath('data.1.id', $pendingPurchase->id)
|
||||||
|
->assertJsonPath('data.1.quantity', 4)
|
||||||
|
->assertJsonPath('data.2.id', $paidPurchase->id)
|
||||||
|
->assertJsonPath('data.2.quantity', 2);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_authentication_is_required_to_read_a_sale_detail(): void
|
public function test_authentication_is_required_to_read_a_sale_detail(): void
|
||||||
{
|
{
|
||||||
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized();
|
$this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized();
|
||||||
@@ -110,6 +187,54 @@ class AdminAppSaleControllerTest extends TestCase
|
|||||||
->assertJsonPath('data.items.0.total', '25000.00');
|
->assertJsonPath('data.items.0.total', '25000.00');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function test_sales_list_uses_cart_quantity_until_purchase_items_exist(): void
|
||||||
|
{
|
||||||
|
$tenant = $this->createTenant('acme');
|
||||||
|
Sanctum::actingAs($this->createAdminAppUser($tenant));
|
||||||
|
|
||||||
|
$catalogItem = CatalogItem::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'slug' => 'entrada-general',
|
||||||
|
'nombre' => 'Entrada general',
|
||||||
|
'descripcion' => 'Acceso general',
|
||||||
|
'precio' => '12500.00',
|
||||||
|
]);
|
||||||
|
$cart = Cart::query()->create([
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => 'checkout',
|
||||||
|
]);
|
||||||
|
CartItem::query()->create([
|
||||||
|
'cart_id' => $cart->id,
|
||||||
|
'catalog_item_id' => $catalogItem->id,
|
||||||
|
'cantidad' => 3,
|
||||||
|
]);
|
||||||
|
$purchase = Purchase::query()->create([
|
||||||
|
'cart_id' => $cart->id,
|
||||||
|
'tenant_codigo' => $tenant->codigo,
|
||||||
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
'total' => '37500.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/tenant/sales')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.0.id', $purchase->id)
|
||||||
|
->assertJsonPath('data.0.quantity', 3);
|
||||||
|
|
||||||
|
PurchaseItem::query()->create([
|
||||||
|
'compra_id' => $purchase->id,
|
||||||
|
'source_catalog_item_id' => $catalogItem->id,
|
||||||
|
'nombre' => 'Entrada general',
|
||||||
|
'item_nombre' => 'Entrada general',
|
||||||
|
'cantidad' => 2,
|
||||||
|
'precio_unitario' => '12500.00',
|
||||||
|
'total' => '25000.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->getJson('/api/v1/adminapp/tenant/sales')
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.0.quantity', 2);
|
||||||
|
}
|
||||||
|
|
||||||
public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
|
public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
|
||||||
{
|
{
|
||||||
$tenant = $this->createTenant('acme');
|
$tenant = $this->createTenant('acme');
|
||||||
@@ -241,6 +366,18 @@ class AdminAppSaleControllerTest extends TestCase
|
|||||||
'user_id' => $admin->id,
|
'user_id' => $admin->id,
|
||||||
'status' => 'converted',
|
'status' => 'converted',
|
||||||
]);
|
]);
|
||||||
|
$catalogItem = CatalogItem::query()->create([
|
||||||
|
'tenant_code' => $tenant->codigo,
|
||||||
|
'slug' => 'entrada-general',
|
||||||
|
'nombre' => 'Entrada general',
|
||||||
|
'descripcion' => 'Acceso general',
|
||||||
|
'precio' => '10000.00',
|
||||||
|
]);
|
||||||
|
CartItem::query()->create([
|
||||||
|
'cart_id' => $cart->id,
|
||||||
|
'catalog_item_id' => $catalogItem->id,
|
||||||
|
'cantidad' => 2,
|
||||||
|
]);
|
||||||
$cart->delete();
|
$cart->delete();
|
||||||
$purchase = Purchase::query()->create([
|
$purchase = Purchase::query()->create([
|
||||||
'cart_id' => $cart->id,
|
'cart_id' => $cart->id,
|
||||||
@@ -251,11 +388,17 @@ class AdminAppSaleControllerTest extends TestCase
|
|||||||
|
|
||||||
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
|
$this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
|
||||||
->assertOk()
|
->assertOk()
|
||||||
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);
|
->assertJsonPath('data.status', Purchase::STATUS_CANCELLED)
|
||||||
|
->assertJsonPath('data.quantity', 2);
|
||||||
|
|
||||||
$this->assertSame(Purchase::STATUS_CANCELLED, $purchase->fresh()->status);
|
$this->assertSame(Purchase::STATUS_CANCELLED, $purchase->fresh()->status);
|
||||||
$this->assertSoftDeleted('carritos', ['id' => $cart->id]);
|
$this->assertSoftDeleted('carritos', ['id' => $cart->id]);
|
||||||
$this->assertSame('converted', Cart::withTrashed()->findOrFail($cart->id)->status);
|
$this->assertSame('converted', Cart::withTrashed()->findOrFail($cart->id)->status);
|
||||||
|
|
||||||
|
$this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
|
||||||
|
->assertOk()
|
||||||
|
->assertJsonPath('data.items.0.product', 'Entrada general')
|
||||||
|
->assertJsonPath('data.items.0.quantity', 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void
|
public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class DesfilePuraTendenciaSeederTest extends TestCase
|
|||||||
'footer_bg_color' => '#D4441C',
|
'footer_bg_color' => '#D4441C',
|
||||||
'display_categories' => false,
|
'display_categories' => false,
|
||||||
'display_seach_bar' => false,
|
'display_seach_bar' => false,
|
||||||
'cart_editing_policy' => 'disabled',
|
'cart_editing_policy' => 'full',
|
||||||
'checkout_editing_policy' => 'disabled',
|
'checkout_editing_policy' => 'disabled',
|
||||||
'display_cart_item_images' => false,
|
'display_cart_item_images' => false,
|
||||||
'site_title' => 'Desfile Pura Tendencia',
|
'site_title' => 'Desfile Pura Tendencia',
|
||||||
|
|||||||
56
tests/Unit/Purchase/PurchaseStateGuardTest.php
Normal file
56
tests/Unit/Purchase/PurchaseStateGuardTest.php
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Unit\Purchase;
|
||||||
|
|
||||||
|
use App\Domains\Purchase\Exceptions\PurchaseExpiredException;
|
||||||
|
use App\Domains\Purchase\Models\Purchase;
|
||||||
|
use App\Domains\Purchase\Services\PurchaseStateGuard;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class PurchaseStateGuardTest extends TestCase
|
||||||
|
{
|
||||||
|
private PurchaseStateGuard $guard;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
$this->guard = new PurchaseStateGuard;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_rejects_a_purchase_with_expired_status(): void
|
||||||
|
{
|
||||||
|
$purchase = (new Purchase)->forceFill([
|
||||||
|
'status' => Purchase::STATUS_EXPIRED,
|
||||||
|
'expires_at' => null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->expectException(PurchaseExpiredException::class);
|
||||||
|
|
||||||
|
$this->guard->assertNotExpired($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_rejects_an_active_purchase_when_its_deadline_has_passed(): void
|
||||||
|
{
|
||||||
|
$purchase = (new Purchase)->forceFill([
|
||||||
|
'status' => Purchase::STATUS_PENDING_PAYMENT,
|
||||||
|
'expires_at' => now()->subMinute(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->expectException(PurchaseExpiredException::class);
|
||||||
|
|
||||||
|
$this->guard->assertNotExpired($purchase);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_does_not_treat_a_paid_purchase_as_expired_by_time(): void
|
||||||
|
{
|
||||||
|
$purchase = (new Purchase)->forceFill([
|
||||||
|
'status' => Purchase::STATUS_PAID,
|
||||||
|
'expires_at' => now()->subMinute(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->guard->assertNotExpired($purchase);
|
||||||
|
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user