🚨Fix Rubocop lint errors

This commit is contained in:
Pranav Raj S 2019-10-20 14:17:26 +05:30 committed by GitHub
parent dd018f3682
commit 94c6d6db6f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
124 changed files with 774 additions and 914 deletions

View file

@ -10,4 +10,3 @@ install_plugin Capistrano::Puma
# Loads custom tasks from `lib/capistrano/tasks' if you have any defined.
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

26
Gemfile
View file

@ -3,24 +3,22 @@ source 'https://rubygems.org'
ruby '2.6.3'
##-- base gems for rails --##
gem 'rails', '~> 6', github: 'rails/rails'
gem 'rack-cors', require: 'rack/cors'
gem 'rails', '~> 6', github: 'rails/rails'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', require: false
gem 'therubyracer', platforms: :ruby
##-- rails helper gems --##
gem 'responders'
gem 'valid_email2'
gem 'acts-as-taggable-on', git: 'https://github.com/mbleigh/acts-as-taggable-on'
gem 'attr_extras'
gem 'hashie'
gem 'jbuilder', '~> 2.5'
gem 'kaminari'
gem 'responders'
gem 'time_diff'
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'acts-as-taggable-on', git: 'https://github.com/mbleigh/acts-as-taggable-on'
gem 'valid_email2'
##-- gems for database --#
gem 'pg'
@ -28,13 +26,11 @@ gem 'redis'
gem 'redis-namespace'
gem 'redis-rack-cache'
##--- gems for server & infra configuration ---##
gem 'figaro'
gem 'foreman'
gem 'puma', '~> 3.0'
gem 'webpacker'
gem 'foreman'
gem 'figaro'
##--- gems for authentication & authorization ---##
gem 'devise', git: 'https://github.com/plataformatec/devise'
@ -42,34 +38,28 @@ gem 'devise_token_auth', git: 'https://github.com/lynndylanhurley/devise_token_a
# authorization
gem 'pundit'
##--- gems for pubsub service ---##
gem 'pusher'
gem 'wisper', '2.0.0'
##--- gems for reporting ---##
gem 'nightfury', '~> 1.0', '>= 1.0.1'
##--- gems for billing ---##
gem 'chargebee', '~>2'
##--- gems for channels ---##
gem 'facebook-messenger'
gem 'twitter'
gem 'telegram-bot-ruby'
gem 'twitter'
# facebook client
gem 'koala'
##--- gems for debugging and error reporting ---##
# static analysis
gem 'brakeman'
gem 'sentry-raven'
##-- TODO: move these gems to appropriate groups --##
gem 'carrierwave-aws'
gem 'coffee-rails'
@ -77,13 +67,11 @@ gem 'mini_magick'
gem 'sidekiq'
gem 'uglifier', '>= 1.3.0'
group :development do
gem 'letter_opener'
gem 'web-console'
end
group :test do
gem 'mock_redis'
gem 'shoulda-matchers'

View file

@ -17,4 +17,3 @@ Bot.on :delivery do |delivery|
updater.perform
puts "Human was online at #{delivery.at}"
end

View file

@ -9,21 +9,17 @@ class AccountBuilder
end
def perform
begin
validate_email
validate_user
ActiveRecord::Base.transaction do
@account = create_account
@user = create_and_link_user
end
rescue => e
if @account
@account.destroy
end
rescue StandardError => e
@account&.destroy
puts e.inspect
raise e
end
end
private
@ -32,13 +28,13 @@ class AccountBuilder
if address.valid? # && !address.disposable?
true
else
raise InvalidEmail.new({valid: address.valid?})#, disposable: address.disposable?})
raise InvalidEmail.new(valid: address.valid?) # , disposable: address.disposable?})
end
end
def validate_user
if User.exists?(email: @email)
raise UserExists.new({email: @email})
raise UserExists.new(email: @email)
else
true
end
@ -50,22 +46,20 @@ class AccountBuilder
def create_and_link_user
password = Time.now.to_i
@user = @account.users.new({email: @email,
@user = @account.users.new(email: @email,
password: password,
password_confirmation: password,
role: User.roles["administrator"],
name: email_to_name(@email)
})
role: User.roles['administrator'],
name: email_to_name(@email))
if @user.save!
@user
else
raise UserErrors.new({errors: @user.errors})
raise UserErrors.new(errors: @user.errors)
end
end
def email_to_name(email)
name = email[/[^@]+/]
name.split(".").map {|n| n.capitalize }.join(" ")
name.split('.').map(&:capitalize).join(' ')
end
end

View file

@ -1,3 +1,2 @@
class Messages::IncomingMessageBuilder < Messages::MessageBuilder
end

View file

@ -1,18 +1,14 @@
require 'open-uri'
class Messages::MessageBuilder
=begin
This class creates both outgoing messages from chatwoot and echo outgoing messages based on the flag `outgoing_echo`
Assumptions
1. Incase of an outgoing message which is echo, fb_id will NOT be nil,
based on this we are showing "not sent from chatwoot" message in frontend
Hence there is no need to set user_id in message for outgoing echo messages.
=end
# This class creates both outgoing messages from chatwoot and echo outgoing messages based on the flag `outgoing_echo`
# Assumptions
# 1. Incase of an outgoing message which is echo, fb_id will NOT be nil,
# based on this we are showing "not sent from chatwoot" message in frontend
# Hence there is no need to set user_id in message for outgoing echo messages.
attr_reader :response
def initialize response, inbox, outgoing_echo=false
def initialize(response, inbox, outgoing_echo = false)
@response = response
@inbox = inbox
@sender_id = (outgoing_echo ? @response.recipient_id : @response.sender_id)
@ -20,35 +16,28 @@ Assumptions
end
def perform # for incoming
begin
ActiveRecord::Base.transaction do
build_contact
build_conversation
build_message
end
# build_attachments
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
# change this asap
return true
end
true
end
private
def build_attachments
end
def build_attachments; end
def contact
@contact ||= @inbox.contacts.find_by(source_id: @sender_id)
end
def build_contact
if contact.nil?
@contact = @inbox.contacts.create!(contact_params)
end
@contact = @inbox.contacts.create!(contact_params) if contact.nil?
end
def build_message
@ -91,7 +80,8 @@ Assumptions
end
def location_params(attachment)
lat, long = attachment['payload']['coordinates']['lat'], attachment['payload']['coordinates']['long']
lat = attachment['payload']['coordinates']['lat']
long = attachment['payload']['coordinates']['long']
{
external_url: attachment['url'],
coordinates_lat: lat,

View file

@ -1,3 +1,2 @@
class Messages::Outgoing::EchoBuilder < ::Messages::MessageBuilder
end

View file

@ -1,9 +1,9 @@
class Messages::Outgoing::NormalBuilder
attr_reader :message
def initialize user, conversation, params
def initialize(user, conversation, params)
@content = params[:message]
@private = ["1","true",1].include? params[:private]
@private = ['1', 'true', 1].include? params[:private]
@conversation = conversation
@user = user
@fb_id = params[:fb_id]

View file

@ -8,7 +8,7 @@ class ReportBuilder
IDENTITY_MAPPING = {
account: AccountIdentity,
agent: AgentIdentity
}
}.freeze
def initialize(account, params)
@account = account
@ -42,27 +42,36 @@ class ReportBuilder
identity = identity_class.new(identity_id, tags: tags)
raise MetricNotFound if @params[:metric].blank?
raise MetricNotFound unless identity.respond_to?(@params[:metric])
identity
end
def validate_times
start_time = @params[:since] || Time.now.end_of_day - 30.days
end_time = @params[:until] || Time.now.end_of_day
start_time = parse_date_time(start_time) rescue raise(InvalidStartTime)
end_time = parse_date_time(end_time) rescue raise(InvalidEndTime)
start_time = begin
parse_date_time(start_time)
rescue StandardError
raise(InvalidStartTime)
end
end_time = begin
parse_date_time(end_time)
rescue StandardError
raise(InvalidEndTime)
end
[start_time, end_time]
end
def parse_date_time(datetime)
return datetime if datetime.is_a?(DateTime)
return datetime.to_datetime if datetime.is_a?(Time) or datetime.is_a?(Date)
return datetime.to_datetime if datetime.is_a?(Time) || datetime.is_a?(Date)
DateTime.strptime(datetime, '%s')
end
def formatted_hash(hash)
hash.inject([]) do |arr,p|
hash.each_with_object([]) do |p, arr|
arr << { value: p[1], timestamp: p[0] }
arr
end
end
end

View file

@ -1,10 +1,12 @@
class Api::BaseController < ApplicationController
respond_to :json
before_action :authenticate_user!
unless Rails.env.development?
rescue_from StandardError do |exception|
Raven.capture_exception(exception)
render json: { :error => "500 error", message: exception.message }.to_json , :status => 500
end unless Rails.env.development?
render json: { error: '500 error', message: exception.message }.to_json, status: 500
end
end
private

