| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace App\Services;
- use App\Models\TreasuryAccount;
- use App\Models\TreasuryLaunch;
- use Illuminate\Database\Eloquent\Collection;
- 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
- {
- $accounts = TreasuryAccount::query()
- ->when(
- $unitId !== null,
- fn ($query) => $query->where('unit_id', $unitId),
- fn ($query) => $query->whereNull('unit_id'),
- )
- ->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
- {
- return TreasuryAccount::find($id);
- }
- public function create(array $data): TreasuryAccount
- {
- // Sem unit_id => conta da rede (franqueador). Com unit_id => conta da unidade (franchisee).
- $data['unit_id'] = $data['unit_id'] ?? null;
- return TreasuryAccount::create($data);
- }
- public function update(int $id, array $data): ?TreasuryAccount
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- $model->update($data);
- return $model->fresh();
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- return false;
- }
- return $model->delete();
- }
- // Add custom business logic methods here
- }
|