Beispiel #1
0
def item_form(request, id=None):
    if id:
        item = get_object_or_404(Item, id=id)
        scenario = 'Update'
    else:
        item = Item()
        scenario = 'Create'
    if request.POST:
        form = ItemForm(data=request.POST, instance=item, user=request.user)
        if form.is_valid():
            item = form.save(commit=False)
            item.save(account_no=form.cleaned_data['account_no'], opening_balance=form.cleaned_data['opening_balance'])
            if request.is_ajax():
                return render(request, 'callback.html', {'obj': ItemSerializer(item).data})
            return redirect('/inventory/items/')
    else:
        form = ItemForm(instance=item, user=request.user)
    if request.is_ajax():
        base_template = 'modal.html'
    else:
        base_template = 'inventory_base.html'
    return render(request, 'item_form.html', {
        'scenario': scenario,
        'form': form,
        'base_template': base_template,
    })
def index(request):
    # GET is simple, and just queries the database and dumps out
    # the results
    if request.method == 'GET':
        list_of_items = Item.objects.all()
        data = serializers.serialize("json", list_of_items)
        return HttpResponse(data, content_type="application/json")
    # POST requires a bit of authentication and some logic to
    # determine if we are going to be adding a new item or just
    # updating an old one
    if request.method == 'POST':
        if request.user.username:
            data = json.loads(request.body.decode(), parse_float=Decimal)['fields']
            items = Item.objects.filter(itemId=data['itemId'])
            if items:
                for o in items:
                    o.count = data['count']
                    o.save()
            else:
                item = Item(itemId=data['itemId'], count=data['count'], name=data['name'], short=data['short'], desc=data['desc'])
                item.save()
            return HttpResponse({}, content_type="application/json")
        else:
            # Of course, make sure to notify the user that a login is
            # required to post items or change them
            return HttpResponse('Unauthorized', status=401)
Beispiel #3
0
def index(request):
    # GET is simple, and just queries the database and dumps out
    # the results
    if request.method == 'GET':
        list_of_items = Item.objects.all()
        data = serializers.serialize("json", list_of_items)
        return HttpResponse(data, content_type="application/json")
    # POST requires a bit of authentication and some logic to
    # determine if we are going to be adding a new item or just
    # updating an old one
    if request.method == 'POST':
        if request.user.username:
            data = json.loads(request.body.decode(),
                              parse_float=Decimal)['fields']
            items = Item.objects.filter(itemId=data['itemId'])
            if items:
                for o in items:
                    o.count = data['count']
                    o.save()
            else:
                item = Item(itemId=data['itemId'],
                            count=data['count'],
                            name=data['name'],
                            short=data['short'],
                            desc=data['desc'])
                item.save()
            return HttpResponse({}, content_type="application/json")
        else:
            # Of course, make sure to notify the user that a login is
            # required to post items or change them
            return HttpResponse('Unauthorized', status=401)
Beispiel #4
0
def on_login(sender, user, **kwargs):
    """
	Executed when a user has just logged in
	"""

    #update notifications pertaining to items
    Item.update_notifications(user)
Beispiel #5
0
def on_login(sender, user, **kwargs):
	"""
	Executed when a user has just logged in
	"""
	
	#update notifications pertaining to items
	Item.update_notifications(user)
Beispiel #6
0
def item_form(request, id=None):
    if id:
        item = get_object_or_404(Item, id=id)
        scenario = 'Update'
    else:
        item = Item()
        scenario = 'Create'
    if request.POST:
        form = ItemForm(data=request.POST, instance=item, user=request.user)
        if form.is_valid():
            item = form.save(commit=False)
            item.save(account_no=form.cleaned_data['account_no'],
                      opening_balance=form.cleaned_data['opening_balance'])
            if request.is_ajax():
                return render(request, 'callback.html',
                              {'obj': ItemSerializer(item).data})
            return redirect('/inventory/items/')
    else:
        form = ItemForm(instance=item, user=request.user)
    if request.is_ajax():
        base_template = 'modal.html'
    else:
        base_template = 'inventory_base.html'
    return render(request, 'item_form.html', {
        'scenario': scenario,
        'form': form,
        'base_template': base_template,
    })
