Exemplo n.º 1
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.º 2
0
def inventory_new(request):
    """
    Inventory Edit Page
    """
    type = request.path.split("/")[-2]
    template = ""

    if type == "book":
        template = "capstone/book_edit.html"
    elif type == "dvd":
        template = "capstone/dvd_edit.html"
    else:
        template = ""

    if request.method == 'POST':
        if type == "book":
            form = BookEditForm(request.POST)
        elif type == "dvd":
            form = DVDEditForm(request.POST)
        else:
            form = {}

        if form.is_valid():
            new_item = form.save(commit=False)

            inventory_type = InventoryType.objects.filter(
                type_name__contains=type).first()

            inventory_item = InventoryItem(available=True,
                                           active=True,
                                           price=form.cleaned_data['price'],
                                           inventory_type=inventory_type)

            inventory_item.save()
            new_item.save()

            new_item.inventory = inventory_item
            new_item.save()

            return redirect('inventory_details',
                            pk=inventory_item.inventory_id)
    else:
        if type == "book":
            form = BookEditForm()
        elif type == "dvd":
            form = DVDEditForm()
        else:
            form = {}

    responseData = {
        "form": form,
    }

    return render(request, template, responseData)
Exemplo n.º 3
0
def get_inventory(db=None):
    """
    Gets all InventoryItems.

    :param db: optional, the database connection to commit to
    :returns: list, all items in Inventory as InventoryItems
    """
    db = db or get_db()
    cur = db.cursor()

    cur.execute("""
        SELECT ItemID, ItemName, Description, Price, Category, Quantity
        FROM InventoryItem    
    """)

    result = []
    for row in cur.fetchall():
        try:
            if row[5] > 0:
                result.append(InventoryItem(id_=row[0], name=row[1], description=row[2],
                                            price=row[3], category=ItemCategory[row[4]], qty=row[5]))
        except Exception as e:
            print("invalid inventory item:", e)

    cur.close()
    return result
Exemplo n.º 4
0
def get_shopping_cart(user, db=None):
    """
    Gets all ShoppingCartItems for user

    :param user: User, the user to request for
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()
    cur.execute("""
        SELECT InventoryItemID, Price, Quantity
        FROM ShoppingCartItem
        WHERE UserID = ?
    """, [user.id_])

    cart = ShoppingCart(user)
    for row in cur.fetchall():
        try:
            item = get_inventory_item(InventoryItem(id_=row[0]), db)
            cart.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2]))
        except Exception as e:
            print("invalid purchase item:", e)

    cur.close()
    return cart
Exemplo n.º 5
0
def get_user_purchases(user, db=None):
    """
    Gets all purchases by user.

    :param user: User, the user to find purchases for
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()

    # insert the purchase
    cur.execute("""
        SELECT PurchaseID, TotalPrice, CreditCard, Address
        FROM Purchase
        WHERE Username=? 
    """, [user.username])

    purchases = []
    for row1 in cur.fetchall():
        purchase = Purchase(username=user.username, id_=row1[0], total_price=row1[1],
                            credit_card=row1[2], address=Address().from_str(row1[3]))
        cur.execute("""
            SELECT InventoryItemID, Price, Quantity
            FROM PurchaseItem
            WHERE PurchaseID=?
        """, [purchase.id_])
        for row2 in cur.fetchall():
            item = get_inventory_item(InventoryItem(row2[0]), db)
            purchase.items.append(ShoppingCartItem(item=item, price=row2[1], qty=row2[2]))
        purchases.append(purchase)

    cur.close()
    return purchases
