TreasuryLaunchService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Services;
  3. use App\Models\TreasuryAccount;
  4. use App\Models\TreasuryLaunch;
  5. use Illuminate\Database\Eloquent\Collection;
  6. use Illuminate\Support\Facades\Auth;
  7. class TreasuryLaunchService
  8. {
  9. /**
  10. * Extrato de um banco: lançamentos onde ele é origem ou destino.
  11. * Sem account_id retorna o extrato consolidado (todos os lançamentos).
  12. */
  13. public function getAll(?int $accountId = null): Collection
  14. {
  15. return TreasuryLaunch::query()
  16. ->with('financialPlanAccount')
  17. ->when($accountId !== null, fn ($query) => $query->where(function ($q) use ($accountId) {
  18. $q->where('from_account_id', $accountId)
  19. ->orWhere('to_account_id', $accountId);
  20. }))
  21. ->orderBy('launch_date', 'desc')
  22. ->orderBy('created_at', 'desc')
  23. ->get();
  24. }
  25. public function findById(int $id): ?TreasuryLaunch
  26. {
  27. return TreasuryLaunch::find($id);
  28. }
  29. public function create(array $data): TreasuryLaunch
  30. {
  31. return TreasuryLaunch::create($this->normalize($data));
  32. }
  33. public function update(int $id, array $data): ?TreasuryLaunch
  34. {
  35. $model = $this->findById($id);
  36. if (!$model) {
  37. return null;
  38. }
  39. $model->update($this->normalize($data, isCreate: false));
  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. /**
  51. * Traduz a movimentação manual (account_id + transaction_type) para os campos
  52. * do lançamento: entrada credita o banco (to_account), saída debita (from_account).
  53. */
  54. private function normalize(array $data, bool $isCreate = true): array
  55. {
  56. $accountId = $data['account_id'] ?? null;
  57. unset($data['account_id']);
  58. if ($accountId !== null && isset($data['transaction_type'])) {
  59. $account = TreasuryAccount::find($accountId);
  60. $data['unit_id'] = $account?->unit_id;
  61. if ($data['transaction_type'] === 'entrada') {
  62. $data['to_account_id'] = $accountId;
  63. $data['from_account_id'] = null;
  64. } else {
  65. $data['from_account_id'] = $accountId;
  66. $data['to_account_id'] = null;
  67. }
  68. }
  69. if ($isCreate) {
  70. $data['user_id'] = Auth::id();
  71. $data['origin'] = $data['origin'] ?? 'manual';
  72. $data['launch_date'] = $data['launch_date'] ?? now()->toDateString();
  73. $data['is_reconciled'] = false;
  74. }
  75. return $data;
  76. }
  77. }