Пример #1
0
    def reserve_fabric(self,
                       fabric,
                       quantity,
                       acknowledgement_id,
                       employee=None):
        """
        Internal method to apply the new quantity to the obj and
        create or update a log of the quantity change
        """

        #Create log to track quantity changes
        try:
            log = Log.objects.get(acknowledgement_id=acknowledgement_id,
                                  supply_id=fabric.id)
        except Log.DoesNotExist:
            log = Log(supply=fabric, acknowledgement_id=acknowledgement_id)

        # Get log quantity for fabric cut later
        original_qty = log.quantity or 0

        # Set log attributes
        log.action = "RESERVE"
        log.quantity = quantity
        log.employee = employee
        log.message = u"Reserve {0}{1} of {2} for Ack#{3}".format(
            quantity, fabric.units, fabric.description, acknowledgement_id)

        # Save log
        log.save()
Пример #2
0
    def _change_supply_cost(self, supply, cost):
        """
        Method to change the cost of a supply

        This will change the supply's product cost, respective of supplier, in the database
        and will log the event as 'PRICE CHANGE'
        """
        try:
            product = Product.objects.get(supply=supply,
                                          supplier=supply.supplier)
        except Product.MultipleObjectsReturned:
            product = Product.objects.filter(
                supply=supply, supplier=supply.supplier).order_by('id')[0]

        old_price = product.cost
        product.cost = cost
        product.save()

        log = Log(
            supply=supply,
            supplier=supply.supplier,
            action="PRICE CHANGE",
            quantity=None,
            cost=product.cost,
            message=
            u"Price change from {0:.2f}{2} to {1:.2f}{2} for {3} [Supplier: {4}]"
            .format(old_price, product.cost, supply.supplier.currency,
                    supply.description, supply.supplier.name))
        log.save()
Пример #3
0
    def _log_quantity(self, obj, old_quantity, new_quantity, employee=None, acknowledgement=None):
        """
        Internal method to apply the new quantity to the obj and
        create a log of the quantity change
        """
        new_quantity = Decimal(str(new_quantity))

        #Type change to ensure that calculations are only between Decimals
        old_quantity = Decimal(str(old_quantity))

        if new_quantity < 0:
            raise ValueError('Quantity cannot be negative')

        if new_quantity != old_quantity:
            if new_quantity > old_quantity:
                action = 'ADD'
                diff = new_quantity - old_quantity
            elif new_quantity < old_quantity:
                action = 'SUBTRACT'
                diff = old_quantity - new_quantity

            #Create log to track quantity changes
            log = Log(supply=obj,
                      action=action,
                      quantity=diff,
                      employee=employee,
                      acknowledgement=acknowledgement,
                      message=u"{0}ed {1}{2} {3} {4}".format(action.capitalize(),
                                                             diff,
                                                             obj.units,
                                                             "to" if action == "ADD" else "from",
                                                             obj.description))

            #Save log
            log.save()
Пример #4
0
    def subtract(self, request, **kwargs):
        """
        Subtracts a quantity to the supply
        
        This method checks that the request method is post, and that
        there is both a quantity and an acknowledgement ID
        """

        obj = self._meta.queryset.get(pk=kwargs['pk'])
        if request.GET.has_key('country'):
            obj.country = request.GET.get('country')
        quantity = request.REQUEST.get('quantity')
        obj.quantity = round(float(obj.quantity) - float(quantity), 2)
        obj.save()

        #log the event
        log = Log(supply=obj,
                  message="Subtracted {0}{1} of {2}".format(
                      quantity, obj.units, obj.description),
                  action="SUBTRACT",
                  quantity=quantity)
        log.save()

        data = {'quantity': obj.quantity}
        for key in obj.__dict__:
            if key[0] != "_":
                data[key] = obj.__dict__[key]
        """        
        data['supplier'] = {'name': obj.supplier.name,
                            'currency': obj.supplier.currency}"""
        return self.create_response(request, data)
Пример #5
0
    def _log_receiving_item(self, item):
        supply = item.supply
        supply.supplier = item.purchase_order.supplier

        log = Log(supply=item.supply,
                  supplier=item.purchase_order.supplier,
                  action="ADD",
                  quantity=item.quantity,
                  message=u"Received {0:.0f}{1} of {2} from {3}".format(
                      item.quantity, supply.purchasing_units,
                      supply.description, item.purchase_order.supplier.name))
        log.save()
