20 Commits
Jody ... live

Author SHA1 Message Date
15b7696dc2 Merge pull request 'main' (#13) from main into live
Reviewed-on: #13
2024-05-26 11:11:54 +02:00
69f077a0f5 Merge pull request 'sort vehicles by last activity' (#12) from sort_vehicles_by_last_entry_2 into main
Reviewed-on: #12
2024-05-25 21:51:28 +02:00
dfb07ae7ee sort vehicles by last activity 2024-05-25 17:53:51 +02:00
208cb497aa remove the plan pitstop feature
Co-authored-by: Joachim Lusiardi <joachim@lusiardi.de>
Co-committed-by: Joachim Lusiardi <joachim@lusiardi.de>
2024-05-22 11:50:43 +02:00
b539361ca7 Merge pull request 'Fix links to imprint and datenschutzerklärung' (#10) from fix_links into main
Reviewed-on: #10
2024-05-22 08:52:44 +02:00
091bfcd4ca Fix links to imprint and datenschutzerklärung 2024-05-22 08:50:13 +02:00
0f7c36a804 pin werkzeug to version 2.2.2 to prevent incompatibilities 2024-05-17 10:43:58 +02:00
3bfc2fc182 pin versions 2023-05-08 20:50:35 +02:00
802af2418a remove limitter 2023-04-17 21:25:02 +02:00
cd9fc4755e handle pitstops without costs properly 2022-05-13 16:48:08 +02:00
158c419747 Merge pull request 'Zeige Preisentwicklung von Consumables' (#7) from PR_7 into prepare2022
Reviewed-on: http://gitea.lusiardi.de/jlusiardi/rollerverbrauch/pulls/7
2022-05-13 16:32:16 +02:00
79e5fdf56b Zeige Preisentwicklung von Consumables 2022-05-12 17:27:51 -06:00
a9338805e2 add wsgi stuff 2021-12-21 18:22:00 +00:00
7f82a288da update db conf in production 2021-12-21 16:23:15 +00:00
8728d3028b update db conf in production 2021-12-21 16:21:00 +00:00
bc7e1591bd fix sorting for regular costs 2021-06-23 08:29:35 +02:00
673b671ab8 fix date of service 2021-06-22 21:49:32 +02:00
578b2c15d8 bugfix: could not create service 2021-06-22 21:39:49 +02:00
5cd06db1b6 Merge pull request 'vehicles can now be deactivated' (#6) from vehicles_can_be_deactivated into master
Reviewed-on: #6
2021-06-20 06:49:33 +00:00
3035006225 vehicles can now be deactivated 2021-06-20 08:43:46 +02:00
40 changed files with 265 additions and 719 deletions

View File

@@ -6,7 +6,6 @@ from flask_sqlalchemy import SQLAlchemy
import os import os
from config import config from config import config
from flask_security.forms import LoginForm from flask_security.forms import LoginForm
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address from flask_limiter.util import get_remote_address
from .forms import * from .forms import *
@@ -15,13 +14,6 @@ from .forms import *
app = Flask(__name__) app = Flask(__name__)
app.config.from_object(config[os.getenv('FLASK_CONFIG') or 'default']) app.config.from_object(config[os.getenv('FLASK_CONFIG') or 'default'])
# applies to all routes, so choose limits wisely!
limiter = Limiter(
app,
key_func=get_remote_address,
# default_limits=["500 per second"]
)
@app.errorhandler(429) @app.errorhandler(429)
def ratelimit_handler(e): def ratelimit_handler(e):
@@ -62,21 +54,10 @@ def user_registered_sighandler(application, user, confirm_token):
tools.db_log_add(new_vehicle) 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 @app.before_first_request
def before_first_request(): def before_first_request():
db.create_all() 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='admin', description='Role for administrators')
user_datastore.find_or_create_role(name='user', description='Role for all users.') user_datastore.find_or_create_role(name='user', description='Role for all users.')
db.session.commit() 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): class Role(db.Model, RoleMixin):
""" """
Entity to handle different roles for users: Typically user and admin exist Entity to handle different roles for users: Typically user and admin exist
@@ -57,9 +48,6 @@ class User(db.Model, UserMixin):
roles = db.relationship( roles = db.relationship(
"Role", secondary=roles_users, backref=db.backref("users", lazy="dynamic") "Role", secondary=roles_users, backref=db.backref("users", lazy="dynamic")
) )
favourite_filling_stations = db.relationship(
"FillingStation", secondary=users_fillingstations
)
def __repr__(self): def __repr__(self):
return '<User id="%r" email="%r" ' % (self.id, self.email) return '<User id="%r" email="%r" ' % (self.id, self.email)
@@ -82,6 +70,7 @@ class Vehicle(db.Model):
services = db.relationship("Service", order_by="asc(Service.odometer)") services = db.relationship("Service", order_by="asc(Service.odometer)")
regulars = db.relationship("RegularCost") regulars = db.relationship("RegularCost")
consumables = db.relationship("Consumable", secondary=vehicles_consumables) consumables = db.relationship("Consumable", secondary=vehicles_consumables)
is_active = db.Column(db.Boolean(), default=True)
# allow vehicle names to be duplicated between different owners but must still be uniq for each owner # allow vehicle names to be duplicated between different owners but must still be uniq for each owner
__table_args__ = (db.UniqueConstraint("owner_id", "name", name="_owner_name_uniq"),) __table_args__ = (db.UniqueConstraint("owner_id", "name", name="_owner_name_uniq"),)
@@ -173,14 +162,12 @@ class Consumable(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), unique=True) name = db.Column(db.String(255), unique=True)
ext_id = db.Column(db.String(255))
unit = 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.name = name
self.ext_id = ext_id
self.unit = unit self.unit = unit
def __repr__(self): def __repr__(self):
@@ -207,33 +194,3 @@ class Service(db.Model):
'<Service odometer="%r" date="%r" vehicle_id="%r" costs="%r" description="%r">' '<Service odometer="%r" date="%r" vehicle_id="%r" costs="%r" description="%r">'
% (self.odometer, self.date, self.vehicle_id, self.costs, self.description) % (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): class CreateConsumableForm(FlaskForm):
name = StringField('Name', validators=[Length(1, 255)]) name = StringField('Name', validators=[Length(1, 255)])
ext_id = SelectField('Tankerkönig ID', coerce=int)
unit = StringField('Unit', validators=[Length(1, 255)]) unit = StringField('Unit', validators=[Length(1, 255)])
submit = SubmitField(label='Do it!') submit = SubmitField(label='Do it!')
class EditConsumableForm(FlaskForm): class EditConsumableForm(FlaskForm):
name = StringField('Name', validators=[Length(1, 255)]) name = StringField('Name', validators=[Length(1, 255)])
ext_id = SelectField('Tankerkönig ID', coerce=int)
unit = StringField('Unit', validators=[Length(1, 255)]) unit = StringField('Unit', validators=[Length(1, 255)])
submit = SubmitField(label='Do it!') submit = SubmitField(label='Do it!')

View File

@@ -6,7 +6,7 @@ from .checks import *
class CreateServiceForm(FlaskForm): class CreateServiceForm(FlaskForm):
date = DateField('Date of Pitstop') date = DateField('Date of Service')
odometer = IntegerField('Odometer (km)', validators=[odometer_date_check]) odometer = IntegerField('Odometer (km)', validators=[odometer_date_check])
costs = DecimalField('Costs (€, overall)', places=2, validators=[costs_check]) costs = DecimalField('Costs (€, overall)', places=2, validators=[costs_check])
description = TextAreaField('Description', validators=[Length(1, 4096)]) description = TextAreaField('Description', validators=[Length(1, 4096)])
@@ -72,4 +72,4 @@ class EditServiceForm(FlaskForm):
'litres': 'Litres must be higher than 0.01 L.', 'litres': 'Litres must be higher than 0.01 L.',
'costs': 'Costs must be higher than 0.01 €.' 'costs': 'Costs must be higher than 0.01 €.'
} }
return messages return messages

