55 lines
2.0 KiB
PHP
55 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services\ClassPreparation;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class ClassPreparationInventoryService
|
|
{
|
|
public function buildAvailability(string $schoolYear, string $semester, bool $limitToSemester, array $allowed): array
|
|
{
|
|
$inventoryMap = array_fill_keys($allowed, 0);
|
|
|
|
$joinRows = DB::table('inventory_items as ii')
|
|
->select('ic.name AS item_name, COALESCE(SUM(CASE WHEN ii.good_qty IS NOT NULL THEN ii.good_qty WHEN ii.`condition`=\"good\" THEN ii.quantity ELSE 0 END),0) AS available')
|
|
->join('inventory_categories as ic', 'ic.id', '=', 'ii.category_id')
|
|
->where('ii.type', 'classroom')
|
|
->where('ii.school_year', $schoolYear)
|
|
->whereIn('ic.name', $allowed);
|
|
|
|
if ($limitToSemester && $semester !== '') {
|
|
$joinRows->where('ii.semester', $semester);
|
|
}
|
|
|
|
$joinRows = $joinRows->groupBy('ic.name')->get()->toArray();
|
|
|
|
foreach ($joinRows as $r) {
|
|
$name = (string) ($r->item_name ?? '');
|
|
if ($name !== '' && isset($inventoryMap[$name])) {
|
|
$inventoryMap[$name] = max($inventoryMap[$name], (int) ($r->available ?? 0));
|
|
}
|
|
}
|
|
|
|
$nameRows = DB::table('inventory_items')
|
|
->select('name AS item_name, COALESCE(SUM(CASE WHEN good_qty IS NOT NULL THEN good_qty WHEN `condition`=\"good\" THEN quantity ELSE 0 END),0) AS available')
|
|
->where('type', 'classroom')
|
|
->where('school_year', $schoolYear)
|
|
->whereIn('name', $allowed);
|
|
|
|
if ($limitToSemester && $semester !== '') {
|
|
$nameRows->where('semester', $semester);
|
|
}
|
|
|
|
$nameRows = $nameRows->groupBy('name')->get()->toArray();
|
|
|
|
foreach ($nameRows as $r) {
|
|
$name = (string) ($r->item_name ?? '');
|
|
if ($name !== '' && isset($inventoryMap[$name])) {
|
|
$inventoryMap[$name] = max($inventoryMap[$name], (int) ($r->available ?? 0));
|
|
}
|
|
}
|
|
|
|
return $inventoryMap;
|
|
}
|
|
}
|