From 8dbf70168c79afb620d3eab4641734354bbb5e64 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Wed, 3 Dec 2025 15:45:11 +0100 Subject: [PATCH] A adjustStock method --- src/Traits/HasStocks.php | 24 ++++++++++++++++++ tests/Feature/ProductStockTest.php | 39 +++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/Traits/HasStocks.php b/src/Traits/HasStocks.php index 33e104e..fba329d 100644 --- a/src/Traits/HasStocks.php +++ b/src/Traits/HasStocks.php @@ -79,6 +79,30 @@ trait HasStocks return true; } + public function adjustStock( + StockType $type, + int $quantity, + \DateTimeInterface|null $until = null, + ?StockStatus $status = null, + ) { + if (!$this->manage_stock) { + return false; + } + + $this->stocks()->create([ + 'quantity' => $type === StockType::INCREASE ? $quantity : -$quantity, + 'type' => $type, + 'status' => $status ?? StockStatus::COMPLETED, + 'expires_at' => $until, + ]); + + $this->logStockChange($type === StockType::INCREASE ? $quantity : -$quantity, 'adjust'); + + $this->save(); + + return true; + } + public function reserveStock( int $quantity, $reference = null, diff --git a/tests/Feature/ProductStockTest.php b/tests/Feature/ProductStockTest.php index bd6deac..2e7cb8e 100644 --- a/tests/Feature/ProductStockTest.php +++ b/tests/Feature/ProductStockTest.php @@ -193,7 +193,7 @@ class ProductStockTest extends TestCase // Expired reservations should be counted in available stock $available = $product->reservations()->get(); - + $this->assertEquals(0, $available->count()); } @@ -275,4 +275,41 @@ class ProductStockTest extends TestCase $this->assertCount(1, $reservations); $this->assertEquals($active->id, $reservations->first()->id); } + + /** @test */ + public function can_adjust_stock() + { + $product = Product::factory()->create(['manage_stock' => true]); + + $product->increaseStock(20); + $this->assertEquals(20, $product->getAvailableStock()); + + $product->adjustStock( + type: \Blax\Shop\Enums\StockType::DECREASE, + quantity: 5 + ); + $this->assertEquals(15, $product->getAvailableStock()); + + $product->adjustStock( + type: \Blax\Shop\Enums\StockType::INCREASE, + quantity: 10 + ); + $this->assertEquals(25, $product->getAvailableStock()); + + // Also with until + $product->adjustStock( + type: \Blax\Shop\Enums\StockType::DECREASE, + quantity: 5, + until: now()->addDay() + ); + $this->assertEquals(20, $product->getAvailableStock()); + + $this->travel(23)->hours(); + + $this->assertEquals(20, $product->getAvailableStock()); + + $this->travel(2)->days(); + + $this->assertEquals(25, $product->getAvailableStock()); + } }