Пример #6
0
    def obj_create(self, bundle, **kwargs):
        """
        Creates the supply, and then respectively 
        creates the intermediary product instance for the
        many to many relationship with suppliers
        
        We must separate the suppliers data before calling the parent 
        obj_create method
        """

        try:
            suppliers = bundle.data['suppliers']
        except KeyError:
            suppliers = [bundle.data['supplier']]

        #Initial supply creation
        bundle = super(SupplyResource, self).obj_create(bundle, **kwargs)

        #Creates products to establish supplier/supply relationship
        for supplier in suppliers:
            #Gets or creates a new product
            try:
                product = Product(
                    supply=bundle.obj,
                    supplier=Supplier.objects.get(pk=supplier['id']))
            except Product.DoesNotExist as e:
                product = Product(
                    supplier=Supplier.objects.get(pk=supplier['id']),
                    supply=bundle.obj)
            product = self.hydrate_product(product=product,
                                           bundle=bundle,
                                           **supplier)
            product.save()

            log = Log(
                supply=product.supply,
                supplier=product.supplier,
                action="PRICE CHANGE",
                quantity=None,
                cost=product.cost,
                message=u"Price set to {0}{1} for {2} [Supplier: {3}]".format(
                    product.cost, product.supplier.currency,
                    product.supply.description, product.supplier.name))
            log.save()

        return bundle
Пример #7
0
 def create(cls, supplier=None, **kwargs):
     item = cls()
     try:
         item.supply = Supply.objects.get(id=kwargs['supply']["id"])
     except KeyError:
         item.supply = Supply.objects.get(id=kwargs['id'])
         
     item.supply.supplier = supplier
     item.description = item.supply.description
     
     # Apply costs
     if "cost" in kwargs:
         if Decimal(kwargs['cost']) != item.supply.cost:
             item.unit_cost = Decimal(kwargs['cost'])
             product = Product.objects.get(supply=item.supply, supplier=supplier)
             old_price = product.cost
             product.cost = Decimal(kwargs['cost'])
             product.save()
             
             message = u"Price change from {0}{2} to {1}{2} for {3} [Supplier: {4}]"
             log = Log(supply=item.supply,
                       supplier=supplier,
                       action="PRICE CHANGE",
                       quantity=None,
                       cost=product.cost,
                       message=message.format(old_price,
                                              product.cost,
                                              supplier.currency,
                                              item.supply.description,
                                              supplier.name))
             log.save()
     else:
         item.unit_cost = item.supply.cost
     item.discount = item.supply.discount
     if "discount" in kwargs:
         item.discount = kwargs['discount']
         
     if "comments" in kwargs:
         item.comments = kwargs['comments']
     
     item.quantity = int(kwargs["quantity"])
     
     item.calculate_total()
    
     return item
Пример #8
0
    def hydrate_product(self,
                        product=None,
                        supply=None,
                        supplier=None,
                        bundle=None,
                        **kwargs):
        """
        Takes the products and hydrates it with the appropriate variables
        """
        #Get product by supplier and supply if not provided
        if not product:
            product = Product.objects.get(supply=supply, supplier=supplier)

        #Update all fields with value
        for field in product._meta.get_all_field_names():
            if field in kwargs and field not in ['id', 'supplier', 'supply']:
                if field.lower() == 'cost':
                    if bundle.request.user.has_perm('supplies.view_cost'):
                        if Decimal(kwargs[field]) != product.cost:
                            old_price = product.cost
                            product.cost = kwargs[field]
                            log = Log(
                                supply=product.supply,
                                supplier=product.supplier,
                                action="PRICE CHANGE",
                                quantity=None,
                                cost=product.cost,
                                message=
                                u"Price change from {0}{2} to {1}{2} for {3} [Supplier: {4}]"
                                .format(old_price, product.cost,
                                        product.supplier.currency,
                                        product.supply.description,
                                        product.supplier.name))
                            log.save()
                else:
                    setattr(product, field, kwargs[field])

        return product
