diff --git a/src/Models/Cart.php b/src/Models/Cart.php index f3aeb99..58ca86d 100644 --- a/src/Models/Cart.php +++ b/src/Models/Cart.php @@ -85,11 +85,11 @@ public function scopeFirstOrCreateWithStoreItems( /** * Calculate price by quantity of items. */ - public function calculatedPriceByQuantity(): int + public function calculatedPriceByQuantity(): float { $totalPrice = 0; foreach ($this->items()->get() as $item) { - $totalPrice += (int) $item->quantity * (int) $item->itemable->getPrice(); + $totalPrice += (int) $item->quantity * (float) $item->itemable->getPrice(); } return $totalPrice; diff --git a/tests/Feature/Models/CartStoreTest.php b/tests/Feature/Models/CartStoreTest.php index 7359fcd..9db6b45 100644 --- a/tests/Feature/Models/CartStoreTest.php +++ b/tests/Feature/Models/CartStoreTest.php @@ -12,6 +12,7 @@ use function Pest\Laravel\assertDatabaseCount; use function Pest\Laravel\assertDatabaseHas; use function Pest\Laravel\assertDatabaseMissing; +use function PHPUnit\Framework\assertEquals; use function PHPUnit\Framework\assertInstanceOf; /* @@ -188,11 +189,20 @@ $cart->storeItems($items); // Assertions - \PHPUnit\Framework\assertEquals(230000, $cart->calculatedPriceByQuantity()); + assertEquals(230000, $cart->calculatedPriceByQuantity()); + + // Float + $cart->storeItems([ + [ + 'itemable' => Product::query()->create(['title' => 'Product float', 'price' => 15000.3]), + 'quantity' => 2, + ], + ]); + assertEquals(260000.6, $cart->calculatedPriceByQuantity()); // DB Assertions assertDatabaseCount('carts', 1); - assertDatabaseCount('cart_items', 3); + assertDatabaseCount('cart_items', 4); assertDatabaseHas('cart_items', [ 'itemable_id' => $product1->id, 'itemable_type' => $product1::class,