114 Commits

Author SHA1 Message Date
adf51c85f2 Merge branch 'development' into 'master'
Development

Fixes:
 * wrong date preselected when creation a pitstop
 * creation of new vehicle

See merge request !26
2016-07-29 21:50:52 +02:00
48d7c108f1 Merge branch '9-creation-of-new-vehicle-fails' into 'development'
Resolve "Creation of new vehicle fails"

Closes #9

See merge request !25
2016-07-29 21:12:30 +02:00
7129e676e2 Fixed issue 9 2016-07-29 21:10:58 +02:00
aaa94f08fa Merge branch 'issue_8_wrong_date_on_creating_new_pitstop' into 'development'
fix issue 8



See merge request !24
2016-07-29 21:02:43 +02:00
92fb25c1c1 fix issue 8 2016-07-25 18:54:27 +02:00
5fa710149d Merge branch 'development' into 'master'
Merge preparation for Esther



See merge request !23
2016-07-24 11:26:34 +02:00
c815c2b09a Merge branch 'style_consumable_selection' into 'development'
Style consumable selection



See merge request !22
2016-07-23 13:14:05 +02:00
529f9a6c64 Fixed problem with preselected values 2016-07-23 13:09:38 +02:00
bebccf0a36 Merge branch 'issue_7_really_delete_pitstop_page_does_not_show_all_information' into 'development'
Fix issue with missing information on pitstop delete page



See merge request !21
2016-07-21 19:14:45 +02:00
89ebab29c4 Merge branch 'issue_6_pitstop_is_not_editable' into 'development'
Fixed the edit function



See merge request !20
2016-07-21 19:14:21 +02:00
a4ecae4700 Fix issue with missing information on pitstop delete page 2016-07-21 19:11:32 +02:00
88f88591a9 Fixed the edit function 2016-07-21 19:03:04 +02:00
473c2a4f5b Slight style improvement 2016-07-18 21:30:06 +02:00
fd685c316d Update README.md 2016-07-17 10:06:19 +02:00
112ed38dbd fixed SQL Error with MySQL 5.7.12 2016-07-17 10:03:56 +02:00
2f737c1715 fixed DB URL 2016-07-17 10:02:41 +02:00
5a447763d0 Merge branch 'development' into 'master'
Merge branch 'development' into 'master'

Merge preparation for  Danielle