View File

@@ -1,20 +1,25 @@
from flask_wtf import FlaskForm from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField, SelectMultipleField from wtforms import (
StringField,
SubmitField,
SelectField,
SelectMultipleField,
BooleanField,
)
from wtforms.validators import Length from wtforms.validators import Length
class SelectVehicleForm(FlaskForm): class SelectVehicleForm(FlaskForm):
vehicle = SelectField('Vehicle', coerce=int) vehicle = SelectField("Vehicle", coerce=int)
submit = SubmitField(label='Do it!') submit = SubmitField(label="Do it!")
class EditVehicleForm(FlaskForm): class EditVehicleForm(FlaskForm):
name = StringField('Name', validators=[Length(1, 255)]) name = StringField("Name", validators=[Length(1, 255)])
consumables = SelectMultipleField('Consumables', coerce=int,validators=[]) consumables = SelectMultipleField("Consumables", coerce=int, validators=[])
submit = SubmitField(label='Do it!') is_active = BooleanField("Is active")
submit = SubmitField(label="Do it!")
class DeleteVehicleForm(FlaskForm): class DeleteVehicleForm(FlaskForm):
submit = SubmitField(label='Do it!') submit = SubmitField(label="Do it!")

View File

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

View File

@@ -10,25 +10,23 @@ from ..tools import db_log_update, db_log_delete, db_log_add
from .. import app, db, user_datastore from .. import app, db, user_datastore
@app.route('/account', methods=['GET']) @app.route("/account", methods=["GET"])
@login_required @login_required
def get_account_page(): def get_account_page():
stations = [x.as_dict() for x in current_user.favourite_filling_stations] return render_template(
for station in stations: "account.html",
station['state'] = 'favourite' map_pos=(current_user.home_lat, current_user.home_long, current_user.home_zoom),
return render_template('account.html', )
map_pos=(current_user.home_lat, current_user.home_long, current_user.home_zoom),
fs=json.dumps(stations))
@app.route('/account/vehicle/edit/<int:vid>', methods=['GET', 'POST']) @app.route("/account/vehicle/edit/<int:vid>", methods=["GET", "POST"])
@login_required @login_required
def edit_vehicle(vid): def edit_vehicle(vid):
vehicle = Vehicle.query.filter(Vehicle.id == vid).first() vehicle = Vehicle.query.filter(Vehicle.id == vid).first()
# prevent edit of foreign vehicles # prevent edit of foreign vehicles
if vehicle not in current_user.vehicles: if vehicle not in current_user.vehicles:
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
form = EditVehicleForm() form = EditVehicleForm()
form.consumables.choices = [(g.id, g.name) for g in Consumable.query.all()] form.consumables.choices = [(g.id, g.name) for g in Consumable.query.all()]
@@ -39,8 +37,12 @@ def edit_vehicle(vid):
if form.name.data is not None: if form.name.data is not None:
form.name.default = form.name.data form.name.default = form.name.data
if form.is_active.data is not None:
form.is_active.default = form.is_active.data
if form.validate_on_submit(): if form.validate_on_submit():
vehicle.name = form.name.data vehicle.name = form.name.data
vehicle.is_active = form.is_active.data
# we cannot delete consumables where there are pitstops for => report error # we cannot delete consumables where there are pitstops for => report error
vehicle.consumables = [] vehicle.consumables = []
for consumable_id in form.consumables.data: for consumable_id in form.consumables.data:
@@ -53,25 +55,26 @@ def edit_vehicle(vid):
except IntegrityError: except IntegrityError:
db.session.rollback() db.session.rollback()
form.name.errors.append('"%s" is not unique.' % (form.name.data)) form.name.errors.append('"%s" is not unique.' % (form.name.data))
return render_template('editVehicleForm.html', form=form) return render_template("editVehicleForm.html", form=form)
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
form.name.default = vehicle.name form.name.default = vehicle.name
form.is_active.default = vehicle.is_active
form.process() form.process()
return render_template('editVehicleForm.html', form=form, vehicle=vehicle) return render_template("editVehicleForm.html", form=form, vehicle=vehicle)
@app.route('/account/vehicle/delete/<int:vid>', methods=['GET', 'POST']) @app.route("/account/vehicle/delete/<int:vid>", methods=["GET", "POST"])
@login_required @login_required
def delete_vehicle(vid): def delete_vehicle(vid):
vehicle = Vehicle.query.filter(Vehicle.id == vid).first() vehicle = Vehicle.query.filter(Vehicle.id == vid).first()
# prevent deletion of foreign vehicles # prevent deletion of foreign vehicles
if vehicle not in current_user.vehicles: if vehicle not in current_user.vehicles:
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
if len(current_user.vehicles) == 1: if len(current_user.vehicles) == 1:
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
form = DeleteVehicleForm() form = DeleteVehicleForm()
@@ -79,12 +82,12 @@ def delete_vehicle(vid):
db.session.delete(vehicle) db.session.delete(vehicle)
db.session.commit() db.session.commit()
db_log_delete(vehicle) db_log_delete(vehicle)
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
return render_template('deleteVehicleForm.html', form=form, vehicle=vehicle) return render_template("deleteVehicleForm.html", form=form, vehicle=vehicle)
@app.route('/account/vehicle/create', methods=['GET', 'POST']) @app.route("/account/vehicle/create", methods=["GET", "POST"])
@login_required @login_required
def create_vehicle(): def create_vehicle():
form = EditVehicleForm() form = EditVehicleForm()
@@ -100,8 +103,8 @@ def create_vehicle():
if form.validate_on_submit(): if form.validate_on_submit():
if len(form.consumables.data) == 0: if len(form.consumables.data) == 0:
form.consumables.errors.append('At least one consumable must be selected.') form.consumables.errors.append("At least one consumable must be selected.")
return render_template('createVehicleForm.html', form=form) return render_template("createVehicleForm.html", form=form)
vehicle_name = form.name.data vehicle_name = form.name.data
new_vehicle = Vehicle(vehicle_name) new_vehicle = Vehicle(vehicle_name)
@@ -117,13 +120,13 @@ def create_vehicle():
except IntegrityError: except IntegrityError:
db.session.rollback() db.session.rollback()
form.name.errors.append('"%s" is not unique.' % (form.name.data)) form.name.errors.append('"%s" is not unique.' % (form.name.data))
return render_template('createVehicleForm.html', form=form) return render_template("createVehicleForm.html", form=form)
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
return render_template('createVehicleForm.html', form=form) return render_template("createVehicleForm.html", form=form)
@app.route('/account/delete', methods=['GET', 'POST']) @app.route("/account/delete", methods=["GET", "POST"])
@login_required @login_required
def delete_account(): def delete_account():
form = DeleteAccountForm() form = DeleteAccountForm()
@@ -131,25 +134,7 @@ def delete_account():
if form.validate_on_submit(): if form.validate_on_submit():
user_datastore.delete_user(current_user) user_datastore.delete_user(current_user)
db.session.commit() db.session.commit()
return redirect(url_for('index')) return redirect(url_for("index"))
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({})
return render_template("deleteAccountForm.html", form=form)