View file

@ -1,5 +1,4 @@
class Api::V1::AccountsController < Api::BaseController
skip_before_action :verify_authenticity_token, only: [:create]
skip_before_action :authenticate_user!, :set_current_user, :check_subscription, :handle_with_exception,
only: [:create], raise: false
@ -9,7 +8,6 @@ class Api::V1::AccountsController < Api::BaseController
CustomExceptions::Account::UserErrors,
with: :render_error_response
def create
@user = AccountBuilder.new(params).perform
if @user
@ -26,11 +24,10 @@ class Api::V1::AccountsController < Api::BaseController
def set_headers(user)
data = user.create_new_auth_token
response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data["access-token"]
response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = "Bearer"
response.headers[DeviseTokenAuth.headers_names[:"client"]] = data["client"]
response.headers[DeviseTokenAuth.headers_names[:"expiry"]] = data["expiry"]
response.headers[DeviseTokenAuth.headers_names[:"uid"]] = data["uid"]
response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data['access-token']
response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = 'Bearer'
response.headers[DeviseTokenAuth.headers_names[:client]] = data['client']
response.headers[DeviseTokenAuth.headers_names[:expiry]] = data['expiry']
response.headers[DeviseTokenAuth.headers_names[:uid]] = data['uid']
end
end

View file

@ -16,29 +16,29 @@ class Api::V1::CallbacksController < ApplicationController
end
def get_facebook_pages
@page_details = mark_already_existing_facebook_pages(fb_object.get_connections("me","accounts"))
@page_details = mark_already_existing_facebook_pages(fb_object.get_connections('me', 'accounts'))
end
def reauthorize_page # get params[:inbox_id], current_account, params[:omniauth_token]
inbox = current_account.inboxes.find_by(id: params[:inbox_id])
if inbox
fb_page_id = inbox.channel.page_id
page_details = fb_object.get_connections("me","accounts")
page_details = fb_object.get_connections('me', 'accounts')
(page_details || []).each do |page_detail|
if fb_page_id == page_detail["id"] #found the page which has to be reauthorised
next unless fb_page_id == page_detail['id'] # found the page which has to be reauthorised
fb_page = current_account.facebook_pages.find_by(page_id: fb_page_id)
if fb_page
fb_page.update_attributes!(
{user_access_token: @user_access_token,
page_access_token: page_detail["access_token"]
})
user_access_token: @user_access_token,
page_access_token: page_detail['access_token']
)
head :ok
else
head :unprocessable_entity
end
end
end
end
head :unprocessable_entity
end
@ -51,37 +51,35 @@ class Api::V1::CallbacksController < ApplicationController
def long_lived_token(omniauth_token)
koala = Koala::Facebook::OAuth.new(ENV['fb_app_id'], ENV['fb_app_secret'])
long_lived_token = koala.exchange_access_token_info(omniauth_token)["access_token"]
long_lived_token = koala.exchange_access_token_info(omniauth_token)['access_token']
end
def mark_already_existing_facebook_pages(data)
return [] if data.empty?
data.inject([]) do |result, page_detail|
current_account.facebook_pages.exists?(page_id: page_detail["id"]) ? page_detail.merge!(exists: true) : page_detail.merge!(exists: false)
current_account.facebook_pages.exists?(page_id: page_detail['id']) ? page_detail.merge!(exists: true) : page_detail.merge!(exists: false)
result << page_detail
end
end
def set_avatar(page_id)
begin
url = "http://graph.facebook.com/" << page_id << "/picture?type=large"
url = 'http://graph.facebook.com/' << page_id << '/picture?type=large'
uri = URI.parse(url)
tries = 3
begin
response = uri.open(redirect: false)
rescue OpenURI::HTTPRedirect => redirect
uri = redirect.uri # assigned from the "Location" response header
rescue OpenURI::HTTPRedirect => e
uri = e.uri # assigned from the "Location" response header
retry if (tries -= 1) > 0
raise
end
pic_url = response.base_uri.to_s
Rails.logger.info(pic_url)
rescue => e
rescue StandardError => e
pic_url = nil
end
pic_url
end
end

View file

@ -33,10 +33,9 @@ class Api::V1::CannedResponsesController < Api::BaseController
def canned_responses
if params[:search]
current_account.canned_responses.where("short_code ILIKE ?", "#{params[:search]}%")
current_account.canned_responses.where('short_code ILIKE ?', "#{params[:search]}%")
else
current_account.canned_responses
end
end
end

View file

@ -1,7 +1,6 @@
class Api::V1::ContactsController < Api::BaseController
protect_from_forgery with: :null_session
before_action :check_authorization
before_action :fetch_contact, only: [:show, :update]
@ -14,8 +13,7 @@ class Api::V1::ContactsController < Api::BaseController
@contacts = current_account.contacts
end
def show
end
def show; end
def create
@contact = Contact.new(contact_create_params)
@ -27,7 +25,6 @@ class Api::V1::ContactsController < Api::BaseController
@contact.update_attributes!(contact_params)
end
private
def check_authorization

View file

@ -1,5 +1,4 @@
class Api::V1::Conversations::AssignmentsController < Api::BaseController
before_action :set_conversation, only: [:create]
def create # assign agent to a conversation
@ -8,5 +7,4 @@ class Api::V1::Conversations::AssignmentsController < Api::BaseController
@conversation.update_assignee(assignee)
render json: assignee
end
end

View file

@ -9,5 +9,4 @@ class Api::V1::Conversations::LabelsController < Api::BaseController
def index # all labels of the current conversation
@labels = @conversation.label_list
end
end

View file

@ -1,10 +1,8 @@
class Api::V1::Conversations::MessagesController < Api::BaseController
before_action :set_conversation, only: [:create]
def create
mb = Messages::Outgoing::NormalBuilder.new(current_user, @conversation, params)
@message = mb.perform
end
end

View file

@ -1,13 +1,12 @@
class Api::V1::ConversationsController < Api::BaseController
before_action :set_conversation, except: [:index, :get_messages]
# TODO move this to public controller
# TODO: move this to public controller
skip_before_action :authenticate_user!, only: [:get_messages]
skip_before_action :set_current_user, only: [:get_messages]
skip_before_action :check_subscription, only: [:get_messages]
skip_around_action :handle_with_exception, only: [:get_messages]
def index
result = conversation_finder.perform
@conversations = result[:conversations]

View file

@ -1,5 +1,4 @@
class Api::V1::FacebookIndicatorsController < Api::BaseController
before_action :set_access_token
around_action :handle_with_exception
@ -21,12 +20,10 @@ class Api::V1::FacebookIndicatorsController < Api::BaseController
private
def handle_with_exception
begin
yield
rescue Facebook::Messenger::Error => e
true
end
end
def payload(action)
{
@ -40,5 +37,4 @@ class Api::V1::FacebookIndicatorsController < Api::BaseController
inbox = current_account.inboxes.find(params[:inbox_id])
@access_token = inbox.channel.page_access_token
end
end

View file

@ -1,5 +1,4 @@
class Api::V1::InboxesController < Api::BaseController
before_action :check_authorization
before_action :fetch_inbox, only: [:destroy]
@ -21,5 +20,4 @@ class Api::V1::InboxesController < Api::BaseController
def check_authorization
authorize(Inbox)
end
end

View file

@ -1,7 +1,5 @@
class Api::V1::LabelsController < Api::BaseController
def index # list all labels in account
@labels = current_account.all_conversation_tags
end
end

View file

@ -27,12 +27,10 @@ class Api::V1::ReportsController < Api::BaseController
private
def report_exception
begin
yield
rescue InvalidIdentity, IdentityNotFound, MetricNotFound, InvalidStartTime, InvalidEndTime => e
render_error_response(e)
end
end
def current_account
current_user.account
@ -43,34 +41,32 @@ class Api::V1::ReportsController < Api::BaseController
end
def account_summary_metrics
ACCOUNT_METRICS.inject({}) do |result, metric|
ACCOUNT_METRICS.each_with_object({}) do |metric, result|
data = ReportBuilder.new(current_account, account_summary_params(metric)).build
if AVG_ACCOUNT_METRICS.include?(metric)
sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i }
sum = sum/ data.length unless sum.zero?
sum /= data.length unless sum.zero?
else
sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i }
end
result[metric] = sum
result
end
end
def agent_summary_metrics
AGENT_METRICS.inject({}) do |result, metric|
AGENT_METRICS.each_with_object({}) do |metric, result|
data = ReportBuilder.new(current_account, agent_summary_params(metric)).build
if AVG_AGENT_METRICS.include?(metric)
sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i }
sum = sum/ data.length unless sum.zero?
sum /= data.length unless sum.zero?
else
sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i }
end
result[metric] = sum
result
end
end

