Permalink
Browse files

rideshare backend functional mostly

  • Loading branch information...
thirtyseven committed Oct 4, 2011
1 parent 86d14aa commit ce8cbd69d0d6707659a78e818b0494008a59bf10
View
@@ -33,7 +33,7 @@
"""
import re
-from datetime import datetime
+from datetime import datetime, date
from django.conf import settings
from django.contrib import auth
@@ -86,14 +86,31 @@ def rides(bounds=None, **kwargs):
bbox = _str_to_bbox(bounds)
qset = (db.Ride.objects
.filter(route__isnull=False,
- route__bboverlaps=bbox))
+ route__bboverlaps=bbox,
+ depart_time__gte=date.today()))
else:
qset = (db.Ride.objects
.filter(route__isnull=False))
for ride in qset:
- yield {'id': ride.user.id,
+ yield {'id': ride.id,
'route': ride.route}
+def ride_request_update(request_id, status, user=None, **kwargs):
+ ride_request = (db.RideRequest.objects.filter(id=request_id)
+ .select_related("ride","ride__user"))
+ try:
+ req = ride_request[0]
+ except IndexError:
+ raise APIException("Request not found.")
+ if req.ride.user == user:
+ req.status=status
+ req.save()
+ return [{"id": req.id, "status": req.status }]
+ else:
+ raise APIException("You do not have permission to update this request.")
+
+
+
def attendee_info(username, **kwargs):
"""Get information for displaying attendee bubble
View
@@ -8,6 +8,7 @@
"""
from django import forms
+from django.forms.models import modelformset_factory
from occupywallst import models as db
@@ -141,5 +142,14 @@ def save(self):
class RideForm(forms.ModelForm):
class Meta:
model = db.Ride
- exclude = ['seats_used', 'route', 'route_data',]
-
+ exclude = ['seats_used', 'route', 'route_data', 'forum_post']
+
+class RideRequestForm(forms.Form):
+ info = forms.CharField(help_text="Want a seat? Tell us about yourself.",
+ widget=forms.widgets.Textarea)
+ def save(self, user, ride):
+ ride_request = db.RideRequest(user=user,ride=ride)
+ ride_request.status = "pending"
+ ride_request.info = self.cleaned_data['info']
+ ride_request.save()
+ return ride_request
@@ -250,3 +250,4 @@ a.button:active {
#sql-info .item:first-child { border-top: none; }
#sql-info .item p { margin: 0; padding: 0; text-indent: -3em; margin-left: 3em;
font: 8pt "DeJavu Sans Mono", monospace; }
+#mapright { width: 600px; font-size: 0.9em; vertical-align: top; }
@@ -7,11 +7,40 @@ var rides_init;
var map;
var dserv;
var markers = [];
+ var lines = {}
+ var current_line = null;
var philadelphia;
- $("#add_link").click(function() {
- $("#add_ride").toggle(100);
- return false;
+ function clear_map() {
+ $.each(lines, function(i, e) {
+ console.log(e);
+ e.setMap(null);
+ });
+ $.each(markers, function(i, e) {
+ e.setMap(null);
+ });
+ if (current_line) {
+ current_line.setMap(null);
+ }
+ markers = [];
+ lines = {}
+
+ }
+
+ $("form select[name='status']").change(function() {
+ var option = $(this).val();
+ var form = $(this).parent();
+ $.post(form.attr('action'), form.serialize(), function() {
+ var status = form.parent().parent().find(".req-status");
+ });
+ });
+
+ $("#id_waypoints").change(function() {
+ clear_map();
+ var waypoints = $(this).val().split("\n");
+ if (waypoints.length > 1) {
+ show_route(waypoints);
+ }
});
function init(args) {
@@ -25,7 +54,20 @@ var rides_init;
zoomControl: true,
scaleControl: true
});
- google.maps.event.addListener(map, "idle", update_rides);
+ if (args.update_rides) {
+ google.maps.event.addListener(map, "idle", update_rides);
+ }
+ if (args.initial_polyline) {
+ var bounds = new google.maps.LatLngBounds();
+ var polyline_arr = args.initial_polyline.map(function(e) {
+ var latlng = new google.maps.LatLng(e[0],e[1]);
+ bounds.extend(latlng);
+ return latlng;
+ })
+ var polyline = happy_line(polyline_arr);
+ map.fitBounds(bounds);
+
+ }
// $("#addroute").click(function() {
// ev.preventDefault();
// show_route($("textarea").val().split('\n'));
@@ -37,12 +79,17 @@ var rides_init;
var bounds = { bounds: map.getBounds().toUrlValue() };
$.getJSON("/api/safe/rides/", bounds, function(rides) {
+ clear_map();
rides.results.forEach(function(ride, i) {
- console.log(ride) ;
- happy_line(ride.route.map(function(p) {
+ var line = happy_line(ride.route.map(function(p) {
var point = new google.maps.LatLng(p[1],p[0]);
return point;
}));
+ google.maps.event.addListener(line, 'click', function(e) {
+ window.location = "/rides/"+ride.id+"/";
+ });
+ lines[ride.id]=line;
+ console.log(line);
});
});
}
@@ -75,7 +122,7 @@ var rides_init;
return line;
}
- function show_route(waypoints) {
+ function show_route(waypoints, info) {
var i;
var from = waypoints[0];
var to = waypoints[waypoints.length - 1];
@@ -99,8 +146,9 @@ var rides_init;
return;
}
var line = happy_line(result.routes[0].overview_path);
+ current_line = line;
google.maps.event.addListener(line, 'click', function(e) {
- var balloon = new google.maps.InfoWindow({content: 'we\'re driving from ' + from + '<br /> so you should carpool with us :3'});
+ var balloon = new google.maps.InfoWindow({content: info});
balloon.open(map, new google.maps.Marker({position: e.latLng}));
});
// if (glob.bounds) {
View
@@ -22,8 +22,9 @@
from django.contrib.gis.geos import Point, LineString
from django.contrib.auth.models import User, Group
from django.core.exceptions import ValidationError
-from django.db.models import F
-from django.db import transaction
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+from django.template.defaultfilters import slugify
from occupywallst.utils import jsonify
from occupywallst import geo
@@ -572,6 +573,7 @@ class Ride(models.Model):
Google's goofy compressed version of route coords.""")
info = models.TextField(blank=True, help_text="""
A long description written by user in markup.""")
+ forum_post = models.ForeignKey(ForumPost, null=True, blank=True)
is_deleted = models.BooleanField(default=False, editable=False,
help_text="""
Flag to indicate should no longer be listed on site.""")
@@ -595,12 +597,25 @@ def clean(self):
if len(self.waypoint_list) < 2:
raise ValidationError('Must have at least two waypoints')
- def update_from_maps(self):
+ @property
+ def pending_requests(self):
+ return self.requests.filter(status="pending")
+
+ @property
+ def accepted_requests(self):
+ return self.requests.filter(status="accepted")
+
+ def forum_title(self):
+ waypoints = self.waypoint_list
+ return "%s to %s on %s" % (
+ waypoints[0], waypoints[-1], self.depart_time.date())
+
+ def retrieve_route_from_google(self):
route = geo.directions(self.waypoint_list)
points = []
for waypoint in route:
points += \
- [ p[::-1] for p in waypoint['overview_polyline']['points']]
+ [ (x,y) for y,x in waypoint['overview_polyline']['points']]
self.route = LineString(points)
@property
@@ -609,7 +624,22 @@ def waypoint_list(self):
@property
def seats_avail(self):
- return self.seats_total - self.seats_used
+ return self.seats_total - self.accepted_requests.count()
+
+ @models.permalink
+ def get_absolute_url(self):
+ return ('occupywallst.views.ride_info', [self.id])
+
+
+@receiver(post_save, sender=Ride)
+def ride_save_callback(sender, instance, created, *args, **kwargs):
+ if created:
+ post = ForumPost(title=instance.forum_title(), author=instance.user)
+ post.slug = ("ride-%s-%s"
+ % (instance.user.username, slugify(instance.title)))
+ post.save()
+ instance.forum_post = post
+ instance.save()
class RideRequest(models.Model):
@@ -623,13 +653,13 @@ class RideRequest(models.Model):
('rejected', 'Rejected'),
)
- ride = models.ForeignKey(Ride, editable=False, unique=True,
+ ride = models.ForeignKey(Ride, editable=False,
related_name="requests", help_text="""
The ride the user wants to get in on.""")
- user = models.ForeignKey(User, editable=False, unique=True, help_text="""
+ user = models.ForeignKey(User, help_text="""
The user who needs a ride to the event.""")
status = models.CharField(max_length=32, choices=STATUS_CHOICES,
- help_text="""
+ default="pending", help_text="""
Current acceptance status of request.""")
info = models.TextField(blank=True, help_text="""
User explains why they think they deserve a ride.""")
@@ -639,6 +669,13 @@ class RideRequest(models.Model):
objects = models.GeoManager()
+ @property
+ def accepted(self):
+ return self.status=="accepted"
+ @property
+ def declined(self):
+ return self.status=="declined"
+
class Meta:
unique_together = ("ride", "user")
Oops, something went wrong.

0 comments on commit ce8cbd6

Please sign in to comment.