admin.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #!/usr/bin/env python
  2. #
  3. # All-in-one admin script.
  4. #
  5. import os
  6. import sys
  7. import csv
  8. import time
  9. import sqlite3 as sql
  10. # Nonstandard imports:
  11. import config
  12. def init():
  13. '''
  14. Initiates the databases in SQLite
  15. '''
  16. conn = sql.connect(config.db)
  17. cursor = conn.cursor()
  18. try:
  19. cursor.execute("""
  20. CREATE TABLE catalog (
  21. name TEXT NOT NULL,
  22. price REAL NOT NULL,
  23. stock INTEGER NOT NULL
  24. )
  25. """)
  26. cursor.executemany("""
  27. INSERT INTO catalog VALUES (?, ?, 0)
  28. """, config.prices)
  29. cursor.execute(
  30. """
  31. CREATE TABLE transactions (
  32. trans_id INTEGER PRIMARY KEY AUTOINCREMENT,
  33. customer TEXT,
  34. email TEXT,
  35. sabonete_mel INTEGER,
  36. sabonete_patchouli INTEGER,
  37. sabonete_papoula INTEGER,
  38. sabonete_capimlimao INTEGER,
  39. alcoolgel INTEGER,
  40. status TEXT,
  41. rating INTEGER,
  42. create_date TEXT,
  43. paid_date TEXT,
  44. sent_date TEXT
  45. )
  46. """)
  47. conn.commit()
  48. print "Database initialized."
  49. except sql.OperationalError:
  50. print "Databases already exist. Cannot init."
  51. conn.close()
  52. def new_purchase(customer, email, mel, patchouli, papoula, capimlimao, gel):
  53. '''
  54. Logs in a new purchase in detail (every single product)
  55. '''
  56. conn = sql.connect(config.db)
  57. cursor = conn.cursor()
  58. purchases = (mel, patchouli, papoula, capimlimao, gel)
  59. new_id = "unknown"
  60. i = 0
  61. try:
  62. for product in config.products:
  63. cursor.execute("""
  64. SELECT stock FROM catalog
  65. WHERE name = ?
  66. """, (product,))
  67. in_stock = int(cursor.fetchone()[0])
  68. if purchases[i] > in_stock:
  69. i = product
  70. raise ValueError, "unavailable"
  71. else:
  72. cursor.execute("""
  73. UPDATE catalog
  74. SET stock = ?
  75. WHERE name = ?
  76. """, (in_stock - purchases[i], product))
  77. i += 1
  78. # if everything was available, commit these changes:
  79. conn.commit()
  80. # log this transaction in the history:
  81. cursor.execute("""
  82. INSERT INTO transactions (
  83. customer, email,
  84. sabonete_mel,
  85. sabonete_patchouli,
  86. sabonete_papoula,
  87. sabonete_capimlimao,
  88. alcoolgel,
  89. create_date, status
  90. )
  91. VALUES (?, ?, ?, ?, ?, ?, ?, ?, "pendente")
  92. """, (customer, email, mel, patchouli, papoula, capimlimao, gel,
  93. time.ctime()
  94. ))
  95. conn.commit()
  96. new_id = cursor.lastrowid
  97. conn.close()
  98. return (new_id, "ok")
  99. except sql.OperationalError, e:
  100. print "Error: %s" % e
  101. print "Please check if the order is correctly typed."
  102. conn.rollback()
  103. conn.close()
  104. raise sql.OperationalError, e
  105. except ValueError:
  106. conn.rollback()
  107. conn.close()
  108. new_id = "unavailable"
  109. return (new_id, i)
  110. def view_availability(prodname):
  111. '''
  112. Returns the available quantity of a given product in the database
  113. '''
  114. conn = sql.connect(config.db)
  115. cursor = conn.cursor()
  116. cursor.execute("""
  117. SELECT stock FROM catalog
  118. WHERE name = ?
  119. """, (prodname,))
  120. quantity = cursor.fetchone()
  121. conn.close()
  122. if quantity is not None:
  123. return quantity[0]
  124. else:
  125. return "product not found"
  126. def view_purchase(trans_id):
  127. '''
  128. Views an existing purchase.
  129. '''
  130. conn = sql.connect(config.db)
  131. cursor = conn.cursor()
  132. cursor.execute("""
  133. SELECT customer, email,
  134. sabonete_mel,
  135. sabonete_patchouli,
  136. sabonete_papoula,
  137. sabonete_capimlimao,
  138. alcoolgel,
  139. status, create_date
  140. FROM transactions
  141. WHERE trans_id = ?
  142. """, (trans_id,))
  143. order = cursor.fetchone()
  144. conn.close()
  145. return order
  146. def update_price():
  147. '''
  148. When the price changes (in the config), run this to update the DB.
  149. '''
  150. conn = sql.connect(config.db)
  151. cursor = conn.cursor()
  152. try:
  153. cursor.executemany(
  154. """
  155. UPDATE catalog
  156. SET price = ?
  157. WHERE name = ?
  158. """, config.prices
  159. )
  160. conn.commit()
  161. except sql.OperationalError, e:
  162. print "Error: %s" % e
  163. print "Please run the 'init' command to initialize the database."
  164. conn.rollback()
  165. conn.close()
  166. def view_everything():
  167. '''
  168. View all the stock
  169. '''
  170. conn = sql.connect(config.db)
  171. cursor = conn.cursor()
  172. cursor.execute("SELECT name, stock FROM catalog")
  173. for row in cursor.fetchall():
  174. print row
  175. conn.close()
  176. def get_transactions(status):
  177. '''
  178. Lists all transaction IDs and customers for a given status.
  179. Returns tuple of tuple(id, email address)
  180. '''
  181. conn = sql.connect(config.db)
  182. cursor = conn.cursor()
  183. cursor.execute("""
  184. SELECT trans_id, email FROM transactions
  185. WHERE status = ?
  186. """, (status,))
  187. transactions = cursor.fetchall()
  188. conn.close()
  189. return transactions
  190. if __name__ == "__main__":
  191. if "update" in sys.argv:
  192. update_price()
  193. elif "init" in sys.argv:
  194. init()
  195. elif "new" in sys.argv:
  196. customer = raw_input("Nome do cliente: ")
  197. email = raw_input("Email para contato: ")
  198. while True:
  199. mel = input("Qtd sabonetes mel: ")
  200. patchouli = input("Qtd sabonetes patchouli: ")
  201. papoula = input("Qtd sabonetes papoula: ")
  202. capimlimao = input("Qtd sabonetes capim-limao: ")
  203. alcool_gel = input("Qtd alcool-gel: ")
  204. ok = raw_input("Informacoes ok? (s/n) ")
  205. if ok == "s":
  206. break
  207. try:
  208. code = new_purchase(customer, email, mel, patchouli, papoula, capimlimao, alcool_gel)
  209. if code[1] == "ok":
  210. print "Pedido cadastrado. Codigo do pedido: %s" % code[0]
  211. else:
  212. print "Produto em falta no estoque: %s" % code[1]
  213. except sql.OperationalError, e:
  214. print "Erro ao cadastrar: %s" % e
  215. elif "view" in sys.argv:
  216. transaction = raw_input("Codigo do pedido: ")
  217. purchase = view_purchase(transaction)
  218. if purchase is not None:
  219. print "Sumario do pedido #%s:" % transaction
  220. print "Cliente: %s (%s)" % (purchase[0], purchase[1])
  221. print "************************"
  222. print "Descricao do pedido:"
  223. if purchase[2] != 0:
  224. print "Sabonete de Mel: %s unidades" % purchase[2]
  225. if purchase[3] != 0:
  226. print "Sabonete de Patchouli: %s unidades" % purchase[3]
  227. if purchase[4] != 0:
  228. print "Sabonete de Papoula: %s unidades" % purchase[4]
  229. if purchase[5] != 0:
  230. print "Sabonete de Capim-limao: %s unidades" % purchase[5]
  231. if purchase[6] != 0:
  232. print "Alcool-gel: %s unidades" % purchase[6]
  233. print "************************"
  234. print "Status do pedido: %s" % purchase[7]
  235. print "Criado em: %s" % purchase[8]
  236. else:
  237. print "Pedido nao encontrado."
  238. elif "debug" in sys.argv:
  239. view_everything()
  240. elif "trans" in sys.argv:
  241. trans = get_transactions("pendente")
  242. for tran in trans:
  243. print "Order #%s by %s" % (tran[0], tran[1])
  244. else:
  245. print "Options are 'init', 'update', 'new', 'view', 'trans' 'debug'"
  246. sys.exit(0)