|
|
@@ -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
|