This adds the following features:
 * Add accounting for additional consumable materials (#5)
 * Add cost field to pit stop (#4)
 * Make last pit stop editable / deletable (#3)

See merge request !19
2016-07-17 09:40:54 +02:00
cfb9dfabc0 Merge branch 'issue_5_more_consumable_material' into development
Conflicts:
	app/__init__.py
2016-07-17 09:22:38 +02:00
c0f6ef7b4f Merge branch 'pycharm' into 'development'
Fixed project structure for pycharm



See merge request !16
2016-07-17 08:10:04 +02:00
fdb8993ac3 Merge branch 'issue_5_more_consumable_material' into pycharm
Conflicts:
	app/__init__.py
	app/rollerverbrauch/templates/createPitStopForm.html
	app/rollerverbrauch/templates/newPitStopForm.html
	app/rollerverbrauch/templates/selectVehice.html
	app/rollerverbrauch/templates/selectVehicle.html
	app/templates/newPitStopForm.html
	app/templates/selectVehice.html
2016-07-16 19:29:25 +02:00
1f5cb6b1fa Fixed issue with status on non-logged in index page 2016-07-16 13:29:32 +02:00
2a524ffdbf Merge branch 'issue_5_more_consumable_material' into 'development'
Issue 5 more consumable material



See merge request !17
2016-07-16 12:12:43 +02:00
1516ac2c51 db update script and some fixes 2016-07-16 12:07:01 +02:00
aa9fda93c0 statistics 3rd 2016-07-11 22:15:23 +02:00
ca5bd9bb02 statistics 2nd step 2016-07-11 06:59:34 +02:00
4ea42a7efd first step for statistics 2016-07-10 13:40:49 +02:00
43e3f9c98b . 2016-07-04 20:19:59 +02:00
738bcb9f89 Fixed project structure for pycharm 2016-07-03 19:29:30 +02:00
af5d4ae6b3 cann add pitstops for selected vehicles / consumables 2016-06-29 22:50:01 +02:00
907d0435d1 consumables for vehicles can be edited 2016-06-28 23:33:24 +02:00
fe4236eead renamed template for create a pitstop 2016-06-28 21:35:04 +02:00
a0be122186 reworked the crud funtions for vehicles 2016-06-27 22:09:42 +02:00
fa4126be66 adds update & delete for consumables
adds functionality to
* update
* delete
for consumables
2016-06-27 21:35:00 +02:00
60f2e9f4e4 adds form to create a consumable 2016-06-27 20:08:49 +02:00
5e24b9779e makes the name of a consumable unique
makes the column unique and extends the create form to respect the
uniqueness.
2016-06-27 19:48:04 +02:00
90639a757d Merge branch 'development' into issue_5_more_consumable_material 2016-06-26 08:27:14 +02:00
820063837d Merge branch 'issue_4_add_cost_field' into development 2016-06-26 08:26:33 +02:00
f2623cf6e9 bugfix for creating first pitstop of a vehicle 2016-06-26 08:25:53 +02:00
1072142a1b adds consumables to database
this adds a new consumables entity to the database and
the possibility in the admin page to add these.
2016-06-26 08:19:28 +02:00
56757f29a1 Merge branch 'issue_3_last_stop_editable' into 'development'
Issue 3 last stop editable



See merge request !15
2016-06-24 07:17:00 +02:00
9d41c39ae7 adds edit feature for last pitstop
Adds the possibility to edit the last pitstop in a dedicated
form.
2016-06-24 07:15:24 +02:00
6f7716abc6 adds delete feature for last pitstop
Adds the possibility to delete the latest pitstop after a
confirmation page.
2016-06-22 22:48:27 +02:00
6d26ceeae8 Merge branch 'issue_4_add_cost_field' into 'development'
adds tracking of costs

This commit adds a new field to each pitstop for tracking of
costs.
This includes:
* a new DB column
* a new field in the create pitstop form
* a new column in the pitstop overview
* new stats values related to costs
* 2 new graphs

See merge request !14
2016-06-22 21:01:46 +02:00
5b69a82e05 adds tracking of costs
This commit adds a new field to each pitstop for tracking of
costs.
This includes:
* a new DB column
* a new field in the create pitstop form
* a new column in the pitstop overview
* new stats values related to costs
* 2 new graphs
2016-06-21 21:06:41 +02:00
f82cf425fd Merge branch 'development' into 'master'
Merge preparation for Cathrine



See merge request !13
2016-05-28 20:47:26 +02:00
7696fb870c Merge branch 'docker_compose' into 'development'
Docker compose



See merge request !12
2016-05-28 17:13:22 +02:00
63ff5845e2 added demo config 2016-05-26 13:54:51 +02:00
10494a03a9 first version for docker-compose 2016-05-26 12:08:24 +02:00
2176579baa Merge branch 'implement_delete_account' into 'development'
Implement delete account



See merge request !11
2016-05-25 09:41:15 +02:00
da7c40c78b Merge branch 'index_page' into implement_delete_account 2016-05-25 09:40:20 +02:00
00579eb542 Merge branch 'index_page' into implement_delete_account 2016-05-24 23:56:12 +02:00
ef55b4e479 First step 2016-05-24 23:55:58 +02:00
a6c5abfd88 Merge branch 'index_page' into 'development'
Index page



See merge request !10
2016-05-24 07:02:33 +02:00
293ff50809 Some more UI changes 2016-05-24 06:49:39 +02:00
873a28aa28 ui redesign 2016-05-22 11:47:46 +02:00
1c4d73da43 Adds start page for unauthed visitors 2016-05-18 08:19:11 +02:00
7eef2b6cee Adds start page for unauthed visitors 2016-05-18 08:17:53 +02:00
227dc79e6b Merge branch 'issue_1' into 'development'
Handle vehicle name uniqueness

Vehicle names now must be only unique per owner, not globally.
Also errors are displayed to the forms on creation and edit of
vehicles.

See merge request !9
2016-05-16 18:49:39 +02:00
19b1e3b7ae Handle vehicle name uniqueness
Vehicle names now must be only unique per owner, not globally.
Also errors are displayed to the forms on creation and edit of
vehicles.
2016-05-16 18:46:24 +02:00
c5305caf36 switched to configurable db 2016-05-05 15:06:29 +02:00
e1e5fe7725 Little Improvements
Help text for create pitstops form
More precise error messages for create pitstops form
Fixed bu in statistics page when only one pitstop was present
2016-05-03 22:21:57 +02:00
471f1415d9 Removed print 2016-05-02 08:03:24 +02:00
99df28a015 Merge branch 'add_charts' into 'master'
Add charts



See merge request !8
2016-05-02 08:02:33 +02:00
6b861903af add consumption chart 2016-05-02 07:59:31 +02:00
706f30e2e2 switched off drop representation 2016-05-02 07:59:14 +02:00
Joachim Lusiardi
cc7d2620e8 Worked on charts 2016-05-02 06:42:43 +02:00
161cc16498 continued work ok charts 2016-04-30 06:41:59 +02:00
ef976299dc Fix PEP8 error 2016-04-28 22:33:14 +02:00
60293d6a27 Demo Chart 2016-04-28 07:53:53 +02:00
1e5b63d068 Merge branch 'add_app_step_log' into 'master'
fixed variable name



See merge request !7
2016-04-28 07:11:10 +02:00
13a5b07df2 fixed variable name 2016-04-28 07:10:44 +02:00
662e5b5b63 Merge branch 'add_app_step_log' into 'master'
Add app step log



See merge request !6
2016-04-28 06:44:46 +02:00
fd206de263 add logging for performed db operations 2016-04-28 06:32:51 +02:00
e936f1c60f fixed typos in readme 2016-04-27 21:41:47 +02:00
a7df0aebee Merge branch 'add_vehicles' into 'master'
Add vehicles



See merge request !5
2016-04-27 07:24:59 +02:00
3e2d62b28f improved design of the form elements 2016-04-27 07:23:28 +02:00
ca7166f731 fixed stats 2016-04-25 22:28:35 +02:00
34905921d9 fixes display of last pitstops
the display of the last pitstops now is separated by vehicle.
2016-04-25 07:23:01 +02:00
038e255b56 can add pitstops to vehicles nows 2016-04-24 14:09:41 +02:00
3709eddabb prevents the deletion of vehicles of other users 2016-04-24 12:42:07 +02:00
c941e1bccf finished modules merge 2016-04-23 23:24:25 +02:00
7bc5422687 Merge branch 'create_modules' into add_vehicles
Conflicts:
	app/main.py
2016-04-23 23:22:44 +02:00
0d8ae0cd18 introduces modules 2016-04-23 23:08:39 +02:00
3ec2e4648d Merge branch 'user_handling' into 'master'
User handling



See merge request !4
2016-04-23 17:35:10 +02:00
267c59cbb3 adds create and delete vehicle 2016-04-23 17:11:43 +02:00
d19b0a5858 adds edit vehicle name 2016-04-23 11:20:39 +02:00
729fee51e9 Merge branch 'user_handling' into add_vehicles
Conflicts:
	app/main.py
2016-04-21 21:52:58 +02:00
4261a9bb0b reworked git ignore file 2016-04-21 08:12:12 +02:00
0303be7945 more user handling features of flask-security activated
Now users can recover their passwords and change them while
logged in.
2016-04-21 08:11:57 +02:00
01798e9548 adds admin page
admin users must have role admin (which must currently be set
manually via database)
2016-04-19 22:41:40 +02:00
9eb7ec7c8a switched to environment variable for config file lookup 2016-04-19 21:09:15 +02:00
344db8d998 add example config file 2016-04-19 08:19:31 +02:00
1240a3c64b Users are allowed to register now
This includes sending a welcome email.
2016-04-19 07:39:17 +02:00
baca41619d first iteration of vehicles 2016-04-19 06:47:10 +02:00
2e0fc3b772 Merge branch 'master' into user_handling
Conflicts:
	app/main.py
	app/requirements.txt
2016-04-18 21:43:01 +02:00
1d449cb0ab Merge branch 'master' of code.nerd2nerd.org:n0ob/rollerverbrauch 2016-04-18 21:01:31 +02:00
4c97bd86db Fixed date vs datetime 2016-04-18 20:58:20 +02:00
8057c59329 Merge branch 'wtforms' into 'master'
Wtforms



See merge request !3
2016-04-18 20:35:58 +02:00
1998fcb7d8 Merge branch 'master' into wtforms
Conflicts:
	app/main.py
2016-04-18 20:34:39 +02:00
01019c22d9 add switch for debugger 2016-04-18 08:13:27 +02:00
864b7822ac Changed to WTForms including validation 2016-04-18 07:25:40 +02:00
6f218e591f add render_field macro to layout.html 2016-04-17 15:06:54 +02:00
8c8803874e First step for WTForms 2016-04-17 12:50:31 +02:00
6ed4110ce9 logout only if logged in 2016-04-17 09:59:34 +02:00
a9b2781ae3 custom login form added 2016-04-17 09:34:11 +02:00
f6f1d960b7 Add logout button to menu 2016-04-17 09:05:59 +02:00
bbfa7b9341 First step towards flask security user handling 2016-04-17 08:59:11 +02:00
808e0d80d3 Merge branch 'introduce_sqlalchemy' into 'master'
switched to Flask-SQLAlchemy for db handling



See merge request !2
2016-04-16 15:57:56 +02:00
fc421558b0 switched to Flask-SQLAlchemy for db handling 2016-04-16 15:48:24 +02:00
c1adf69ca0 Merge branch 'reduce_features' into 'master'
Reduce features



See merge request !1
2016-04-14 19:54:40 +02:00
059c86b449 add .gitignore file 2016-04-14 19:53:49 +02:00
fb521194f7 Reduce services feature and reformatting 2016-04-14 07:32:06 +02:00
ef02cc8ab3 Add basic build and run information 2016-04-14 07:02:28 +02:00
8f99b798bb reworked docker file for faster build times 2016-04-13 08:30:13 +02:00
50 changed files with 2184 additions and 555 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
.idea/
**.DS_Store
**.swp
**.pyc

View File

@@ -1,9 +1,14 @@
FROM debian8_python3
ADD app /app
RUN pip3 install -r /app/requirements.txt; \
COPY requirements.txt /requirements.txt
RUN pip3 install -r /requirements.txt; \
mkdir /data
ADD app /app
ADD main.py /main.py
ADD config.py /config.py
VOLUME ["/data"]
VOLUME ["/app/config]
EXPOSE 5000
ENTRYPOINT python3 /app/main.py
ENTRYPOINT python3 /main.py

31
README.md Normal file
View File

@@ -0,0 +1,31 @@
# How to build & run
## build
`docker build --tag=$(basename $PWD) .`
## general configuration
Look at *app/config/email.py.example** for the configuration of the
parameters required for sending emails. Copy the file as *email.py* to
a folder that will serve as configuration directory and fill in the
information. The directory will be used as volume during container
operation.
## start database
`docker run --name pitstops_db -e MYSQL_ROOT_PASSWORD=$SOMESECUREPASSWORD$ -e MYSQL_DATABASE=pitstops -d mysql:latest`
## Database migrations
### From *Cathrine* to *Master*:
`ALTER TABLE pitstop ADD COLUMN costs DECIMAL(5,2) NOT NULL DEFAULT 0.0 AFTER vehicle_id;`
## run in development
Include the development version of the code as volume, so the app gets
reloaded automatically. The sqlite file will be stored in *tmp* so it
can be inspected with tools like *sqlite3*. The switch *DEBUG* enables
debugging during development.
`docker run --rm --name rollerverbrauch -ti -v $PWD/app:/app --link pitstops_db:database -p 5000:5000 -e SECURITY_PASSWORD_SALT=XXX -e SECRET_KEY=XXX -e MAIL_SERVER=XXX -e MAIL_USERNAME=XXX -e MAIL_PASSWORD=XXX rollerverbrauch`
## run in production
`docker run --name pitstops -tid -e PROXY_DATA=server_names:ps.lusiardi.de,port:5000 --link pitstops_db:database -e SECURITY_PASSWORD_SALT=XXX -e SECRET_KEY=XXX -e MAIL_SERVER=XXX -e MAIL_USERNAME=XXX -e MAIL_PASSWORD=XXX rollerverbrauch:catherine`

488
app/__init__.py Normal file
View File

@@ -0,0 +1,488 @@
from datetime import date
from flask import Flask
from flask import redirect, g
from flask import render_template
from flask import url_for
from flask_mail import Mail
from flask_security import Security, SQLAlchemyUserDatastore, \
login_required, roles_required, user_registered
from flask_security.core import current_user
from flask_security.forms import LoginForm
from flask_sqlalchemy import SQLAlchemy
import os
from config import config
from sqlalchemy.exc import IntegrityError
from flask.ext.security.forms import LoginForm
from .forms import \
CreatePitstopForm, \
EditVehicleForm, \
DeleteVehicleForm, \
SelectVehicleForm, \
DeleteAccountForm, \
DeletePitStopForm, \
EditPitstopForm, \
CreateConsumableForm, \
EditConsumableForm, \
DeletConsumableForm, \
SelectConsumableForm
app = Flask(__name__)
app.config.from_object(config[os.getenv('FLASK_CONFIG') or 'default'])
db = SQLAlchemy(app)
mail = Mail(app)
from .entities import \
User, \
Role, \
Pitstop, \
Vehicle, \
Consumable
# required to activate the filters
from .filters import *
from .tools import *
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
@user_registered.connect_via(app)
def user_registered_sighandler(app, user, confirm_token):
"""
Called after a user was created
"""
role = user_datastore.find_role('user')
user_datastore.add_role_to_user(user, role)
new_vehicle = Vehicle('default vehicle')
db.session.add(new_vehicle)
user.vehicles.append(new_vehicle)
db.session.commit()
tools.db_log_add(user)
tools.db_log_add(new_vehicle)
@app.before_first_request
def before_first_request():
db.create_all()
user_datastore.find_or_create_role(name='admin', description='Role for administrators')
user_datastore.find_or_create_role(name='user', description='Role for all users.')
db.session.commit()
@app.before_request
def before_request():
g.data = {}
@app.route('/')
def index():
if current_user.is_authenticated:
return redirect(url_for('get_pit_stops'))
else:
user_count = len(User.query.all())
consumables = Consumable.query.all()
per_consumable = {}
for consumable in consumables:
per_consumable[consumable.id] = {
'name': consumable.name,
'unit': consumable.unit,
'amount': 0
}
vehicles = Vehicle.query.all()
kilometers = 0
for vehicle in vehicles:
stats = tools.VehicleStats(vehicle)
for consumable in stats.consumables:
per_consumable[consumable.id]['amount'] += consumable.overall_amount
kilometers += stats.overall_distance
vehicle_count = len(vehicles)
pitstop_count = len(Pitstop.query.all())
data = {
'users': user_count,
'vehicles': vehicle_count,
'pitstops': pitstop_count,
'kilometers': kilometers,
'consumables': per_consumable
}
return render_template('index.html', login_user_form=LoginForm(), data=data)
@app.route('/account/vehicle/edit/<int:vid>', methods=['GET', 'POST'])
@login_required
def edit_vehicle(vid):
vehicle = Vehicle.query.filter(Vehicle.id == vid).first()
# prevent edit of foreign vehicles
if vehicle not in current_user.vehicles:
return redirect(url_for('get_account_page'))
form = EditVehicleForm()
form.consumables.choices = [(g.id, g.name) for g in Consumable.query.all()]
if not form.consumables.data:
form.consumables.default = [g.id for g in vehicle.consumables]
if form.name.data is not None:
form.name.default = form.name.data
if form.validate_on_submit():
vehicle.name = form.name.data
# we cannot delete consumables where there are pitstops for => report error
vehicle.consumables = []
for consumable_id in form.consumables.data:
consumable = Consumable.query.get(consumable_id)
if consumable is not None:
vehicle.consumables.append(consumable)
try:
db.session.commit()
tools.db_log_update(vehicle)
except IntegrityError:
db.session.rollback()
form.name.errors.append('"%s" is not unique.' % (form.name.data))
return render_template('editVehicleForm.html', form=form)
return redirect(url_for('get_account_page'))
form.name.default = vehicle.name
form.process()
return render_template('editVehicleForm.html', form=form, vehicle=vehicle)
@app.route('/account/vehicle/delete/<int:vid>', methods=['GET', 'POST'])
@login_required
def delete_vehicle(vid):
vehicle = Vehicle.query.filter(Vehicle.id == vid).first()
# prevent deletion of foreign vehicles
if vehicle not in current_user.vehicles:
return redirect(url_for('get_account_page'))
if len(current_user.vehicles) == 1:
return redirect(url_for('get_account_page'))
form = DeleteVehicleForm()
if form.validate_on_submit():
db.session.delete(vehicle)
db.session.commit()
tools.db_log_delete(vehicle)
return redirect(url_for('get_account_page'))
return render_template('deleteVehicleForm.html', form=form, vehicle=vehicle)
@app.route('/account/vehicle/create', methods=['GET', 'POST'])
@login_required
def create_vehicle():
form = EditVehicleForm()
form.consumables.choices = [(g.id, g.name) for g in Consumable.query.all()]
if form.name.data is not None:
form.name.default = form.name.data
if form.consumables.data:
form.consumables.default = form.consumables.data
else:
form.consumables.default = []
if form.validate_on_submit():
if len(form.consumables.data) == 0:
form.consumables.errors.append('At least one consumable must be selected.')
return render_template('createVehicleForm.html', form=form)
vehicle_name = form.name.data
new_vehicle = Vehicle(vehicle_name)
for consumable_id in form.consumables.data:
consumable = Consumable.query.get(consumable_id)
if consumable is not None:
new_vehicle.consumables.append(consumable)
db.session.add(new_vehicle)
current_user.vehicles.append(new_vehicle)
try:
db.session.commit()
tools.db_log_add(new_vehicle)
except IntegrityError:
db.session.rollback()
form.name.errors.append('"%s" is not unique.' % (form.name.data))
return render_template('createVehicleForm.html', form=form)
return redirect(url_for('get_account_page'))
return render_template('createVehicleForm.html', form=form)
@app.route('/pitstops/vehicle/select', methods=['GET', 'POST'])
@login_required
def select_vehicle_for_new_pitstop():
if len(current_user.vehicles) == 1:
return redirect(url_for('select_consumable_for_new_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_new_pitstop', vid=form.vehicle.data))
return render_template('selectVehicle.html', form=form)
@app.route('/pitstops/vehicle/<int:vid>/consumable/select', methods=['GET', 'POST'])
@login_required
def select_consumable_for_new_pitstop(vid):
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'))
if len(vehicle.consumables) == 1:
return redirect(url_for('create_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('create_pit_stop_form', vid=vid, cid=form.consumable.data))
return render_template('selectConsumableForVehicle.html', vehicle=vehicle, form=form)
@app.route('/pitstops/vehicle/<int:vid>/consumable/<int:cid>/create', methods=['GET', 'POST'])
@login_required
def create_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))
form = CreatePitstopForm()
# the last pitstop is required to be able to check the monotonicy of date and odometer
last_pitstop = tools.get_latest_pitstop_for_vehicle(vid)
last_pitstop_consumable = tools.get_latest_pitstop_for_vehicle_and_consumable(vid, cid)
# we can enter the same odometer if the pitstops are not equal
form.same_odometer_allowed = (last_pitstop != last_pitstop_consumable)
# set the lower limits for odometer andd date and the values for amount and costs of the last stop
form.set_pitstop(tools.compute_lower_limits_for_new_pitstop(last_pitstop, last_pitstop_consumable, cid))
# set the label of the litres field to make the user comfortable
form.set_consumable(consumable)
# preinitialize the defaults with potentially existing values from a try before
form.preinit_with_data()
#
# Validate should accept same odometer on different consumables
#
if form.validate_on_submit():
new_stop = Pitstop(form.odometer.data, form.litres.data, form.date.data, form.costs.data, cid)
db.session.add(new_stop)
vehicle.pitstops.append(new_stop)
try:
db.session.commit()
tools.db_log_add(new_stop)
except IntegrityError:
db.session.rollback()
form.odometer.errors.append('Pitstop already present for %s at odometer %s km!' % (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()
return render_template('createPitStopForm.html', form=form, vehicle=vehicle, messages=form.get_hint_messages())
@app.route('/pitstops/delete/<int:pid>', methods=['GET', 'POST'])
@login_required
def delete_pit_stop_form(pid):
pitstop = Pitstop.query.filter(Pitstop.id == pid).first()
if pitstop is None:
return redirect(url_for('get_pit_stops'))
vehicle = Vehicle.query.filter(Vehicle.id == pitstop.vehicle_id).first()
if vehicle not in current_user.vehicles:
return redirect(url_for('get_pit_stops'))
form = DeletePitStopForm()
if form.validate_on_submit():
db.session.delete(pitstop)
db.session.commit()
tools.db_log_delete(pitstop)
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id)))
return render_template('deletePitstopForm.html', form=form, pitstop=pitstop )
@app.route('/pitstops/edit/<int:pid>', methods=['GET', 'POST'])
@login_required
def edit_pit_stop_form(pid):
edit_pitstop = Pitstop.query.get(pid)
if edit_pitstop is None:
return redirect(url_for('get_pit_stops'))
vehicle = Vehicle.query.filter(Vehicle.id == edit_pitstop.vehicle_id).first()
if vehicle not in current_user.vehicles:
return redirect(url_for('get_pit_stops'))
last_pitstop_pos = vehicle.pitstops.index(edit_pitstop) - 1
if last_pitstop_pos > 0:
last_pitstop = vehicle.pitstops[last_pitstop_pos]
else:
last_pitstop = Pitstop(0, 0, date(1970, 1, 1), 0, 0)
form = EditPitstopForm()
form.set_pitstop(last_pitstop)
if form.validate_on_submit():
edit_pitstop.costs = form.costs.data
edit_pitstop.date = form.date.data
edit_pitstop.amount = form.litres.data
edit_pitstop.odometer = form.odometer.data
db.session.commit()
tools.db_log_update(edit_pitstop)
return redirect(url_for('get_pit_stops', _anchor='v' + str(vehicle.id)))
form.odometer.default = edit_pitstop.odometer
form.litres.default = edit_pitstop.amount
form.date.default = edit_pitstop.date
form.costs.default = edit_pitstop.costs
form.process()
messages = {
'date': 'Date must be between %s and %s (including).' % (str(last_pitstop.date), str(date.today())),
'odometer': 'Odometer must be greater than %s km.' % (str(last_pitstop.odometer))
}
if edit_pitstop.costs is not None and edit_pitstop.costs > 0:
messages['costs'] = 'Costs must be higher than 0.01 €.'
return render_template('editPitStopForm.html', form=form, vehicle=vehicle, messages=messages)
@app.route('/pitstops', methods=['GET'])
@login_required
def get_pit_stops():
return render_template('pitstops.html', user=current_user)
@app.route('/manual', methods=['GET'])
@login_required
def get_manual():
return render_template('manual.html', data=g.data)
@app.route('/admin', methods=['GET'])
@roles_required('admin')
def get_admin_page():
users = User.query.all()
consumables = Consumable.query.all()
for consumable in consumables:
consumable.in_use = len(consumable.vehicles) > 0
return render_template('admin.html', users=users, consumables=consumables)
@app.route('/admin/consumable/create', methods=['GET', 'POST'])
@login_required
def create_consumable():
form = CreateConsumableForm()
# preinitialize the defaults with potentially existing values from a try before
if form.name.data is not None:
form.name.default = form.name.data
if form.unit.data is not None:
form.unit.default = form.unit.data
if form.validate_on_submit():
new_consumable = Consumable(form.name.data, form.unit.data)
db.session.add(new_consumable)
try:
db.session.commit()
tools.db_log_add(new_consumable)
except IntegrityError:
db.session.rollback()
form.name.errors.append('"%s" is not unique.' % (form.name.data))
return render_template('createConsumableForm.html', form=form)
return redirect(url_for('get_admin_page'))
return render_template('createConsumableForm.html', form=form)
@app.route('/admin/consumable/delete/<int:cid>', methods=['GET', 'POST'])
@login_required
def delete_consumable(cid):
consumable = Consumable.query.filter(Consumable.id == cid).first()
if consumable is None:
return redirect(url_for('get_admin_page'))
form = DeletConsumableForm()
if form.validate_on_submit():
db.session.delete(consumable)
db.session.commit()
tools.db_log_delete(consumable)
return redirect(url_for('get_admin_page'))
return render_template('deleteConsumableForm.html', form=form, consumable=consumable)
@app.route('/admin/consumable/edit/<int:cid>', methods=['GET', 'POST'])
@login_required
def edit_consumable(cid):
consumable = Consumable.query.filter(Consumable.id == cid).first()
if consumable is None:
return redirect(url_for('get_admin_page'))
form = EditConsumableForm()
form.name.default = consumable.name
form.unit.default = consumable.unit
# preinitialize the defaults with potentially existing values from a try before
if form.name.data is not None:
form.name.default = form.name.data
if form.unit.data is not None:
form.unit.default = form.unit.data
if form.validate_on_submit():
consumable.name = form.name.data
consumable.unit = form.unit.data
try:
db.session.commit()
tools.db_log_update(consumable)
except IntegrityError:
db.session.rollback()
form.name.errors.append('"%s" is not unique.' % (form.name.data))
return render_template('editConsumableForm.html', form=form)
return redirect(url_for('get_admin_page'))
return render_template('editConsumableForm.html', form=form)
@app.route('/account', methods=['GET'])
@login_required
def get_account_page():
return render_template('account.html', data=g.data)
@app.route('/statistics', methods=['GET'])
@login_required
def get_statistics():
stats = []
for vehicle in current_user.vehicles:
stats.append(tools.VehicleStats(vehicle))
return render_template('statistics.html', data=stats)
@app.route('/account/delete', methods=['GET', 'POST'])
@login_required
def delete_account():
form = DeleteAccountForm()
if form.validate_on_submit():
user_datastore.delete_user(current_user)
db.session.commit()
return redirect(url_for('index'))
return render_template('deleteAccountForm.html', form=form)

View File

@@ -0,0 +1,6 @@
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_USERNAME = 'your-gmail-username'
MAIL_PASSWORD = 'your-gmail-password'

View File

@@ -1,92 +0,0 @@
'''
@author: shing19m
'''
from datetime import datetime
import sqlite3
class Db(object):
'''
classdocs
'''
def __init__(self, db_file):
'''
Constructor
'''
self.db = sqlite3.connect(db_file)
def __del__(self):
self.db.close()
def getAllPitStops(self):
return self._perform_query('select * from pitstops order by id asc')
def getAllServices(self):
return self._perform_query('select * from services')
def getLastPitStop(self):
pitstops = self._perform_query('select * from pitstops order by id desc limit 1')
if len(pitstops) == 0:
return {'date': datetime.strftime(datetime.now(), '%Y-%m-%d'), 'odometer': 0, 'litres': 0}
return pitstops[0]
def get_service_warning_info(self):
info = self._perform_query('select (odometer_planned - (select odometer from pitstops order by id desc limit 1)) km_left, tasks from services where date is null order by odometer_planned asc limit 1;')
if len(info) == 0:
return None
return info[0]
def get_next_undone_service(self):
services = self._perform_query('select * from services where date is null limit 1')
if len(services) == 0:
return None
return services[0]
def get_salt_for_user(self, user):
salt = self._perform_query_param('select salt from users where name = ?', [user])
if len(salt) == 0:
return None
return salt[0]['salt']
def check_password_for_user(self, user, password):
user = self._perform_query_param('select * from users where name = ? and password = ?', [user, password])
if len(user) == 0:
return False
return True
def _perform_query_param(self, query, data):
cursor = self.db.execute(query, data)
names = list(map(lambda x: x[0], cursor.description))
result = []
for row in cursor.fetchall():
row_result = {}
for index in range(0, len(names)):
row_result[names[index]] = row[index]
result.append(row_result)
return result
def _perform_query(self, query):
cursor = self.db.execute(query)
names = list(map(lambda x: x[0], cursor.description))
result = []
for row in cursor.fetchall():
row_result = {}
for index in range(0, len(names)):
row_result[names[index]] = row[index]
result.append(row_result)
return result
def addPitStop(self, date, odometer, litres):
self.db.execute('insert into pitstops (date, odometer, litres) values (?, ?, ?)', [date, odometer, litres])
self.db.commit()
def init_db(self, resource):
with resource as f:
sql_commands = f.read()
self.db.cursor().executescript(sql_commands)
self.db.commit()

142
app/entities.py Normal file
View File

@@ -0,0 +1,142 @@
from app import db
from flask_security import UserMixin, RoleMixin
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
vehicles_consumables = db.Table('vehicles_consumables',
db.Column('vehicle_id', db.Integer(), db.ForeignKey('vehicle.id')),
db.Column('consumable_id', db.Integer(), db.ForeignKey('consumable.id')))
class Role(db.Model, RoleMixin):
"""
Entity to handle different roles for users: Typically user and admin exist
"""
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
def __str__(self):
return self.name
def __hash__(self):
return hash(self.name)
class User(db.Model, UserMixin):
"""
Entity to represent a user including login data and links to roles and vehicles.
"""
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
vehicles = db.relationship(
'Vehicle'
)
roles = db.relationship(
'Role',
secondary=roles_users,
backref=db.backref('users', lazy='dynamic')
)
def __repr__(self):
return '<User id="%r" email="%r" ' % (self.id, self.email)
class Vehicle(db.Model):
"""
Entity to represent a vehicle.
Attributes:
* name of the vehilce
* the id of the owner
* list of pitstops
* list of possible consumables
"""
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integer, db.ForeignKey('user.id'))
name = db.Column(db.String(255))
pitstops = db.relationship(
'Pitstop'
)
consumables = db.relationship(
'Consumable',
secondary=vehicles_consumables
)
# 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'),)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Vehicle id="%r" owner_id="%r" name="%r" />' % (self.id, self.owner_id, self.name)
class Pitstop(db.Model):
"""
Entity to represent a pitstop for a single consumable.
Attributes:
* the date of the pitstop
* the odometer of the pitstop
* the id of the fuelled consumable
* amount of consumable used
* the costs of the consumable
* the id of the vehicle that was refuelled
"""
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.Date)
odometer = db.Column(db.Integer)
consumable_id = db.Column(db.Integer, db.ForeignKey('consumable.id'))
amount = db.Column(db.Numeric(5, 2))
costs = db.Column(db.Numeric(5, 2), default=0)
vehicle_id = db.Column(db.Integer, db.ForeignKey('vehicle.id'))
# short cut to access the fuelled consumable of the pitstop
consumable = db.relationship('Consumable')
# this uniqueness constraint makes sure that for each consumable and each vehicle only one pitstop exists at the
# same odometer
__table_args__ = (db.UniqueConstraint('odometer',
'consumable_id',
'vehicle_id',
name='_odometer_consumable_vehicle_uniq'),)
def __init__(self, odometer, amount, date, costs, consumable_id):
self.odometer = odometer
self.amount = amount
self.date = date
self.costs = costs
self.consumable_id = consumable_id
def __repr__(self):
return '<Pitstop odometer="%r" amount="%r" date="%r" vehicle_id="%r" consumable_id="%r">' % \
(self.odometer, self.amount, self.date, self.vehicle_id, self.consumable_id)
class Consumable(db.Model):
"""
Entity to represent a material that be consumed by a vehilce.
Attributes:
* name (must be globally unique)
* unit
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), unique=True)
unit = db.Column(db.String(255))
vehicles = db.relationship(
'Vehicle',
secondary=vehicles_consumables
)
def __init__(self, name, unit):
self.name = name
self.unit = unit
def __repr__(self):
return '<Consumable name="%s" unit="%s" />' % (self.name, self.unit)

22
app/filters.py Normal file
View File

@@ -0,0 +1,22 @@
from app import app
import hashlib
@app.template_filter('none_filter')
def none_filter(value):
if value is None:
return ''
else:
return value
@app.template_filter('md5')
def md5_filter(value):
m = hashlib.md5()
m.update(str(value).encode('UTF-8'))
return m.hexdigest()
@app.template_filter('str')
def str_filter(value):
return str(value)

169
app/forms.py Normal file
View File

@@ -0,0 +1,169 @@
from flask_wtf import Form
from wtforms import DateField, IntegerField, DecimalField, StringField, SelectField, SubmitField, SelectMultipleField, BooleanField
from wtforms.validators import ValidationError, Length
from datetime import date
def date_check(form, field):
"""
Checks that the date of the pitstop is not before the date of the latest pitstop and not after today.
:param form: the form where the field is in
:param field: the field to check
:return: Nothing or a ValidationError if the limits are not kept
"""
if field.data < form.last_pitstop.date:
raise ValidationError('The new date must not be before %s' % form.last_pitstop.date)
if field.data > date.today():
raise ValidationError('The new date must not be after %s' % date.today())
def odometer_check(form, field):
"""
:param form:
:param field:
:return:
"""
if not form.same_odometer_allowed and field.data <= form.last_pitstop.odometer:
raise ValidationError('The new odometer value must be higher than %i km' % form.last_pitstop.odometer)
if form.same_odometer_allowed and field.data < form.last_pitstop.odometer:
raise ValidationError('The new odometer value must be higher than %i km' % form.last_pitstop.odometer)
def litres_check(form, field):
if field.data is not None and field.data <= 0:
raise ValidationError('You must fuel at least 0.1 l')
def costs_check(form, field):
if field.data is not None and field.data <= 0:
raise ValidationError('Costs must be above 0.01 €.')
def edit_costs_check(form, field):
"""
Costs must be given, if a default value was given to the form field.
:param form:
:param field:
:return:
"""
costs_check_required = (form.costs.default is not None and form.costs.default > 0)
if costs_check_required and field.data is not None and field.data <= 0:
raise ValidationError('Costs must be above 0.01 €.')
class SelectVehicleForm(Form):
vehicle = SelectField('Vehicle', coerce=int)
submit = SubmitField(label='Do it!')
class SelectConsumableForm(Form):
consumable = SelectField('Consumable', coerce=int)
submit = SubmitField(label='Do it!')
class CreatePitstopForm(Form):
date = DateField('Date of Pitstop', validators=[date_check])
odometer = IntegerField('Odometer (km)', validators=[odometer_check])
litres = DecimalField('Litres (l)', places=2, validators=[litres_check])
costs = DecimalField('Costs (€, overall)', places=2, validators=[costs_check])
submit = SubmitField(label='Do it!')
last_pitstop = None
same_odometer_allowed = True
def set_pitstop(self, last_pitstop):
self.last_pitstop = last_pitstop
def set_consumable(self, consumable):
self.litres.label = '%s (%s)' % (consumable.name, consumable.unit)
def preinit_with_data(self):
if self.date.data:
self.date.default = self.date.data
else:
self.date.default = date.today()
if self.odometer.data:
self.odometer.default = self.odometer.data
else:
self.odometer.default = self.last_pitstop.odometer
if self.litres.data:
self.litres.default = self.litres.data
else:
self.litres.default = self.last_pitstop.amount
if self.costs.data:
self.costs.default = self.costs.data
else:
self.costs.default = self.last_pitstop.costs
def get_hint_messages(self):
if self.same_odometer_allowed:
or_equal = ' or equal to'
else:
or_equal = ''
messages = {
'date': 'Date must be between %s and %s (including).' % (str(self.last_pitstop.date), str(date.today())),
'odometer': 'Odometer must be greater than%s %s km.' % (or_equal, str(self.last_pitstop.odometer)),
'costs': 'Costs must be higher than 0.01 €.'
}
return messages
class EditVehicleForm(Form):
name = StringField('Name', validators=[Length(1, 255)])
consumables = SelectMultipleField('Consumables', coerce=int,validators=[])
submit = SubmitField(label='Do it!')
class DeleteVehicleForm(Form):
submit = SubmitField(label='Do it!')
class DeleteAccountForm(Form):
submit = SubmitField(label='Really delete my account!')
class DeletePitStopForm(Form):
submit = SubmitField(label='Really delete this pitstop!')
class EditPitstopForm(Form):
date = DateField('Date of Pitstop', validators=[date_check])
odometer = IntegerField('Odometer (km)', validators=[odometer_check])
litres = DecimalField('Litres (l)', places=2, validators=[litres_check])
costs = DecimalField('Costs (€, overall)', places=2, validators=[edit_costs_check])
submit = SubmitField(label='Update it!')
last_pitstop = None
same_odometer_allowed = True
def set_pitstop(self, last_pitstop):
self.last_pitstop = last_pitstop
def set_consumable(self, consumable):
self.litres.label = '%s (%s)' % (consumable.name, consumable.unit)
def preinit_with_data(self):
if self.date.data:
self.date.default = self.date.data
if self.odometer.data:
self.odometer.default = self.odometer.data
if self.litres.data:
self.litres.default = self.litres.data
if self.costs.data:
self.costs.default = self.costs.data
class CreateConsumableForm(Form):
name = StringField('Name', validators=[Length(1, 255)])
unit = StringField('Unit', validators=[Length(1, 255)])
submit = SubmitField(label='Do it!')
class EditConsumableForm(Form):
name = StringField('Name', validators=[Length(1, 255)])
unit = StringField('Unit', validators=[Length(1, 255)])
submit = SubmitField(label='Do it!')
class DeletConsumableForm(Form):
submit = SubmitField(label='Do it!')

View File

@@ -1,186 +0,0 @@
from datetime import datetime
from flask import Flask
from flask import render_template, make_response
from flask import request, redirect, g
from flask import url_for
from flask import Response
import hashlib
import os.path
import time
from functools import wraps
import db
#from db import Db
app = Flask(__name__)
DATABASE = '/data/rollerverbrauch.db'
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
def check_auth(username, password):
salt = g.db2.get_salt_for_user(username)
if salt == None:
return False
m = hashlib.sha256(password.encode('utf-8'))
m = hashlib.sha256((m.hexdigest()+salt).encode('utf-8'))
digest = m.hexdigest()
ok = g.db2.check_password_for_user(username, digest)
if not ok:
app.logger.error("digest: " + digest)
return ok
def authenticate():
resp = make_response(render_template('login_required.html'), 401)
resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
return resp
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.before_request
def before_request():
g.db2 = db.Db(app.config['DATABASE'])
g.data = {}
add_service_warning(g.data)
@app.teardown_request
def teardown_request(exception):
pass
@app.route('/')
@requires_auth
def index():
return redirect(url_for('get_pit_stops'))
@app.route('/services')
@requires_auth
def get_services():
data = g.db2.getAllServices()
data.reverse()
g.data['services'] = data
return render_template('services.html', data=g.data)
@app.route('/pitstops', methods=['POST'])
@requires_auth
def create_pit_stop():
last_pitstop = g.db2.getLastPitStop()
errorMsg = {}
date = request.form['date']
try:
date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d')
except ValueError:
errorMsg['date'] = 'invalid date, only YYYY-MM-DD is allowed'
date = request.form['date']
odometer = request.form['odometer']
try:
odometer = int(odometer)
except ValueError:
errorMsg['odometer'] = 'Illegal Value, only Integers allowed'
odometer = None
if odometer is not None and odometer <= last_pitstop['odometer']:
errorMsg['odometer'] = 'Illegal Value, new Value must be bigger as given value'
odometer = request.form['odometer']
if odometer is None:
odometer = request.form['odometer']
litres = request.form['litres']
try:
litres = float(litres)
except ValueError:
errorMsg['litres'] = 'Illegal Value, only floating point allowed'
litres = None
if litres is not None and litres <= 0:
errorMsg['litres'] = 'Litres must not be 0'
litres = request.form['litres']
if litres is None:
litres = request.form['litres']
# error checking here
if len(errorMsg) > 0:
data = {'last': {'date': date, 'odometer': odometer, 'litres': litres}, 'error': errorMsg}
return render_template('newPitStopForm.html', data=data)
g.db2.addPitStop(date, odometer, litres)
return redirect(url_for('get_pit_stops'))
@app.route('/pitstops/createForm', methods=['GET'])
@requires_auth
def create_pit_stop_form():
values = g.db2.getLastPitStop()
values['date'] = time.strftime("%Y-%m-%d")
g.data['last'] = values
g.data['error'] = None
return render_template('newPitStopForm.html', data=g.data)
def add_service_warning(data):
service_info = g.db2.get_service_warning_info()
data['service_info'] = service_info
@app.route('/pitstops', methods=['GET'])
@requires_auth
def get_pit_stops():
data = prepare_pit_stops(g.db2.getAllPitStops())
g.data['pitstops'] = data
return render_template('pitstops.html', data=g.data)
@app.route('/manual', methods=['GET'])
@requires_auth
def get_manual():
return render_template('manual.html', data=g.data)
@app.route('/statistics', methods=['GET'])
@requires_auth
def get_statistics():
pitstops = g.db2.getAllPitStops()
count = len(pitstops)
distance = 0
sumLitres = 0
averageDistance = 0
averageLitresFuelled = 0
averageLitresUsed = 0
if count > 0:
sumLitres = 0
for pitstop in pitstops:
sumLitres += pitstop['litres']
averageLitresFuelled = sumLitres/count
if count > 1:
distance = pitstops[-1]['odometer'] - pitstops[0]['odometer']
averageDistance = distance/(count - 1)
averageLitresUsed = 100 * (sumLitres-pitstops[0]['litres'])/distance
g.data['distance'] = distance
g.data['count'] = count
g.data['litres'] = sumLitres
g.data['averageDistance'] = averageDistance
g.data['averageListresFuelled'] = averageLitresFuelled
g.data['averageListresUsed'] = averageLitresUsed
return render_template('statistics.html', data=g.data)
def prepare_pit_stops(pitstops):
for index in range(1, len(pitstops)):
last = pitstops[index - 1]
curr = pitstops[index]
curr['distance'] = curr['odometer'] - last['odometer']
curr['average'] = 100 * curr['litres']/curr['distance']
last_date = datetime.strptime(last['date'], '%Y-%m-%d')
curr_date = datetime.strptime(curr['date'], '%Y-%m-%d')
curr['days'] = (curr_date - last_date).days
pitstops.reverse()
return pitstops
if __name__ == '__main__':
if not os.path.isfile(DATABASE) or os.stat(DATABASE).st_size == 0:
db = db.Db(app.config['DATABASE'])
db.init_db(app.open_resource('schema.sql', mode='r'))
app.run(debug=True, host='0.0.0.0')

View File

@@ -1,2 +0,0 @@
#db-sqlite3
Flask

View File

@@ -1,25 +0,0 @@
drop table if exists pitstops;
create table pitstops (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`date` TEXT NOT NULL,
`odometer` INTEGER NOT NULL,
`litres` REAL NOT NULL
);
drop table if exists services;
CREATE TABLE `services` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`date` TEXT,
`odometer_planned` INTEGER NOT NULL,
`odometer_done` INTEGER,
`tasks` TEXT NOT NULL
);
drop table if exists users;
create table `users` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`salt` TEXT NOT NULL,
`password` TEXT NOT NULL
);
insert into users (name, salt, password) values ('shing19m', 'pL85Kl2U', '207357fdbf6f379c53bb5ab7fa0bc8c0072ae743973a510f551db7b5c90049b7');

View File

@@ -1,8 +1,10 @@
body {
padding-top: 50px;
}
.starter-template {
padding: 40px 15px;
padding-top: 30px;
padding-bottom: 60px;
text-align: center;
}
@@ -22,9 +24,55 @@ td {
color: #a94442;
}
.pitstop {
}
.nav-pills > li > a {
border: 1px solid;
}
h1 {
margin-top: 0px;
}
h2 {
margin-top: 0px;
}
h3 {
margin-top: 0px;
text-align: center;
}
h3:before{
content:"― ";
}
h3:after{
content:" ―";
}
.tab-content > .active {
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
border-bottom: 1px solid #ddd;
padding: 1px;
padding-top: 15px;
}
.panel-body > p, .panel-body > ul {
text-align: left;
}
// for small devices
@media only screen
and (min-device-width : 320px)
and (max-device-width : 568px) {
h3:before{
content:"";
}
h3:after{
content:"";
}
#charts_tabs {
display:none;
}
#charts_tabs-content {
display:none;
}
}

View File

@@ -1 +1,80 @@
function createChart(id, data, unit) {
return AmCharts.makeChart(id, {
"type": "serial",
//"theme": "chalk",
//"marginRight": 40,
//"marginLeft": 40,
//"autoMarginOffset": 20,
"mouseWheelZoomEnabled":true,
"dataDateFormat": "YYYY-MM-DD",
"valueAxes": [{
"id": "v1",
"axisAlpha": 0,
"position": "left",
"ignoreAxisWidth":true,
// "title": unit
}],
"balloon": {
"borderThickness": 1,
"shadowAlpha": 10,
},
"graphs": [{
"id": "g1",
"balloon":{
"drop":false,
"adjustBorderColor":false,
"color":"#ffffff",
},
"bullet": "round",
"bulletBorderAlpha": 1,
"bulletColor": "#000000",
"bulletSize": 5,
"hideBulletsCount": 50,
"lineThickness": 2,
// "title": unit,
//"useLineColorForBulletBorder": true,
"valueField": "value",
"balloonText": "<span style='font-size:18px;'>[[value]] "+unit+"</span>"
}],
"chartScrollbar": {
"graph": "g1",
"oppositeAxis":false,
"offset":30,
"scrollbarHeight": 80,
"backgroundAlpha": 0,
"selectedBackgroundAlpha": 0.1,
"selectedBackgroundColor": "#888888",
"graphFillAlpha": 0,
"graphLineAlpha": 0.5,
"selectedGraphFillAlpha": 0,
"selectedGraphLineAlpha": 1,
"autoGridCount":true,
"color":"#AAAAAA"
},
"chartCursor": {
"pan": true,
"valueLineEnabled": true,
"valueLineBalloonEnabled": true,
"cursorAlpha":1,
"cursorColor":"#258cbb",
"limitToGraph":"g1",
"valueLineAlpha":0.2,
"valueZoomable":true
},
"valueScrollbar":{
"oppositeAxis":false,
"offset":50,
"scrollbarHeight":10
},
"categoryField": "date",
"categoryAxis": {
"parseDates": true,
"dashLength": 1,
// "minorGridEnabled": true
},
"export": {
"enabled": true
},
"dataProvider": data
});
}

View File

@@ -0,0 +1,67 @@
{% extends "layout.html" %}
{% block body %}
<h3>Account management for {{current_user.email}}</h3>
<div class="panel panel-default">
<div class="panel-heading">Password</div>
<div class="panel-body">
<a href='{{ url_for('security.change_password') }}' class="btn btn-primary " role="button">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Change
</a>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Vehicles</div>
<div class="panel-body">
<a href="{{ url_for('create_vehicle') }}" class="btn btn-primary " role="button">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> create
</a>
</div>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<th>
Vehicle
</th>
<th>
Info
</th>
<th>
Actions
</th>
</tr>
{% for vehicle in current_user.vehicles %}
<tr>
<td>
{{ vehicle.name }}
</td>
<td>
{{ vehicle.pitstops | length }} pitstops<br />
{{ vehicle.consumables | length }} consumables
</td>
<td>
<a href="{{ url_for('edit_vehicle', vid=vehicle.id) }}" class="btn btn-primary " role="button">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> edit
</a>
{% if current_user.vehicles | length > 1 %}
<a href="{{ url_for('delete_vehicle', vid=vehicle.id) }}" class="btn btn-primary btn-warning " role="button">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> delete
</a>
{% else %}
&nbsp;
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="panel panel-default">
<div class="panel-heading">Account</div>
<div class="panel-body">
<a href='{{ url_for('delete_account') }}' class="btn btn-primary " role="button">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Delete
</a>
</div>
</div>
{% endblock %}

66
app/templates/admin.html Normal file
View File

@@ -0,0 +1,66 @@
{% extends "layout.html" %}
{% block body %}
<h3>Admin</h3>
<div class="panel panel-default">
<div class="panel-heading">Users</div>
<div class="panel-body">
We have {{ users|length }} users so far:
<ul>
{% for user in users %}
<li>{{user.email}}</li>
{% endfor %}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Consumables</div>
<div class="panel-body">
<a href="{{ url_for('create_consumable') }}" class="btn btn-primary " role="button">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> create
</a>
</div>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<th>
Name
</th>
<th>
Unit
</th>
<th>
Used by
</th>
<th>
Actions
</th>
</tr>
{% for consumable in consumables %}
<tr>
<td>
{{ consumable.name }}
</td>
<td>
{{ consumable.unit }}
</td>
<td>
{{ consumable.vehicles | length }} vehicles
</td>
<td>
{% if not consumable.in_use %}
<a href="{{ url_for('delete_consumable', cid=consumable.id) }}" class="btn btn-primary btn-warning " role="button">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> delete
</a>
{% endif %}
<a href="{{ url_for('edit_consumable', cid=consumable.id) }}" class="btn btn-primary " role="button">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> edit
</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% 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>Create consumable</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.unit) }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,30 @@
{% 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>New Pitstop for '{{ vehicle.name }}'</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.date) }}
<span id="{{form.date.id}}_help" class="help-block">
{{messages['date']}}
</span>
{{ render_field_with_errors(form.odometer) }}
<span id="{{form.odometer.id}}_help" class="help-block">
{{messages['odometer']}}
</span>
{{ render_field_with_errors(form.litres) }}
{{ render_field_with_errors(form.costs) }}
<span id="{{form.costs.id}}_help" class="help-block">
{{messages['costs']}}
</span>
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% 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>Create vehicle</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.consumables) }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,18 @@
{% 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>Delete account for '{{current_user.email}}'?</h3>
This cannot be undone!
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,18 @@
{% 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>Delete vehicle '{{consumable.name}}'?</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,42 @@
{% 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>Delete pitstop?</h3>
<table style='width: 100%'>
<tr>
<th style='text-align:right'>Date of Pitstop</th>
<td style='text-align: left'>{{ pitstop.date }}</td>
</tr>
<tr>
<th style='text-align:right'>Odometer</th>
<td style='text-align: left'>{{ pitstop.odometer }} km</td>
</tr>
<tr>
<th style='text-align:right'>Litres</th>
<td style='text-align: left'>{{ pitstop.amount }} {{ pitstop.consumable.unit }}</td>
</tr>
<tr>
<th style='text-align:right'>Costs (overall)</th>
<td style='text-align: left'>
{% if pitstop.costs %}
{{pitstop.costs}}
{% else %}
--
{% endif %}
</td>
</tr>
</table>
<form class='form-horizontal' method='POST'>
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class='col-md-2' ></div>
{% endblock %}

View File

@@ -0,0 +1,18 @@
{% 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>Delete vehicle '{{vehicle.name}}'?</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% 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>Edit consumable </h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.unit) }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,29 @@
{% 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>Edit Pitstop for '{{ vehicle.name }}'</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.date) }}
<span id="{{form.date.id}}_help" class="help-block">
{{messages['date']}}
</span>
{{ render_field_with_errors(form.odometer) }}
<span id="{{form.odometer.id}}_help" class="help-block">
{{messages['odometer']}}
</span>
{{ render_field_with_errors(form.litres) }}
{{ render_field_with_errors(form.costs) }}
<span id="{{form.costs.id}}_help" class="help-block">
{{messages['costs']}}
</span>
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% 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>Edit vehicle</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.name) }}
{{ render_field_with_errors(form.consumables) }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
{% endblock %}

34
app/templates/index.html Normal file
View File

@@ -0,0 +1,34 @@
{% extends "layout.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block body %}
<div class="row">
<div class="col-md-4">
{{ render_login_form() }}
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body" >
<h1>Join the pitstop community!</h1>
<p>There are already {{ data.users}} members with {{ data.vehicles }} vehicles who have logged {{ data.kilometers }}km in {{ data.pitstops }} pitstops. They fuelled</p>
<ul>
{% for key in data.consumables %}
{% set consumable = data.consumables[key] %}
<li>{{consumable.amount}}{{consumable.unit}} of {{consumable.name}}</li>
{% endfor %}
</ul>
<p>With pitstop community you can:</p>
<ul>
<li>manage multiple vehicles</li>
<li>track each pitstop</li>
<li>get statistics about the fuel consumption</li>
</ul>
<p><a href='{{ url_for('security.register') }}'>Register your account now</a> or <a href='{{ url_for('security.login') }}'>log into your account</a>.</p>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -1,32 +1,96 @@
{% macro alert_level(km_left) -%}
{% if km_left == None %}
alert-success
{% elif km_left < 0 %}
alert-danger
{% elif km_left < 300 %}
alert-warning
{% macro navigation() -%}
{% if current_user.email %}
<li><a href='{{ url_for('select_vehicle_for_new_pitstop') }}'>Create Pitstop</a></li>
<li><a href='{{ url_for('get_statistics') }}'>Statistics</a></li>
<li><a href='{{ url_for('get_account_page') }}'>Account</a></li>
{% if current_user.has_role('admin') %}
<li><a href='{{ url_for('get_admin_page') }}'>Admin</a></li>
{% endif %}
<li><a href='{{ url_for('security.logout') }}'>Logout</a></li>
{% else %}
alert-success
{% endif %}
{%- endmacro %}
{% macro service_warning() -%}
{% if data != None and data.service_info != None and 'km_left' in data.service_info %}
<div class="alert {{ alert_level(data.service_info['km_left']) }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
Service required in {{ data.service_info['km_left'] }} km. Tasks: {{ data.service_info['tasks'] }}.
</div>
<li><a href='{{ url_for('security.login') }}'>Login</a></li>
<li><a href='{{ url_for('security.register') }}'>Register</a></li>
{% endif %}
{%- endmacro %}
{% macro navigation() -%}
<li><a href='{{ url_for('create_pit_stop_form') }}'>Create Pitstop</a></li>
<li><a href='{{ url_for('get_statistics') }}'>Statistics</a></li>
<li><a href='{{ url_for('get_services') }}'>Services</a></li>
<li><a href='{{ url_for('get_manual') }}'>Manual</a></li>
{%- endmacro %}
{% macro render_field_with_errors(field) %}
<div class="form-group">
{% if field.type == 'SubmitField' %}
<div class="col-md-4" ></div>
<div class="col-sm-4" style="align:center">
<input id="{{ field.id }}" name="{{ field.id }}" class="btn btn-default" type="submit" value="{{ field.label.text }}">
</div>
<!--
<div class="col-sm-3" style="align:center">
<a class="btn btn-default" href="{{ g.data['back'] }}" role="button">Cancel</a>
</div>
-->
<div class="col-md-4" ></div>
{% else %}
<label class="col-sm-6 control-label">
{{ field.label }}
</label>
<div class="col-sm-6">
{% if field.type == 'SelectField' %}
<select id="{{ field.id }}" name="{{ field.id }}" class="form-control">
{% for choice in field.choices %}
<option value="{{ choice[0] }}" {% if choice[0] == field.default %}selected="selected"{%endif%}>{{ choice[1] }}</option>
{% endfor %}
</select>
{% elif field.type == 'SelectMultipleField' %}
<select id="{{ field.id }}" name="{{ field.id }}" class="form-control" multiple="multiple">
{% for choice in field.choices %}
<option value="{{ choice[0] }}" {% if choice[0] in field.default %}selected="selected"{%endif%}>{{ choice[1] }}</option>
{% endfor %}
</select>
{% 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" />
{% 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" />
{% elif field.type == 'PasswordField' %}
<input class="form-control" type="password" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" aria-describedby="{{ field.id }}_help" />
{% elif field.type == 'DateField' %}
<input class="form-control" type="date" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" aria-describedby="{{ field.id }}_help" />
{% elif field.type == 'IntegerField' %}
<input class="form-control" type="number" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" step="1" aria-describedby="{{ field.id }}_help" />
{% elif field.type == 'DecimalField' %}
<input class="form-control" type="number" id="{{ field.id }}" name="{{ field.id }}" value="{{ field.default|none_filter }}" step="{{ 1 / 10 ** field.places}}" aria-describedby="{{ field.id }}_help" />
{% else %}
{{ field(**kwargs)|safe }}
{% endif %}
{% if field.errors %}
<p class='error'>
{% for error in field.errors %}
{{ error }}
{% endfor %}
</p>
{% endif %}
</div>
{% endif %}
</div>
{% endmacro %}
{% macro render_login_form() %}
<div class="panel panel-default">
<div class="panel-body">
<h3>Login</h3>
<form class='form-horizontal' action="{{ url_for_security('login') }}" method="POST" name="login_user_form">
{{ login_user_form.hidden_tag() }}
{{ render_field_with_errors(login_user_form.email) }}
{{ render_field_with_errors(login_user_form.password) }}
{{ render_field_with_errors(login_user_form.remember) }}
{{ render_field(login_user_form.next) }}
{{ render_field_with_errors(login_user_form.submit) }}
{% if security.recoverable %}
<a href="{{ url_for_security('forgot_password') }}">Forgot password</a>
{% endif %}
</form>
</div>
</div>
{% endmacro %}
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
@@ -36,7 +100,7 @@
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Rollerverbrauch</title>
<title>refuel journal</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="{{ url_for('static', filename='apple-touch-icon-57.png') }}">
@@ -63,6 +127,10 @@
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='main.css') }}">
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/patterns.js"></script>
<script src="{{ url_for('static', filename='main.js') }}"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
@@ -74,7 +142,7 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ url_for('get_pit_stops') }}">Rollerverbrauch</a>
<a class="navbar-brand" href="{{ url_for('index') }}">refuel journal</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
@@ -90,7 +158,14 @@
{% endblock %}
</div>
</div>
{#
<nav class="navbar navbar-inverse navbar-fixed-bottom">
<div class="container">
<div class="navbar-footer">
<a class="navbar-brand" href="">Imprint</a>
</div>
</div>
</nav>
#}
</body>
</html>

View File

@@ -1,5 +0,0 @@
{% extends "layout.html" %}
{% block body %}
Please authorize yourself!
{% endblock %}

View File

@@ -12,7 +12,6 @@
{%- endmacro %}
{% block body %}
{{ service_warning() }}
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">

View File

@@ -1,44 +0,0 @@
{% extends "layout.html" %}
{% block body %}
{{ service_warning() }}
<form class='form-horizontal' id='createPitStop' action="{{ url_for('create_pit_stop') }}" method='post'>
<!-- Text input-->
<div class="form-group {% if data.error['date'] %}has-error{% endif %}">
<label class="col-sm-2 control-label" for="date">Date of Pitstop</label>
<div class="col-sm-10">
<input class="form-control" id="date" name="date" placeholder="" required="" type="date" value='{{ data.last.date }}' />
<p class='error'>{{ data.error['date'] }}</p>
</div>
</div>
<!-- Text input-->
<div class="form-group {% if data.error['odometer'] %}has-error{% endif %}">
<label class="col-sm-2 control-label" for="odometer">Odometer (km)</label>
<div class="col-sm-10">
<input class="form-control" id="odometer" name="odometer" placeholder="" type="number" value='{{ data.last.odometer }}' />
<p class='error'>{{ data.error['odometer'] }}</p>
</div>
</div>
<!-- Text input-->
<div class="form-group {% if data.error['litres'] %}has-error{% endif %}">
<label class="col-sm-2 control-label" for="litres">Litres (l)</label>
<div class="col-sm-10">
<input class="form-control" id="litres" name="litres" placeholder="" type="number" step='0.1' value='{{ data.last.litres }}' />
<p class='error'>{{ data.error['litres'] }}</p>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<div class="controls">
<button id="buttonLogId" name="buttonLogId" class="btn btn-success" onclick="document.getElementById('create_pit_stop').submit();">Log Pitstop</button>
<button id="buttonAbortId" name="buttonAbortId" class="btn btn-warning" onclick="window.location.href='{{ url_for('get_pit_stops') }}'" type="button" >Abort</button>
</div>
</div>
</form>
{% endblock %}

View File

@@ -1,40 +1,78 @@
{% extends "layout.html" %}
{% extends "layout.html" %}
{% block body %}
{{ service_warning() }}
<div class="col-md-2" ></div>
<div class="col-md-8">
<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
{% for vehicle in current_user.vehicles %}
<li {% if loop.first %}class="active" {%endif %}>
<a href="#v{{vehicle.id}}" id="i{{vehicle.id}}" data-toggle="tab">
{{ vehicle.name }}
</a>
</li>
{% endfor %}
</ul>
<div id="my-tab-content" class="tab-content">
{% for vehicle in current_user.vehicles %}
<div class="tab-pane {% if loop.first %}active{% endif %}" id="v{{vehicle.id}}">
<h3>{{vehicle.name}}</h3>
{% if vehicle.pitstops %}
{% for pitstop in vehicle.pitstops|reverse %}
<div class="panel panel-default">
<div class="panel-body">
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>Date</th>
<td>{{pitstop.date}}</td>
</tr>
<tr>
<th>Odometer</th>
<td>{{pitstop.odometer}} km</td>
</tr>
<tr>
<th>{{ pitstop.consumable.name }}</th>
<td>{{pitstop.amount}} {{ pitstop.consumable.unit }}</td>
</tr>
<tr>
<th>Costs</th>
<td>
{% if pitstop.costs %}
{{pitstop.costs}} €
{% else %}
-- €
{% endif %}
</td>
</tr>
</table>
{% if loop.first %}
<a href="{{ url_for('edit_pit_stop_form', pid=pitstop.id) }}" class="btn btn-primary">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> edit
</a>
<a href="{{ url_for('delete_pit_stop_form', pid=pitstop.id) }}" class="btn btn-primary btn-warning ">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> delete
</a>
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<div class="alert alert-warning" role="alert">
not enough data: <a href="{{ url_for('select_consumable_for_new_pitstop', vid=vehicle.id) }}">log a pitstop</a>?
</div>
{% endif %}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-2" ></div>
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>
Date<br />
Days
</th>
<th>
Odometer<br />
Distance
</th>
<th>
Litres<br />
Average
</th>
</tr>
{% for pitstop in data['pitstops'] %}
<tr class='pitstop'>
<td>
{{pitstop.date}}<br />
{% if pitstop.days %}{{pitstop.days}}{% else %} --{% endif %} days
</td>
<td>
{{pitstop.odometer}} km<br />
{% if pitstop.distance %}{{pitstop.distance}}{% else %} --{% endif %} km
</td>
<td>
{{pitstop.litres}} l<br />
{% if pitstop.average %}{{pitstop.average | round(2)}}{% else %} --{% endif %} l/100km
</td>
</tr>
{% endfor %}
</table>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#tabs').tab();
if(window.location.hash != "") {
$('a[href="' + window.location.hash + '"]').click()
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,20 @@
{% extends "layout.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block body %}
<div class="col-md-2" ></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<h3>Change password</h3>
<form class='form-horizontal' action="{{ url_for_security('change_password') }}" method="POST" name="change_password_form">
{{ change_password_form.hidden_tag() }}
{{ render_field_with_errors(change_password_form.password) }}
{{ render_field_with_errors(change_password_form.new_password) }}
{{ render_field_with_errors(change_password_form.new_password_confirm) }}
{{ render_field_with_errors(change_password_form.submit) }}
</form>
</div>
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% extends "layout.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block body %}
<div class="col-md-2" ></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<h3>Reset password</h3>
<form class='form-horizontal' action="{{ url_for_security('forgot_password') }}" method="POST" name="forgot_password_form">
{{ forgot_password_form.hidden_tag() }}
{{ render_field_with_errors(forgot_password_form.email) }}
{{ render_field_with_errors(forgot_password_form.submit) }}
</form>
</div>
</div>
<div class="col-md-2" ></div>
</div>
{% endblock %}

View File

@@ -0,0 +1,13 @@
{% extends "layout.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block body %}
<div class="row">
<div class="col-md-2" ></div>
<div class="col-md-8">
{{ render_login_form() }}
</div>
<div class="col-md-2" ></div>
</div>
{% endblock %}

View File

@@ -0,0 +1,23 @@
{% extends "layout.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block body %}
<div class="col-md-2" ></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<h3>Register</h3>
<form class='form-horizontal' action="{{ url_for_security('register') }}" method="POST" name="register_user_form">
{{ register_user_form.hidden_tag() }}
{{ render_field_with_errors(register_user_form.email) }}
{{ render_field_with_errors(register_user_form.password) }}
{% if register_user_form.password_confirm %}
{{ render_field_with_errors(register_user_form.password_confirm) }}
{% endif %}
{{ render_field_with_errors(register_user_form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,12 @@
{% extends "layout.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block body %}
<h1>Reset password</h1>
<form class='form-horizontal' action="{{ url_for_security('reset_password', token=reset_password_token) }}" method="POST" name="reset_password_form">
{{ reset_password_form.hidden_tag() }}
{{ render_field_with_errors(reset_password_form.password) }}
{{ render_field_with_errors(reset_password_form.password_confirm) }}
{{ render_field(reset_password_form.submit) }}
</form>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% 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>Select Consumable for '{{ vehicle.name }}'</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.consumable) }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -0,0 +1,19 @@
{% 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>Select Vehicle</h3>
<form class='form-horizontal' method="POST">
{{ form.hidden_tag() }}
{{ render_field_with_errors(form.vehicle) }}
{{ render_field_with_errors(form.submit) }}
</form>
</div>
</div>
</div>
<div class="col-md-2" ></div>
{% endblock %}

View File

@@ -1,91 +0,0 @@
{% extends "layout.html" %}
{% macro print_service_header() -%}
<tr>
<th>
Odometer<br />
(planned<br />
done)
</th>
<th>
Date<br />
(done)
</th>
<th>
Tasks
</th>
</tr>
{%- endmacro %}
{% macro print_service(service) -%}
<tr class='pitstop'>
<td>
{{service.odometer_planned}} km<br />
{% if service.odometer_done %}
{{service.odometer_done}} km
{% else %}
-- km
{% endif %}
</td>
<td>
{% if service.date %}
{{service.date}}
{% else %}
--
{% endif %}
</td>
<td>
{% for task in service.tasks.split(',') %}
{{task}} <br />
{% endfor %}
</td>
</tr>
{%- endmacro %}
{% block body %}
{{ service_warning() }}
<div class="tabbable tabs-left">
<ul class="nav nav-pills" id="tabs">
<li class="active">
<a href="#tab1" data-toggle="tab">Inspektionen</a>
</li>
<li>
<a href="#tab2" data-toggle="tab">Inspektionen (erledigt)</a>
</li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab-pane active">
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
{{ print_service_header() }}
{% for service in data['services'] | reverse() %}
{% if not service.odometer_done %}
{{ print_service(service) }}
{% endif %}
{% endfor %}
</table>
</div>
</div>
<div id="tab2" class="tab-pane">
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
{{ print_service_header() }}
{% for service in data['services'] %}
{% if service.odometer_done %}
{{ print_service(service) }}
{% endif %}
{% endfor %}
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
console.log('ready')
$('.nav-tabs').tab();
});
</script>
{% endblock %}

View File

@@ -1,34 +1,175 @@
{% extends "layout.html" %}
{% block body %}
{{ service_warning() }}
{% macro chartScript(divId, data, unit)%}
{% set hash = divId | md5 %}
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>Number of Pitstops:</th>
<td>{{ data.count }}</td>
</tr>
<tr>
<th>Logged Distance:</th>
<td>{{ data.distance | round(2) }} km</td>
</tr>
<tr>
<th>Average Distance:</th>
<td>{{ data.averageDistance | round(2) }} km</td>
</tr>
<tr>
<th>Litres fuelled:</th>
<td>{{ data.litres | round(2) }} l</td>
</tr>
<tr>
<th>Average Litres fuelled:</th>
<td>{{ data.averageListresFuelled | round(2) }} l</td>
</tr>
<tr>
<th>Average Litres used:</th>
<td>{{ data.averageListresUsed | round(2) }} l/100km</td>
</tr>
</table>
</div>
data_{{ hash }} = [{% for stop in data %}{
"date": "{{stop.date}}",
"value": {{stop.value}}
}{% if not loop.last %},{%endif%}
{% endfor%}
]
var chart_{{ hash }} = createChart('{{divId}}', data_{{ hash }}, '{{unit}}');
function zoom_chart_{{ hash }}() {
chart_{{ hash }}.zoomToIndexes(
chart_{{ hash }}.dataProvider.length - 40,
chart_{{ hash }}.dataProvider.length - 1
);
}
chart_{{ hash }}.addListener("rendered", zoom_chart_{{ hash }});
zoom_chart_{{ hash }}()
{% endmacro %}
{% macro nav_tab(id, text, active) %}
{#
#}
<li class="{% if active %}active{% endif %}">
<a href="#ref_{{id}}" id="id_{{id}}" data-toggle="tab" >
{{ text }}
</a>
</li>
{% endmacro %}
{% macro tab_pane(id, content, active) %}
<div class="tab-pane {% if active %}active{% endif %}" id="ref_{{ id }}">
{{ content }}
</div>
{% endmacro %}
{% macro chart(data, baseId, unit, link) %}
{% if data|length > 0 %}
{% set chartID = 'chart_' + baseId %}
<div id="{{ chartID }}" style="width:100%; height:500px;"></div>
<script type="text/javascript">
{{ chartScript(chartID, data, unit) }}
</script>
{% else %}
<div class="alert alert-warning" role="alert">
not enough data: <a href="{{ link }}">log a pitstop</a>?
</div>
{% endif %}
{% endmacro %}
{% macro print_consumable_table(consumable) %}
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>Average Distance:</th>
<td>{{ consumable.average_distance | round(2) }} km</td>
</tr>
<tr>
<th>Amount fuelled:</th>
<td>{{ consumable.overall_amount | round(2) }} {{ consumable.unit }}</td>
</tr>
<tr>
<th>Average Amount fuelled:</th>
<td>{{ consumable.average_amount_fuelled | round(2) }} {{ consumable.unit }}</td>
</tr>
<tr>
<th>Average Amount used:</th>
<td>{{ consumable.average_amount_used | round(2) }} {{ consumable.unit }}/100km</td>
</tr>
</table>
{% endmacro %}
{% macro print_vehicle_table(vehicle) %}
<h3>{{vehicle.name}}</h3>
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>Logged Distance:</th>
<td>{{ vehicle.overall_distance | round(2) }} km</td>
</tr>
<tr>
<th>Logged Costs:</th>
<td>{{ vehicle.overall_costs | round(2) }} €</td>
</tr>
</table>
</div>
{% endmacro %}
{% macro tab_script(id) %}
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#{{id}}').tab();
if(window.location.hash != "") {
$('a[href="' + window.location.hash + '"]').click()
}
});
</script>
{% endmacro %}
{% block body %}
<div id="content">
<ul id="vehicle_tabs" class="nav nav-tabs" data-tabs="tabs">
{% for vehicle in data %}
{{ nav_tab(vehicle.id, vehicle.name, loop.first) }}
{% endfor %}
</ul>
<div id="vehicle_content" class="tab-content ">
{% for vehicle in data %}
<div class="tab-pane {% if loop.first %}active{% endif %}" id="ref_{{vehicle.id}}">
{{ print_vehicle_table(vehicle) }}
<ul id="vehicle_{{vehicle.id}}_tabs" class="nav nav-tabs" data-tabs="tabs">
{{ nav_tab(vehicle.id|string + '_odometer', 'Odometer', true) }}
{% for consumable in vehicle.consumables %}
{{ nav_tab(vehicle.id|string + '_' + consumable.id|string, consumable.name, false) }}
{% endfor %}
</ul>
<div id="vehicle_{{vehicle.id}}_content" class="tab-content ">
{{ tab_pane(
vehicle.id|string + '_odometer',
chart(
vehicle.odometers,
'ref_' + vehicle.id|string + '_odometer',
'km',
url_for('select_consumable_for_new_pitstop', vid=vehicle.id)
),
true
)
}}
{% for consumable in vehicle.consumables %}
<div class="tab-pane" id="ref_{{vehicle.id}}_{{consumable.id}}">
{{ print_consumable_table(consumable) }}
<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 + '_amount', 'Amount', false) }}
</ul>
<div id="consumable_{{vehicle.id}}_{{consumable.id}}_content" class="tab-content ">
{{ tab_pane(
vehicle.id|string + '_' + consumable.id|string + '_consumption',
chart(
consumable.average_amount,
'ref_' + vehicle.id|string + '_' + consumable.id|string + '_consumption',
consumable.unit + '/100km',
url_for('create_pit_stop_form', vid=vehicle.id, cid=consumable.id)
),
true
)
}}
{{ tab_pane(
vehicle.id|string + '_' + consumable.id|string + '_amount',
chart(
consumable.amounts,
'ref_' + vehicle.id|string + '_' + consumable.id|string + '_amount',
consumable.unit,
url_for('create_pit_stop_form', vid=vehicle.id, cid=consumable.id)
),
false
)
}}
</div>
{{ tab_script('vehicle_' + vehicle.id|string + '_' + consumable.id|string + '_tabs') }}
</div>
{% endfor %}
</div>
{{ tab_script('vehicle_' + vehicle.id|string + '_tabs') }}
</div>
{% endfor %}
</div>
{{ tab_script('vehicle_tabs') }}
</div>
{% endblock %}

177
app/tools.py Normal file
View File

@@ -0,0 +1,177 @@
import logging
from datetime import date
from .entities import Pitstop
class ConsumableStats:
def __init__(self, vehicle, consumable):
self.name = consumable.name
self.id = consumable.id
self.unit = consumable.unit
self.overall_amount = 0
self.average_distance = 0
self.average_amount_fuelled = 0
self.average_amount_used = 0
self.average_amount = []
self.amounts = []
pitstops = [stop for stop in vehicle.pitstops if stop.consumable_id == consumable.id]
pitstop_count = len(pitstops)
if pitstop_count > 0:
for pitstop in pitstops:
self.overall_amount += pitstop.amount
self.amounts.append(StatsEvent(pitstop.date, pitstop.amount))
self.average_amount_fuelled = self.overall_amount / pitstop_count
if pitstop_count > 1:
overall_distance = vehicle.pitstops[-1].odometer - vehicle.pitstops[0].odometer
self.average_distance = overall_distance / (pitstop_count - 1)
self.average_amount_used = 100 * (self.overall_amount - pitstops[0].amount) / overall_distance
for index in range(1, pitstop_count):
last_ps = pitstops[index - 1]
current_ps = pitstops[index]
self.average_amount.append(
StatsEvent(
current_ps.date,
round(100 * current_ps.amount/(current_ps.odometer - last_ps.odometer), 2)))
class VehicleStats:
def __init__(self, vehicle):
self.name = vehicle.name
self.id = vehicle.id
self.overall_distance = 0
self.overall_costs = 0
self.consumables = []
self.odometers = []
for consumable in vehicle.consumables:
self.consumables.append(ConsumableStats(vehicle, consumable))
pitstop_count = len(vehicle.pitstops)
if pitstop_count > 0:
for pitstop in vehicle.pitstops:
self.odometers.append(StatsEvent(pitstop.date, pitstop.odometer))
if pitstop.costs is not None:
self.overall_costs += pitstop.costs
if pitstop_count > 1:
self.overall_distance = vehicle.pitstops[-1].odometer - vehicle.pitstops[0].odometer
class StatsEvent:
def __init__(self, date, value):
self.date = date
self.value = value
def db_log_add(entity):
logging.info('db_add: %s' % str(entity))
def db_log_delete(entity):
logging.info('db_delete: %s' % str(entity))
def db_log_update(entity):
logging.info('db_update: %s' % str(entity))
def check_vehicle_name_is_unique(current_user, name_field):
"""
Checks if the vehicle name given in the name_field is unique for the vehicles of the current user. An error is added
to the field it the name is not unique.
:param current_user: the user currently logged in
:param name_field: the form field to enter the name to
:return: True if the name is unique, False otherwise.
"""
vehicle_name = name_field.data
for vehicle in current_user.vehicles:
if vehicle.name == vehicle_name:
name_field.default = vehicle_name
name_field.errors.append('Vehicle "%s" already exists.' % vehicle_name)
return False
return True
def get_latest_pitstop_for_vehicle(vehicle_id):
"""
return the latest pit stop for the vehicle with the given id.
:param vehicle_id: the id of the vehicle
:return: the latest pitstop or None if no pitstop exists
"""
latest_pitstop = Pitstop.query\
.filter(Pitstop.vehicle_id == vehicle_id)\
.order_by(Pitstop.id.desc())\
.first()
return latest_pitstop
def get_latest_pitstop_for_vehicle_and_consumable(vehicle_id, consumable_id):
"""
return the latest pit stop for the vehicle and consumable with the given ids.
:param vehicle_id: the id of the vehicle
:param consumable_id: the id of the consumable
:return: the latest pitstop or None if no pitstop exists
"""
latest_pitstop_consumable = Pitstop.query\
.filter(Pitstop.vehicle_id == vehicle_id)\
.filter(Pitstop.consumable_id == consumable_id)\
.order_by(Pitstop.id.desc())\
.first()
return latest_pitstop_consumable
def compute_lower_limits_for_new_pitstop(latest_pitstop, last_pitstop_consumable, consumable_id):
"""
This function figures out the lower limits for date and odometer of a new pitstop.
:param latest_pitstop:
:param last_pitstop_consumable:
:param consumable_id:
:return:
"""
odometer = 0
date_of_pitstop = date(1970, 1, 1)
amount = 0
costs = 0
if latest_pitstop is not None:
odometer = latest_pitstop.odometer
date_of_pitstop = latest_pitstop.date
if last_pitstop_consumable is not None:
amount = last_pitstop_consumable.amount
costs = last_pitstop_consumable.costs
return Pitstop(odometer, amount, date_of_pitstop, costs, consumable_id)
# if latest_pitstop is not None:
# if last_pitstop_consumable is not None and last_pitstop_consumable != latest_pitstop:
# if latest_pitstop.id > last_pitstop_consumable.id:
# return Pitstop(latest_pitstop.odometer,
# last_pitstop_consumable.overall_amount,
# latest_pitstop.date,
# last_pitstop_consumable.costs,
# consumable_id)
# else:
# return Pitstop(last_pitstop_consumable.odometer,
# last_pitstop_consumable.overall_amount,
# last_pitstop_consumable.date,
# last_pitstop_consumable.costs,
# consumable_id)
# else:
# # either only one pitstop exists or both are the same
# litres = 0
# costs = 0
# if latest_pitstop.consumable_id == last_pitstop_consumable.consumable_id:
# litres = latest_pitstop.overall_amount
# costs = latest_pitstop.costs
# return Pitstop(latest_pitstop.odometer, litres, latest_pitstop.date, costs, consumable_id)
# else:
# # No existing pitstop at all: insert fake data
# return Pitstop(0, 0, date(1970, 1, 1), 0, None)

16
compose_config/config.py Normal file
View File

@@ -0,0 +1,16 @@
import os
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:%s@database/pitstops' % (os.environ['DATABASE_ENV_MYSQL_ROOT_PASSWORD'])
#SQLALCHEMY_DATABASE_URI = 'sqlite:////data/rollerverbrauch.db'
MAIL_SERVER = ''
MAIL_PORT= 25
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_USERNAME = ''
MAIL_PASSWORD = ''
SECURITY_EMAIL_SENDER = ''
SECURITY_PASSWORD_SALT = 'SecretSalt'
SECRET_KEY = 'SecretKey'
SECURITY_SEND_REGISTER_EMAIL = False

46
config.py Normal file
View File

@@ -0,0 +1,46 @@
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECURITY_PASSWORD_HASH = 'pbkdf2_sha512'
SECURITY_REGISTERABLE = True
SECURITY_CHANGEABLE = True
SECURITY_RECOVERABLE = True
SECURITY_PASSWORD_SALT = os.environ.get('SECURITY_PASSWORD_SALT') or 'SOME SECRET STRING'
SECRET_KEY = os.environ.get('SECRET_KEY') or 'SOME SECRET STRING'
SECURITY_EMAIL_SENDER = 'no-reply@lusiardi.de'
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_SERVER = 'mail.nerd2nerd.org'
MAIL_PORT = 25
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
SECURITY_SEND_REGISTER_EMAIL = False
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:%s@database/pitstops' % (os.environ['DATABASE_ENV_MYSQL_ROOT_PASSWORD'])
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data_testing.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}

View File

@@ -4,14 +4,14 @@ SIZES="57 60 72 76 114 120 144 152 180"
for SIZE in $SIZES
do
convert ./icon_orig.png -resize ${SIZE}x${SIZE} app/static/apple-touch-icon-${SIZE}.png
convert ./icon_orig.png -resize ${SIZE}x${SIZE} app/rollerverbrauch/static/apple-touch-icon-${SIZE}.png
done
convert ./icon_orig.png -resize 192x192 app/static/android-icon-192x192.png
convert ./icon_orig.png -resize 192x192 app/rollerverbrauch/static/android-icon-192x192.png
SIZES="16 32 96"
for SIZE in $SIZES
do
convert ./icon_orig.png -resize ${SIZE}x${SIZE} app/static/favicon-${SIZE}.png
convert ./icon_orig.png -resize ${SIZE}x${SIZE} app/rollerverbrauch/static/favicon-${SIZE}.png
done

View File

@@ -0,0 +1,28 @@
CREATE TABLE IF NOT EXISTS `consumable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`unit` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=latin1;
INSERT INTO `consumable`(`id`, `name`, `unit`) VALUES (1, 'Super E5', 'l');
CREATE TABLE IF NOT EXISTS `vehicles_consumables` (
`vehicle_id` int(11) DEFAULT NULL,
`consumable_id` int(11) DEFAULT NULL,
KEY `vehicle_id` (`vehicle_id`),
KEY `consumable_id` (`consumable_id`),
CONSTRAINT `vehicles_consumables_ibfk_1` FOREIGN KEY (`vehicle_id`) REFERENCES `vehicle` (`id`),
CONSTRAINT `vehicles_consumables_ibfk_2` FOREIGN KEY (`consumable_id`) REFERENCES `consumable` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `pitstop` ADD COLUMN `costs` decimal(5,2) DEFAULT NULL;
ALTER TABLE `pitstop` CHANGE `litres` `amount` decimal(5,2) DEFAULT NULL;
ALTER TABLE `pitstop` ADD COLUMN `consumable_id` int(11);
ALTER TABLE `pitstop` ADD FOREIGN KEY (`consumable_id`) REFERENCES `consumable` (`id`);
UPDATE `pitstop` set `consumable_id`=1;
INSERT INTO `vehicles_consumables`(`vehicle_id`, `consumable_id`) SELECT `id`, 1 FROM `vehicle`;

20
docker-compose.yml Normal file
View File

@@ -0,0 +1,20 @@
version: '2'
services:
rollerverbrauch:
build: .
depends_on:
- database
volumes:
- ./compose_config/:/config
environment:
- config=/config/config.py
- DATABASE_ENV_MYSQL_ROOT_PASSWORD=foobar123
ports:
- 5000
database:
image: mysql
environment:
- MYSQL_ROOT_PASSWORD=foobar123
- MYSQL_DATABASE=pitstops
ports:
- 3306

12
main.py Normal file
View File

@@ -0,0 +1,12 @@
import os
from app import app
import logging
def setup_logging():
logging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', level=logging.INFO)
if __name__ == '__main__':
DEBUG = 'DEBUG' in os.environ and os.environ['DEBUG'] != 'False'
setup_logging()
app.run(debug=DEBUG, host='0.0.0.0')

5
requirements.txt Normal file
View File

@@ -0,0 +1,5 @@
Flask
Flask-SQLAlchemy
Flask-Security
Flask-WTF
PyMySQL