Reduce services feature and reformatting

This commit is contained in:
Joachim Lusiardi 2016-04-14 07:32:06 +02:00
parent 8f99b798bb
commit fb521194f7
9 changed files with 51 additions and 197 deletions

View File

@ -1,51 +1,39 @@
''' """
@author: shing19m @author: jlusiardi
''' """
from datetime import datetime from datetime import datetime
import sqlite3 import sqlite3
class Db(object): class Db(object):
''' """
classdocs classdocs
''' """
def __init__(self, db_file): def __init__(self, db_file):
''' """
Constructor Constructor
''' """
self.db = sqlite3.connect(db_file) self.db = sqlite3.connect(db_file)
def __del__(self): def __del__(self):
self.db.close() self.db.close()
def getAllPitStops(self): def get_all_pit_stops(self):
return self._perform_query('select * from pitstops order by id asc') return self._perform_query('select * from pitstops order by id asc')
def getAllServices(self): def get_last_pit_stop(self):
return self._perform_query('select * from services')
def getLastPitStop(self):
pitstops = self._perform_query('select * from pitstops order by id desc limit 1') pitstops = self._perform_query('select * from pitstops order by id desc limit 1')
if len(pitstops) == 0: if len(pitstops) == 0:
return {'date': datetime.strftime(datetime.now(), '%Y-%m-%d'), 'odometer': 0, 'litres': 0} return {'date': datetime.strftime(datetime.now(), '%Y-%m-%d'), 'odometer': 0, 'litres': 0}
return pitstops[0] return pitstops[0]
def get_service_warning_info(self): def add_pit_stop(self, date, odometer, litres):
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;') self.db.execute('insert into pitstops (date, odometer, litres) values (?, ?, ?)', [date, odometer, litres])
if len(info) == 0: self.db.commit()
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): def get_salt_for_user(self, user):
salt = self._perform_query_param('select salt from users where name = ?', [user]) salt = self._perform_query_param('select salt from users where name = ?', [user])
@ -81,10 +69,6 @@ class Db(object):
result.append(row_result) result.append(row_result)
return 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): def init_db(self, resource):
with resource as f: with resource as f:
sql_commands = f.read() sql_commands = f.read()

View File

