feat: enhance checkout process with cart integration and stock confirmation
This commit is contained in:
@@ -3,14 +3,17 @@
|
||||
namespace App\Domains\Purchase\Models;
|
||||
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Cart\Models\Cart;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
#[Fillable([
|
||||
'cart_id',
|
||||
'tenant_codigo',
|
||||
'user_id',
|
||||
'status',
|
||||
@@ -30,6 +33,7 @@ class Purchase extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cart_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
];
|
||||
}
|
||||
@@ -50,6 +54,14 @@ class Purchase extends Model
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Cart, $this>
|
||||
*/
|
||||
public function cart(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Cart::class, 'cart_id')->withTrashed();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<PurchaseItem, $this>
|
||||
*/
|
||||
@@ -76,7 +88,25 @@ class Purchase extends Model
|
||||
|
||||
public function getTotalAmount(): float
|
||||
{
|
||||
return (float) $this->items()->sum('total');
|
||||
if ($this->items()->exists()) {
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
$cart = $this->relationLoaded('cart') ? $this->getRelation('cart') : $this->cart;
|
||||
|
||||
if ($cart === null) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/** @var Collection<int, mixed> $items */
|
||||
$items = $cart->relationLoaded('items')
|
||||
? $cart->getRelation('items')
|
||||
: $cart->items()->with('variant.product')->get();
|
||||
|
||||
return $items->reduce(
|
||||
static fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * (int) $item->cantidad),
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
public function finalize(): void
|
||||
|
||||
Reference in New Issue
Block a user