Эх сурвалжийг харах

feat(treasury): compute account balance from launches

getAll attaches each account balance (sum of incoming minus outgoing launches) via two aggregations, exposed in the resource.
ebagabee 1 сар өмнө
parent
commit
2279932a1b

+ 1 - 0
app/Http/Resources/TreasuryAccountResource.php

@@ -27,6 +27,7 @@ public function toArray(Request $request): array
             'bank_account' => $this->bank_account,
             'bank_type_account' => $this->bank_type_account,
             'active' => (bool) $this->active,
+            'balance' => (float) ($this->balance ?? 0),
             'created_at' => Carbon::parse($this->created_at)->format('Y-m-d H:i:s'),
             'updated_at' => Carbon::parse($this->updated_at)->format('Y-m-d H:i:s'),
         ];

+ 35 - 1
app/Services/TreasuryAccountService.php

@@ -3,6 +3,7 @@
 namespace App\Services;
 
 use App\Models\TreasuryAccount;
+use App\Models\TreasuryLaunch;
 use Illuminate\Database\Eloquent\Collection;
 
 class TreasuryAccountService
@@ -11,10 +12,11 @@ class TreasuryAccountService
      * Lista as contas de tesouraria por escopo:
      * - franqueador (rede/conta-mãe): sem unit_id => contas com unit_id null;
      * - franchisee: unit_id da unidade ativa => contas daquela unidade.
+     * Cada conta recebe o saldo (entradas - saídas dos lançamentos).
      */
     public function getAll(?int $unitId = null): Collection
     {
-        return TreasuryAccount::query()
+        $accounts = TreasuryAccount::query()
             ->when(
                 $unitId !== null,
                 fn ($query) => $query->where('unit_id', $unitId),
@@ -22,6 +24,38 @@ public function getAll(?int $unitId = null): Collection
             )
             ->orderBy('created_at', 'desc')
             ->get();
+
+        $this->attachBalances($accounts);
+
+        return $accounts;
+    }
+
+    /**
+     * Calcula o saldo de cada conta em duas agregações:
+     * saldo = soma das entradas (to_account) - soma das saídas (from_account).
+     */
+    private function attachBalances(Collection $accounts): void
+    {
+        $ids = $accounts->pluck('id');
+
+        if ($ids->isEmpty()) {
+            return;
+        }
+
+        $incoming = TreasuryLaunch::whereIn('to_account_id', $ids)
+            ->groupBy('to_account_id')
+            ->selectRaw('to_account_id, SUM(amount) as total')
+            ->pluck('total', 'to_account_id');
+
+        $outgoing = TreasuryLaunch::whereIn('from_account_id', $ids)
+            ->groupBy('from_account_id')
+            ->selectRaw('from_account_id, SUM(amount) as total')
+            ->pluck('total', 'from_account_id');
+
+        foreach ($accounts as $account) {
+            $balance = (float) ($incoming[$account->id] ?? 0) - (float) ($outgoing[$account->id] ?? 0);
+            $account->setAttribute('balance', $balance);
+        }
     }
 
     public function findById(int $id): ?TreasuryAccount