Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions app/graph/types/team_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@ class TeamType < DefaultObject
field :dbid, GraphQL::Types::Int, null: true
field :members_count, GraphQL::Types::Int, null: true
field :permissions, GraphQL::Types::String, null: true
field :get_embed_whitelist, GraphQL::Types::String, null: true
field :get_report_design_image_template, GraphQL::Types::String, null: true
field :get_status_target_turnaround, GraphQL::Types::String, null: true
field :search_id, GraphQL::Types::String, null: true
field :search, CheckSearchType, null: true
field :check_search_trash, CheckSearchType, null: true
Expand All @@ -25,7 +22,6 @@ class TeamType < DefaultObject
field :public_team_id, GraphQL::Types::String, null: true
field :permissions_info, JsonStringType, null: true
field :dynamic_search_fields_json_schema, JsonStringType, null: true
field :get_rules, JsonStringType, null: true
field :rules_json_schema, GraphQL::Types::String, null: true
field :rules_search_fields_json_schema, JsonStringType, null: true
field :medias_count, GraphQL::Types::Int, null: true
Expand All @@ -34,7 +30,6 @@ class TeamType < DefaultObject
field :unconfirmed_count, GraphQL::Types::Int, null: true
field :get_language_detection, GraphQL::Types::Boolean, null: true
field :get_report, JsonStringType, null: true
field :get_fieldsets, JsonStringType, null: true
field :url, GraphQL::Types::String, null: true
field :data_report, JsonStringType, null: true
field :available_newsletter_header_types, JsonStringType, null: true # List of header type strings
Expand Down Expand Up @@ -126,6 +121,12 @@ def get_explainers_enabled
object.get_explainers_enabled
end

field :get_tipline_newsletter_enabled, GraphQL::Types::Int, null: true

def get_tipline_newsletter_enabled
object.get_tipline_newsletter_enabled
end

field :public_team, PublicTeamType, null: true

def public_team
Expand Down
58 changes: 39 additions & 19 deletions app/workers/tipline_newsletter_worker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ class TiplineNewsletterWorker
sidekiq_options queue: 'smooch_priority', retry: 0

def perform(team_id, language, job_created_at = 0)
team = Team.find_by_id team_id.to_i
return 0 if team.nil? || team.get_tipline_newsletter_enabled.to_i == 0
tbi = TeamBotInstallation.where(user_id: BotUser.smooch_user&.id.to_i, team_id: team_id.to_i).last
newsletter = Bot::Smooch.get_newsletter(team_id, language)
return 0 if tbi.nil? || !newsletter&.enabled
Expand Down Expand Up @@ -34,27 +36,22 @@ def perform(team_id, language, job_created_at = 0)
log team_id, language, 'Preparing newsletter to be sent...'
start = Time.now
total = 0
TiplineSubscription.where(language: language, team_id: team_id).find_each do |ts|
log team_id, language, "Sending newsletter to subscriber ##{ts.id}..."
begin
RequestStore.store[:smooch_bot_platform] = ts.platform
Bot::Smooch.get_installation('team_bot_installation_id', tbi.id) { |i| i.id == tbi.id }
RequestStore.store[:smooch_bot_provider] = 'ZENDESK' if ts.platform != 'WhatsApp' # Adjustment for tiplines running CAPI and Smooch at the same time

response = (ts.platform == 'WhatsApp' ? Bot::Smooch.send_message_to_user(ts.uid, newsletter.format_as_template_message, {}, false, true, 'newsletter') : Bot::Smooch.send_message_to_user(ts.uid, *newsletter.format_as_tipline_message))

