feat: add getTotalAmount method to Cart and refactor Purchase model to utilize it
This commit is contained in:
@@ -10,7 +10,6 @@ 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',
|
||||
@@ -59,7 +58,7 @@ class Purchase extends Model
|
||||
*/
|
||||
public function cart(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Cart::class, 'cart_id')->withTrashed();
|
||||
return $this->belongsTo(Cart::class, 'cart_id');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,21 +91,15 @@ class Purchase extends Model
|
||||
return (float) $this->items()->sum('total');
|
||||
}
|
||||
|
||||
$cart = $this->relationLoaded('cart') ? $this->getRelation('cart') : $this->cart;
|
||||
$cart = $this->relationLoaded('cart')
|
||||
? $this->getRelation('cart')
|
||||
: $this->cart()->first();
|
||||
|
||||
if ($cart === null) {
|
||||
if (! $cart) {
|
||||
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,
|
||||
);
|
||||
return $cart->getTotalAmount();
|
||||
}
|
||||
|
||||
public function finalize(): void
|
||||
|
||||
Reference in New Issue
Block a user