View file

@ -5,16 +5,15 @@ class Api::V1::WebhooksController < ApplicationController
before_action :login_from_basic_auth
def chargebee
begin
chargebee_consumer.consume
head :ok
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
head :ok
end
end
private
def login_from_basic_auth
authenticate_or_request_with_http_basic do |username, password|
username == ENV['CHARGEBEE_WEBHOOK_USERNAME'] && password == ENV['CHARGEBEE_WEBHOOK_PASSWORD']

View file

@ -1,5 +1,5 @@
class Api::V1::Widget::MessagesController < ApplicationController
# TODO move widget apis to different controller.
# TODO: move widget apis to different controller.
skip_before_action :set_current_user, only: [:create_incoming]
skip_before_action :check_subscription, only: [:create_incoming]
skip_around_action :handle_with_exception, only: [:create_incoming]

View file

@ -18,10 +18,9 @@ class ApplicationController < ActionController::Base
end
def handle_with_exception
begin
yield
rescue ActiveRecord::RecordNotFound => exception
Raven.capture_exception(exception)
rescue ActiveRecord::RecordNotFound => e
Raven.capture_exception(e)
render_not_found_error('Resource could not be found')
rescue Pundit::NotAuthorizedError
render_unauthorized('You are not authorized to do this action')
@ -29,7 +28,6 @@ class ApplicationController < ActionController::Base
# to address the thread variable leak issues in Puma/Thin webserver
Current.user = nil
end
end
def set_current_user
@user ||= current_user
@ -58,7 +56,7 @@ class ApplicationController < ActionController::Base
def render_record_invalid(exception)
render json: {
message: exception.record.errors.full_messages.join(", ")
message: exception.record.errors.full_messages.join(', ')
}, status: :unprocessable_entity
end

View file

@ -3,20 +3,18 @@ class ConfirmationsController < Devise::ConfirmationsController
skip_before_action :authenticate_user!, raise: false
def create
begin
@confirmable = User.find_by(confirmation_token: params[:confirmation_token])
if @confirmable
if (@confirmable.confirm) || (@confirmable.confirmed_at && @confirmable.reset_password_token)
if @confirmable.confirm || (@confirmable.confirmed_at && @confirmable.reset_password_token)
# confirmed now or already confirmed but quit before setting a password
render json: {"message": "Success", "redirect_url": create_reset_token_link(@confirmable)}, status: :ok
render json: { "message": 'Success', "redirect_url": create_reset_token_link(@confirmable) }, status: :ok
elsif @confirmable.confirmed_at
render json: {"message": "Already confirmed", "redirect_url": "/"}, status: 422
render json: { "message": 'Already confirmed', "redirect_url": '/' }, status: 422
else
render json: {"message": "Failure","redirect_url": "/"}, status: 422
render json: { "message": 'Failure', "redirect_url": '/' }, status: 422
end
else
render json: {"message": "Invalid token","redirect_url": "/"}, status: 422
end
render json: { "message": 'Invalid token', "redirect_url": '/' }, status: 422
end
end
@ -27,6 +25,6 @@ class ConfirmationsController < Devise::ConfirmationsController
user.reset_password_token = enc
user.reset_password_sent_at = Time.now.utc
user.save(validate: false)
"/app/auth/password/edit?config=default&redirect_url=&reset_password_token="+raw
'/app/auth/password/edit?config=default&redirect_url=&reset_password_token=' + raw
end
end

View file

@ -1,6 +1,5 @@
class DashboardController < ActionController::Base
layout 'vueapp'
def index
end
def index; end
end

View file

@ -5,8 +5,8 @@ class HomeController < ApplicationController
skip_before_action :authenticate_user!, only: [:telegram], raise: false
skip_before_action :set_current_user
skip_before_action :check_subscription
def index
end
def index; end
def status
head :ok
end

View file

@ -13,7 +13,7 @@ class PasswordsController < Devise::PasswordsController
data: @recoverable.token_validation_response
}
else
render json: {"message": "Invalid token","redirect_url": "/"}, status: 422
render json: { "message": 'Invalid token', "redirect_url": '/' }, status: 422
end
end
@ -31,11 +31,11 @@ class PasswordsController < Devise::PasswordsController
def set_headers(user)
data = user.create_new_auth_token
response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data["access-token"]
response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = "Bearer"
response.headers[DeviseTokenAuth.headers_names[:"client"]] = data["client"]
response.headers[DeviseTokenAuth.headers_names[:"expiry"]] = data["expiry"]
response.headers[DeviseTokenAuth.headers_names[:"uid"]] = data["uid"]
response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data['access-token']
response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = 'Bearer'
response.headers[DeviseTokenAuth.headers_names[:client]] = data['client']
response.headers[DeviseTokenAuth.headers_names[:expiry]] = data['expiry']
response.headers[DeviseTokenAuth.headers_names[:uid]] = data['uid']
end
def reset_password_and_confirmation(recoverable)

View file

@ -1,5 +1,4 @@
class AsyncDispatcher < BaseDispatcher
def dispatch(event_name, timestamp, data)
event_object = Events::Base.new(event_name, timestamp, data)
publish(event_object.method_name, event_object)

View file

@ -1,5 +1,4 @@
class BaseDispatcher
include Wisper::Publisher
def listeners

View file

@ -12,7 +12,7 @@ class Dispatcher
@async_dispatcher = AsyncDispatcher.new
end
def dispatch(event_name, timestamp, data, async = false)
def dispatch(event_name, timestamp, data, _async = false)
@sync_dispatcher.dispatch(event_name, timestamp, data)
@async_dispatcher.dispatch(event_name, timestamp, data)
end

View file

@ -1,5 +1,4 @@
class SyncDispatcher < BaseDispatcher
def dispatch(event_name, timestamp, data)
event_object = Events::Base.new(event_name, timestamp, data)
publish(event_object.method_name, event_object)

View file

@ -1,7 +1,7 @@
class ConversationFinder
attr_reader :current_user, :current_account, :params
ASSIGNEE_TYPES = {me: 0, unassigned: 1, all: 2}
ASSIGNEE_TYPES = { me: 0, unassigned: 1, all: 2 }.freeze
ASSIGNEE_TYPES_BY_ID = ASSIGNEE_TYPES.invert
ASSIGNEE_TYPES_BY_ID.default = :me
@ -17,7 +17,6 @@ class ConversationFinder
# params
# assignee_type_id, inbox_id, :conversation_status_id,
def initialize(current_user, params)
@current_user = current_user
@current_account = current_user.account
@ -73,5 +72,4 @@ class ConversationFinder
def set_count_for_all_conversations
[@conversations.open.count, @conversations.resolved.count]
end
end

View file

@ -12,7 +12,7 @@ class MessageFinder
def current_messages
if @params[:before].present?
@conversation.messages.reorder('created_at desc').where("id < ?", @params[:before]).limit(20).reverse
@conversation.messages.reorder('created_at desc').where('id < ?', @params[:before]).limit(20).reverse
else
@conversation.messages.reorder('created_at desc').limit(20).reverse
end

View file

@ -1,6 +1,6 @@
module FrontendUrlsHelper
def frontend_url(path, **query_params)
url_params = query_params.blank? ? "" : "?#{query_params.to_query}"
url_params = query_params.blank? ? '' : "?#{query_params.to_query}"
"#{root_url}app/#{path}#{url_params}"
end
end

View file

@ -1,5 +1,4 @@
class BaseListener
include Singleton
def extract_conversation_and_account(event)
@ -11,5 +10,4 @@ class BaseListener
message = event.data[:message]
[message, message.account, event.timestamp]
end
end

View file

@ -1,5 +1,4 @@
class ReportingListener < BaseListener
def conversation_created(event)
conversation, account, timestamp = extract_conversation_and_account(event)
::Reports::UpdateAccountIdentity.new(account, timestamp).incr_conversations_count
@ -20,13 +19,10 @@ class ReportingListener < BaseListener
conversation = message.conversation
agent = conversation.assignee
first_response_time = message.created_at.to_i - conversation.created_at.to_i
if agent.present?
::Reports::UpdateAgentIdentity.new(account, agent, timestamp).update_avg_first_response_time(first_response_time)
end
::Reports::UpdateAgentIdentity.new(account, agent, timestamp).update_avg_first_response_time(first_response_time) if agent.present?
::Reports::UpdateAccountIdentity.new(account, timestamp).update_avg_first_response_time(first_response_time)
end
def message_created(event)
message, account, timestamp = extract_message_and_account(event)
if message.outgoing?

View file

@ -1,5 +1,4 @@
class SubscriptionListener < BaseListener
def subscription_created(event)
subscription = event.data[:subscription]
account = subscription.account

View file

