TreasuryAccountService.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Services;
  3. use App\Models\TreasuryAccount;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class TreasuryAccountService
  6. {
  7. /**
  8. * Lista as contas de tesouraria por escopo:
  9. * - franqueador (rede/conta-mãe): sem unit_id => contas com unit_id null;
  10. * - franchisee: unit_id da unidade ativa => contas daquela unidade.
  11. */
  12. public function getAll(?int $unitId = null): Collection
  13. {
  14. return TreasuryAccount::query()
  15. ->when(
  16. $unitId !== null,
  17. fn ($query) => $query->where('unit_id', $unitId),
  18. fn ($query) => $query->whereNull('unit_id'),
  19. )
  20. ->orderBy('created_at', 'desc')
  21. ->get();
  22. }
  23. public function findById(int $id): ?TreasuryAccount
  24. {
  25. return TreasuryAccount::find($id);
  26. }
  27. public function create(array $data): TreasuryAccount
  28. {
  29. // Sem unit_id => conta da rede (franqueador). Com unit_id => conta da unidade (franchisee).
  30. $data['unit_id'] = $data['unit_id'] ?? null;
  31. return TreasuryAccount::create($data);
  32. }
  33. public function update(int $id, array $data): ?TreasuryAccount
  34. {
  35. $model = $this->findById($id);
  36. if (!$model) {
  37. return null;
  38. }
  39. $model->update($data);
  40. return $model->fresh();
  41. }
  42. public function delete(int $id): bool
  43. {
  44. $model = $this->findById($id);
  45. if (!$model) {
  46. return false;
  47. }
  48. return $model->delete();
  49. }
  50. // Add custom business logic methods here
  51. }