InteractionsModel.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. <?php
  2. namespace Models;
  3. use Libs\Database;
  4. class InteractionsModel
  5. {
  6. private \PDO $pdo;
  7. public function __construct()
  8. {
  9. $this->pdo = Database::pdo();
  10. }
  11. public function getInteractionsData(int $companyId, string $userEmail, array $queryParams): array
  12. {
  13. $filters = $this->normalizeFilters($queryParams);
  14. $myOperatorId = $this->getOperatorIdByUserEmail($companyId, $userEmail);
  15. [$whereSql, $params] = $this->buildWhereClause($companyId, $filters, $myOperatorId);
  16. $total = $this->getTotalCount($whereSql, $params);
  17. $items = $this->getItems($whereSql, $params, $filters['page'], $filters['per_page']);
  18. return [
  19. 'items' => $items,
  20. 'pagination' => [
  21. 'page' => $filters['page'],
  22. 'per_page' => $filters['per_page'],
  23. 'total' => $total,
  24. 'total_pages' => $filters['per_page'] > 0 ? (int) ceil($total / $filters['per_page']) : 0,
  25. ],
  26. ];
  27. }
  28. private function getOperatorIdByUserEmail(int $companyId, string $userEmail): ?int
  29. {
  30. $normalizedEmail = mb_strtolower(trim($userEmail));
  31. if ($normalizedEmail === '') {
  32. return null;
  33. }
  34. $stmt = $this->pdo->prepare(
  35. "SELECT operator_id
  36. FROM operator
  37. WHERE company_id = :company_id
  38. AND operator_deleted_at = 'infinity'
  39. AND lower(operator_email) = :email
  40. LIMIT 1"
  41. );
  42. $stmt->execute([
  43. 'company_id' => $companyId,
  44. 'email' => $normalizedEmail,
  45. ]);
  46. $operatorId = $stmt->fetchColumn();
  47. return $operatorId === false ? null : (int) $operatorId;
  48. }
  49. private function normalizeFilters(array $queryParams): array
  50. {
  51. $page = max(1, (int) ($queryParams['page'] ?? 1));
  52. $perPage = (int) ($queryParams['per_page'] ?? 20);
  53. $perPage = max(1, min(100, $perPage));
  54. $filter = strtolower(trim((string) ($queryParams['filter'] ?? 'all')));
  55. if (!in_array($filter, ['all', 'my_clients', 'new', 'unfinished'], true)) {
  56. $filter = 'all';
  57. }
  58. $sentiment = strtolower(trim((string) ($queryParams['sentiment'] ?? 'all')));
  59. if (!in_array($sentiment, ['all', 'positive', 'neutral', 'negative'], true)) {
  60. $sentiment = 'all';
  61. }
  62. return [
  63. 'page' => $page,
  64. 'per_page' => $perPage,
  65. 'search' => trim((string) ($queryParams['search'] ?? '')),
  66. 'filter' => $filter,
  67. 'sentiment' => $sentiment,
  68. 'operator_id' => max(0, (int) ($queryParams['operator_id'] ?? 0)),
  69. ];
  70. }
  71. private function buildWhereClause(int $companyId, array $filters, ?int $myOperatorId): array
  72. {
  73. $where = [
  74. "c.company_id = :company_id",
  75. "c.conversation_deleted_at = 'infinity'",
  76. "cl.client_deleted_at = 'infinity'",
  77. // Oculta conversas sem nenhuma mensagem visível, evitando exibir
  78. // conversas "vazias" na listagem. Verifica apenas os flags de
  79. // visibilidade da mensagem (não o sentinela de soft-delete
  80. // message_deleted_at, que o seed atual não preenche com 'infinity').
  81. "EXISTS (
  82. SELECT 1
  83. FROM message m
  84. WHERE m.conversation_id = c.conversation_id
  85. AND m.message_deleted = FALSE
  86. AND m.message_hidden = FALSE
  87. AND m.message_is_event = FALSE
  88. )",
  89. ];
  90. $params = ['company_id' => $companyId];
  91. if ($filters['search'] !== '') {
  92. $where[] = '(cl.client_name ILIKE :search OR cl.client_phone ILIKE :search OR o.operator_name ILIKE :search OR c.conversation_last_message_preview ILIKE :search)';
  93. $params['search'] = '%' . $filters['search'] . '%';
  94. }
  95. if ($filters['operator_id'] > 0) {
  96. $where[] = 'c.operator_id = :operator_id';
  97. $params['operator_id'] = $filters['operator_id'];
  98. }
  99. if ($filters['filter'] === 'unfinished') {
  100. $where[] = "lower(c.conversation_status) <> 'closed'";
  101. }
  102. if ($filters['filter'] === 'new') {
  103. $where[] = "c.conversation_started_at >= NOW() - INTERVAL '24 hours'";
  104. }
  105. if ($filters['filter'] === 'my_clients') {
  106. if ($myOperatorId !== null) {
  107. $where[] = 'c.operator_id = :my_operator_id';
  108. $params['my_operator_id'] = $myOperatorId;
  109. } else {
  110. $where[] = '1 = 0';
  111. }
  112. }
  113. if ($filters['sentiment'] !== 'all') {
  114. $where[] = $this->getSentimentWhereClause('ca', $filters['sentiment']);
  115. }
  116. return [implode("\n AND ", $where), $params];
  117. }
  118. private function getTotalCount(string $whereSql, array $params): int
  119. {
  120. $stmt = $this->pdo->prepare(
  121. "SELECT COUNT(*)
  122. FROM conversation c
  123. INNER JOIN client cl ON cl.client_id = c.client_id
  124. LEFT JOIN operator o
  125. ON o.operator_id = c.operator_id
  126. AND o.operator_deleted_at = 'infinity'
  127. LEFT JOIN conversation_analysis ca
  128. ON ca.conversation_id = c.conversation_id
  129. AND ca.conversation_analysis_deleted_at = 'infinity'
  130. WHERE {$whereSql}"
  131. );
  132. $stmt->execute($params);
  133. return (int) $stmt->fetchColumn();
  134. }
  135. private function getItems(string $whereSql, array $params, int $page, int $perPage): array
  136. {
  137. $offset = ($page - 1) * $perPage;
  138. $params['limit'] = $perPage;
  139. $params['offset'] = $offset;
  140. $stmt = $this->pdo->prepare(
  141. "SELECT
  142. c.conversation_id,
  143. cl.client_phone,
  144. o.operator_name,
  145. COALESCE(ca.conversation_analysis_sentiment, c.conversation_status) AS sentiment_label,
  146. COALESCE(ca.conversation_analysis_sentiment_score, 0) AS sentiment_score,
  147. COALESCE(ca.conversation_analysis_aspect, '') AS aspect,
  148. COALESCE(ca.conversation_analysis_sub_aspect, '') AS sub_aspect,
  149. c.conversation_last_message_at
  150. FROM conversation c
  151. INNER JOIN client cl ON cl.client_id = c.client_id
  152. LEFT JOIN operator o
  153. ON o.operator_id = c.operator_id
  154. AND o.operator_deleted_at = 'infinity'
  155. LEFT JOIN conversation_analysis ca
  156. ON ca.conversation_id = c.conversation_id
  157. AND ca.conversation_analysis_deleted_at = 'infinity'
  158. WHERE {$whereSql}
  159. ORDER BY c.conversation_last_message_at DESC, c.conversation_id DESC
  160. LIMIT :limit OFFSET :offset"
  161. );
  162. foreach ($params as $key => $value) {
  163. if (in_array($key, ['limit', 'offset', 'operator_id', 'my_operator_id', 'company_id'], true)) {
  164. $stmt->bindValue(':' . $key, (int) $value, \PDO::PARAM_INT);
  165. continue;
  166. }
  167. $stmt->bindValue(':' . $key, $value);
  168. }
  169. $stmt->execute();
  170. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
  171. return array_map(function (array $row): array {
  172. return [
  173. 'conversationId' => (int) $row['conversation_id'],
  174. 'client' => $row['client_phone'] ?? '',
  175. 'agent' => $row['operator_name'] ?? '',
  176. 'sentiment' => $this->normalizeSentimentLabel((string) ($row['sentiment_label'] ?? '')),
  177. 'score' => round((float) ($row['sentiment_score'] ?? 0), 2),
  178. 'aspect' => $row['aspect'] ?? '',
  179. 'subaspect' => $row['sub_aspect'] ?? '',
  180. 'datetime' => $this->formatIsoDateTime($row['conversation_last_message_at'] ?? null),
  181. ];
  182. }, $rows);
  183. }
  184. private function getSentimentWhereClause(string $analysisAlias, string $sentiment): string
  185. {
  186. if ($sentiment === 'positive') {
  187. return "(
  188. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) IN ('positive', 'positivo')
  189. OR {$analysisAlias}.conversation_analysis_sentiment_score >= 0.15
  190. )";
  191. }
  192. if ($sentiment === 'negative') {
  193. return "(
  194. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) IN ('negative', 'negativo')
  195. OR {$analysisAlias}.conversation_analysis_sentiment_score <= -0.15
  196. )";
  197. }
  198. return "(
  199. {$analysisAlias}.conversation_id IS NOT NULL
  200. AND lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) NOT IN ('positive', 'positivo', 'negative', 'negativo')
  201. AND {$analysisAlias}.conversation_analysis_sentiment_score > -0.15
  202. AND {$analysisAlias}.conversation_analysis_sentiment_score < 0.15
  203. )";
  204. }
  205. private function normalizeSentimentLabel(string $label): string
  206. {
  207. $normalized = trim($label);
  208. if ($normalized === '') {
  209. return 'NEUTRO';
  210. }
  211. return mb_strtoupper(str_replace('_', ' ', $normalized));
  212. }
  213. private function formatIsoDateTime(?string $dateTime): ?string
  214. {
  215. if (!$dateTime) {
  216. return null;
  217. }
  218. $timestamp = strtotime($dateTime);
  219. if ($timestamp === false) {
  220. return null;
  221. }
  222. return gmdate('Y-m-d\TH:i:s\Z', $timestamp);
  223. }
  224. }