Beispiel #7
0
def update_user_notifications():
    """
	Cycles through all active users and updates their notifications
	"""
    userset = User.objects.filter(is_active=True)

    for user in userset:
        Item.update_notifications(user)
Beispiel #8
0
def update_user_notifications():
	"""
	Cycles through all active users and updates their notifications
	"""
	userset = User.objects.filter(is_active=True)
	
	for user in userset:
		Item.update_notifications(user)
	def post(self):
		data = request.get_json()

		item = Item(name=data['name'], category=data['category'], price=data['price'], updated_on=datetime.now())

		item.save()

		return jsonify(pretty(item))
Beispiel #10
0
def edit(id=None):
    setExits()
    #import pdb;pdb.set_trace()

    transaction = Transaction(g.db)

    if request.form:
        id = request.form.get('id', None)
    id = cleanRecordID(id)
    items = Item(g.db).select()
    current_item = None

    if id < 0:
        flash("Invalid Record ID")
        return redirect(g.listURL)

    if id >= 0 and not request.form:
        if id == 0:
            rec = transaction.new()
            rec.created = local_datetime_now()
            if 'last_trx' in session:
                transaction.update(rec, session['last_trx'])
        else:
            rec = transaction.get(id)

        if not rec:
            flash('Record not Found')
            return redirect(g.listURL)
        else:
            #Get the item if there is one
            if rec.item_id != 0:
                current_item = Item(g.db).get(rec.item_id)

    elif request.form:
        current_item = Item(g.db).get(
            cleanRecordID(request.form.get('item_id', "0")))
        if id == 0:
            rec = transaction.new()
        else:
            rec = transaction.get(id)
            if not rec:
                flash('Record not found when trying to save')
                return redirect(g.listURL)

        transaction.update(rec, request.form)
        error_list = []
        if save_record(rec, error_list):
            return redirect(g.listURL)
        else:
            for err in error_list:
                flash(err)
        return redirect(g.listURL)

    return render_template('trx_edit.html',
                           rec=rec,
                           current_item=current_item,
                           items=items)
    def setUp(self):
        self.path = os.path.join(os.getcwd(), 'assignment_table_load.xls')
        self.sheet = 2
        self.mercent = Merchant(merchant_id='001',merchant_name="test merchant", merchant_address="address")
        self.mercent.save()
        self.test_item = Item(item_id="0001",merchant_id="0002",item_name="one Item", item_price=200,merchant_obj=self.mercent)
        self.test_item.save()
        self.new_item = Item(item_id="0002",merchant_id="0002",item_name="one Item new", item_price=200,merchant_obj=self.mercent)
        self.new_item.save()

        self.cart = Cart(customer="test Customer")
        self.cart.save()
Beispiel #12
0
def stock_on_hand(id=None):
    """Return the stock count for the item.id else something else"""
    rec = Item(g.db).get(cleanRecordID(id))
    if rec:
        soh = Item(g.db).stock_on_hand(cleanRecordID(id))
        if soh > 0:
            if soh >= cleanRecordID(rec.min_stock):
                return soh
            else:
                return "{} Min ({})".format(soh, rec.min_stock)

        return "- out of stock -"
def load_item(csv_file, sheet):
    book = xlrd.open_workbook(csv_file) # Open an .xls file
    sheet = book.sheet_by_index(sheet) # Get the first sheet
    for counter in range(21): # Loop for five times
        if counter:
            # grab the current row
            rows = sheet.row_values(counter)
            item = Item(item_id=rows[0], merchant_id=rows[1], item_name=rows[2], item_price=rows[3],
                        merchant_obj=Merchant.objects.get(merchant_id=rows[1]))
            item.save()

    return True