@ -12,16 +12,16 @@ from functools import wraps
import db import db
#from db import Db
app = Flask(__name__) app = Flask(__name__)
DATABASE = '/data/rollerverbrauch.db' DATABASE = '/data/rollerverbrauch.db'
DEBUG = True DEBUG = True
SECRET_KEY = 'development key' SECRET_KEY = 'development key'
app.config.from_object(__name__) app.config.from_object(__name__)
def check_auth(username, password): def check_auth(username, password):
salt = g.db2.get_salt_for_user(username) salt = g.db2.get_salt_for_user(username)
if salt == None: if salt is None:
return False return False
m = hashlib.sha256(password.encode('utf-8')) m = hashlib.sha256(password.encode('utf-8'))
m = hashlib.sha256((m.hexdigest()+salt).encode('utf-8')) m = hashlib.sha256((m.hexdigest()+salt).encode('utf-8'))
@ -31,11 +31,13 @@ def check_auth(username, password):
app.logger.error("digest: " + digest) app.logger.error("digest: " + digest)
return ok return ok
def authenticate(): def authenticate():
resp = make_response(render_template('login_required.html'), 401) resp = make_response(render_template('login_required.html'), 401)
resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"' resp.headers['WWW-Authenticate'] = 'Basic realm="Login Required"'
return resp return resp
def requires_auth(f): def requires_auth(f):
@wraps(f) @wraps(f)
def decorated(*args, **kwargs): def decorated(*args, **kwargs):
@ -45,50 +47,45 @@ def requires_auth(f):
return f(*args, **kwargs) return f(*args, **kwargs)
return decorated return decorated
@app.before_request @app.before_request
def before_request(): def before_request():
g.db2 = db.Db(app.config['DATABASE']) g.db2 = db.Db(app.config['DATABASE'])
g.data = {} g.data = {}
add_service_warning(g.data)
@app.teardown_request @app.teardown_request
def teardown_request(exception): def teardown_request(exception):
pass pass
@app.route('/') @app.route('/')
@requires_auth @requires_auth
def index(): def index():
return redirect(url_for('get_pit_stops')) 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']) @app.route('/pitstops', methods=['POST'])
@requires_auth @requires_auth
def create_pit_stop(): def create_pit_stop():
last_pitstop = g.db2.getLastPitStop() last_pitstop = g.db2.get_last_pit_stop()
errorMsg = {} error_msg = {}
date = request.form['date'] date = request.form['date']
try: try:
date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d') date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d')
except ValueError: except ValueError:
errorMsg['date'] = 'invalid date, only YYYY-MM-DD is allowed' error_msg['date'] = 'invalid date, only YYYY-MM-DD is allowed'
date = request.form['date'] date = request.form['date']
odometer = request.form['odometer'] odometer = request.form['odometer']
try: try:
odometer = int(odometer) odometer = int(odometer)
except ValueError: except ValueError:
errorMsg['odometer'] = 'Illegal Value, only Integers allowed' error_msg['odometer'] = 'Illegal Value, only Integers allowed'
odometer = None odometer = None
if odometer is not None and odometer <= last_pitstop['odometer']: if odometer is not None and odometer <= last_pitstop['odometer']:
errorMsg['odometer'] = 'Illegal Value, new Value must be bigger as given value' error_msg['odometer'] = 'Illegal Value, new Value must be bigger as given value'
odometer = request.form['odometer'] odometer = request.form['odometer']
if odometer is None: if odometer is None:
odometer = request.form['odometer'] odometer = request.form['odometer']
@ -97,76 +94,77 @@ def create_pit_stop():
try: try:
litres = float(litres) litres = float(litres)
except ValueError: except ValueError:
errorMsg['litres'] = 'Illegal Value, only floating point allowed' error_msg['litres'] = 'Illegal Value, only floating point allowed'
litres = None litres = None
if litres is not None and litres <= 0: if litres is not None and litres <= 0:
errorMsg['litres'] = 'Litres must not be 0' error_msg['litres'] = 'Litres must not be 0'
litres = request.form['litres'] litres = request.form['litres']
if litres is None: if litres is None:
litres = request.form['litres'] litres = request.form['litres']
# error checking here # error checking here
if len(errorMsg) > 0: if len(error_msg) > 0:
data = {'last': {'date': date, 'odometer': odometer, 'litres': litres}, 'error': errorMsg} data = {'last': {'date': date, 'odometer': odometer, 'litres': litres}, 'error': error_msg}
return render_template('newPitStopForm.html', data=data) return render_template('newPitStopForm.html', data=data)
g.db2.addPitStop(date, odometer, litres) g.db2.add_pit_stop(date, odometer, litres)
return redirect(url_for('get_pit_stops')) return redirect(url_for('get_pit_stops'))
@app.route('/pitstops/createForm', methods=['GET']) @app.route('/pitstops/createForm', methods=['GET'])
@requires_auth @requires_auth
def create_pit_stop_form(): def create_pit_stop_form():
values = g.db2.getLastPitStop() values = g.db2.get_last_pit_stop()
values['date'] = time.strftime("%Y-%m-%d") values['date'] = time.strftime("%Y-%m-%d")
g.data['last'] = values g.data['last'] = values
g.data['error'] = None g.data['error'] = None
return render_template('newPitStopForm.html', data=g.data) 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']) @app.route('/pitstops', methods=['GET'])
@requires_auth @requires_auth
def get_pit_stops(): def get_pit_stops():
data = prepare_pit_stops(g.db2.getAllPitStops()) data = prepare_pit_stops(g.db2.get_all_pit_stops())
g.data['pitstops'] = data g.data['pitstops'] = data
return render_template('pitstops.html', data=g.data) return render_template('pitstops.html', data=g.data)
@app.route('/manual', methods=['GET']) @app.route('/manual', methods=['GET'])
@requires_auth @requires_auth
def get_manual(): def get_manual():
return render_template('manual.html', data=g.data) return render_template('manual.html', data=g.data)
@app.route('/statistics', methods=['GET']) @app.route('/statistics', methods=['GET'])
@requires_auth @requires_auth
def get_statistics(): def get_statistics():
pitstops = g.db2.getAllPitStops() pitstops = g.db2.get_all_pit_stops()
count = len(pitstops) count = len(pitstops)
distance = 0 distance = 0
sumLitres = 0 sum_litres = 0
averageDistance = 0 average_distance = 0
averageLitresFuelled = 0 average_litres_fuelled = 0
averageLitresUsed = 0 average_litres_used = 0
if count > 0: if count > 0:
sumLitres = 0 sum_litres = 0
for pitstop in pitstops: for pitstop in pitstops:
sumLitres += pitstop['litres'] sum_litres += pitstop['litres']
averageLitresFuelled = sumLitres/count average_litres_fuelled = sum_litres/count
if count > 1: if count > 1:
distance = pitstops[-1]['odometer'] - pitstops[0]['odometer'] distance = pitstops[-1]['odometer'] - pitstops[0]['odometer']
averageDistance = distance/(count - 1) average_distance = distance/(count - 1)
averageLitresUsed = 100 * (sumLitres-pitstops[0]['litres'])/distance average_litres_used = 100 * (sum_litres-pitstops[0]['litres'])/distance
g.data['distance'] = distance g.data['distance'] = distance
g.data['count'] = count g.data['count'] = count
g.data['litres'] = sumLitres g.data['litres'] = sum_litres
g.data['averageDistance'] = averageDistance g.data['averageDistance'] = average_distance
g.data['averageListresFuelled'] = averageLitresFuelled g.data['averageListresFuelled'] = average_litres_fuelled
g.data['averageListresUsed'] = averageLitresUsed g.data['averageListresUsed'] = average_litres_used
return render_template('statistics.html', data=g.data) return render_template('statistics.html', data=g.data)
def prepare_pit_stops(pitstops): def prepare_pit_stops(pitstops):
for index in range(1, len(pitstops)): for index in range(1, len(pitstops)):
last = pitstops[index - 1] last = pitstops[index - 1]

