Skip to content

Commit 5977b06

Browse files
committed
Calculate subtotal right after calculating line items
1 parent 3f57a4d commit 5977b06

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

src/Cart/Calculator/CalculateLineItems.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class CalculateLineItems
1212

1313
public function handle(Cart $cart, Closure $next)
1414
{
15-
$cart->lineItems()->map(function (LineItem $lineItem) use ($cart) {
15+
$cart->lineItems()->each(function (LineItem $lineItem) use ($cart) {
1616
$product = $lineItem->product();
1717

1818
$price = match (true) {
@@ -24,10 +24,10 @@ public function handle(Cart $cart, Closure $next)
2424
$lineItem->unitPrice($price);
2525
$lineItem->subTotal($price * $lineItem->quantity());
2626
$lineItem->total($lineItem->subTotal());
27-
28-
return $lineItem;
2927
});
3028

29+
$cart->subTotal($cart->lineItems()->map->subTotal()->sum());
30+
3131
return $next($cart);
3232
}
3333

src/Cart/Calculator/CalculateTotals.php

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ public function handle(Cart $cart, Closure $next)
1111
{
1212
$pricesIncludeTax = config('statamic.cargo.taxes.price_includes_tax');
1313

14-
// Calculate the subtotal by summing the line item subtotals (totals without additional taxes)
15-
$cart->subTotal($cart->lineItems()->map->subTotal()->sum());
16-
1714
// Calculate the total (subtotal + taxes if they aren't included in the prices)
1815
$total = $cart->subTotal();
1916

tests/Cart/Calculator/CalculateLineItemsTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,23 @@ public function total_can_be_calculated_correctly_with_variant_when_price_contai
9393
$this->assertEquals(5100, $cart->lineItems()->find('a')->total());
9494
}
9595

96+
#[Test]
97+
public function calculates_order_subtotal()
98+
{
99+
Collection::make('products')->save();
100+
$productA = tap(Entry::make()->collection('products')->data(['price' => 2550]))->save();
101+
$productB = tap(Entry::make()->collection('products')->data(['price' => 1500]))->save();
102+
103+
$cart = Cart::make()->lineItems([
104+
['id' => 'a', 'product' => $productA->id(), 'quantity' => 2],
105+
['id' => 'b', 'product' => $productB->id(), 'quantity' => 1],
106+
]);
107+
108+
(new CalculateLineItems)->handle($cart, fn ($cart) => $cart);
109+
110+
$this->assertEquals(6600, $cart->subTotal());
111+
}
112+
96113
#[Test]
97114
public function total_can_be_calculated_correctly_using_price_hook()
98115
{

0 commit comments

Comments
 (0)