if response.code.to_i < 400
log team_id, language, "Newsletter sent to subscriber ##{ts.id}, response: (#{response.code}) #{response.body.inspect}"
Bot::Smooch.save_smooch_response(response, nil, Time.now.to_i, 'newsletter', language, {}, 1.month)
count += 1
else
log team_id, language, "Could not send newsletter to subscriber ##{ts.id}: (#{response.code}) #{response.body.inspect}"
end
rescue StandardError => e
log team_id, language, "Could not send newsletter to subscriber ##{ts.id} (exception): #{e.message}"
end
# Send to all subscribers with non-whatsapp platform
TiplineSubscription.where(language: language, team_id: team_id).where.not(platform: 'WhatsApp').find_each do |ts|
count += send_newsletter_to_subscriber(ts, tbi.id, newsletter, team_id, language)
total += 1
end
# Apply limit in case get_tipline_newsletter_enabled == 1 and platform is whatsapp
if team.get_tipline_newsletter_enabled.to_i == 1
limit = team.get_tipline_newsletter_subscribers_limit
query = TiplineSubscription.where(language: language, team_id: team_id, platform: 'WhatsApp')
query = query.limit(limit.to_i) unless limit.blank?
query.find_each do |ts|
count += send_newsletter_to_subscriber(ts, tbi.id, newsletter, team_id, language)
total += 1
end
end

finish = Time.now

# Save a delivery event for this newsletter
Expand All @@ -77,6 +74,29 @@ def log(team_id, language, message)
logger.info "[Smooch Bot] [Newsletter] [Team ##{team_id}] [Language #{language}] [#{Time.now}] #{message}"
end

def send_newsletter_to_subscriber(ts, tbi_id, newsletter, team_id, language)
count = 0
log team_id, language, "Sending newsletter to subscriber ##{ts.id}..."
begin
RequestStore.store[:smooch_bot_platform] = ts.platform
Bot::Smooch.get_installation('team_bot_installation_id', tbi_id) { |i| i.id == tbi_id }
RequestStore.store[:smooch_bot_provider] = 'ZENDESK' if ts.platform != 'WhatsApp' # Adjustment for tiplines running CAPI and Smooch at the same time

response = (ts.platform == 'WhatsApp' ? Bot::Smooch.send_message_to_user(ts.uid, newsletter.format_as_template_message, {}, false, true, 'newsletter') : Bot::Smooch.send_message_to_user(ts.uid, *newsletter.format_as_tipline_message))

if response.code.to_i < 400
log team_id, language, "Newsletter sent to subscriber ##{ts.id}, response: (#{response.code}) #{response.body.inspect}"
Bot::Smooch.save_smooch_response(response, nil, Time.now.to_i, 'newsletter', language, {}, 1.month)
count = 1
else
log team_id, language, "Could not send newsletter to subscriber ##{ts.id}: (#{response.code}) #{response.body.inspect}"
end
rescue StandardError => e
log team_id, language, "Could not send newsletter to subscriber ##{ts.id} (exception): #{e.message}"
end
count
end