View File

@ -6,15 +6,6 @@ create table pitstops (
`litres` REAL 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; drop table if exists users;
create table `users` ( create table `users` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,

View File

@ -1,30 +1,6 @@
{% macro alert_level(km_left) -%}
{% if km_left == None %}
alert-success
{% elif km_left < 0 %}
alert-danger
{% elif km_left < 300 %}
alert-warning
{% 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>
{% endif %}
{%- endmacro %}
{% macro navigation() -%} {% macro navigation() -%}
<li><a href='{{ url_for('create_pit_stop_form') }}'>Create Pitstop</a></li> <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_statistics') }}'>Statistics</a></li>
<li><a href='{{ url_for('get_services') }}'>Services</a></li>
<li><a href='{{ url_for('get_manual') }}'>Manual</a></li> <li><a href='{{ url_for('get_manual') }}'>Manual</a></li>
{%- endmacro %} {%- endmacro %}
@ -36,7 +12,7 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Rollerverbrauch</title> <title>Rollerverbrauch 0.1</title>
<meta name="description" content=""> <meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1"> <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') }}"> <link rel="apple-touch-icon" href="{{ url_for('static', filename='apple-touch-icon-57.png') }}">

View File

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

View File

@ -1,7 +1,6 @@
{% extends "layout.html" %} {% extends "layout.html" %}
{% block body %} {% block body %}
{{ service_warning() }}
<form class='form-horizontal' id='createPitStop' action="{{ url_for('create_pit_stop') }}" method='post'> <form class='form-horizontal' id='createPitStop' action="{{ url_for('create_pit_stop') }}" method='post'>

View File

@ -1,7 +1,6 @@
{% extends "layout.html" %} {% extends "layout.html" %}
{% block body %} {% block body %}
{{ service_warning() }}
<div class="table-responsive"> <div class="table-responsive">
<table class="table table-striped table-bordered table-condensed"> <table class="table table-striped table-bordered table-condensed">

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,7 +1,6 @@
{% extends "layout.html" %} {% extends "layout.html" %}
{% block body %} {% block body %}
{{ service_warning() }}
<div class="table-responsive"> <div class="table-responsive">
<table class="table table-striped table-bordered table-condensed"> <table class="table table-striped table-bordered table-condensed">