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 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 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)
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))
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))
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()
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)
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})
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))
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)
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)
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)
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
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})
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 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)
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')
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
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))
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
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)
def setUp(self): self.vendor = Vendor(name='Brand X') self.item = Item(upc='12345', name='Product X', vendor=self.vendor)
def save_record(rec): """Attempt to validate and save a record""" #import pdb;pdb.set_trace() transfer = Transfer(g.db) trx_table = Transaction(g.db) transfer.update(rec, request.form) if validate_form(rec): if rec.id: ## delete the current transfer record. trx_table.delete(cleanRecordID(rec.out_trx_id)) trx_table.delete(cleanRecordID(rec.in_trx_id)) ## related transfer record is deleted by cascade transfer.delete(cleanRecordID(rec.id)) g.db.commit() # trigger the casscade delete of transactions rec = transfer.new() transfer.update(rec, request.form) transfer.save(rec) #Create trx recods for this transfer... #create the Outgoing trx record trx_rec = trx_table.new() trx_rec.item_id = rec.item_id trx_rec.qty = abs(rec.qty) * -1 trx_rec.created = rec.transfer_date trx_rec.warehouse_id = request.form["warehouse_out_id"] trx_rec.value = 0 trx_rec.trx_type = "Transfer Out" trx_table.save(trx_rec) rec.out_trx_id = trx_rec.id trx_rec2 = trx_table.new() trx_table.update(trx_rec2, trx_rec._asdict()) trx_rec2.qty = abs(rec.qty) trx_rec2.value = Item(g.db).lifo_cost(trx_rec.item_id, end_date=rec.transfer_date) trx_rec2.warehouse_id = request.form["warehouse_in_id"] trx_rec2.trx_type = "Transfer In" trx_table.save(trx_rec2) rec.in_trx_id = trx_rec2.id transfer.save(rec) #Save some data to session session['last_transfer'] = { "transfer_date": rec.transfer_date, } try: g.db.commit() #Save the date and comment to session return True except Exception as e: flash( printException('Error attempting to save Transfer record', str(e))) g.db.rollback() return False
def get_stock_on_hand(item_id=0): return str(Item(g.db).stock_on_hand(cleanRecordID(item_id)))
def edit(id=None): setExits() g.title = "Edit {} Record".format(g.title) item = Item(g.db) transactionList = None #import pdb;pdb.set_trace() if request.form: id = request.form.get('id', None) id = cleanRecordID(id) if id < 0: flash("Invalid Record ID") return redirect(g.listURL) categories = Category(g.db).select() uoms = Uom(g.db).select() if id >= 0 and not request.form: if id == 0: rec = item.new() # allow creation of new properties item.save(rec) # need an id for transactions g.db.commit() # have to commit this to protect the ID we just got # This name changes behavure of the Cancel link in the edit form g.cancelURL = url_for('.cancel') + "{}/".format(rec.id) else: rec = item.get(id) if not rec: flash('Record not Found') return redirect(g.listURL) #import pdb;pdb.set_trace() if request.form: rec = item.get(id) if rec: item.update(rec, request.form) if validate_form(): item.save(rec) try: g.db.commit() return redirect(g.listURL) except Exception as e: g.db.rollback() flash( printException('Error attempting to save Item record', str(e))) return redirect(g.listURL) else: pass # There are imput errors else: flash('Record not Found') return redirect(g.listURL) transactionList = get_trx_list_for_item(rec.id) transferList = get_transfer_list_for_item(rec.id) qoh_list = get_qoh_by_warehouse(rec.id) on_hand = item.stock_on_hand(id) return render_template('item_edit.html', rec=rec, categories=categories, uoms=uoms, transactionList=transactionList, transferList=transferList, qoh_list=qoh_list, on_hand=on_hand)
def validate_form(rec): valid_form = True #Try to coerse qty to a number if request.form['qty'].strip() == '': flash('Quantity is required') valid_form = False else: try: rec.qty = float(rec.qty) if rec.qty <= 0: flash('Quantity must be greater than 0') valid_form = False #truncate qty if int elif rec.qty - int(rec.qty) == 0: rec.qty = int(rec.qty) except ValueError as e: flash('Quantity must be a number') valid_form = False # Must be attached to an item itemID = cleanRecordID(request.form.get('item_id', 0)) if itemID <= 0: flash("You must select an item to use with this transfer") valid_form = False #Must not be more than stock on hand elif rec.qty and type(rec.qty) != str: QOH = Item(g.db).stock_on_hand( itemID, warehouse_id=request.form.get("warehouse_out_id")) if rec.qty > QOH: flash("You may not transfer more than the quantity on hand ({})". format(QOH)) valid_form = False if not Warehouse(g.db).get( cleanRecordID(request.form.get('warehouse_out_id'))): flash("You must select a transfer out warehouse") valid_form = False if not Warehouse(g.db).get( cleanRecordID(request.form.get('warehouse_in_id'))): flash("You must select a transfer in warehouse") valid_form = False # test for valid date test_date = rec.transfer_date if isinstance(test_date, str): test_date = getDatetimeFromString(rec.transfer_date) if not test_date: flash("There must be transfer date") valid_form = False else: rec.transfer_date = test_date if test_date > local_datetime_now(): flash("Transfer date may not be in the future") valid_form = False return valid_form
def edit_from_list(id=None, item_id=None): """Handle creation of transfer from the Item record form It's not practical to edit existing transfers, so delete the offending transfer record then recreate it instead. """ setExits() #import pdb;pdb.set_trace() rec = None item_rec = None tran_id = cleanRecordID(id) item_id = cleanRecordID(item_id) transfer = Transfer(g.db) if tran_id > 0: sql = get_transfer_select(where="transfer.id = {}".format(tran_id)) rec = transfer.query(sql) if rec: rec = rec[0] item_id = rec.item_id # warehouse_in_id = rec.warehouse_in_id # warehouse_out_id = rec.warehouse_out_id else: rec = transfer.new() rec.transfer_date = local_datetime_now() if 'last_transfer' in session: transfer.update(rec, session['last_transfer']) if item_id > 0: item_rec = Item(g.db).get(item_id) if item_rec: rec.item_id = item_id else: flash("This is not a valid item id") return "failure: This is not a valid item id." warehouses = get_warehouse_dropdown(item_id) warehouse_in_id = cleanRecordID( request.form.get('warehouse_in_id', rec._asdict().get('warehouse_in_id', 0))) warehouse_out_id = cleanRecordID( request.form.get('warehouse_out_id', rec._asdict().get('warehouse_out_id', 0))) # Handle Response? if request.form: #import pdb;pdb.set_trace() if save_record(rec): return "success" # the success function looks for this... else: pass return render_template( 'transfer_edit_from_list.html', rec=rec, warehouses=warehouses, item=item_rec, warehouse_in_id=warehouse_in_id, warehouse_out_id=warehouse_out_id, )
def addItem(name, count, itemtype): for i in range(count): i = Item() i.itemType = itemtype i.itemName = name i.save()
def create(self, validated_data): item = Item(**validated_data) item.save() return item