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; } }