| 3719 |
stevensc |
1 |
import React, { useEffect, useState } from 'react';
|
|
|
2 |
import { useParams } from 'react-router-dom';
|
|
|
3 |
|
|
|
4 |
import { useAlert, useAlertModal, useApi, useModal } from '@shared/hooks';
|
|
|
5 |
import {
|
|
|
6 |
getConversations,
|
|
|
7 |
deleteConversation as deleteConversationService
|
|
|
8 |
} from '@inmail/services';
|
|
|
9 |
import { SearchUserModal } from '@shared/components';
|
|
|
10 |
|
|
|
11 |
export function useConversations() {
|
|
|
12 |
const { uuid } = useParams();
|
|
|
13 |
const [conversations, setConversations] = useState([]);
|
|
|
14 |
const [currentConversation, setCurrentConversation] = useState(null);
|
|
|
15 |
const [deletedUrl, setDeletedUrl] = useState(null);
|
|
|
16 |
|
|
|
17 |
const { showSuccess, showError } = useAlert();
|
|
|
18 |
const { showAlert, closeAlert } = useAlertModal();
|
|
|
19 |
const { showModal, closeModal } = useModal();
|
|
|
20 |
|
|
|
21 |
const { loading, execute } = useApi(getConversations, {
|
|
|
22 |
onSuccess: (data) => {
|
|
|
23 |
setConversations(data);
|
|
|
24 |
},
|
|
|
25 |
onError: (error) => {
|
|
|
26 |
showError(error.message);
|
|
|
27 |
}
|
|
|
28 |
});
|
|
|
29 |
|
|
|
30 |
const { execute: executeDeleteConversation } = useApi(deleteConversationService, {
|
|
|
31 |
onSuccess: (data) => {
|
|
|
32 |
showSuccess(data);
|
|
|
33 |
setConversations((prev) => prev.filter((c) => c.delete_url !== deletedUrl));
|
|
|
34 |
setCurrentConversation(null);
|
|
|
35 |
setDeletedUrl(null);
|
|
|
36 |
closeAlert();
|
|
|
37 |
},
|
|
|
38 |
onError: (error) => {
|
|
|
39 |
showError(error.message);
|
|
|
40 |
setDeletedUrl(null);
|
|
|
41 |
}
|
|
|
42 |
});
|
|
|
43 |
|
|
|
44 |
const deleteConversation = (url) => {
|
|
|
45 |
setDeletedUrl(url);
|
|
|
46 |
showAlert({
|
|
|
47 |
title: 'Borrar conversación',
|
|
|
48 |
message: '¿Estás seguro de querer borrar esta conversación?',
|
|
|
49 |
onConfirm: () => executeDeleteConversation(url),
|
|
|
50 |
onCancel: closeAlert
|
|
|
51 |
});
|
|
|
52 |
};
|
|
|
53 |
|
|
|
54 |
const startConversation = () => {
|
|
|
55 |
showModal(
|
|
|
56 |
'Iniciar conversación',
|
|
|
57 |
<SearchUserModal
|
|
|
58 |
onSelect={(user) => {
|
|
|
59 |
setCurrentConversation(user);
|
|
|
60 |
setConversations((prev) => [user, ...prev]);
|
|
|
61 |
closeModal();
|
|
|
62 |
}}
|
|
|
63 |
/>
|
|
|
64 |
);
|
|
|
65 |
};
|
|
|
66 |
|
|
|
67 |
useEffect(() => {
|
|
|
68 |
if (!uuid) return;
|
|
|
69 |
const conversation = conversations.find((c) => c.uuid === uuid);
|
|
|
70 |
setCurrentConversation(conversation);
|
|
|
71 |
}, [uuid]);
|
|
|
72 |
|
|
|
73 |
useEffect(() => {
|
|
|
74 |
execute(uuid ? `/inmail/user/${uuid}` : '/inmail');
|
|
|
75 |
}, [uuid]);
|
|
|
76 |
|
|
|
77 |
return {
|
|
|
78 |
conversations,
|
|
|
79 |
loading,
|
|
|
80 |
currentConversation,
|
|
|
81 |
setCurrentConversation,
|
|
|
82 |
deleteConversation,
|
|
|
83 |
startConversation
|
|
|
84 |
};
|
|
|
85 |
}
|