TreasuryLaunchService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. ->when($accountId !== null, fn ($query) => $query->where(function ($q) use ($accountId) {
  17. $q->where('from_account_id', $accountId)
  18. ->orWhere('to_account_id', $accountId);
  19. }))
  20. ->orderBy('launch_date', 'desc')
  21. ->orderBy('created_at', 'desc')
  22. ->get();
  23. }
  24. public function findById(int $id): ?TreasuryLaunch
  25. {
  26. return TreasuryLaunch::find($id);
  27. }
  28. public function create(array $data): TreasuryLaunch
  29. {
  30. return TreasuryLaunch::create($this->normalize($data));
  31. }
  32. public function update(int $id, array $data): ?TreasuryLaunch
  33. {
  34. $model = $this->findById($id);
  35. if (!$model) {
  36. return null;
  37. }
  38. $model->update($this->normalize($data, isCreate: false));
  39. return $model->fresh();
  40. }
  41. public function delete(int $id): bool
  42. {
  43. $model = $this->findById($id);
  44. if (!$model) {
  45. return false;
  46. }
  47. return $model->delete();
  48. }
  49. /**
  50. * Traduz a movimentação manual (account_id + transaction_type) para os campos
  51. * do lançamento: entrada credita o banco (to_account), saída debita (from_account).
  52. */
  53. private function normalize(array $data, bool $isCreate = true): array
  54. {
  55. $accountId = $data['account_id'] ?? null;
  56. unset($data['account_id']);
  57. if ($accountId !== null && isset($data['transaction_type'])) {
  58. $account = TreasuryAccount::find($accountId);
  59. $data['unit_id'] = $account?->unit_id;
  60. if ($data['transaction_type'] === 'entrada') {
  61. $data['to_account_id'] = $accountId;
  62. $data['from_account_id'] = null;
  63. } else {
  64. $data['from_account_id'] = $accountId;
  65. $data['to_account_id'] = null;
  66. }
  67. }
  68. if ($isCreate) {
  69. $data['user_id'] = Auth::id();
  70. $data['origin'] = $data['origin'] ?? 'manual';
  71. $data['launch_date'] = $data['launch_date'] ?? now()->toDateString();
  72. $data['is_reconciled'] = false;
  73. }
  74. return $data;
  75. }
  76. }