Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Event validations #51

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
42 changes: 19 additions & 23 deletions app/controllers/events_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,40 +19,36 @@ def create
user = User.find_by(uuid: params[:user_id])
puts "New event params: #{event_params}"
@event = user.events.new(event_params)
@event.geocode_user_addresses #Need to get location first in order to get local time zone
@event.adjust_for_local_time # Fixes time here, before validation checks

if @event.save && @event.update_ride_id! && @event.update_estimate!
if @event.save
@event.schedule_bg_job
redirect_to "/?message=success#upcoming"
redirect_to "/?message=create_success#upcoming"
else
p @event
if @event.ride_id == nil
p @errors = ['Cannot find rides for departure address','Please make sure it is accurate']
@event.destroy
elsif @event.pickup_estimate == nil
p @errors = ['Distance cannot exceed 100 miles','You\'re crazy! Take a plane!']
@event.destroy
else
p @errors = @event.errors.full_messages
end
p @errors = @event.errors.full_messages
render "users/index", locals: {current_user: user}
end
end

def update
user = User.find_or_create_by(uuid: params[:user_id])
event = user.events.find_by(id: params[:id])
event.update_attributes(event_params)
event.adjust_for_local_time
event.update_ride_id!
redirect_to "/"
user = User.find_by(uuid: params[:user_id])
@event = user.events.find_by(id: params[:id])
@event.update_attributes(event_params)

if @event.save
@event.clear_bg_jobs
@event.schedule_bg_job
redirect_to "/?message=update_success#upcoming"
else
p @errors = @event.errors.full_messages
render "users/index", locals: {current_user: user}
end
end

def destroy
event = User.find_by(uuid: params[:user_id]).events.find_by(_id: params[:id])
event.delete
render json:{deleted_event: event}
@event = User.find_by(uuid: params[:user_id]).events.find_by(_id: params[:id])
@event.clear_bg_jobs
@event.destroy!
render json:{deleted_event: @event}
end

def ubertest
Expand Down
7 changes: 6 additions & 1 deletion app/controllers/home_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ def index
if current_user.phone #if they already have phone saved in DB
events = current_user.upcoming_sorted_events
@event = Event.new
@success = 'Event successfully scheduled' if params[:message] == 'success'
if params[:message] == 'create_success'
@success = 'Event successfully scheduled'
elsif params[:message] == 'update_success'
@success = 'Event successfully updated'
end

render "users/index", locals: {events: events}
puts "CURRENT USER: #{current_user}"
else #if they are logged in but don't have phone saved
Expand Down
52 changes: 37 additions & 15 deletions app/models/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ class Event
field :pickup_estimate, type: Integer
field :arrival_coords, type: Array, default: [] #format: [lat, lng]
field :depart_coords, type: Array, default: [] #format: [lat, lng]

validates_presence_of :name, :arrival_datetime
validate :arrival_address_found, :depart_address_found, :depart_arrival_address_not_same, :date_is_not_in_the_past

belongs_to :user

geocoded_by :geocode_user_addresses
before_validation :geocode,
:if => lambda{ |obj| obj.depart_address_changed? || obj.arrival_address_changed? }
before_validation :update_ride_id, :update_estimate
before_validation :adjust_for_local_time, #must happen after geocoding; is there a better way to ensure the order?
:if => lambda{ |obj| obj.arrival_datetime_changed? }

belongs_to :user
validates_presence_of :name, :arrival_datetime
validate :arrival_address_found, :depart_address_found, :depart_arrival_address_not_same, :date_is_not_in_the_past, :ride_id_not_found, :pickup_estimate_not_found


def geocode_user_addresses
Expand Down Expand Up @@ -70,15 +71,27 @@ def date_is_not_in_the_past
end
end

def ride_id_not_found #depends on successful "update_ride_id!""
unless ride_id
errors.add(:ride_name, "can't be found for that departure address; please confirm you entered it correctly, and that this type of ride is available in this city.")
end
end

def pickup_estimate_not_found #depends on successful "update_estimate!"
unless pickup_estimate
errors.add(:pickup_estimate, "unavailable. Check that the distance do not exceed 100 miles.")
end
end

######## TIME ZONE ADJUSTMENTS ########
def adjust_for_local_time
input_time = self.arrival_datetime #What the user entered; Mongo defaults to save as UTC
puts "Input time from user:"
p input_time = self.arrival_datetime #What the user entered; Mongo defaults to save as UTC
timezone = Timezone::Zone.new(latlon: self.depart_coords)
puts "Local timezone of event: #{timezone.zone}"

offset = timezone.utc_offset
self.timezone_offset = offset

self.arrival_datetime = input_time - offset #Fixes time in DB to reflect actual UTC time of the event
puts "Correct time of event in UTC: #{self.arrival_datetime}"
end
Expand All @@ -90,14 +103,14 @@ def arrival_datetime_local #Returns datetime in local timezone; same as what use
###### SCHEDULING BG JOBS AND CHECKING WHEN TO NOTIFY USER #######

def time_as_str
self.arrival_datetime.strftime("%l:%M%P")
self.arrival_datetime_local.strftime("%l:%M%P")
end

def estimated_duration
(self.duration_estimate + self.pickup_estimate).minutes
end

def update_estimate!
def update_estimate
puts "RIDE ESTIMATE RESPONSE:"
p response = request_estimate_response(self)

Expand All @@ -106,20 +119,24 @@ def update_estimate!
else
self.pickup_estimate = response['pickup_estimate']
self.duration_estimate = (response['trip']['duration_estimate']/60.0).ceil
self.save!

puts "ESTIMATED DURATION: #{estimated_duration} (minutes)"

response
end
end

def update_estimate!
response = update_estimate
self.save!
response
end

def notification_buffer
return 10.minutes
end

def time_to_notify_user
self.arrival_datetime - estimated_duration - notification_buffer
self.arrival_datetime_local - estimated_duration - notification_buffer
end

def schedule_bg_job
Expand All @@ -146,6 +163,12 @@ def schedule_bg_job
puts "************************************"
end

def clear_bg_jobs
puts "Clearing delayed Resque jobs:"
p Resque.remove_delayed(NotifyUserWorker, self) +
Resque.remove_delayed(RequestEstimateWorker, self)
end

def time_of_next_bg_job
if time_to_notify_user - Time.now > 180.minutes #more than 3 hours before need to notify
return time_to_notify_user - 180.minutes
Expand All @@ -154,7 +177,7 @@ def time_of_next_bg_job
end
end

def update_ride_id!
def update_ride_id
p "Updating ride ID"
p "SELF.USER.UBER_ACCESS_TOKEN: #{self.user.uber_access_token}"
p response = HTTParty.get("https://api.uber.com/v1/products",
Expand All @@ -168,11 +191,10 @@ def update_ride_id!
}
)

puts "Response from update_ride_id! method: #{response}"
puts "Response from update_ride_id method: #{response}"
response["products"].each do |product|
if self.ride_name.downcase == product["display_name"].downcase
self.ride_id = product["product_id"]
self.save!
return self.ride_id
end
end
Expand Down