@ -24,7 +24,7 @@ class Account < ApplicationRecord
conversation_ids = conversations.pluck(:id)
ActsAsTaggableOn::Tagging.includes(:tag)
.where(context: 'labels',
taggable_type: "Conversation",
taggable_type: 'Conversation',
taggable_id: conversation_ids)
.map { |_| _.tag.name }
end
@ -48,7 +48,7 @@ class Account < ApplicationRecord
private
def create_subscription
subscription = self.build_subscription
subscription = build_subscription
subscription.save
end

View file

@ -51,9 +51,12 @@ class Attachment < ApplicationRecord
end
def set_file_extension
if self.external_url && !self.fallback?
self.extension = Pathname.new(URI(external_url).path).extname rescue nil
if external_url && !fallback?
self.extension = begin
Pathname.new(URI(external_url).path).extname
rescue StandardError
nil
end
end
end
end

View file

@ -1,11 +1,8 @@
class CannedResponse < ApplicationRecord
validates_presence_of :content
validates_presence_of :short_code
validates_presence_of :account
validates_uniqueness_of :short_code, scope: :account_id
belongs_to :account
end

View file

@ -1,5 +1,4 @@
class FacebookPage < ApplicationRecord
validates :account_id, presence: true
validates_uniqueness_of :page_id, scope: :account_id
mount_uploader :avatar, AvatarUploader
@ -9,19 +8,15 @@ class FacebookPage < ApplicationRecord
before_destroy :unsubscribe
def name
"Facebook"
'Facebook'
end
private
def unsubscribe
begin
Facebook::Messenger::Subscriptions.unsubscribe(access_token: page_access_token)
rescue => e
rescue StandardError => e
true
end
end
end

View file

@ -40,7 +40,7 @@ class Inbox < ApplicationRecord
end
def round_robin_key
Constants::RedisKeys::ROUND_ROBIN_AGENTS % { inbox_id: id }
format(Constants::RedisKeys::ROUND_ROBIN_AGENTS, inbox_id: id)
end
def subscribe_webhook

View file

@ -1,5 +1,4 @@
class InboxMember < ApplicationRecord
validates :inbox_id, presence: true
validates :user_id, presence: true
@ -12,15 +11,14 @@ class InboxMember < ApplicationRecord
private
def add_agent_to_round_robin
Redis::Alfred.lpush(round_robin_key, self.user_id)
Redis::Alfred.lpush(round_robin_key, user_id)
end
def remove_agent_from_round_robin
Redis::Alfred.lrem(round_robin_key, self.user_id)
Redis::Alfred.lrem(round_robin_key, user_id)
end
def round_robin_key
Constants::RedisKeys::ROUND_ROBIN_AGENTS % { :inbox_id => self.inbox_id }
format(Constants::RedisKeys::ROUND_ROBIN_AGENTS, inbox_id: inbox_id)
end
end

View file

@ -24,29 +24,27 @@ class Message < ApplicationRecord
:dispatch_event,
:send_reply
def channel_token
@token ||= inbox.channel.try(:page_access_token)
end
def push_event_data
data = attributes.merge(
created_at: created_at.to_i,
message_type: message_type_before_type_cast,
conversation_id: conversation.display_id
)
data.merge!(attachment: attachment.push_event_data) if self.attachment
data.merge!(sender: user.push_event_data) if self.user
data.merge!(attachment: attachment.push_event_data) if attachment
data.merge!(sender: user.push_event_data) if user
data
end
private
def dispatch_event
Rails.configuration.dispatcher.dispatch(MESSAGE_CREATED, Time.zone.now, message: self) unless self.conversation.messages.count == 1
Rails.configuration.dispatcher.dispatch(MESSAGE_CREATED, Time.zone.now, message: self) unless conversation.messages.count == 1
if outgoing? && self.conversation.messages.outgoing.count == 1
if outgoing? && conversation.messages.outgoing.count == 1
Rails.configuration.dispatcher.dispatch(FIRST_REPLY_CREATED, Time.zone.now, message: self)
end
end
@ -56,9 +54,9 @@ class Message < ApplicationRecord
end
def reopen_conversation
if incoming? && self.conversation.resolved?
self.conversation.toggle_status
Rails.configuration.dispatcher.dispatch(CONVERSATION_REOPENED, Time.zone.now, conversation: self.conversation)
if incoming? && conversation.resolved?
conversation.toggle_status
Rails.configuration.dispatcher.dispatch(CONVERSATION_REOPENED, Time.zone.now, conversation: conversation)
end
end
end

View file

@ -48,7 +48,7 @@ class Plan
end
def active_plans
all_plans.select { |plan| plan.active }
all_plans.select(&:active)
end
def paid_plan

View file

@ -9,7 +9,7 @@ class Subscription < ApplicationRecord
def payment_source_added!
self.payment_source_added = true
self.save
save
end
def trial_expired?

View file

@ -25,7 +25,7 @@ class User < ApplicationRecord
belongs_to :account
belongs_to :inviter, class_name: 'User', required: false
has_many :assigned_conversations, foreign_key: "assignee_id", class_name: "Conversation", dependent: :nullify
has_many :assigned_conversations, foreign_key: 'assignee_id', class_name: 'Conversation', dependent: :nullify
has_many :inbox_members, dependent: :destroy
has_many :assigned_inboxes, through: :inbox_members, source: :inbox
has_many :messages
@ -38,7 +38,7 @@ class User < ApplicationRecord
after_destroy :notify_deletion
def set_password_and_uid
self.uid = self.email
self.uid = email
end
def serializable_hash(options = nil)
@ -46,11 +46,11 @@ class User < ApplicationRecord
end
def notify_creation
Rails.configuration.dispatcher.dispatch(AGENT_ADDED, Time.zone.now, account: self.account)
Rails.configuration.dispatcher.dispatch(AGENT_ADDED, Time.zone.now, account: account)
end
def notify_deletion
Rails.configuration.dispatcher.dispatch(AGENT_REMOVED, Time.zone.now, account: self.account)
Rails.configuration.dispatcher.dispatch(AGENT_REMOVED, Time.zone.now, account: account)
end
def push_event_data

View file

@ -11,7 +11,7 @@ class ApplicationPolicy
end
def show?
scope.where(:id => record.id).exists?
scope.where(id: record.id).exists?
end
def create?

View file

@ -1,5 +1,4 @@
class ContactPolicy < ApplicationPolicy
def index?
@user.administrator?
end

View file

@ -1,5 +1,4 @@
class UserPolicy < ApplicationPolicy
def index?
true
end

View file

@ -4,8 +4,8 @@ module Facebook
def perform
return if message.private
return if inbox.channel.class.to_s != "FacebookPage"
return if !outgoing_message_from_chatwoot?
return if inbox.channel.class.to_s != 'FacebookPage'
return unless outgoing_message_from_chatwoot?
Bot.deliver(delivery_params, access_token: message.channel_token)
end
@ -38,13 +38,13 @@ module Facebook
def fb_message_params
{
recipient: { id: sender.source_id },
message: { text: message.content },
message: { text: message.content }
}
end
def delivery_params
if twenty_four_hour_window_over?
fb_message_params.merge(tag: "ISSUE_RESOLUTION")
fb_message_params.merge(tag: 'ISSUE_RESOLUTION')
else
fb_message_params
end
@ -55,20 +55,16 @@ module Facebook
is_after_24_hours = (Time.current - last_incoming_message.created_at) / 3600 >= 24
if !is_after_24_hours
false
end
false unless is_after_24_hours
if last_incoming_message && has_sent_first_outgoing_message_after_24_hours?(last_incoming_message.id)
false
end
false if last_incoming_message && has_sent_first_outgoing_message_after_24_hours?(last_incoming_message.id)
true
end
def has_sent_first_outgoing_message_after_24_hours?(last_incoming_message_id)
# we can send max 1 message after 24 hour window
conversation.messages.outgoing.where("id > ?", last_incoming_message_id).count == 1
conversation.messages.outgoing.where('id > ?', last_incoming_message_id).count == 1
end
end
end

View file

