class Buy(): """Handles the SuperPy buy action Uses the bought and products database to record the buy action New products are added to the product database, complete with a new EAN13 barcode Bought products are then stored in the bought database """ def __init__(self, args): self.args = args check_required_arguments( args, ('product_name', 'price', 'expiration_date')) self.database_bought = Database( config.BOUGHT_FILE, config.BOUGHT_FIELDS) self.database_products = Database( config.PRODUCTS_FILE, config.PRODUCTS_FIELDS) self.product_name = args['product_name'] def run(self): # check id product exists in product database product = filter_list( self.database_products.data, 'product_name', [self.product_name]) barcode = '' if len(product) == 0: # generate a new barcode barcode = Barcode(config.STORE_BARCODE_PREFIX) # add product to products database self.database_products.add({ 'product_name': self.product_name, 'full_name': self.product_name.title(), 'ean13': barcode, }) else: # use preexisting barcode barcode = product[0]['ean13'] # add buy to bought database self.database_bought.add( { 'id': self.database_bought.rowcount + 1, 'product_name': self.product_name, 'buy_date': Today().get_date(), 'buy_price': self.args['price'], 'expiration_date': self.args['expiration_date'], 'ean13': barcode }) return 'OK'
class Sell(): """Handles the SuperPy sell action Uses the bought and products database to record the sell action Sold products that are in inventory are stored in the sold database The product with the earliest expiration date is sold first """ def __init__(self, args): self.args = args check_required_arguments(args, ('product_name', 'price')) self.database_bought = Database(config.BOUGHT_FILE, config.BOUGHT_FIELDS) self.database_sold = Database(config.SOLD_FILE, config.SOLD_FIELDS) def run(self): bought_id = self.get_bought_id() if bought_id == None: return 'ERROR: Product not in stock' self.database_sold.add({ 'id': self.database_sold.rowcount + 1, 'bought_id': bought_id, 'sell_date': Today().get_date(), 'sell_price': self.args['price'], }) return 'OK' def get_bought_id(self): inventory = filter_list(self.database_bought.data, 'product_name', [self.args['product_name']]) if len(inventory) == 0: return None # sell the product with the earliest expiration date inventory = sort_list(inventory, 'expiration_date') if len(inventory) == 1: return inventory[0]['id'] for item in inventory: is_sold = filter_list(self.database_sold.data, 'bought_id', [item['id']]) if len(is_sold) == 0: return item['id'] return None