class User < ActiveRecord::Base has_one :user_notification_setting has_many :ratings, :class_name => "VendorRating" has_many :repair_requests, :class_name => "AssetRepairRequest" has_many :user_notifications, :class_name => "NotificationUser" has_one :user_setting , :class_name => "UserNotificationSetting" has_and_belongs_to_many :roles, :join_table => :users_roles has_many :member, :dependent => :destroy accepts_nested_attributes_for :member has_many :organizations, :through => :member accepts_nested_attributes_for :organizations has_many :asset belongs_to :vacation has_one :user_vacation_info has_many :recurring_time_offs has_many :cancellations, :through => :shifts has_many :alerts has_and_belongs_to_many :certifications has_many :swaps, :through => :shifts has_many :tasks has_many :timeoffs, :dependent => :destroy has_many :recurring_time_offs, :dependent => :destroy has_and_belongs_to_many :jobs has_many :feedbacks has_many :notes, :dependent => :destroy accepts_nested_attributes_for :notes, :reject_if => lambda { |note| note[:content].blank? } accepts_nested_attributes_for :certifications has_many :schedules, :dependent => :destroy do def current_week cur_day = Time.zone.now.strftime('%Y-%m-%d') where("start_date <= '#{cur_day}' and end_date >= '#{cur_day}'") end def week_schedule_by_date(date) where("start_date <= '#{date}' and end_date >= '#{date}'") end def not_template where(:template_id => nil) end def schedule_by_date(start_date,end_date ) where("start_date >= '#{start_date}' and end_date <= '#{end_date}'") end def published where(:publish => true) end end has_many :shifts, :through => :schedules has_many :shift_trades, :through => :swaps do def affirmatives where(:status => 'affirmative') end end has_many :candidates, :dependent => :destroy do def initials where(:status => 'initial') end end has_attached_file :avatar, :styles => { :medium => "300x300!", :thumb => "100x100!" }, :default_url => "assets/missing.png" validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/ # validates_uniqueness_of :phone_number # validates_length_of :phone_number, :within => 6..13, if: Proc.new {|user| user.phone_number != nil} validates_uniqueness_of :email # validates :first_name, :last_name ,:email , :presence => true # validates :email, :uniqueness => true include PgSearch multisearchable :against => [:first_name, :last_name , :phone_number ,:email ] pg_search_scope :custom_search, :against => [:first_name, :last_name], :using => { :tsearch => {:prefix => true} } rolify acts_as_messageable devise :database_authenticatable, :registerable, :recoverable, :rememberable,:timeoutable, :trackable, :validatable,:lockable, :invitable, :omniauthable, :omniauth_providers => [:facebook,:google_oauth2,:twitter], :timeout_in => 8.hours # functions for Sripe of TrackMyAssets def stripe_create(token, plan_id , coupon) Stripe.api_key = "sk_test_eIdlWzka50kLJLNIqAIklamd" already_coupon = Stripe::Coupon.all already_coupon.data.each do |ex_coupon| if ex_coupon and !ex_coupon.id.blank? and ex_coupon.id == coupon @coupon_code = coupon else @coupon_code end end customer = Stripe::Customer.create( :description => "http://trackmyassets.biz", :plan => plan_id, :source => token , :coupon => @coupon_code ) return customer['id'] end # Stripe Coupon Checking def self.check_coupon(coupon_id) Stripe.api_key = "sk_test_eIdlWzka50kLJLNIqAIklamd" already_coupon = Stripe::Coupon.all already_coupon.data.each do |ex_coupon| if ex_coupon and !ex_coupon.id.blank? and ex_coupon.id == coupon_id @coupon = coupon_id else end end return @coupon end def rating_for_vendors(vendor) user_ratings_for_vendor = self.ratings.find_by_vendor_id(vendor.id) if !user_ratings_for_vendor user_ratings_for_vendor = vendor.ratings.new() user_ratings_for_vendor.user_id = self.id user_ratings_for_vendor.vendor_id = vendor.id end user_ratings_for_vendor end def notifications Notification.joins(:subscribers).where(notification_users: {user_id: self.id}).order(created_at: :desc) end def unread_notifications_count Notification.joins(:subscribers).where(notification_users: {user_id: self.id, seen: false}).order(created_at: :desc).count() end def to_json { :id => self.id, :email => self.email, :first_name => self.first_name, :last_name => self.last_name, :phone => self.phone_number, # :address => self.address, :roles => self.roles, :is_invited => !self.invitation_created_at.nil?, :is_accepted => !self.invitation_accepted_at.nil?, :is_locked => !self.locked_at.nil? } end def reset_user_password_token self.reset_password_token = SecureRandom.hex(3) self.reset_password_sent_at = Time.now.utc self.save!(validate: false) self.reset_password_token end def self.serialize_into_session(record) [record.id.to_s, record.authenticatable_salt] end def assign_api_token update_attribute(:api_token, SecureRandom.uuid) end def self.is_valid_user(email,password) @user = User.find_by_email(email) @user and @user.valid_password?(password) ? @user : nil end # Function for MT2W def send_shift_reminder(min) self.shifts.each do |shift| d = shift.due_date t = shift.start_time - min.to_i.minutes dt = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec) ShiftReminderWorker.perform_at(dt,self.email,"Your shift starts in #{min} minutes") end end def self.enable where(:disabled => false) end def self.find_for_facebook_oauth(auth) where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| already_user = User.where(:email => auth.info.email).first if !user.persisted? and auth.info.email and already_user.blank? user.provider = auth.provider user.uid = auth.uid user.email = auth.info.email user.password = Devise.friendly_token[0,20] user.first_name = auth.info.first_name user.last_name = auth.info.last_name # user.username = auth.info.name # assuming the user model has a name user.avatar = process_uri(auth.info.image) # assuming the user model has an image user.save(:validate=>false) return user elsif already_user return already_user else return false end end end def self.process_uri(uri) avatar_url = URI.parse(uri) avatar_url.scheme = 'https' avatar_url.to_s end def persisted? !(new_record? || destroyed?) end def update_card(subscriber, card_info) token = Stripe::Token.create( card: { number: card_info[:number], exp_month: card_info[:exp_month], exp_year: card_info[:exp_year], cvc: card_info[:cvc] } ) customer = Stripe::Customer.retrieve(subscriber.customer_id) card = customer.cards.create(card: token.id) card.save customer.default_card = card.id customer.save rescue Stripe::InvalidRequestError => e logger.error "Stripe Error While Updating Card Info: #{e.message}" errors.add :base, "#{e.message}" false end def get_role_name(org_id) member = self.member.where(:organization_id => org_id).first if member.present? return member.roles.first.name end end def get_role(org_id) member = self.member.where(:organization_id => org_id).first if member.present? return member.roles.first end end def can_do_this(org,setting) role = get_role_name(org.id) if (role == 'admin' || role == 'manager' || role == 'super_admin' || setting) return true else return false end end def self.find_for_twitter_oauth(auth, signed_in_resource=nil) user = User.where(:provider => auth.provider, :uid => auth.uid).first if user return user else user = User.new name = auth.info.name if name.include?(" ") user.first_name = name.split(" ").first user.last_name = name.split(" ").second else user.first_name = name user.last_name = " " end user.provider = auth.provider user.uid = auth.uid user.password = Devise.friendly_token[0,20] user.avatar = auth.info.image user.save(:validate=>false) return user end end def self.find_for_google_oauth2(access_token, signed_in_resource=nil) data = access_token.info user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first if user return user else registered_user = User.where(:email => data.email).first if registered_user return registered_user else user = User.new user.provider = access_token.provider user.uid = access_token.uid user.email = data["email"] user.password = Devise.friendly_token[0,20] user.first_name = data.first_name user.last_name = data.last_name user.avatar = data.image # assuming the user model has an image user.save(:validate=>false) return user end end end def idle?(date, s_time, e_time) shift = self.shifts.where( "due_date = :date AND ( ((start_time <= :s_time) AND (end_time >= :s_time)) OR ((:e_time >= start_time) AND (:e_time <= end_time)) OR ((start_time >= :s_time) AND (end_time <= :e_time)) ) ", {:date => date, :s_time => s_time, :e_time => e_time}).first false if shift true if shift.nil? end def notify_new_signup(org_id) emails = self.organizations.find_by_id(org_id).users.with_role(:manager).collect { |user| user.email } Notifier.delay.new_signup(emails,self.id) end def notify_alert(swap) if self.email_notify Notifier.delay.swap(self.email,swap.id) end if self.sms_notify content = "Swap Date : #{swap.shift.due_date} Start Time : #{swap.shift.start_time} End Time : #{swap.shift.end_time}" arguments = { :to => self.phone_number, :content => content } SmsWorker.perform_async(arguments) end end def notify_message(lateness) if self.email_notify Notifier.delay.late(self.email,lateness.id) end if self.sms_notify content = "Lateness Reason : #{lateness.reason} Start Time : #{lateness.shift.start_time} End Time : #{lateness.shift.end_time}" arguments = { :to => self.phone_number, :content => content } SmsWorker.perform_async(arguments) end end def send_instructions template = 'send_instructions' subject = "Reset password instructions" Notifier.delay.send_instructions(self, subject, template) end def name "#{first_name}"+ ' ' + "#{last_name}" end def mailboxer_email(object) self.email end def self.encode user JWT.encode({ user_id: user.id, exp: (DateTime.now + 30).to_i }, JWT_SECRET, JWT_ALGORITHM) end def self.for_oauth oauth oauth.get_data data = oauth.data user = find_by_email(data[:email]) user = user.present? ? user : data end def average_rating avg_rating = VendorRating.where(vendor_id: self.id).average("rating") return avg_rating.to_i end # Get Asset Vendor def get_asset_repair_vendor Asset.where("vendor_id = ?", self.id) end # Get Asset Purchase Vendor def get_asset_purchase_vendor Asset.where("purchase_vendor_id = ?", self.id) end end