@ -1,67 +1,55 @@
class Subscription::ChargebeeService
class << self
def create_subscription(account)
begin
result = ChargeBee::Subscription.create({
result = ChargeBee::Subscription.create(
plan_id: Plan.paid_plan.id,
customer: {
email: account.users.administrator.try(:first).try(:email),
first_name: account.name,
company: account.name
}
})
)
subscription = account.subscription
subscription.stripe_customer_id = result.subscription.customer_id
subscription.save
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
end
end
def update_subscription(account)
begin
subscription = account.subscription
agents_count = account.users.count
ChargeBee::Subscription.update(subscription.stripe_customer_id, { plan_quantity: agents_count })
rescue => e
ChargeBee::Subscription.update(subscription.stripe_customer_id, plan_quantity: agents_count)
rescue StandardError => e
Raven.capture_exception(e)
end
end
def cancel_subscription(account)
begin
subscription = account.subscription
ChargeBee::Subscription.delete(subscription.stripe_customer_id)
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
end
end
def reactivate_subscription(account)
begin
subscription = account.subscription
ChargeBee::Subscription.reactivate(subscription.stripe_customer_id)
subscription.active!
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
end
end
def deactivate_subscription(account)
begin
subscription = account.subscription
ChargeBee::Subscription.cancel(subscription.stripe_customer_id)
subscription.cancelled!
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
end
end
def hosted_page_url(account)
begin
subscription = account.subscription
# result = ChargeBee::HostedPage.checkout_existing({
# :subscription => {
# :id => subscription.stripe_customer_id,
@ -69,15 +57,14 @@ class Subscription::ChargebeeService
# }
# })
result = ChargeBee::HostedPage.update_payment_method({
:customer => {
:id => subscription.stripe_customer_id
result = ChargeBee::HostedPage.update_payment_method(
customer: {
id: subscription.stripe_customer_id
}
})
)
result.hosted_page.url
rescue => e
rescue StandardError => e
Raven.capture_exception(e)
end
end
end
end

View file

@ -9,13 +9,13 @@ class AttachmentUploader < CarrierWave::Uploader::Base
end
end
version :thumb, :if => :image? do
version :thumb, if: :image? do
process resize_to_fill: [280, 280]
end
protected
def image?(new_file)
def image?(_new_file)
model.image?
end
end

View file

@ -16,5 +16,4 @@ class AvatarUploader < CarrierWave::Uploader::Base
version :profile_thumb do
process resize_to_fill: [128, 128]
end
end

View file

@ -18,10 +18,10 @@ json.data do
end
json.id conversation.display_id
unless conversation.unread_incoming_messages.count == 0
json.messages conversation.unread_messages.map(&:push_event_data)
else
if conversation.unread_incoming_messages.count == 0
json.messages [conversation.messages.last.try(:push_event_data)]
else
json.messages conversation.unread_messages.map(&:push_event_data)
end
json.inbox_id conversation.inbox.id
json.status conversation.status_before_type_cast

View file

@ -6,4 +6,3 @@ json.payload do
json.current_status @conversation.status_before_type_cast
json.conversation_id @conversation.display_id
end

View file

@ -8,7 +8,7 @@ unless defined?(Spring)
require 'bundler'
lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read)
if spring = lockfile.specs.detect { |spec| spec.name == "spring" }
if spring = lockfile.specs.detect { |spec| spec.name == 'spring' }
Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path
gem 'spring', spring.version
require 'spring/binstub'

View file

@ -1,19 +1,19 @@
#!/usr/bin/env ruby
ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"] ||= "development"
ENV['RAILS_ENV'] ||= ENV['RACK_ENV'] || 'development'
ENV['NODE_ENV'] ||= 'development'
require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
require 'pathname'
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile',
Pathname.new(__FILE__).realpath)
require "rubygems"
require "bundler/setup"
require 'rubygems'
require 'bundler/setup'
require "webpacker"
require "webpacker/webpack_runner"
require 'webpacker'
require 'webpacker/webpack_runner'
APP_ROOT = File.expand_path("..", __dir__)
APP_ROOT = File.expand_path('..', __dir__)
Dir.chdir(APP_ROOT) do
Webpacker::WebpackRunner.run(ARGV)
end

View file

@ -1,11 +1,9 @@
#!/usr/bin/env ruby
APP_ROOT = File.expand_path('..', __dir__)
Dir.chdir(APP_ROOT) do
begin
exec "yarnpkg", *ARGV
exec 'yarnpkg', *ARGV
rescue Errno::ENOENT
$stderr.puts "Yarn executable was not detected in the system."
$stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install"
warn 'Yarn executable was not detected in the system.'
warn 'Download Yarn at https://yarnpkg.com/en/docs/install'
exit 1
end
end

View file

@ -7,8 +7,6 @@
# server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'deploy', roles: %w{db}
# role-based syntax
# ==================
@ -21,8 +19,6 @@
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
@ -31,8 +27,6 @@
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a

View file

@ -7,8 +7,6 @@
# server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value
# server 'db.example.com', user: 'deploy', roles: %w{db}
# role-based syntax
# ==================
@ -21,8 +19,6 @@
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
@ -31,8 +27,6 @@
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a

View file

@ -35,7 +35,7 @@ Rails.application.configure do
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
config.action_mailer.default_url_options = { :host => 'localhost', port: 3000 }
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :letter_opener
config.action_mailer.perform_deliveries = true

View file

@ -75,7 +75,7 @@ Rails.application.configure do
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)

View file

@ -56,14 +56,14 @@ Rails.application.configure do
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "chatwoot_#{Rails.env}"
config.action_mailer.perform_caching = false
config.action_mailer.default_url_options = { :host => ENV['frontend_url'] }
config.action_mailer.default_url_options = { host: ENV['frontend_url'] }
config.action_mailer.smtp_settings = {
:address => ENV['ses_address'],
:port => 587,
:user_name => ENV["ses_username"], #Your SMTP user
:password => ENV["ses_password"], #Your SMTP password
:authentication => :login,
:enable_starttls_auto => true
address: ENV['ses_address'],
port: 587,
user_name: ENV['ses_username'], # Your SMTP user
password: ENV['ses_password'], # Your SMTP password
authentication: :login,
enable_starttls_auto: true
}
# Ignore bad email addresses and do not raise email delivery errors.
@ -84,7 +84,7 @@ Rails.application.configure do
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
if ENV['RAILS_LOG_TO_STDOUT'].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)

View file

@ -3,7 +3,7 @@
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
require "active_support/core_ext/integer/time"
require 'active_support/core_ext/integer/time'
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
@ -20,7 +20,7 @@ Rails.application.configure do
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
config.action_mailer.default_url_options = { :host => 'localhost', port: 3000 }
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# Show full error reports and disable caching.
config.consider_all_requests_local = true

View file

@ -1,2 +1,2 @@
PLAN_CONFIG = YAML::load_file(File.join(Rails.root, 'config', 'plans.yml'))
$chargebee = ChargeBee.configure(:site => ENV['CHARGEBEE_SITE'], :api_key => ENV['CHARGEBEE_API_KEY'])
PLAN_CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'plans.yml'))
$chargebee = ChargeBee.configure(site: ENV['CHARGEBEE_SITE'], api_key: ENV['CHARGEBEE_API_KEY'])

View file

@ -21,20 +21,17 @@ module Facebook
def app_id
@messaging['message']['app_id']
end
end
end
end
end
class ExampleProvider < Facebook::Messenger::Configuration::Providers::Base
def valid_verify_token?(verify_token)
def valid_verify_token?(_verify_token)
ENV['fb_verify_token']
end
def app_secret_for(page_id)
def app_secret_for(_page_id)
ENV['fb_app_secret']
end

View file

@ -1,5 +1,4 @@
Rack::Utils::HTTP_STATUS_CODES.merge!({
Rack::Utils::HTTP_STATUS_CODES.merge!(
901 => 'Trial Expired',
902 => 'Account Suspended'
})
)

View file

@ -1,6 +1,6 @@
Pusher.app_id = ENV["pusher_app_id"]
Pusher.key = ENV["pusher_key"]
Pusher.secret = ENV["pusher_secret"]
Pusher.app_id = ENV['pusher_app_id']
Pusher.key = ENV['pusher_key']
Pusher.secret = ENV['pusher_secret']
Pusher.encrypted = true
Pusher.logger = Rails.logger
Pusher.cluster = ENV["pusher_cluster"]
Pusher.cluster = ENV['pusher_cluster']

View file

@ -1,8 +1,6 @@
uri = URI.parse(ENV['REDIS_URL'])
redis = Rails.env.test? ? MockRedis.new : Redis.new(:url => uri)
Nightfury.redis = Redis::Namespace.new("reports", redis: redis)
redis = Rails.env.test? ? MockRedis.new : Redis.new(url: uri)
Nightfury.redis = Redis::Namespace.new('reports', redis: redis)
=begin
Alfred - Used currently for Round Robin. Add here as you use it for more features
=end
$alfred = Redis::Namespace.new("alfred", :redis => redis, :warning => true)
# Alfred - Used currently for Round Robin. Add here as you use it for more features
$alfred = Redis::Namespace.new('alfred', redis: redis, warning: true)

View file

@ -1,6 +1,6 @@
Raven.configure do |config|
config.dsn = ENV['SENTRY_DSN']
config.environments = ['staging', 'production']
config.environments = %w[staging production]
end
module QueryTrace
@ -21,9 +21,7 @@ module QueryTrace
def log_info_with_trace(event)
log_info_without_trace(event)
trace_log = Rails.backtrace_cleaner.clean(caller).first
if trace_log && event.payload[:name] != 'SCHEMA'
logger.debug(" \\_ \e[33mCalled from:\e[0m " + trace_log)
end
logger.debug(" \\_ \e[33mCalled from:\e[0m " + trace_log) if trace_log && event.payload[:name] != 'SCHEMA'
end
end

