Add stock_amount to product and reflect it in product detail template. (#213)

This commit is contained in:
Víðir Valberg Guðmundsson 2018-04-21 17:00:39 +02:00 committed by Thomas Steen Rasmussen
parent 2eea0acf0e
commit 193c182422
3 changed files with 72 additions and 1 deletions

View file

@ -0,0 +1,34 @@
# Generated by Django 2.0.4 on 2018-04-15 16:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shop', '0053_auto_20180318_0906'),
]
operations = [
migrations.AddField(
model_name='product',
name='stock_amount',
field=models.IntegerField(blank=True, help_text='Initial amount available in stock if there is a limited supply, e.g. fridge space', null=True),
),
migrations.AlterField(
model_name='epaypayment',
name='order',
field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to='shop.Order'),
),
migrations.AlterField(
model_name='invoice',
name='customorder',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='shop.CustomOrder'),
),
migrations.AlterField(
model_name='invoice',
name='order',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='shop.Order'),
),
]

View file

@ -318,6 +318,15 @@ class Product(CreatedUpdatedModel, UUIDModel):
blank=True
)
stock_amount = models.IntegerField(
help_text=(
'Initial amount available in stock if there is a limited '
'supply, e.g. fridge space'
),
null=True,
blank=True
)
objects = ProductQuerySet.as_manager()
def __str__(self):
@ -333,8 +342,17 @@ class Product(CreatedUpdatedModel, UUIDModel):
)
def is_available(self):
""" Is the product available or not?
Checks for the following:
- Whether now is in the self.available_in
- If a stock is defined, that there are items left
"""
now = timezone.now()
return now in self.available_in
time_available = now in self.available_in
stock_available = (self.stock_amount - self.left_in_stock()) > 0
return time_available and stock_available
def is_old(self):
now = timezone.now()
@ -346,6 +364,16 @@ class Product(CreatedUpdatedModel, UUIDModel):
now = timezone.now()
return self.available_in.lower > now
def left_in_stock(self):
sold = OrderProductRelation.objects.filter(
product=self,
order__paid=True,
).aggregate(Sum('quantity'))['quantity__sum']
total_left = self.stock_amount - (sold or 0)
return total_left
class OrderProductRelation(CreatedUpdatedModel):
order = models.ForeignKey('shop.Order', on_delete=models.PROTECT)

View file

@ -25,6 +25,15 @@
<hr />
{% if product.stock_amount %}
<h3>
<small>Availability</small><br />
<bold>{{ product.left_in_stock }}</bold> available<br />
</h3>
<hr />
{% endif %}
<h3>Add to order</h3>
{% if user.is_authenticated %}