View File

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

View File

@@ -1,62 +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, limiter
@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
@limiter.limit('1 per second')
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

@@ -6,17 +6,17 @@ from ..tools import VehicleStats
from .. import app from .. import app
@app.route('/statistics', methods=['GET']) @app.route("/statistics", methods=["GET"])
@login_required @login_required
def get_statistics(): def get_statistics():
stats = [] stats = []
for vehicle in current_user.vehicles:
def key(v):
return (not v.is_active, v.name)
vehicles = sorted(current_user.vehicles, key=key)
for vehicle in vehicles:
stats.append(VehicleStats(vehicle)) stats.append(VehicleStats(vehicle))
return render_template('statistics.html', data=stats) return render_template("statistics.html", data=stats)
@app.route('/manual', methods=['GET'])
@login_required
def get_manual():
return render_template('manual.html')

View File

@@ -7,70 +7,100 @@ import types
from ..entities import Vehicle, Consumable, Pitstop from ..entities import Vehicle, Consumable, Pitstop
from ..forms import SelectVehicleForm, SelectConsumableForm, \ from ..forms import (
CreatePitstopForm, EditPitstopForm, DeletePitStopForm SelectVehicleForm,
from ..tools import db_log_update, db_log_delete, db_log_add, \ SelectConsumableForm,
pitstop_service_key, get_event_line_for_vehicle, \ CreatePitstopForm,
update_filling_station_prices, RegularCostInstance, \ EditPitstopForm,
calculate_regular_cost_instances DeletePitStopForm,
)
from ..tools import (
db_log_update,
db_log_delete,
db_log_add,
pitstop_service_key,
get_event_line_for_vehicle,
RegularCostInstance,
calculate_regular_cost_instances,
get_users_active_vehicle,
)
from .. import app, db from .. import app, db
@app.route('/pitstops/vehicle/select', methods=['GET', 'POST']) @app.route("/pitstops/vehicle/select", methods=["GET", "POST"])
@login_required @login_required
def select_vehicle_for_new_pitstop(): def select_vehicle_for_new_pitstop():
if len(current_user.vehicles) == 1: active_vehicles = get_users_active_vehicle(current_user)
return redirect(url_for('select_consumable_for_new_pitstop', vid=current_user.vehicles[0].id)) if len(active_vehicles) == 1:
return redirect(
url_for(
"select_consumable_for_new_pitstop", vid=active_vehicles[0].id
)
)
form = SelectVehicleForm() form = SelectVehicleForm()
form.vehicle.choices = [(g.id, g.name) for g in current_user.vehicles] form.vehicle.choices = [
(g.id, g.name) for g in active_vehicles
]
if form.validate_on_submit(): if form.validate_on_submit():
return redirect(url_for('select_consumable_for_new_pitstop', vid=form.vehicle.data)) return redirect(
url_for("select_consumable_for_new_pitstop", vid=form.vehicle.data)
)
return render_template('selectVehicle.html', form=form) return render_template("selectVehicle.html", form=form)
@app.route('/pitstops/vehicle/<int:vid>/consumable/select', methods=['GET', 'POST']) @app.route("/pitstops/vehicle/<int:vid>/consumable/select", methods=["GET", "POST"])
@login_required @login_required
def select_consumable_for_new_pitstop(vid): def select_consumable_for_new_pitstop(vid):
vehicle = Vehicle.query.get(vid) vehicle = Vehicle.query.get(vid)
if vehicle is None or vehicle not in current_user.vehicles: if vehicle is None or vehicle not in current_user.vehicles:
return redirect(url_for('select_vehicle_for_new_pitstop')) return redirect(url_for("select_vehicle_for_new_pitstop"))
if len(vehicle.consumables) == 0: if len(vehicle.consumables) == 0:
flash('Please choose at least one consumable!', 'warning') flash("Please choose at least one consumable!", "warning")
return redirect(url_for('edit_vehicle', vid=vid)) return redirect(url_for("edit_vehicle", vid=vid))
if len(vehicle.consumables) == 1: if len(vehicle.consumables) == 1:
return redirect(url_for('create_pit_stop_form', vid=vid, cid=vehicle.consumables[0].id)) return redirect(
url_for("create_pit_stop_form", vid=vid, cid=vehicle.consumables[0].id)
)
form = SelectConsumableForm() form = SelectConsumableForm()
form.consumable.choices = [(g.id, g.name) for g in vehicle.consumables] form.consumable.choices = [(g.id, g.name) for g in vehicle.consumables]
if form.validate_on_submit(): if form.validate_on_submit():
return redirect(url_for('create_pit_stop_form', vid=vid, cid=form.consumable.data)) return redirect(
url_for("create_pit_stop_form", vid=vid, cid=form.consumable.data)
)
return render_template('selectConsumableForVehicle.html', vehicle=vehicle, form=form) return render_template(
"selectConsumableForVehicle.html", vehicle=vehicle, form=form
)
@app.route('/pitstops/vehicle/<int:vid>/consumable/<int:cid>/create', methods=['GET', 'POST']) @app.route(
"/pitstops/vehicle/<int:vid>/consumable/<int:cid>/create", methods=["GET", "POST"]
)
@login_required @login_required
def create_pit_stop_form(vid, cid): def create_pit_stop_form(vid, cid):
vehicle = Vehicle.query.get(vid) vehicle = Vehicle.query.get(vid)
if vehicle is None or vehicle not in current_user.vehicles: if vehicle is None or vehicle not in current_user.vehicles:
return redirect(url_for('select_vehicle_for_new_pitstop')) return redirect(url_for("select_vehicle_for_new_pitstop"))
consumable = Consumable.query.get(cid) consumable = Consumable.query.get(cid)
if consumable not in vehicle.consumables: if consumable not in vehicle.consumables:
return redirect(url_for('select_consumable_for_new_pitstop', vid=vid)) return redirect(url_for("select_consumable_for_new_pitstop", vid=vid))
form = CreatePitstopForm() form = CreatePitstopForm()
data = get_event_line_for_vehicle(vehicle) data = get_event_line_for_vehicle(vehicle)
if len(data) > 0: if len(data) > 0:
form.set_pitstops(data) form.set_pitstops(data)
form.same_odometer_allowed = (type(data[-1]) != Pitstop) or (data[-1].consumable.id != cid) form.same_odometer_allowed = (type(data[-1]) != Pitstop) or (
data[-1].consumable.id != cid
)
else: else:
form.set_pitstops([]) form.set_pitstops([])
form.same_odometer_allowed = True form.same_odometer_allowed = True
@@ -85,7 +115,9 @@ def create_pit_stop_form(vid, cid):
# Validate should accept same odometer on different consumables # Validate should accept same odometer on different consumables
# #
if form.validate_on_submit(): if form.validate_on_submit():
new_stop = Pitstop(form.odometer.data, form.litres.data, form.date.data, form.costs.data, cid) new_stop = Pitstop(
form.odometer.data, form.litres.data, form.date.data, form.costs.data, cid
)
db.session.add(new_stop) db.session.add(new_stop)
vehicle.pitstops.append(new_stop) vehicle.pitstops.append(new_stop)
try: try:
@@ -93,44 +125,57 @@ def create_pit_stop_form(vid, cid):
db_log_add(new_stop) db_log_add(new_stop)
except IntegrityError: except IntegrityError:
db.session.rollback() db.session.rollback()
form.odometer.errors.append('Pitstop already present for %s at odometer %s km!' % (consumable.name, form.odometer.data)) form.odometer.errors.append(
return render_template('createPitStopForm.html', form=form, vehicle=vehicle, messages=form.get_hint_messages()) "Pitstop already present for %s at odometer %s km!"
return redirect(url_for('get_pit_stops', _anchor= 'v' + str(vehicle.id))) % (consumable.name, form.odometer.data)
)
return render_template(
"createPitStopForm.html",
form=form,
vehicle=vehicle,
messages=form.get_hint_messages(),
)
return redirect(url_for("get_pit_stops", _anchor="v" + str(vehicle.id)))
form.process() form.process()
return render_template('createPitStopForm.html', form=form, vehicle=vehicle, messages=form.get_hint_messages()) return render_template(
"createPitStopForm.html",
form=form,
vehicle=vehicle,
messages=form.get_hint_messages(),
)
@app.route('/pitstops/delete/<int:pid>', methods=['GET', 'POST']) @app.route("/pitstops/delete/<int:pid>", methods=["GET", "POST"])
@login_required @login_required
def delete_pit_stop_form(pid): def delete_pit_stop_form(pid):
pitstop = Pitstop.query.filter(Pitstop.id == pid).first() pitstop = Pitstop.query.filter(Pitstop.id == pid).first()
if pitstop is None: if pitstop is None:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
vehicle = Vehicle.query.filter(Vehicle.id == pitstop.vehicle_id).first() vehicle = Vehicle.query.filter(Vehicle.id == pitstop.vehicle_id).first()
if vehicle not in current_user.vehicles: if vehicle not in current_user.vehicles:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
form = DeletePitStopForm() form = DeletePitStopForm()
if form.validate_on_submit(): if form.validate_on_submit():
db.session.delete(pitstop) db.session.delete(pitstop)
db.session.commit() db.session.commit()
db_log_delete(pitstop) db_log_delete(pitstop)
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id))) return redirect(url_for("get_pit_stops", _anchor="v" + str(vehicle.id)))
return render_template('deletePitstopForm.html', form=form, pitstop=pitstop ) return render_template("deletePitstopForm.html", form=form, pitstop=pitstop)
@app.route('/pitstops/edit/<int:pid>', methods=['GET', 'POST']) @app.route("/pitstops/edit/<int:pid>", methods=["GET", "POST"])
@login_required @login_required
def edit_pit_stop_form(pid): def edit_pit_stop_form(pid):
edit_pitstop = Pitstop.query.get(pid) edit_pitstop = Pitstop.query.get(pid)
if edit_pitstop is None: if edit_pitstop is None:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
vehicle = Vehicle.query.filter(Vehicle.id == edit_pitstop.vehicle_id).first() vehicle = Vehicle.query.filter(Vehicle.id == edit_pitstop.vehicle_id).first()
if vehicle not in current_user.vehicles: if vehicle not in current_user.vehicles:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
form = EditPitstopForm() form = EditPitstopForm()
data = get_event_line_for_vehicle(vehicle) data = get_event_line_for_vehicle(vehicle)
@@ -148,19 +193,22 @@ def edit_pit_stop_form(pid):
edit_pitstop.odometer = form.odometer.data edit_pitstop.odometer = form.odometer.data
db.session.commit() db.session.commit()
db_log_update(edit_pitstop) db_log_update(edit_pitstop)
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id))) return redirect(url_for("get_pit_stops", _anchor="v" + str(vehicle.id)))
form.preinit_with_data() form.preinit_with_data()
form.process() form.process()
return render_template('editPitStopForm.html', form=form, vehicle=vehicle, messages=form.get_hint_messages()) return render_template(
"editPitStopForm.html",
form=form,
vehicle=vehicle,
messages=form.get_hint_messages(),
)
@app.route('/pitstops', methods=['GET']) @app.route("/pitstops", methods=["GET"])
@login_required @login_required
def get_pit_stops(): def get_pit_stops():
user = { user = {"vehicles": []}
'vehicles': []
}
for vehicle in current_user.vehicles: for vehicle in current_user.vehicles:
data = [] data = []
for pitstop in vehicle.pitstops: for pitstop in vehicle.pitstops:
@@ -172,71 +220,12 @@ def get_pit_stops():
data.sort(key=pitstop_service_key) data.sort(key=pitstop_service_key)
v = { v = {
'id': vehicle.id, "id": vehicle.id,
'name': vehicle.name, "name": vehicle.name,
'data': data, "data": data,
"regulars": vehicle.regulars, "regulars": vehicle.regulars,
} }
user['vehicles'].append(v) user["vehicles"].append(v)
user["vehicles"].sort(key=lambda v: (v["data"][-1].date, v["data"][-1].odometer or 0 ), reverse=True)
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)
return render_template("pitstops.html", user=user)

