Skip to content

Instantly share code, notes, and snippets.

@Dinsmoor
Created December 11, 2017 21:09
Show Gist options
  • Select an option

  • Save Dinsmoor/7cffe6802e096fa4d3d3a577ec8a01e6 to your computer and use it in GitHub Desktop.

Select an option

Save Dinsmoor/7cffe6802e096fa4d3d3a577ec8a01e6 to your computer and use it in GitHub Desktop.
Super simple tool to manage orders for custom coasters
# text-based order management system
DEBUG = True
import pickle
import sys
import random
import datetime
from dateutil import parser as dateparser
try:
import readline
except Exception as e:
if DEBUG:
print e
# version 3 compatibility
if sys.version_info.major >= (3):
raw_input = input
t_fmt = '%d%b%y %H:%M'
class Orderman:
def __init__(self):
self.customer = None
self.commands = []
try:
dbn = sys.argv[1]
self.dbn = dbn
self.load_db()
except IndexError as e:
if DEBUG:
print(e)
print("You must pass a db name as an argument.")
exit()
except IOError as e:
if DEBUG:
print(e)
self.db = {}
print("Init new db as "+ dbn)
try:
readline.parse_and_bind("tab: complete")
readline.set_completer(self.complete)
except NameError as e:
if DEBUG:
print(e)
pass
self.control_loop()
def complete(self, text, state):
for cmd in self.commands:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1
def load_db(self, dbn=None):
if not dbn:
dbn = self.dbn
else:
self.dbn = dbn
self.db = pickle.load(open(dbn, 'rb'))
print("Loaded db", dbn)
def save_db(self, dbn=None):
if not dbn:
dbn = self.dbn
pickle.dump(self.db, open(dbn, 'wb'))
print("Saved db", dbn)
def control_loop(self):
while True:
self.commands = ['add','update','exit',
'list','find','savedb','loaddb',
'backup','restore','report', 'help',
'name','status','quantity','style',
'stain','total']
for customer in self.db.keys():
self.commands.append(customer)
try:
cmd = raw_input("> ")
s_cmd = cmd.split(" ")
if s_cmd[0] == "exit":
exit()
elif s_cmd[0] == "help":
print("""
? exit - 'exit' - Quits the program
? add - 'add' - Create a new order
? update - 'update Jon4433 status' - Update existing order
? list - 'list' - Show all orders
? find - 'find Jon' - Find orders containing a keyword
? loaddb - 'loaddb' - Reloads currently selected database
? savedb - 'savedb' - Saves currently selected database
? report - 'report' - Returns all order data
? backup - 'backup mybackup' - Makes a copy of the current database
? restore - 'restore mybackup' - Restores a copy to the current database
""")
elif s_cmd[0] == "add":
self.add_order()
elif s_cmd[0] == "update":
try:
self.customer = s_cmd[1]
self.update_order(s_cmd[2])
except IndexError:
self.update_order()
except KeyError:
print("Customer ID not found. Try 'list'")
elif s_cmd[0] == "list":
try:
print("Customer \tStatusDate \tStatus")
print("======== \t========== \t=======")
for customer in sorted(self.db):
print(customer+"\t"+\
self.db[customer]['statusdate'].strftime(t_fmt)+\
"\t"+self.db[customer]['status'])
except AttributeError as e:
print(e)
print(self.db)
elif s_cmd[0] == "find":
self.print_tableheaders()
self.find(s_cmd[1])
elif s_cmd[0] == "show":
self.print_tableheaders()
self.find(s_cmd[1])
elif s_cmd[0] == "loaddb":
self.load_db()
elif s_cmd[0] == "savedb":
self.save_db()
elif s_cmd[0] == "report":
self.print_tableheaders()
self.find("]}]")
elif s_cmd[0] == "backup":
self.save_db(s_cmd[1])
elif s_cmd[0] == "restore":
self.load_db(s_cmd[1])
elif s_cmd[0] == "suggest":
self.suggest()
else:
print("Invalid Query. Try 'help'")
except KeyboardInterrupt:
print("\n")
continue
except EOFError as e:
if DEBUG:
print(e)
print("Saving and Exiting")
self.save_db()
break
except IndexError as e:
if DEBUG:
print(e)
print("Syntax Error")
except AttributeError as e:
if DEBUG:
print(e)
print("Invalid Query. Try 'help'")
def add_order(self):
try:
name = raw_input("name> ")
try:
orderdate = dateparser.parse(raw_input("order date> "))
except Exception as e:
if DEBUG:
print(e)
print("Incorrect date format. Try '1 Dec 2017'")
raise TypeError
statusdate = datetime.datetime.today()
status = "order created"
quantity = raw_input("qty> ")
style = raw_input("style> ")
stain = raw_input("stain> ")
total = raw_input("total> ")
key = name+str(random.randrange(0,9999))
if key in self.db.keys():
key = key+str(random.randrange(0,9))
try:
self.db[key] = {
'name':name,
'orderdate':orderdate,
'statusdate':statusdate,
'status':status,
'quantity':quantity,
'style':style,
'stain':stain,
'total':total,
}
print("Created order customer ID "+ key)
self.save_db()
except TypeError as e:
if DEBUG:
print(e)
print("Error: Please check your entires.")
except KeyboardInterrupt:
print("Order entry cancelled\n")
def update_order(self, sel=None):
options = ['name','status','quantity','style','stain','total']
if not self.customer:
print("Cannot continue without a selected customer.")
return
if not sel:
sel = raw_input("value?> ")
if sel == "help":
for option in options:
print(option)
if sel in options:
modi = raw_input((sel+"> "))
if modi == "":
print("Update Cancelled")
return
self.db[self.customer][sel] = modi
print("Updated Customer "+self.customer+" to "+sel, modi)
if sel == "status":
self.db[self.customer]['statusdate'] = datetime.datetime.today()
self.save_db()
def print_tableheaders(self):
print("Customer\tStatus\t\tStatus Date\tOrder Date\tQty\tStyle\t\tStain\tTotal")
print("========\t======\t\t===========\t==========\t===\t=====\t\t=====\t=====")
def find(self, qry):
for customer in sorted(self.db):
if qry in (customer + str(self.db[customer].values()) +\
self.db[customer]['statusdate'].strftime(t_fmt) +\
self.db[customer]['orderdate'].strftime(t_fmt) + "]}]"):
print(customer+"\t"+\
self.db[customer]['status']+"\t"+\
self.db[customer]['statusdate'].strftime(t_fmt)+"\t"+\
self.db[customer]['orderdate'].strftime('%d%b%y %H')+"\t"+\
self.db[customer]['quantity']+"\t"+\
self.db[customer]['style']+"\t"+\
self.db[customer]['stain']+"\t"+\
self.db[customer]['total']+"\t")
def suggest(self):
self.print_tableheaders()
print("\tWork required")
for customer, data in self.db.iteritems():
if data['status'] == "order created":
self.find(customer)
print("\n")
print("\tDelivery Required")
for customer, data in self.db.iteritems():
if "delivery" in data['status']:
self.find(customer)
print("\n")
print("\tCollect Payment")
for customer, data in self.db.iteritems():
if "pay" in data['status']:
self.find(customer)
print("\n")
print("\tLong time with no status update")
for customer, data in self.db.iteritems():
if (data['statusdate'] - datetime.datetime.now()) >= datetime.timedelta(days=3):
print("Old status days: "+ (data['statusdate'] - datetime.datetime.now()).days)
self.find(customer)
if __name__ == "__main__":
Orderman()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment