first prototype

master
Marek Baczynski 5 years ago
parent 5d0a34d2ee
commit 0446ae6a09

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -0,0 +1,178 @@
import json, csv, datetime, copy
import requests
from flask import Flask
from flask import render_template, send_from_directory, request, Response, send_file, session
app = Flask(__name__)
class Item():
items = {}
def __init__(self, name, price, itemid=None):
self.id = itemid if itemid != None else 0
self.name = name
self.price = price
self.events = []
Item.items[self.id] = self
def newEvent(self, type, value, date=None):
event = {}
if date==None:
# date = datetime.datetime.now().strftime('%Y-%m-%d')
print ("no date given, using now")
date = datetime.datetime.now()
event['date'] = date
event['type'] = type
event['value'] = value
self.events.append(event)
def recount(self, count, date=None):
if count < 0:
return False
self.newEvent('count', count, date)
Item.fileSave()
return True
def add(self, count, date=None):
self.newEvent('add', count, date)
Item.fileSave()
return True
def howMany(self):
count = 0
for event in self.events:
if event['type']=='add':
count += event['value']
if event['type']=='count':
count = event['value']
return count
def countSold(self, fromDate=None, verbose=False):
count = 0
totalSold = 0
lastDate = 'the start'
for event in self.events:
if event['type']=='add':
count += event['value']
if event['type']=='count':
newCount = event['value']
if newCount<count:
sold = count - newCount
totalSold += sold
if verbose:
print("sold {} between {} and {}".format(sold, lastDate, event['date'].strftime('%Y-%m-%d')))
lastDate = event['date']
count = newCount
return totalSold
def soldValue(self, fromDate=None):
return self.countSold() * self.price
@staticmethod
def fileSave():
fileContent = []
for key, item in Item.items.items():
itemEntity = {}
itemEntity['id'] = item.id
itemEntity['name'] = item.name
itemEntity['price'] = item.price
itemEntity['events'] = copy.deepcopy(item.events)
for event in itemEntity['events']:
event['date'] = event['date'].strftime('%Y-%m-%d')
fileContent.append(itemEntity)
with open('data.json', 'w') as outfile:
json.dump(fileContent, outfile)
print ("Saved to file.")
@staticmethod
def fileLoad():
with open('data.json', 'r') as f:
fileContent = json.load(f)
for itemEntry in fileContent:
item = Item(itemEntry['name'], itemEntry['price'], itemid=itemEntry['id'])
for event in itemEntry['events']:
item.newEvent(event['type'], event['value'], datetime.datetime.strptime(event['date'], '%Y-%m-%d'))
print ("Loaded from file")
@app.route('/')
def index():
return render_template('inventory.html')
@app.route('/recount', methods=['POST'])
def recount():
if 'id' not in request.form or 'count' not in request.form:
return "bad request"
itemid = int(request.form['id'])
count = int(request.form['count'])
if itemid in Item.items:
if Item.items[itemid].recount(count):
return 'ok'
else:
return 'error'
else:
return 'item not found'
@app.route('/restock', methods=['POST'])
def restock():
if 'id' not in request.form or 'count' not in request.form:
return "bad request"
itemid = int(request.form['id'])
count = int(request.form['count'])
if itemid in Item.items:
if Item.items[itemid].add(count):
return 'ok'
else:
return 'error'
else:
return 'item not found'
@app.route('/getdata')
def data():
jsonContent = []
for key, item in Item.items.items():
itemEntity = {}
itemEntity['id'] = item.id
itemEntity['name'] = item.name
itemEntity['price'] = str(item.price/100) + '.00'
itemEntity['quantity'] = item.howMany()
jsonContent.append(itemEntity)
return json.dumps(jsonContent)
@app.route('/salestats/<startDate>')
def saleStats(startDate = 0):
if startDate !=0:
try:
startDate = datetime.datetime.strptime(startDate, '%Y-%m-%d')
except:
return "invalid date format"
jsonContent = {}
jsonContent['totalCount'] = 0
jsonContent['totalValue'] = 0
itemTable = []
for key, item in Item.items.items():
itemEntity = {}
itemEntity['id'] = item.id
itemEntity['name'] = item.name
itemEntity['price'] = str(item.price/100) + '.00'
if startDate != 0:
itemEntity['soldQuantity'] = item.countSold(startDate)
else:
itemEntity['soldQuantity'] = item.countSold()
itemEntity['soldValue'] = str(itemEntity['soldQuantity'] * item.price / 100) + '.00'
jsonContent['totalCount'] += itemEntity['soldQuantity']
jsonContent['totalValue'] += itemEntity['soldQuantity'] * item.price/100
itemTable.append(itemEntity)
jsonContent['items'] = itemTable
jsonContent['startDate'] = startDate.strftime('%Y-%m-%d') if startDate != 0 else "2018-09-01"
jsonContent['endDate'] = datetime.datetime.now().strftime('%Y-%m-%d')
return json.dumps(jsonContent)
@app.route('/salestats')
def saleStatsNoDate():
return saleStats()
if __name__ == '__main__':
# app.secret_key = 'asuiygdiahsdo[ainsfl]asfkjnb;asklnj'
# app.config['SESSION_TYPE'] = 'memcached'
print("is this the work?")
Item.fileLoad()
app.run('0.0.0.0')

