Ejemplo n.º 1
0
def new_trip(request, **kwargs):
    route = Route.objects.get(id=kwargs.get('route_id'))
    # Create route + shape
    context = dict()
    context.update(kwargs)
    context['headsign_options'] = route.desc.split('-')
    context['service_times'] = Service.objects.all()

    if request.method == 'POST':
        request_params = request.POST.dict()

        shape_file = shapefile.Reader(shp=request.FILES['shape-file'],
                                      dbf=request.FILES['shape-file-dbf'])
        stops_reader = DictReaderStrip(request.FILES['stops-file'])

        # Check required fields are present in the stops csv
        expected_fields = set([
            'stop_sequence', 'lat', 'lon', 'stop_name', 'designation',
            'location_type'
        ])
        current_fields = set(stops_reader.fieldnames)

        if not expected_fields.issubset(current_fields):
            missing_fields = expected_fields.difference(current_fields)
            context[
                'error_message'] = 'The following columns are missing from the uploaded stops file: {}.'.format(
                    missing_fields)
            return render(request, 'myapp/new-trip.html', context)

        # Trip variables
        headsign = request_params['headsign']
        service_id = request_params['service-id']
        direction = request_params['inbound']
        route_id = kwargs['route_id']

        # corridor + 4 characters for the route number
        corridor = route.route_id[0]
        route_number = route.route_id[5:9]
        origin = request_params['origin']
        route_variation = request_params['route-variation']
        shape_id = "{}{}{}{}{}".format(corridor, route_number, origin,
                                       route_variation, direction)

        trip_id = shape_id

        with transaction.atomic():
            # Create new shape
            shape = Shape(feed_id=kwargs['feed_id'], shape_id=shape_id)
            shape.save()

            trip = Trip(trip_id=trip_id,
                        headsign=headsign,
                        service_id=service_id,
                        direction=direction,
                        route_id=route_id,
                        shape_id=shape.id)
            trip.save()

            # Create shape points from the uploaded shape files
            shapes = shape_file.shapes()

            sequence_start = 1001
            # The  trip line string is stored in layer 1
            for idx, point in enumerate(shapes[1].points):
                shape_point = ShapePoint(point='POINT ({} {})'.format(
                    point[0], point[1]),
                                         shape_id=shape.id,
                                         sequence=sequence_start + idx)

                shape_point.save()
            shape.update_geometry()

            start_seconds = 6 * 3600  # First trip is at 6am
            delta = 5 * 60  # % minutes

            for row in stops_reader:
                tmp = list(row['stop_name'].upper().replace(' ', ''))
                random.shuffle(tmp)
                stop_suffix = "".join(
                    tmp[:3])  # pick 3 characters from the shuffled stop name

                stop, created = Stop.objects.get_or_create(
                    point=geos.fromstr('POINT({} {})'.format(
                        row['lon'], row['lat'])),
                    feed_id=kwargs['feed_id'],
                    defaults={
                        'stop_id':
                        '{}{}{}{}'.format(corridor.zfill(2), row['designation']
                                          or 0, direction, stop_suffix),
                        'name':
                        row['stop_name'],
                        'location_type':
                        row['location_type'],
                    })

                trip.stoptime_set.add(
                    StopTime(stop_id=stop.id,
                             trip_id=trip.id,
                             stop_sequence=int(row['stop_sequence']) + 1,
                             arrival_time=start_seconds,
                             departure_time=start_seconds))
                start_seconds += delta

            trip.save()
            trip.update_geometry()
            trip.refresh_from_db()

            return http.HttpResponseRedirect(
                reverse('route_detail',
                        kwargs={
                            'pk': kwargs['route_id'],
                            'feed_id': kwargs['feed_id'],
                            'agency_id': kwargs['agency_id']
                        }))

    return render(request, 'myapp/new-trip.html', context)
Ejemplo n.º 2
0
def trip_detail_view(request, **kwargs):
    context = dict()

    trip = Trip.objects.get(pk=kwargs['pk'])
    trip.update_geometry()

    corridor_prefix = trip.route.route_id[0].zfill(2)
    inbound_status = trip.direction

    cursor = connection.cursor()
    cursor.execute(
        "SELECT n.id, n.latitude, n.longitude FROM multigtfs_ride r JOIN multigtfs_newstop n ON(n.ride_id=r.id)"
        " WHERE r.route_id = " + kwargs['route_id'])
    columns = [column[0] for column in cursor.description]
    new_stops = []

    for row in cursor.fetchall():
        new_stops.append(dict(zip(columns, row)))
    new_stops = yaml.load(json.dumps(new_stops))

    cursor.execute(
        "SELECT CONCAT(n.longitude, ' ', n.latitude) FROM multigtfs_ride r JOIN multigtfs_newroute n ON(n.ride_id=r.id)"
        " WHERE r.route_id = " + kwargs['route_id'])
    new_stops_route = []

    for row in cursor.fetchall():
        for i in row:
            i = i.encode('latin-1')
            i = i.translate(None, "()#")
            new_stops_route.append(i)
    stops = Stop.objects.filter(parent_station__isnull=True).order_by('name')

    context['agency_id'] = kwargs['agency_id']
    context['feed_id'] = kwargs['feed_id']
    context['route_id'] = kwargs['route_id']
    context['trip'] = trip
    context['stops'] = stops
    context['corridor'] = corridor_prefix
    context['inbound_status'] = inbound_status
    context['new_stops'] = new_stops
    context['new_stops_route'] = new_stops_route

    if request.method == 'POST':
        start_seconds = 6 * 3600  # First trip is at 6am
        delta = 5 * 60  # % minutes

        stop_ids = request.POST.getlist('stop_id')
        try:
            with transaction.atomic():
                # Delete existing stop times
                stop_times = trip.stoptime_set.all()
                for stop_time in stop_times:
                    stop_time.delete()

                # Add new stop times
                for index, stop_id in enumerate(stop_ids):
                    data = {
                        'stop_id': stop_id,
                        'trip_id': trip.id,
                        'stop_sequence': index + 1,
                        'arrival_time': start_seconds,
                        'departure_time': start_seconds
                    }
                    trip.stoptime_set.add(StopTime(**data))
                    start_seconds += delta

                    # Delete existing route shape

                    # trip.shape

                    # Add new route shape
        except DatabaseError as e:
            context[
                'error_message'] = 'An error occurred while processing your request.'

        return http.HttpResponseRedirect(reverse('trip_detail', kwargs=kwargs))
    return render(request, 'myapp/trip-detail.html', context)