DashboardOverviewModel.php 21 KB

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