remove the plan pitstop feature

Co-authored-by: Joachim Lusiardi <joachim@lusiardi.de>
Co-committed-by: Joachim Lusiardi <joachim@lusiardi.de>
This commit is contained in:
Joachim Lusiardi 2024-05-22 11:50:43 +02:00 committed by jlusiardi
parent b539361ca7
commit 208cb497aa
30 changed files with 4 additions and 574 deletions

View File

@ -54,21 +54,10 @@ def user_registered_sighandler(application, user, confirm_token):
tools.db_log_add(new_vehicle)
def assure_consumable(name, ext_id, unit):
if not Consumable.query.filter(Consumable.ext_id == ext_id).first():
c = Consumable(name, ext_id, unit)
db.session.add(c)
@app.before_first_request
def before_first_request():
db.create_all()
# make sure all consumables from tankerkoenig exist: diesel, e5, e10
assure_consumable('Diesel', 'diesel', 'L')
assure_consumable('Super','e5', 'L')
assure_consumable('Super E10','e10', 'L')
user_datastore.find_or_create_role(name='admin', description='Role for administrators')
user_datastore.find_or_create_role(name='user', description='Role for all users.')
db.session.commit()

View File

@ -14,15 +14,6 @@ vehicles_consumables = db.Table(
)
users_fillingstations = db.Table(
"users_fillingstations",
db.Column("user_id", db.Integer(), db.ForeignKey("user.id")),
db.Column(
"fillingstation_id", db.Integer(), db.ForeignKey("filling_station.int_id")
),
)
class Role(db.Model, RoleMixin):
"""
Entity to handle different roles for users: Typically user and admin exist
@ -57,9 +48,6 @@ class User(db.Model, UserMixin):
roles = db.relationship(
"Role", secondary=roles_users, backref=db.backref("users", lazy="dynamic")
)
favourite_filling_stations = db.relationship(
"FillingStation", secondary=users_fillingstations
)
def __repr__(self):
return '<User id="%r" email="%r" ' % (self.id, self.email)
@ -174,14 +162,12 @@ class Consumable(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), unique=True)
ext_id = db.Column(db.String(255))
unit = db.Column(db.String(255))
vehicles = db.relationship("Vehicle", secondary=vehicles_consumables)
vehicles = db.relationship("Vehicle", secondary=vehicles_consumables, viewonly=True)
def __init__(self, name, ext_id, unit):
def __init__(self, name, unit):
self.name = name
self.ext_id = ext_id
self.unit = unit
def __repr__(self):
@ -208,33 +194,3 @@ class Service(db.Model):
'<Service odometer="%r" date="%r" vehicle_id="%r" costs="%r" description="%r">'
% (self.odometer, self.date, self.vehicle_id, self.costs, self.description)
)
class FillingStation(db.Model):
int_id = db.Column(db.Integer, primary_key=True)
id = db.Column(db.String(40), unique=True, nullable=False)
name = db.Column(db.Text(), nullable=False)
street = db.Column(db.Text(), nullable=False)
place = db.Column(db.Text(), nullable=False)
houseNumber = db.Column(db.Text())
postCode = db.Column(db.Integer(), nullable=False)
brand = db.Column(db.Text(), nullable=False)
lat = db.Column(db.Numeric(8, 5), nullable=False)
lng = db.Column(db.Numeric(8, 5), nullable=False)
last_update = db.Column(db.DateTime)
diesel = db.Column(db.Numeric(10, 3), default=0)
e5 = db.Column(db.Numeric(10, 3), default=0)
e10 = db.Column(db.Numeric(10, 3), default=0)
open = db.Column(db.Boolean())
def as_dict(self):
res = {}
for c in self.__table__.columns:
val = getattr(self, c.name)
import decimal
if isinstance(val, decimal.Decimal):
val = float(val)
val = str(val)
res[c.name] = val
return res

View File

@ -10,14 +10,12 @@ class SelectConsumableForm(FlaskForm):
class CreateConsumableForm(FlaskForm):
name = StringField('Name', validators=[Length(1, 255)])
ext_id = SelectField('Tankerkönig ID', coerce=int)
unit = StringField('Unit', validators=[Length(1, 255)])
submit = SubmitField(label='Do it!')
class EditConsumableForm(FlaskForm):
name = StringField('Name', validators=[Length(1, 255)])
ext_id = SelectField('Tankerkönig ID', coerce=int)
unit = StringField('Unit', validators=[Length(1, 255)])
submit = SubmitField(label='Do it!')

View File

@ -3,5 +3,4 @@ from .admin import *
from .misc import *
from .pitstop import *
from .service import *
from .filling_stations import *
from .regular_cost import *

View File

@ -13,13 +13,9 @@ from .. import app, db, user_datastore
@app.route("/account", methods=["GET"])
@login_required
def get_account_page():
stations = [x.as_dict() for x in current_user.favourite_filling_stations]
for station in stations:
station["state"] = "favourite"
return render_template(
"account.html",
map_pos=(current_user.home_lat, current_user.home_long, current_user.home_zoom),
fs=json.dumps(stations),
)
@ -142,24 +138,3 @@ def delete_account():
return render_template("deleteAccountForm.html", form=form)
@app.route("/account/home", methods=["GET"])
@login_required
def get_users_home():
return jsonify(
{
"lat": float(current_user.home_lat),
"long": float(current_user.home_long),
"zoom": current_user.home_zoom,
}
)
@app.route("/account/home", methods=["POST"])
@login_required
def set_users_home():
current_user.home_lat = request.json["lat"]
current_user.home_long = request.json["long"]
current_user.home_zoom = request.json["zoom"]
db.session.commit()
return jsonify({})

View File

@ -22,8 +22,6 @@ def get_admin_page():
@login_required
def create_consumable():
form = CreateConsumableForm()
choices = [(0, ''), (1, 'diesel'), (2, 'e5'), (3, 'e10')]
form.ext_id.choices = choices
# preinitialize the defaults with potentially existing values from a try before
if form.name.data is not None:
@ -32,7 +30,7 @@ def create_consumable():
form.unit.default = form.unit.data
if form.validate_on_submit():
new_consumable = Consumable(form.name.data, choices[form.ext_id.data][1], form.unit.data)
new_consumable = Consumable(form.name.data, form.unit.data)
db.session.add(new_consumable)
try:
db.session.commit()
@ -72,28 +70,19 @@ def edit_consumable(cid):
return redirect(url_for('get_admin_page'))
form = EditConsumableForm()
choices = [(0, ''), (1, 'diesel'), (2, 'e5'), (3, 'e10')]
form.ext_id.choices = choices
form.name.default = consumable.name
form.unit.default = consumable.unit
form.ext_id.default = 3
for c in choices:
if c[1] == consumable.ext_id:
form.ext_id.default = c[0]
# preinitialize the defaults with potentially existing values from a try before
if form.name.data is not None:
form.name.default = form.name.data
if form.unit.data is not None:
form.unit.default = form.unit.data
if form.ext_id.data is not None:
form.ext_id.default = form.ext_id.data
if form.validate_on_submit():
consumable.name = form.name.data
consumable.unit = form.unit.data
consumable.ext_id = choices[form.ext_id.data][1]
try:
db.session.commit()
db_log_update(consumable)

View File

@ -1,61 +0,0 @@
from flask import request, jsonify
from flask_security import login_required
from flask_security.core import current_user
import requests
from ..entities import FillingStation
from .. import app, db
@app.route('/filling_stations/favourites/toggle/<fsid>')
def add_favourite_filling_stations(fsid):
favourite_ids = {x.id: x for x in current_user.favourite_filling_stations}
if fsid in favourite_ids:
current_user.favourite_filling_stations.remove(favourite_ids[fsid])
state = 'normal'
else:
fs = FillingStation.query.filter(FillingStation.id == fsid).first()
current_user.favourite_filling_stations.append(fs)
state = 'favourite'
db.session.commit()
return jsonify({'state': state})
@app.route('/filling_stations', methods=['GET'])
@login_required
def query_filling_stations():
api_key = app.config['TANKERKOENIG_API_KEY']
latitude = request.args.get('latitude')
longitude = request.args.get('longitude')
radius = request.args.get('radius', default=1.5)
gas_type = request.args.get('type', default='all')
sort = request.args.get('sort', default='dist')
url = 'https://creativecommons.tankerkoenig.de/json/list.php'
params = {
'lat': latitude, 'lng': longitude, 'rad': radius, 'apikey': api_key, 'type': gas_type, 'sort': sort
}
response = requests.get(url, params=params)
data = response.json()
for station in data['stations']:
fs = FillingStation.query.filter(FillingStation.id == station['id']).first()
if not fs:
fs = FillingStation()
fs.id = station['id']
fs.brand = station['brand']
fs.lat = station['lat']
fs.lng = station['lng']
fs.name = station['name']
fs.street = station['street']
fs.place = station['place']
fs.houseNumber = station['houseNumber']
fs.postCode = station['postCode']
db.session.add(fs)
if fs in current_user.favourite_filling_stations:
station['state'] = 'favourite'
else:
station['state'] = 'normal'
db.session.commit()
return jsonify(data)

View File

@ -20,7 +20,6 @@ from ..tools import (
db_log_add,
pitstop_service_key,
get_event_line_for_vehicle,
update_filling_station_prices,
RegularCostInstance,
calculate_regular_cost_instances,
get_users_active_vehicle,
@ -229,86 +228,3 @@ def get_pit_stops():
user["vehicles"].append(v)
return render_template("pitstops.html", user=user)
@app.route("/pitstops/plan/vehicle/select", methods=["GET", "POST"])
@login_required
def select_vehicle_for_plan_pitstop():
if len(current_user.vehicles) == 1:
return redirect(
url_for(
"select_consumable_for_plan_pitstop", vid=current_user.vehicles[0].id
)
)
form = SelectVehicleForm()
form.vehicle.choices = [(g.id, g.name) for g in current_user.vehicles]
if form.validate_on_submit():
return redirect(
url_for("select_consumable_for_plan_pitstop", vid=form.vehicle.data)
)
return render_template("selectVehicle.html", form=form)
@app.route(
"/pitstops/plan/vehicle/<int:vid>/consumable/select", methods=["GET", "POST"]
)
@login_required
def select_consumable_for_plan_pitstop(vid):
vehicle = Vehicle.query.get(vid)
if vehicle is None or vehicle not in current_user.vehicles:
return redirect(url_for("select_consumable_for_plan_pitstop"))
if len(vehicle.consumables) == 0:
flash("Please choose at least one consumable!", "warning")
return redirect(url_for("edit_vehicle", vid=vid))
if len(vehicle.consumables) == 1:
return redirect(
url_for("plan_pit_stop_form", vid=vid, cid=vehicle.consumables[0].id)
)
form = SelectConsumableForm()
form.consumable.choices = [(g.id, g.name) for g in vehicle.consumables]
if form.validate_on_submit():
return redirect(
url_for("plan_pit_stop_form", vid=vid, cid=form.consumable.data)
)
return render_template(
"selectConsumableForVehicle.html", vehicle=vehicle, form=form
)
@app.route(
"/pitstops/plan/vehicle/<int:vid>/consumable/<int:cid>", methods=["GET", "POST"]
)
@login_required
def plan_pit_stop_form(vid, cid):
vehicle = Vehicle.query.get(vid)
if vehicle is None or vehicle not in current_user.vehicles:
return redirect(url_for("select_vehicle_for_new_pitstop"))
consumable = Consumable.query.get(cid)
if consumable not in vehicle.consumables:
return redirect(url_for("select_consumable_for_new_pitstop", vid=vid))
update_filling_station_prices(
[x.id for x in current_user.favourite_filling_stations]
)
offers = []
for fs in current_user.favourite_filling_stations:
offers.append(
(
fs,
getattr(fs, consumable.ext_id),
)
)
return render_template(
"planPitStopForm.html", vehicle=vehicle, consumable=consumable, offers=offers
)

View File

@ -18,7 +18,6 @@ from ..tools import (
db_log_add,
pitstop_service_key,
get_event_line_for_vehicle,
update_filling_station_prices,
get_users_active_vehicle,
)
from .. import app, db

View File

@ -94,16 +94,6 @@ and (max-device-width : 568px) {
}
}
.filling_station_info {
margin: 5px;
border: 1px solid;
}
.filling_station_info img{
margin-top: 6px;
height:48px;
}
/*
* styling for sortable tables
*/
@ -120,7 +110,3 @@ th.headerSortUp {
th.headerSortDown {
background-image: url(../img/up.gif);
}
.filling_station_closed {
text-decoration: line-through;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 725 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -1,184 +0,0 @@
// initially display germany
var lat = 50.75653081787912,
lon = 9.262980794432847,
zoom = 5;
var map;
var filling_stations = {};
var filling_station_markers;
query_location = function(updater) {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
zoom = 11;
if(updater){
updater(lat, lon);
}
});
}
}
update_map = function() {
var lonLat = new OpenLayers.LonLat( lon, lat )
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
map.getProjectionObject() // to Spherical Mercator Projection
);
map.setCenter (lonLat, zoom);
}
load_filling_stations = function() {
var url = '/filling_stations?latitude=' + lat + '&longitude='+ lon + '&type=all&radius=5&sort=dist';
$.ajax({
type: 'GET',
url: url,
success: function(data) {
data.stations.forEach(function(station) {
if (!(station.id in filling_stations)) {
filling_stations[station.id] = station;
filling_stations[station.id].marker = false;
}
});
update_filling_station_markers();
}
});
}
clicked_on_filling_station_marker = function(station, marker) {
return function(data) {
$.ajax({
type: 'GET',
url: '/filling_stations/favourites/toggle/'+station.id,
dataType: 'json',
timeout: 1000,
success: function(data) {
if (data.state == 'favourite') {
marker.setUrl('/static/img/filling_station_favourite_marker.png');
} else {
marker.setUrl('/static/img/filling_station_marker.png');
}
},
contentType : 'application/json'
});
}
}
display_station_information = function(station) {
return function(event) {
var info = $('#station_info');
info.empty();
info.addClass('filling_station_info');
var cell1 = $('<div>', {'class':'col-md-8'})
var cell2 = $('<div>', {'class':'col-md-4'})
var img = $('<img>', {'src': '/static/logos/'+station.brand.toLowerCase()+'.png'});
// hide if the brand icon loads with error
img.error(function(){
$(this).hide();
});
var name = $('<div>').text(station.name);
var street_number = $('<div>').text(station.street + ' ' + station.houseNumber);
var postcode_place = $('<div>').text(station.postCode + ' ' + station.place);
info.append(cell1
.append(name)
.append(street_number)
.append(postcode_place))
.append(cell2
.append(img));
cell2.height(cell1.height());
};
}
update_filling_station_markers = function() {
for(id in filling_stations) {
var station = filling_stations[id];
if(!station.marker) {
var lonLat = new OpenLayers.LonLat(station.lng, station.lat)
.transform(new OpenLayers.Projection('EPSG:4326'), map.getProjectionObject());
if (station.state == 'favourite') {
var icon = new OpenLayers.Icon('/static/img/filling_station_favourite_marker.png');
} else {
var icon = new OpenLayers.Icon('/static/img/filling_station_marker.png');
}
var marker = new OpenLayers.Marker(lonLat, icon);
marker.events.register('click', marker, clicked_on_filling_station_marker(station, marker));
marker.events.register('mouseover', null, display_station_information(station));
filling_station_markers.addMarker(marker);
station.marker = true;
}
}
}
activate_map = function(map_div_id, button_ids, home_lat, home_long, home_zoom, init_stations) {
// resize to reasonable height
$('#' + map_div_id).css('height',0.75*($('#' + map_div_id).css('width')));
// init map
map = new OpenLayers.Map(map_div_id);
map.addLayer(new OpenLayers.Layer.OSM());
map.events.register('moveend', null, function(e){
var p = e.object.center.clone();
var p = p.transform(map.getProjectionObject(), 'EPSG:4326');
lon = p.lon;
lat = p.lat;
zoom = e.object.zoom;
});
filling_station_markers = new OpenLayers.Layer.Markers('Filling Stations');
map.addLayer(filling_station_markers);
// handle initial / favourite stations
filling_stations = init_stations;
update_filling_station_markers();
update_map();
if ((home_lat == 0) && (home_long == 0)) {
query_location(update_map);
} else {
lat = home_lat;
lon = home_long;
zoom = home_zoom;
update_map();
}
// get button
$('#'+button_ids[0]).click(function(e){
load_filling_stations();
});
// set home button
$('#'+button_ids[1]).click(function(e){
$.ajax({
type: 'POST',
url: '/account/home',
data: JSON.stringify({'long': lon, 'lat': lat, 'zoom': zoom}),
dataType: 'json',
timeout: 1000,
contentType : 'application/json'
});
});
// go home button
$('#'+button_ids[2]).click(function(e){
$.ajax({
type: 'GET',
url: '/account/home',
dataType: 'json',
timeout: 1000,
success: function(data) {
lat = data.lat;
lon = data.long;
zoom = data.zoom;
update_map();
},
contentType : 'application/json'
});
});
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -66,32 +66,6 @@
</tbody>
</table>
</div>
<div class="panel panel-default">
<div class="panel-heading">Filling Stations</div>
<div class="panel-body">
<div class="row">
<div class="col-md-6 olMap" style="height: 400px" id="mapdiv"></div>
<div class="col-md-6">
<div class="row">
<div class="btn-group col-md-12" role="group">
<button type="button" class="btn btn-default glyphicon glyphicon-home" id="go_home_button" title="go to home location"/>
<button type="button" class="btn btn-default glyphicon glyphicon-screenshot " id="set_home_button" title="set home location"/>
<button type="button" class="btn btn-default glyphicon glyphicon-download" id="get_button" title="load fuel stations"/>
</div>
</div>
<div id="station_info" class="row">
</div>
</div>
</div>
</div>
<script>
var lat = {{ map_pos[0] or 0 }};
var long = {{ map_pos[1] or 0 }};
var zoom = {{ map_pos[2] or 0 }};
var init_filling_station = JSON.parse({{ fs|tojson }});
activate_map('mapdiv', ['get_button', 'set_home_button', 'go_home_button'], lat, long, zoom, init_filling_station);
</script>
</div>
<div class="panel panel-default">
<div class="panel-heading">Account</div>
<div class="panel-body">

View File

@ -9,7 +9,6 @@
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.ext_id) }}
{{ render_field_with_errors(form.unit) }}
{{ render_field_with_errors(form.submit) }}
</form>

View File

@ -9,7 +9,6 @@
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.ext_id) }}
{{ render_field_with_errors(form.unit) }}
{{ render_field_with_errors(form.submit) }}
</form>

View File

@ -5,7 +5,6 @@
<li><a id='new_service_link' href='{{ url_for('select_vehicle_for_new_regular_cost') }}'>Create Regular Cost</a></li>
<li><a id='statistics_limk' href='{{ url_for('get_statistics') }}'>Statistics</a></li>
<li><a id='account_link' href='{{ url_for('get_account_page') }}'>Account</a></li>
<li><a id='plan_pitstop_link' href='{{ url_for('select_vehicle_for_plan_pitstop') }}'>Plan Pitstop</a></li>
{% if current_user.has_role('admin') %}
<li><a id='admin_link' href='{{ url_for('get_admin_page') }}'>Admin</a></li>
{% endif %}
@ -136,7 +135,6 @@
<script src="https://www.amcharts.com/lib/3/themes/patterns.js"></script>
<script src="https://openlayers.org/api/OpenLayers.js"></script>
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
<script src="{{ url_for('static', filename='js/fillingstations.js') }}"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">

View File

@ -1,57 +0,0 @@
{% extends "layout.html" %}
{% block body %}
<div class="col-md-2" ></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<h3>Plan Pitstop for '{{ vehicle.name }}'</h3>
Price comparision for {{ consumable.name }}:
<div class="table-responsive">
<table id="compare" class="table table-striped table-bordered table-condensed tablesorter">
<thead>
<tr>
<th>Filling Station</th>
<th>Price/{{ consumable.unit }}</th>
</tr>
</thead>
<tbody>
{% for offer in offers %}
<tr>
<td>
<div class="row filling_station_info " style="border: 0px">
<div class="col-md-8">
<div>{{ offer[0].name }}</div>
<div>{{ offer[0].street }} {{ offer[0].houseNumber }}</div>
<div>{{ offer[0].postCode }} {{ offer[0].place }}</div>
</div>
<div class="col-md-4" style="height: 60px;">
<img src="/static/logos/{{ offer[0].brand|lower }}.png">
</div>
</div>
</td>
<td>
{% if offer[0].open %}
{{ offer[1] }} €/{{ consumable.unit }}
{% else %}
Closed
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#compare").tablesorter({sortList: [[1,0]]});
$("img").error(function(){
$(this).hide();
});
});
</script>
<div class="col-md-2" ></div>
{% endblock %}

View File

@ -3,7 +3,7 @@ import requests
import logging
from datetime import date, datetime, timedelta
from .entities import Pitstop, FillingStation
from .entities import Pitstop
from . import db, app
@ -229,51 +229,6 @@ def chunks(l, n):
yield l[i : i + n]
def update_filling_station_prices(ids):
max_age = (datetime.now() - timedelta(minutes=15)).strftime("%Y-%m-%d %H:%M")
res = (
db.session.query(FillingStation)
.filter(FillingStation.id.in_(ids))
.filter(
or_(
FillingStation.last_update == None, FillingStation.last_update < max_age
)
)
.all()
)
if len(res) > 0:
id_map = {x.id: x for x in res}
query_ids = [x.id for x in res]
api_key = app.config["TANKERKOENIG_API_KEY"]
url = "https://creativecommons.tankerkoenig.de/json/prices.php"
# documentation tells us to query max 10 filling stations at a time...
for c in chunks(query_ids, 10):
params = {"apikey": api_key, "ids": ",".join(c)}
response = requests.get(url, params=params)
response_json = response.json()
if response_json["ok"]:
prices = response_json["prices"]
for price in prices:
id = price
station_status = prices[id]
id_map[id].open = station_status["status"] == "open"
if id_map[id].open:
id_map[id].diesel = station_status["diesel"]
id_map[id].e10 = station_status["e10"]
id_map[id].e5 = station_status["e5"]
id_map[id].last_update = datetime.now()
else:
logging.error(
"could not update filling stations because of {r} on URL {u}.".format(
r=str(response_json), u=response.url
)
)
db.session.commit()
def calculate_regular_cost_instances(vehicle):
data = []
for regular in vehicle.regulars: