InteractionsModel.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. "o.operator_deleted_at = 'infinity'",
  78. ];
  79. $params = ['company_id' => $companyId];
  80. if ($filters['search'] !== '') {
  81. $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)';
  82. $params['search'] = '%' . $filters['search'] . '%';
  83. }
  84. if ($filters['operator_id'] > 0) {
  85. $where[] = 'c.operator_id = :operator_id';
  86. $params['operator_id'] = $filters['operator_id'];
  87. }
  88. if ($filters['filter'] === 'unfinished') {
  89. $where[] = "lower(c.conversation_status) <> 'closed'";
  90. }
  91. if ($filters['filter'] === 'new') {
  92. $where[] = "c.conversation_started_at >= NOW() - INTERVAL '24 hours'";
  93. }
  94. if ($filters['filter'] === 'my_clients') {
  95. if ($myOperatorId !== null) {
  96. $where[] = 'c.operator_id = :my_operator_id';
  97. $params['my_operator_id'] = $myOperatorId;
  98. } else {
  99. $where[] = '1 = 0';
  100. }
  101. }
  102. if ($filters['sentiment'] !== 'all') {
  103. $where[] = $this->getSentimentWhereClause('ca', $filters['sentiment']);
  104. }
  105. return [implode("\n AND ", $where), $params];
  106. }
  107. private function getTotalCount(string $whereSql, array $params): int
  108. {
  109. $stmt = $this->pdo->prepare(
  110. "SELECT COUNT(*)
  111. FROM conversation c
  112. INNER JOIN client cl ON cl.client_id = c.client_id
  113. INNER JOIN operator o ON o.operator_id = c.operator_id
  114. LEFT JOIN conversation_analysis ca
  115. ON ca.conversation_id = c.conversation_id
  116. AND ca.conversation_analysis_deleted_at = 'infinity'
  117. WHERE {$whereSql}"
  118. );
  119. $stmt->execute($params);
  120. return (int) $stmt->fetchColumn();
  121. }
  122. private function getItems(string $whereSql, array $params, int $page, int $perPage): array
  123. {
  124. $offset = ($page - 1) * $perPage;
  125. $params['limit'] = $perPage;
  126. $params['offset'] = $offset;
  127. $stmt = $this->pdo->prepare(
  128. "SELECT
  129. c.conversation_id,
  130. cl.client_phone,
  131. o.operator_name,
  132. COALESCE(ca.conversation_analysis_sentiment, c.conversation_status) AS sentiment_label,
  133. COALESCE(ca.conversation_analysis_sentiment_score, 0) AS sentiment_score,
  134. COALESCE(ca.conversation_analysis_aspect, '') AS aspect,
  135. COALESCE(ca.conversation_analysis_sub_aspect, '') AS sub_aspect,
  136. c.conversation_last_message_at
  137. FROM conversation c
  138. INNER JOIN client cl ON cl.client_id = c.client_id
  139. INNER JOIN operator o ON o.operator_id = c.operator_id
  140. LEFT JOIN conversation_analysis ca
  141. ON ca.conversation_id = c.conversation_id
  142. AND ca.conversation_analysis_deleted_at = 'infinity'
  143. WHERE {$whereSql}
  144. ORDER BY c.conversation_last_message_at DESC, c.conversation_id DESC
  145. LIMIT :limit OFFSET :offset"
  146. );
  147. foreach ($params as $key => $value) {
  148. if (in_array($key, ['limit', 'offset', 'operator_id', 'my_operator_id', 'company_id'], true)) {
  149. $stmt->bindValue(':' . $key, (int) $value, \PDO::PARAM_INT);
  150. continue;
  151. }
  152. $stmt->bindValue(':' . $key, $value);
  153. }
  154. $stmt->execute();
  155. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
  156. return array_map(function (array $row): array {
  157. return [
  158. 'conversationId' => (int) $row['conversation_id'],
  159. 'client' => $row['client_phone'] ?? '',
  160. 'agent' => $row['operator_name'] ?? '',
  161. 'sentiment' => $this->normalizeSentimentLabel((string) ($row['sentiment_label'] ?? '')),
  162. 'score' => round((float) ($row['sentiment_score'] ?? 0), 2),
  163. 'aspect' => $row['aspect'] ?? '',
  164. 'subaspect' => $row['sub_aspect'] ?? '',
  165. 'datetime' => $this->formatIsoDateTime($row['conversation_last_message_at'] ?? null),
  166. ];
  167. }, $rows);
  168. }
  169. private function getSentimentWhereClause(string $analysisAlias, string $sentiment): string
  170. {
  171. if ($sentiment === 'positive') {
  172. return "(
  173. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) IN ('positive', 'positivo')
  174. OR {$analysisAlias}.conversation_analysis_sentiment_score >= 0.15
  175. )";
  176. }
  177. if ($sentiment === 'negative') {
  178. return "(
  179. lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) IN ('negative', 'negativo')
  180. OR {$analysisAlias}.conversation_analysis_sentiment_score <= -0.15
  181. )";
  182. }
  183. return "(
  184. {$analysisAlias}.conversation_id IS NOT NULL
  185. AND lower(COALESCE({$analysisAlias}.conversation_analysis_sentiment, '')) NOT IN ('positive', 'positivo', 'negative', 'negativo')
  186. AND {$analysisAlias}.conversation_analysis_sentiment_score > -0.15
  187. AND {$analysisAlias}.conversation_analysis_sentiment_score < 0.15
  188. )";
  189. }
  190. private function normalizeSentimentLabel(string $label): string
  191. {
  192. $normalized = trim($label);
  193. if ($normalized === '') {
  194. return 'NEUTRO';
  195. }
  196. return mb_strtoupper(str_replace('_', ' ', $normalized));
  197. }
  198. private function formatIsoDateTime(?string $dateTime): ?string
  199. {
  200. if (!$dateTime) {
  201. return null;
  202. }
  203. $timestamp = strtotime($dateTime);
  204. if ($timestamp === false) {
  205. return null;
  206. }
  207. return gmdate('Y-m-d\TH:i:s\Z', $timestamp);
  208. }
  209. }