gruene-seele/app/Repositories/StockEntryRepository.php

92 lines
2.3 KiB
PHP

<?php
namespace App\Repositories;
use App\Models\StockEntry;
use Illuminate\Database\Eloquent\Collection;
class StockEntryRepository
{
/**
* @param array<string, mixed> $data
*/
public function create(array $data): StockEntry
{
$data['unit'] = ($data['entry_type'] ?? '') === 'ingredient' ? 'gram' : 'piece';
return StockEntry::query()->create($data);
}
/**
* @param array<string, mixed> $data
*/
public function update(StockEntry $stockEntry, array $data): StockEntry
{
if (array_key_exists('entry_type', $data)) {
$data['unit'] = ($data['entry_type'] ?? '') === 'ingredient' ? 'gram' : 'piece';
}
$stockEntry->update($data);
return $stockEntry->fresh();
}
/**
* @param array<string, mixed> $data
*/
public function receive(StockEntry $stockEntry, array $data): StockEntry
{
$data['status'] = 'received';
$data['received_by'] = auth()->id();
$stockEntry->update($data);
return $stockEntry->fresh();
}
/**
* @return Collection<int, StockEntry>
*/
public function getByStatus(string $status): Collection
{
return StockEntry::query()
->where('status', $status)
->orderByDesc('ordered_at')
->get();
}
/**
* @return Collection<int, StockEntry>
*/
public function getForIngredient(int $ingredientId): Collection
{
return StockEntry::query()
->where('ingredient_id', $ingredientId)
->where('status', 'received')
->orderByDesc('received_at')
->get();
}
/**
* Liste: Pending zuerst (neuestes Bestelldatum), dann Received (neuester Eingang).
*
* @return Collection<int, StockEntry>
*/
public function listForIndex(): Collection
{
$with = [
'ingredient',
'packagingItem',
'supplier',
'location',
'quality',
'orderedByUser',
'receivedByUser',
];
$pending = StockEntry::query()->with($with)->where('status', 'pending')->orderByDesc('ordered_at')->get();
$received = StockEntry::query()->with($with)->where('status', 'received')->orderByDesc('received_at')->get();
return $pending->concat($received)->values();
}
}