Exemplo n.º 6
0
def inventory_update_view():
    if login.current_user.is_anonymous():
        abort()
    # 1 = checkin, 2 = checkout
    status = int(request.form["status"])
    checkout_meta = None
    # provide meta
    if status == InventoryItem.CHECKED_OUT:  # checkout
        dtype = int(request.form["duration_type"])
        duration = request.form["duration"]
        try:
            duration = int(duration)
            # enforce duration limit
            if duration > 999:
                duration = 999
        except ValueError:
            duration = 0
        checkout_meta = CheckoutMeta(
            duration=duration, duration_type=dtype, is_ooo=(True if int(request.form.get("ooo", 0)) else False)
        )
    person = Person.objects(id=request.form["personid"]).get()
    item = InventoryItem.objects(id=request.form["itemid"]).get()
    # add a log
    log = InventoryLog.add_log(
        person=person, item=item, status=int(request.form["status"]), checkout_meta=checkout_meta
    )
    # update the item status
    item.status = status
    item.save()
    response = {
        "duration": {"dateAdded": log.get_date_added(), "description": log.get_checkout_description()},
        "person": {"name": log.person.name},
    }
    return json.dumps(response)
Exemplo n.º 7
0
def get_warehouse_inventory_list(warehouse):
    db = get_cloudant_db(warehouse)
    inventory_list = {}
    for doc_id in db:
        doc = db[doc_id]
        if doc['type'] not in inventory_list:
            inventory_list[doc['type']] = [
                InventoryItem(doc['_id'], doc['quantity'], doc['description'],
                              doc['warehouse'], doc['price'], doc['type'],
                              doc['name'])
            ]
        else:
            inventory_list[doc['type']].append(
                InventoryItem(doc['_id'], doc['quantity'], doc['description'],
                              doc['warehouse'], doc['price'], doc['type'],
                              doc['name']))
    return inventory_list
Exemplo n.º 8
0
def cart_add():
    if request.args.get('id') is None:
        return redirect('/inventory')

    db.add_to_cart(user=User(current_user.get_id()),
                   item=db.get_inventory_item(
                       InventoryItem(id_=request.args.get('id'))))
    return redirect('/cart')
Exemplo n.º 9
0
 def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
     super(InventoryItemForm, self).__init__(request.form, obj, prefix, **kwargs)
     self.csrf_enabled = False
     self.group.choices = [(str(grp.id), grp.name) for grp in InventoryGroup.objects]
     # select the group
     if request.args.get('id') and not self.is_submitted():
         item = InventoryItem.objects(id=request.args.get('id')).get()
         self.group.data = str(item.group.id)
Exemplo n.º 10
0
 def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
     super(InventoryItemForm, self).__init__(request.form, obj, prefix,
                                             **kwargs)
     self.csrf_enabled = False
     self.group.choices = [(str(grp.id), grp.name)
                           for grp in InventoryGroup.objects]
     # select the group
     if request.args.get('id') and not self.is_submitted():
         item = InventoryItem.objects(id=request.args.get('id')).get()
         self.group.data = str(item.group.id)
Exemplo n.º 11
0
def cart_remove():
    if request.args.get('id') is None:
        return redirect('/cart')

    id_ = request.args.get('id')
    qty = request.args.get('qty')

    db.remove_from_cart(user=User(current_user.get_id()),
                        item=ShoppingCartItem(item=InventoryItem(id_=id_)),
                        qty=qty)
    return redirect('/cart')
Exemplo n.º 12
0
 def create_model(self, form):
     # only if its set do we care if its unique
     if form.identifier.data and InventoryItem.objects(identifier=form.identifier.data).count():
         flash('Identifier (%s) is already in use' % form.identifier.data)
         return False
     # overriden to update the date values of the model
     now = datetime.now()
     item = InventoryItem(
         name=form.name.data,
         identifier=form.identifier.data,
         comment=form.comment.data,
         status=form.status.data,
         # get the model for the target group
         group=InventoryGroup.objects.get(id=form.group.data),
         date_added=now,
         date_updated=now
     )
     try:
         item.save()
     except Exception, e:
         flash('Unable to add the item', category='error')
         if settings.DEBUG:
             flash('DEBUG: %s' % e, category='error')
         return False
