Skip to content

Commit

Permalink
Fix create templates job failing on first run (#2061)
Browse files Browse the repository at this point in the history
Fixes #2044

The first time the job is run the
three_sixty_dialog_client_waba_account_id is nil so it calls the
fetch_client_info method. This method successfully updates the
organization, but as it's the last line of the method it saves the
return of the update `true` to the local variable that is used in the
url to create the templates. This results in an error. Subsequent times
it's ran it does not error because it uses the value of the
organization's attribute, which is the correct value.
  • Loading branch information
mattwr18 authored Oct 24, 2024
1 parent 98a96ed commit 82805e4
Show file tree
Hide file tree
Showing 20 changed files with 346 additions and 391 deletions.
6 changes: 5 additions & 1 deletion .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 27,8 @@ Metrics/PerceivedComplexity:

Metrics/AbcSize:
Exclude:
- 'db/data/**'
- 'db/data/**'

Lint/MissingSuper:
Exclude:
- 'app/services/**/*.rb'
4 changes: 2 additions & 2 deletions app/adapters/whats_app_adapter/three_sixty_dialog_inbound.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 96,10 @@ def initialize_file(whats_app_message)
content_type = message_file[:mime_type]
file_id = message_file[:id]
filename = message_file[:filename] || file_id
file_fetcher = WhatsAppAdapter::ThreeSixtyDialog::FileFetcherService.new(organization_id: organization.id, file_id: file_id)
external_file = WhatsAppAdapter::ThreeSixtyDialog::FileFetcherService.call(organization_id: organization.id, file_id: file_id)

file.attachment.attach(
io: StringIO.new(file_fetcher.call),
io: StringIO.new(external_file),
filename: filename,
content_type: content_type,
identify: false
Expand Down
13 changes: 1 addition & 12 deletions app/adapters/whats_app_adapter/three_sixty_dialog_outbound.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 183,7 @@ def welcome_message_payload(recipient, organization)
policy: 'deterministic',
code: 'de'
},
name: "welcome_message_#{organization.project_name.parameterize.underscore}",
components: [
{
type: 'body',
parameters: [
{
type: 'text',
text: organization.project_name
}
]
}
]
name: "welcome_message_#{organization.project_name.parameterize.underscore}"
}
}
end
Expand Down
3 changes: 2 additions & 1 deletion app/jobs/whats_app_adapter/create_api_key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 16,7 @@ def perform(organization_id:, channel_id:)
url = URI.parse(
"#{base_uri}/partners/#{partner_id}/channels/#{channel_id}/api_keys"
)

headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Expand All @@ -39,7 40,7 @@ def handle_response(response)
Rails.logger.debug api_key
organization.update!(three_sixty_dialog_client_api_key: api_key)
WhatsAppAdapter::SetWebhookUrl.perform_later(organization_id: organization.id)
WhatsAppAdapter::CreateTemplates.perform_later(organization_id: organization.id, token: token)
WhatsAppAdapter::ThreeSixtyDialog::CreateTemplatesJob.perform_later(organization_id: organization.id)
when Net::HTTPClientError, Net::HTTPServerError
exception = WhatsAppAdapter::ThreeSixtyDialogError.new(error_code: response.code, message: response.body)
ErrorNotifier.report(exception)
Expand Down
154 changes: 0 additions & 154 deletions app/jobs/whats_app_adapter/create_templates.rb

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 1,70 @@
# frozen_string_literal: true

require 'net/http'

module WhatsAppAdapter
module ThreeSixtyDialog
class CreateTemplatesJob < ApplicationJob
def perform(organization_id:)
organization = Organization.find(organization_id)

existing_templates = WhatsAppAdapter::ThreeSixtyDialog::TemplateFetcherService.call(organization_id: organization.id)

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|
WhatsAppAdapter::ThreeSixtyDialog::TemplateCreatorService.call(organization_id: organization.id,
payload: new_request_template_payload(key, value))
end
end