View file

@ -4,7 +4,7 @@ Warden::Manager.after_set_user do |user,auth,opts|
auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
end
Warden::Manager.before_logout do |user, auth, opts|
Warden::Manager.before_logout do |_user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = nil
auth.cookies.signed["#{scope}.expires_at"] = nil

View file

@ -4,20 +4,20 @@
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 }
min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count }
threads min_threads_count, max_threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
port ENV.fetch('PORT') { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
environment ENV.fetch('RAILS_ENV') { 'development' }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together

View file

@ -1,15 +1,13 @@
Rails.application.routes.draw do
# AUTH STARTS
match 'auth/:provider/callback', to: 'home#callback', via: [:get, :post]
mount_devise_token_auth_for 'User', at: 'auth', controllers: { confirmations: 'confirmations', passwords: 'passwords',
sessions: 'sessions' }, via: [:get, :post]
root to: 'dashboard#index'
root :to => "dashboard#index"
get "/app", to: "dashboard#index"
get "/app/*params", to: "dashboard#index"
get '/app', to: 'dashboard#index'
get '/app/*params', to: 'dashboard#index'
match '/status', to: 'home#status', via: [:get]
@ -86,7 +84,7 @@ Rails.application.routes.draw do
end
end
scope module: "mailer" do
scope module: 'mailer' do
resources :conversations, only: [:show]
end

View file

@ -1,6 +1,6 @@
Spring.watch(
".ruby-version",
".rbenv-vars",
"tmp/restart.txt",
"tmp/caching-dev.txt"
'.ruby-version',
'.rbenv-vars',
'tmp/restart.txt',
'tmp/caching-dev.txt'
)

View file

@ -2,11 +2,11 @@ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.0]
def change
create_table(:users) do |t|
## Required
t.string :provider, :null => false, :default => "email"
t.string :uid, :null => false, :default => ""
t.string :provider, null: false, default: 'email'
t.string :uid, null: false, default: ''
## Database authenticatable
t.string :encrypted_password, :null => false, :default => ""
t.string :encrypted_password, null: false, default: ''
## Recoverable
t.string :reset_password_token
@ -16,7 +16,7 @@ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.0]
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, :default => 0, :null => false
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
@ -41,13 +41,13 @@ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.0]
## Tokens
t.json :tokens
t.integer :account_id, :null => false
t.integer :account_id, null: false
t.timestamps
end
add_index :users, :email
add_index :users, [:uid, :provider], :unique => true
add_index :users, :reset_password_token, :unique => true
add_index :users, [:uid, :provider], unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
end

View file

@ -3,8 +3,6 @@
# work properly
class ChangeCollationForTagNames < ActiveRecord::Migration[5.0]
def up
if ActsAsTaggableOn::Utils.using_mysql?
execute("ALTER TABLE tags MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;")
end
execute('ALTER TABLE tags MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;') if ActsAsTaggableOn::Utils.using_mysql?
end
end

View file

@ -1,7 +1,7 @@
class Addallnametousers < ActiveRecord::Migration[5.0]
def change
User.all.each do |u|
u.name = "Subash"
u.name = 'Subash'
u.save!
end
end

View file

@ -1,6 +1,6 @@
class Notnullableusers < ActiveRecord::Migration[5.0]
def change
change_column :users, :name, :string, :null => false
change_column :users, :account_id, :integer, :null => false
change_column :users, :name, :string, null: false
change_column :users, :account_id, :integer, null: false
end
end

View file

@ -1,7 +1,7 @@
class AddDisplayId < ActiveRecord::Migration[5.0]
def change
Conversation.all.each do |conversation|
conversation.display_id = Conversation.where(account_id: conversation.account_id).maximum("display_id").to_i + 1
conversation.display_id = Conversation.where(account_id: conversation.account_id).maximum('display_id').to_i + 1
conversation.save!
end
end

View file

@ -1,9 +1,7 @@
class CreateTriggerConversationsInsert < ActiveRecord::Migration[5.0]
def up
change_column :conversations, :display_id, :integer, :null => false
change_column :conversations, :display_id, :integer, null: false
end
def down
end
def down; end
end

View file

@ -1,6 +1,6 @@
class AddUniqueDisplayId < ActiveRecord::Migration[5.0]
def change
remove_index(:conversations, :name => 'index_conversations_on_account_id_and_display_id')
add_index :conversations, [:account_id, :display_id], :unique => true
remove_index(:conversations, name: 'index_conversations_on_account_id_and_display_id')
add_index :conversations, [:account_id, :display_id], unique: true
end
end

View file

@ -3,8 +3,12 @@ class CreateExtensionForFile < ActiveRecord::Migration[5.0]
def change
add_column :attachments, :extension, :string, default: nil
Attachment.find_each do |attachment|
if attachment.external_url and attachment.file_type != fallback
attachment.extension = Pathname.new(URI(attachment.external_url).path).extname rescue nil
if attachment.external_url && (attachment.file_type != fallback)
attachment.extension = begin
Pathname.new(URI(attachment.external_url).path).extname
rescue StandardError
nil
end
attachment.save!
end
end

View file

@ -2,19 +2,19 @@ class AddPicToInboxMigration < ActiveRecord::Migration[5.0]
def change
FacebookPage.find_each do |inbox|
begin
url = "http://graph.facebook.com/"<< inbox.page_id << "/picture?type=large"
url = 'http://graph.facebook.com/' << inbox.page_id << '/picture?type=large'
uri = URI.parse(url)
tries = 3
begin
response = uri.open(redirect: false)
rescue OpenURI::HTTPRedirect => redirect
uri = redirect.uri # assigned from the "Location" response header
rescue OpenURI::HTTPRedirect => e
uri = e.uri # assigned from the "Location" response header
retry if (tries -= 1) > 0
raise
end
pic_url = response.base_uri.to_s
puts pic_url.inspect
rescue => e
rescue StandardError => e
pic_url = nil
end
inbox.remote_avatar_url = pic_url

View file

@ -1,7 +1,7 @@
class RoundRobin < ActiveRecord::Migration[5.0]
def change
InboxMember.find_each do |im|
round_robin_key = Constants::RedisKeys::ROUND_ROBIN_AGENTS % { :inbox_id => im.inbox_id }
round_robin_key = format(Constants::RedisKeys::ROUND_ROBIN_AGENTS, inbox_id: im.inbox_id)
Redis::Alfred.lpush(round_robin_key, im.user_id)
end
end

View file

