Exemplo n.º 1
0
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")
Exemplo n.º 2
0
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")
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
 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
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
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')
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
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
Exemplo n.º 12
0
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
Exemplo n.º 13
0
    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()
Exemplo n.º 14
0
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
Exemplo n.º 15
0
    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()
Exemplo n.º 16
0
    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 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")