Compare commits

...
Author SHA1 Message Date
Sojan 8fc8e95404 tesT: claude 2025-03-07 02:54:28 -08:00
Sojan 4201bc965e tesT: claude 2025-03-07 02:53:30 -08:00
Sojan b7db7811d4 chore: grok version 2025-03-07 02:48:20 -08:00
Sojan b411752612 chore: grok version 2025-03-07 02:42:39 -08:00
Sojan 20f27b6edf chore: grok version 2025-03-07 02:33:14 -08:00
Sojan 5a72f4d0c8 chore: grok version 2025-03-07 02:31:52 -08:00
Sojan e911afe7f6 chore: grok version 2025-03-07 02:29:55 -08:00
Sojan d3a8e83a95 chore: fixes 2025-03-07 02:25:21 -08:00
Sojan 335c06af7a chore: fixes 2025-03-07 02:07:00 -08:00
Sojan 8a720f9642 chore: improvements 2025-03-07 01:59:56 -08:00
Sojan 3ac946712b feat: Optimize circle ci builds 2025-03-07 01:55:07 -08:00
PranavandGitHub 8fefdea4e8 chore: Dynamically load OldSidebar if needed (#11038)
Move old sidebar loading to async
2025-03-06 19:12:54 -08:00
PranavandGitHub a513f152ed fix: Extend the locale without variant check for article locales as well (#11021)
We allow users to select locale variants when creating the help center
(e.g., pt_BR or en_UK). However, the selected variant may not always be
available for translation in the app. In such cases, we need to fall
back to either the base language or the default locale.

While this fallback logic was implemented for the portal locale, it was
missing for article locales.

This PR fixes that issue.
2025-03-06 18:24:46 -08:00
a0cf25ccde chore: Rescue slack link unfurling errors. (#11033)
Fixes
https://linear.app/chatwoot/issue/CW-4122/slackwebapierrorsmissingscope-missing-scope

This PR adds the ability to handle errors when scopes are missing during
link unfurling. Since link unfurling is just a nice-to-have feature that
doesn't affect core functionality, we will silently ignore these errors.

---------

Co-authored-by: Sojan <sojan@pepalo.com>
2025-03-06 15:57:16 -08:00
8d85a02ca9 feat: handle Channel errors (#11015)
This PR adds missing error handlers for the following channels and cases

1. WhatsApp - Generic Handlers for both Cloud and 360Dialog (Deprecated)
2. Instagram - Handler for a case where there is an HTTP error instead
of an `:error` in the 200 response
3. Facebook - Errors from the two sentry issues
([Net::OpenTimeout](https://chatwoot-p3.sentry.io/issues/6164805227) &
[JSON::ParserError](https://chatwoot-p3.sentry.io/issues/5903200786))
4. SMS: Generic handlers for Bandwidth SMS

#### Checklist

- [x] Bandwidth SMS
- [x] Whatsapp Cloud + 360 Dialog
- [x] Twilio SMS
- [x] Line
- [x] Telegram
- [x] Instagram
- [x] Facebook
- [x] GMail
- [x] 365 Mail
- [x] SMTP Mail

---------

Co-authored-by: Muhsin Keloth <muhsinkeramam@gmail.com>
2025-03-06 20:09:47 +05:30
Sivin VargheseandGitHub 7e1458fd32 fix: Issue when saving hotkeys (#11026)
# Pull Request Template

## Description

This PR fixes an issue when saving send message button hotkeys, where a
TypeError occurs: `this.updateUISettings is not a function`.

This issue arises after merging this PR
https://github.com/chatwoot/chatwoot/pull/10974

Fixes
https://chatwoot-p3.sentry.io/issues/6339976939/events/ca9946f92cb74428a72f1f74976a56a3/

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my code
- [ ] I have commented on my code, particularly in hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream
modules
2025-03-06 10:53:02 +05:30
PranavandGitHub d017156f32 fix: Disable syncing IMAP if the account is suspended (#11031)
This PR disables the IMAP syncing if the account is suspended.
2025-03-05 17:10:24 -08:00
23 changed files with 684 additions and 273 deletions
+196 -112
View File
@@ -1,117 +1,117 @@
version: 2.1
orbs:
node: circleci/node@6.1.0
ruby: circleci/ruby@2.1.0
defaults: &defaults
working_directory: ~/build
machine:
image: ubuntu-2204:2024.05.1
resource_class: large
environment:
RAILS_LOG_TO_STDOUT: false
COVERAGE: true
LOG_LEVEL: warn
parallelism: 4
executors:
app-executor:
machine:
image: ubuntu-2204:2024.05.1
resource_class: large
environment:
RAILS_LOG_TO_STDOUT: false
COVERAGE: true
LOG_LEVEL: warn
jobs:
build:
<<: *defaults
commands:
setup_dependencies:
steps:
- checkout
# Setup Node with caching
- node/install:
node-version: '23.7'
- node/install-pnpm
- restore_cache:
keys:
- pnpm-deps-v1-{{ checksum "pnpm-lock.yaml" }}
- node/install-packages:
pkg-manager: pnpm
override-ci-command: pnpm i
- run: node --version
- run: pnpm --version
- save_cache:
key: pnpm-deps-v1-{{ checksum "pnpm-lock.yaml" }}
paths:
- node_modules
# Setup Ruby with caching
- ruby/install:
version: '3.3.3'
- restore_cache:
keys:
- gem-cache-v1-{{ checksum "Gemfile.lock" }}
- run:
name: Add PostgreSQL repository and update
name: Install Bundler and Gems
command: |
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update -y
gem install bundler -v 2.5.16
bundle config set --local path 'vendor/bundle'
bundle install --jobs=4 --retry=3
- save_cache:
key: gem-cache-v1-{{ checksum "Gemfile.lock" }}
paths:
- vendor/bundle
# Install system dependencies using a layer caching approach
- restore_cache:
keys:
- apt-cache-v1-{{ checksum ".circleci/apt-packages.txt" }}
- run:
name: Create apt packages list
command: |
mkdir -p .circleci
cat > .circleci/apt-packages.txt \<< EOF
libpq-dev
redis-server
postgresql-common
postgresql-16
postgresql-16-pgvector
build-essential
git
curl
libssl-dev
zlib1g-dev
libreadline-dev
libyaml-dev
openjdk-11-jdk
jq
software-properties-common
ca-certificates
imagemagick
libxml2-dev
libxslt1-dev
file
g++
gcc
autoconf
gnupg2
patch
ruby-dev
liblzma-dev
libgmp-dev
libncurses5-dev
libffi-dev
libgdbm6
libgdbm-dev
libvips
EOF
- run:
name: Install System Dependencies
command: |
sudo apt-get update
DEBIAN_FRONTEND=noninteractive sudo apt-get install -y \
libpq-dev \
redis-server \
postgresql-common \
postgresql-16 \
postgresql-16-pgvector \
build-essential \
git \
curl \
libssl-dev \
zlib1g-dev \
libreadline-dev \
libyaml-dev \
openjdk-11-jdk \
jq \
software-properties-common \
ca-certificates \
imagemagick \
libxml2-dev \
libxslt1-dev \
file \
g++ \
gcc \
autoconf \
gnupg2 \
patch \
ruby-dev \
liblzma-dev \
libgmp-dev \
libncurses5-dev \
libffi-dev \
libgdbm6 \
libgdbm-dev \
libvips
- run:
name: Install RVM and Ruby 3.3.3
command: |
sudo apt-get install -y gpg
gpg --keyserver hkp://keyserver.ubuntu.com --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
\curl -sSL https://get.rvm.io | bash -s stable
echo 'source ~/.rvm/scripts/rvm' >> $BASH_ENV
source ~/.rvm/scripts/rvm
rvm install "3.3.3"
rvm use 3.3.3 --default
gem install bundler -v 2.5.16
- run:
name: Install Application Dependencies
command: |
source ~/.rvm/scripts/rvm
bundle install
# pnpm install
- run:
name: Download cc-test-reporter
command: |
mkdir -p ~/tmp
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ~/tmp/cc-test-reporter
chmod +x ~/tmp/cc-test-reporter
# Swagger verification
- run:
name: Verify swagger API specification
command: |
bundle exec rake swagger:build
if [[ `git status swagger/swagger.json --porcelain` ]]
then
echo "ERROR: The swagger.json file is not in sync with the yaml specification. Run 'rake swagger:build' and commit 'swagger/swagger.json'."
exit 1
# Add PostgreSQL repository once
if [ ! -f /etc/apt/sources.list.d/pgdg.list ]; then
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update -y
fi
curl -L https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.3.0/openapi-generator-cli-6.3.0.jar > ~/tmp/openapi-generator-cli-6.3.0.jar
java -jar ~/tmp/openapi-generator-cli-6.3.0.jar validate -i swagger/swagger.json
# we remove the FRONTED_URL from the .env before running the tests
# Install packages
DEBIAN_FRONTEND=noninteractive sudo apt-get install -y $(cat .circleci/apt-packages.txt)
- save_cache:
key: apt-cache-v1-{{ checksum ".circleci/apt-packages.txt" }}
paths:
- /var/cache/apt
# Set up database
- run:
name: Database Setup and Configure Environment Variables
command: |
@@ -128,39 +128,107 @@ jobs:
sed -i -e "/POSTGRES_PASSWORD/ s/=.*/=$pg_pass/" .env
echo -en "\nINSTALLATION_ENV=circleci" >> ".env"
# Database setup
# Download code climate reporter just once and cache it
- restore_cache:
keys:
- cc-test-reporter-v1
- run:
name: Run DB migrations
command: bundle exec rails db:chatwoot_prepare
name: Download cc-test-reporter
command: |
if [ ! -f ~/tmp/cc-test-reporter ]; then
mkdir -p ~/tmp
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ~/tmp/cc-test-reporter
chmod +x ~/tmp/cc-test-reporter
fi
- save_cache:
key: cc-test-reporter-v1
paths:
- ~/tmp/cc-test-reporter
# Bundle audit
workflows:
version: 2
build_and_test:
jobs:
- lint
- test-frontend:
requires:
- lint
- test-backend:
requires:
- lint
- report-coverage:
requires:
- test-frontend
- test-backend
jobs:
lint:
executor: app-executor
steps:
- setup_dependencies
# Swagger verification
- run:
name: Verify swagger API specification
command: |
bundle exec rake swagger:build
if [[ `git status swagger/swagger.json --porcelain` ]]
then
echo "ERROR: The swagger.json file is not in sync with the yaml specification. Run 'rake swagger:build' and commit 'swagger/swagger.json'."
exit 1
fi
# Cache the openapi jar
if [ ! -f ~/tmp/openapi-generator-cli-6.3.0.jar ]; then
curl -L https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.3.0/openapi-generator-cli-6.3.0.jar > ~/tmp/openapi-generator-cli-6.3.0.jar
fi
java -jar ~/tmp/openapi-generator-cli-6.3.0.jar validate -i swagger/swagger.json
# Bundle audit - run only in lint job
- run:
name: Bundle audit
command: bundle exec bundle audit update && bundle exec bundle audit check -v
# Rubocop linting
- run:
name: Rubocop
command: bundle exec rubocop
# ESLint linting
# ESLint
- run:
name: eslint
command: pnpm run eslint
test-frontend:
executor: app-executor
steps:
- setup_dependencies
- run:
name: Run DB migrations
command: bundle exec rails db:chatwoot_prepare
- run:
name: Run frontend tests
command: |
mkdir -p ~/build/coverage/frontend
~/tmp/cc-test-reporter before-build
pnpm run test:coverage
- run:
name: Code Climate Test Coverage (Frontend)
command: |
~/tmp/cc-test-reporter format-coverage -t lcov -o "~/build/coverage/frontend/codeclimate.frontend_$CIRCLE_NODE_INDEX.json"
~/tmp/cc-test-reporter format-coverage -t lcov -o "~/build/coverage/frontend/codeclimate.json"
- persist_to_workspace:
root: ~/build
paths:
- coverage/frontend
# Run backend tests
test-backend:
executor: app-executor
parallelism: 4
steps:
- setup_dependencies
- run:
name: Run DB migrations
command: bundle exec rails db:chatwoot_prepare
- run:
name: Run backend tests
command: |
@@ -174,18 +242,34 @@ jobs:
--out ~/tmp/test-results/rspec.xml \
-- ${TESTFILES}
no_output_timeout: 30m
- run:
name: Code Climate Test Coverage (Backend)
command: |
~/tmp/cc-test-reporter format-coverage -t simplecov -o "~/build/coverage/backend/codeclimate.$CIRCLE_NODE_INDEX.json"
- run:
name: List coverage directory contents
command: |
ls -R ~/build/coverage
- persist_to_workspace:
root: ~/build
paths:
- coverage
- coverage/backend
- store_test_results:
path: ~/tmp/test-results
- store_artifacts:
path: ~/tmp/test-artifacts
report-coverage:
executor: app-executor
steps:
- attach_workspace:
at: ~/build
- run:
name: Download cc-test-reporter
command: |
mkdir -p ~/tmp
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ~/tmp/cc-test-reporter
chmod +x ~/tmp/cc-test-reporter
- run:
name: Upload coverage results to Code Climate
command: |
# Sum the coverage reports
~/tmp/cc-test-reporter sum-coverage ~/build/coverage/**/codeclimate*.json -p 5 -o ~/build/coverage/codeclimate.json
# Upload the combined report
~/tmp/cc-test-reporter upload-coverage -i ~/build/coverage/codeclimate.json
+1 -1
View File
@@ -561,7 +561,7 @@ GEM
activesupport (>= 3.0.0)
raabro (1.4.0)
racc (1.8.1)
rack (2.2.11)
rack (2.2.12)
rack-attack (6.7.0)
rack (>= 1.0, < 4)
rack-contrib (2.5.0)
+19 -14
View File
@@ -5,10 +5,11 @@ module SwitchLocale
def switch_locale(&)
# priority is for locale set in query string (mostly for widget/from js sdk)
locale ||= locale_from_params
locale ||= params[:locale]
locale ||= locale_from_custom_domain
# if locale is not set in account, let's use DEFAULT_LOCALE env variable
locale ||= locale_from_env_variable
locale ||= ENV.fetch('DEFAULT_LOCALE', nil)
set_locale(locale, &)
end
@@ -32,26 +33,30 @@ module SwitchLocale
end
def set_locale(locale, &)
# if locale is empty, use default_locale
locale ||= I18n.default_locale
safe_locale = validate_and_get_locale(locale)
# Ensure locale won't bleed into other requests
# https://guides.rubyonrails.org/i18n.html#managing-the-locale-across-requests
I18n.with_locale(locale, &)
I18n.with_locale(safe_locale, &)
end
def locale_from_params
I18n.available_locales.map(&:to_s).include?(params[:locale]) ? params[:locale] : nil
def validate_and_get_locale(locale)
return I18n.default_locale.to_s if locale.blank?
available_locales = I18n.available_locales.map(&:to_s)
locale_without_variant = locale.split('_')[0]
if available_locales.include?(locale)
locale
elsif available_locales.include?(locale_without_variant)
locale_without_variant
else
I18n.default_locale.to_s
end
end
def locale_from_account(account)
return unless account
I18n.available_locales.map(&:to_s).include?(account.locale) ? account.locale : nil
end
def locale_from_env_variable
return unless ENV.fetch('DEFAULT_LOCALE', nil)
I18n.available_locales.map(&:to_s).include?(ENV.fetch('DEFAULT_LOCALE')) ? ENV.fetch('DEFAULT_LOCALE') : nil
account.locale
end
end
@@ -1,4 +1,6 @@
class Public::Api::V1::Portals::BaseController < PublicController
include SwitchLocale
before_action :show_plain_layout
before_action :set_color_scheme
before_action :set_global_config
@@ -27,14 +29,7 @@ class Public::Api::V1::Portals::BaseController < PublicController
end
def switch_locale_with_portal(&)
locale_without_variant = params[:locale].split('_')[0]
is_locale_available = I18n.available_locales.map(&:to_s).include?(params[:locale])
is_locale_variant_available = I18n.available_locales.map(&:to_s).include?(locale_without_variant)
if is_locale_available
@locale = params[:locale]
elsif is_locale_variant_available
@locale = locale_without_variant
end
@locale = validate_and_get_locale(params[:locale])
I18n.with_locale(@locale, &)
end
@@ -44,12 +39,12 @@ class Public::Api::V1::Portals::BaseController < PublicController
Rails.logger.info "Article: not found for slug: #{params[:article_slug]}"
render_404 && return if article.blank?
@locale = if article.category.present?
article.category.locale
else
article.portal.default_locale
end
article_locale = if article.category.present?
article.category.locale
else
article.portal.default_locale
end
@locale = validate_and_get_locale(article_locale)
I18n.with_locale(@locale, &)
end
@@ -26,7 +26,7 @@ const { t } = useI18n();
/>
</div>
<div
class="absolute bg-n-alpha-3 px-4 py-3 border rounded-xl border-n-strong text-n-slate-12 bottom-6 w-52 text-xs backdrop-blur-[100px] shadow-[0px_0px_24px_0px_rgba(0,0,0,0.12)] opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all"
class="absolute bg-n-alpha-3 px-4 py-3 border rounded-xl border-n-strong text-n-slate-12 bottom-6 w-52 text-xs backdrop-blur-[100px] shadow-[0px_0px_24px_0px_rgba(0,0,0,0.12)] opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all break-all"
:class="{
'ltr:left-0 rtl:right-0': orientation === ORIENTATION.LEFT,
'ltr:right-0 rtl:left-0': orientation === ORIENTATION.RIGHT,
@@ -102,6 +102,7 @@ const statusToShow = computed(() => {
if (isRead.value) return MESSAGE_STATUS.READ;
if (isDelivered.value) return MESSAGE_STATUS.DELIVERED;
if (isSent.value) return MESSAGE_STATUS.SENT;
if (status.value === MESSAGE_STATUS.FAILED) return MESSAGE_STATUS.FAILED;
return MESSAGE_STATUS.PROGRESS;
});
@@ -3,7 +3,6 @@ import { mapGetters } from 'vuex';
import { defineAsyncComponent } from 'vue';
import NextSidebar from 'next/sidebar/Sidebar.vue';
import Sidebar from '../../components/layout/Sidebar.vue';
import WootKeyShortcutModal from 'dashboard/components/widgets/modal/WootKeyShortcutModal.vue';
import AddAccountModal from 'dashboard/components/layout/sidebarComponents/AddAccountModal.vue';
import AccountSelector from 'dashboard/components/layout/sidebarComponents/AccountSelector.vue';
@@ -20,6 +19,10 @@ import { FEATURE_FLAGS } from 'dashboard/featureFlags';
const CommandBar = defineAsyncComponent(
() => import('./commands/commandbar.vue')
);
const Sidebar = defineAsyncComponent(
() => import('../../components/layout/Sidebar.vue')
);
import { emitter } from 'shared/helpers/mitt';
export default {
@@ -39,13 +39,14 @@ export default {
},
mixins: [globalConfigMixin],
setup() {
const { isEditorHotKeyEnabled } = useUISettings();
const { isEditorHotKeyEnabled, updateUISettings } = useUISettings();
const { currentFontSize, updateFontSize } = useFontSize();
return {
currentFontSize,
updateFontSize,
isEditorHotKeyEnabled,
updateUISettings,
};
},
data() {
@@ -2,8 +2,15 @@ class Inboxes::FetchImapEmailInboxesJob < ApplicationJob
queue_as :scheduled_jobs
def perform
Inbox.where(channel_type: 'Channel::Email').all.find_each(batch_size: 100) do |inbox|
::Inboxes::FetchImapEmailsJob.perform_later(inbox.channel) if inbox.channel.imap_enabled
email_inboxes = Inbox.where(channel_type: 'Channel::Email')
email_inboxes.find_each(batch_size: 100) do |inbox|
::Inboxes::FetchImapEmailsJob.perform_later(inbox.channel) if should_fetch_emails?(inbox)
end
end
private
def should_fetch_emails?(inbox)
inbox.channel.imap_enabled && !inbox.account.suspended?
end
end
+18 -3
View File
@@ -37,7 +37,7 @@ class Channel::Sms < ApplicationRecord
body = message_body(contact_number, message.content)
body['media'] = message.attachments.map(&:download_url) if message.attachments.present?
send_to_bandwidth(body)
send_to_bandwidth(body, message)
end
def send_text_message(contact_number, message_content)
@@ -56,7 +56,7 @@ class Channel::Sms < ApplicationRecord
}
end
def send_to_bandwidth(body)
def send_to_bandwidth(body, message = nil)
response = HTTParty.post(
"#{api_base_path}/users/#{provider_config['account_id']}/messages",
basic_auth: bandwidth_auth,
@@ -64,7 +64,22 @@ class Channel::Sms < ApplicationRecord
body: body.to_json
)
response.success? ? response.parsed_response['id'] : nil
if response.success?
response.parsed_response['id']
else
handle_error(response, message)
nil
end
end
def handle_error(response, message)
Rails.logger.error("[#{account_id}] Error sending SMS: #{response.parsed_response['description']}")
return if message.blank?
# https://dev.bandwidth.com/apis/messaging-apis/messaging/#tag/Messages/operation/createMessage
message.external_error = response.parsed_response['description']
message.status = :failed
message.save!
end
def bandwidth_auth
@@ -20,15 +20,30 @@ class Facebook::SendOnFacebookService < Base::SendOnChannelService
end
def send_message_to_facebook(delivery_params)
result = Facebook::Messenger::Bot.deliver(delivery_params, page_id: channel.page_id)
parsed_result = JSON.parse(result)
parsed_result = deliver_message(delivery_params)
return if parsed_result.nil?
if parsed_result['error'].present?
message.update!(status: :failed, external_error: external_error(parsed_result))
Rails.logger.info "Facebook::SendOnFacebookService: Error sending message to Facebook : Page - #{channel.page_id} : #{result}"
Rails.logger.info "Facebook::SendOnFacebookService: Error sending message to Facebook : Page - #{channel.page_id} : #{parsed_result}"
end
message.update!(source_id: parsed_result['message_id']) if parsed_result['message_id'].present?
end
def deliver_message(delivery_params)
result = Facebook::Messenger::Bot.deliver(delivery_params, page_id: channel.page_id)
JSON.parse(result)
rescue JSON::ParserError
message.update!(status: :failed, external_error: 'Facebook was unable to process this request')
Rails.logger.error "Facebook::SendOnFacebookService: Error parsing JSON response from Facebook : Page - #{channel.page_id} : #{result}"
nil
rescue Net::OpenTimeout
message.update!(status: :failed, external_error: 'Request timed out, please try again later')
Rails.logger.error "Facebook::SendOnFacebookService: Timeout error sending message to Facebook : Page - #{channel.page_id}"
nil
end
def fb_text_message_params
{
recipient: { id: contact.get_source_id(inbox.id) },
@@ -70,22 +70,28 @@ class Instagram::SendOnInstagramService < Base::SendOnChannelService
query: query
)
if response[:error].present?
Rails.logger.error("Instagram response: #{response['error']} : #{message_content}")
message.status = :failed
message.external_error = external_error(response)
handle_response(response, message_content)
end
def handle_response(response, message_content)
parsed_response = response.parsed_response
if response.success? && parsed_response['error'].blank?
message.update!(source_id: parsed_response['message_id'])
parsed_response
else
external_error = external_error(parsed_response)
Rails.logger.error("Instagram response: #{external_error} : #{message_content}")
message.update!(status: :failed, external_error: external_error)
nil
end
message.source_id = response['message_id'] if response['message_id'].present?
message.save!
response
end
def external_error(response)
# https://developers.facebook.com/docs/instagram-api/reference/error-codes/
error_message = response[:error][:message]
error_code = response[:error][:code]
error_message = response.dig('error', 'message')
error_code = response.dig('error', 'code')
"#{error_code} - #{error_message}"
end
@@ -27,6 +27,33 @@ class Whatsapp::Providers::BaseService
raise 'Overwrite this method in child class'
end
def error_message
raise 'Overwrite this method in child class'
end
def process_response(response)
parsed_response = response.parsed_response
if response.success? && parsed_response['error'].blank?
parsed_response['messages'].first['id']
else
handle_error(response)
nil
end
end
def handle_error(response)
Rails.logger.error response.body
return if @message.blank?
# https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes/#sample-response
error_message = error_message(response)
return if error_message.blank?
@message.external_error = error_message
@message.status = :failed
@message.save!
end
def create_buttons(items)
buttons = []
items.each do |item|
@@ -1,5 +1,6 @@
class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseService
def send_message(phone_number, message)
@message = message
if message.attachments.present?
send_attachment_message(phone_number, message)
elsif message.content_type == 'input_select'
@@ -78,6 +79,7 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
}
type_content['caption'] = message.content unless %w[audio sticker].include?(type)
type_content['filename'] = attachment.file.filename if type == 'document'
response = HTTParty.post(
"#{api_base_path}/messages",
headers: api_headers,
@@ -91,13 +93,9 @@ class Whatsapp::Providers::Whatsapp360DialogService < Whatsapp::Providers::BaseS
process_response(response)
end
def process_response(response)
if response.success?
response['messages'].first['id']
else
Rails.logger.error response.body
nil
end
def error_message(response)
# {"meta": {"success": false, "http_code": 400, "developer_message": "errro-message", "360dialog_trace_id": "someid"}}
response.parsed_response.dig('meta', 'developer_message')
end
def template_body_parameters(template_info)
@@ -1,5 +1,7 @@
class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseService
def send_message(phone_number, message)
@message = message
if message.attachments.present?
send_attachment_message(phone_number, message)
elsif message.content_type == 'input_select'
@@ -111,13 +113,9 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
process_response(response)
end
def process_response(response)
if response.success?
response['messages'].first['id']
else
Rails.logger.error response.body
nil
end
def error_message(response)
# https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes/#sample-response
response.parsed_response&.dig('error', 'message')
end
def template_body_parameters(template_info)
@@ -18,6 +18,10 @@ class Integrations::Slack::SendOnSlackService < Base::SendOnChannelService
slack_client.chat_unfurl(
event
)
# You may wonder why we're not requesting reauthorization and disabling hooks when scope errors occur.
# Since link unfurling is just a nice-to-have feature that doesn't affect core functionality, we will silently ignore these errors.
rescue Slack::Web::Api::Errors::MissingScope => e
Rails.logger.warn "Slack: Missing scope error: #{e.message}"
end
private
@@ -2,11 +2,19 @@ require 'rails_helper'
RSpec.describe Inboxes::FetchImapEmailInboxesJob do
let(:account) { create(:account) }
let(:suspended_account) { create(:account, status: 'suspended') }
let(:imap_email_channel) do
create(:channel_email, imap_enabled: true, imap_address: 'imap.gmail.com', imap_port: 993, imap_login: 'imap@gmail.com',
imap_password: 'password', account: account)
create(:channel_email, imap_enabled: true, account: account)
end
let(:imap_email_channel_suspended) do
create(:channel_email, imap_enabled: true, account: suspended_account)
end
let(:disabled_imap_channel) do
create(:channel_email, imap_enabled: false, account: account)
end
let(:email_inbox) { create(:inbox, channel: imap_email_channel, account: account) }
it 'enqueues the job' do
expect { described_class.perform_later }.to have_enqueued_job(described_class)
@@ -14,9 +22,26 @@ RSpec.describe Inboxes::FetchImapEmailInboxesJob do
end
context 'when called' do
it 'fetch all the email channels' do
it 'fetches emails only for active accounts with imap enabled' do
# Should call perform_later only once for the active, imap-enabled inbox
expect(Inboxes::FetchImapEmailsJob).to receive(:perform_later).with(imap_email_channel).once
# Should not call for suspended account or disabled IMAP channels
expect(Inboxes::FetchImapEmailsJob).not_to receive(:perform_later).with(imap_email_channel_suspended)
expect(Inboxes::FetchImapEmailsJob).not_to receive(:perform_later).with(disabled_imap_channel)
described_class.perform_now
end
it 'skips suspended accounts' do
expect(Inboxes::FetchImapEmailsJob).not_to receive(:perform_later).with(imap_email_channel_suspended)
described_class.perform_now
end
it 'skips disabled imap channels' do
expect(Inboxes::FetchImapEmailsJob).not_to receive(:perform_later).with(disabled_imap_channel)
described_class.perform_now
end
end
@@ -269,6 +269,19 @@ describe Integrations::Slack::SendOnSlackService do
expect(hook).to be_disabled
expect(hook).to have_received(:prompt_reauthorization!)
end
it 'logs MissingScope error during link unfurl' do
unflur_payload = { channel: 'channel', ts: 'timestamp', unfurls: {} }
error = Slack::Web::Api::Errors::MissingScope.new('Missing required scope')
expect(slack_client).to receive(:chat_unfurl)
.with(unflur_payload)
.and_raise(error)
expect(Rails.logger).to receive(:warn).with('Slack: Missing scope error: Missing required scope')
link_builder.link_unfurl(unflur_payload)
end
end
context 'when message contains mentions' do
@@ -0,0 +1,74 @@
require 'rails_helper'
RSpec.describe 'SwitchLocale Concern', type: :controller do
controller(ApplicationController) do
include SwitchLocale
def index
switch_locale { render plain: I18n.locale }
end
def account_locale
switch_locale_using_account_locale { render plain: I18n.locale }
end
end
let(:account) { create(:account, locale: 'es') }
let(:portal) { create(:portal, custom_domain: 'custom.example.com', config: { default_locale: 'fr_FR' }) }
describe '#switch_locale' do
context 'when locale is provided in params' do
it 'sets locale from params' do
get :index, params: { locale: 'es' }
expect(response.body).to eq('es')
end
it 'falls back to default locale if invalid' do
get :index, params: { locale: 'invalid' }
expect(response.body).to eq('en')
end
end
context 'when request is from custom domain' do
before { request.host = portal.custom_domain }
it 'sets locale from portal' do
get :index
expect(response.body).to eq('fr')
end
it 'overrides portal locale with param' do
get :index, params: { locale: 'es' }
expect(response.body).to eq('es')
end
end
context 'when locale is not provided anywhere' do
it 'sets locale from environment variable' do
with_modified_env(DEFAULT_LOCALE: 'de_DE') do
get :index
expect(response.body).to eq('de')
end
end
it 'falls back to default locale if env locale invalid' do
with_modified_env(DEFAULT_LOCALE: 'invalid') do
get :index
expect(response.body).to eq('en')
end
end
end
end
describe '#switch_locale_using_account_locale' do
before do
routes.draw { get 'account_locale' => 'anonymous#account_locale' }
end
it 'sets locale from account' do
controller.instance_variable_set(:@current_account, account)
get :account_locale
expect(response.body).to eq('es')
end
end
end
@@ -117,5 +117,54 @@ describe Facebook::SendOnFacebookService do
expect(message.reload.status).to eq('failed')
end
end
context 'when deliver_message fails' do
let(:message) { create(:message, message_type: 'outgoing', inbox: facebook_inbox, account: account, conversation: conversation) }
it 'handles JSON parse errors' do
allow(bot).to receive(:deliver).and_return('invalid_json')
described_class.new(message: message).perform
expect(message.reload.status).to eq('failed')
expect(message.external_error).to eq('Facebook was unable to process this request')
end
it 'handles timeout errors' do
allow(bot).to receive(:deliver).and_raise(Net::OpenTimeout)
described_class.new(message: message).perform
expect(message.reload.status).to eq('failed')
expect(message.external_error).to eq('Request timed out, please try again later')
end
it 'handles facebook error with code' do
error_response = {
error: {
message: 'Invalid OAuth access token.',
type: 'OAuthException',
code: 190,
fbtrace_id: 'BLBz/WZt8dN'
}
}.to_json
allow(bot).to receive(:deliver).and_return(error_response)
described_class.new(message: message).perform
expect(message.reload.status).to eq('failed')
expect(message.external_error).to eq('190 - Invalid OAuth access token.')
end
it 'handles successful delivery with message_id' do
success_response = {
message_id: 'mid.1456970487936:c34767dfe57ee6e339'
}.to_json
allow(bot).to receive(:deliver).and_return(success_response)
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('mid.1456970487936:c34767dfe57ee6e339')
expect(message.status).not_to eq('failed')
end
end
end
end
@@ -4,7 +4,7 @@ describe Instagram::SendOnInstagramService do
subject(:send_reply_service) { described_class.new(message: message) }
before do
stub_request(:post, /graph.facebook.com/)
stub_request(:post, /graph\.facebook\.com/)
create(:message, message_type: :incoming, inbox: instagram_inbox, account: account, conversation: conversation)
end
@@ -15,16 +15,49 @@ describe Instagram::SendOnInstagramService do
let(:contact_inbox) { create(:contact_inbox, contact: contact, inbox: instagram_inbox) }
let(:conversation) { create(:conversation, contact: contact, inbox: instagram_inbox, contact_inbox: contact_inbox) }
let(:response) { double }
let(:mock_response) do
instance_double(
HTTParty::Response,
:success? => true,
:body => { message_id: 'anyrandommessageid1234567890' }.to_json,
:parsed_response => { 'message_id' => 'anyrandommessageid1234567890' }
)
end
let(:error_body) do
{
'error' => {
'message' => 'The Instagram account is restricted.',
'type' => 'OAuthException',
'code' => 400,
'fbtrace_id' => 'anyrandomfbtraceid1234567890'
}
}
end
let(:error_response) do
instance_double(
HTTParty::Response,
:success? => false,
:body => error_body.to_json,
:parsed_response => error_body
)
end
let(:response_with_error) do
instance_double(
HTTParty::Response,
:success? => true,
:body => error_body.to_json,
:parsed_response => error_body
)
end
describe '#perform' do
context 'with reply' do
before do
allow(Facebook::Messenger::Configuration::AppSecretProofCalculator).to receive(:call).and_return('app_secret_key', 'access_token')
allow(HTTParty).to receive(:post).and_return(
{
'message_id': 'anyrandommessageid1234567890'
}
)
allow(HTTParty).to receive(:post).and_return(mock_response)
end
context 'without message_tag HUMAN_AGENT' do
@@ -35,22 +68,8 @@ describe Instagram::SendOnInstagramService do
it 'if message is sent from chatwoot and is outgoing' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
allow(HTTParty).to receive(:post).with(
{
recipient: { id: contact.get_source_id(instagram_inbox.id) },
message: {
text: message.content
}
}
).and_return(
{
'message_id': 'anyrandommessageid1234567890'
}
)
response = described_class.new(message: message).perform
expect(response).to eq({ message_id: 'anyrandommessageid1234567890' })
expect(response['message_id']).to eq('anyrandommessageid1234567890')
end
it 'if message is sent from chatwoot and is outgoing with multiple attachments' do
@@ -78,22 +97,13 @@ describe Instagram::SendOnInstagramService do
message.save!
response = described_class.new(message: message).perform
expect(response).to eq({ message_id: 'anyrandommessageid1234567890' })
expect(response['message_id']).to eq('anyrandommessageid1234567890')
end
it 'if message sent from chatwoot is failed' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
allow(HTTParty).to receive(:post).and_return(
{
'error': {
'message': 'The Instagram account is restricted.',
'type': 'OAuthException',
'code': 400,
'fbtrace_id': 'anyrandomfbtraceid1234567890'
}
}
)
allow(HTTParty).to receive(:post).and_return(response_with_error)
described_class.new(message: message).perform
expect(HTTParty).to have_received(:post)
expect(message.reload.status).to eq('failed')
@@ -129,5 +139,39 @@ describe Instagram::SendOnInstagramService do
end
end
end
context 'when handling errors' do
before do
allow(Facebook::Messenger::Configuration::AppSecretProofCalculator).to receive(:call).and_return('app_secret_key', 'access_token')
end
it 'handles HTTP errors' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
allow(HTTParty).to receive(:post).and_return(error_response)
described_class.new(message: message).perform
expect(message.reload.status).to eq('failed')
expect(message.reload.external_error).to eq('400 - The Instagram account is restricted.')
end
it 'handles response errors' do
message = create(:message, message_type: 'outgoing', inbox: instagram_inbox, account: account, conversation: conversation)
error_response = instance_double(
HTTParty::Response,
success?: true,
body: { 'error' => { 'message' => 'Invalid message format', 'code' => 100 } }.to_json,
parsed_response: { 'error' => { 'message' => 'Invalid message format', 'code' => 100 } }
)
allow(HTTParty).to receive(:post).and_return(error_response)
described_class.new(message: message).perform
expect(message.reload.status).to eq('failed')
expect(message.reload.external_error).to eq('100 - Invalid message format')
end
end
end
end
@@ -263,4 +263,56 @@ describe Whatsapp::Providers::WhatsappCloudService do
end
end
end
describe '#handle_error' do
let(:error_message) { 'Invalid message format' }
let(:error_response) do
{
'error' => {
'message' => error_message,
'code' => 100
}
}
end
let(:error_response_object) do
instance_double(
HTTParty::Response,
body: error_response.to_json,
parsed_response: error_response
)
end
before do
allow(Rails.logger).to receive(:error)
end
context 'when there is a message' do
it 'logs error and updates message status' do
service.instance_variable_set(:@message, message)
service.send(:handle_error, error_response_object)
expect(message.reload.status).to eq('failed')
expect(message.reload.external_error).to eq(error_message)
end
end
context 'when error message is blank' do
let(:error_response_object) do
instance_double(
HTTParty::Response,
body: '{}',
parsed_response: {}
)
end
it 'logs error but does not update message' do
service.instance_variable_set(:@message, message)
service.send(:handle_error, error_response_object)
expect(message.reload.status).not_to eq('failed')
expect(message.reload.external_error).to be_nil
end
end
end
end
@@ -12,13 +12,30 @@ describe Whatsapp::SendOnWhatsappService do
describe '#perform' do
before do
stub_request(:post, 'https://waba.360dialog.io/v1/configs/webhook')
stub_request(:post, 'https://waba.360dialog.io/v1/messages')
end
context 'when a valid message' do
let(:whatsapp_request) { double }
let(:whatsapp_request) { instance_double(HTTParty::Response) }
let!(:whatsapp_channel) { create(:channel_whatsapp, sync_templates: false) }
let!(:contact_inbox) { create(:contact_inbox, inbox: whatsapp_channel.inbox, source_id: '123456789') }
let!(:conversation) { create(:conversation, contact_inbox: contact_inbox, inbox: whatsapp_channel.inbox) }
let(:api_key) { 'test_key' }
let(:headers) { { 'D360-API-KEY' => api_key, 'Content-Type' => 'application/json' } }
let(:template_body) do
{
to: '123456789',
template: {
name: 'sample_shipping_confirmation',
namespace: '23423423_2342423_324234234_2343224',
language: { 'policy': 'deterministic', 'code': 'en_US' },
components: [{ 'type': 'body', 'parameters': [{ 'type': 'text', 'text': '3' }] }]
},
type: 'template'
}
end
let(:success_response) { { 'messages' => [{ 'id' => '123456789' }] }.to_json }
it 'calls channel.send_message when with in 24 hour limit' do
# to handle the case of 24 hour window limit.
@@ -26,14 +43,14 @@ describe Whatsapp::SendOnWhatsappService do
conversation: conversation)
message = create(:message, message_type: :outgoing, content: 'test',
conversation: conversation)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: { 'to' => '123456789', 'text' => { 'body' => 'test' }, 'type' => 'text' }.to_json
)
stub_request(:post, 'https://waba.360dialog.io/v1/messages')
.with(
headers: headers,
body: { 'to' => '123456789', 'text' => { 'body' => 'test' }, 'type' => 'text' }.to_json
)
.to_return(status: 200, body: success_response, headers: { 'content-type' => 'application/json' })
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
@@ -41,23 +58,13 @@ describe Whatsapp::SendOnWhatsappService do
it 'calls channel.send_template when after 24 hour limit' do
message = create(:message, message_type: :outgoing, content: 'Your package has been shipped. It will be delivered in 3 business days.',
conversation: conversation)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: {
to: '123456789',
template: {
name: 'sample_shipping_confirmation',
namespace: '23423423_2342423_324234234_2343224',
language: { 'policy': 'deterministic', 'code': 'en_US' },
components: [{ 'type': 'body', 'parameters': [{ 'type': 'text', 'text': '3' }] }]
},
type: 'template'
}.to_json
)
stub_request(:post, 'https://waba.360dialog.io/v1/messages')
.with(
headers: headers,
body: template_body.to_json
).to_return(status: 200, body: success_response, headers: { 'content-type' => 'application/json' })
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
@@ -65,23 +72,12 @@ describe Whatsapp::SendOnWhatsappService do
it 'calls channel.send_template if template_params are present' do
message = create(:message, additional_attributes: { template_params: template_params },
content: 'Your package will be delivered in 3 business days.', conversation: conversation, message_type: :outgoing)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: {
to: '123456789',
template: {
name: 'sample_shipping_confirmation',
namespace: '23423423_2342423_324234234_2343224',
language: { 'policy': 'deterministic', 'code': 'en_US' },
components: [{ 'type': 'body', 'parameters': [{ 'type': 'text', 'text': '3' }] }]
},
type: 'template'
}.to_json
)
stub_request(:post, 'https://waba.360dialog.io/v1/messages')
.with(
headers: headers,
body: template_body.to_json
).to_return(status: 200, body: success_response, headers: { 'content-type' => 'application/json' })
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end
@@ -93,23 +89,22 @@ describe Whatsapp::SendOnWhatsappService do
content: 'عميلنا العزيز الرجاء الرد على هذه الرسالة بكلمة *نعم* للرد على إستفساركم من قبل خدمة العملاء.',
conversation: conversation
)
allow(HTTParty).to receive(:post).and_return(whatsapp_request)
allow(whatsapp_request).to receive(:success?).and_return(true)
allow(whatsapp_request).to receive(:[]).with('messages').and_return([{ 'id' => '123456789' }])
expect(HTTParty).to receive(:post).with(
'https://waba.360dialog.io/v1/messages',
headers: { 'D360-API-KEY' => 'test_key', 'Content-Type' => 'application/json' },
body: {
to: '123456789',
template: {
name: 'customer_yes_no',
namespace: '2342384942_32423423_23423fdsdaf23',
language: { 'policy': 'deterministic', 'code': 'ar' },
components: [{ 'type': 'body', 'parameters': [] }]
},
type: 'template'
}.to_json
)
stub_request(:post, 'https://waba.360dialog.io/v1/messages')
.with(
headers: headers,
body: {
to: '123456789',
template: {
name: 'customer_yes_no',
namespace: '2342384942_32423423_23423fdsdaf23',
language: { 'policy': 'deterministic', 'code': 'ar' },
components: [{ 'type': 'body', 'parameters': [] }]
},
type: 'template'
}.to_json
).to_return(status: 200, body: success_response, headers: { 'content-type' => 'application/json' })
described_class.new(message: message).perform
expect(message.reload.source_id).to eq('123456789')
end