DashboardOverviewController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. <?php
  2. namespace Controllers;
  3. use Libs\Database;
  4. use Libs\ResponseLib;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class DashboardOverviewController
  7. {
  8. private \PDO $pdo;
  9. public function __construct()
  10. {
  11. $this->pdo = Database::pdo();
  12. }
  13. public function __invoke(ServerRequestInterface $request)
  14. {
  15. $userId = (int) ($request->getAttribute('user_id') ?? 0);
  16. if ($userId <= 0) {
  17. return ResponseLib::sendFail('Unauthorized: Missing authenticated user', [], 'E_VALIDATE')->withStatus(401);
  18. }
  19. try {
  20. $companyId = $this->getCompanyIdByUserId($userId);
  21. if ($companyId === null) {
  22. return ResponseLib::sendFail('User not found', [], 'E_NOT_FOUND')->withStatus(404);
  23. }
  24. $filters = $this->normalizeFilters($request->getQueryParams());
  25. $range = $this->resolveDateRange($filters['period']);
  26. return ResponseLib::sendOk([
  27. 'kpis' => $this->getKpis($companyId, $filters, $range),
  28. 'priorityQueue' => $this->getPriorityQueue($companyId, $filters, $range),
  29. 'radarData' => $this->getRadarData($companyId, $range),
  30. 'volumeData' => $this->getVolumeData($companyId, $range),
  31. 'aspectsData' => $this->getAspectsData($companyId, $filters, $range),
  32. 'aspectsDrilldown' => $this->getAspectsDrilldown($companyId, $filters, $range),
  33. ]);
  34. } catch (\Throwable $e) {
  35. return ResponseLib::sendFail('Failed to load dashboard overview', [], 'E_GENERIC')->withStatus(500);
  36. }
  37. }
  38. private function getCompanyIdByUserId(int $userId): ?int
  39. {
  40. $stmt = $this->pdo->prepare(
  41. "SELECT company_id
  42. FROM \"user\"
  43. WHERE user_id = :user_id
  44. AND user_deleted_at = 'infinity'
  45. LIMIT 1"
  46. );
  47. $stmt->execute(['user_id' => $userId]);
  48. $companyId = $stmt->fetchColumn();
  49. return $companyId === false ? null : (int) $companyId;
  50. }
  51. private function normalizeFilters(array $queryParams): array
  52. {
  53. $period = strtolower((string) ($queryParams['period'] ?? 'week'));
  54. $unit = strtolower((string) ($queryParams['unit'] ?? 'all'));
  55. $area = strtolower((string) ($queryParams['area'] ?? 'all'));
  56. $sentiment = strtolower((string) ($queryParams['sentiment'] ?? 'all'));
  57. $volumeView = strtolower((string) ($queryParams['volume_view'] ?? 'day'));
  58. if (!in_array($period, ['today', 'yesterday', 'week'], true)) {
  59. $period = 'week';
  60. }
  61. if (!in_array($sentiment, ['all', 'positive', 'neutral', 'negative'], true)) {
  62. $sentiment = 'all';
  63. }
  64. if (!in_array($volumeView, ['hour', 'day'], true)) {
  65. $volumeView = 'day';
  66. }
  67. return [
  68. 'period' => $period,
  69. 'unit' => $unit,
  70. 'area' => $area,
  71. 'sentiment' => $sentiment,
  72. 'volume_view' => $volumeView,
  73. ];
  74. }
  75. private function resolveDateRange(string $period): array
  76. {
  77. $today = new \DateTimeImmutable('today');
  78. if ($period === 'today') {
  79. $start = $today;
  80. $end = $today;
  81. } elseif ($period === 'yesterday') {
  82. $start = $today->modify('-1 day');
  83. $end = $start;
  84. } else {
  85. $start = $today->modify('-6 days');
  86. $end = $today;
  87. }
  88. return [
  89. 'start_date' => $start->format('Y-m-d'),
  90. 'end_date' => $end->format('Y-m-d'),
  91. 'start_datetime' => $start->format('Y-m-d 00:00:00'),
  92. 'end_exclusive_datetime' => $end->modify('+1 day')->format('Y-m-d 00:00:00'),
  93. ];
  94. }
  95. private function getKpis(int $companyId, array $filters, array $range): array
  96. {
  97. $registeredStmt = $this->pdo->prepare(
  98. "SELECT COUNT(*)
  99. FROM client
  100. WHERE company_id = :company_id
  101. AND client_deleted_at = 'infinity'
  102. AND client_is_registered = TRUE"
  103. );
  104. $registeredStmt->execute(['company_id' => $companyId]);
  105. $unregisteredStmt = $this->pdo->prepare(
  106. "SELECT COUNT(*)
  107. FROM client
  108. WHERE company_id = :company_id
  109. AND client_deleted_at = 'infinity'
  110. AND client_is_registered = FALSE"
  111. );
  112. $unregisteredStmt->execute(['company_id' => $companyId]);
  113. $activeOperatorsSql = "SELECT COUNT(*)
  114. FROM operator
  115. WHERE company_id = :company_id
  116. AND operator_deleted_at = 'infinity'
  117. AND lower(operator_status) <> 'inativo'";
  118. $activeOperatorsParams = ['company_id' => $companyId];
  119. if ($filters['area'] !== 'all') {
  120. $activeOperatorsSql .= " AND lower(operator_department) = :area";
  121. $activeOperatorsParams['area'] = $filters['area'];
  122. }
  123. $activeOperatorsStmt = $this->pdo->prepare($activeOperatorsSql);
  124. $activeOperatorsStmt->execute($activeOperatorsParams);
  125. $conversationSql = "SELECT
  126. COUNT(DISTINCT c.conversation_id) AS total_conversations,
  127. COALESCE(AVG(ca.conversation_analysis_sentiment_score), 0) AS general_sentiment_score
  128. FROM conversation c
  129. INNER JOIN operator o ON o.operator_id = c.operator_id
  130. LEFT JOIN conversation_analysis ca
  131. ON ca.conversation_id = c.conversation_id
  132. AND ca.conversation_analysis_deleted_at = 'infinity'
  133. WHERE c.company_id = :company_id
  134. AND c.conversation_deleted_at = 'infinity'
  135. AND c.conversation_started_at >= :start_datetime
  136. AND c.conversation_started_at < :end_exclusive_datetime
  137. AND o.operator_deleted_at = 'infinity'";
  138. $conversationParams = [
  139. 'company_id' => $companyId,
  140. 'start_datetime' => $range['start_datetime'],
  141. 'end_exclusive_datetime' => $range['end_exclusive_datetime'],
  142. ];
  143. if ($filters['area'] !== 'all') {
  144. $conversationSql .= " AND lower(o.operator_department) = :area";
  145. $conversationParams['area'] = $filters['area'];
  146. }
  147. if ($filters['sentiment'] !== 'all') {
  148. $conversationSql .= ' AND ' . $this->getSentimentWhereClause('ca', $filters['sentiment']);
  149. }
  150. $conversationStmt = $this->pdo->prepare($conversationSql);
  151. $conversationStmt->execute($conversationParams);
  152. $conversationMetrics = $conversationStmt->fetch(\PDO::FETCH_ASSOC) ?: [];
  153. return [
  154. 'registeredUsers' => (int) $registeredStmt->fetchColumn(),
  155. 'activeAgents' => (int) $activeOperatorsStmt->fetchColumn(),
  156. 'totalConversations' => (int) ($conversationMetrics['total_conversations'] ?? 0),
  157. 'generalSentimentScore' => round((float) ($conversationMetrics['general_sentiment_score'] ?? 0), 2),
  158. 'unregisteredUsers' => (int) $unregisteredStmt->fetchColumn(),
  159. ];
  160. }
  161. private function getPriorityQueue(int $companyId, array $filters, array $range): array
  162. {
  163. $sql = "SELECT
  164. c.conversation_id AS id,
  165. cl.client_name AS customer_name,
  166. cl.client_segment AS segment,
  167. COALESCE(NULLIF(a.alert_title, ''), ca.conversation_analysis_sentiment, c.conversation_status) AS status_label,
  168. c.conversation_sla_deadline,
  169. c.conversation_last_message_at,
  170. o.operator_name AS seller_name,
  171. c.conversation_last_message_preview AS last_message,
  172. COALESCE(NULLIF(a.alert_description, ''), CONCAT(ca.conversation_analysis_aspect, ' — ', ca.conversation_analysis_sub_aspect), c.conversation_last_message_preview) AS motive,
  173. c.conversation_impact_value,
  174. c.conversation_ticket_value,
  175. c.conversation_conversion_chance,
  176. c.conversation_optimum_window,
  177. c.client_id,
  178. c.operator_id
  179. FROM conversation c
  180. INNER JOIN client cl ON cl.client_id = c.client_id AND cl.client_deleted_at = 'infinity'
  181. INNER JOIN operator o ON o.operator_id = c.operator_id AND o.operator_deleted_at = 'infinity'
  182. LEFT JOIN conversation_analysis ca
  183. ON ca.conversation_id = c.conversation_id
  184. AND ca.conversation_analysis_deleted_at = 'infinity'
  185. LEFT JOIN LATERAL (
  186. SELECT alert_title, alert_description
  187. FROM alert
  188. WHERE company_id = c.company_id
  189. AND client_id = c.client_id
  190. AND alert_deleted_at = 'infinity'
  191. AND alert_is_resolved = FALSE
  192. ORDER BY alert_created_at DESC
  193. LIMIT 1
  194. ) a ON TRUE
  195. WHERE c.company_id = :company_id
  196. AND c.conversation_deleted_at = 'infinity'
  197. AND c.conversation_started_at >= :start_datetime
  198. AND c.conversation_started_at < :end_exclusive_datetime";
  199. $params = [
  200. 'company_id' => $companyId,
  201. 'start_datetime' => $range['start_datetime'],
  202. 'end_exclusive_datetime' => $range['end_exclusive_datetime'],
  203. ];
  204. if ($filters['area'] !== 'all') {
  205. $sql .= " AND lower(o.operator_department) = :area";
  206. $params['area'] = $filters['area'];
  207. }
  208. if ($filters['sentiment'] !== 'all') {
  209. $sql .= ' AND ' . $this->getSentimentWhereClause('ca', $filters['sentiment']);
  210. }
  211. $sql .= " ORDER BY (c.conversation_sla_deadline < NOW()) DESC,
  212. ROUND(c.conversation_impact_value * (c.conversation_conversion_chance / 100.0)) DESC,
  213. c.conversation_last_message_at ASC
  214. LIMIT 10";
  215. $stmt = $this->pdo->prepare($sql);
  216. $stmt->execute($params);
  217. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
  218. return array_map(function (array $row): array {
  219. $impact = (float) ($row['conversation_impact_value'] ?? 0);
  220. $chance = (int) ($row['conversation_conversion_chance'] ?? 0);
  221. return [
  222. 'id' => (int) $row['id'],
  223. 'customerName' => $row['customer_name'] ?? '',
  224. 'segment' => $row['segment'] ?? '',
  225. 'status' => $this->normalizeStatusLabel((string) ($row['status_label'] ?? 'open')),
  226. 'slaStatus' => $this->formatSlaStatus($row['conversation_sla_deadline'] ?? null),
  227. 'timeAgo' => $this->formatRelativeTime($row['conversation_last_message_at'] ?? null),
  228. 'sellerName' => $row['seller_name'] ?? '',
  229. 'lastMessage' => $row['last_message'] ?? '',
  230. 'motive' => $row['motive'] ?? '',
  231. 'impact' => (int) round($impact),
  232. 'ticket' => (int) round((float) ($row['conversation_ticket_value'] ?? 0)),
  233. 'chance' => $chance,
  234. 'optimumWindow' => $row['conversation_optimum_window'] ?? '',
  235. 'score' => (int) round($impact * ($chance / 100)),
  236. 'conversationId' => (int) $row['id'],
  237. 'clientId' => (int) ($row['client_id'] ?? 0),
  238. 'operatorId' => (int) ($row['operator_id'] ?? 0),
  239. ];
  240. }, $rows);
  241. }
  242. private function getRadarData(int $companyId, array $range): array
  243. {
  244. $stmt = $this->pdo->prepare(
  245. "SELECT
  246. emotion_confidence,
  247. emotion_happiness,
  248. emotion_anticipation,
  249. emotion_fear,
  250. emotion_sadness,
  251. emotion_anger
  252. FROM emotion_snapshot
  253. WHERE company_id = :company_id
  254. AND emotion_snapshot_date BETWEEN :start_date AND :end_date
  255. ORDER BY emotion_snapshot_date DESC
  256. LIMIT 1"
  257. );
  258. $stmt->execute([
  259. 'company_id' => $companyId,
  260. 'start_date' => $range['start_date'],
  261. 'end_date' => $range['end_date'],
  262. ]);
  263. $row = $stmt->fetch(\PDO::FETCH_ASSOC) ?: [];
  264. return [
  265. ['name' => 'Confiança', 'value' => (float) ($row['emotion_confidence'] ?? 0)],
  266. ['name' => 'Alegria', 'value' => (float) ($row['emotion_happiness'] ?? 0)],
  267. ['name' => 'Antecipação', 'value' => (float) ($row['emotion_anticipation'] ?? 0)],
  268. ['name' => 'Medo', 'value' => (float) ($row['emotion_fear'] ?? 0)],
  269. ['name' => 'Tristeza', 'value' => (float) ($row['emotion_sadness'] ?? 0)],
  270. ['name' => 'Raiva', 'value' => (float) ($row['emotion_anger'] ?? 0)],
  271. ];
  272. }
  273. private function getVolumeData(int $companyId, array $range): array
  274. {
  275. $stmt = $this->pdo->prepare(
  276. "SELECT
  277. volume_snapshot_date,
  278. lower(volume_channel) AS volume_channel,
  279. SUM(volume_message_count) AS message_count
  280. FROM volume_snapshot
  281. WHERE company_id = :company_id
  282. AND volume_snapshot_date BETWEEN :start_date AND :end_date
  283. GROUP BY volume_snapshot_date, lower(volume_channel)
  284. ORDER BY volume_snapshot_date ASC, lower(volume_channel) ASC"
  285. );
  286. $stmt->execute([
  287. 'company_id' => $companyId,
  288. 'start_date' => $range['start_date'],
  289. 'end_date' => $range['end_date'],
  290. ]);
  291. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
  292. $grouped = [];
  293. foreach ($rows as $row) {
  294. $date = $this->formatSnapshotDate((string) $row['volume_snapshot_date']);
  295. if (!isset($grouped[$date])) {
  296. $grouped[$date] = ['date' => $date];
  297. }
  298. $grouped[$date][$row['volume_channel']] = (int) ($row['message_count'] ?? 0);
  299. }
  300. return array_values($grouped);
  301. }
  302. private function getAspectsData(int $companyId, array $filters, array $range): array
  303. {
  304. $sql = "SELECT
  305. aspect_feedback_aspect AS aspect,
  306. SUM(CASE WHEN " . $this->getAspectSentimentCase('positive') . " THEN 1 ELSE 0 END) AS positive_count,
  307. SUM(CASE WHEN " . $this->getAspectSentimentCase('neutral') . " THEN 1 ELSE 0 END) AS neutral_count,
  308. SUM(CASE WHEN " . $this->getAspectSentimentCase('negative') . " THEN 1 ELSE 0 END) AS negative_count
  309. FROM aspect_feedback
  310. WHERE company_id = :company_id
  311. AND aspect_feedback_deleted_at = 'infinity'
  312. AND aspect_feedback_created_at >= :start_datetime
  313. AND aspect_feedback_created_at < :end_exclusive_datetime";
  314. $params = [
  315. 'company_id' => $companyId,
  316. 'start_datetime' => $range['start_datetime'],
  317. 'end_exclusive_datetime' => $range['end_exclusive_datetime'],
  318. ];
  319. if ($filters['sentiment'] !== 'all') {
  320. $sql .= ' AND ' . $this->getAspectFilterClause($filters['sentiment']);
  321. }
  322. $sql .= ' GROUP BY aspect_feedback_aspect ORDER BY aspect_feedback_aspect ASC';
  323. $stmt = $this->pdo->prepare($sql);
  324. $stmt->execute($params);
  325. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
  326. return array_map(static function (array $row): array {
  327. return [
  328. 'aspect' => $row['aspect'],
  329. 'positive' => (int) ($row['positive_count'] ?? 0),
  330. 'neutral' => (int) ($row['neutral_count'] ?? 0),
  331. 'negative' => (int) ($row['negative_count'] ?? 0),
  332. ];
  333. }, $rows);
  334. }
  335. private function getAspectsDrilldown(int $companyId, array $filters, array $range): array
  336. {
  337. $sql = "SELECT
  338. aspect_feedback_aspect AS aspect,
  339. aspect_feedback_sentiment AS sentiment,
  340. aspect_feedback_text AS label,
  341. COUNT(*) AS total
  342. FROM aspect_feedback
  343. WHERE company_id = :company_id
  344. AND aspect_feedback_deleted_at = 'infinity'
  345. AND aspect_feedback_created_at >= :start_datetime
  346. AND aspect_feedback_created_at < :end_exclusive_datetime";
  347. $params = [
  348. 'company_id' => $companyId,
  349. 'start_datetime' => $range['start_datetime'],
  350. 'end_exclusive_datetime' => $range['end_exclusive_datetime'],
  351. ];
  352. if ($filters['sentiment'] !== 'all') {
  353. $sql .= ' AND ' . $this->getAspectFilterClause($filters['sentiment']);
  354. }
  355. $sql .= ' GROUP BY aspect_feedback_aspect, aspect_feedback_sentiment, aspect_feedback_text
  356. ORDER BY aspect_feedback_aspect ASC, COUNT(*) DESC, aspect_feedback_text ASC';
  357. $stmt = $this->pdo->prepare($sql);
  358. $stmt->execute($params);
  359. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
  360. $drilldown = [];
  361. foreach ($rows as $row) {
  362. $aspect = $row['aspect'];
  363. $sentiment = $this->normalizeAspectSentiment((string) ($row['sentiment'] ?? 'neutral'));
  364. if (!isset($drilldown[$aspect])) {
  365. $drilldown[$aspect] = [
  366. 'positive' => [],
  367. 'neutral' => [],
  368. 'negative' => [],
  369. ];
  370. }
  371. if (count($drilldown[$aspect][$sentiment]) >= 5) {
  372. continue;
  373. }
  374. $drilldown[$aspect][$sentiment][] = [
  375. 'label' => $row['label'],
  376. 'value' => (int) ($row['total'] ?? 0),
  377. ];
  378. }
  379. return $drilldown;
  380. }
  381. private function getSentimentWhereClause(string $analysisAlias, string $sentiment): string
  382. {
  383. if ($sentiment === 'positive') {
  384. return "(
  385. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) IN ('positive', 'positivo')
  386. OR {$analysisAlias}.conversation_analysis_sentiment_score >= 0.15
  387. )";
  388. }
  389. if ($sentiment === 'negative') {
  390. return "(
  391. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) IN ('negative', 'negativo')
  392. OR {$analysisAlias}.conversation_analysis_sentiment_score <= -0.15
  393. )";
  394. }
  395. return "(
  396. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) NOT IN ('positive', 'positivo', 'negative', 'negativo')
  397. AND {$analysisAlias}.conversation_analysis_sentiment_score > -0.15
  398. AND {$analysisAlias}.conversation_analysis_sentiment_score < 0.15
  399. )";
  400. }
  401. private function getAspectSentimentCase(string $sentiment): string
  402. {
  403. if ($sentiment === 'positive') {
  404. return "lower(aspect_feedback_sentiment) IN ('positive', 'positivo')";
  405. }
  406. if ($sentiment === 'negative') {
  407. return "lower(aspect_feedback_sentiment) IN ('negative', 'negativo')";
  408. }
  409. return "lower(aspect_feedback_sentiment) NOT IN ('positive', 'positivo', 'negative', 'negativo')";
  410. }
  411. private function getAspectFilterClause(string $sentiment): string
  412. {
  413. return $this->getAspectSentimentCase($sentiment);
  414. }
  415. private function normalizeAspectSentiment(string $sentiment): string
  416. {
  417. $normalized = strtolower(trim($sentiment));
  418. if (in_array($normalized, ['positive', 'positivo'], true)) {
  419. return 'positive';
  420. }
  421. if (in_array($normalized, ['negative', 'negativo'], true)) {
  422. return 'negative';
  423. }
  424. return 'neutral';
  425. }
  426. private function normalizeStatusLabel(string $status): string
  427. {
  428. $normalized = trim($status);
  429. if ($normalized === '') {
  430. return 'SEM STATUS';
  431. }
  432. return mb_strtoupper(str_replace('_', ' ', $normalized));
  433. }
  434. private function formatSlaStatus(?string $deadline): string
  435. {
  436. if (!$deadline) {
  437. return 'Sem SLA';
  438. }
  439. $deadlineTime = strtotime($deadline);
  440. if ($deadlineTime === false) {
  441. return 'Sem SLA';
  442. }
  443. $delta = $deadlineTime - time();
  444. if ($delta >= 0) {
  445. return 'Dentro do SLA';
  446. }
  447. $overdue = abs($delta);
  448. if ($overdue >= 86400) {
  449. return 'SLA ' . floor($overdue / 86400) . 'd estourado';
  450. }
  451. if ($overdue >= 3600) {
  452. return 'SLA ' . floor($overdue / 3600) . 'h estourado';
  453. }
  454. return 'SLA ' . max(1, floor($overdue / 60)) . 'm estourado';
  455. }
  456. private function formatRelativeTime(?string $dateTime): string
  457. {
  458. if (!$dateTime) {
  459. return 'agora';
  460. }
  461. $timestamp = strtotime($dateTime);
  462. if ($timestamp === false) {
  463. return 'agora';
  464. }
  465. $delta = max(0, time() - $timestamp);
  466. if ($delta >= 86400) {
  467. return 'há ' . floor($delta / 86400) . 'd';
  468. }
  469. if ($delta >= 3600) {
  470. return 'há ' . floor($delta / 3600) . 'h';
  471. }
  472. if ($delta >= 60) {
  473. return 'há ' . floor($delta / 60) . 'm';
  474. }
  475. return 'agora';
  476. }
  477. private function formatSnapshotDate(string $date): string
  478. {
  479. return $date . 'T00:00:00Z';
  480. }
  481. }