def save_delivery_event(newsletter, count, start, finish)
event = TiplineNewsletterDelivery.new({
recipients_count: count,
Expand Down
1 change: 1 addition & 0 deletions lib/relay.idl
Original file line number Diff line number Diff line change
Expand Up @@ -12602,6 +12602,7 @@ type Team implements Node {
get_status_target_turnaround: String
get_suggested_matches_filters: JsonStringType
get_tipline_inbox_filters: JsonStringType
get_tipline_newsletter_enabled: Int
id: ID!
inactive: Boolean
join_requests(
Expand Down
58 changes: 58 additions & 0 deletions lib/tasks/migrate/20260406120511_migrate_team_newsletter.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
namespace :check do
namespace :migrate do
# bundle exec rails check:migrate:migrate_tipline_newsletter_action
desc 'Enable/disable tipline newsletter based on tipline platform'
task migrate_tipline_newsletter_action: :environment do
started = Time.now.to_i
smooch = BotUser.smooch_user
output = []
TeamBotInstallation.where(user_id: smooch.id).find_each do |tbi|
print '.'
integrations = tbi.smooch_enabled_integrations
unless integrations.empty?
team = tbi.team
action = 2
if integrations.count == 1
action = !(integrations.keys == ['whatsapp'])
elsif !integrations.keys.include?('whatsapp')
action = 1
else
platforms = TiplineSubscription.where(team_id: team.id).map(&:platform).uniq
if platforms.count == 1
action = !(platforms == ['WhatsApp'])
end
end
# Use action.to_i as the return in lines 16 and 22 is a boolean
output << { team: team.slug, action: action.to_i }
team.set_tipline_newsletter_enabled = action.to_i
team.save!
end
end
puts "Workspace actions......\n"
pp output
minutes = ((Time.now.to_i - started) / 60).to_i
puts "[#{Time.now}] Done in #{minutes} minutes."
end
# bundle exec rails "check:migrate:set_tipline_newsletter_subscribers_limit[slug, limit]"
desc 'Set tipline newsletter subscribers limit, 0 means no limit'
task :set_tipline_newsletter_subscribers_limit, [:slug, :limit] => :environment do |_t, args|
raise "You should set team slug" if args[:slug].blank?
team = Team.where(slug: args[:slug]).first
unless team.nil?
limit = args[:limit].to_i == 0 ? nil : args[:limit].to_i
team.set_tipline_newsletter_subscribers_limit = limit
team.save!
end
end
# bundle exec rails "check:migrate:set_tipline_newsletter_action[slug, true/false]"
desc 'Enable/Disable tipline newsletter'
task :set_tipline_newsletter_action, [:slug, :action] => :environment do |_t, args|
raise "You should set team slug" if args[:slug].blank?
team = Team.where(slug: args[:slug]).first
unless team.nil?
team.set_tipline_newsletter_enabled = ActiveModel::Type::Boolean.new.cast(args[:action])
team.save!
end
end
end
end
14 changes: 14 additions & 0 deletions public/relay.json
Original file line number Diff line number Diff line change
Expand Up @@ -65815,6 +65815,20 @@
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "get_tipline_newsletter_enabled",
"description": null,
"args": [

],
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
Expand Down
2 changes: 1 addition & 1 deletion test/controllers/graphql_controller_8_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1008,7 +1008,7 @@ def setup
u = create_user is_admin: true
authenticate_with_user(u)
t = create_team set_report: { en: { use_introduction: true, introduction: 'Test' } }
fields = %w(get_embed_whitelist get_report_design_image_template get_status_target_turnaround get_rules get_languages get_language get_report get_data_report_url get_outgoing_urls_utm_code get_shorten_outgoing_urls get_report)
fields = %w(get_embed_whitelist get_report_design_image_template get_status_target_turnaround get_rules get_languages get_language get_report get_data_report_url get_outgoing_urls_utm_code get_shorten_outgoing_urls get_report get_tipline_newsletter_enabled)
post :create, params: { query: "query Team { team { join_requests(first: 10) { edges { node { id } } }, #{fields.join(', ')} } }", team: t.slug }
assert_response :success
end
Expand Down
21 changes: 21 additions & 0 deletions test/workers/tipline_newsletter_worker_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ def setup
require 'sidekiq/testing'
Sidekiq::Testing.inline!
setup_smooch_bot(true)
@team.set_tipline_newsletter_enabled = 1
@team.save!
create_tipline_subscription team_id: @team.id
rss = '<rss version="1"><channel><title>x</title><link>x</link><description>x</description><item><title>x</title><link>x</link></item></channel></rss>'
WebMock.stub_request(:get, 'http://test.com/feed.rss').to_return(status: 200, body: rss)
Expand Down Expand Up @@ -89,4 +91,23 @@ def setup
TiplineNewsletterWorker.perform_async(@team.id, 'en')
end
end

[
{ test: 'nl_0_without_limit', enabled: 0, limit: nil, expected: 0 },
{ test: 'nl_0_with_limit', enabled: 0, limit: 1, expected: 0 },
{ test: 'nl_1_without_limit', enabled: 1, limit: nil, expected: 6},
{ test: 'nl_1_with_limit', enabled: 1, limit: 1, expected: 4},
{ test: 'nl_2_without_limit', enabled: 2, limit: nil,expected: 3 },
{ test: 'nl_2_with_limit', enabled: 2, limit: 1, expected: 3 },
].each do |raw|
test "should send newsletter when set_tipline_newsletter_enabled is #{raw[:test]}" do
@team.set_tipline_newsletter_enabled = raw[:enabled]
@team.set_tipline_newsletter_subscribers_limit = raw[:limit]
@team.save!
['WhatsApp', 'WhatsApp', 'Telegram', 'Telegram', 'Facebook Messenger'].each do |platform|
create_tipline_subscription team_id: @team.id, platform: platform
end
assert_equal raw[:expected], TiplineNewsletterWorker.new.perform(@team.id, 'en')
end
end
end
Loading