I am working on task like this, in a company, they want to sale product called 'computer'.
if enough stock does not exists before the sale date, it should give message for insufficient qty , message.
Also should give information of total available product quantity for sale before that date, and it's valuation.
if company have enough quantity for sale, than it should display message of remaining qty of that product and it's valuation.
e.g.
valuation = quantity * purchase price
my code
import datetime
class Supplier:
def add_supplier(self, name, address, email, contact_no):
"""
Function: Used to add supplier details.
Parameter:name: Supplier Name
address: Supplier address
email: Supplier email
contact_no: Supplier Contact detail
Return: Nothing
"""
self.name = name
self.address = address
self.email = email
self.contact_no = contact_no
class Product:
def add_product(self, name):
"""
Function: To add product in to an inventory.
Parameter: Product name
Return: Nothing
"""
self.name = name
class Company(Supplier, Product):
data_dict = []
def purchase(self, product_obj, qty, price, date=datetime.date.today()):
"""
Function: Used to purchase product.
Parameter: product_obj: Product object.
qty: Product quantity.
price: Product price.
date: Product date.
Return: Nothing
"""
self.data_dict.append({'product': product_obj.name, 'qty': qty, 'price': price, 'date': str(date)})
def sale(self, sale_qty, sale_date):
"""
Function: To sale product from warehouse.
Parameter: sale_qty: Product sell quantity.
sale_date: Product sell date.
Return: Nothing
"""
self.newdict = (sorted(self.data_dict, key=lambda x: x['date']))
assert sale_qty > 0
unit_val = 0
rqilr = 0
rpilr = 0
qty = 0
price = 0
sum_qty = 0
sum_price = 0
#print(newdict) # testing.
for i, row in enumerate(self.newdict):
if row['date'] > sale_date:
print("Sorry, not enough quantity.\nStart the purchase order procedure pls!\n")
qty += row['qty']
price += row['price']
unit_val = price/qty
# we have enough Computers in stock.
if qty >= sale_qty:
break
else: # loop completes normally
for i in self.newdict:
sum_price += i['price']
sum_qty += i['qty']
print("Sorry, not enough qty. Operation cancelled.\nCurrent quantity = {} and valuation = {}".format(sum_qty, sum_price))
# remaining_qty_in_last_row sort name = rqilr
rqilr = qty - sale_qty
rpilr = rqilr * unit_val
self.newdict = [{**row, 'price': rpilr, 'qty': rqilr}] + self.newdict[i + 1:]
#print(self.newdict)
# For current quantity and valuation
for i in self.newdict:
sum_price += i['price']
sum_qty += i['qty']
print("Sold!\n available quantity = {} and valuation = {}".format(sum_qty, sum_price))
C = Company()
PRODUCT_OBJ = Product()
PRODUCT_OBJ.add_product('Computer')
while True:
option = int(input("""1. You want to add stock of the product!"
2. Want to sale product?
"""))
if option == 1:
qty = int(input("Enter the qty of the product.\n"))
price = float(input("Enter the price of the product.\n"))
purchase_date = input("Enter purchase date.\n")
C.purchase(PRODUCT_OBJ, qty, price, purchase_date)
elif option == 2:
qty = int(input("Enter the qty you wanna sale, pal!"))
sale_date = input("Enter sale date.\n")
C.sale(qty, sale_date)
else:
print("Enter only 1 & 2 option.\n")
after executing program I am having menu like in program.
You want to add stock of the product!
Want to sale product?
but output not getting proper output of remaining quantity and valuation.
Any suggestion , how to make it right?
Related
So, I am working on my OOP concepts and knowledge by creating dummy projects. Right now I am creating like an online shopping system where admins can upload different products and users can purchase products.
I am having problems with this specific feature where I want to increment product count.
Product Class:
class Product:
def __init__(self, product_name, description, price, company, product_count):
self.product_name = product_name
self.description = description
self.price = price
self.company = company
self.product_count = product_count
and that is how you create a product:
#CREATE PRODUCT
laptop = Product('Dell Inspiron', 'Dell Inspiron with 8GB ram', 1500, 'DELL', 100)
tv = Product('Sony TV', 'Best Sony TV Ever', 2000, 'Sony', 100)
smartwatch = Product('Fossil 6 Gen Smartwatch', 'Fossil watch with wear OS', 300, 'Fossil',100)
shoes = Product('Running shoes', 'Medium size running shoes', 100, 'Nike',100)
gloves = Product('Rock CLimbing gloves', 'Medium gloves for rock clmbing', 250, 'Timberland',100)
Only Admin can upload products and I am storing them in a dictionary:
Admin Class:
class Admin:
def __init__(self, name):
self.name = name
self.products = {}
self.order = {}
self.total_products = 0
self.orders_recieved = {}
self.order_status = 'Order Recieved'
Logic to add_products:
def add_products(self, product):
if product not in self.products:
self.products[product.product_name] = {
'name':product.product_name,
'description':product.description,
'price': product.price,
'company':product.company,
'count':product.product_count
}
if product not in s.site_products: #I am also storing all products in different dict() ignore this
s.site_products[product.product_name] = {
'name':product.product_name,
'description':product.description,
'price': product.price,
'company':product.company,
'count':product.product_count
}
s.product_total += 1
self.total_products += 1
else:
product.product_count += product.product_count
print('Product already exists')
#This is how you add products:
admin1.add_products(laptop)
admin1.add_products(laptop)
admin1.add_products(tv)
admin1.add_products(smartwatch)
admin2.add_products(shoes)
admin2.add_products(gloves)
Admin has to pass in the product created using Product class in add_Product function(). What I want to do is when an Admin tries to upload the same product twice, only its count changes by adding the previous count and the new one.
But for some reason I am unable to do that I have tried multiple ways but still stuck on it. It is probably something very simple that I am missing out.
Thanks in advance!
Your check for whether a product is already in the dictionary uses the product object rather than its product_name attribute, which is the key you use to add items to the dictionary.
If you change that line, it should work.
Test code:
class Product:
def __init__(self, product_name, description, price, company, product_count):
self.product_name = product_name
self.description = description
self.price = price
self.company = company
self.product_count = product_count
class Admin:
def __init__(self, name):
self.name = name
self.products = {}
self.total_products = 0
def add_products(self, product):
if product.product_name not in self.products:
self.products[product.product_name] = {
'name':product.product_name,
'description':product.description,
'price': product.price,
'company':product.company,
'count':product.product_count
}
self.total_products += 1
else:
self.products[product.product_name]['count'] += product.product_count
print('Product already exists')
a = Admin("foo")
print('try a product')
a.add_products(Product('Dell Inspiron', 'Dell Inspiron with 8GB ram', 1500, 'DELL', 100))
print('try it again')
a.add_products(Product('Dell Inspiron', 'Dell Inspiron with 8GB ram', 1500, 'DELL', 100))
Output:
try a product
try it again
Product already exists
I have deals products and normal products. I have a function for normal products which calculate grand toal is working fine but when I add deal product in the cart it did calculate the grand total but only normal prices not deals prices
get total of one product with quantity
def get_total(self):
price = self.product.price
quantity = self.quantity
total = price*quantity
print(total)
return total
function of get cart total
#property
def get_cart_total(self):
orderitem = self.orderitem_set.all()
total = sum(item.get_total for item in orderitem)
return total
i have two fields in databse
price and deal_price
how i can calculate complete correct cart total?
You need to compute the grand total using deal_price.
Example
I'm not sure if this would work since i haven't seen the complete source but you need something like this
def get_deal_total(self):
price = self.product.deal_price
quantity = self.quantity
total = price*quantity
print(total)
return total
#property
def get_cart_deal_total(self):
orderitem = self.orderitem_set.all()
total = sum(item.get_deal_total for item in orderitem)
return total
I'm a odoo 13 user (not developer).
I'm try to create a custom module for to show product margin percent, in purchase order line.
I've copy module code from default Odoo sale_margin addon, and I've adapt it for my custom module.
In Purchase Order, when I add product, edit qty or product price value, I have error:
margin = ((price - line.price_unit) / price) * 100
ZeroDivisionError: float division by zero
Please, can someone help me to solve this issue?
Below code,
Thanks
from odoo import models, fields, api
import odoo.addons.decimal_precision as dp
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
margin = fields.Float(string='Margin (%)', compute='_product_margin', digits='Product Price', store=True)
sale_price = fields.Float(string='Price', digits='Product Price')
def _compute_margin(self, order_id, product_id, product_uom_id):
sale_price = product_id.lst_price
if product_uom_id != product_id.uom_id:
sale_price = product_id.uom_id._compute_price(sale_price, product_uom_id)
#api.model
def _get_sale_price(self, product, product_uom):
sale_price = product.lst_price
if product_uom != product.uom_id:
sale_price = product.uom_id._compute_price(sale_price, product_uom)
#api.onchange('product_id', 'product_uom')
def product_id_change_margin(self):
if not self.product_id or not self.product_uom:
return
self.sale_price = self._compute_margin(self.order_id, self.product_id, self.product_uom)
#api.model
def create(self, vals):
vals.update(self._prepare_add_missing_fields(vals))
# Calculation of the margin for programmatic creation of a PO line. It is therefore not
# necessary to call product_id_change_margin manually
if 'sale_price' not in vals and ('display_type' not in vals or not vals['display_type']):
order_id = self.env['sale.order'].browse(vals['order_id'])
product_id = self.env['product.product'].browse(vals['product_id'])
product_uom_id = self.env['uom.uom'].browse(vals['product_uom'])
vals['sale_price'] = self._compute_margin(order_id, product_id, product_uom_id)
return super(SaleOrderLine, self).create(vals)
#api.depends('product_id', 'sale_price', 'product_uom', 'price_unit', 'price_subtotal')
def _product_margin(self):
for line in self:
price = line.sale_price
margin = ((price - line.price_unit) / price) * 100
line.margin = margin
I am completing the Python course on CodeAcademy (I am running the code on my computer not CodeAcademy) and wrote this piece of code to add items to a shopping cart. The shopping cart is a dictionary.
class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
my_cart = ShoppingCart("Amy")
my_cart.add_item("Nishiki Modulus", "$400")
print my_cart.items_in_cart
This code works and returns:
Nishiki Modulus added.
{'Nishiki Modulus': '$400'}
But I would like to figure out how to add several items (and prices) at the same time. I have been experimenting with no luck.
I ran
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
for products in product:
if not products in self.items_in_cart:
self.items_in_cart[products] = price
print "added."
else:
print "Product is already in the cart."
my_cart = ShoppingCart("Amy")
my_cart.add_item(["Nishiki Modulus", "Trek 700", "Fuji Sportif"], ["$400", "$450", "$700"])
print my_cart.items_in_cart
As I predicted, the keys are right but not the values. This returns:
added.
added.
added.
{'Trek 700': ['$400', '$450', '$700'], 'Fuji Sportif': ['$400', '$450', '$700'], 'Nishiki Modulus': ['$400', '$450', '$700']}
I'm think something along the lines of:
for products, price in product.items():
but then I can't figure out how to correctly add the list to items_in_cart
Can anyone point me in the right direction? Please let me know if anything is unclear.
You can zip the products and their prices like this
for prod, money in zip(product, price):
if not prod in self.items_in_cart:
self.items_in_cart[prod] = money
print "added."
else:
print "Product is already in the cart."
This will zip the product and price list and give one value at a time from both the lists. So we will get the product and its corresponding price.
Or you can iterate the product list, and get the corresponding value from the price with the index, like this
for index, prod in enumerate(product):
if not prod in self.items_in_cart:
self.items_in_cart[prod] = price[index]
print "added."
else:
print "Product is already in the cart."
You can try with simple-indexed for loop:
def add_item(self, product, price):
"""Add product to the cart."""
for index in range(len(product):
if not product[index] in self.items_in_cart:
self.items_in_cart[product[index]] = price[index]
print "added."
else:
print "Product is already in the cart."
Or use zip:
for products, prices in zip(product, price):
You are setting the value of items_in_cart[product] to price, a list of strings. You should be setting it to one of the strings in price.
Here's the ShoppingCart class fixed:
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
priceIndex = 0
for products in product:
if not products in self.items_in_cart:
self.items_in_cart[products] = price[priceIndex]
print "added."
else:
print "Product is already in the cart."
priceIndex += 1
I would add a new method add_items that calls your original add_item in a loop. This will keep your code cleaner and easier to work with.
class ShoppingCart(object):
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name
def add_item(self, product, price):
"""Add product to the cart."""
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + " added."
else:
print product + " is already in the cart."
def add_items(self, products, prices):
for product, price in zip(products, prices):
self.add_item(product, price)
my_cart = ShoppingCart("Amy")
my_cart.add_items(["Nishiki Modulus", "Trek 700", "Fuji Sportif"], ["$400", "$450", "$700"])
print my_cart.items_in_cart
Consider the following Django model
Customer(models.Model)
name = models.CharField()
Product(models.Model)
name = models.CharField()
Score(models.Model)
points = models.IntegerField()
customer = models.ForeignKey(Customer)
product = models.ForeignKey(Product)
I would like to get a list of all products annotated with:
total score from all customers
score from the current customer only
I was able to get it working for the total score like this:
products = Product.objects.annotate(total_points = Sum('score__points')).all()
but I don't know how to add an annotation with only the current customer score (if the customer has reviewed the product, None otherwise). I want something like this:
cus = Cusomter.objects.get(pk=123)
products = Product.objects.annotate(total_points = Sum('score__points'),\
current_customer_points= (Score.points where customer=cus and product = this).all()
ids = SortedDict()
for p in Product.objects.annotate(total=Sum('score__points')):
ids[p.pk] = p
for score in Score.objects.filter(customer_id=1, product__in=ids.keys()):
ids[score.product_id].customer_score = score
for p in ids.values():
print p.total, '/', p.customer_score.points if hasattr(p, 'customer_score') else '-'