iachat/app/javascript/dashboard/store/modules/inboxes.js
Cayo P. R. Oliveira acd1e56a28 feat: baileys provider for whatsapp (#7)
* feat: baileys provider and placeholder for link device modal

* chore: drop qrcode.vue in favor of just img tag

* chore: update modal props

* feat: setup channel provider connection

* chore: update .env.example with Baileys API default configuration

* feat: add support for Baileys provider in WhatsApp events processing

* chore: rename Baileys API default host variable to DEFAULT_BAILEYS_URL

* feat: add setup and disconnect methods for Baileys channel provider in inboxes controller that will be implemented

* feat: add CHANNEL_CONNECTION_UPDATE event and include it in broadcast data preparation

* refactor: simplify channel retrieval logic in WhatsappEventsJob

* refactor: revert CHANNEL_UPDATE_EVENTS constant from ActionCableBroadcastJob

* feat: add 'baileys' as a provider option in Whatsapp channel model

* feat: add provider_connection field to Whatsapp channel model and migration

* refactor: remove unnecessary  CHANNEL_CONNECTION_UPDATE event type

* feat: implement channel provider connection with baileys API

* feat: add inbox association to Whatsapp channel model and update webhook URL handling

* feat: enhance Baileys service to handle webhook multiple event types

* refactor: simplify webhook verification logic in Baileys service

* feat: add setup channel provider call, and refactor some logic

* chore: adapt logic to new API

* refactor: fix typo

* refactor: fix import

* refactor: fix typo

* chore: add fixme comment about race condition

* fix: remove double disconnect call

* feat: implement message processing for incoming WhatsApp messages

* refactor: streamline message type determination and improve readability

* chore: increase cache key granularity

provider connection info might be updated multiple times within 1 second, so updates might be lost due to cache key not being updated. changing cache key to milliseconds solves this

* feat: add `is-loading` to buttons

* feat: update send_message method to use 'to' parameter and improve error handling

* refactor: simplify test setup and update API key in specs

* chore: add setup and disconnect channel provider specs

* test: fix spec after increase cache key granularity

* feat: handle reconnecting state on modal

* style: centered error text

* feat: advanced options on create inbox

* feat: handle new reconnecting on backend

* refactor: update inbox controller specs and leave a FIXME note

* test: add specs for Whatsapp::IncomingMessageBaileysService

* feat: add baileys configuration page

* feat: link device button when disconnected on conversation

* chore: refactor .env.example

* feat: add TODO for unimplemented methods in IncomingMessageBaileysService

* fix: correct method name and update environment variable references in WhatsappBaileysService

* refactor: simplify channel lookup by removing redundant method and handling phone number check directly

* chore: add TODO for unimplemented event processing methods in IncomingMessageBaileysService

* fix: update environment variable references in WhatsappBaileysService tests

* chore(webhook): add pt-BR translations

* chore: add pt-br translations

* chore: inboxname component margin

* refactor: inboxname computed prop

* feat: enhance WhatsApp provider connection handling and message processing

* test: inbox controller

* chore: improve baileys connection and messages handling

* test: incoming message service baileys

* refactor: update provider config validation and improve test setup for WhatsApp Baileys service

* fix: ensure only text messages are sent and update message source ID

* fix: create message

* fix: only update message on success

* test: fix broken specs

* chore: raise error on unsupported message content type

* feat: hide provider connection data from non-admins

* fix: update advanced options

* chore: move class definition

* fix: issue with send_message not returning id

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>
2025-04-03 23:28:38 -03:00

305 lines
10 KiB
JavaScript

import * as MutationHelpers from 'shared/helpers/vuex/mutationHelpers';
import * as types from '../mutation-types';
import { INBOX_TYPES } from 'dashboard/helper/inbox';
import InboxesAPI from '../../api/inboxes';
import WebChannel from '../../api/channel/webChannel';
import FBChannel from '../../api/channel/fbChannel';
import TwilioChannel from '../../api/channel/twilioChannel';
import { throwErrorMessage } from '../utils/api';
import AnalyticsHelper from '../../helper/AnalyticsHelper';
import camelcaseKeys from 'camelcase-keys';
import { ACCOUNT_EVENTS } from '../../helper/AnalyticsHelper/events';
const buildInboxData = inboxParams => {
const formData = new FormData();
const { channel = {}, ...inboxProperties } = inboxParams;
Object.keys(inboxProperties).forEach(key => {
formData.append(key, inboxProperties[key]);
});
const { selectedFeatureFlags, ...channelParams } = channel;
// selectedFeatureFlags needs to be empty when creating a website channel
if (selectedFeatureFlags) {
if (selectedFeatureFlags.length) {
selectedFeatureFlags.forEach(featureFlag => {
formData.append(`channel[selected_feature_flags][]`, featureFlag);
});
} else {
formData.append('channel[selected_feature_flags][]', '');
}
}
Object.keys(channelParams).forEach(key => {
formData.append(`channel[${key}]`, channel[key]);
});
return formData;
};
export const state = {
records: [],
uiFlags: {
isFetching: false,
isFetchingItem: false,
isCreating: false,
isUpdating: false,
isDeleting: false,
isUpdatingIMAP: false,
isUpdatingSMTP: false,
},
};
export const getters = {
getInboxes($state) {
return $state.records;
},
getWhatsAppTemplates: $state => inboxId => {
const [inbox] = $state.records.filter(
record => record.id === Number(inboxId)
);
const {
message_templates: whatsAppMessageTemplates,
additional_attributes: additionalAttributes,
} = inbox || {};
const { message_templates: apiInboxMessageTemplates } =
additionalAttributes || {};
const messagesTemplates =
whatsAppMessageTemplates || apiInboxMessageTemplates;
// filtering out the whatsapp templates with media
if (messagesTemplates instanceof Array) {
return messagesTemplates.filter(template => {
return !template.components.some(
i => i.format === 'IMAGE' || i.format === 'VIDEO'
);
});
}
return [];
},
getNewConversationInboxes($state) {
return $state.records.filter(inbox => {
const { channel_type: channelType, phone_number: phoneNumber = '' } =
inbox;
const isEmailChannel = channelType === INBOX_TYPES.EMAIL;
const isSmsChannel =
channelType === INBOX_TYPES.TWILIO &&
phoneNumber.startsWith('whatsapp');
return isEmailChannel || isSmsChannel;
});
},
getInbox: $state => inboxId => {
const [inbox] = $state.records.filter(
record => record.id === Number(inboxId)
);
return inbox || {};
},
getInboxById: $state => inboxId => {
const [inbox] = $state.records.filter(
record => record.id === Number(inboxId)
);
return camelcaseKeys(inbox || {}, { deep: true });
},
getUIFlags($state) {
return $state.uiFlags;
},
getWebsiteInboxes($state) {
return $state.records.filter(item => item.channel_type === INBOX_TYPES.WEB);
},
getTwilioInboxes($state) {
return $state.records.filter(
item => item.channel_type === INBOX_TYPES.TWILIO
);
},
getSMSInboxes($state) {
return $state.records.filter(
item =>
item.channel_type === INBOX_TYPES.SMS ||
(item.channel_type === INBOX_TYPES.TWILIO && item.medium === 'sms')
);
},
dialogFlowEnabledInboxes($state) {
return $state.records.filter(
item => item.channel_type !== INBOX_TYPES.EMAIL
);
},
};
const sendAnalyticsEvent = channelType => {
AnalyticsHelper.track(ACCOUNT_EVENTS.ADDED_AN_INBOX, {
channelType,
});
};
export const actions = {
revalidate: async ({ commit }, { newKey }) => {
try {
const isExistingKeyValid = await InboxesAPI.validateCacheKey(newKey);
if (!isExistingKeyValid) {
const response = await InboxesAPI.refetchAndCommit(newKey);
commit(types.default.SET_INBOXES, response.data.payload);
}
} catch (error) {
// Ignore error
}
},
get: async ({ commit }) => {
commit(types.default.SET_INBOXES_UI_FLAG, { isFetching: true });
try {
const response = await InboxesAPI.get(true);
commit(types.default.SET_INBOXES_UI_FLAG, { isFetching: false });
commit(types.default.SET_INBOXES, response.data.payload);
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isFetching: false });
}
},
createChannel: async ({ commit }, params) => {
try {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: true });
const response = await WebChannel.create(params);
commit(types.default.ADD_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
const { channel = {} } = params;
sendAnalyticsEvent(channel.type);
return response.data;
} catch (error) {
const errorMessage = error?.response?.data?.message;
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
throw new Error(errorMessage);
}
},
createWebsiteChannel: async ({ commit }, params) => {
try {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: true });
const response = await WebChannel.create(buildInboxData(params));
commit(types.default.ADD_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
sendAnalyticsEvent('website');
return response.data;
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
return throwErrorMessage(error);
}
},
createTwilioChannel: async ({ commit }, params) => {
try {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: true });
const response = await TwilioChannel.create(params);
commit(types.default.ADD_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
sendAnalyticsEvent('twilio');
return response.data;
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
throw error;
}
},
createFBChannel: async ({ commit }, params) => {
try {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: true });
const response = await FBChannel.create(params);
commit(types.default.ADD_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
sendAnalyticsEvent('facebook');
return response.data;
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isCreating: false });
throw new Error(error);
}
},
updateInbox: async ({ commit }, { id, formData = true, ...inboxParams }) => {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdating: true });
try {
const response = await InboxesAPI.update(
id,
formData ? buildInboxData(inboxParams) : inboxParams
);
commit(types.default.EDIT_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdating: false });
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdating: false });
throwErrorMessage(error);
}
},
updateInboxIMAP: async ({ commit }, { id, ...inboxParams }) => {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingIMAP: true });
try {
const response = await InboxesAPI.update(id, inboxParams);
commit(types.default.EDIT_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingIMAP: false });
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingIMAP: false });
throwErrorMessage(error);
}
},
updateInboxSMTP: async ({ commit }, { id, ...inboxParams }) => {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingSMTP: true });
try {
const response = await InboxesAPI.update(id, inboxParams);
commit(types.default.EDIT_INBOXES, response.data);
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingSMTP: false });
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isUpdatingSMTP: false });
throwErrorMessage(error);
}
},
delete: async ({ commit }, inboxId) => {
commit(types.default.SET_INBOXES_UI_FLAG, { isDeleting: true });
try {
await InboxesAPI.delete(inboxId);
commit(types.default.DELETE_INBOXES, inboxId);
commit(types.default.SET_INBOXES_UI_FLAG, { isDeleting: false });
} catch (error) {
commit(types.default.SET_INBOXES_UI_FLAG, { isDeleting: false });
throw new Error(error);
}
},
reauthorizeFacebookPage: async ({ commit }, params) => {
try {
const response = await FBChannel.reauthorizeFacebookPage(params);
commit(types.default.EDIT_INBOXES, response.data);
} catch (error) {
throw new Error(error.message);
}
},
deleteInboxAvatar: async (_, inboxId) => {
try {
await InboxesAPI.deleteInboxAvatar(inboxId);
} catch (error) {
throw new Error(error);
}
},
setupChannelProvider: async (_, inboxId) => {
try {
await InboxesAPI.setupChannelProvider(inboxId);
} catch (error) {
throwErrorMessage(error);
}
},
disconnectChannelProvider: async (_, inboxId) => {
try {
await InboxesAPI.disconnectChannelProvider(inboxId);
} catch (error) {
throwErrorMessage(error);
}
},
};
export const mutations = {
[types.default.SET_INBOXES_UI_FLAG]($state, uiFlag) {
$state.uiFlags = { ...$state.uiFlags, ...uiFlag };
},
[types.default.SET_INBOXES]: MutationHelpers.set,
[types.default.SET_INBOXES_ITEM]: MutationHelpers.setSingleRecord,
[types.default.ADD_INBOXES]: MutationHelpers.create,
[types.default.EDIT_INBOXES]: MutationHelpers.update,
[types.default.DELETE_INBOXES]: MutationHelpers.destroy,
};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};