Exemplo n.º 13
0
 def create_model(self, form):
     # only if its set do we care if its unique
     if form.identifier.data and InventoryItem.objects(
             identifier=form.identifier.data).count():
         flash('Identifier (%s) is already in use' % form.identifier.data)
         return False
     # overriden to update the date values of the model
     now = datetime.now()
     item = InventoryItem(
         name=form.name.data,
         identifier=form.identifier.data,
         comment=form.comment.data,
         status=form.status.data,
         # get the model for the target group
         group=InventoryGroup.objects.get(id=form.group.data),
         date_added=now,
         date_updated=now)
     try:
         item.save()
     except Exception, e:
         flash('Unable to add the item', category='error')
         if settings.DEBUG:
             flash('DEBUG: %s' % e, category='error')
         return False
Exemplo n.º 14
0
def cart_update():
    for id_, qty in request.args.items():
        # this makes sure we only use ints
        # noinspection PyBroadException
        try:
            qty = int(qty)
            inv_item = db.get_inventory_item(InventoryItem(id_))
            if inv_item.quantity >= qty:
                db.update_cart(user=User(current_user.get_id()),
                               item=ShoppingCartItem(item=inv_item),
                               qty=qty)
            else:
                flask.flash(
                    "<b>Exceeds stock:</b> {} has no more than {} items available."
                    .format(inv_item.name, inv_item.quantity), "warning")
        except Exception:
            continue
    return redirect('/cart')
Exemplo n.º 15
0
def handle_headers(payload, sock):
    block_headers = Headers.parse(payload)
    print(f'{len(block_headers.headers)} new headers')
    update_blocks(block_headers)

    # after 500 headers, get the blocks
    if len(blocks) < 500:
        send_getheaders(sock)
    else:
        items = [
            InventoryItem(2, int_to_little_endian(hash_, 32))
            for hash_ in blocks[:10]
        ]
        getdata = GetData(items=items)
        msg = Message(getdata.command, getdata.serialize())
        sock.send(msg.serialize())

    print(f'We now have {len(blocks)} headers')
Exemplo n.º 16
0
def get_inventory_item(item, db=None):
    """
    Gets a singular InventoryItem
    :param item: InventoryItem
    :param db: optional
    :return: InventoryItem
    """
    db = db or get_db()
    cur = db.cursor()

    cur.execute("""
        SELECT ItemID, ItemName, Description, Price, Category, Quantity
        FROM InventoryItem
        WHERE ItemID=?   
    """, [item.id_])
    row = cur.fetchone()
    if row is not None:
        return InventoryItem(id_=row[0], name=row[1], description=row[2],
                             price=row[3], category=ItemCategory[row[4]], qty=row[5])
    return None
