vehicles can now be deactivated #6

Merged
jlusiardi merged 1 commits from vehicles_can_be_deactivated into master 2021-06-20 08:49:34 +02:00
13 changed files with 280 additions and 179 deletions

View File

@ -82,6 +82,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"),)

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

@ -10,25 +10,27 @@ 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] stations = [x.as_dict() for x in current_user.favourite_filling_stations]
for station in stations: for station in stations:
station['state'] = 'favourite' station["state"] = "favourite"
return render_template('account.html', return render_template(
"account.html",
map_pos=(current_user.home_lat, current_user.home_long, current_user.home_zoom), map_pos=(current_user.home_lat, current_user.home_long, current_user.home_zoom),
fs=json.dumps(stations)) 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 +41,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 +59,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 +86,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 +107,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 +124,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 +138,28 @@ 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) return render_template("deleteAccountForm.html", form=form)
@app.route('/account/home', methods=['GET']) @app.route("/account/home", methods=["GET"])
@login_required @login_required
def get_users_home(): def get_users_home():
return jsonify( return jsonify(
{'lat': float(current_user.home_lat), 'long': float(current_user.home_long), 'zoom': current_user.home_zoom}) {
"lat": float(current_user.home_lat),
"long": float(current_user.home_long),
"zoom": current_user.home_zoom,
}
)
@app.route('/account/home', methods=['POST']) @app.route("/account/home", methods=["POST"])
@login_required @login_required
def set_users_home(): def set_users_home():
current_user.home_lat = request.json['lat'] current_user.home_lat = request.json["lat"]
current_user.home_long = request.json['long'] current_user.home_long = request.json["long"]
current_user.home_zoom = request.json['zoom'] current_user.home_zoom = request.json["zoom"]
db.session.commit() db.session.commit()
return jsonify({}) return jsonify({})

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,101 @@ 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,
update_filling_station_prices,
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 +116,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 +126,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 +194,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 +221,94 @@ 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)
return render_template('pitstops.html', user=user) return render_template("pitstops.html", user=user)
@app.route('/pitstops/plan/vehicle/select', methods=['GET', 'POST']) @app.route("/pitstops/plan/vehicle/select", methods=["GET", "POST"])
@login_required @login_required
def select_vehicle_for_plan_pitstop(): def select_vehicle_for_plan_pitstop():
if len(current_user.vehicles) == 1: if len(current_user.vehicles) == 1:
return redirect(url_for('select_consumable_for_plan_pitstop', vid=current_user.vehicles[0].id)) return redirect(
url_for(
"select_consumable_for_plan_pitstop", vid=current_user.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 current_user.vehicles]
if form.validate_on_submit(): if form.validate_on_submit():
return redirect(url_for('select_consumable_for_plan_pitstop', vid=form.vehicle.data)) return redirect(
url_for("select_consumable_for_plan_pitstop", vid=form.vehicle.data)
)
return render_template('selectVehicle.html', form=form) return render_template("selectVehicle.html", form=form)
@app.route('/pitstops/plan/vehicle/<int:vid>/consumable/select', methods=['GET', 'POST']) @app.route(
"/pitstops/plan/vehicle/<int:vid>/consumable/select", methods=["GET", "POST"]
)
@login_required @login_required
def select_consumable_for_plan_pitstop(vid): def select_consumable_for_plan_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_consumable_for_plan_pitstop')) return redirect(url_for("select_consumable_for_plan_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('plan_pit_stop_form', vid=vid, cid=vehicle.consumables[0].id)) return redirect(
url_for("plan_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('plan_pit_stop_form', vid=vid, cid=form.consumable.data)) return redirect(
url_for("plan_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/plan/vehicle/<int:vid>/consumable/<int:cid>', methods=['GET', 'POST']) @app.route(
"/pitstops/plan/vehicle/<int:vid>/consumable/<int:cid>", methods=["GET", "POST"]
)
@login_required @login_required
def plan_pit_stop_form(vid, cid): def plan_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))
update_filling_station_prices([x.id for x in current_user.favourite_filling_stations]) update_filling_station_prices(
[x.id for x in current_user.favourite_filling_stations]
)
offers = [] offers = []
for fs in current_user.favourite_filling_stations: for fs in current_user.favourite_filling_stations:
offers.append((fs, getattr(fs, consumable.ext_id),)) offers.append(
(
return render_template('planPitStopForm.html', vehicle=vehicle, consumable=consumable, offers=offers) fs,
getattr(fs, consumable.ext_id),
)
)
return render_template(
"planPitStopForm.html", vehicle=vehicle, consumable=consumable, offers=offers
)

View File

@ -19,6 +19,7 @@ from ..tools import (
pitstop_service_key, pitstop_service_key,
get_event_line_for_vehicle, get_event_line_for_vehicle,
update_filling_station_prices, update_filling_station_prices,
get_users_active_vehicle,
) )
from .. import app, db from .. import app, db
@ -48,13 +49,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 +160,3 @@ def end_regular_form(pid):
form=form, form=form,
vehicle=vehicle, vehicle=vehicle,
) )

View File

@ -3,17 +3,27 @@ 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,
)
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 +38,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 +106,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

@ -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 />

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,11 +1,11 @@
{% 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>
<li><a id='statistics_limk' href='{{ url_for('get_statistics') }}'>Statistics</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='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') %} {% if current_user.has_role('admin') %}
<li><a id='admin_link' href='{{ url_for('get_admin_page') }}'>Admin</a></li> <li><a id='admin_link' href='{{ url_for('get_admin_page') }}'>Admin</a></li>
{% endif %} {% endif %}
@ -45,7 +45,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' %}

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

@ -103,7 +103,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:
@ -294,3 +296,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

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