Няма описание

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. from flask import Flask, render_template, request, redirect, jsonify
  2. from flask_sqlalchemy import SQLAlchemy
  3. import datetime
  4. import json
  5. import urllib.request
  6. import os
  7. import csv
  8. import sys
  9. app = Flask(__name__)
  10. connect = 'mysql+pymysql://root@localhost/restaurante'
  11. app.config['SQLALCHEMY_DATABASE_URI'] = connect
  12. db = SQLAlchemy(app)
  13. path_to_upload = os.getcwd() + '/static'
  14. if os.path.isdir(path_to_upload):
  15. app.config['UPLOAD_FOLDER'] = path_to_upload
  16. else:
  17. os.mkdir(path_to_upload)
  18. app.config['UPLOAD_FOLDER'] = path_to_upload
  19. class ordenes(db.Model):
  20. id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  21. nombre_cliente = db.Column(db.String(60))
  22. fecha = db.Column((db.DateTime), default=datetime.datetime.utcnow)
  23. num_celular = db.Column(db.String(14))
  24. class comida(db.Model):
  25. id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  26. categoria = db.Column(db.String(20))
  27. path_a_imagen = db.Column(db.String(50))
  28. nombre = db.Column(db.String(50))
  29. precio = db.Column(db.Float)
  30. descripcion = db.Column(db.Text)
  31. comida_bebida = db.Column(db.Integer)
  32. class orden_comida(db.Model):
  33. orden_id = db.Column(db.Integer, db.ForeignKey(ordenes.id))
  34. comida_id = db.Column(db.Integer, db.ForeignKey(comida.id))
  35. id = db.Column(db.Integer, autoincrement=True, primary_key=True)
  36. peticion = db.Column(db.Text, default=None)
  37. class orden_servidas(db.Model):
  38. orden_id = db.Column(db.Integer, db.ForeignKey(
  39. ordenes.id), primary_key=True)
  40. @app.route('/')
  41. def menu():
  42. return render_template('home.html', descripcion='Restaurante Ejemplo')
  43. @app.route('/ElMenuCategorizado')
  44. def ElMenuCategorizado():
  45. categorias = db.engine.execute(
  46. 'SELECT DISTINCT categoria from comida where comida_bebida =0')
  47. return render_template('ElMenuCategorizado.html', descripcion='El Menú', categorias=categorias)
  48. @app.route('/view/<string:categoriaStr>', methods=['POST', 'GET'])
  49. def viewItem(categoriaStr):
  50. if request.method == 'POST':
  51. files = request.files['imagen']
  52. if files:
  53. filename = (files.filename)
  54. files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  55. post_nombre = request.form['nombre']
  56. post_descripcion = request.form['descripcion']
  57. post_precio = float(request.form['Precio'])
  58. try:
  59. post_categoria = request.form['selectCat']
  60. if post_categoria == '0':
  61. post_categoria = request.form['nuevaCategoria']
  62. except KeyError:
  63. post_categoria = categoriaStr
  64. post_id = request.form['idItem']
  65. if files:
  66. db.engine.execute(
  67. 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}", path_a_imagen ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, files.filename, post_id))
  68. else:
  69. db.engine.execute(
  70. 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, post_id))
  71. db.session.commit()
  72. return redirect('/view/'+categoriaStr)
  73. else:
  74. items = comida.query.filter_by(categoria=categoriaStr).all()
  75. categorias = db.engine.execute(
  76. 'SELECT DISTINCT categoria from comida where comida_bebida=0')
  77. return render_template('verComida.html', link='view', descripcion=categoriaStr, items=items, categorias=categorias)
  78. @app.route('/deleteItem/<string:categoriaStr>/<int:itemId>')
  79. def deleteItem(categoriaStr, itemId):
  80. item = comida.query.filter_by(id=itemId).first()
  81. db.session.delete(item)
  82. db.session.commit()
  83. return redirect('/view/'+categoriaStr)
  84. @app.route('/csvMenu', methods=['POST', 'GET'])
  85. def csvMenu():
  86. if request.method == 'POST':
  87. files = request.files['CSV_file']
  88. if files:
  89. filename = (files.filename)
  90. files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  91. with open(os.getcwd() + '/static/'+filename) as csv_file:
  92. csv_reader = csv.reader(csv_file, delimiter=',')
  93. for row in csv_reader:
  94. try:
  95. post_nombre = row[0]
  96. post_descripcion = row[1]
  97. post_precio = float(row[2])
  98. post_categoria = row[3]
  99. post_nombreImagen = row[4]
  100. post_comidaBebida = int(row[5])
  101. db.session.add(comida(nombre=row[0], descripcion=row[1], precio=float(row[2]),
  102. path_a_imagen=row[4], comida_bebida=row[5], categoria=row[3]))
  103. db.session.commit()
  104. except ValueError:
  105. continue
  106. return redirect('/')
  107. else:
  108. return render_template('csvMenu.html', descripcion='Subir CSV')
  109. @app.route('/addItem', methods=['POST', 'GET'])
  110. def addItem():
  111. if request.method == 'POST':
  112. files = request.files['imagen']
  113. if files:
  114. filename = (files.filename)
  115. files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  116. post_nombre = request.form['nombre']
  117. post_descripcion = request.form['descripcion']
  118. post_precio = float(request.form['Precio'])
  119. post_categoria = request.form['categoria']
  120. if post_categoria == '0':
  121. post_categoria = request.form['nuevaCategoria']
  122. post_tipo = request.form['tipoDeItem']
  123. db.session.add(comida(nombre=post_nombre, categoria=post_categoria, descripcion=post_descripcion,
  124. precio=post_precio, path_a_imagen=files.filename, comida_bebida=post_tipo))
  125. db.session.commit()
  126. return redirect('/addItem')
  127. else:
  128. categorias = db.engine.execute(
  129. 'SELECT DISTINCT categoria from comida where comida_bebida =0')
  130. return render_template('addItem.html', descripcion='Añadir item al menú', categorias=categorias)
  131. @app.route('/viewBebidas')
  132. def viewBebidas():
  133. categorias = db.engine.execute(
  134. 'SELECT DISTINCT categoria from comida where comida_bebida =1')
  135. return render_template('LasBebidas.html', descripcion='El Menú', categorias=categorias)
  136. last_entry = 0
  137. @app.route('/ordenes', methods=['POST', 'GET'])
  138. def ordenesFun():
  139. if request.method == 'POST':
  140. post_order = int(request.get_json()['order'])
  141. db.engine.execute(
  142. 'delete from `ordenes` where id = {}'.format(post_order))
  143. db.engine.execute(
  144. 'delete from `orden_comida` where orden_id ={}'.format(post_order))
  145. db.session.commit()
  146. return redirect('/ordenes')
  147. else:
  148. global last_entry
  149. ordenesJson = {}
  150. ordenesCompletas = ordenes.query.all()
  151. for orden in ordenesCompletas:
  152. print(orden.id, file=sys.stderr)
  153. query2 = db.engine.execute(
  154. 'SELECT comida_id, peticion, categoria, nombre, precio, comida_bebida FROM `ordenes`, `orden_comida`, comida where comida.id=orden_comida.comida_id and ordenes.id = orden_comida.orden_id and orden_comida.orden_id = {} ORDER BY ordenes.id '.format(orden.id))
  155. ordenFull = []
  156. for comida in query2:
  157. ordenesDict = {}
  158. ordenesDict['comida_id'] = comida.comida_id
  159. ordenesDict['peticion'] = comida.peticion
  160. ordenesDict['nombre'] = comida.nombre
  161. ordenesDict['categoria'] = comida.categoria
  162. ordenesDict['precio'] = comida.precio
  163. ordenesDict['comida_bebida'] = comida.comida_bebida
  164. ordenFull.append(ordenesDict)
  165. print(ordenFull, file=sys.stderr)
  166. ordenesJson.setdefault(orden.id, {})['ordenCompleta'] = ordenFull
  167. ordenesJson[orden.id]['nombre'] = orden.nombre_cliente
  168. ordenesJson[orden.id]['num_celular'] = orden.num_celular
  169. ordenesJson[orden.id]['fecha'] = orden.fecha
  170. last_entry = orden.id
  171. return render_template('ordenes.html', ordenes=ordenesJson, descripcion='Ordenes Pendientes')
  172. @app.route('/retrieveMenu', methods=['POST', 'GET'])
  173. def retrieveMenu():
  174. if request.method == "GET":
  175. categoriasDeComida = db.engine.execute(
  176. "select categoria from comida where comida_bebida =0")
  177. comidaDict = {}
  178. for categoria in categoriasDeComida:
  179. query = db.engine.execute(
  180. "select * from comida where categoria ='{}'".format(categoria['categoria']))
  181. comidaDict[categoria['categoria']] = {}
  182. for item in query:
  183. comidaDict[categoria['categoria']][item['id']] = {}
  184. comidaDict[categoria['categoria']
  185. ][item['id']]['nombre'] = item['nombre']
  186. comidaDict[categoria['categoria']
  187. ][item['id']]["precio"] = item["precio"]
  188. comidaDict[categoria['categoria']
  189. ][item['id']]["descripcion"] = item["descripcion"]
  190. comidaDict[categoria['categoria']
  191. ][item['id']]["path_a_imagen"] = item["path_a_imagen"]
  192. categoriasDeBebidas = db.engine.execute(
  193. "select categoria from comida where comida_bebida=1")
  194. bebidaDict = {}
  195. for categoria in categoriasDeBebidas:
  196. query = db.engine.execute(
  197. "select * from comida where categoria ='{}'".format(categoria['categoria']))
  198. bebidaDict[categoria['categoria']] = {}
  199. for item in query:
  200. bebidaDict[categoria['categoria']][item['id']] = {}
  201. bebidaDict[categoria['categoria']
  202. ][item['id']]['id'] = item['id']
  203. bebidaDict[categoria['categoria']
  204. ][item['id']]['nombre'] = item['nombre']
  205. bebidaDict[categoria['categoria']
  206. ][item['id']]["precio"] = item["precio"]
  207. bebidaDict[categoria['categoria']
  208. ][item['id']]["descripcion"] = item["descripcion"]
  209. bebidaDict[categoria['categoria']
  210. ][item['id']]["path_a_imagen"] = item["path_a_imagen"]
  211. wholeDict = {"comidas": comidaDict, "bebidas": bebidaDict}
  212. print(wholeDict)
  213. return jsonify(wholeDict)
  214. @app.route('/papelonDeComida', methods=['POST', 'GET'])
  215. def papelonDeComida():
  216. global last_entry
  217. if request.method == 'GET':
  218. ordenesJson = {}
  219. ordenesCompletas = ordenes.query.filter(
  220. ordenes.id > last_entry).all()
  221. for orden in ordenesCompletas:
  222. query2 = db.engine.execute(
  223. 'SELECT comida_id, peticion, categoria, nombre, precio, comida_bebida FROM `ordenes`, `orden_comida`, comida where comida.id=orden_comida.comida_id and ordenes.id = orden_comida.orden_id and orden_comida.orden_id = {} ORDER BY ordenes.id '.format(orden.id))
  224. ordenFull = []
  225. for comida in query2:
  226. ordenesDict = {}
  227. ordenesDict['comida_id'] = comida.comida_id
  228. ordenesDict['peticion'] = comida.peticion
  229. ordenesDict['nombre'] = comida.nombre
  230. ordenesDict['categoria'] = comida.categoria
  231. ordenesDict['precio'] = comida.precio
  232. ordenesDict['comida_bebida'] = comida.comida_bebida
  233. ordenFull.append(ordenesDict)
  234. print(ordenFull, file=sys.stderr)
  235. ordenesJson.setdefault(orden.id, {})['ordenCompleta'] = ordenFull
  236. ordenesJson[orden.id]['nombre'] = orden.nombre_cliente
  237. ordenesJson[orden.id]['num_celular'] = orden.num_celular
  238. ordenesJson[orden.id]['fecha'] = orden.fecha
  239. last_entry = orden.id
  240. return jsonify(ordenesJson)
  241. else:
  242. print('vamos a insertar', file=sys.stderr)
  243. post_nombre = request.get_json()[0]['nombre']
  244. post_num = request.get_json()[0]['celular']
  245. post_order = []
  246. post_order.append(request.get_json()[0]['ordenCompleta'])
  247. post_order.append(request.get_json()[0]['peticiones'])
  248. print(post_order, file=sys.stderr)
  249. db.session.add(
  250. ordenes(nombre_cliente=post_nombre, num_celular=post_num))
  251. db.session.commit()
  252. last_id = ordenes.query.order_by(ordenes.id.desc()).first().id
  253. print(last_id, file=sys.stderr)
  254. for order in post_order[0]:
  255. try:
  256. print(order, file=sys.stderr)
  257. post_peti = post_order[1][order]
  258. except KeyError as k:
  259. post_peti = ""
  260. db.session.add(orden_comida(orden_id=last_id,
  261. comida_id=post_order[0][order], peticion=post_peti))
  262. print("Insertando", file=sys.stderr)
  263. db.session.commit()
  264. return "YOU DID IT"
  265. @app.route('/viewBebidas/<string:categoriaStr>', methods=['POST', 'GET'])
  266. def viewBebida(categoriaStr):
  267. if request.method == 'POST':
  268. files = request.files['imagen']
  269. if files:
  270. filename = (files.filename)
  271. files.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  272. post_nombre = request.form['nombre']
  273. post_descripcion = request.form['descripcion']
  274. post_precio = float(request.form['Precio'])
  275. try:
  276. post_categoria = request.form['selectCat']
  277. print(post_categoria)
  278. if post_categoria == '0':
  279. print('im here')
  280. post_categoria = request.form['nuevaCategoria']
  281. except KeyError:
  282. post_categoria = categoriaStr
  283. post_id = request.form['idItem']
  284. if files:
  285. db.engine.execute(
  286. 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}", path_a_imagen ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, files.filename, post_id))
  287. else:
  288. db.engine.execute(
  289. 'update comida set nombre ="{}", descripcion ="{}", precio ={}, categoria ="{}" where id = {}'.format(post_nombre, post_descripcion, post_precio, post_categoria, post_id))
  290. db.session.commit()
  291. return redirect('/viewBebidas/'+categoriaStr)
  292. else:
  293. items = comida.query.filter_by(categoria=categoriaStr).all()
  294. categorias = db.engine.execute(
  295. 'SELECT DISTINCT categoria from comida where comida_bebida =1')
  296. return render_template('verComida.html', link='viewBebidas', descripcion=categoriaStr, items=items, categorias=categorias)
  297. if __name__ == "__main__":
  298. app.run(debug=True, threaded=True,)