# Path: web/pos/serializers.py
# class OrderSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Order
#         fields = ('id', 'user', 'total_price', 'done', 'last_change')
# 
# class OrderItemSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Order_Item
#         fields = ('id', 'product', 'order', 'price', 'name', 'timestamp')
# 
# Path: web/pos/helper.py
# def get_current_user_order(username):
#     """
#     Gets the order for the current user.
#     """
# 
#     usr = User.objects.get_by_natural_key(username)
#     q = Order.objects.filter(user=usr, done=False)\
#                      .order_by('-last_change')
#     if q.count() >= 1:
#         return q[0]
#     else:
#         return Order.objects.create(user=usr)
# 
# def get_can_negative_stock():
#     """
#     Gets from database if negative stock is allowed. Returns True when allowed.
#     """
# 
#     setting, is_created = Setting.objects.get_or_create(key="negative_stock")
# 
#     if is_created:
#         setting.value = "off"
#         setting.save()
#         return False
# 
#     print(setting.value)
#     if setting.value == "off" or setting.value == "no":
#         return False
#     return True
# 
# def product_list_from_order(order):
#     """
#     Returns a list of Products that appear in an Order
#     """
# 
#     product_list = []
#     order_item_list = Order_Item.objects.filter(order=order)
# 
#     for order_item in order_item_list:
#         product_list.append(order_item.product)
# 
#     return product_list
# 
# Path: web/pos/models.py
# class Product(models.Model):
#     # The different colours, to use as Product.<colour>
#     BLUE = "blue"
#     GREEN = "green"
#     YELLOW = "yellow"
#     ORANGE = "orange"
#     PURPLE = "purple"
#     BLACK = "black"
#     PINK = "pink"
#     CYAN = "cyan"
# 
#     # Colour choices
#     COLOUR_CHOICES = (
#             (BLUE, "Blue"),
#             (GREEN, "Green"),
#             (YELLOW, "Yellow"),
#             (ORANGE, "Orange"),
#             (PURPLE, "Purple"),
#             (BLACK, "Black"),
#             (PINK, "Pink"),
#             (CYAN, "Cyan"),
#     )
# 
#     name = models.CharField(max_length=100,
#                             validators=[validate_product_name])
#     price = models.DecimalField(max_digits=7, decimal_places=2)
#     stock_applies = models.BooleanField()
#     minimum_stock = models.PositiveSmallIntegerField(default=0)
#     stock = models.IntegerField(default=0)
#     code = models.CharField(max_length=50, unique=True, null=True, blank=True)
#     colour = models.CharField(max_length=10,
#                               choices=COLOUR_CHOICES, default="blue")
# 
#     def __str__(self):
#         return self.name
# 
#     def clean(self):
#         validate_product_name(self.name)
#         if self.code == "":
#             self.code = None
# 
#     def save(self, *args, **kwargs):
#         if not self.pk:
#             self.full_clean()
#         return super(Product, self).save(*args, **kwargs)
# 
# class Order_Item(models.Model):
#     product = models.ForeignKey(Product,
#                                 on_delete=models.CASCADE)
#     order = models.ForeignKey(Order, on_delete=models.CASCADE)
#     price = models.DecimalField(max_digits=7, decimal_places=2)
#     name = models.CharField(max_length=100)
#     timestamp = models.DateTimeField(auto_now=True)
# 
# class Order(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL,
#                              on_delete=models.CASCADE)
#     total_price = models.DecimalField(max_digits=10,
#                                       decimal_places=2,
#                                       default=0)
#     done = models.BooleanField(default=False)
#     last_change = models.DateTimeField(auto_now=True)
# 
#     def get_absolute_url(self):
#         return reverse('view_order', args=[self.id])
# 
# class Cash(models.Model):
#     amount = models.DecimalField(max_digits=7,
#                                  decimal_places=2,
#                                  default=0)


import logging
import decimal
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.http import (HttpResponse,
                         JsonResponse,
                         HttpResponseBadRequest)
from rest_framework import status
from .serializers import OrderSerializer, OrderItemSerializer
from .helper import (get_current_user_order,
                     get_can_negative_stock,
                     product_list_from_order)
from .models import Product, Order_Item, Order, Cash
@csrf_exempt
def current_order_item(request, item_id):
    if not request.user.is_authenticated:
        return HttpResponse(status=status.HTTP_401_UNAUTHORIZED)

    order = get_current_user_order(request.user.username)

    if request.method == 'DELETE':
        order_item = get_object_or_404(Order_Item, id=item_id)
        order_product = order_item.product

        if order_product.stock_applies:
            order_product.stock += 1
            order_product.save()

        order.total_price = (
            order.total_price -
            order_item.price).quantize(
                decimal.Decimal('0.01'))

        if order.total_price < 0:
            logging.error("prices below 0! "
                          "You might be running in to the "
                          "10 digit total order price limit")
            order.total_price = 0

        order.save()
        order_item.delete()

        order_items = Order_Item.objects.filter(order=order)

