| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace App\Services;
- use App\Models\FinancialPlanAccount;
- use Illuminate\Database\Eloquent\Collection;
- class FinancialPlanAccountService
- {
- /**
- * Plano de contas por escopo: franqueador (matriz) usa unit_id null;
- * franchisee usa o unit_id da unidade. Ordenado por código (1.1, 1.1.1, ...).
- */
- public function getAll(?int $unitId = null): Collection
- {
- return FinancialPlanAccount::query()
- ->with('parent:id,code,description,chart_type')
- ->when(
- $unitId !== null,
- // Unidade: vê o próprio plano (editável) + o plano da matriz (unit_id null, só leitura/uso).
- fn ($query) => $query->where(
- fn ($sub) => $sub->where('unit_id', $unitId)->orWhereNull('unit_id'),
- ),
- // Matriz: vê apenas o próprio plano; nunca enxerga o plano das unidades.
- fn ($query) => $query->whereNull('unit_id'),
- )
- ->orderBy('code')
- ->get();
- }
- public function findById(int $id): ?FinancialPlanAccount
- {
- return FinancialPlanAccount::find($id);
- }
- public function findByIdForUnit(int $id, int $unitId): ?FinancialPlanAccount
- {
- return FinancialPlanAccount::where('id', $id)->where('unit_id', $unitId)->first();
- }
- public function create(array $data): FinancialPlanAccount
- {
- $data['unit_id'] = $data['unit_id'] ?? null;
- $data['order'] = $data['order'] ?? $data['code'];
- $data['parent_id'] = $data['parent_id'] ?? null;
- $data = $this->applyParentChartType($data);
- return FinancialPlanAccount::create($data)->load('parent:id,code,description,chart_type');
- }
- public function update(int $id, array $data): ?FinancialPlanAccount
- {
- $model = $this->findById($id);
- if (!$model) {
- return null;
- }
- $data = $this->applyParentChartType($data);
- $model->update($data);
- return $model->fresh('parent:id,code,description,chart_type');
- }
- /**
- * Conta filha herda o chart_type do pai (a UI não envia chart_type nesse caso).
- */
- private function applyParentChartType(array $data): array
- {
- if (!empty($data['parent_id'])) {
- $parent = FinancialPlanAccount::find($data['parent_id']);
- if ($parent) {
- $data['chart_type'] = $parent->chart_type;
- }
- }
- return $data;
- }
- public function delete(int $id): bool
- {
- $model = $this->findById($id);
- if (!$model) {
- return false;
- }
- return $model->delete();
- }
- // Add custom business logic methods here
- }
|