FranchisorDashboardService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\ReceivableStatus;
  4. use Illuminate\Support\Carbon;
  5. use Illuminate\Support\Facades\DB;
  6. /**
  7. * Agrega os indicadores da tela inicial (Dashboard) da visão do Franqueador.
  8. *
  9. * Premissas de cálculo:
  10. * - "Matrículas por Período" = quantidade de alunos cadastrados por mês (created_at),
  11. * nos últimos 6 meses.
  12. * - "Aniversariantes do Mês" = alunos cujo mês de nascimento é o mês corrente.
  13. * - "Tickets Abertos" = chamados de suporte com status 'in_progress'.
  14. * - "Tarefas Pendentes" = cartões do Kanban que ainda não foram concluídos.
  15. * - "Receita Geral" = total cobrado das franquias (franchisee_account_receives),
  16. * pago + em aberto; a legenda traz a quantidade de pagamentos pendentes.
  17. * - "Estoque Geral de Produtos" = soma das quantidades em estoque dos produtos.
  18. *
  19. * Todas as métricas por unidade respeitam o filtro `unitIds` (vazio = rede inteira);
  20. * o estoque de produtos é do catálogo do franqueador (não filtra por unidade).
  21. */
  22. class FranchisorDashboardService
  23. {
  24. private const SETTLED = [
  25. ReceivableStatus::PAID->value,
  26. ReceivableStatus::CANCELLED->value,
  27. ];
  28. public function overview(array $unitIds = [], ?Carbon $startDate = null, ?Carbon $endDate = null): array
  29. {
  30. $startDate ??= Carbon::now()->startOfMonth();
  31. $endDate ??= Carbon::now()->endOfMonth();
  32. return [
  33. 'enrollments' => $this->enrollments($unitIds),
  34. 'birthdays' => $this->birthdays($unitIds),
  35. 'attendance' => $this->attendance($unitIds, $startDate, $endDate),
  36. 'open_tickets' => $this->openTickets($unitIds),
  37. 'tickets' => $this->tickets($unitIds),
  38. 'pending_tasks' => $this->pendingTasks($unitIds),
  39. 'general_revenue' => $this->generalRevenue($unitIds),
  40. 'product_stock' => $this->productStock(),
  41. 'products' => $this->products(),
  42. 'units_summary' => $this->unitsSummary($unitIds, $startDate, $endDate),
  43. ];
  44. }
  45. /**
  46. * Receita usa a mesma base do cálculo do TBR. O status é derivado da
  47. * existência de contrato de franquia vigente na data atual.
  48. */
  49. private function unitsSummary(array $unitIds, Carbon $startDate, Carbon $endDate): array
  50. {
  51. $units = DB::table('units')
  52. ->whereNull('deleted_at')
  53. ->when(!empty($unitIds), fn ($q) => $q->whereIn('id', $unitIds));
  54. $filteredUnitIds = (clone $units)->pluck('id')->map(fn ($id) => (int) $id)->all();
  55. $total = count($filteredUnitIds);
  56. $today = Carbon::today()->toDateString();
  57. $activeContracts = $total === 0
  58. ? 0
  59. : (int) DB::table('franchisee_contracts')
  60. ->whereNull('deleted_at')
  61. ->whereIn('unit_id', $filteredUnitIds)
  62. ->whereNotNull('start_date')
  63. ->where('start_date', '<=', $today)
  64. ->where(function ($q) use ($today) {
  65. $q->whereNull('end_date')->orWhere('end_date', '>=', $today);
  66. })
  67. ->distinct()
  68. ->count('unit_id');
  69. $receivables = $total === 0
  70. ? ['received' => 0.0, 'missing' => 0.0]
  71. : $this->unitReceivables($filteredUnitIds, $startDate, $endDate);
  72. return [
  73. 'total' => $total,
  74. 'revenue' => round($receivables['received'], 2),
  75. 'missing_receivables' => round($receivables['missing'], 2),
  76. 'active_contracts' => $activeContracts,
  77. 'without_active_contract' => max(0, $total - $activeContracts),
  78. ];
  79. }
  80. /**
  81. * Separa os recebíveis das unidades entre valores efetivamente recebidos no
  82. * período e valores com vencimento no período que ainda não foram recebidos.
  83. * Mantém a mesma composição usada pelo faturamento-base do TBR.
  84. */
  85. private function unitReceivables(array $unitIds, Carbon $startDate, Carbon $endDate): array
  86. {
  87. $start = $startDate->toDateString();
  88. $end = $endDate->toDateString();
  89. $sources = [
  90. DB::table('student_contract_installments')
  91. ->whereNull('deleted_at')
  92. ->whereIn('unit_id', $unitIds),
  93. DB::table('unit_account_receivables')
  94. ->whereNull('deleted_at')
  95. ->whereIn('unit_id', $unitIds),
  96. DB::table('franchisee_account_receives')
  97. ->whereNull('deleted_at')
  98. ->where('origin', 'manual_unit')
  99. ->whereNotNull('unit_id')
  100. ->whereIn('unit_id', $unitIds),
  101. ];
  102. $received = 0.0;
  103. $missing = 0.0;
  104. foreach ($sources as $source) {
  105. $received += (float) (clone $source)
  106. ->where('status', ReceivableStatus::PAID->value)
  107. ->whereBetween('payment_date', [$start, $end])
  108. ->sum('paid_value');
  109. $missing += (float) (clone $source)
  110. ->whereNotIn('status', self::SETTLED)
  111. ->whereBetween('due_date', [$start, $end])
  112. ->sum('value');
  113. }
  114. return ['received' => $received, 'missing' => $missing];
  115. }
  116. /**
  117. * Matrículas (alunos cadastrados) por mês nos últimos 6 meses.
  118. */
  119. private function enrollments(array $unitIds): array
  120. {
  121. $start = Carbon::now()->startOfMonth()->subMonthsNoOverflow(5);
  122. // Agrupa por ano-mês de forma portável (independente do SGBD): puxa apenas
  123. // a data de cadastro no período e conta os meses em memória.
  124. $createdAt = DB::table('students')
  125. ->whereNull('deleted_at')
  126. ->where('created_at', '>=', $start)
  127. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  128. ->pluck('created_at');
  129. $counts = [];
  130. foreach ($createdAt as $date) {
  131. $ym = Carbon::parse($date)->format('Y-m');
  132. $counts[$ym] = ($counts[$ym] ?? 0) + 1;
  133. }
  134. $labels = [];
  135. $data = [];
  136. $months = ['JAN', 'FEV', 'MAR', 'ABR', 'MAI', 'JUN', 'JUL', 'AGO', 'SET', 'OUT', 'NOV', 'DEZ'];
  137. for ($i = 0; $i < 6; $i++) {
  138. $month = $start->copy()->addMonthsNoOverflow($i);
  139. $labels[] = $months[$month->month - 1];
  140. $data[] = (int) ($counts[$month->format('Y-m')] ?? 0);
  141. }
  142. return ['labels' => $labels, 'data' => $data];
  143. }
  144. /**
  145. * Aniversariantes do mês corrente (dia + nome).
  146. */
  147. private function birthdays(array $unitIds): array
  148. {
  149. return DB::table('students')
  150. ->whereNull('deleted_at')
  151. ->whereMonth('birth_date', Carbon::now()->month)
  152. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  153. ->get(['name', 'birth_date'])
  154. ->map(fn ($s) => [
  155. 'day' => (int) Carbon::parse($s->birth_date)->day,
  156. 'name' => $s->name,
  157. ])
  158. ->sortBy('day')
  159. ->values()
  160. ->all();
  161. }
  162. private function openTickets(array $unitIds): int
  163. {
  164. return (int) $this->openTicketsQuery($unitIds)->count();
  165. }
  166. private function tickets(array $unitIds): array
  167. {
  168. return $this->openTicketsQuery($unitIds)
  169. ->orderByDesc('created_at')
  170. ->get(['id', 'severity', 'created_at', 'sector', 'status', 'title'])
  171. ->map(fn ($ticket) => [
  172. 'id' => (int) $ticket->id,
  173. 'number' => '#' . $ticket->id,
  174. 'title' => $ticket->title,
  175. 'priority' => $ticket->severity,
  176. 'date' => Carbon::parse($ticket->created_at)->format('d/m/Y'),
  177. 'sector' => $ticket->sector ?: 'Não informado',
  178. 'status' => $ticket->status,
  179. ])
  180. ->all();
  181. }
  182. private function openTicketsQuery(array $unitIds)
  183. {
  184. return DB::table('support_tickets')
  185. ->whereNull('deleted_at')
  186. ->where('status', 'in_progress')
  187. ->when(!empty($unitIds), fn ($q) => $q->where(function ($units) use ($unitIds) {
  188. $units->whereIn('applicant_unit_id', $unitIds)
  189. ->orWhereIn('target_unit_id', $unitIds)
  190. ->orWhereIn('unit_id', $unitIds);
  191. }));
  192. }
  193. private function attendance(array $unitIds, Carbon $startDate, Carbon $endDate): array
  194. {
  195. $rows = DB::table('units as u')
  196. ->leftJoin('classes as c', function ($join) use ($startDate, $endDate) {
  197. $join->on('c.unit_id', '=', 'u.id')
  198. ->whereNull('c.deleted_at')
  199. ->whereBetween('c.date_time_start', [$startDate, $endDate]);
  200. })
  201. ->leftJoin('class_attendances as ca', function ($join) {
  202. $join->on('ca.class_id', '=', 'c.id')->whereNull('ca.deleted_at');
  203. })
  204. ->whereNull('u.deleted_at')
  205. ->when(!empty($unitIds), fn ($q) => $q->whereIn('u.id', $unitIds))
  206. ->groupBy('u.id', 'u.fantasy_name')
  207. ->orderBy('u.fantasy_name')
  208. ->get([
  209. 'u.id',
  210. 'u.fantasy_name',
  211. DB::raw('COUNT(ca.id) as attendance_count'),
  212. DB::raw('SUM(CASE WHEN ca.in_class THEN 1 ELSE 0 END) as present_count'),
  213. ]);
  214. $total = (int) $rows->sum('attendance_count');
  215. $present = (int) $rows->sum('present_count');
  216. return [
  217. 'average' => $total > 0 ? round(($present / $total) * 100, 1) : 0,
  218. 'units' => $rows->map(function ($row) {
  219. $count = (int) $row->attendance_count;
  220. $average = $count > 0
  221. ? round(((int) $row->present_count / $count) * 100, 1)
  222. : 0;
  223. return [
  224. 'id' => (int) $row->id,
  225. 'unit' => $row->fantasy_name,
  226. 'frequency' => $average,
  227. 'status' => $count === 0
  228. ? 'Sem dados'
  229. : ($average >= 70 ? 'Alto' : 'Baixa'),
  230. ];
  231. })->all(),
  232. ];
  233. }
  234. private function pendingTasks(array $unitIds): int
  235. {
  236. return (int) DB::table('kanbans')
  237. ->whereNull('deleted_at')
  238. ->where('phase', '!=', 'concluido')
  239. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  240. ->count();
  241. }
  242. /**
  243. * Receita Geral = total das cobranças às franquias (pago + em aberto),
  244. * com a contagem das que ainda estão pendentes.
  245. */
  246. private function generalRevenue(array $unitIds): array
  247. {
  248. $base = DB::table('franchisee_account_receives')
  249. ->whereNull('deleted_at')
  250. ->whereNotNull('unit_id')
  251. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds));
  252. $value = (float) (clone $base)->sum('value');
  253. $pending = (int) (clone $base)
  254. ->whereNotIn('status', self::SETTLED)
  255. ->count();
  256. return ['value' => $value, 'pending_count' => $pending];
  257. }
  258. private function productStock(): int
  259. {
  260. return (int) DB::table('products')
  261. ->whereNull('deleted_at')
  262. ->sum('quantity');
  263. }
  264. private function products(): array
  265. {
  266. return DB::table('products')
  267. ->whereNull('deleted_at')
  268. ->orderBy('name')
  269. ->get(['id', 'name', 'quantity'])
  270. ->map(function ($product) {
  271. $quantity = (int) $product->quantity;
  272. return [
  273. 'id' => (int) $product->id,
  274. 'name' => $product->name,
  275. 'quantity' => $quantity,
  276. 'status' => $quantity <= 15
  277. ? 'Baixo'
  278. : ($quantity <= 30 ? 'Limitado' : 'Alto'),
  279. ];
  280. })->all();
  281. }
  282. }