FinancialPlanAccountService.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Services;
  3. use App\Models\FinancialPlanAccount;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class FinancialPlanAccountService
  6. {
  7. /**
  8. * Plano de contas por escopo: franqueador (matriz) usa unit_id null;
  9. * franchisee usa o unit_id da unidade. Ordenado por código (1.1, 1.1.1, ...).
  10. */
  11. public function getAll(?int $unitId = null): Collection
  12. {
  13. return FinancialPlanAccount::query()
  14. ->with('parent:id,code,description,chart_type')
  15. ->when(
  16. $unitId !== null,
  17. // Unidade: vê o próprio plano (editável) + o plano da matriz (unit_id null, só leitura/uso).
  18. fn ($query) => $query->where(
  19. fn ($sub) => $sub->where('unit_id', $unitId)->orWhereNull('unit_id'),
  20. ),
  21. // Matriz: vê apenas o próprio plano; nunca enxerga o plano das unidades.
  22. fn ($query) => $query->whereNull('unit_id'),
  23. )
  24. ->orderBy('code')
  25. ->get();
  26. }
  27. public function findById(int $id): ?FinancialPlanAccount
  28. {
  29. return FinancialPlanAccount::find($id);
  30. }
  31. public function findByIdForUnit(int $id, int $unitId): ?FinancialPlanAccount
  32. {
  33. return FinancialPlanAccount::where('id', $id)->where('unit_id', $unitId)->first();
  34. }
  35. public function create(array $data): FinancialPlanAccount
  36. {
  37. $data['unit_id'] = $data['unit_id'] ?? null;
  38. $data['order'] = $data['order'] ?? $data['code'];
  39. $data['parent_id'] = $data['parent_id'] ?? null;
  40. $data = $this->applyParentChartType($data);
  41. return FinancialPlanAccount::create($data)->load('parent:id,code,description,chart_type');
  42. }
  43. public function update(int $id, array $data): ?FinancialPlanAccount
  44. {
  45. $model = $this->findById($id);
  46. if (!$model) {
  47. return null;
  48. }
  49. $data = $this->applyParentChartType($data);
  50. $model->update($data);
  51. return $model->fresh('parent:id,code,description,chart_type');
  52. }
  53. /**
  54. * Conta filha herda o chart_type do pai (a UI não envia chart_type nesse caso).
  55. */
  56. private function applyParentChartType(array $data): array
  57. {
  58. if (!empty($data['parent_id'])) {
  59. $parent = FinancialPlanAccount::find($data['parent_id']);
  60. if ($parent) {
  61. $data['chart_type'] = $parent->chart_type;
  62. }
  63. }
  64. return $data;
  65. }
  66. public function delete(int $id): bool
  67. {
  68. $model = $this->findById($id);
  69. if (!$model) {
  70. return false;
  71. }
  72. return $model->delete();
  73. }
  74. // Add custom business logic methods here
  75. }