-
Notifications
You must be signed in to change notification settings - Fork 0
/
EloquentStockRepository.php
66 lines (57 loc) · 2.34 KB
/
EloquentStockRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
namespace Src\Infrastructure\repositories\Eloquent;
use App\Models\IngredientStock;
use App\Models\StockTransaction;
use Illuminate\Support\Facades\DB;
use Src\Application\ports\infrastructure\repositories\StockRepository;
use Src\Domain\Entities\StockItem;
class EloquentStockRepository implements StockRepository
{
public function getStockItems(array $ingredientIds): array
{
$stockItems = IngredientStock::query()->whereIn("ingredient_id", $ingredientIds)->lockForUpdate()->get()->all();
$items = [];
foreach ($stockItems as $stockItem) {
$items[] = new StockItem(
$stockItem["ingredient_id"],
$stockItem["name"],
$stockItem["full_quantity"],
$stockItem["available_quantity"],
$stockItem["min_threshold_percentage"]
);
}
return $items;
}
public function updateStocks(array $stockItems): void
{
$ingredientIds = [];
$caseStatements = [];
$stockTransactions = [];
foreach ($stockItems as $stockItem) {
$ingredientIds[] = $stockItem->getId();
$transactions = $stockItem->getStockTransactions();
$caseStatements[] = "WHEN {$stockItem->getId()} THEN {$stockItem->getAvailableQuantity()}";
if (count($transactions)) {
foreach ($transactions as $stockTransaction) {
$stockTransactions[] = [
"transaction_id" => $stockTransaction->getId(),
"ingredient_id" => $stockTransaction->getIngredientId(),
"type" => $stockTransaction->getType(),
"reason" => $stockTransaction->getReason(),
"quantity" => $stockTransaction->getQuantity()
];
}
}
}
$caseStatements = implode(" ", $caseStatements);
// The goal is to update all the stocks in a single query.
IngredientStock::query()
->whereIn('ingredient_id', $ingredientIds)
->update(
[
'available_quantity' => DB::raw("CASE ingredient_id $caseStatements ELSE available_quantity END")
]
);
StockTransaction::factory()->createMany($stockTransactions);
}
}