# Path: web/pos/serializers.py
# class OrderSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Order
#         fields = ('id', 'user', 'total_price', 'done', 'last_change')
# 
# class OrderItemSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Order_Item
#         fields = ('id', 'product', 'order', 'price', 'name', 'timestamp')
# 
# Path: web/pos/helper.py
# def get_current_user_order(username):
#     """
#     Gets the order for the current user.
#     """
# 
#     usr = User.objects.get_by_natural_key(username)
#     q = Order.objects.filter(user=usr, done=False)\
#                      .order_by('-last_change')
#     if q.count() >= 1:
#         return q[0]
#     else:
#         return Order.objects.create(user=usr)
# 
# def get_can_negative_stock():
#     """
#     Gets from database if negative stock is allowed. Returns True when allowed.
#     """
# 
#     setting, is_created = Setting.objects.get_or_create(key="negative_stock")
# 
#     if is_created:
#         setting.value = "off"
#         setting.save()
#         return False
# 
#     print(setting.value)
#     if setting.value == "off" or setting.value == "no":
#         return False
#     return True
# 
# def product_list_from_order(order):
#     """
#     Returns a list of Products that appear in an Order
#     """
# 
#     product_list = []
#     order_item_list = Order_Item.objects.filter(order=order)
# 
#     for order_item in order_item_list:
#         product_list.append(order_item.product)
# 
#     return product_list
# 
# Path: web/pos/models.py
# class Product(models.Model):
#     # The different colours, to use as Product.<colour>
#     BLUE = "blue"
#     GREEN = "green"
#     YELLOW = "yellow"
#     ORANGE = "orange"
#     PURPLE = "purple"
#     BLACK = "black"
#     PINK = "pink"
#     CYAN = "cyan"
# 
#     # Colour choices
#     COLOUR_CHOICES = (
#             (BLUE, "Blue"),
#             (GREEN, "Green"),
#             (YELLOW, "Yellow"),
#             (ORANGE, "Orange"),
#             (PURPLE, "Purple"),
#             (BLACK, "Black"),
#             (PINK, "Pink"),
#             (CYAN, "Cyan"),
#     )
# 
#     name = models.CharField(max_length=100,
#                             validators=[validate_product_name])
#     price = models.DecimalField(max_digits=7, decimal_places=2)
#     stock_applies = models.BooleanField()
#     minimum_stock = models.PositiveSmallIntegerField(default=0)
#     stock = models.IntegerField(default=0)
#     code = models.CharField(max_length=50, unique=True, null=True, blank=True)
#     colour = models.CharField(max_length=10,
#                               choices=COLOUR_CHOICES, default="blue")
# 
#     def __str__(self):
#         return self.name
# 
#     def clean(self):
#         validate_product_name(self.name)
#         if self.code == "":
#             self.code = None
# 
#     def save(self, *args, **kwargs):
#         if not self.pk:
#             self.full_clean()
#         return super(Product, self).save(*args, **kwargs)
# 
# class Order_Item(models.Model):
#     product = models.ForeignKey(Product,
#                                 on_delete=models.CASCADE)
#     order = models.ForeignKey(Order, on_delete=models.CASCADE)
#     price = models.DecimalField(max_digits=7, decimal_places=2)
#     name = models.CharField(max_length=100)
#     timestamp = models.DateTimeField(auto_now=True)
# 
# class Order(models.Model):
#     user = models.ForeignKey(settings.AUTH_USER_MODEL,
#                              on_delete=models.CASCADE)
#     total_price = models.DecimalField(max_digits=10,
#                                       decimal_places=2,
#                                       default=0)
#     done = models.BooleanField(default=False)
#     last_change = models.DateTimeField(auto_now=True)
# 
#     def get_absolute_url(self):
#         return reverse('view_order', args=[self.id])
# 
# class Cash(models.Model):
#     amount = models.DecimalField(max_digits=7,
#                                  decimal_places=2,
#                                  default=0)


# Path: web/pos/apiviews.py
import logging
import decimal
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.http import (HttpResponse,
                         JsonResponse,
                         HttpResponseBadRequest)
from rest_framework import status
from .serializers import OrderSerializer, OrderItemSerializer
from .helper import (get_current_user_order,
                     get_can_negative_stock,
                     product_list_from_order)
from .models import Product, Order_Item, Order, Cash

@csrf_exempt
def current_order_item(request, item_id):
    if not request.user.is_authenticated:
        return HttpResponse(status=status.HTTP_401_UNAUTHORIZED)

    order = get_current_user_order(request.user.username)

    if request.method == 'DELETE':
        order_item = get_object_or_404(Order_Item, id=item_id)
        order_product = order_item.product

        if order_product.stock_applies:
            order_product.stock += 1
            order_product.save()

        order.total_price = (
            order.total_price -
            order_item.price).quantize(
                decimal.Decimal('0.01'))

        if order.total_price < 0:
            logging.error("prices below 0! "
                          "You might be running in to the "
                          "10 digit total order price limit")
            order.total_price = 0

        order.save()
        order_item.delete()

        order_items = Order_Item.objects.filter(order=order)

        serializer = OrderItemSerializer(order_items, many=True)