Skip to content

Commit

Permalink
Add specs
Browse files Browse the repository at this point in the history
- create a notification after successfully creating a welcome message
  • Loading branch information
mattwr18 committed Oct 7, 2024
1 parent 88d7166 commit 8478bff
Show file tree
Hide file tree
Showing 12 changed files with 357 additions and 18 deletions.
6 changes: 4 additions & 2 deletions .env.test.local
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ POSTMARK_TRANSACTIONAL_STREAM=outbound
# SENTRY_DSN=
#
# THREE_SIXTY_DIALOG_PARTNER_ID=
# THREE_SIXTY_DIALOG_PARTNER_USERNAME=
# THREE_SIXTY_DIALOG_PARTNER_PASSWORD=

THREE_SIXTY_DIALOG_PARTNER_ID=valid_partner_id
THREE_SIXTY_DIALOG_PARTNER_USERNAME=valid_partner_username
THREE_SIXTY_DIALOG_PARTNER_PASSWORD=valid_partner_password
THREE_SIXTY_DIALOG_PARTNER_REST_API_ENDPOINT=https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693
ATTR_ENCRYPTED_KEY=spaL/6RL5DbZgAMNRDwp2KVaicUcZpaC1z43tV5iGtc=\n # Base64.encode64(OpenSSL::Cipher.new('aes-256-gcm').random_key)
34 changes: 34 additions & 0 deletions app/activity_notifications/whats_app_template_created.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# frozen_string_literal: true

class WhatsAppTemplateCreated < Noticed::Base
deliver_by :database, format: :to_database, association: :notifications_as_recipient

param :organization_id

def to_database
{
type: self.class.name,
organization_id: params[:organization_id]
}
end

def group_key
{ "#{self.class.to_s.underscore}_organization_id".to_sym => record.id }
end

def record_for_avatar
record.organization.users.sample
end

def group_message(*)
t('.text_html')
end

def url
organization_settings_path(record.organization, anchor: 'onboarding-success-section')
end

def link_text
t('.link_text')
end
end
2 changes: 1 addition & 1 deletion app/components/settings_form/settings_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<%= c('settings_field', organization: organization, type: :textarea, attr: :onboarding_page) %>
<% end %>

<%= c 'section', data: { testid: 'onboarding-success-section' } do %>
<%= c 'section', id: 'onboarding-success-section', data: { testid: 'onboarding-success-section' } do %>
<%= c('heading', tag: :h2) { t('organization.form.groups.onboarding_success') } %>
<%= c('settings_field', organization: organization, type: :input, attr: :onboarding_success_heading) %>
<%= c('settings_field', organization: organization, type: :textarea, attr: :onboarding_success_text) %>
Expand Down
8 changes: 4 additions & 4 deletions app/jobs/whats_app_adapter/create_templates.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def perform(organization_id:, token:)
existing_templates = WhatsAppAdapter::ThreeSixtyDialog::TemplateFetcherService.new(
waba_account_id: waba_account_id,
token: token
)
).call
templates_to_create_array = whats_app_templates.keys.difference(existing_templates)
templates_to_create = whats_app_templates.select { |key, _value| key.in?(templates_to_create_array) }
templates_to_create.each do |key, value|
Expand Down Expand Up @@ -140,10 +140,10 @@ def welcome_message_template_payload
end

def handle_response(response)
case response.code.to_i
when 201
case response
when Net::HTTPSuccess
Rails.logger.debug 'Great!'
when 400..599
when Net::HTTPClientError, Net::HTTPServerError
return if response.body.match?(/you have provided is already in use. Please choose a different name for your template./)

