Skip to content

Commit

Permalink
Refactor Webphone.vue and ConversationCard.vue components
Browse files Browse the repository at this point in the history
- Fix typo in listernSockets method
- Add error handling in startCall method
- Update active call status in outcomingCall method
- Improve handling of status messages in ConversationCard.vue component
- Update translations in webphone.json file in en, es, pt, and pt_BR
- Improve connection to Wavoip in webphone.js file
  • Loading branch information
nestordavalos committed Sep 22, 2024
1 parent 0c1eafd commit 22719fc
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export default {
callInfo(newCallInfo) {
let instances = this.$store.state.webphone.wavoip;
Object.keys(instances).forEach(token => {
this.listernSockets(token, instances[token].whatsapp_instance);
this.listenSockets(token, instances[token].whatsapp_instance);
});
const status = newCallInfo.status;
Expand Down Expand Up @@ -161,6 +161,10 @@ export default {
clearInterval(this.timer);
}
const startDate = this.$store.state.webphone.call.active_start_date;
if (!startDate) {
console.error('startDate is undefined');
return;
}
this.timer = setInterval(() => {
const now = new Date();
this.elapsedTime = Math.floor((now - startDate) / 1000);
Expand All @@ -187,11 +191,17 @@ export default {
},
mute() {
this.isMuted = true;
if (this.localStream && this.localStream.getAudioTracks().length > 0) {
this.localStream.getAudioTracks()[0].enabled = false;
}
},
unMute() {
this.isMuted = false;
if (this.localStream && this.localStream.getAudioTracks().length > 0) {
this.localStream.getAudioTracks()[0].enabled = true;
}
},
listernSockets(token, whatsapp_instance) {
listenSockets(token, whatsapp_instance) {
whatsapp_instance.socket.off('signaling');
whatsapp_instance.socket.on('signaling', (...args) => {
Expand All @@ -213,25 +223,11 @@ export default {
contact_name: name,
profile_picture: profile_picture,
});
} else if (data?.tag === 'terminate') {
setTimeout(() => {
this.$store.dispatch('webphone/resetCall');
}, 3500);
} else if (data?.tag === 'reject') {
setTimeout(() => {
this.$store.dispatch('webphone/resetCall');
}, 3500);
} else if (data?.tag === 'accept_elsewhere') {
setTimeout(() => {
this.$store.dispatch('webphone/resetCall');
}, 3500);
} else if (data?.tag === 'reject_elsewhere') {
} else if (['terminate', 'reject', 'accept_elsewhere', 'reject_elsewhere'].includes(data?.tag)) {
setTimeout(() => {
this.$store.dispatch('webphone/resetCall');
}, 3500);
}
// setCallState(data?.tag)
});
},
playCalling() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ export default {
currentChat: 'getSelectedChat',
inboxesList: 'inboxes/getInboxes',
activeInbox: 'getSelectedInbox',
currentUser: 'getCurrentUser',
accountId: 'getCurrentAccountId',
callInfo: 'webphone/getCallInfo',
}),
Expand Down Expand Up @@ -143,6 +142,16 @@ export default {
hasSlaPolicyId() {
return this.chat?.sla_policy_id;
},
callStatusMessage() {
const statusMessages = {
accept: this.$t('WEBPHONE.ACTIVE'),
terminate: this.$t('WEBPHONE.TERMINATE'),
reject: this.$t('WEBPHONE.REJECTED'),
outgoing_calling: this.$t('WEBPHONE.CONNECT_CALLING'),
preaccept: this.$t('WEBPHONE.CALLING'),
};
return statusMessages[this.callInfo.status] || '';
},
},
methods: {
onCardClick(e) {
Expand Down Expand Up @@ -299,34 +308,10 @@ export default {
<p class="text-green-500 m-0">{{ $t('WEBPHONE.VOICE_CALL') }}</p>
<p class="text-green-500 m-0">-</p>
<p
v-if="callInfo.status === 'accept'"
class="text-slate-800 dark:text-slate-100 m-0 text-center"
>
{{ $t('WEBPHONE.ACTIVE') }}
</p>
<p
v-if="callInfo.status === 'terminate'"
class="text-slate-800 dark:text-slate-100 m-0 text-center"
>
{{ $t('WEBPHONE.TERMINATE') }}
</p>
<p
v-if="callInfo.status === 'reject'"
class="text-slate-800 dark:text-slate-100 m-0 text-center"
>
{{ $t('WEBPHONE.TERMINATE') }}
</p>
<p
v-if="callInfo.status === 'outcoming_calling'"
class="text-slate-800 dark:text-slate-100 m-0 text-center"
>
{{ $t('WEBPHONE.CONNECT_CALLING') }}
</p>
<p
v-if="callInfo.status === 'preaccept'"
v-if="callStatusMessage"
class="text-slate-800 dark:text-slate-100 m-0 text-center"
>
{{ $t('WEBPHONE.CALLING') }}
{{ callStatusMessage }}
</p>
</div>
<template v-else>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export default {
},
methods: {
async startCall() {
if (!this.currentContact) {
useAlert(this.$t('WEBPHONE.CONTACT_NOT_FOUND'));
return;
}
try {
await this.$store.dispatch('webphone/outcomingCall', {
contact_name: this.currentContact.name,
Expand All @@ -50,13 +54,13 @@ export default {
chat_id: this.currentChat.id,
});
} catch (error) {
if (error.message === 'Numero não existe') {
if (error.message === 'Número não existe') {
useAlert(this.$t('WEBPHONE.CONTACT_INVALID'));
} else if (
error.message === 'Linha ocupada, tente mais tarde ou faça um upgrade'
error.message === 'Linha ocupada, tente mais tarde ou faça um upgrade'
) {
useAlert(this.$t('WEBPHONE.ALL_INSTANCE_BUSY'));
} else if (error.message === 'Limite de ligações atingido') {
} else if (error.message === 'Limite de ligações atingido') {
useAlert(this.$t('WEBPHONE.CALL_LIMIT'));
} else {
useAlert(this.$t('WEBPHONE.ERROR_TO_MADE_CALL'));
Expand Down Expand Up @@ -85,7 +89,7 @@ export default {
variant="clear"
color-scheme="secondary"
icon="call"
:disabled="callInfo.id"
:disabled="callInfo && callInfo.id"
@click="startCall"
/>
<woot-button
Expand Down
8 changes: 7 additions & 1 deletion app/javascript/dashboard/i18n/locale/en/webphone.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
"ALL_INSTANCE_BUSY": "All lines are busy",
"CONTACT_INVALID": "Contact does not exist on WhatsApp",
"CALL_LIMIT": "Daily call limit reached",
"ERROR_TO_MADE_CALL": "An error occurred while trying to call"
"ERROR_TO_MADE_CALL": "An error occurred while trying to call",
"CONTACT_NOT_FOUND": "Contact not found",
"NUMBER_NOT_FOUND": "Number not found",
"DAILY_LIMIT_REACHED": "Daily limit reached",
"LINE_BUSY_TRY_AGAIN": "Line busy, try again",
"NO_AVAILABLE_INSTANCES": "No available instances",
"CONNECTION_FAILED": "Connection failed"
}
}
22 changes: 14 additions & 8 deletions app/javascript/dashboard/i18n/locale/es/webphone.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
{
"WEBPHONE": {
"CALL": "Llamar",
"TERMINATE": "Finalizada",
"ACCEPT_ELSEWHERE": "Aceptada por otro usuario",
"REJECT_ELSEWHERE": "Rechazada por otro usuario",
"TERMINATE": "Terminado",
"ACCEPT_ELSEWHERE": "Aceptado por otro usuario",
"REJECT_ELSEWHERE": "Rechazado por otro usuario",
"CONNECT_CALLING": "Conectando",
"CALLING": "Llamando",
"VOICE_CALL": "Llamada de voz",
"IN_PROGRESS": "En progreso",
"ACTIVE": "Activa",
"ACTIVE": "Activo",
"MUTE": "Silenciar micrófono",
"UNMUTE": "Activar micrófono",
"TURN_ON_VIDEO": "Activar video",
"TURN_OFF_VIDEO": "Desactivar video",
"TURN_ON_VIDEO": "Encender video",
"TURN_OFF_VIDEO": "Apagar video",
"NUMPAD": "Teclado",
"TRANSFER": "Transferir",
"UNKNOWN": "Desconocido",
"ALL_INSTANCE_BUSY": "Todas las líneas están ocupadas",
"CONTACT_INVALID": "El contacto no existe en WhatsApp",
"CALL_LIMIT": "Límite diario de llamadas alcanzado",
"ERROR_TO_MADE_CALL": "Ocurrió un error al intentar llamar"
"CALL_LIMIT": "Se ha alcanzado el límite diario de llamadas",
"ERROR_TO_MADE_CALL": "Ocurrió un error al intentar llamar",
"CONTACT_NOT_FOUND": "Contacto no encontrado",
"NUMBER_NOT_FOUND": "Número no encontrado",
"DAILY_LIMIT_REACHED": "Límite diario alcanzado",
"LINE_BUSY_TRY_AGAIN": "Línea ocupada, inténtalo de nuevo",
"NO_AVAILABLE_INSTANCES": "No hay instancias disponibles",
"CONNECTION_FAILED": "Fallo de conexión"
}
}
14 changes: 10 additions & 4 deletions app/javascript/dashboard/i18n/locale/pt/webphone.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,23 @@
"CALLING": "A chamar",
"VOICE_CALL": "Chamada de voz",
"IN_PROGRESS": "Em progresso",
"ACTIVE": "Ativa",
"ACTIVE": "Ativo",
"MUTE": "Silenciar microfone",
"UNMUTE": "Ativar microfone",
"TURN_ON_VIDEO": "Ativar vídeo",
"TURN_OFF_VIDEO": "Desativar vídeo",
"TURN_ON_VIDEO": "Ligar vídeo",
"TURN_OFF_VIDEO": "Desligar vídeo",
"NUMPAD": "Teclado",
"TRANSFER": "Transferir",
"UNKNOWN": "Desconhecido",
"ALL_INSTANCE_BUSY": "Todas as linhas estão ocupadas",
"CONTACT_INVALID": "O contacto não existe no WhatsApp",
"CALL_LIMIT": "Limite diário de chamadas atingido",
"ERROR_TO_MADE_CALL": "Ocorreu um erro ao tentar ligar"
"ERROR_TO_MADE_CALL": "Ocorreu um erro ao tentar fazer a chamada",
"CONTACT_NOT_FOUND": "Contacto não encontrado",
"NUMBER_NOT_FOUND": "Número não encontrado",
"DAILY_LIMIT_REACHED": "Limite diário atingido",
"LINE_BUSY_TRY_AGAIN": "Linha ocupada, tente novamente",
"NO_AVAILABLE_INSTANCES": "Não há instâncias disponíveis",
"CONNECTION_FAILED": "Falha na ligação"
}
}
26 changes: 16 additions & 10 deletions app/javascript/dashboard/i18n/locale/pt_BR/webphone.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
{
"WEBPHONE": {
"CALL": "Ligar",
"TERMINATE": "Finalizada",
"TERMINATE": "Terminada",
"ACCEPT_ELSEWHERE": "Aceito por outro usuário",
"REJECT_ELSEWHERE": "Rejeitado por outro usuário",
"CONNECT_CALLING": "Ligando",
"CONNECT_CALLING": "Conectando",
"CALLING": "Chamando",
"VOICE_CALL": "Chamada de voz",
"IN_PROGRESS": "Em progresso",
"ACTIVE": "Ativa",
"MUTE": "Desativar microphone",
"UNMUTE": "Ativar microphone",
"TURN_ON_VIDEO": "Ativar video",
"TURN_OFF_VIDEO": "Desativar video",
"ACTIVE": "Ativo",
"MUTE": "Silenciar microfone",
"UNMUTE": "Ativar microfone",
"TURN_ON_VIDEO": "Ligar vídeo",
"TURN_OFF_VIDEO": "Desligar vídeo",
"NUMPAD": "Teclado",
"TRANSFER": "Transferir",
"UNKNOWN": "Desconhecido",
"ALL_INSTANCE_BUSY": "Todas as linhas estão ocupadas",
"CONTACT_INVALID": "Contato não existe no Whatsapp",
"CALL_LIMIT": "Limite de ligações diários atingido",
"ERROR_TO_MADE_CALL": "Ocorreu um erro ao tentar ligar"
"CONTACT_INVALID": "O contato não existe no WhatsApp",
"CALL_LIMIT": "Limite diário de chamadas atingido",
"ERROR_TO_MADE_CALL": "Ocorreu um erro ao tentar fazer a chamada",
"CONTACT_NOT_FOUND": "Contato não encontrado",
"NUMBER_NOT_FOUND": "Número não encontrado",
"DAILY_LIMIT_REACHED": "Limite diário atingido",
"LINE_BUSY_TRY_AGAIN": "Linha ocupada, tente novamente",
"NO_AVAILABLE_INSTANCES": "Não há instâncias disponíveis",
"CONNECTION_FAILED": "Falha na conexão"
}
}
22 changes: 16 additions & 6 deletions app/javascript/dashboard/store/modules/webphone.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,17 @@ export const actions = {
return;
}
const WAV = new Wavoip();
const whatsapp_instance = WAV.connect(token);
let whatsapp_instance;
try {
whatsapp_instance = WAV.connect(token);
} catch (error) {
console.error('Error connecting to Wavoip:', error);
useAlert(i18n.t('WEBPHONE.CONNECTION_FAILED'));
return;
}
commit(types.default.ADD_WAVOIP, {
token: token,
whatsapp_instance: whatsapp_instance,
whatsapp_instance: wavoipInstance,
inboxName: inboxName,
});
whatsapp_instance.socket.on('connect', () => {});
Expand All @@ -59,6 +66,9 @@ export const actions = {
outcomingCall: async ({ commit, state, dispatch }, callInfo) => {
let { phone, contact_name, chat_id } = callInfo;
let instances = callInfo.instances ?? Object.keys(state.wavoip);
if (!instances || instances.length === 0) {
throw new Error(i18n.t('WEBPHONE.NO_AVAILABLE_INSTANCES'));
}
let token = callInfo.token ?? instances[0];
let wavoip = state.wavoip[token].whatsapp_instance;
let inbox_name = state.wavoip[token].inbox_name;
Expand Down Expand Up @@ -96,10 +106,10 @@ export const actions = {
}
if (offerResponse.error) {
let remainingInstances = instances.filter(instance => instance !== token);
if (offerResponse.message === 'Numero não existe') {
if (offerResponse.message === i18n.t('WEBPHONE.NUMBER_NOT_FOUND')) {
throw new Error(offerResponse.message);
} else if (offerResponse.message === 'Limite de ligações atingido') {
useAlert('Limite de ligações diários atingido');
useAlert(i18n.t('WEBPHONE.DAILY_LIMIT_REACHED'));
}
if (remainingInstances.length > 0) {
dispatch('outcomingCall', {
Expand All @@ -108,7 +118,7 @@ export const actions = {
token: null,
});
} else {
throw new Error('Linha ocupada, tente mais tarde ou faça um upgrade');
throw new Error(i18n.t('WEBPHONE.LINE_BUSY_TRY_AGAIN'));
}
return;
}
Expand Down Expand Up @@ -162,7 +172,7 @@ export const actions = {
});
if (status === 'accept') {
commit(types.default.SET_WEBPHONE_CALL, {
active_start_date: new Date(),
active_start_date: Date.now()
});
}
},
Expand Down

0 comments on commit 22719fc

Please sign in to comment.