db.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import pymysql
  2. class db():
  3. DB = "EBA_STOCK"
  4. USER = "root"
  5. PASSWORD = "howdoiturnthison"
  6. def connect(self):
  7. self.conn = pymysql.connect(unix_socket='/var/run/mysqld/mysqld.sock', user=db.USER, passwd=db.PASSWORD, db=db.DB,cursorclass=pymysql.cursors.DictCursor)
  8. def __init__(self):
  9. self.connect()
  10. def client(self, _hash):
  11. cur = self.conn.cursor()
  12. cur.execute("SELECT id,nombre,apellido,hash FROM clientes where hash=%s", (_hash,))
  13. res = cur.fetchall()
  14. if len(res) == 0:
  15. return None
  16. return res[0]
  17. def get_pedido(self, clientid, pedidoid):
  18. cur = self.conn.cursor()
  19. cur.execute( "SELECT id, cant_productos, subtotal, fecha, estado FROM pedidos where cliente = %s and id = %s", (int(clientid),pedidoid) )
  20. pedido = cur.fetchone()
  21. pedido["fecha"] = pedido["fecha"].strftime("%Y-%m-%d %H:%M")
  22. productos = self.products()
  23. cur.execute( "SELECT id_producto, cantidad FROM productos_pedido where id_pedido = %s", (int(pedidoid),) )
  24. for row in cur.fetchall():
  25. for p in productos:
  26. if p["id"] != row["id_producto"]:
  27. continue
  28. p["cantidad"] = row["cantidad"]
  29. pedido["productos"] = productos
  30. return pedido
  31. def pedidos(self, clientid):
  32. ret=[]
  33. cur = self.conn.cursor()
  34. cur.execute( "SELECT id, cant_productos, subtotal, fecha, estado FROM pedidos where cliente = %s", (int(clientid),) )
  35. for row in cur.fetchall():
  36. row["fecha"] = row["fecha"].strftime("%Y-%m-%d %H:%M")
  37. ret.append(row)
  38. return ret
  39. def products(self, _id=None):
  40. ret=[]
  41. if _id is None:
  42. cur = self.conn.cursor()
  43. cur.execute("SELECT id,nombre,precio FROM productos where id between 1000 and 2999")
  44. for row in cur.fetchall():
  45. row["cantidad"]=0
  46. ret.append(row)
  47. else:
  48. pass
  49. return ret
  50. def create_pedido(self, productos, _hash):
  51. clienteID = int(self.client(_hash)["id"])
  52. cur = self.conn.cursor()
  53. subtotal = sum([ p["precio"]*p["cantidad"] for p in productos])
  54. params = ( clienteID, sum([ p["cantidad"] for p in productos]), subtotal )
  55. #CREADO, CONFIRMADO, ARMADO, ENVIADO
  56. ex = cur.execute("insert into pedidos (cliente,cant_productos,subtotal,fecha,estado) values (%s, %s, %s, NOW(), 'CREADO')", params)
  57. _id = cur.lastrowid
  58. lista_productos = [ (_id,p["id"],p["cantidad"]) for p in productos ]
  59. cur.executemany("insert into productos_pedido(id_pedido,id_producto,cantidad) values (%s, %s, %s)", lista_productos)
  60. self.conn.commit()
  61. return 0