View File

@@ -18,7 +18,7 @@ from ..tools import (
db_log_add, db_log_add,
pitstop_service_key, pitstop_service_key,
get_event_line_for_vehicle, get_event_line_for_vehicle,
update_filling_station_prices, get_users_active_vehicle,
) )
from .. import app, db from .. import app, db
@@ -48,13 +48,14 @@ def delete_regular_form(pid):
@app.route("/regular_costs/vehicle/select", methods=["GET", "POST"]) @app.route("/regular_costs/vehicle/select", methods=["GET", "POST"])
@login_required @login_required
def select_vehicle_for_new_regular_cost(): def select_vehicle_for_new_regular_cost():
if len(current_user.vehicles) == 1: active_vehicles = get_users_active_vehicle(current_user)
if len(active_vehicles) == 1:
return redirect( return redirect(
url_for("create_regular_cost_for_vehicle", vid=current_user.vehicles[0].id) url_for("create_regular_cost_for_vehicle", vid=active_vehicles[0].id)
) )
form = SelectVehicleForm() form = SelectVehicleForm()
form.vehicle.choices = [(g.id, g.name) for g in current_user.vehicles] form.vehicle.choices = [(g.id, g.name) for g in active_vehicles]
if form.validate_on_submit(): if form.validate_on_submit():
return redirect( return redirect(
@@ -158,4 +159,3 @@ def end_regular_form(pid):
form=form, form=form,
vehicle=vehicle, vehicle=vehicle,
) )