Пример #9
0
    def hydrate(self, bundle):
        """
        Implements the hydrate function 
        """
        #Set the country, in order to retrieve the correct quantity
        bundle = self._set_country(bundle)

        #Takes supplier and add to supplier list in data
        if "supplier" in bundle.data:
            try:
                suppliers = bundle.data['suppliers']
            except KeyError:
                bundle.data['suppliers'] = []
                suppliers = []

            if bundle.data['supplier']['id'] not in [
                    s['id'] for s in suppliers
            ]:
                bundle.data['suppliers'].append(bundle.data['supplier'])
                del bundle.data['supplier']

        #Adds new types
        try:
            if bundle.data['type'].lower() == 'custom':
                bundle.obj.type = bundle.data['custom-type']
                del bundle.data['custom-type']
            else:
                bundle.obj.type = bundle.data['type']

            bundle.data['type'] = bundle.obj.type
        except KeyError as e:
            logger.warn(e)

        #Adds the quantity
        try:
            logger.debug("{0} : {1}".format(bundle.obj.quantity,
                                            bundle.data['quantity']))
            logger.debug(bundle.obj.id)
            logger.debug(
                bool(
                    Decimal(str(bundle.obj.quantity)) != Decimal(
                        bundle.data['quantity'])
                    and bundle.obj.quantity != None))
            if Decimal(str(bundle.obj.quantity)) != Decimal(
                    bundle.data['quantity']) and bundle.obj.quantity != None:
                action = "ADD" if float(bundle.data['quantity']
                                        ) > bundle.obj.quantity else "SUBTRACT"
                diff = abs(
                    Decimal(str(bundle.obj.quantity)) -
                    Decimal(bundle.data['quantity']))
                bundle.obj.quantity = float(bundle.data['quantity'])
                log = Log(supply=bundle.obj,
                          action=action,
                          quantity=diff,
                          message=u"{0}ed {1}{2} {3} {4}".format(
                              action.capitalize(), diff, bundle.obj.units,
                              "to" if action == "ADD" else "from",
                              bundle.obj.description))
                log.save()

        except KeyError:
            pass

        #Adds the image
        if "image" in bundle.data:
            try:
                bundle.obj.image = S3Object.objects.get(
                    pk=bundle.data['image']['id'])
            except KeyError:
                #Create a new S3object for the image
                s3_obj = S3Object()
                s3_obj.key = bundle.data['image']['key']
                s3_obj.bucket = bundle.data['image']['bucket']
                s3_obj.save()

                bundle.obj.image = s3_obj
            except S3Object.DoesNotExist:
                raise
        """
        #Change the quantity
        if "quantity" in bundle.data and bundle.obj.pk:
            #Equalize the 2 quantities so that
            #they are easier to work with and compare
            client_quantity = float(bundle.data['quantity'])
            server_quantity = float(bundle.obj.quantity)
            difference = abs(client_quantity - server_quantity)

            #Get the description
            description = bundle.obj.description
            purchasing_units = bundle.obj.purchasing_units
            
            #Checks if quantity is added
            if client_quantity > server_quantity:
                if bundle.request.user.has_perm('supplies.add_quantity'):
                    bundle.obj.quantity = client_quantity
                    logger.info("Added {0}{1} to {2} inventory".format(difference,
                                                                       purchasing_units,
                                                                       description))
                else:
                    bundle.data['quantity'] = server_quantity
                    bundle.data['quantity'] = server_quantity
                    warning = "{0} is not authorized to add to the quantity of Fabric {1}".format(bundle.request.user.username,
                                                                                                  bundle.obj.description)
                    logger.warn(warning)
                    #raise Unauthorized("User does not have authorization to add to inventory.")
                
            #Checks if quantity was subtracted
            elif client_quantity < server_quantity:
                if bundle.request.user.has_perm('supplies.subtract_quantity'):
                    bundle.obj.quantity = client_quantity
                    logger.info("Subtracted {0}{1} from {2} inventory".format(difference,
                                                                       purchasing_units,
                                                                       description))
                else:
                    bundle.data['quantity'] = server_quantity
                    warning = "{0} is not authorized to subtract from the quantity of Fabric {1}".format(bundle.request.user.username,
                                                                                                         bundle.obj.description)
                    logger.warn(warning)
                    #raise Unauthorized("User does not have authorization to subtract from inventory.")
        """

        return bundle