@ -3,24 +3,7 @@ var data_filtered = [];
var current_selection = -1; var current_selection = -1;
var is_editing = false; var is_editing = false;
data = [ data = []
{
id : 1,
name : "Arduino",
price : 25,
quantity : 4
}, {
id : 2,
name : "Buck converter",
price : 30,
quantity : 6
}, {
id : 3,
name : "Line driver",
price : 10,
quantity : 12
}
]
function populate_table(data) { function populate_table(data) {
data.forEach(function(d) { data.forEach(function(d) {
@ -61,10 +44,21 @@ function recount_confirm(id, previous_value) {
$('#inventory-item-' + id + ' > #item-recount > div').text('Recount'); $('#inventory-item-' + id + ' > #item-recount > div').text('Recount');
$('#inventory-item-' + id + ' > #item-recount > div').attr('onclick', 'recount(' + id + ')') $('#inventory-item-' + id + ' > #item-recount > div').attr('onclick', 'recount(' + id + ')')
$('#inventory-item-' + id + ' > #item-quantity').empty(); $('#inventory-item-' + id + ' > #item-quantity').empty();
// TODO: Perform ajax to set new quantity
// If you got an ok: // If you got an ok:
if (quantity.length > 0) { if (quantity.length > 0) {
data = {};
data['id'] = id;
data['count'] = quantity;
$('#inventory-item-' + id + ' > #item-quantity').text(quantity); $('#inventory-item-' + id + ' > #item-quantity').text(quantity);
$.post( "recount", data, function( data ) {
if(data=="ok"){
//nothing on success
}else{
alert("Something went wrong :(");
$('#inventory-item-' + id + ' > #item-quantity').text(previous_value);
}
});
// TODO: Also refresh the 'data' array // TODO: Also refresh the 'data' array
} else { } else {
$('#inventory-item-' + id + ' > #item-quantity').text(previous_value); $('#inventory-item-' + id + ' > #item-quantity').text(previous_value);
@ -100,12 +94,22 @@ function restock_confirm(id) {
$('#inventory-item-' + id + ' > #item-restock > div').removeClass('button-confirm'); $('#inventory-item-' + id + ' > #item-restock > div').removeClass('button-confirm');
$('#inventory-item-' + id + ' > #item-restock > div').text('Restock'); $('#inventory-item-' + id + ' > #item-restock > div').text('Restock');
$('#inventory-item-' + id + ' > #item-restock > div').attr('onclick', 'restock(' + id + ')'); $('#inventory-item-' + id + ' > #item-restock > div').attr('onclick', 'restock(' + id + ')');
// TODO: Perform ajax to send restock info
// If you got an ok: // If you got an ok:
data = {};
data['id'] = id;
data['count'] = quantity;
var previous_q = parseInt($('#inventory-item-' + id + ' > #item-quantity').text()); var previous_q = parseInt($('#inventory-item-' + id + ' > #item-quantity').text());
if (quantity.length > 0) { if (quantity.length > 0) {
$('#inventory-item-' + id + ' > #item-quantity').text(previous_q + parseInt(quantity)); $('#inventory-item-' + id + ' > #item-quantity').text(previous_q + parseInt(quantity));
// TODO: Also refresh the 'data' array $.post( "restock", data, function( data ) {
if(data=="ok"){
//nothing on success
}else{
alert("Something went wrong :(");
$('#inventory-item-' + id + ' > #item-quantity').text(previous_q);
}
})
} else { } else {
$('#inventory-item-' + id + ' > #item-quantity').text(previous_q); $('#inventory-item-' + id + ' > #item-quantity').text(previous_q);
} }
@ -152,10 +156,12 @@ function default_keypress_handler(e) {
} }
$( document ).ready(function(){ $( document ).ready(function(){
// $.getJSON( "ajax/test.json", function( data ) { $.getJSON( "getdata", function( result ) {
populate_table(data); populate_table(result);
data_filtered = data; data_filtered = result;
// }); data=result;
});
$('#filter-textbox').on('keyup', function() { $('#filter-textbox').on('keyup', function() {
data_filtered = [] data_filtered = []

Loading…
Cancel
Save