From c612554cbd25d9c3e94ecf9e58b435585dc19942 Mon Sep 17 00:00:00 2001 From: Jan Willem Rigters Date: Wed, 18 Sep 2024 12:27:30 +0200 Subject: [PATCH] Created price hook from a lineItem perspective --- docs/dynamic-pricing.md | 14 ++++++++++++++ src/Orders/Calculator/LineItemCalculator.php | 2 ++ src/SimpleCommerce.php | 9 +++++++++ 3 files changed, 25 insertions(+) diff --git a/docs/dynamic-pricing.md b/docs/dynamic-pricing.md index 4526c9d49..68dafad0d 100644 --- a/docs/dynamic-pricing.md +++ b/docs/dynamic-pricing.md @@ -37,6 +37,20 @@ SimpleCommerce::productVariantPriceHook(function (Order $order, Product $product }); ``` +Another alternative method is available to calculate from a lineItem perspective. + +```php +use DuncanMcClean\SimpleCommerce\Orders\LineItem; + +SimpleCommerce::lineItemPriceHook(function (LineItem $lineItem) { + if ($lineItem->product()->get('sale')) { + return $lineItem->product()->get('price') * 0.9; // 10% discount + } + + return $lineItem->product()->get('price'); +}); +``` + :::note Note! These methods will not make any change to the price displayed to customers or stored in your products. They're only used when 'calculating' line items (eg. when an item is added to the cart, quantity changed, etc). ::: diff --git a/src/Orders/Calculator/LineItemCalculator.php b/src/Orders/Calculator/LineItemCalculator.php index 7cc089d9a..421186c65 100644 --- a/src/Orders/Calculator/LineItemCalculator.php +++ b/src/Orders/Calculator/LineItemCalculator.php @@ -41,6 +41,8 @@ public function handle(Order $order, Closure $next) if ($product->purchasableType() === ProductType::Product) { if (SimpleCommerce::$productPriceHook) { $productPrice = (SimpleCommerce::$productPriceHook)($order, $product); + } elseif (SimpleCommerce::$lineItemPriceHook) { + $productPrice = (SimpleCommerce::$lineItemPriceHook)($lineItem); } else { $productPrice = $product->price(); } diff --git a/src/SimpleCommerce.php b/src/SimpleCommerce.php index fe8d8e159..8431af2a2 100644 --- a/src/SimpleCommerce.php +++ b/src/SimpleCommerce.php @@ -23,6 +23,8 @@ class SimpleCommerce public static $productVariantPriceHook; + public static $lineItemPriceHook; + public static function version(): string { if (app()->environment('testing')) { @@ -200,4 +202,11 @@ public static function productVariantPriceHook(Closure $callback): self return new static; } + + public static function lineItemPriceHook(Closure $callback): self + { + static::$lineItemPriceHook = $callback; + + return new static; + } }