Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from django.views.generic import CreateView, ListView, UpdateView, DeleteView
from django.shortcuts import redirect, render
from django.http import JsonResponse
from .forms import ProductForm
from .models import Product
from helper.views import get_user_franchise, user_is_employee
from django.shortcuts import HttpResponse, get_object_or_404
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import permission_required
from django.utils.timezone import datetime
from django.contrib.auth.decorators import login_required
class ProductList(ListView):
template_name = "product/product_list.html"
model = Product
context_object_name = "products"
def get_queryset(self):
if user_is_employee(self.request):
return Product.objects.filter(franchise=get_user_franchise(self.request))
else:
return Product.objects.filter(franchise__user=self.request.user)
class ProductCreate(CreateView):
model = Product
form_class = ProductForm
success_url = '/product/'
def form_valid(self, form):
form.instance.user = self.request.user
form.instance.franchise_id = get_user_franchise(self.request)
return super(ProductCreate, self).form_valid(form)
class ProductUpdate(UpdateView):
model = Product
success_url = '/product/'
form_class = ProductForm
def form_valid(self, form):
form.instance.user = self.request.user
form.instance.franchise_id = get_user_franchise(self.request)
return super(ProductUpdate, self).form_valid(form)
class ProductDelete(DeleteView):
model = Product
success_url = '/product/'
def search_product(request, product):
product = Product.objects.get(
bar_code=product,
franchise=get_user_franchise(request),
expire_date__gt=datetime.today()
)
if not product:
context = {'status': 404 }
return JsonResponse(context)
else:
context = {
'id': product.id,
'name': product.name,
'price': product.sale_price
}
return JsonResponse(context)
def decrement_product_in_stock(product_id,product_quantity):
product = Product.objects.get(pk=product_id)
product.in_stock = product.in_stock - int(product_quantity)
if product.in_stock <= 0:
product.delete()
else:
product.save()
return True
def increment_product_in_stock(product_id,product_quantity):
product = Product.objects.get(pk=product_id)
product.in_stock = product.in_stock + int(product_quantity)
product.save()
return True
def expired_products(request):
try:
expired_products = Product.objects.filter(
franchise_id=get_user_franchise(request),
expire_date__lte=datetime.today()
).values('expire_date','name')
context = dict()
context['expired_products'] = expired_products
context['expired_products_count'] = expired_products.count()
return context
except:
return {'expired_products': 0,'expired_products_count': 0}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment