mejoras
This commit is contained in:
@@ -116,7 +116,7 @@ try {
|
||||
'mime_type' => $msg['mime_type'] ?? null,
|
||||
'status' => $msg['status'] ?? 'sent',
|
||||
'created_at' => $msg['created_at'],
|
||||
'time' => date('H:i', strtotime($msg['created_at'])),
|
||||
'time' => date('g:i a', strtotime($msg['created_at'])),
|
||||
'date' => date('d/m/Y', strtotime($msg['created_at']))
|
||||
];
|
||||
}, $conversations);
|
||||
|
||||
@@ -21,6 +21,8 @@ try {
|
||||
$offset = ($page - 1) * $limit;
|
||||
|
||||
// Obtener conversaciones agregadas por usuario: último mensaje + conteo de no leídos + avatar
|
||||
$filter = isset($_GET['filter']) ? strtolower(trim($_GET['filter'])) : 'all';
|
||||
|
||||
$sql = "SELECT
|
||||
u.id AS user_id,
|
||||
COALESCE(u.name, u.phone_number) AS name,
|
||||
@@ -46,14 +48,23 @@ try {
|
||||
SELECT user_id, MAX(created_at) AS last_time FROM conversations GROUP BY user_id
|
||||
) t2 ON t1.user_id = t2.user_id AND t1.created_at = t2.last_time
|
||||
) lm ON lm.user_id = u.id
|
||||
GROUP BY u.id
|
||||
ORDER BY lm.created_at DESC
|
||||
LIMIT %d OFFSET %d";
|
||||
GROUP BY u.id";
|
||||
|
||||
// Aplicar filtro 'unread' si se solicita
|
||||
if ($filter === 'unread') {
|
||||
$sql .= " HAVING IFNULL(SUM(CASE WHEN c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0) THEN 1 ELSE 0 END), 0) > 0";
|
||||
}
|
||||
|
||||
$sql .= "\n ORDER BY lm.created_at DESC\n LIMIT %d OFFSET %d";
|
||||
|
||||
$conversations = $db->fetchAll(sprintf($sql, $limit, $offset));
|
||||
|
||||
// Conteo total de usuarios con al menos una conversación (útil para paginar)
|
||||
$totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations");
|
||||
if ($filter === 'unread') {
|
||||
$totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations c WHERE c.direction = 'incoming' AND (c.is_read IS NULL OR c.is_read = 0)");
|
||||
} else {
|
||||
$totalRow = $db->fetch("SELECT COUNT(DISTINCT user_id) AS count FROM conversations");
|
||||
}
|
||||
$total = isset($totalRow['count']) ? intval($totalRow['count']) : 0;
|
||||
|
||||
// Si no hay datos, retornar array vacío
|
||||
|
||||
+37
-26
@@ -22,12 +22,16 @@ try {
|
||||
echo json_encode(['error' => 'user_id es requerido']);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
// Paginación: limit y before (timestamp) - cargamos N mensajes anteriores a 'before'
|
||||
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
|
||||
$limit = max(1, min(200, $limit));
|
||||
$before = !empty($_GET['before']) ? $_GET['before'] : null; // expect timestamp string
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Obtener mensajes del usuario (de ambas tablas para compatibilidad)
|
||||
$conversations = $db->fetchAll(
|
||||
"SELECT
|
||||
|
||||
// Construir consulta: obtener mensajes ordenados DESC (más recientes primero) y limitar
|
||||
$sql = "SELECT
|
||||
id,
|
||||
user_id,
|
||||
COALESCE(content, message_text) as content,
|
||||
@@ -41,25 +45,29 @@ try {
|
||||
COALESCE(c.is_read, 0) as is_read
|
||||
FROM conversations c
|
||||
LEFT JOIN users u ON c.user_id = u.id
|
||||
WHERE user_id = :user_id
|
||||
UNION ALL
|
||||
SELECT
|
||||
id,
|
||||
user_id,
|
||||
message_text as content,
|
||||
NULL as message_id,
|
||||
NULL as media_url,
|
||||
NULL as user_phone,
|
||||
direction,
|
||||
message_type,
|
||||
status,
|
||||
created_at,
|
||||
1 as is_read
|
||||
FROM conversations
|
||||
WHERE user_id = :user_id
|
||||
ORDER BY created_at ASC",
|
||||
['user_id' => $userId]
|
||||
);
|
||||
WHERE user_id = :user_id";
|
||||
|
||||
$params = ['user_id' => $userId];
|
||||
if ($before) {
|
||||
$sql .= " AND created_at < :before";
|
||||
$params['before'] = $before;
|
||||
}
|
||||
|
||||
$sql .= " ORDER BY created_at DESC LIMIT " . $limit;
|
||||
|
||||
$conversations = $db->fetchAll($sql, $params);
|
||||
|
||||
// Si no hay mensajes, devolver array vacío
|
||||
if (empty($conversations)) {
|
||||
echo json_encode(['success' => true, 'data' => [], 'has_more' => false]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Queremos devolver los mensajes en orden cronológico ascendente para la UI
|
||||
$conversations = array_reverse($conversations);
|
||||
|
||||
// Indicar si hay más mensajes anteriores (si la consulta original devolvió exactamente $limit, podría haber más)
|
||||
$hasMore = count($conversations) >= 1 && count($conversations) == $limit ? true : false;
|
||||
|
||||
// Si no hay mensajes en conversations, intentar con conversations
|
||||
if (empty($conversations)) {
|
||||
@@ -115,8 +123,11 @@ try {
|
||||
'created_at' => $msg['created_at']
|
||||
];
|
||||
}, $conversations);
|
||||
|
||||
echo json_encode($conversations);
|
||||
|
||||
// earliest message timestamp (para paginación hacia atrás)
|
||||
$earliest = $conversations[0]['created_at'] ?? null;
|
||||
|
||||
echo json_encode(['success' => true, 'data' => $conversations, 'has_more' => $hasMore, 'earliest' => $earliest]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error in get_user_conversations.php: " . $e->getMessage());
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/**
|
||||
* API - Marcar conversación como NO LEÍDA (set is_read = 0)
|
||||
*/
|
||||
require_once '../config/config.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: POST');
|
||||
header('Access-Control-Allow-Headers: Content-Type');
|
||||
|
||||
try {
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$userId = isset($input['user_id']) ? intval($input['user_id']) : 0;
|
||||
if (!$userId) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'user_id is required']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
// Marcar como no leídos todos los mensajes entrantes del usuario
|
||||
$db->execute("UPDATE conversations SET is_read = 0 WHERE user_id = ? AND direction = 'incoming'", [$userId]);
|
||||
|
||||
echo json_encode(['success' => true]);
|
||||
} catch (Exception $e) {
|
||||
error_log('mark_conversation_unread failed: ' . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user