View File

@@ -3,17 +3,28 @@ from flask_security import login_required, current_user
from datetime import date from datetime import date
from ..entities import Vehicle, Service from ..entities import Vehicle, Service
from ..forms import CreateServiceForm, DeleteServiceForm, EditServiceForm, SelectVehicleForm from ..forms import (
from ..tools import db_log_update, db_log_delete, get_event_line_for_vehicle, get_latest_pitstop_for_vehicle CreateServiceForm,
DeleteServiceForm,
EditServiceForm,
SelectVehicleForm,
)
from ..tools import (
db_log_update,
db_log_delete,
get_event_line_for_vehicle,
get_latest_pitstop_for_vehicle,
get_users_active_vehicle,
)
from .. import app, db from .. import app, db
@app.route('/service/vehicle/<int:vid>/create', methods=['GET', 'POST']) @app.route("/service/vehicle/<int:vid>/create", methods=["GET", "POST"])
@login_required @login_required
def create_service_for_vehicle(vid): def create_service_for_vehicle(vid):
vehicle = Vehicle.query.get(vid) vehicle = Vehicle.query.get(vid)
if vehicle is None or vehicle not in current_user.vehicles: if vehicle is None or vehicle not in current_user.vehicles:
return redirect(url_for('get_account_page')) return redirect(url_for("get_account_page"))
form = CreateServiceForm() form = CreateServiceForm()
@@ -28,47 +39,55 @@ def create_service_for_vehicle(vid):
form.preinit_with_data() form.preinit_with_data()
if form.validate_on_submit(): if form.validate_on_submit():
new_service = Service(form.date.data, form.odometer.data, vid, form.costs.data, form.description.data) new_service = Service(
form.date.data,
form.odometer.data,
vid,
form.costs.data,
form.description.data,
)
db.session.add(new_service) db.session.add(new_service)
vehicle.services.append(new_service) vehicle.services.append(new_service)
db.session.commit() db.session.commit()
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id))) return redirect(url_for("get_pit_stops", _anchor="v" + str(vehicle.id)))
form.process() form.process()
return render_template('createServiceForm.html', form=form, vehicle=vehicle, messages=[]) return render_template(
"createServiceForm.html", form=form, vehicle=vehicle, messages=[]
)
@app.route('/service/delete/<int:sid>', methods=['GET', 'POST']) @app.route("/service/delete/<int:sid>", methods=["GET", "POST"])
@login_required @login_required
def delete_service_form(sid): def delete_service_form(sid):
service = Service.query.filter(Service.id == sid).first() service = Service.query.filter(Service.id == sid).first()
if service is None: if service is None:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
vehicle = Vehicle.query.filter(Vehicle.id == service.vehicle_id).first() vehicle = Vehicle.query.filter(Vehicle.id == service.vehicle_id).first()
if vehicle not in current_user.vehicles: if vehicle not in current_user.vehicles:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
form = DeleteServiceForm() form = DeleteServiceForm()
if form.validate_on_submit(): if form.validate_on_submit():
db.session.delete(service) db.session.delete(service)
db.session.commit() db.session.commit()
db_log_delete(service) db_log_delete(service)
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id))) return redirect(url_for("get_pit_stops", _anchor="v" + str(vehicle.id)))
return render_template('deleteServiceForm.html', form=form, service=service ) return render_template("deleteServiceForm.html", form=form, service=service)
@app.route('/service/edit/<int:sid>', methods=['GET', 'POST']) @app.route("/service/edit/<int:sid>", methods=["GET", "POST"])
@login_required @login_required
def edit_service_form(sid): def edit_service_form(sid):
edit_service = Service.query.get(sid) edit_service = Service.query.get(sid)
if edit_service is None: if edit_service is None:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
vehicle = Vehicle.query.filter(Vehicle.id == edit_service.vehicle_id).first() vehicle = Vehicle.query.filter(Vehicle.id == edit_service.vehicle_id).first()
if vehicle not in current_user.vehicles: if vehicle not in current_user.vehicles:
return redirect(url_for('get_pit_stops')) return redirect(url_for("get_pit_stops"))
data = get_event_line_for_vehicle(vehicle) data = get_event_line_for_vehicle(vehicle)
data = [x for x in data if x != edit_service] data = [x for x in data if x != edit_service]
@@ -88,25 +107,31 @@ def edit_service_form(sid):
edit_service.odometer = form.odometer.data edit_service.odometer = form.odometer.data
db.session.commit() db.session.commit()
db_log_update(edit_service) db_log_update(edit_service)
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id))) return redirect(url_for("get_pit_stops", _anchor="v" + str(vehicle.id)))
form.preinit_with_data() form.preinit_with_data()
form.process() form.process()
return render_template('editServiceForm.html', form=form, vehicle=vehicle, messages=form.get_hint_messages()) return render_template(
"editServiceForm.html",
form=form,
vehicle=vehicle,
messages=form.get_hint_messages(),
)
@app.route('/service/vehicle/select', methods=['GET', 'POST']) @app.route("/service/vehicle/select", methods=["GET", "POST"])
@login_required @login_required
def select_vehicle_for_new_service(): def select_vehicle_for_new_service():
if len(current_user.vehicles) == 1: active_vehicles = get_users_active_vehicle(current_user)
return redirect(url_for('create_service_for_vehicle', vid=current_user.vehicles[0].id)) if len(active_vehicles) == 1:
return redirect(
url_for("create_service_for_vehicle", vid=active_vehicles[0].id)
)
form = SelectVehicleForm() form = SelectVehicleForm()
form.vehicle.choices = [(g.id, g.name) for g in current_user.vehicles] form.vehicle.choices = [(g.id, g.name) for g in active_vehicles]
if form.validate_on_submit(): if form.validate_on_submit():
return redirect(url_for('create_service_for_vehicle', vid=form.vehicle.data)) return redirect(url_for("create_service_for_vehicle", vid=form.vehicle.data))
return render_template('selectVehicle.html', form=form)
return render_template("selectVehicle.html", form=form)

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 * styling for sortable tables
*/ */
@@ -120,7 +110,3 @@ th.headerSortUp {
th.headerSortDown { th.headerSortDown {
background-image: url(../img/up.gif); 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

@@ -33,7 +33,10 @@
{% for vehicle in current_user.vehicles %} {% for vehicle in current_user.vehicles %}
<tr> <tr>
<td> <td>
{{ vehicle.name }} {{ vehicle.name }}<br />
{% if not vehicle.is_active %}
(inactive)
{% endif %}
</td> </td>
<td> <td>
{{ vehicle.pitstops | length }} pitstops<br /> {{ vehicle.pitstops | length }} pitstops<br />
@@ -63,32 +66,6 @@
</tbody> </tbody>
</table> </table>
</div> </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 panel-default">
<div class="panel-heading">Account</div> <div class="panel-heading">Account</div>
<div class="panel-body"> <div class="panel-body">

View File

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

View File

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

View File

@@ -10,6 +10,7 @@
{{ form.hidden_tag() }} {{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }} {{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.consumables) }} {{ render_field_with_errors(form.consumables) }}
{{ render_field_with_errors(form.is_active) }}
{{ render_field_with_errors(form.submit) }} {{ render_field_with_errors(form.submit) }}
</form> </form>
</div> </div>

View File

@@ -1,6 +1,5 @@
{% macro navigation() -%} {% macro navigation() -%}
{% if current_user.email %} {% if current_user.email %}
<li><a id='plan_pitstop_link' href='{{ url_for('select_vehicle_for_plan_pitstop') }}'>Plan Pitstop</a></li>
<li><a id='new_pitstop_link' href='{{ url_for('select_vehicle_for_new_pitstop') }}'>Create Pitstop</a></li> <li><a id='new_pitstop_link' href='{{ url_for('select_vehicle_for_new_pitstop') }}'>Create Pitstop</a></li>
<li><a id='new_service_link' href='{{ url_for('select_vehicle_for_new_service') }}'>Create Service</a></li> <li><a id='new_service_link' href='{{ url_for('select_vehicle_for_new_service') }}'>Create Service</a></li>
<li><a id='new_service_link' href='{{ url_for('select_vehicle_for_new_regular_cost') }}'>Create Regular Cost</a></li> <li><a id='new_service_link' href='{{ url_for('select_vehicle_for_new_regular_cost') }}'>Create Regular Cost</a></li>
@@ -45,7 +44,7 @@
{% endfor %} {% endfor %}
</select> </select>
{% elif field.type == 'BooleanField' %} {% elif field.type == 'BooleanField' %}
<input class="form-control" type="checkbox" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" aria-describedby="{{ field.id }}_help" /> <input class="form-control" type="checkbox" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.id }}" aria-describedby="{{ field.id }}_help" {% if field.default %}checked{% endif %}/>
{% elif field.type == 'StringField' %} {% elif field.type == 'StringField' %}
<input class="form-control" type="text" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" aria-describedby="{{ field.id }}_help" /> <input class="form-control" type="text" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" aria-describedby="{{ field.id }}_help" />
{% elif field.type == 'PasswordField' %} {% elif field.type == 'PasswordField' %}
@@ -136,7 +135,6 @@
<script src="https://www.amcharts.com/lib/3/themes/patterns.js"></script> <script src="https://www.amcharts.com/lib/3/themes/patterns.js"></script>
<script src="https://openlayers.org/api/OpenLayers.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/main.js') }}"></script>
<script src="{{ url_for('static', filename='js/fillingstations.js') }}"></script>
</head> </head>
<body> <body>
<nav class="navbar navbar-inverse navbar-fixed-top"> <nav class="navbar navbar-inverse navbar-fixed-top">
@@ -185,7 +183,7 @@
<div class="col-md-12"> <div class="col-md-12">
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-body"> <div class="panel-body">
<a href="https://www.lusiardi.de/impressum/" target="_new">Impressum</a> - <a href="https://www.lusiardi.de/datenschutzerklaerung/" target="_new">Datenschutzerklärung</a> <a href="https://lusiardi.de/pages/impressum.html" target="_new">Impressum</a> - <a href="https://lusiardi.de/pages/datenschutzerklaerung.html" target="_new">Datenschutzerklärung</a>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -1,31 +0,0 @@
{% extends "layout.html" %}
{% macro line(header, cell) -%}
<tr>
<th>
{{ header }}
</th>
<td>
{{ cell }}
</td>
</tr>
{%- endmacro %}
{% block body %}
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
{{ line('Reifenluftdruck (vorne)', '1,75 - 2,0 Bar') }}
{{ line('Reifenluftdruck (hinten)', '2,0 - 2,25 Bar') }}
{{ line('Scheinwerfer', '12V 35/35W HS1-Halogen-Glühlampe') }}
{{ line('Standlicht', '12V 5W Glassockel 9mm') }}
{{ line('Blinker vorne', '12V 10W Stecksockel 15mm') }}
{{ line('Rück-/Bremslicht', '12V/21/5W Stecksockel 15mm') }}
{{ line('Blinker hinten', '12V 10W Stecksockel 15mm') }}
{{ line('Tankinhalt', 'ca. 6,0 L') }}
{{ line('Motoröl', 'SAE 15W40') }}
{{ line('Getriebeöl', 'SAE 80/90 (0,12/0,09)') }}
</table>
</div>
{% endblock %}

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

@@ -164,6 +164,7 @@
<ul id="consumable_{{vehicle.id}}_{{consumable.id}}_tabs" class="nav nav-tabs" data-tabs="tabs"> <ul id="consumable_{{vehicle.id}}_{{consumable.id}}_tabs" class="nav nav-tabs" data-tabs="tabs">
{{ nav_tab(vehicle.id|string + '_' + consumable.id|string + '_consumption', 'Consumption', true) }} {{ nav_tab(vehicle.id|string + '_' + consumable.id|string + '_consumption', 'Consumption', true) }}
{{ nav_tab(vehicle.id|string + '_' + consumable.id|string + '_amount', 'Amount', false) }} {{ nav_tab(vehicle.id|string + '_' + consumable.id|string + '_amount', 'Amount', false) }}
{{ nav_tab(vehicle.id|string + '_' + consumable.id|string + '_price', 'Price', false) }}
</ul> </ul>
<div id="consumable_{{vehicle.id}}_{{consumable.id}}_content" class="tab-content "> <div id="consumable_{{vehicle.id}}_{{consumable.id}}_content" class="tab-content ">
{{ tab_pane( {{ tab_pane(
@@ -188,6 +189,17 @@
false false
) )
}} }}
{{ tab_pane(
vehicle.id|string + '_' + consumable.id|string + '_price',
chart(
consumable.price,
'ref_' + vehicle.id|string + '_' + consumable.id|string + '_price',
'€ / '+consumable.unit,
url_for('create_pit_stop_form', vid=vehicle.id, cid=consumable.id)
),
false
)
}}
</div> </div>
{{ tab_script('vehicle_' + vehicle.id|string + '_' + consumable.id|string + '_tabs') }} {{ tab_script('vehicle_' + vehicle.id|string + '_' + consumable.id|string + '_tabs') }}
</div> </div>

View File

@@ -3,7 +3,7 @@ import requests
import logging import logging
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
from .entities import Pitstop, FillingStation from .entities import Pitstop
from . import db, app from . import db, app
@@ -27,6 +27,7 @@ class ConsumableStats:
self.average_amount_used = 0 self.average_amount_used = 0
self.average_amount = [] self.average_amount = []
self.amounts = [] self.amounts = []
self.price = []
pitstops = [ pitstops = [
stop for stop in vehicle.pitstops if stop.consumable_id == consumable.id stop for stop in vehicle.pitstops if stop.consumable_id == consumable.id
@@ -37,6 +38,9 @@ class ConsumableStats:
for pitstop in pitstops: for pitstop in pitstops:
self.overall_amount += pitstop.amount self.overall_amount += pitstop.amount
self.amounts.append(StatsEvent(pitstop.date, pitstop.amount)) self.amounts.append(StatsEvent(pitstop.date, pitstop.amount))
# some pitstops seem to have lost their costs...
if pitstop.costs:
self.price.append(StatsEvent(pitstop.date, pitstop.costs/pitstop.amount))
self.average_amount_fuelled = self.overall_amount / pitstop_count self.average_amount_fuelled = self.overall_amount / pitstop_count
if pitstop_count > 1: if pitstop_count > 1:
overall_distance = ( overall_distance = (
@@ -103,7 +107,9 @@ class VehicleStats:
c.value = accumulated_costs c.value = accumulated_costs
if self.overall_distance > 0: if self.overall_distance > 0:
self.costs_per_distance = float(self.overall_costs) / (float(self.overall_distance) / 100) self.costs_per_distance = float(self.overall_costs) / (
float(self.overall_distance) / 100
)
class StatsEvent: class StatsEvent:
@@ -202,7 +208,9 @@ def compute_lower_limits_for_new_pitstop(
def pitstop_service_key(x): def pitstop_service_key(x):
return x.date, x.odometer # if the entry got no odometer (regular costs!) then we assume it's okay
# to have regular cost at a virtual odometer of 0 on that day.
return x.date, x.odometer or 0
def get_event_line_for_vehicle(vehicle): def get_event_line_for_vehicle(vehicle):
@@ -221,51 +229,6 @@ def chunks(l, n):
yield l[i : i + 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): def calculate_regular_cost_instances(vehicle):
data = [] data = []
for regular in vehicle.regulars: for regular in vehicle.regulars:
@@ -294,3 +257,14 @@ def calculate_regular_cost_instances(vehicle):
) )
data.append(r) data.append(r)
return data return data
def get_users_active_vehicle(user):
def selector(vehicle):
if not vehicle.pitstops:
return date.today()
return vehicle.pitstops[-1].date
active_vehicles = [g for g in user.vehicles if g.is_active]
active_vehicles.sort(key=selector, reverse=True)
return active_vehicles

View File

@@ -41,8 +41,8 @@ class TestingConfig(Config):
class ProductionConfig(Config): class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:{h}@database/pitstops'.format( SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://pitstops:{h}@localhost/pitstops'.format(
h=os.environ.get('DATABASE_ENV_MYSQL_ROOT_PASSWORD')) h=os.environ.get('MYSQL_PASSWORD'))
config = { config = {

View File

@@ -0,0 +1,2 @@
ALTER TABLE `vehicle` ADD COLUMN `is_active` tinyint(1);
UPDATE `vehicle` SET `is_active` = 1;

View File

@@ -1,9 +1,13 @@
Flask Flask==2.1.2
Flask-SQLAlchemy Flask-SQLAlchemy==2.5.1
Flask-Security Flask-Security==3.0.0
Flask-WTF Flask-WTF==1.0.1
PyMySQL PyMySQL==1.0.2
markdown markdown
Flask-Limiter Flask-Limiter==2.4.5.1
requests requests==2.27.1
email_validator email-validator==1.2.1
gunicorn==20.1.0
pytz==2022.1
SQLAlchemy==1.4.36
Werkzeug==2.2.2