Exemplo n.º 17
0
def get_purchase(purchase, db=None):
    """
    Gets a purchase from the database based on PurchaseID

    :param purchase: Purchase, must have id
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()
    cur.execute("""
        SELECT Username, TotalPrice, CreditCard, Address
        FROM Purchase
        WHERE PurchaseID = ?
    """, [purchase.id_])

    row = cur.fetchone()
    try:
        purchase = Purchase(id_=purchase.id_, username=row[0], total_price=row[1],
                            credit_card=row[2], address=Address().from_str(row[3]))
    except Exception as e:
        print("invalid purchase:", e)

    cur.execute("""
        SELECT InventoryItemID, Price, Quantity
        FROM PurchaseItem
        WHERE pi.PurchaseID = ?
    """, [purchase.id_])

    for row in cur.fetchall():
        try:
            item = get_inventory_item(InventoryItem(id_=row[0]), db)
            purchase.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2]))
        except Exception as e:
            print("invalid purchase item:", e)

    cur.close()
    return purchase
Exemplo n.º 18
0
 def add_item(btn):
     session.merge(InventoryItem(character=character.name, item=btn.text))
     session.commit()
     self.dismiss()
     item_tab.set_items()
Exemplo n.º 19
0
def create_db(force=False):
    """
    Automatically creates database, if needed.
    :param force: if True, creates the database anyways. NOTE: does not delete existing db. Renames
                    renames old database to DATABASE_FILE.db.old.
    """
    if force:
        try:
            print("attempting to archive existing database.")
            os.rename(DATABASE, DATABASE + ".old")
        except OSError as ose:
            print("error archiving database file:", ose)

    # if database does not exist, create tables
    if not os.path.exists(DATABASE) or force:
        db = sqlite3.connect("./data.db")
        cur = db.cursor()

        # create User table
        cur.execute("""
            CREATE TABLE User (
                UserID INTEGER PRIMARY KEY AUTOINCREMENT,
                Username TEXT,
                Password TEXT
            );
        """)
        # create InventoryItem table
        cur.execute("""
            CREATE TABLE InventoryItem (
                ItemID INTEGER PRIMARY KEY AUTOINCREMENT,
                ItemName TEXT,
                Description TEXT,
                Price FLOAT,
                Category TEXT,
                Quantity INTEGER
            );
        """)
        db.commit()
        # create Purchase table
        cur.execute("""
            CREATE TABLE Purchase (
                PurchaseID INTEGER PRIMARY KEY AUTOINCREMENT,
                Username TEXT,
                TotalPrice FLOAT,
                CreditCard TEXT,
                Address TEXT
            );
        """)
        db.commit()
        # create PurchaseItem table
        cur.execute("""
            CREATE TABLE PurchaseItem (
                PurchaseID INTEGER,
                InventoryItemID INTEGER,
                Price FLOAT,
                Quantity INTEGER,
                FOREIGN KEY (PurchaseID) REFERENCES Purchase (PurchaseID),
                FOREIGN KEY (InventoryItemID) REFERENCES InventoryItem (ItemID)
            );
        """)
        db.commit()
        # create ShoppingCartItem table
        cur.execute("""
            CREATE TABLE ShoppingCartItem (
                UserID INTEGER,
                InventoryItemID INTEGER,
                Price FLOAT,
                Quantity INTEGER,
                FOREIGN KEY (UserID) REFERENCES User (UserID),
                FOREIGN KEY (InventoryItemID) REFERENCES InventoryItem (ItemID)
            );
        """)
        db.commit()

        # insert Admin user
        add_user(User(username="******", password="******"), db)

        # insert Sample Inventory items
        add_item(InventoryItem(name="Apple", description="One a day is 19g of sugar!", price=1.25,
                               category=ItemCategory.TOYS, qty=23), db)
        add_item(InventoryItem(name="Teddy Bear", description="Missing his head, but he still loves you!", price=9.99,
                               category=ItemCategory.TOYS, qty=6), db)

        add_item(InventoryItem(name="Book", description="That's a nice cover. I might read that.", price=42.11,
                               category=ItemCategory.BOOKS, qty=2), db)
        add_item(InventoryItem(name="The Great Gatsby", description="Every girls dream love story.", price=18.50,
                               category=ItemCategory.BOOKS, qty=30), db)
        add_item(InventoryItem(name="Twilight", description="Spurkle Purty", price=0.99,
                               category=ItemCategory.BOOKS, qty=88), db)

        add_item(InventoryItem(name="Raspberry Pi", description="What do you do with this?", price=3.14,
                               category=ItemCategory.SMALL_ELECTRONICS, qty=99), db)
        add_item(InventoryItem(name="Apple Pi", description="Raspberry pi, but tastier!", price=5.55,
                               category=ItemCategory.SMALL_ELECTRONICS, qty=99), db)

        add_item(InventoryItem(name="Toothpaste", description="Minty Fresh", price=500.99,
                               category=ItemCategory.HOUSEHOLD_ITEMS, qty=10), db)

        db.commit()
        cur.close()
        db.close()