buckets/app/Repositories/StreamRepository.php

88 lines
2 KiB
PHP

<?php
namespace App\Repositories;
use App\Models\Scenario;
use App\Models\Stream;
use Illuminate\Support\Collection;
class StreamRepository
{
public function getForScenario(Scenario $scenario): Collection
{
return $scenario->streams()
->with('bucket:id,name')
->orderBy('type')
->orderBy('name')
->get();
}
public function create(Scenario $scenario, array $data): Stream
{
return $scenario->streams()->create($data);
}
public function update(Stream $stream, array $data): Stream
{
$stream->update($data);
return $stream->fresh('bucket');
}
public function delete(Stream $stream): bool
{
return $stream->delete();
}
public function toggleActive(Stream $stream): Stream
{
$stream->update([
'is_active' => ! $stream->is_active,
]);
return $stream->fresh('bucket');
}
/**
* Check if a bucket belongs to the scenario
*/
public function bucketBelongsToScenario(Scenario $scenario, ?int $bucketId): bool
{
if (! $bucketId) {
return true;
}
return $scenario->buckets()
->where('id', $bucketId)
->exists();
}
/**
* Get streams grouped by type
*/
public function getGroupedByType(Scenario $scenario): array
{
return [
'income' => $scenario->streams()
->with('bucket:id,name')
->byType(Stream::TYPE_INCOME)
->orderBy('name')
->get(),
'expense' => $scenario->streams()
->with('bucket:id,name')
->byType(Stream::TYPE_EXPENSE)
->orderBy('name')
->get(),
];
}
/**
* Get streams for a specific bucket
*/
public function getForBucket(int $bucketId): Collection
{
return Stream::where('bucket_id', $bucketId)
->where('is_active', true)
->get();
}
}