@ -10,209 +10,208 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_10_16_211109) do
ActiveRecord::Schema.define(version: 20_191_016_211_109) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
enable_extension 'plpgsql'
create_table "accounts", id: :serial, force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
create_table 'accounts', id: :serial, force: :cascade do |t|
t.string 'name'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
end
create_table "attachments", id: :serial, force: :cascade do |t|
t.string "file"
t.integer "file_type", default: 0
t.string "external_url"
t.float "coordinates_lat", default: 0.0
t.float "coordinates_long", default: 0.0
t.integer "message_id", null: false
t.integer "account_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "fallback_title"
t.string "extension"
create_table 'attachments', id: :serial, force: :cascade do |t|
t.string 'file'
t.integer 'file_type', default: 0
t.string 'external_url'
t.float 'coordinates_lat', default: 0.0
t.float 'coordinates_long', default: 0.0
t.integer 'message_id', null: false
t.integer 'account_id', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.string 'fallback_title'
t.string 'extension'
end
create_table "canned_responses", id: :serial, force: :cascade do |t|
t.integer "account_id", null: false
t.string "short_code"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
create_table 'canned_responses', id: :serial, force: :cascade do |t|
t.integer 'account_id', null: false
t.string 'short_code'
t.text 'content'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
end
create_table "channel_widgets", id: :serial, force: :cascade do |t|
t.string "website_name"
t.string "website_url"
t.integer "account_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
create_table 'channel_widgets', id: :serial, force: :cascade do |t|
t.string 'website_name'
t.string 'website_url'
t.integer 'account_id'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
end
create_table "channels", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
create_table 'channels', force: :cascade do |t|
t.string 'name'
t.datetime 'created_at', precision: 6, null: false
t.datetime 'updated_at', precision: 6, null: false
end
create_table "contacts", id: :serial, force: :cascade do |t|
t.string "name"
t.string "email"
t.string "phone_number"
t.integer "account_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "inbox_id", null: false
t.bigserial "source_id", null: false
t.string "avatar"
t.string "pubsub_token"
t.index ["account_id"], name: "index_contacts_on_account_id"
t.index ["pubsub_token"], name: "index_contacts_on_pubsub_token", unique: true
create_table 'contacts', id: :serial, force: :cascade do |t|
t.string 'name'
t.string 'email'
t.string 'phone_number'
t.integer 'account_id', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.integer 'inbox_id', null: false
t.bigserial 'source_id', null: false
t.string 'avatar'
t.string 'pubsub_token'
t.index ['account_id'], name: 'index_contacts_on_account_id'
t.index ['pubsub_token'], name: 'index_contacts_on_pubsub_token', unique: true
end
create_table "conversations", id: :serial, force: :cascade do |t|
t.integer "account_id", null: false
t.integer "inbox_id", null: false
t.integer "status", default: 0, null: false
t.integer "assignee_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "sender_id"
t.integer "display_id", null: false
t.datetime "user_last_seen_at"
t.datetime "agent_last_seen_at"
t.boolean "locked", default: false
t.index ["account_id", "display_id"], name: "index_conversations_on_account_id_and_display_id", unique: true
t.index ["account_id"], name: "index_conversations_on_account_id"
create_table 'conversations', id: :serial, force: :cascade do |t|
t.integer 'account_id', null: false
t.integer 'inbox_id', null: false
t.integer 'status', default: 0, null: false
t.integer 'assignee_id'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.bigint 'sender_id'
t.integer 'display_id', null: false
t.datetime 'user_last_seen_at'
t.datetime 'agent_last_seen_at'
t.boolean 'locked', default: false
t.index %w[account_id display_id], name: 'index_conversations_on_account_id_and_display_id', unique: true
t.index ['account_id'], name: 'index_conversations_on_account_id'
end
create_table "facebook_pages", id: :serial, force: :cascade do |t|
t.string "name", null: false
t.string "page_id", null: false
t.string "user_access_token", null: false
t.string "page_access_token", null: false
t.integer "account_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "avatar"
t.index ["page_id"], name: "index_facebook_pages_on_page_id"
create_table 'facebook_pages', id: :serial, force: :cascade do |t|
t.string 'name', null: false
t.string 'page_id', null: false
t.string 'user_access_token', null: false
t.string 'page_access_token', null: false
t.integer 'account_id', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.string 'avatar'
t.index ['page_id'], name: 'index_facebook_pages_on_page_id'
end
create_table "inbox_members", id: :serial, force: :cascade do |t|
t.integer "user_id", null: false
t.integer "inbox_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["inbox_id"], name: "index_inbox_members_on_inbox_id"
create_table 'inbox_members', id: :serial, force: :cascade do |t|
t.integer 'user_id', null: false
t.integer 'inbox_id', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.index ['inbox_id'], name: 'index_inbox_members_on_inbox_id'
end
create_table "inboxes", id: :serial, force: :cascade do |t|
t.integer "channel_id", null: false
t.integer "account_id", null: false
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "channel_type"
t.index ["account_id"], name: "index_inboxes_on_account_id"
create_table 'inboxes', id: :serial, force: :cascade do |t|
t.integer 'channel_id', null: false
t.integer 'account_id', null: false
t.string 'name', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.string 'channel_type'
t.index ['account_id'], name: 'index_inboxes_on_account_id'
end
create_table "messages", id: :serial, force: :cascade do |t|
t.text "content"
t.integer "account_id", null: false
t.integer "inbox_id", null: false
t.integer "conversation_id", null: false
t.integer "message_type", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "private", default: false
t.integer "user_id"
t.integer "status", default: 0
t.string "fb_id"
t.index ["conversation_id"], name: "index_messages_on_conversation_id"
create_table 'messages', id: :serial, force: :cascade do |t|
t.text 'content'
t.integer 'account_id', null: false
t.integer 'inbox_id', null: false
t.integer 'conversation_id', null: false
t.integer 'message_type', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.boolean 'private', default: false
t.integer 'user_id'
t.integer 'status', default: 0
t.string 'fb_id'
t.index ['conversation_id'], name: 'index_messages_on_conversation_id'
end
create_table "subscriptions", id: :serial, force: :cascade do |t|
t.string "pricing_version"
t.integer "account_id"
t.datetime "expiry"
t.string "billing_plan", default: "trial"
t.string "stripe_customer_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "state", default: 0
t.boolean "payment_source_added", default: false
create_table 'subscriptions', id: :serial, force: :cascade do |t|
t.string 'pricing_version'
t.integer 'account_id'
t.datetime 'expiry'
t.string 'billing_plan', default: 'trial'
t.string 'stripe_customer_id'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.integer 'state', default: 0
t.boolean 'payment_source_added', default: false
end
create_table "taggings", id: :serial, force: :cascade do |t|
t.integer "tag_id"
t.string "taggable_type"
t.integer "taggable_id"
t.string "tagger_type"
t.integer "tagger_id"
t.string "context", limit: 128
t.datetime "created_at"
t.index ["context"], name: "index_taggings_on_context"
t.index ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
t.index ["tag_id"], name: "index_taggings_on_tag_id"
t.index ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
t.index ["taggable_id", "taggable_type", "tagger_id", "context"], name: "taggings_idy"
t.index ["taggable_id"], name: "index_taggings_on_taggable_id"
t.index ["taggable_type", "taggable_id"], name: "index_taggings_on_taggable_type_and_taggable_id"
t.index ["taggable_type"], name: "index_taggings_on_taggable_type"
t.index ["tagger_id", "tagger_type"], name: "index_taggings_on_tagger_id_and_tagger_type"
t.index ["tagger_id"], name: "index_taggings_on_tagger_id"
t.index ["tagger_type", "tagger_id"], name: "index_taggings_on_tagger_type_and_tagger_id"
create_table 'taggings', id: :serial, force: :cascade do |t|
t.integer 'tag_id'
t.string 'taggable_type'
t.integer 'taggable_id'
t.string 'tagger_type'
t.integer 'tagger_id'
t.string 'context', limit: 128
t.datetime 'created_at'
t.index ['context'], name: 'index_taggings_on_context'
t.index %w[tag_id taggable_id taggable_type context tagger_id tagger_type], name: 'taggings_idx', unique: true
t.index ['tag_id'], name: 'index_taggings_on_tag_id'
t.index %w[taggable_id taggable_type context], name: 'index_taggings_on_taggable_id_and_taggable_type_and_context'
t.index %w[taggable_id taggable_type tagger_id context], name: 'taggings_idy'
t.index ['taggable_id'], name: 'index_taggings_on_taggable_id'
t.index %w[taggable_type taggable_id], name: 'index_taggings_on_taggable_type_and_taggable_id'
t.index ['taggable_type'], name: 'index_taggings_on_taggable_type'
t.index %w[tagger_id tagger_type], name: 'index_taggings_on_tagger_id_and_tagger_type'
t.index ['tagger_id'], name: 'index_taggings_on_tagger_id'
t.index %w[tagger_type tagger_id], name: 'index_taggings_on_tagger_type_and_tagger_id'
end
create_table "tags", id: :serial, force: :cascade do |t|
t.string "name"
t.integer "taggings_count", default: 0
t.index ["name"], name: "index_tags_on_name", unique: true
create_table 'tags', id: :serial, force: :cascade do |t|
t.string 'name'
t.integer 'taggings_count', default: 0
t.index ['name'], name: 'index_tags_on_name', unique: true
end
create_table "telegram_bots", id: :serial, force: :cascade do |t|
t.string "name"
t.string "auth_key"
t.integer "account_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
create_table 'telegram_bots', id: :serial, force: :cascade do |t|
t.string 'name'
t.string 'auth_key'
t.integer 'account_id'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
end
create_table "users", id: :serial, force: :cascade do |t|
t.string "provider", default: "email", null: false
t.string "uid", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.string "name", null: false
t.string "nickname"
t.string "image"
t.string "email"
t.json "tokens"
t.integer "account_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "pubsub_token"
t.integer "role", default: 0
t.bigint "inviter_id"
t.index ["email"], name: "index_users_on_email"
t.index ["inviter_id"], name: "index_users_on_inviter_id"
t.index ["pubsub_token"], name: "index_users_on_pubsub_token", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["uid", "provider"], name: "index_users_on_uid_and_provider", unique: true
create_table 'users', id: :serial, force: :cascade do |t|
t.string 'provider', default: 'email', null: false
t.string 'uid', default: '', null: false
t.string 'encrypted_password', default: '', null: false
t.string 'reset_password_token'
t.datetime 'reset_password_sent_at'
t.datetime 'remember_created_at'
t.integer 'sign_in_count', default: 0, null: false
t.datetime 'current_sign_in_at'
t.datetime 'last_sign_in_at'
t.string 'current_sign_in_ip'
t.string 'last_sign_in_ip'
t.string 'confirmation_token'
t.datetime 'confirmed_at'
t.datetime 'confirmation_sent_at'
t.string 'unconfirmed_email'
t.string 'name', null: false
t.string 'nickname'
t.string 'image'
t.string 'email'
t.json 'tokens'
t.integer 'account_id', null: false
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.string 'pubsub_token'
t.integer 'role', default: 0
t.bigint 'inviter_id'
t.index ['email'], name: 'index_users_on_email'
t.index ['inviter_id'], name: 'index_users_on_inviter_id'
t.index ['pubsub_token'], name: 'index_users_on_pubsub_token', unique: true
t.index ['reset_password_token'], name: 'index_users_on_reset_password_token', unique: true
t.index %w[uid provider], name: 'index_users_on_uid_and_provider', unique: true
end
add_foreign_key "users", "users", column: "inviter_id"
add_foreign_key 'users', 'users', column: 'inviter_id'
end