private

# rubocop:disable Style/FormatStringToken
def whats_app_templates
I18n.t('.')[:adapter][:whats_app][:request_template].transform_values do |value|
value.gsub('%{first_name}', '{{1}}').gsub('%{request_title}', '{{2}}')
end
end
# rubocop:enable Style/FormatStringToken

# rubocop:disable Metrics/MethodLength
def new_request_template_payload(template_name, template_text)
{
name: template_name,
category: 'MARKETING',
components: [
{
type: 'BODY',
text: template_text,
example: {
body_text: [
[
'Jakob',
'Familie und Freizeit'
]
]
}
},
{
type: 'BUTTONS',
buttons: [
{
type: 'QUICK_REPLY',
text: 'Antworten'
},
{
type: 'QUICK_REPLY',
text: 'Mehr Infos'
}
]
}
],
language: 'de',
allow_category_change: true
}
end
# rubocop:enable Metrics/MethodLength
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -7,80 7,40 @@ module ThreeSixtyDialog
class CreateWelcomeMessageTemplateJob < ApplicationJob
def perform(organization_id:)
@organization = Organization.find_by(id: organization_id)
@token = WhatsAppAdapter::ThreeSixtyDialog::TokenFetcherService.call

@base_uri = ENV.fetch('THREE_SIXTY_DIALOG_PARTNER_REST_API_ENDPOINT', 'https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693')
@partner_id = ENV.fetch('THREE_SIXTY_DIALOG_PARTNER_ID', nil)
@waba_account_id = organization.three_sixty_dialog_client_waba_account_id
existing_templates = WhatsAppAdapter::ThreeSixtyDialog::TemplateFetcherService.new(
waba_account_id: waba_account_id,
token: token
).call
@base_uri = ENV.fetch('THREE_SIXTY_DIALOG_WHATS_APP_REST_API_ENDPOINT', 'https://stoplight.io/mocks/360dialog/360dialog-partner-api/24588693')
existing_templates = WhatsAppAdapter::ThreeSixtyDialog::TemplateFetcherService.call(organization_id: organization.id)

if "welcome_message_#{organization.project_name.parameterize.underscore}".in?(existing_templates)
notify_admin_to_update_existing_template
else
create_welcome_message_template
WhatsAppAdapter::ThreeSixtyDialog::TemplateCreatorService.call(organization_id: organization.id,
payload: welcome_message_template_payload)
end
end

attr_reader :organization, :token, :base_uri, :partner_id, :waba_account_id
attr_reader :organization, :base_uri

private

def notify_admin_to_update_existing_template
User.admin.find_each { |admin| PostmarkAdapter::Outbound.welcome_message_updated!(admin, organization) }
end

def create_welcome_message_template
url = URI.parse(
"#{base_uri}/partners/#{partner_id}/waba_accounts/#{waba_account_id}/waba_templates"
)
headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: "Bearer #{token}"
}

request = Net::HTTP::Post.new(url.to_s, headers)
payload = welcome_message_template_payload
request.body = payload.to_json
response = Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
http.request(request)
end
handle_response(response)
end

def welcome_message_template_payload
{
name: "welcome_message_#{organization.project_name.parameterize.underscore}",
category: 'MARKETING',
components: [
{
type: 'BODY',
text: ["*#{organization.onboarding_success_heading}*", organization.onboarding_success_text].join("\n\n").gsub(
organization.project_name.to_s, '{{1}}'
),
example: {
body_text: [
['100eyes']
]
}
text: ["*#{organization.onboarding_success_heading}*", organization.onboarding_success_text].join("\n\n")
}
],
language: 'de',
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
7 changes: 7 additions & 0 deletions app/services/application_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 1,7 @@
# frozen_string_literal: true

class ApplicationService
def self.call(...)
new(...).call
end
end
Loading

0 comments on commit 82805e4

Please sign in to comment.