Guest User

Untitled

a guest
Oct 23rd, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. def change_plan
  2. account = Account.find(params[:id])
  3.  
  4. old_plan = account.plan
  5. new_plan = Plan.find(params[:account][:plan_id])
  6.  
  7. account.change_plan!(params[:account][:plan_id])
  8.  
  9. SlackService.new.plan_change(current_user, account, old_plan, new_plan).deliver
  10. redirect_to action: "show", id: params[:id]
  11. end
  12.  
  13. require 'net/http'
  14.  
  15. class SlackService
  16. NAME_AND_ICON = {
  17. username: 'Dashboard',
  18. icon_emoji: ':bat:'
  19. }
  20.  
  21. SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/###/###/###"
  22. SLACK_WEBHOOK_CHANNEL = Rails.env.production? ? "###" : "###"
  23.  
  24. def initialize(channel = SLACK_WEBHOOK_CHANNEL)
  25. @uri = URI(SLACK_WEBHOOK_URL)
  26. @channel = channel
  27. end
  28.  
  29. def plan_change(user, account, old_plan, new_plan)
  30. params = {
  31. attachments: [
  32. {
  33. author_name: "#{user.first_name} #{user.last_name}",
  34. text: "Account: #{account.name} (#{account.id})",
  35. title: 'Dashboard Plan Change',
  36. fields: [
  37. {
  38. title: 'Old Plan',
  39. value: "#{old_plan.name} (#{ActionController::Base.helpers.number_to_currency(old_plan.price)})",
  40. short: true
  41. },
  42. {
  43. title: 'New Plan',
  44. value: "#{new_plan.name} ($#{ActionController::Base.helpers.number_to_currency(new_plan.price)})",
  45. short: true
  46. },
  47. ]
  48. }
  49. ]
  50. }
  51. @params = generate_payload(params)
  52. self
  53. end
  54.  
  55. def deliver
  56. begin
  57. Net::HTTP.post_form(@uri, @params)
  58. rescue => e
  59. Rails.logger.error("SlackService: Error when sending: #{e.message}")
  60. end
  61. end
  62.  
  63. private
  64.  
  65. def generate_payload(params)
  66. {
  67. payload: NAME_AND_ICON
  68. .merge(channel: @channel)
  69. .merge(params).to_json
  70. }
  71. end
  72. end
Add Comment
Please, Sign In to add comment