L'outil de gestion de stock de composants électroniques du Tetalab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

482 lines
17 KiB

#!/usr/bin/env python
# -*- coding: utf-8
import math
import psycopg2
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
########################################################################
# App settings
########################################################################
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.secret_key = '446307a5f61c2bb810436b2ee0f903f2'
app.debug = True
app.static_url_path='/static'
db = SQLAlchemy(app)
########################################################################
# Database
########################################################################
class Stock_users(db.Model):
id = db.Column(db.Integer, primary_key=True)
mail = db.Column(db.Text, nullable=False)
password = db.Column(db.Text, nullable=False)
name = db.Column(db.Text, nullable=False)
class Stock_componants(db.Model):
id = db.Column(db.Integer, primary_key=True)
reference = db.Column(db.Text, nullable=False)
designation = db.Column(db.Text, nullable=False)
last_price = db.Column(db.Float)
mean_price = db.Column(db.Float)
quantity = db.Column(db.Integer)
min_quantity = db.Column(db.Integer)
place = db.Column(db.Text, nullable=False)
provider_id = db.Column(db.Integer, nullable=False)
class Stock_providers(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False)
address = db.Column(db.Text)
mail = db.Column(db.Text)
url = db.Column(db.Text)
comment = db.Column(db.Text)
class Stock_kits(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False)
description = db.Column(db.Text, nullable=False)
class Stock_kit_compositions(db.Model):
id = db.Column(db.Integer, primary_key=True)
kit_id = db.Column(db.Integer, db.ForeignKey('Stock_kits.id'), nullable=False)
component_id = db.Column(db.Integer, db.ForeignKey('Stock_componants.id'), nullable=False)
component_quantity = db.Column(db.Integer, nullable=False)
def resume_session(func):
@wraps(func)
def check(*args, **kwargs):
# default
limit = 10
offset = 0
page = 1
nexthop = offset + limit
prevhop = offset
order = 'asc'
order_refresh = 0
c_empty = ''
c_sort = 'reference'
c_provider = 0
c_count = 0
p_empty = ''
p_sort = 'name'
offset_reset = ['c_reference', 'c_designation', 'c_place', 'c_provider']
if not 'session' in session:
session['session'] = ''
if not 'c_limit' in session:
session['c_limit'] = limit
if not 'c_offest' in session:
session['c_offset'] = offset
if not 'c_sort' in session:
session['c_sort'] = c_sort
if not 'c_order' in session:
session['c_order'] = order
if not 'c_order_refresh' in session:
session['c_order_refresh'] = order_refresh
if not 'c_page' in session:
session['c_page'] = page
if not 'c_nexthop' in session:
session['c_nexthop'] = nexthop
if not 'c_prevhop' in session:
session['c_prevhop'] = prevhop
if not 'c_reference' in session:
session['c_reference'] = c_empty
if not 'c_designation' in session:
session['c_designation'] = c_empty
if not 'c_place' in session:
session['c_place'] = c_empty
if not 'c_provider' in session:
session['c_provider'] = c_provider
if not 'c_count' in session:
session['c_count'] = c_count
if not 'p_sort' in session:
session['p_sort'] = p_sort
if not 'p_order' in session:
session['p_order'] = order
if not 'p_order_refresh' in session:
session['p_order_refresh'] = order_refresh
if not 'p_page' in session:
session['p_page'] = page
if not 'p_nexthop' in session:
session['p_nexthop'] = nexthop
if not 'p_prevhop' in session:
session['p_prevhop'] = prevhop
if not 'p_offset' in session:
session['p_offset'] = offset
if not 'p_limit' in session:
session['p_limit'] = limit
if not 'p_name' in session:
session['p_name'] = p_empty
if not 'p_address' in session:
session['p_address'] = p_empty
if not 'p_mail' in session:
session['p_mail'] = p_empty
if not 'p_url' in session:
session['p_url'] = p_empty
if not 'p_comment' in session:
session['p_comment'] = p_empty
# Cookies/session sync
for key in request.cookies:
old = str(session[key])
try:
session[key] = int(str(request.cookies[key]))
except ValueError:
# Value is not an int, will be treated as string
session[key] = str(request.cookies[key])
if key in offset_reset and len(str(session[key])) > 0 and old != str(session[key]):
session['c_offset'] = 0
if key != 'session':
print '[s]', key, request.cookies[key]
# Switch sort order
if session['c_order_refresh'] == 1:
refresh = {'desc': 'asc', 'asc': 'desc'}
session['c_order'] = refresh[session['c_order']]
session['c_order_refresh'] = 0
if session['p_order_refresh'] == 1:
refresh = {'desc': 'asc', 'asc': 'desc'}
session['p_order'] = refresh[session['p_order']]
session['p_order_refresh'] = 0
return func(*args, **kwargs)
return check
########################################################################
# Routes
########################################################################
@app.errorhandler(404)
def page_not_found(e):
return render_template('error.html'), 404
@app.route("/")
def authenticate():
return render_template('index.html')
########################################################################
# Componants
########################################################################
@app.route('/componants', methods=['GET', 'POST'])
@resume_session
def componants():
""" Main page """
providers = Stock_providers.query.order_by(Stock_providers.id).all()
return render_template('componants.html',
providers=providers,
reference=session['c_reference'],
designation=session['c_designation'],
place=session['c_place'],
provider_id=session['c_provider'])
@app.route('/componants/<componant_id>')
@resume_session
def get_componant(componant_id):
""" Edit componant """
try:
componant_id = int(componant_id)
except ValueError as e:
return render_template('error.html'), 404
componant = Stock_componants.query.filter_by(id=componant_id).first()
if componant:
providers = Stock_providers.query.order_by(Stock_providers.name).all()
provider = componant.provider_id
provider = Stock_providers.query.filter_by(id=provider).first()
return render_template('componant.html', componant=componant, providers=providers, provider=provider)
return render_template('error.html'), 404
@app.route('/componants/update/<componant_id>', methods=['POST'])
@resume_session
def update_componant(componant_id):
""" Update componant field"""
field = request.form['field']
value = request.form['value']
if field and value:
try:
componant = Stock_componants.query.filter_by(id=componant_id).first()
setattr(componant, field, value)
commit = db.session.commit()
if commit == None:
return 'OK'
except Exception as e:
pass
return 'KO'
@app.route('/componants/delete/<componant_id>')
@resume_session
def delete_componant(componant_id):
""" Delete componant """
try:
componant_id = int(componant_id)
Stock_componants.query.filter_by(id=componant_id).delete()
db.session.commit()
except ValueError as e:
return render_template('error.html'), 404
except Exception as e:
print "[+] Error at delete_componant:\n------------------------------\n%s------------------------------" % e.message
return componants()
@app.route('/componants/new', methods=['POST'])
@resume_session
def new_componant():
""" Add componant """
componant = Stock_componants(reference=session['c_reference'],
designation=session['c_designation'],
last_price=0,
mean_price=0,
quantity=0,
min_quantity=0,
place=session['c_place'],
provider_id=session['c_provider'])
try:
db.session.add(componant)
commit = db.session.commit()
except Exception as e:
print "[+] Error at new_componant:\n------------------------------\n%s------------------------------" % e.message
return 'KO'
if commit != None:
return 'KO'
return 'OK'
@app.route('/componants/in/<componant_id>')
@resume_session
def in_componants():
""" Incoming order """
return render_template('wip.html')
@app.route('/componants/out/<componant_id>')
@resume_session
def out_componants():
""" Outgoing order """
return render_template('wip.html')
## Componants update result set
@app.route('/componants/update', methods=['POST'])
@resume_session
def update_componants():
""" Display componants list """
# search by reference
like = '%s%s%s' % ('%', str(session['c_reference']), '%')
componants = Stock_componants.query.filter(Stock_componants.reference.like(like))
# search by designation
like = '%s%s%s' % ('%', str(session['c_designation']), '%')
componants = componants.filter(Stock_componants.designation.like(like))
# search by place
like = '%s%s%s' % ('%', str(session['c_place']),'%')
componants = componants.filter(Stock_componants.place.like(like))
# search by provider
if session['c_provider'] > 1:
componants = componants.filter_by(provider_id=session['c_provider'])
# Pages calculation
session['c_count'] = componants.count()
session['c_pagecount'] = int(math.ceil(session['c_count'] / float(session['c_limit'])))
session['c_page'] = int(math.ceil(float(float(session['c_offset']) + 1) / float(session['c_limit'])))
if session['c_page'] > session['c_pagecount']:
session['c_page'] = session['c_pagecount']
session['c_offset'] = 0
session['c_nexthop'] = session['c_offset'] + session['c_limit']
if session['c_nexthop'] > session['c_count'] - 1:
session['c_nexthop'] = int(session['c_offset'])
session['c_prevhop'] = int(session['c_offset']) - session['c_limit']
if session['c_prevhop'] < 0:
session['c_prevhop'] = 0
# Sorting
sort = getattr(Stock_componants, session['c_sort'])
if session['c_order'] == 'desc':
sort = getattr(Stock_componants, session['c_sort']).desc()
componants = componants.order_by(sort)
# Applying offset
componants = componants.offset(session['c_offset'])
# Applying limit
componants = componants.limit(session['c_limit'])
# Get result
componants = componants.all()
response = app.make_response(render_template('result_componants.html',
componants=componants,
offset=session['c_offset'] ,
nexthop=session['c_nexthop'],
prevhop=session['c_prevhop'],
page_count=session['c_pagecount'],
page=session['c_page'],
sort=session['c_sort'],
order=session['c_order'],
row_count=session['c_count']))
for key in session:
response.set_cookie(key, value=str(session[key]))
if key != 'session':
print '[c]', key, session[key]
return response
########################################################################
# Providers
########################################################################
@app.route('/providers', methods=['GET', 'POST'])
@resume_session
def providers():
return render_template('providers.html',
name=session['p_name'],
address=session['p_address'],
mail=session['p_mail'],
url=session['p_url'],
comment=session['p_comment'])
@app.route('/providers/<provider_id>')
@resume_session
def get_provider(provider_id):
""" Edit provider """
try:
provider_id = int(provider_id)
except ValueError as e:
return render_template('error.html'), 404
provider = Stock_providers.query.filter_by(id=provider_id).first()
if provider:
return render_template('provider.html', provider=provider)
return render_template('error.html'), 404
@app.route('/providers/update/<provider_id>', methods=['POST'])
@resume_session
def update_provider(provider_id):
""" Update provider field"""
field = request.form['field']
value = request.form['value']
if field and value:
try:
provider = Stock_providers.query.filter_by(id=provider_id).first()
setattr(provider, field, value)
commit = db.session.commit()
if commit == None:
return 'OK'
except Exception as e:
pass
return 'KO'
@app.route('/providers/new', methods=['POST'])
@resume_session
def new_provider():
""" Add provider """
provider = Stock_providers(name=session['p_name'],
address=session['p_address'],
mail=session['p_mail'],
url=session['p_url'],
comment=session['p_comment'])
try:
db.session.add(provider)
commit = db.session.commit()
except Exception as e:
print 'Error at new_provider():', e
print 'Commit = ', commit
return 'KO'
if commit != None:
return 'KO'
return 'OK'
@app.route('/providers/delete/<provider_id>')
@resume_session
def delete_provider(provider_id):
""" Delete provider """
try:
provider_id = int(provider_id)
Stock_providers.query.filter_by(id=provider_id).delete()
db.session.commit()
except ValueError as e:
return render_template('error.html'), 404
except Exception as e:
print "[+] Error at delete_provider:\n-----------------------------\n%s-----------------------------" % e.message
return providers()
@app.route('/providers/update', methods=['POST'])
@resume_session
def search_providers():
""" Display componants list """
# search by reference
like = '%s%s%s' % ('%', str(session['p_name']), '%')
providers = Stock_providers.query.filter(Stock_providers.name.like(like))
# search by designation
like = '%s%s%s' % ('%', str(session['p_address']), '%')
providers = providers.filter(Stock_providers.address.like(like))
# search by place
like = '%s%s%s' % ('%', str(session['p_mail']),'%')
providers = providers.filter(Stock_providers.mail.like(like))
# search by place
like = '%s%s%s' % ('%', str(session['p_url']),'%')
providers = providers.filter(Stock_providers.url.like(like))
# search by place
like = '%s%s%s' % ('%', str(session['p_comment']),'%')
providers = providers.filter(Stock_providers.comment.like(like))
# Don't take 'all' and 'none' entry
providers = providers.filter(Stock_providers.id > 2)
# Pages calculation
session['p_count'] = providers.count()
session['p_pagecount'] = int(math.ceil(session['p_count'] / float(session['p_limit'])))
session['p_page'] = int(math.ceil(float(float(session['p_offset']) + 1) / float(session['p_limit'])))
if session['p_page'] > session['p_pagecount']:
session['p_page'] = session['p_pagecount']
session['p_offset'] = 0
session['p_nexthop'] = session['p_offset'] + session['p_limit']
if session['p_nexthop'] > session['p_count'] - 1:
session['p_nexthop'] = int(session['p_offset'])
session['p_prevhop'] = int(session['p_offset']) - session['p_limit']
if session['p_prevhop'] < 0:
session['p_prevhop'] = 0
# Sorting
sort = getattr(Stock_providers, session['p_sort'])
if session['p_order'] == 'desc':
sort = getattr(Stock_providers, session['p_sort']).desc()
providers = providers.order_by(sort)
# Applying offset
providers = providers.offset(session['p_offset'])
# Applying limit
providers = providers.limit(session['p_limit'])
# Get result
providers = providers.all()
response = app.make_response(render_template('result_providers.html',
providers=providers,
offset=session['p_offset'] ,
nexthop=session['p_nexthop'],
prevhop=session['p_prevhop'],
page_count=session['p_pagecount'],
page=session['p_page'],
sort=session['p_sort'],
order=session['p_order'],
row_count=session['p_count']))
for key in session:
response.set_cookie(key, value=str(session[key]))
if key != 'session':
print '[c]', key, session[key]
return response
########################################################################
# Kits
########################################################################
########################################################################
# Users
########################################################################
# Main #######################################
if __name__ == '__main__':
app.run(host='0.0.0.0')