started working on services

This commit is contained in:
joachim lusiardi 2015-03-16 22:06:59 +01:00
parent e479bc24ac
commit 73b2ccc195
9 changed files with 231 additions and 86 deletions

69
app/db/__init__.py Normal file
View File

@ -0,0 +1,69 @@
'''
@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 _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()

Binary file not shown.

View File

@ -1,13 +1,15 @@
import sqlite3
from datetime import datetime
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request, redirect, g
from contextlib import closing
import os, os.path
from flask import url_for
import os.path
import time
import db
#from db import Db
app = Flask(__name__)
DATABASE = '/data/rollerverbrauch.db'
DEBUG = True
@ -16,37 +18,30 @@ USERNAME = 'admin'
PASSWORD = 'default'
app.config.from_object(__name__)
def connect_db():
result = sqlite3.connect(app.config['DATABASE'])
return result
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
sql_commands = f.read()
print(sql_commands)
db.cursor().executescript(sql_commands)
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
g.db2 = db.Db(app.config['DATABASE'])
g.data = {}
add_service_warning(g.data)
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
pass
@app.route('/')
def index():
#data = {'pitstopsUrl': url_for('getPitStops')}
#return render_template('index.html', data=data)
return redirect(url_for('getPitStops'))
return redirect(url_for('get_pit_stops'))
@app.route('/services')
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'])
def createPitStop():
last_pitstop = getLastPitStop()
def create_pit_stop():
last_pitstop = g.db2.getLastPitStop()
errorMsg = {}
date = request.form['date']
@ -85,27 +80,31 @@ def createPitStop():
data = {'last': {'date': date, 'odometer': odometer, 'litres': litres}, 'error': errorMsg}
return render_template('newPitStopForm.html', data=data)
addPitStop(date, odometer, litres)
g.db2.addPitStop(date, odometer, litres)
return redirect(url_for('getPitStops'))
return redirect(url_for('get_pit_stops'))
@app.route('/pitstops/createForm', methods=['GET'])
def createPitStopForm():
values = getLastPitStop()
def create_pit_stop_form():
values = g.db2.getLastPitStop()
values['date'] = time.strftime("%Y-%m-%d")
data = {'last': values, 'error': None}
return render_template('newPitStopForm.html', data=data)
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'])
def getPitStops():
data = preparePitStops(getAllPitStops())
data.reverse()
data = {'pitstops': data}
return render_template('pitstops.html', data=data)
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('/statistics', methods=['GET'])
def getStatistics():
pitstops = getAllPitStops()
def get_statistics():
pitstops = g.db2.getAllPitStops()
count = len(pitstops)
distance = 0
sumLitres = 0
@ -117,50 +116,33 @@ def getStatistics():
sumLitres = 0
for pitstop in pitstops:
sumLitres += pitstop['litres']
averageLitresFuelled = round(sumLitres/count, 2)
averageLitresFuelled = sumLitres/count
if count > 1:
distance = pitstops[-1]['odometer'] - pitstops[0]['odometer']
averageDistance = round(distance/(count - 1), 2)
averageLitresUsed = round(100 * (sumLitres-pitstops[0]['litres'])/distance, 2)
data = {
'distance':distance,
'count': count,
'litres': round(sumLitres, 2),
'averageDistance': averageDistance,
'averageListresFuelled': averageLitresFuelled,
'averageListresUsed': averageLitresUsed}
return render_template('statistics.html', data=data)
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 preparePitStops(pitstops):
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'] = round(100 * curr['litres']/curr['distance'], 2)
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
def getLastPitStop():
cur = g.db.execute('select date, odometer, litres from pitstops order by date desc limit 1')
pitstops = [dict(date=row[0], odometer=row[1], litres=row[2]) for row in cur.fetchall()]
if len(pitstops) == 0:
return {'date': datetime.strftime(datetime.now(), '%Y-%m-%d'), 'odometer': 0, 'litres': 0}
return pitstops[0]
def getAllPitStops():
cur = g.db.execute('select date, odometer, litres from pitstops order by id asc')
pitstops = [dict(date=row[0], odometer=row[1], litres=row[2]) for row in cur.fetchall()]
return pitstops
def addPitStop(date, odometer, litres):
g.db.execute('insert into pitstops (date, odometer, litres) values (?, ?, ?)', [date, odometer, litres])
g.db.commit()
if __name__ == '__main__':
if not os.path.isfile(DATABASE) or os.stat(DATABASE).st_size == 0:
init_db()
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

@ -5,3 +5,11 @@ create table pitstops (
`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
);

View File

@ -1,3 +1,22 @@
{% macro alert_level(km_left) -%}
{% if km_left < 0 %}
alert-danger
{% elif km_left < 300 %}
alert-warning
{% else %}
alert-success
{% endif %}
{%- endmacro %}
{% macro service_warning() -%}
<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>
{%- endmacro %}
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
@ -38,7 +57,7 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ url_for('getPitStops') }}">Rollerverbrauch</a>
<a class="navbar-brand" href="{{ url_for('get_pit_stops') }}">Rollerverbrauch</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">

View File

@ -1,13 +1,16 @@
{% extends "layout.html" %}
{% block navigation %}
<li><a href='{{ url_for('createPitStopForm') }}' class="active">Create Pitstop</a></li>
<li><a href='{{ url_for('getStatistics') }}'>Statistics</a></li>
<li><a href='{{ url_for('create_pit_stop_form') }}' class="active">Create Pitstop</a></li>
<li><a href='{{ url_for('get_statistics') }}'>Statistics</a></li>
<li><a href='{{ url_for('get_services') }}'>Services</a></li>
{% endblock %}
{% block body %}
<form class='form-horizontal' id='createPitStop' action="{{ url_for('createPitStop') }}" method='post'>
{{ 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 %}">
@ -39,8 +42,8 @@
<!-- Button (Double) -->
<div class="form-group">
<div class="controls">
<button id="buttonLogId" name="buttonLogId" class="btn btn-success" onclick="document.getElementById('createPitStop').submit();">Log Pitstop</button>
<button id="buttonAbortId" name="buttonAbortId" class="btn btn-warning" onclick="window.location.href='{{ url_for('getPitStops') }}'" type="button" >Abort</button>
<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>

View File

@ -1,12 +1,14 @@
{% extends "layout.html" %}
{% block navigation %}
<li><a href='{{ url_for('createPitStopForm') }}'>Create Pitstop</a></li>
<li><a href='{{ url_for('getStatistics') }}'>Statistics</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_services') }}'>Services</a></li>
{% endblock %}
{% block body %}
{{ service_warning() }}
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
@ -35,7 +37,7 @@
</td>
<td>
{{pitstop.litres}} l<br />
{% if pitstop.average %}{{pitstop.average}}{% else %} --{% endif %} l/100km
{% if pitstop.average %}{{pitstop.average | round(2)}}{% else %} --{% endif %} l/100km
</td>
</tr>
{% endfor %}

View File

@ -0,0 +1,60 @@
{% extends "layout.html" %}
{% block navigation %}
<li><a href='{{ url_for('create_pit_stop_form') }}'>Create Pitstop</a></li>
<li><a href='{{ url_for('get_statistics') }}' class="active">Statistics</a></li>
<li><a href='{{ url_for('get_services') }}' class="active">Services</a></li>
{% endblock %}
{% block body %}
{{ service_warning() }}
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>
Odometer<br />
(planned)
</th>
<th>
Odometer<br />
(done)
</th>
<th>
Date<br />
(done)
</th>
<th>
Tasks
</th>
</tr>
{% for service in data['services'] %}
<tr class='pitstop'>
<td>
{{service.odometer_planned}} km
</td>
<td>
{% 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>
{% endfor %}
</table>
</div>
{% endblock %}

View File

@ -1,12 +1,14 @@
{% extends "layout.html" %}
{% block navigation %}
<li><a href='{{ url_for('createPitStopForm') }}'>Create Pitstop</a></li>
<li><a href='{{ url_for('getStatistics') }}' class="active">Statistics</a></li>
<li><a href='{{ url_for('create_pit_stop_form') }}'>Create Pitstop</a></li>
<li><a href='{{ url_for('get_statistics') }}' class="active">Statistics</a></li>
<li><a href='{{ url_for('get_services') }}'>Services</a></li>
{% endblock %}
{% block body %}
{{ service_warning() }}
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed">
<tr>
@ -15,23 +17,23 @@
</tr>
<tr>
<th>Logged Distance:</th>
<td>{{ data.distance }} km</td>
<td>{{ data.distance | round(2) }} km</td>
</tr>
<tr>
<th>Average Distance:</th>
<td>{{ data.averageDistance }} km</td>
<td>{{ data.averageDistance | round(2) }} km</td>
</tr>
<tr>
<th>Litres fuelled:</th>
<td>{{ data.litres }} l</td>
<td>{{ data.litres | round(2) }} l</td>
</tr>
<tr>
<th>Average Litres fuelled:</th>
<td>{{ data.averageListresFuelled }} l</td>
<td>{{ data.averageListresFuelled | round(2) }} l</td>
</tr>
<tr>
<th>Average Litres used:</th>
<td>{{ data.averageListresUsed }} l/100km</td>
<td>{{ data.averageListresUsed | round(2) }} l/100km</td>
</tr>
</table>
</div>