| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- <?php
- namespace App\Services;
- use App\Models\TreasuryAccount;
- use App\Models\TreasuryLaunch;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Facades\Auth;
- class TreasuryLaunchService
- {
- /**
- * Extrato de um banco: lançamentos onde ele é origem ou destino.
- * Sem account_id retorna o extrato consolidado (todos os lançamentos).
- */
- public function getAll(?int $accountId = null): Collection
- {
- return TreasuryLaunch::query()
- ->with('financialPlanAccount')
- ->when($accountId !== null, fn ($query) => $query->where(function ($q) use ($accountId) {
- $q->where('from_account_id', $accountId)
- ->orWhere('to_account_id', $accountId);
- }))
- ->orderBy('launch_date', 'desc')
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): ?TreasuryLaunch
- {
- return TreasuryLaunch::find($id);
- }
- public function create(array $data): TreasuryLaunch
- {
- return TreasuryLaunch::create($this->normalize($data));
- }
- public function update(int $id, array $data): ?TreasuryLaunch
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- $model->update($this->normalize($data, isCreate: false));
- return $model->fresh();
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- return false;
- }
- return $model->delete();
- }
- /**
- * Traduz a movimentação manual (account_id + transaction_type) para os campos
- * do lançamento: entrada credita o banco (to_account), saída debita (from_account).
- */
- private function normalize(array $data, bool $isCreate = true): array
- {
- $accountId = $data['account_id'] ?? null;
- unset($data['account_id']);
- if ($accountId !== null && isset($data['transaction_type'])) {
- $account = TreasuryAccount::find($accountId);
- $data['unit_id'] = $account?->unit_id;
- if ($data['transaction_type'] === 'entrada') {
- $data['to_account_id'] = $accountId;
- $data['from_account_id'] = null;
- } else {
- $data['from_account_id'] = $accountId;
- $data['to_account_id'] = null;
- }
- }
- if ($isCreate) {
- $data['user_id'] = Auth::id();
- $data['origin'] = $data['origin'] ?? 'manual';
- $data['launch_date'] = $data['launch_date'] ?? now()->toDateString();
- $data['is_reconciled'] = false;
- }
- return $data;
- }
- }
|