Beispiel #14
0
 def setUp(self):
     self.supplier = Location.objects.filter(location_type="S")[0]
     clinics = Location.objects.filter(location_type="C")
     self.clinic = clinics[0]
     self.clinic_b = clinics[1]
     self.user = User.objects.all()[0]
     d = Item(name="Test item",user=self.user)
     d.save()
     s = Shipment(active=True,from_location=self.supplier,to_location=self.clinic,name="test supplier id",shipment_type="R",user=self.user)
     s.save()
     self.item = Item.objects.all()[0]
     self.shipment = Shipment.objects.all()[0]
     self.base_itemlot = {'active' : True, 'qty' : 23, 'item' : self.item.id, 'shipment' : self.shipment.id, 'user' : self.user.id, 'expiration' : '01/09/14', 'lot_num' : "test lot 213", 'unit_price' : 12.3}
    def mutate(root, info, input=None):
        ok = True

        user = User.objects.get(pk=input.user.id)
        item_instance = Item(name=input.name,
                             user=user,
                             category=input.category,
                             quantity=input.quantity,
                             purchase_date=input.purchase_date,
                             expiry_date=input.expiry_date,
                             perishable=input.perishable)
        item_instance.save()
        return CreateItem(ok=ok, item=item_instance)
Beispiel #16
0
class TransactionTest(TestCase):
    def setUp(self):
        self.shift = Shift(begin_date=timezone.now())
        self.shift.save()
        self.transaction = self.shift.create_transaction()
        self.transaction.save()
        self.vendor = Vendor(name='Brand X')
        self.vendor.save()
        self.item = Item(\
            upc='12345',\
            name='Product X',\
            vendor=self.vendor,\
            price=23.45,\
            taxable=True\
        )
        self.item.save()

    def test_end_transaction(self):
        self.transaction.end_transaction()
        self.assertIsNotNone(self.transaction.finish_date)

    def test_cannot_end_ended_transaction(self):
        self.transaction.end_transaction()
        finish_date = self.transaction.finish_date
        self.transaction.end_transaction()
        self.assertEqual(self.transaction.finish_date, finish_date)

    def test_create_line_item(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        self.assertIsNotNone(line_item)

    def test_cannot_create_line_item_on_ended_transaction(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        self.transaction.end_transaction()
        line_item = self.transaction.create_line_item(self.item, 1)
        self.assertIsNone(line_item)

    def test_line_item_description(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        self.assertEqual(line_item.description, 'Brand X Product X')

    def test_get_totals(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        line_item.save()
        line_item = self.transaction.create_line_item(self.item, 1)
        line_item.save()
        transaction_total = self.transaction.get_totals()
        self.assertEqual(transaction_total.sub_total, Decimal('46.90'))
        self.assertEqual(transaction_total.tax_total, Decimal('3.28'))
        self.assertEqual(transaction_total.total, Decimal('50.18'))
Beispiel #17
0
 def setUp(self):
     self.shift = Shift(begin_date=timezone.now())
     self.shift.save()
     self.transaction = self.shift.create_transaction()
     self.transaction.save()
     self.vendor = Vendor(name='Brand X')
     self.vendor.save()
     self.item = Item(\
         upc='12345',\
         name='Product X',\
         vendor=self.vendor,\
         price=23.45,\
         taxable=True\
     )
     self.item.save()
Beispiel #18
0
class TransactionTest(TestCase):
    def setUp(self):
        self.shift = Shift(begin_date=timezone.now())
        self.shift.save()
        self.transaction = self.shift.create_transaction()
        self.transaction.save()
        self.vendor = Vendor(name='Brand X')
        self.vendor.save()
        self.item = Item(\
            upc='12345',\
            name='Product X',\
            vendor=self.vendor,\
            price=23.45,\
            taxable=True\
        )
        self.item.save()
    def test_end_transaction(self):
        self.transaction.end_transaction()
        self.assertIsNotNone(self.transaction.finish_date)
    def test_cannot_end_ended_transaction(self):
        self.transaction.end_transaction()
        finish_date = self.transaction.finish_date
        self.transaction.end_transaction()
        self.assertEqual(self.transaction.finish_date, finish_date)
    def test_create_line_item(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        self.assertIsNotNone(line_item)
    def test_cannot_create_line_item_on_ended_transaction(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        self.transaction.end_transaction()
        line_item = self.transaction.create_line_item(self.item, 1)
        self.assertIsNone(line_item)
    def test_line_item_description(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        self.assertEqual(line_item.description, 'Brand X Product X')
    def test_get_totals(self):
        line_item = self.transaction.create_line_item(self.item, 1)
        line_item.save()
        line_item = self.transaction.create_line_item(self.item, 1)
        line_item.save()
        transaction_total = self.transaction.get_totals()
        self.assertEqual(transaction_total.sub_total, Decimal('46.90'))
        self.assertEqual(transaction_total.tax_total, Decimal('3.28'))
        self.assertEqual(transaction_total.total, Decimal('50.18'))
    def test_paid_tender_ends_transaction(self):
        self.transaction.create_line_item(self.item, 1)
        self.transaction.create_tender(25.09, 'CASH')
        self.assertIsNotNone(self.transaction.finish_date)
Beispiel #19
0
 def setUp(self):
     self.supplier = Location.objects.filter(location_type="S")[0]
     clinics = Location.objects.filter(location_type="C")
     self.clinic = clinics[0]
     self.clinic_b = clinics[1]
     self.user = User.objects.all()[0]
     d = Item(name="Test item",user=self.user)
     d.save()
     s = Shipment(active=True,from_location=self.supplier,to_location=self.clinic,name="test supplier id",shipment_type="R",user=self.user)
     s.save()
     self.item = Item.objects.all()[0]
     self.shipment = Shipment.objects.all()[0]
     self.baseitem_lot = controller.update_itemlot({'active' : True, 'qty' : 23, 'item' : self.item.id, 'shipment' : self.shipment.id, 'user' : self.user.id, 'expiration' : '01/09/14', 'lot_num' : "test lot 213", 'unit_price' : 12.3})['itemlot']
     self.base_stockchange = {'active' : True, 'qty' : 50, 'date' : '16/07/13', 'change_type' : 'M', 'user' : self.user.id, 'location' : self.clinic.id, 'itemlot' : self.baseitem_lot, 'note' : "test note", 'shipment' : ""}
     self.base_stockchange_dispense = {'active' : True, 'qty' : -50, 'date' : '16/07/13', 'change_type' : 'D', 'user' : self.user.id, 'location' : self.clinic.id, 'itemlot' : self.baseitem_lot, 'note' : "test note", 'shipment' : ""}
     self.base_stockchange_transfer = {'active' : True, 'qty' : 50, 'date' : '16/07/13', 'change_type' : 'T', 'user' : self.user.id, 'location' : self.clinic.id, 'itemlot' : self.baseitem_lot, 'note' : "test note", 'shipment' : self.shipment.id}
Beispiel #20
0
def display():
    setExits()

    recs = Transfer(g.db).select()

    #Get categories to display
    items = Item(g.db)
    item = {}
    #import pdb;pdb.set_trace()

    if recs:
        for rec in recs:
            fnd = items.get(rec.item_id)
            if fnd:
                item[rec.item_id] = fnd.name

    return render_template('transfer_list.html', recs=recs, item=item)
Beispiel #21
0
def delete_item(user, item_id):
	"""
	Attempts to delete the item with the specified id, provided that the provided
	user is its owner
	"""
	item = Item.retrieve_with_write_permission(user, item_id)
	
	item.delete()
Beispiel #22
0
def newitem(request):
    formdata = Item(dateadded=datetime.date.today().isoformat(), quantity=1)
    form = NewItemForm(request.POST or None, instance=formdata)
    if form.is_valid():
        cmodel = form.save()
        cmodel.save()
        return redirect(index)
    return render_to_response('inventory/newitem.html', {'item_form': form},
                              context_instance=RequestContext(request))
Beispiel #23
0
def init_db():
    # Set up test data for now
    from inventory.models import Item, Inventory, ItemInventoryMap
    print("Iniatlizing Database")
    Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    dagger = Item(name='dagger')
    db_session.add(dagger)
    rapier = Item(name='rapier')
    db_session.add(rapier)
    db_session.commit()

    group_inventory = Inventory(name="Group")
    has_5_daggers = ItemInventoryMap(item=dagger, quantity=5)
    group_inventory.items.append(has_5_daggers)
    db_session.add(group_inventory)
    db_session.commit()
Beispiel #24
0
def move_item(user, item_id, location_id):
	"""
	Attempts to move an item with the specified id to a location with the
	specified id.
	"""
	item = Item.retrieve_with_write_permission(user, item_id)
	location = Location.retrieve_with_write_permission(user, location_id)
	
	item.location = location
	item.save()
Beispiel #25
0
def addBooks(request):
    try:
        if (request.method == 'POST'):
            title = request.POST['title']
            amount = request.POST['amount']
            barcode = request.POST['barcode']
            description = request.POST['description']

            item = Item(title=title,
                        amount=amount,
                        barcode=barcode,
                        description=description)
            item.save()
    except:
        raise Http404("All fields are requiered")

        return redirect("/")
    else:
        return render(request, 'addBooks.html')
Beispiel #26
0
def delete(id=None):
    setExits()
    if id == None:
        id = request.form.get('id', request.args.get('id', -1))

    id = cleanRecordID(id)
    if id <= 0:
        flash("That is not a valid record ID")
        return redirect(g.listURL)

    rec = Item(g.db).get(id)
    if not rec:
        flash("Record not found")
    else:
        Item(g.db).delete(rec.id)
        g.db.commit()
        flash("Record Deleted")

    return redirect(g.listURL)
class LoadTestCase(TestCase):
    def setUp(self):
        self.path = os.path.join(os.getcwd(), 'assignment_table_load.xls')
        self.sheet = 2
        self.mercent = Merchant(merchant_id='001',merchant_name="test merchant", merchant_address="address")
        self.mercent.save()
        self.test_item = Item(item_id="0001",merchant_id="0002",item_name="one Item", item_price=200,merchant_obj=self.mercent)
        self.test_item.save()
        self.new_item = Item(item_id="0002",merchant_id="0002",item_name="one Item new", item_price=200,merchant_obj=self.mercent)
        self.new_item.save()

        self.cart = Cart(customer="test Customer")
        self.cart.save()

    def test_data_found(self):
        """Data found according to search"""
        merchant = load_merchant(self.path, 3)
        item = load_item(self.path, 2)
        transaction = load_transaction(self.path, 0)
        sales = load_sales(self.path, 1)
        assert merchant
        assert item
        assert transaction
        assert sales

    def test_cart_create(self):

        row1 = Rows(sn=1,item=self.test_item,quantity=2.5, unit='piece', cart = self.cart)
        row2 = Rows(sn=2,item=self.test_item,quantity=3.5, unit='piece', cart = self.cart)
        row3 = Rows(sn=3,item=self.test_item,quantity=42.5, unit='piece', cart = self.cart)
        row1.save()
        row2.save()
        row3.save()

        assert self.cart.rows.all()
        assert self.cart.status

        name = self.cart.item_update(1, self.test_item, self.new_item)
        assert name == self.new_item.item_name

        self.cart.cancel()
        assert not self.cart.status
Beispiel #28
0
class LineItemTest(TestCase):
    def setUp(self):
        self.shift = Shift(begin_date=timezone.now())
        self.shift.save()
        self.transaction = self.shift.create_transaction()
        self.transaction.save()
        self.vendor = Vendor(name='Brand X')
        self.vendor.save()
        self.item = Item(\
            upc='12345',\
            name='Product X',\
            vendor=self.vendor,\
            price=23.45,\
            taxable=True\
        )
        self.item.save()
    def test_line_item_total(self):
        line_item = self.transaction.create_line_item(self.item, 2)
        line_item.save()
        self.assertEqual(line_item.total(), Decimal(46.90))
Beispiel #29
0
 def post(self, request):
     if request.POST['id']:
         item = Item.objects.get(id=request.POST["id"])
     else:
         item = Item()
     item.name = request.POST["name"]
     item.description = request.POST["description"]
     item.company = request.user.company
     item.save()
     return JsonRepsonse({"Upload": True, "id":item.id})
Beispiel #30
0
def cancel(id=None):
    """If user canceled a new record come here to delete the record stub"""
    setExits()

    if id:
        try:
            Item(g.db).delete(id)
            g.db.commit()
        except:
            flash("Could not delete temporary Item with id = {}".format(id))

    return redirect(g.listURL)
Beispiel #31
0
class LineItemTest(TestCase):
    def setUp(self):
        self.shift = Shift(begin_date=timezone.now())
        self.shift.save()
        self.transaction = self.shift.create_transaction()
        self.transaction.save()
        self.vendor = Vendor(name='Brand X')
        self.vendor.save()
        self.item = Item(\
            upc='12345',\
            name='Product X',\
            vendor=self.vendor,\
            price=23.45,\
            taxable=True\
        )
        self.item.save()

    def test_line_item_total(self):
        line_item = self.transaction.create_line_item(self.item, 2)
        line_item.save()
        self.assertEqual(line_item.total(), Decimal(46.90))
Beispiel #32
0
def add_item(request):
    form = forms.AddItem()
    if request.method == 'POST':
        form = forms.AddItem(request.POST)
        if form.is_valid():
            item = Item()
            item.title = form.cleaned_data['Item_Name']
            item.serial_number = form.cleaned_data['Serial_Number']
            item.amount = form.cleaned_data['Cost']
            item.description = form.cleaned_data['Item_Description']
            item.save()
            messages.add_message(request, messages.SUCCESS,
                                 "Item Added Successful")
            return HttpResponseRedirect(reverse('inventory:landing'))
    return render(request, 'inventory/add_item.html', {'form': form})
Beispiel #33
0
def edit_from_list(id=None, item_id=None):
    """Handle creation of transaction from the Item record form"""
    setExits()
    #import pdb;pdb.set_trace()

    item_id = cleanRecordID(item_id)
    item_rec = None
    rec = None
    warehouses = Warehouse(g.db).select()
    trx_types = get_site_config().get('trx_types', [
        'Add',
        'Remove',
    ])
    transaction = Transaction(g.db)
    trx_id = cleanRecordID(id)
    if trx_id > 0:
        rec = transaction.get(trx_id)

    if rec:
        item_id = rec.item_id
    else:
        rec = transaction.new()
        rec.created = local_datetime_now()
        if 'last_trx' in session:
            transaction.update(rec, session['last_trx'])

    # Handle Response?
    if request.form:
        #import pdb;pdb.set_trace()
        error_list = []
        transaction.update(rec, request.form)
        if save_record(rec, error_list):
            return "success"  # the success function looks for this...
        else:
            pass

    if item_id > 0:
        item_rec = Item(g.db).get(item_id)

    if not item_rec:
        flash("This is not a valid item id")
        return "failure: This is not a valid item id."
    else:
        rec.item_id = item_id

    return render_template('trx_edit_from_list.html',
                           rec=rec,
                           current_item=item_rec,
                           warehouses=warehouses,
                           trx_types=trx_types)
Beispiel #34
0
def get_warehouse_dropdown(item_id=0):
    """Return a list of dicts to be used in the transfer drop downs for warehouses"""

    out = []
    recs = Warehouse(g.db).select()
    if recs:
        for rec in recs:
            out.append(rec._asdict())
            qoh = 0
            if item_id:
                qoh = Item(g.db).stock_on_hand(item_id, warehouse_id=rec.id)

            out[len(out) - 1].update({'qoh': qoh})

    return out
Beispiel #35
0
def create_item(user, location_id, type_id, printed_expiration_date):
	"""
	Attempts to create a new item.
	"""
	
	location = Location.retrieve_with_write_permission(user, location_id)
	item_type = ItemType.retrieve_with_write_permission(user, type_id)
	
	
	#create the item
	try:
		new_item = Item(
			user=user,
			location=location,
			item_type=item_type,
			printed_expiration_date=printed_expiration_date,
		)
		new_item.save()
	except django.core.exceptions.ValidationError:
		raise inventory.exceptions.InvalidDateError(printed_expiration_date)
	except:
		raise inventory.exceptions.ItemCreateError
	
	return new_item
Beispiel #36
0
def open_item(user, item_id, open_date):
	"""
	Attempts to open the provided item, provided that it is not already open.
	"""
	item = Item.retrieve_with_write_permission(user, item_id)
	
	#if already opened, do nothing
	if item.opened:
		return
	
	try:
		item.opened_date = open_date
		item.save()
	except django.core.exceptions.ValidationError:
		raise inventory.exceptions.InvalidDateError(open_date)
Beispiel #37
0
 def setUp(self):
     self.shift = Shift(begin_date=timezone.now())
     self.shift.save()
     self.transaction = self.shift.create_transaction()
     self.transaction.save()
     self.vendor = Vendor(name='Brand X')
     self.vendor.save()
     self.item = Item(\
         upc='12345',\
         name='Product X',\
         vendor=self.vendor,\
         price=23.45,\
         taxable=True\
     )
     self.item.save()
def add_item(request, barcode_id):

    lot_number = request.POST.get('lot_number')
    cost = request.POST.get('cost')
    expiration_date_str = str(request.POST.get('expiration_date'))

    if expiration_date_str == '':

        expiration_date_str = '2016-4-{days}'.format(
            days=DEFAULT_EXPIRATION
        )

    expiration_date = datetime.strptime(expiration_date_str, '%Y-%m-%d')

    location_room = request.POST.get('location_room')
    location_unit = request.POST.get('location_unit')
    location_shelf = request.POST.get('location_shelf')


    product = Product.objects.get(barcode_id__exact=barcode_id)

    item = Item(
        product=product,
        lot_number=lot_number,
        cost=cost,
        expiration_date=expiration_date,
        location_room=location_room,
        location_unit=location_unit,
        location_shelf=location_shelf,
    )

    item.save()

    item_id = item.id

    return redirect('view_item', barcode_id=barcode_id, item_id=item_id)
Beispiel #39
0
def import_data(filespec):
    db = Database('instance/database.sqlite').connect()
    category = Category(db)
    uom = Uom(db)
    item = Item(db)
    trx = Transaction(db)

    with open(filespec, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print('Name: {}, Category: {}'.format(row['item_name'],
                                                  row['category_name']))
            #import pdb;pdb.set_trace()
            #create a Category if not exists
            cats = category.select_one(
                where='name = "{}"'.format(row['category_name']))
            if not cats:
                cats = category.new()
                cats.name = row["category_name"]
                category.save(cats)
            cat_id = cats.id
            #create UOM if not exists
            uom_name = row['uom'].strip()
            if uom_name == '':
                uom_name = "Ea."

            uoms = uom.select_one(where='name = "{}"'.format(uom_name))
            if not uoms:
                uoms = uom.new()
                uoms.name = uom_name
                uom.save(uoms)

            items = item.select_one(
                where='name = "{}"'.format(row['item_name'], ))
            if not items:
                items = item.new()
                items.name = row['item_name']
                items.uom = uom_name
                items.cat_id = cat_id
                item.save(items)

            # Create a transaction record
            trxs = trx.new()
            trx.update(trxs, row)
            trxs.created = datetime.strptime(row['created'], '%Y-%m-%d')
            trxs.item_id = items.id
            trx.save(trxs)

        try:
            db.commit()
        except Exception as e:
            db.rollback()
            print(str(e))
Beispiel #40
0
def get_qoh_by_warehouse(id):
    """Return a list of namedlist with quantity on hand in each warehouse for the item id"""

    recs = []
    id = cleanRecordID(id)
    if id > 0:
        sql = """select COALESCE(sum(trx.qty), 0) as qty, warehouse.name 
        from warehouse 
        join item on item.id = trx.item_id 
        left join trx on trx.warehouse_id = warehouse.id 
        where item.id = {id}  
        group by warehouse_id,item.id 
        order by lower(warehouse.name)""".format(id=id)

        recs = Item(g.db).query(sql)

    else:
        flash("Invalid item ID")

    return recs
Beispiel #41
0
def addItem(request, cat_id):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            newItem = Item()
            newItem.name = cd.get('name')
            newItem.description = cd.get('description')
            newItem.quantity = cd.get('quantity')
            currentCat = request.POST.get("category")
            newItem.category = get_object_or_404(Category, id=currentCat)
            newItem.save()
            items = Item.objects.all().filter(category=currentCat)
            context = {
                'items': items,
            }
            if request.is_ajax():
                return render_to_response(
                    'inventory/getList.html',
                    context,
                    context_instance=RequestContext(request))
            else:
                return HttpResponseRedirect(
                    reverse('inventory:list', args=(cat_id, )))

    message = "Oops, it broke! You should enter in something valid."
    form = CategoryForm()
    categories = Category.objects.all()
    context = {
        'message': message,
        'form': form,
        'categories': categories,
    }
    return render_to_response('inventory/index.html',
                              context,
                              context_instance=RequestContext(request))
Beispiel #42
0
def addItem(request, cat_id):
	if request.method == 'POST':
		form = ItemForm(request.POST)
		if form.is_valid():
			cd = form.cleaned_data
			newItem = Item()
			newItem.name = cd.get('name')
			newItem.description = cd.get('description')
			newItem.quantity = cd.get('quantity')
			currentCat = request.POST.get("category")
			newItem.category = get_object_or_404(Category, id=currentCat)  
			newItem.save()
			items = Item.objects.all().filter(category=currentCat)
			context = {'items': items,}
			if request.is_ajax():
				return render_to_response('inventory/getList.html', context, context_instance=RequestContext(request))
			else:			
				return HttpResponseRedirect(reverse('inventory:list', args=(cat_id,)))

	message = "Oops, it broke! You should enter in something valid."
	form = CategoryForm()
	categories = Category.objects.all()
	context = {'message': message, 'form': form, 'categories': categories, }
	return render_to_response('inventory/index.html', context, context_instance=RequestContext(request))
from inventory.models import Item, Product
import random


number = 10


for i in range(int(number)):

    p = Product()

    p.barcode_id = i * 100
    p.name = 'Product #{i}00'.format(i=i)
    p.description = 'foo'
    p.notes = 'foooooo'
    p.save()

    for j in range(int(number)):

        item = Item()

        item.product = p
        item.cost = random.randrange(2, 100)
        item.save()
Beispiel #44
0
def lifo_cost(id=None):
    """Return the LIFO cost as a string for item """
    cost = Item(g.db).lifo_cost(cleanRecordID(id))
    return str(cost)
Beispiel #45
0
def get_stock_on_hand(item_id=0):
    return str(Item(g.db).stock_on_hand(cleanRecordID(item_id)))