def submit(request): if request.method != 'POST': raise Http404 # list of bundleids to ignore bundleid_ignorelist = [ 'com.apple.print.PrinterProxy' ] submission = request.POST mac = submission.get('mac') machine = None if mac: try: machine = Machine.objects.get(mac=mac) except Machine.DoesNotExist: machine = Machine(mac=mac) if machine: if 'hostname' in submission: machine.hostname = submission.get('hostname') if 'username' in submission: machine.username = submission.get('username') if 'location' in submission: machine.location = submission.get('location') machine.remote_ip = request.META['REMOTE_ADDR'] compressed_inventory = submission.get('base64bz2inventory') if compressed_inventory: compressed_inventory = compressed_inventory.replace(" ", "+") inventory_str = decode_to_string(compressed_inventory) try: inventory_list = plistlib.readPlistFromString(inventory_str) except Exception: inventory_list = None if inventory_list: try: inventory_meta = Inventory.objects.get(machine=machine) except Inventory.DoesNotExist: inventory_meta = Inventory(machine=machine) inventory_meta.sha256hash = \ hashlib.sha256(inventory_str).hexdigest() # clear existing inventoryitems machine.inventoryitem_set.all().delete() # insert current inventory items for item in inventory_list: # skip items in bundleid_ignorelist. if not item.get('bundleid') in bundleid_ignorelist: i_item = machine.inventoryitem_set.create( name=item.get('name', ''), version=item.get('version', ''), bundleid=item.get('bundleid', ''), bundlename=item.get('CFBundleName', ''), path=item.get('path', '') ) machine.last_inventory_update = datetime.now() inventory_meta.save() machine.save() return HttpResponse( "Inventory submmitted for %s.\n" % submission.get('hostname')) return HttpResponse("No inventory submitted.\n")
def set_password(self, service, username, password): ''' Set a (new) password ''' enc_pass = crypt.rsa_enc(self.user, password, verbose=self.verbose) Inventory.create(hostname=service, account_name=username, account_password=enc_pass)
def inventory_submit(request): if request.method != 'POST': return HttpResponseNotFound('No POST data sent') # list of bundleids to ignore bundleid_ignorelist = ['com.apple.print.PrinterProxy'] submission = request.POST serial = submission.get('serial') machine = None if serial: try: machine = Machine.objects.get(serial=serial) except Machine.DoesNotExist: return HttpResponseNotFound('Serial Number not found') compressed_inventory = submission.get('base64bz2inventory') if compressed_inventory: compressed_inventory = compressed_inventory.replace(" ", "+") inventory_str = utils.decode_to_string(compressed_inventory) try: inventory_list = plistlib.readPlistFromString(inventory_str) except Exception: inventory_list = None if inventory_list: try: inventory_meta = Inventory.objects.get(machine=machine) except Inventory.DoesNotExist: inventory_meta = Inventory(machine=machine) inventory_meta.sha256hash = \ hashlib.sha256(inventory_str).hexdigest() # clear existing inventoryitems machine.inventoryitem_set.all().delete() # insert current inventory items inventory_items_to_be_created = [] for item in inventory_list: app, _ = Application.objects.get_or_create( bundleid=item.get("bundleid", ""), name=item.get("name", ""), bundlename=item.get("CFBundleName", "")) # skip items in bundleid_ignorelist. if not item.get('bundleid') in bundleid_ignorelist: i_item = InventoryItem(application=app, version=item.get("version", ""), path=item.get('path', ''), machine=machine) if is_postgres(): inventory_items_to_be_created.append(i_item) else: i_item.save() machine.last_inventory_update = timezone.now() inventory_meta.save() if is_postgres(): InventoryItem.objects.bulk_create( inventory_items_to_be_created) machine.save() return HttpResponse("Inventory submmitted for %s.\n" % submission.get('serial')) return HttpResponse("No inventory submitted.\n")
def purge(): ''' Truncate all tables ''' Users.delete().execute() Inventory.delete().execute() AccessRights.delete().execute() Credentials.delete().execute()
def create(): """Create Method.""" form = InventoryForm(request.form) if form.validate_on_submit(): obj = Inventory() form.populate_obj(obj) obj.deleted = False Inventory.objects.insert(obj) flash("Elemento creado", "success") return redirect(url_for("inventory.list")) return render_template("inventory/create.html", action="create", form=form, menu=principal_menu(), config=config)
class TestOrder(unittest.TestCase): def setUp(self): self.inventory = Inventory() self.inventory.add("item #1", 50) def test_order_filled(self): order = Order("item #1", 50) order.fill(self.inventory) self.assertTrue(order.filled) self.assertEquals(0, self.inventory.get("item #1")) def test_order_not_filled(self): order = Order("item #1", 51) order.fill(self.inventory) self.assertFalse(order.filled) self.assertEquals(50, self.inventory.get("item #1"))
def delete_password(self, service, username): ''' Delete the password for the username of the service ''' inv = Inventory.get((Inventory.account_name) == username & (Inventory.hostname == service)) inv.delete_instance()
def delete_password(self, service, username): ''' Delete the password for the username of the service ''' inv = Inventory.get( (Inventory.account_name) == username & (Inventory.hostname == service) ) inv.delete_instance()
def postProduct(id): new_product = json.loads(request.data) product_name = None # start new code to fix to discriminate between new and old product.. I am doing with the name because if not I will need to set de sku_id on the front to the backend. # I think this code for name I should do it on models name_by_product = Product.query.filter_by(supplier_id=id).all() for item in name_by_product: if item.name == new_product["name"]: product_name = item.name else: product_name = new_product["name"] # finish new code to fix to discriminate between new and old product sku_id = new_product['sku_id'] if product_name == new_product["name"] else random.randint(1,999999) # sku_id = new_product['sku_id'] if "sku_id" in new_product else random.randint(1,999999) product_old = Product.query.filter_by(sku_id=sku_id).filter_by(supplier_id=id).first() if product_old is None: product = Product( category=new_product["category"], sku_id=sku_id, name=new_product["name"], description=new_product["description"], quantity_in=new_product["quantity_in"], price=new_product["price"], supplier_id=id ) inventory = Inventory() inventory.total_supplier_stock = new_product['quantity_in'] db.session.add(product) db.session.commit() return jsonify(product.serialize()), 200 if product_old is not None: stock_old_product= product_old.quantity_in + new_product['quantity_in'] inventory_query = Inventory.query.filter_by(product_id=product_old.id).first() inventory_query.total_supplier_stock = stock_old_product db.session.commit() return jsonify(inventory_query.serialize()), 200
def grant(hostname, user, account_name, verbose=False): ''' Grant access to some credentials ''' inv = Inventory.get(hostname=hostname, account_name=account_name) ar = AccessRights.create(created_by=user.identifier, user=user.identifier, host=inv.identifier) plaintext = crypt.rsa_dec(user, inv.account_password, verbose) cipher = crypt.rsa_enc(user, plaintext) Credentials.create(access=ar.identifier, password=cipher)
def post(self): inventory_from_payload = inventory_parser.parse_args() inventory = Inventory( id=inventory_from_payload['id'], name=inventory_from_payload['name'], description=inventory_from_payload['description'], duration=inventory_from_payload['itemscount'] ) db.session.add(inventory) db.session.commit() return inventory
def create_new_inventory(self): print("Please choose a name for your new inventory!") new_name = self.prompt_for_name() with self.connection.cursor() as cursor: query = sql.insert_query('inventories', ('username', 'name'), [(self.player.username, new_name)], return_fields='*') cursor.execute(query) inventory = next(sql.objects(cursor)) return Inventory(self.connection, inventory)
def populate_inventory(): """ populate db with inventory """ with open('inventory.txt') as fobj: inventory = fobj.read().strip() with db_session() as session: for item in inventory.split('\n'): item = item.split(',') row = Inventory(product_name=item[0], quantity=item[1]) session.add(row)
def get(self): user = users.get_current_user() if user is None: login_url = users.create_login_url('/welcome') self.response.write('<html><body>{}</body></html>'.format('<a href="' + login_url + '">Sign in</a>')) return residence = Residence.get_residence_by_user(user) inventory = Inventory.get_inventory_by_user(user) other_homes = Residence.query(Residence.own==residence.own).fetch() logging.error(other_homes) rooms = [] for home in other_homes: rooms += Room.query(ancestor=home.key).filter(Room.name!="miscellaneous").fetch() room_count = {} for room in rooms: name = room.name if name in room_count: room_count[name] += 1 continue room_count[name] = 1 room_count_final = {} for room in room_count: my_count = Room.query(ancestor=residence.key).filter(Room.name==room).count() if my_count == 0: room_count_final[str(room)] = ("", room_count[room] / max(len(other_homes), 1)) else: up_count = str(my_count + 1) my_tail = "" if up_count[-1:] in ["0", "4", "5", "6", "7", "8", "9"]: my_tail = "th" elif up_count[-1:] in ["2"]: my_tail = "nd" elif up_count[-1:] in ["1"]: my_tail = "st" elif up_count[-1:] in ["3"]: my_tail = "rd" room_count_final[str(room)] = (" (" + up_count + my_tail + ")", room_count[room] / max(len(other_homes), 1) - 2 * my_count) room_count_final = sorted(room_count_final.items(), key=lambda x: x[1][1], reverse=True) template = JINJA_ENVIRONMENT.get_template('tourRoomPage.html') template_data = {'rooms': room_count_final} self.response.write(template.render(template_data))
def post(self): user = users.get_current_user() if user is None: login_url = users.create_login_url('/home') template_data = {} template_data['login_url'] = login_url template = JINJA_ENVIRONMENT.get_template('login.html') self.response.write(template.render(template_data)) return residence = Residence.get_residence_by_user(user) category = self.request.get('category') name = self.request.get('name') price = self.request.get('price') room_name = self.request.get("room") if name.strip() == '' or category.strip() == '': if room_name == "miscellaneous": self.redirect("home") else: self.redirect("/room-tour?room=" + urllib.quote(room_name)) return price = float(price) inventory = Inventory.get_inventory_by_user(user) item = Item(category=category, name=name, price=price, parent=inventory.key) item.put() residence = Residence.get_residence_by_user(user) room = Room.query(ancestor=residence.key).filter(Room.name==room_name).get() if room is None: room = Room(name=room_name, parent=residence.key) room.put() relation = ItemRoomRelation(item=item.key, room=room.key, parent=inventory.key) relation.put() if room_name == "miscellaneous": self.redirect("/home") return self.redirect("/room-tour?room=" + urllib.quote(room_name))
def update_inventory(): inventory = None if session.has_key('username'): groupme_id = session['groupme_id'] inventory = [{ 'type': k[0], 'level': k[1], 'value': v['value'] } for k, v in Inventory(pk=groupme_id, pk_name="groupme_id").nodes.iteritems()] return render_template('update_inventory.html', inventory=inventory, item_map=item_map)
def index(): inventory = None if session.has_key('username'): groupme_id = session['groupme_id'] inventory = [{ 'type': k[0], 'level': k[1], 'value': v['value'] } for k, v in Inventory(pk=groupme_id, pk_name="groupme_id").nodes.iteritems()] return render_template('index.html', inventory=inventory) else: return render_template('login.html')
def get(self): user = users.get_current_user() if user is None: login_url = users.create_login_url('/home') template_data = {} template_data['login_url'] = login_url template = JINJA_ENVIRONMENT.get_template('login.html') self.response.write(template.render(template_data)) return inventory = Inventory.get_inventory_by_user(user) items = inventory.get_items().fetch() logout_url = users.create_logout_url("/") relations = [] for item in items: relations += ItemRoomRelation.query(ancestor=inventory.key).filter(ItemRoomRelation.item==item.key).fetch() i = 0 relation_data = {} for relation in relations: i += 1 if i > 5: break room_name = relation.room.get().name if room_name in relation_data: relation_data[room_name] += relation.item.get().price else: relation_data[room_name] = relation.item.get().price i = 0 cols = ["#4789b", "#EF7014", "#4BA449", "#154995", "#757374"] relation_data_final = [] for k in relation_data: i += 1 relation_data_final.append({"title": str(k), "value": relation_data[k], "color": cols[i]}) relation_data_final = sorted(relation_data_final, key=lambda x: x["value"], reverse=True) template_data = {} template_data['relations'] = relation_data_final self.response.write(json.dumps(relation_data_final))
def run(self): print("Creating an inventory!") inventories = Inventory.get_for_player(self.connection, self.player.username) option, inventory = self.prompt_for_inventory_option(inventories) if option == 'rename': self.rename_inventory(inventory) else: if option == 'create': inventory = self.create_new_inventory() self.inventory_modify_menu(inventory)
def addCatalogItem(): if not login_session.get('access_token'): return redirect('/') else: logged_in = True ownerId = login_session["user_id"] # Query all of the categories categories = session.query(Categories).order_by("categoryName").all() # POST methods actions if request.method == 'POST': # Set the name of the new restaurant into the dictionary new_item = Items(itemName=request.form['item_name'], itemDescription=request.form['item_description'], owner=ownerId, added=currentDateTime, modified=currentDateTime, status='A') # Add it to the session session.add(new_item) # Commit the addition to the database session.commit() addedItem = session.query(Items).order_by(Items.itemId.desc()).first() """Flash message that the item was successfully added. Add BOOTSTRAP css classes as the message category.""" flash('New item was successfully added! (%s)' % addedItem.itemName, 'badge badge-success') new_cat = request.form['item_category'] new_count = request.form['item_inventory'] new_price = request.form['item_price'] new_item_category = ItemCategories(categoryId=new_cat, itemId=addedItem.itemId) new_item_inventory = Inventory(itemId=addedItem.itemId, inventoryCount=new_count, itemPrice=new_price, lastUpdated=currentDateTime) session.add(new_item_category) session.add(new_item_inventory) session.commit() # Item Tags - Outside of scope of this project - Do later # Item Photo - Outside of scope of this project - Do later # Redirect the user back to the main Restaurants page return redirect(url_for('showMyItems')) # GET method actions else: # Display the Add New Restaurant form page return render_template('addItem_LoggedIn.html', categories=categories, email=login_session['email'], logged_in=logged_in)
def getStock(id): supplier_filter = Supplier.query.filter_by(id=id).first() id_supplier = supplier_filter.id supplier_product_list = Product.query.filter_by(id=id_supplier) products = list(map(lambda item: item.serialize(), supplier_product_list)) # product_list = Product.query.all() # supplier_product_list = filter(lambda item: item.id == id_supplier, product_list) # products = list(map(lambda item: item.serialize(), supplier_product_list)) total_supplier_stock = 0 for product in supplier_product_list: total_supplier_stock += product.quantity inventory = Inventory(total_supplier_stock=total_supplier_stock) return jsonify({"exitoso": total_supplier_stock}), 200
def load_inventory(inventory): i = 0 while i < len(inventory): newentry = None newentry = Inventory(bibnum=int(inventory[i]['bibnum']), itemcount=int(inventory[i]['itemcount']), entrydate=datetime.datetime.strptime( inventory[i]['entrydate'], '%d/%m/%Y')) book = db.session.query(Book).filter( Book.bibnum == int(inventory[i]['bibnum'])).first() if book is not None: db.session.add(newentry) book.inventoryentry.append(newentry) db.session.commit() i += 1
def get(self): user = users.get_current_user() if user is None: login_url = users.create_login_url('/home') template_data = {} template_data['login_url'] = login_url template = JINJA_ENVIRONMENT.get_template('login.html') self.response.write(template.render(template_data)) return inventory = Inventory.get_inventory_by_user(user) items = inventory.get_items().fetch() total_price = 0 logout_url = users.create_logout_url("/") relations = [] for item in items: relations += ItemRoomRelation.query(ancestor=inventory.key).filter(ItemRoomRelation.item==item.key).fetch() total_price += item.price relation_data = {} for relation in relations: item = relation.item.get() item_data = {'category': item.category, 'name': item.name, 'price': "${0:.2f}".format(item.price), 'encoded': urllib.quote(item.name)} if relation.room.get().name in relation_data: relation_data[relation.room.get().name].append(item_data) continue relation_data[str(relation.room.get().name)] = [item_data] logging.error(relation) logging.error(relation_data) template_data = {} template_data['relations'] = relation_data template_data['total_price'] = "${0:.2f}".format(total_price) template_data['logout_url'] = logout_url template = JINJA_ENVIRONMENT.get_template('userHomePage.html') self.response.write(template.render(template_data))
def get(self): user = users.get_current_user() if user is None: login_url = users.create_login_url('/welcome') self.response.write('<html><body>{}</body></html>'.format('<a href="' + login_url + '">Sign in</a>')) return name = self.request.get("name") inventory = Inventory.get_inventory_by_user(user) item = Item.query(ancestor=inventory.key).filter(Item.name==name).get() if item is not None: for relation in ItemRoomRelation.query(ancestor=inventory.key).filter(ItemRoomRelation.item==item.key).fetch(): relation.key.delete() item.key.delete() self.redirect("home")
def perform(self, vendor_id=None, docs=None): amazon = Vendor.query.filter_by(name='Amazon').one() for doc in docs: order_number = doc.pop('order_number') vendor_sku = doc.pop('msku') fnsku = doc.pop('fnsku') # Get the order order = Order.query.filter_by(source_id=vendor_id, dest_id=amazon.id, order_number=order_number).first() \ or Order(source_id=vendor_id, dest_id=amazon.id, order_number=order_number) db.session.add(order) # Get the listings listing = Listing.query.filter_by(vendor_id=order.source_id, sku=vendor_sku).one() amz_listing = Listing.query.filter( Listing.vendor_id == amazon.id, Listing.extra['fnsku'].astext == fnsku).one() # Get the inventories src_inv = listing.inventory dest_inv = Inventory.query.filter_by(listing_id=amz_listing.id, owner_id=listing.vendor.id).first() \ or Inventory(listing=amz_listing, owner=listing.vendor) db.session.add(dest_inv) # Get the order item item = OrderItem.query.filter_by(order_id=order.id, source_id=src_inv.id, dest_id=dest_inv.id).first() \ or OrderItem(order=order, source=src_inv, destination=dest_inv) item.update(doc) # If this is a new order item, send_inventory() if item.id is None: item.send_inventory() db.session.add(item) db.session.commit()
def update_or_add_inventory(db_session, inventory_obj, serial_number, model_name, notes, commit=True): """ Either update or add the inventory given serial number, model name(optional), and notes(optional) :param db_session: session of database transactions :param inventory_obj: the inventory row that we got from querying with the provided serial_number :param serial_number: input serial number string :param model_name: input model name string :param notes: input notes string :param commit: if true, commit the db transaction in the end, else, don't commit :return: None. """ if inventory_obj: # if this inventory has been discovered in a host, model_name cannot be updated by user # there is restriction on front end, but double ensure it here if isinstance(inventory_obj.host_id, (int, long)): inventory_obj.update(db_session, notes=notes) # if this inventory is not found in a host, user can define/update the model_name else: inventory_obj.update(db_session, model_name=model_name, notes=notes) if commit: db_session.commit() else: inv = Inventory(serial_number=serial_number, model_name=model_name, notes=notes) db_session.add(inv) if commit: db_session.commit() return
def perform(self, docs=None, vendor_id=None): vendor = Vendor.query.filter_by(id=vendor_id).one() for doc in docs: # Import the Amazon amz_doc = {'sku': doc['sku'], 'fnsku': doc['fnsku']} amz_id = ImportListing(amz_doc) # Import the vendor listing vnd_doc = {'vendor_id': vendor_id, 'sku': doc['msku']} try: vnd_id = vendor.ext.call('ImportListing', **vnd_doc) except (ValueError, AttributeError): vnd_id = coreops.listings.ImportListing(doc=vnd_doc) # Update or create the inventory relationship inventory = Inventory.query.filter_by( owner_id=vendor_id, listing_id=amz_id).first() or Inventory( owner_id=vendor_id, listing_id=amz_id) inventory.update( fnsku=doc['fnsku'], fulfillable=doc['fulfillable'], ) db.session.add(inventory) db.session.commit() # Get updated info for the Amazon listing dqc.pipeline([ mws.GetCompetitivePricingForASIN.message(amz_doc, vendor_id=vendor_id), pa.ItemLookup.message(vendor_id=vendor_id), mws.GetMyFeesEstimate.message(vendor_id=vendor_id), ImportListing.message(), CopyToListing.message(vnd_id) ]).run()
def perform(self, vendor_id=None, order_id=None, items=None): amazon = Vendor.query.filter_by(name='Amazon').one() vendor = Vendor.query.filter_by(id=vendor_id).one() for item_doc in items: sku = item_doc['sku'] amz_listing = Listing.query.filter_by(vendor_id=amazon.id, sku=sku).first() \ or Listing(vendor=amazon, sku=sku) item = OrderItem.query.filter( OrderItem.order_id == order_id, OrderItem.extra['order_item_id'].astext == item_doc['order_item_id']).first() or OrderItem( order_id=order_id) item.quantity = item_doc.pop('qty_shipped') item.received = item.quantity item.source = Inventory.query.filter_by(owner_id=vendor.id, listing_id=amz_listing.id).first() \ or Inventory(owner=vendor, listing=amz_listing) item.destination = None item.update(item_doc) db.session.add(item) db.session.commit()
def inventory_apply_task(pk): log.info("Starting task inventory apply of inventory {}".format(pk)) status, alerts = Inventory.apply_inventory(pk) log.info("Task inventory apply finished for inventory {}".format(pk))
def start(): switch = True while switch: print(""" 1.New Checkout 2.View Today's sale 3.Update Discount by category 4.Exit/Quit """) choice = input("Greetings! Select from the menu:") if choice == "1": in_checkout = True while in_checkout: print(""" 1.Add item Name/Code 2.View stock availability 3.Finish and get bill 4.Exit """) checkout_choice = input("Please enter option:") register_obj = Register() if checkout_choice == '1': print(""" Enter "D" when done Enter "C" if item code needs to be referred """) purchased = [] interrupt = False while not interrupt: code = input("Enter item code:") if code == 'd' or code == 'D': interrupt = True break elif code == 'c' or code == 'C': """ Option for billing person to pause entering code and check item code by its name in case code needs to be referred. """ item_name = input("Enter name to fetch item code:") item_code = Inventory.get_item_code(item_name) print('Item code:', item_code) else: purchased.append(code) prices = Inventory.get_price_list(purchased) register_obj.checkout(purchased, prices) elif checkout_choice == '2': stock = Inventory.get_stock() views.view_stock_availability(stock) elif checkout_choice == '3': """ To avail customer based discount """ print(""" 1.Enter s to check if customer is senior citizen 2.Enter P to check for other privileges 3.Press Enter key to proceed with bill generation without privilege check """) privilege = input('Enter option: ') if privilege == 's': discount_percentage = 30 register_obj.update_discount(discount_percentage) elif privilege == 'p': mobile_num = input( "Enter mobile number to check for special discounts" ) if Customer(mobile_num).checkprevilige(): discount_percentage = 20 register_obj.update_discount(discount_percentage) """ Fetching bill statement and final bill amount """ bill = register_obj.get_bill() views.view_bill(bill) bill_amount = register_obj.get_bill_amount() """ Using polymorphism to make payment using multiple methods, two sample methods used as example """ payment_method = input('1.Cash 2.Card 3.Both') payment_obj = [] if payment_method == '1': payment_obj.append(Cash()) if payment_method == '2': payment_obj.append(Card()) if payment_method == '3': payment_obj.append(Cash()) payment_obj.append(Card()) for option in payment_obj: option.receive_payment(bill_amount) """ Updating total sales and stock quantity once payment succeeds """ Inventory.update_stock(purchased) Store.update_total(bill_amount) in_checkout = False elif checkout_choice == '4': in_checkout = False elif choice == "2": views.view_total_sales(Store.get_total()) elif choice == "3": """ Apply discount to items by category or code (Inventory level discount) """ category = input( "Enter item code or category(to update all items of that category) to apply discount" ) Inventory.update_item_prices(category) elif choice == "4": switch = False print("\n Goodbye") elif choice != "": print("\n Not Valid Choice Try again")
def get(self): products = Inventory.all() filtered_product = products.order("price") self.render("main.html", products=filtered_product)
def setUp(self): self.inventory = Inventory() self.inventory.add("item #1", 50)
def test_remove_item_from_inventory(): inventory = Inventory() inventory.add("item #1", 5).remove("item #1", 3) assert inventory.get("item #1") == 2
def test_remove_invalid_quantity_inventory(): inventory = Inventory() inventory.add("item #1", 3).remove("item #1", 5) assert inventory.get("item #1") == 3
def test_remove_then_add_item_in_inventory(): inventory = Inventory() inventory.add("item #1", 5) inventory.remove("item #1", 3).add("item #1", 4) assert inventory.get("item #1") == 6
def format_input(request): # this will throw a ValueError if there are not enough values date, small, medium, large = request.split(',') formatted_inputs = [] for input in request.split(','): # this will throw a ValueError if the input cannot be cast formatted_inputs.append(int(input)) return formatted_inputs event_requests = [] for request in sys.argv[1:]: try: input = format_input(request) except ValueError: print( "Invalid input format. Please provide 4 integers in format: date,small,medium,large ie. 5,0,3,2" ) exit(1) else: event_requests.append(input) inventory = Inventory() can_fufill = inventory.can_fufill_all_events(event_requests) if not can_fufill: print("Buy More Tuxedos") exit(1) print("Sufficient Inventory")
def test_add_item_into_inventory(): inventory = Inventory() inventory.add("item #1", 1) assert inventory.get("item #1") == 1
def get(self): user = users.get_current_user() if user is None: login_url = users.create_login_url('/welcome') self.response.write('<html><body>{}</body></html>'.format('<a href="' + login_url + '">Sign in</a>')) return name = self.request.get("room") if name is '': self.response.write("no room specified") ResidenceTourHandler residence = Residence.get_residence_by_user(user) room = Room.query(ancestor=residence.key).filter(Room.name==name).get() if room is None: room = Room(name=name, parent=residence.key) room.put() other_rooms = Room.query(Room.name==name).fetch() relations = [] for other_room in other_rooms: relations += ItemRoomRelation.query(ItemRoomRelation.room==other_room.key).fetch() item_count = {} for relation in relations: category = relation.item.get().category if category in item_count: item_count[category] += 1 continue item_count[category] = 1 logging.error(item_count) inventory = Inventory.get_inventory_by_user(user) item_count_final = {} for item in item_count: my_count = Item.query(ancestor=inventory.key).filter(Item.category==item).count() if my_count == 0: item_count_final[str(item)] = ("", item_count[item] / max(len(other_rooms), 1)) else: up_count = str(my_count + 1) my_tail = "" if up_count[-1:] in ["0", "4", "5", "6", "7", "8", "9"]: my_tail = "th" elif up_count[-1:] in ["2"]: my_tail = "nd" elif up_count[-1:] in ["1"]: my_tail = "st" elif up_count[-1:] in ["3"]: my_tail = "rd" logging.error( "(" + up_count + my_tail + ")") item_count_final[str(item)] = ("(" + up_count + my_tail + ")", item_count[item] / max(len(other_rooms), 1) - 2 * my_count) item_count_final = sorted(item_count_final.items(), key=lambda x: x[1][1], reverse=True) logging.error(item_count_final) template = JINJA_ENVIRONMENT.get_template('tourItemPage.html') template_data = {} template_data['items'] = item_count_final template_data['room'] = room.name self.response.write(template.render(template_data))
def test_cannot_remove_item_from_inventory(): inventory = Inventory() inventory.remove("item #1", 3)
def test_get_item_in_inventory(): inventory = Inventory() assert inventory.get("item #1") == 0