exception = WhatsAppAdapter::ThreeSixtyDialogError.new(error_code: response.code, message: response.body)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def perform(organization_id:)
existing_templates = WhatsAppAdapter::ThreeSixtyDialog::TemplateFetcherService.new(
waba_account_id: waba_account_id,
token: token
)
).call
if "welcome_message_#{organization.project_name.parameterize.underscore}".in?(existing_templates)
User.admin.find_each do |admin|
PostmarkAdapter::Outbound.welcome_message_updated!(admin, organization)
Expand Down Expand Up @@ -55,7 +55,9 @@ def welcome_message_template_payload
components: [
{
type: 'BODY',
text: ["*#{organization.onboarding_success_heading}*", organization.onboarding_success_text].join("\n\n"),
text: ["*#{organization.onboarding_success_heading}*", organization.onboarding_success_text].join("\n\n").gsub(
organization.project_name.to_s, '{{1}}'
),
example: {
body_text: [
['100eyes']
Expand All @@ -67,6 +69,16 @@ def welcome_message_template_payload
allow_category_change: true
}
end

def handle_response(response)
case response
when Net::HTTPSuccess
WhatsAppTemplateCreated.with(organization_id: organization.id).deliver_later(organization.users + User.admin.all)
when Net::HTTPClientError, Net::HTTPServerError
exception = WhatsAppAdapter::ThreeSixtyDialogError.new(error_code: response.code, message: response.body)
ErrorNotifier.report(exception)
end
end
end
end
end
2 changes: 1 addition & 1 deletion app/models/organization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Organization < ApplicationRecord
has_one_attached :channel_image

before_update :notify_admin
after_commit :notify_admin_of_welcome_message_change
after_update_commit :notify_admin_of_welcome_message_change

validates :telegram_bot_username, uniqueness: true

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ class TokenFetcherService
def initialize; end

def call
url = URI.parse(
"#{ENV.fetch('THREE_SIXTY_DIALOG_PARTNER_REST_API_ENDPOINT', 'https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693')}/token"
base_uri = URI.parse(
ENV.fetch('THREE_SIXTY_DIALOG_PARTNER_REST_API_ENDPOINT', 'https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693')
)
url = URI::HTTPS.build(host: base_uri.hostname, path: "#{base_uri.path}/token")
headers = { 'Content-Type': 'application/json' }
request = Net::HTTP::Post.new(url.to_s, headers)
request.body = {
Expand Down
3 changes: 3 additions & 0 deletions config/locales/de.yml
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,9 @@ de:
contributor_subscribed:
text_html: "<strong>%{contributor_name}</strong> hat beantragt, erneut Nachrichten per %{contributor_channel} zu bestellen."
link_text: Zum Profil
whats_app_template_created:
text_html: Deine WhatsApp-Vorlage wurde erfolgreich erstellt
link_text: Zu Einstellungen
shared:
community: Community
editorial: Redaktion
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# frozen_string_literal: true

require 'rails_helper'
require 'webmock/rspec'

RSpec.describe WhatsAppAdapter::ThreeSixtyDialog::CreateWelcomeMessageTemplateJob do
describe '#perform_later(organization_id:)' do
subject { -> { described_class.new.perform(organization_id: organization.id) } }

let!(:organization) do
create(:organization,
project_name: 'Test Project Name',
onboarding_success_heading: 'Welcome to Test Project Name',
three_sixty_dialog_client_waba_account_id: 'valid_waba_account_id')
end
let!(:admin) { create_list(:user, 3, admin: true) }
let!(:users_of_an_organization) { create_list(:user, 2, organizations: [organization]) }
let!(:user_of_another_organization) { create_list(:user, 2, organizations: [create(:organization)]) }

before do
allow(ENV).to receive(:fetch).with(
'THREE_SIXTY_DIALOG_PARTNER_REST_API_ENDPOINT', 'https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693'
).and_return('https://hub.360dialog.io/api/v2')
allow(ENV).to receive(:fetch).with(
'THREE_SIXTY_DIALOG_PARTNER_USERNAME', nil
).and_return('valid_partner_username')
allow(ENV).to receive(:fetch).with(
'THREE_SIXTY_DIALOG_PARTNER_PASSWORD', nil
).and_return('valid_partner_password')
allow(ENV).to receive(:fetch).with(
'THREE_SIXTY_DIALOG_PARTNER_ID', nil
).and_return('valid_partner_id')
end

describe 'ActivityNotifications', vcr: { cassette_name: :three_sixty_dialog_welcome_message_created } do
it 'creates a notification for all admin and users of an organizaiton' do
subject.call
whats_app_template_created_notifications = ActivityNotification.where(type: WhatsAppTemplateCreated.name)
expect(whats_app_template_created_notifications.count).to eq(5)

recipient_ids = whats_app_template_created_notifications.pluck(:recipient_id).uniq.sort
user_ids = users_of_an_organization.pluck(:id).uniq
admin_ids = admin.pluck(:id)
all_org_user_plus_admin = (user_ids + admin_ids).sort
expect(recipient_ids).to eq(all_org_user_plus_admin)
end
end
end
end
58 changes: 52 additions & 6 deletions spec/models/organization_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,31 @@
require 'rails_helper'

RSpec.describe Organization do
let(:organization) { create(:organization, business_plan_name: 'Editorial Basic') }
let!(:organization) { create(:organization, business_plan_name: 'Editorial Basic') }

describe '#notify_admin' do
subject { organization.update(params) }

let!(:admin) { create_list(:user, 3, admin: true) }
let!(:users) { create_list(:user, 2) }

context 'does not schedule a PostmarkAdpater::Outbound job' do
let(:params) { { name: 'SomethingElse', upgrade_discount: 100 } }

it 'for other updates' do
expect { subject }.not_to have_enqueued_job
expect { subject }.not_to have_enqueued_job.on_queue('default').with(
'PostmarkAdapter::Outbound',
'business_plan_upgraded_email',
'deliver_now', # How ActionMailer works in test environment, even though in production we call deliver_later
{
params: { admin: an_instance_of(User), organization: organization, price_per_month_with_discount: anything },
args: []
}
)
end
end

context 'with admin' do
let!(:admin) { create_list(:user, 3, admin: true) }
let!(:users) { create_list(:user, 2) }

context 'change to business plan' do
describe 'plan downgraded' do
let(:params) { { business_plan: create(:business_plan, :editorial_pro), upgraded_business_plan_at: nil } }

Expand Down Expand Up @@ -54,6 +62,44 @@
end
end

describe '#notify_admin_of_welcome_message_change' do
subject { organization.update(params) }

before do
allow(ENV).to receive(:fetch).with(
'THREE_SIXTY_DIALOG_PARTNER_REST_API_ENDPOINT', 'https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693'
).and_return('https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693')
end

context 'does not schedule a PostmarkAdpater::Outbound job' do
let(:params) { { name: 'SomethingElse' } }

it 'for other updates' do
expect { subject }.not_to have_enqueued_job(WhatsAppAdapter::ThreeSixtyDialog::CreateWelcomeMessageTemplateJob)
end
end

context 'change to onboarding success heading' do
let(:params) { { onboarding_success_heading: 'Another message' } }

it 'schedules a job to create the welcome message, if necessary' do
expect { subject }.to have_enqueued_job(WhatsAppAdapter::ThreeSixtyDialog::CreateWelcomeMessageTemplateJob).with(
organization_id: organization.id
)
end
end

context 'change to onboarding success text' do
let(:params) { { onboarding_success_text: 'Another message' } }

it 'schedules a job to create the welcome message, if necessary' do
expect { subject }.to have_enqueued_job(WhatsAppAdapter::ThreeSixtyDialog::CreateWelcomeMessageTemplateJob).with(
organization_id: organization.id
)
end
end
end

describe '#contributors_tags_with_count' do
subject { organization.contributors_tags_with_count.pluck(:name, :count) }

Expand Down
13 changes: 13 additions & 0 deletions spec/vcr_setup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@
c.filter_sensitive_data('D360-API-KEY') do |interaction|
interaction.request.headers['D360-Api-Key'].try(:first)
end
c.filter_sensitive_data('THREE_SIXTY_DIALOG_PARTNER_PASSWORD') do
ENV['THREE_SIXTY_DIALOG_PARTNER_PASSWORD']
end
c.filter_sensitive_data('THREE_SIXTY_DIALOG_PARTNER_USERNAME') do
ENV['THREE_SIXTY_DIALOG_PARTNER_USERNAME']
end
c.filter_sensitive_data('THREE_SIXTY_DIALOG_PARTNER_ID') do
ENV['THREE_SIXTY_DIALOG_PARTNER_ID']
end
c.filter_sensitive_data('Bearer <TOKEN>') do |interaction|
interaction.request.headers['Authorization'].try(:first)
end
c.filter_sensitive_data('THREE_SIXTY_DIALOG_CLIENT_WABA_ACCOUNT_ID') { 'valid_waba_account_id' }
c.configure_rspec_metadata!

# Capybara.server_host default
Expand Down
Loading

0 comments on commit 8478bff

Please sign in to comment.