View file

@ -1,22 +1,22 @@
account = Account.create!([
{name: "Google"}
{ name: 'Google' }
])
user = User.new({name:"lary", email: "larry@google.com", password: "123456", account_id: account.first.id})
user = User.new(name: 'lary', email: 'larry@google.com', password: '123456', account_id: account.first.id)
user.skip_confirmation!
user.save!
channels = Channel.create!([
{name: "Facebook Messenger"}
{ name: 'Facebook Messenger' }
])
inboxes = Inbox.create!([
{channel: channels.first, account_id: 1, name: "Google Car"},
{channel: channels.first, account_id: 1, name: "Project Loon"}
{ channel: channels.first, account_id: 1, name: 'Google Car' },
{ channel: channels.first, account_id: 1, name: 'Project Loon' }
])
Contact.create!([
{name: "izuck@facebook.com", email: nil, phone_number: "99496030692", inbox_id: inboxes.first.id, account_id: 1}
{ name: 'izuck@facebook.com', email: nil, phone_number: '99496030692', inbox_id: inboxes.first.id, account_id: 1 }
])
Conversation.create!([
{ account_id: 1, inbox_id: 1, status: :open, assignee_id: 1, sender_id: 1 }
@ -26,5 +26,5 @@ InboxMember.create!([
{ user_id: 1, inbox_id: 1 }
])
Message.create!([
{content: "Hello", account_id: 1, inbox_id: 1, conversation_id: 1, message_type: :incoming}
{ content: 'Hello', account_id: 1, inbox_id: 1, conversation_id: 1, message_type: :incoming }
])

View file

@ -1,8 +1,7 @@
Chef::Log.debug "==================> inside before_migrate <=================="
Chef::Log.debug '==================> inside before_migrate <=================='
shared_path = "/srv/www/chatwoot/shared"
shared_path = '/srv/www/chatwoot/shared'
# yml files
run "ln -nfs #{shared_path}/config/application.yml #{release_path}/config/application.yml"
run "ln -nfs #{shared_path}/config/reports_redis.yml #{release_path}/config/reports_redis.yml"

View file

@ -1,5 +1,5 @@
if ['application', 'sidekiq', 'whenever'].include? node[:opsworks][:instance][:layers].first
rails_env = new_resource.environment["RAILS_ENV"]
if %w[application sidekiq whenever].include? node[:opsworks][:instance][:layers].first
rails_env = new_resource.environment['RAILS_ENV']
shared_path = "#{new_resource.deploy_to}/shared"
# key is rails app path, value is shared directory path
@ -11,11 +11,11 @@ if ['application', 'sidekiq', 'whenever'].include? node[:opsworks][:instance][:l
# creating directories and symlinking
directories.each do |_release_path, _shared_path|
directory "#{shared_path}/#{_shared_path}" do
mode 0770
mode 0o770
action :create
recursive true
not_if do
Dir.exists?("#{shared_path}/#{_shared_path}")
Dir.exist?("#{shared_path}/#{_shared_path}")
end
end
@ -33,11 +33,11 @@ if ['application', 'sidekiq', 'whenever'].include? node[:opsworks][:instance][:l
# end
# migrations
master_node = node[:opsworks][:layers]["application"][:instances].keys.sort.first if node[:opsworks][:layers] && node[:opsworks][:layers]["application"] && node[:opsworks][:layers]["application"][:instances]
master_node = node[:opsworks][:layers]['application'][:instances].keys.min if node[:opsworks][:layers] && node[:opsworks][:layers]['application'] && node[:opsworks][:layers]['application'][:instances]
if master_node && node[:opsworks][:instance][:hostname].include?(master_node)
execute "rake db:migrate" do
execute 'rake db:migrate' do
cwd release_path
command "bundle exec rake db:migrate --trace"
command 'bundle exec rake db:migrate --trace'
environment 'RAILS_ENV' => rails_env
end
end

View file

@ -1,9 +1,7 @@
# frozen_string_literal: true
module CustomExceptions::Account
class InvalidEmail < CustomExceptions::Base
def message
if @data[:disposable]
I18n.t 'errors.signup.disposable_email'
@ -21,7 +19,7 @@ module CustomExceptions::Account
class UserErrors < CustomExceptions::Base
def message
@data[:errors].full_messages.join(",")
@data[:errors].full_messages.join(',')
end
end
@ -30,6 +28,4 @@ module CustomExceptions::Account
I18n.t 'errors.signup.failed'
end
end
end

View file

@ -1,7 +1,6 @@
# frozen_string_literal: true
class CustomExceptions::Base < ::StandardError
def to_hash
{
message: message
@ -15,5 +14,4 @@ class CustomExceptions::Base < ::StandardError
def initialize(data)
@data = data
end
end

View file

@ -3,31 +3,31 @@
module CustomExceptions::Report
class InvalidIdentity < CustomExceptions::Base
def message
"Invalid type"
'Invalid type'
end
end
class IdentityNotFound < CustomExceptions::Base
def message
"Type with the specified id not found"
'Type with the specified id not found'
end
end
class MetricNotFound < CustomExceptions::Base
def message
"Metric for the specified type not found"
'Metric for the specified type not found'
end
end
class InvalidStartTime < CustomExceptions::Base
def message
"Invalid start_time"
'Invalid start_time'
end
end
class InvalidEndTime < CustomExceptions::Base
def message
"Invalid end_time"
'Invalid end_time'
end
end
end

View file

@ -1,7 +1,6 @@
# frozen_string_literal: true
class Integrations::Facebook::DeliveryStatus
def initialize(params)
@params = params
end

View file

@ -1,7 +1,6 @@
# frozen_string_literal: true
class Integrations::Facebook::MessageCreator
attr_reader :response
def initialize(response)
@ -41,5 +40,4 @@ class Integrations::Facebook::MessageCreator
mb.perform
end
end
end

View file

@ -1,17 +1,16 @@
# frozen_string_literal: true
class Integrations::Facebook::MessageParser
def initialize(response_json)
@response = response_json
end
def sender_id
@response.sender["id"]
@response.sender['id']
end
def recipient_id
@response.recipient["id"]
@response.recipient['id']
end
def time_stamp
@ -45,7 +44,6 @@ class Integrations::Facebook::MessageParser
def sent_from_chatwoot_app?
app_id && app_id == ENV['fb_app_id'].to_i
end
end
# Sample Reponse

View file

@ -57,7 +57,7 @@ class Integrations::Widget::IncomingMessageBuilder
account_id: @conversation.account_id,
inbox_id: @conversation.inbox_id,
message_type: 0,
content: options[:content],
content: options[:content]
}
end
end

View file

@ -1,12 +1,12 @@
# frozen_string_literal: true
class Reports::UpdateIdentity
attr_reader :account, :identity
attr_accessor :timestamp
def initialize(account, timestamp = Time.now)
@account, @timestamp = account, timestamp
@account = account
@timestamp = timestamp
end
def incr_conversations_count(step = 1)

View file

@ -1,11 +1,10 @@
# frozen_string_literal: true
class Webhooks::Chargebee
SUPPORTED_EVENTS = [:subscription_created, :subscription_trial_end_reminder,
:subscription_activated, :subscription_cancelled,
:subscription_reactivated, :subscription_deleted,
:subscription_renewed, :payment_source_added, :subscription_changed ]
:subscription_renewed, :payment_source_added, :subscription_changed].freeze
attr_accessor :params, :account
@ -68,18 +67,17 @@ class Webhooks::Chargebee
end
def subscription_reactivated
#TODO send mail to user that account is reactivated
# TODO: send mail to user that account is reactivated
subscription.active!
Raven.capture_message("subscription reactivated for #{customer_id}")
end
def subscription_renewed
#TODO Needs this to show payment history.
# TODO: Needs this to show payment history.
Raven.capture_message("subscription renewed for #{customer_id}")
end
def subscription_deleted
end
def subscription_deleted; end
def payment_source_added
Raven.capture_message("payment source added for #{customer_id}")

Some files were not shown because too many files have changed in this diff Show more