Exemplo n.º 1
0
    def update_values(self, invoice_item):
        self.q_bc_prod = invoice_item.quantity

        # When the CST is contained in the list the calculation is not performed
        # because the taxpayer is exempt.
        if self.cst in [4, 5, 6, 7, 8, 9]:
            return

        # When the branch is Simples Nacional (CRT 1 or 2) and the cofins is 99,
        # the values should be zero
        if self.cst == 99 and invoice_item.parent.branch.crt in [1, 2]:
            self.v_bc = 0
            self.p_cofins = 0
            self.v_cofins = 0
            return

        cost = self._get_item_cost(invoice_item)
        if self.p_cofins == self.COFINS_NAO_CUMULATIVO_PADRAO:
            # Regime de incidencia não cumulativa
            self.v_bc = quantize(invoice_item.quantity * (invoice_item.price - cost))
        else:
            # Regime de incidencia cumulativa
            self.v_bc = quantize(invoice_item.quantity * invoice_item.price)

        if self.p_cofins is not None:
            self.v_cofins = quantize(self.v_bc * self.p_cofins / 100)
Exemplo n.º 2
0
def generate_payments_values(value, installments_number, interest=Decimal(0)):
    """Calculates the values of payments

    :param value: value of payment
    :param installments_number: the number of installments
    :param interest: a :class:`Decimal` with the interest
    :returns: a list with the values
    """
    assert installments_number > 0

    if interest:
        interest_rate = interest / 100 + 1
        normalized_value = quantize(
            (value / installments_number) * interest_rate)
        interest_total = normalized_value * installments_number - value
    else:
        normalized_value = quantize(value / installments_number)
        interest_total = Decimal(0)

    payments = []
    payments_total = Decimal(0)
    for i in range(installments_number):
        payments.append(normalized_value)
        payments_total += normalized_value

    # Adjust the last payment so the total will sum up nicely.
    difference = -(payments_total - interest_total - value)
    if difference:
        payments[-1] += difference

    return payments
Exemplo n.º 3
0
def generate_payments_values(value, installments_number,
                             interest=Decimal(0)):
    """Calculates the values of payments

    :param value: value of payment
    :param installments_number: the number of installments
    :param interest: a :class:`Decimal` with the interest
    :returns: a list with the values
    """
    assert installments_number > 0

    if interest:
        interest_rate = interest / 100 + 1
        normalized_value = quantize((value / installments_number)
                                    * interest_rate)
        interest_total = normalized_value * installments_number - value
    else:
        normalized_value = quantize(value / installments_number)
        interest_total = Decimal(0)

    payments = []
    payments_total = Decimal(0)
    for i in range(installments_number):
        payments.append(normalized_value)
        payments_total += normalized_value

    # Adjust the last payment so the total will sum up nicely.
    difference = -(payments_total - interest_total - value)
    if difference:
        payments[-1] += difference

    return payments
Exemplo n.º 4
0
 def testCreateOutPayments(self):
     payments = self.createOutPayments()
     athird = quantize(Decimal(100) / Decimal(3))
     rest = quantize(Decimal(100) - (athird * 2))
     self.assertEqual(len(payments), 3)
     self.assertEqual(payments[0].value, athird)
     self.assertEqual(payments[1].value, athird)
     self.assertEqual(payments[2].value, rest)
Exemplo n.º 5
0
 def test_create_out_payments(self):
     payments = self.createOutPayments()
     athird = quantize(Decimal(100) / Decimal(3))
     rest = quantize(Decimal(100) - (athird * 2))
     self.assertEqual(len(payments), 3)
     self.assertEqual(payments[0].value, athird)
     self.assertEqual(payments[1].value, athird)
     self.assertEqual(payments[2].value, rest)
Exemplo n.º 6
0
    def test_create_payments(self):
        payments = self.createPayments(Payment.TYPE_IN)
        self.assertEqual(len(payments), 3)
        athird = quantize(Decimal(100) / Decimal(3))
        rest = quantize(Decimal(100) - (athird * 2))
        self.assertEqual(payments[0].value, athird)
        self.assertEqual(payments[1].value, athird)
        self.assertEqual(payments[2].value, rest)

        payments = self.createPayments(Payment.TYPE_OUT)
        self.assertEqual(len(payments), 3)
        athird = quantize(Decimal(100) / Decimal(3))
        rest = quantize(Decimal(100) - (athird * 2))
        self.assertEqual(payments[0].value, athird)
        self.assertEqual(payments[1].value, athird)
        self.assertEqual(payments[2].value, rest)
Exemplo n.º 7
0
    def _get_parameter_value(self, detail):
        """Given a ParameterData object, returns a string representation of
        its current value.
        """
        data = sysparam.get(detail.key, detail.type, self.store)
        if isinstance(data, Domain):
            if not (IDescribable in providedBy(data)):
                raise TypeError(u"Parameter `%s' must implement IDescribable "
                                "interface." % detail.key)
            return data.get_description()
        elif detail.options:
            return detail.options[int(data)]
        elif isinstance(data, bool):
            return [_(u"No"), _(u"Yes")][data]
        elif isinstance(data, decimal.Decimal):
            return quantize(data)
        elif detail.key == u'COUNTRY_SUGGESTED':
            return dgettext("iso_3166", data)
        elif isinstance(data, str):
            # FIXME: workaround to handle locale specific data
            return _(data)

        if data is None:
            return ''
        return str(data)
Exemplo n.º 8
0
    def set_items_discount(self, discount):
        """Apply discount on this sale's items

        :param decimal.Decimal discount: the discount to be applied
            as a percentage, e.g. 10.0, 22.5
        """
        new_total = currency(0)

        item = None
        candidate = None
        for item in self.get_items():
            item.set_discount(discount)
            new_total += quantize(item.price * item.quantity)
            if item.quantity == 1:
                candidate = item

        # Since we apply the discount percentage above, items can generate a
        # 3rd decimal place, that will be rounded to the 2nd, making the value
        # differ. Find that difference and apply it to a sale item, preferable
        # to one with a quantity of 1 since, for instance, applying +0,1 to an
        # item with a quantity of 4 would make it's total +0,4 (+0,3 extra than
        # we are trying to adjust here).
        discount_value = (self.get_sale_base_subtotal() * discount) / 100
        diff = new_total - self.get_sale_base_subtotal() + discount_value
        if diff:
            item = candidate or item
            item.price -= diff
Exemplo n.º 9
0
    def _calculate_federal_tax(self, item, tax_values):
        """ Calculate the IBPT tax for a give item.

        :param item: a |saleitem|
        :returns: the IBPT tax or ``0`` if it does not exist
        :rtype: decimal
        """
        if tax_values is None:
            return Decimal("0")
        sellable = item.sellable
        product = sellable.product

        if product and product.get_icms_template(item.parent.branch):
            origin = product.get_icms_template(item.parent.branch).orig
        else:
            # If the product does not have any fiscal information or it's a
            # service, defaults to national origin
            origin = 0

        # Values (0, 3, 4, 5, 8) represent the taxes codes of brazilian origin.
        if origin in [0, 3, 4, 5, 8]:
            federal_tax = Decimal(tax_values.nacionalfederal) / 100
        # Different codes, represent taxes of international origin.
        else:
            federal_tax = Decimal(tax_values.importadosfederal) / 100
        total_item = quantize(item.price * item.quantity)
        return total_item * federal_tax
Exemplo n.º 10
0
    def set_items_discount(self, discount):
        """Apply discount on this sale's items

        :param decimal.Decimal discount: the discount to be applied
            as a percentage, e.g. 10.0, 22.5
        """
        new_total = currency(0)

        item = None
        candidate = None
        for item in self.get_items():
            item.set_discount(discount)
            new_total += quantize(item.price * item.quantity)
            if item.quantity == 1:
                candidate = item

        # Since we apply the discount percentage above, items can generate a
        # 3rd decimal place, that will be rounded to the 2nd, making the value
        # differ. Find that difference and apply it to a sale item, preferable
        # to one with a quantity of 1 since, for instance, applying +0,1 to an
        # item with a quantity of 4 would make it's total +0,4 (+0,3 extra than
        # we are trying to adjust here).
        discount_value = (self.get_sale_base_subtotal() * discount) / 100
        diff = new_total - self.get_sale_base_subtotal() + discount_value
        if diff:
            item = candidate or item
            item.price -= diff
Exemplo n.º 11
0
 def get_component_cost(self):
     value = Decimal('0')
     for component in self.component_tree:
         if self.component_tree.get_parent(component):
             continue
         value += component.get_total_production_cost()
     return quantize(value)
Exemplo n.º 12
0
    def _get_parameter_value(self, detail):
        """Given a ParameterData object, returns a string representation of
        its current value.
        """
        data = sysparam.get(detail.key, detail.type, self.store)
        if isinstance(data, Domain):
            if not (IDescribable in providedBy(data)):
                raise TypeError(u"Parameter `%s' must implement IDescribable "
                                "interface." % detail.key)
            return data.get_description()
        elif detail.options:
            return detail.options[int(data)]
        elif isinstance(data, bool):
            return [_(u"No"), _(u"Yes")][data]
        elif isinstance(data, decimal.Decimal):
            return quantize(data)
        elif detail.key == u'COUNTRY_SUGGESTED':
            return dgettext("iso_3166", data)
        elif isinstance(data, unicode):
            # FIXME: workaround to handle locale specific data
            return _(data)

        if data is None:
            return ''
        return unicode(data)
Exemplo n.º 13
0
    def _calculate_federal_tax(self, item, tax_values):
        """ Calculate the IBPT tax for a give item.

        :param item: a |saleitem|
        :returns: the IBPT tax or ``0`` if it does not exist
        :rtype: decimal
        """
        if tax_values is None:
            return Decimal("0")
        sellable = item.sellable
        product = sellable.product

        if product and product.icms_template:
            origin = product.icms_template.orig
        else:
            # If the product does not have any fiscal information or it's a
            # service, defaults to national origin
            origin = 0

        # Values (0, 3, 4, 5, 8) represent the taxes codes of brazilian origin.
        if origin in [0, 3, 4, 5, 8]:
            federal_tax = Decimal(tax_values.nacionalfederal) / 100
        # Different codes, represent taxes of international origin.
        else:
            federal_tax = Decimal(tax_values.importadosfederal) / 100
        total_item = quantize(item.price * item.quantity)
        return total_item * federal_tax
Exemplo n.º 14
0
 def get_component_cost(self):
     value = Decimal('0')
     for component in self.component_tree:
         if self.component_tree.get_parent(component):
             continue
         value += component.get_total_production_cost()
     return quantize(value)
Exemplo n.º 15
0
    def test_create_payments(self):
        payments = self.createPayments(Payment.TYPE_IN)
        self.assertEqual(len(payments), 3)
        athird = quantize(Decimal(100) / Decimal(3))
        rest = quantize(Decimal(100) - (athird * 2))
        self.assertEqual(payments[0].value, athird)
        self.assertEqual(payments[1].value, athird)
        self.assertEqual(payments[2].value, rest)

        payments = self.createPayments(Payment.TYPE_OUT)
        self.assertEqual(len(payments), 3)
        athird = quantize(Decimal(100) / Decimal(3))
        rest = quantize(Decimal(100) - (athird * 2))
        self.assertEqual(payments[0].value, athird)
        self.assertEqual(payments[1].value, athird)
        self.assertEqual(payments[2].value, rest)
Exemplo n.º 16
0
 def _update_total(self):
     # We need to update the total manually, since the model quantity update
     # is delayed
     total = self.model.price * self.quantity_model.quantity
     if self.model.ipi_info:
         total += self.model.ipi_info.v_ipi
     self.total.update(currency(quantize(total)))
Exemplo n.º 17
0
def generate_payments_values(value, n_values):
    """Calculates the values of payments

    :param value: value of payment to split
    :param n_values: the number of installments to split the value in
    :returns: a list with the values
    """
    if not n_values:
        raise ValueError(_('Need at least one value'))

    # Round off the individual installments
    # For instance, let's say we're buying something costing 100.00 and paying
    # in 3 installments, then we should have these payment values:
    # - Installment #1: 33.33
    # - Installment #2: 33.33
    # - Installment #3: 33.34
    normalized_value = quantize(value / n_values)
    normalized_values = [normalized_value] * n_values

    # Maybe adjust the last payment so it the total will sum up nicely,
    # for instance following the example above, this will add
    # 0.01 to the third installment, 100 - (33.33 * 3)
    # This is not always needed, since the individual installments might
    # sum up exact, eg 50 + 50
    difference = value - (normalized_value * n_values)
    if difference:
        normalized_values[-1] += difference

    return normalized_values
Exemplo n.º 18
0
 def _update_total(self):
     # We need to update the total manually, since the model quantity
     # update is delayed
     total = self.model.price * self.quantity_model.quantity
     if self.model.ipi_info:
         total += self.model.ipi_info.v_ipi
     self.total.update(currency(quantize(total)))
Exemplo n.º 19
0
def generate_payments_values(value, n_values):
    """Calculates the values of payments

    :param value: value of payment to split
    :param n_values: the number of installments to split the value in
    :returns: a list with the values
    """
    if not n_values:
        raise ValueError(_('Need at least one value'))

    # Round off the individual installments
    # For instance, let's say we're buying something costing 100.00 and paying
    # in 3 installments, then we should have these payment values:
    # - Installment #1: 33.33
    # - Installment #2: 33.33
    # - Installment #3: 33.34
    normalized_value = quantize(value / n_values)
    normalized_values = [normalized_value] * n_values

    # Maybe adjust the last payment so it the total will sum up nicely,
    # for instance following the example above, this will add
    # 0.01 to the third installment, 100 - (33.33 * 3)
    # This is not always needed, since the individual installments might
    # sum up exact, eg 50 + 50
    difference = value - (normalized_value * n_values)
    if difference:
        normalized_values[-1] += difference

    return normalized_values
Exemplo n.º 20
0
    def _validate_percentage(self, value, type_text):
        if value >= 100:
            self.model.discount_percentage = 0
            return ValidationError(
                _(u'%s can not be greater or equal '
                  'to 100%%.') % type_text)
        if value < 0:
            self.model.discount_percentage = 0
            return ValidationError(_("%s can not be less than 0") % type_text)

        if (not sysparam.get_bool('USE_TRADE_AS_DISCOUNT')
                and value > self.max_discount):
            self.model.discount_percentage = 0
            return ValidationError(
                _("%s can not be greater than %d%%") %
                (type_text, self.max_discount))

        discount = self.max_discount / 100 * self.original_sale_amount
        perc = discount * 100 / self.model.get_sale_subtotal()
        new_discount = quantize(self.original_discount + perc)
        #XXX: If the discount is less than the trade value. What to do?
        if (sysparam.get_bool('USE_TRADE_AS_DISCOUNT')
                and value > new_discount):
            self.model.discount_percentage = 0
            return ValidationError(
                _(u'%s can not be greater than (%.2f%%).') %
                (type_text, new_discount))
Exemplo n.º 21
0
    def _validate_percentage(self, value, type_text):
        if value >= 100:
            self.model.discount_percentage = 0
            return ValidationError(_(u'%s can not be greater or equal '
                                     'to 100%%.') % type_text)
        if value < 0:
            self.model.discount_percentage = 0
            return ValidationError(_("%s can not be less than 0")
                                   % type_text)

        if (not sysparam.get_bool('USE_TRADE_AS_DISCOUNT') and
            value > self.max_discount):
            self.model.discount_percentage = 0
            return ValidationError(_("%s can not be greater than %d%%")
                                   % (type_text, self.max_discount))

        discount = self.max_discount / 100 * self.original_sale_amount
        perc = discount * 100 / self.model.get_sale_subtotal()
        new_discount = quantize(self.original_discount + perc)
        #XXX: If the discount is less than the trade value. What to do?
        if (sysparam.get_bool('USE_TRADE_AS_DISCOUNT') and value > new_discount):
            self.model.discount_percentage = 0
            return ValidationError(_(u'%s can not be greater than (%.2f%%).')
                                   % (type_text, new_discount))

        old_discount = self.model.discount_value
        # Avoid unecessary updates if the discount didnt change
        if self.model.discount_value != old_discount:
            self.update_sale_discount()
Exemplo n.º 22
0
 def get_component_cost(self):
     value = Decimal('0')
     for component in self.component_tree:
         if self.component_tree.get_parent(component):
             continue
         value += component.get_total_production_cost()
     value = value / self._product.yield_quantity
     return quantize(value, precision=sysparam.get_int('COST_PRECISION_DIGITS'))
Exemplo n.º 23
0
 def get_component_cost(self):
     value = Decimal('0')
     for component in self.component_tree:
         if self.component_tree.get_parent(component):
             continue
         value += component.get_total_production_cost()
     value = value / self._product.yield_quantity
     return quantize(value, precision=sysparam.get_int('COST_PRECISION_DIGITS'))
Exemplo n.º 24
0
 def reserve_products(self, purchase_order):
     for item in self.work_order.get_items():
         if not item.purchase_item:
             continue
         sale_item = item.sale_item
         to_reserve = sale_item.quantity - sale_item.quantity_decreased
         if to_reserve > 0:
             sale_item.reserve(quantize(to_reserve))
Exemplo n.º 25
0
 def reserve_products(self, purchase_order):
     for item in self.work_order.get_items():
         if not item.purchase_item:
             continue
         sale_item = item.sale_item
         to_reserve = sale_item.quantity - sale_item.quantity_decreased
         if to_reserve > 0:
             sale_item.reserve(quantize(to_reserve))
Exemplo n.º 26
0
 def discount_percentage(self):
     discount_value = self.discount_value
     if not discount_value:
         return currency(0)
     subtotal = self.products_total
     assert subtotal > 0, u"the subtotal should not be zero " u"at this point"
     total = subtotal - discount_value
     percentage = (1 - total / subtotal) * 100
     return quantize(percentage)
Exemplo n.º 27
0
    def add_item(self, item):
        """
        @param item: A :class:`SaleItem` subclass
        @returns: id of the item.:
          0 >= if it was added successfully
          -1 if an error happend
          0 if added but not printed (gift certificates, free deliveries)
        """
        sellable = item.sellable
        max_len = self._get_capability("item_description").max_len
        description = sellable.description[:max_len]
        unit_desc = ''
        if not sellable.unit:
            unit = UnitType.EMPTY
        else:
            if sellable.unit.unit_index == UnitType.CUSTOM:
                unit_desc = sellable.unit.description
            unit = sellable.unit.unit_index or UnitType.EMPTY
        max_len = self._get_capability("item_code").max_len
        code = sellable.code[:max_len]

        try:
            tax_constant = self._printer.get_tax_constant_for_device(sellable)
        except DeviceError as e:
            warning(_("Could not print item"), str(e))
            return -1

        base_price = item.base_price
        discount_value = quantize((base_price - item.price) * item.quantity)
        # If the selling value is greater than the base price
        if discount_value < 0:
            discount_value = 0
            base_price = item.price
        if item.price == 0:
            # The ECF does not accept an item without a price. So we are adding
            # the item with a 0.01 price, and this value will be given as a
            # discount when the coupon is closed.
            base_price = Decimal('0.01')
            discount_value = 0

        try:
            item_id = self._driver.add_item(code,
                                            description,
                                            base_price,
                                            tax_constant.device_value.decode(),
                                            item.quantity,
                                            unit,
                                            unit_desc=unit_desc,
                                            discount=discount_value)
        except DriverError as e:
            warning(_("Could not print item"), str(e))
            item_id = -1

        if item.price == 0 and item_id != -1:
            self._temp_discount[item_id] = base_price * item.quantity

        return item_id
Exemplo n.º 28
0
 def _get_discount_by_percentage(self):
     discount_value = self.discount_value
     if not discount_value:
         return currency(0)
     subtotal = self.get_products_total()
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal - discount_value
     percentage = (1 - total / subtotal) * 100
     return quantize(percentage)
Exemplo n.º 29
0
 def _get_surcharge_by_percentage(self):
     surcharge_value = self.surcharge_value
     if not surcharge_value:
         return currency(0)
     subtotal = self.get_products_total()
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal + surcharge_value
     percentage = ((total / subtotal) - 1) * 100
     return quantize(percentage)
Exemplo n.º 30
0
 def _get_discount_by_percentage(self):
     discount_value = self.discount_value
     if not discount_value:
         return currency(0)
     subtotal = self.get_purchase_subtotal()
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal - discount_value
     percentage = (1 - total / subtotal) * 100
     return quantize(percentage)
Exemplo n.º 31
0
 def _get_surcharge_by_percentage(self):
     surcharge_value = self.surcharge_value
     if not surcharge_value:
         return currency(0)
     subtotal = self.get_products_total()
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal + surcharge_value
     percentage = ((total / subtotal) - 1) * 100
     return quantize(percentage)
Exemplo n.º 32
0
 def discount_percentage(self):
     discount_value = self.discount_value
     if not discount_value:
         return currency(0)
     subtotal = self.products_total
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal - discount_value
     percentage = (1 - total / subtotal) * 100
     return quantize(percentage)
Exemplo n.º 33
0
 def on_discount_value__validate(self, entry, value):
     if not self.discount_value.is_sensitive() or self._proxy is None:
         return
     percentage = quantize(value * 100 / self.model.get_sale_subtotal())
     # If the quantized percentage value is 100, the value may still be lower
     # then the subtotal. In this case, lets consider the discount percentage
     # to be 99.99 (So that we can close a sale for 0.01, for instance)
     if percentage == 100 and value < self.model.get_sale_subtotal():
         percentage = Decimal('99.99')
     return self._validate_percentage(percentage, _(u'Discount'))
Exemplo n.º 34
0
 def on_discount_value__validate(self, entry, value):
     if not self.discount_value.is_sensitive() or self._proxy is None:
         return
     percentage = quantize(value * 100 / self.model.get_sale_subtotal())
     # If the quantized percentage value is 100, the value may still be lower
     # then the subtotal. In this case, lets consider the discount percentage
     # to be 99.99 (So that we can close a sale for 0.01, for instance)
     if percentage == 100 and value < self.model.get_sale_subtotal():
         percentage = Decimal('99.99')
     return self._validate_percentage(percentage, _(u'Discount'))
Exemplo n.º 35
0
    def _calc_normal(self, invoice_item):
        self.v_bc = quantize(invoice_item.price * invoice_item.quantity)

        if self.bc_include_ipi and invoice_item.ipi_info:
            self.v_bc += invoice_item.ipi_info.v_ipi

        if self.p_red_bc is not None:
            self.v_bc -= self.v_bc * self.p_red_bc / 100

        if self.p_icms is not None and self.v_bc is not None:
            self.v_icms = self.v_bc * self.p_icms / 100
Exemplo n.º 36
0
    def set_discount(self, discount):
        """Apply *discount* on this item

        Note that the discount will be applied based on :obj:`.base_price`
        and then substitute :obj:`.price`, making any previous
        discount/surcharge being lost

        :param decimal.Decimal discount: the discount to be applied
            as a percentage, e.g. 10.0, 22.5
        """
        self.price = quantize(self.base_price * (1 - discount / 100))
Exemplo n.º 37
0
    def add_item(self, item):
        """
        @param item: A :class:`SaleItem` subclass
        @returns: id of the item.:
          0 >= if it was added successfully
          -1 if an error happend
          0 if added but not printed (gift certificates, free deliveries)
        """
        sellable = item.sellable
        max_len = self._get_capability("item_description").max_len
        description = sellable.description[:max_len]
        unit_desc = ''
        if not sellable.unit:
            unit = UnitType.EMPTY
        else:
            if sellable.unit.unit_index == UnitType.CUSTOM:
                unit_desc = sellable.unit.description
            unit = sellable.unit.unit_index or UnitType.EMPTY
        max_len = self._get_capability("item_code").max_len
        code = sellable.code[:max_len]

        try:
            tax_constant = self._printer.get_tax_constant_for_device(sellable)
        except DeviceError as e:
            warning(_("Could not print item"), str(e))
            return -1

        base_price = item.base_price
        discount_value = quantize((base_price - item.price) * item.quantity)
        # If the selling value is greater than the base price
        if discount_value < 0:
            discount_value = 0
            base_price = item.price
        if item.price == 0:
            # The ECF does not accept an item without a price. So we are adding
            # the item with a 0.01 price, and this value will be given as a
            # discount when the coupon is closed.
            base_price = Decimal('0.01')
            discount_value = 0

        try:
            item_id = self._driver.add_item(code, description, base_price,
                                            tax_constant.device_value.decode(),
                                            item.quantity, unit,
                                            unit_desc=unit_desc,
                                            discount=discount_value)
        except DriverError as e:
            warning(_("Could not print item"), str(e))
            item_id = -1

        if item.price == 0 and item_id != -1:
            self._temp_discount[item_id] = base_price * item.quantity

        return item_id
Exemplo n.º 38
0
    def set_discount(self, discount):
        """Apply *discount* on this item

        Note that the discount will be applied based on :obj:`.base_price`
        and then substitute :obj:`.price`, making any previous
        discount/surcharge being lost

        :param decimal.Decimal discount: the discount to be applied
            as a percentage, e.g. 10.0, 22.5
        """
        self.price = quantize(self.base_price * (1 - discount / 100))
Exemplo n.º 39
0
    def update_values(self, invoice_item):
        # IPI is only calculated if cst is one of the following
        if not self.cst in [0, 49, 50, 99]:
            return

        if self.calculo == self.CALC_ALIQUOTA:
            self.v_bc = quantize(invoice_item.price * invoice_item.quantity)
            if self.p_ipi is not None:
                self.v_ipi = self.v_bc * self.p_ipi / 100
        elif self.calculo == self.CALC_UNIDADE:
            if self.q_unid is not None and self.v_unid is not None:
                self.v_ipi = self.q_unid * self.v_unid
Exemplo n.º 40
0
 def discount_percentage(self):
     """Discount by percentage.
     Note that percentage must be added as an absolute value not as a
     factor like 1.05 = 5 % of surcharge
     The correct form is 'percentage = 3' for a discount of 3 %"""
     discount_value = self.discount_value
     if not discount_value:
         return currency(0)
     subtotal = self.purchase_subtotal
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal - discount_value
     percentage = (1 - total / subtotal) * 100
     return quantize(percentage)
Exemplo n.º 41
0
    def _calc_normal(self, invoice_item):
        self.v_bc = quantize(invoice_item.price * invoice_item.quantity)

        if self.bc_include_ipi and invoice_item.ipi_info:
            self.v_bc += invoice_item.ipi_info.v_ipi

        if self.p_red_bc is not None:
            self.v_bc -= self.v_bc * self.p_red_bc / 100

        if self.p_icms is not None and self.v_bc is not None:
            self.v_icms = self.v_bc * self.p_icms / 100

        if self.p_fcp is not None and self.v_bc is not None:
            self.v_fcp = self.v_bc * self.p_fcp / 100
Exemplo n.º 42
0
 def surcharge_percentage(self):
     """Surcharge by percentage.
     Note that surcharge must be added as an absolute value not as a
     factor like 0.97 = 3 % of discount.
     The correct form is 'percentage = 3' for a surcharge of 3 %"""
     surcharge_value = self.surcharge_value
     if not surcharge_value:
         return currency(0)
     subtotal = self.purchase_subtotal
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal + surcharge_value
     percentage = ((total / subtotal) - 1) * 100
     return quantize(percentage)
Exemplo n.º 43
0
 def surcharge_percentage(self):
     """Surcharge by percentage.
     Note that surcharge must be added as an absolute value not as a
     factor like 0.97 = 3 % of discount.
     The correct form is 'percentage = 3' for a surcharge of 3 %"""
     surcharge_value = self.surcharge_value
     if not surcharge_value:
         return currency(0)
     subtotal = self.purchase_subtotal
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal + surcharge_value
     percentage = ((total / subtotal) - 1) * 100
     return quantize(percentage)
Exemplo n.º 44
0
 def discount_percentage(self):
     """Discount by percentage.
     Note that percentage must be added as an absolute value not as a
     factor like 1.05 = 5 % of surcharge
     The correct form is 'percentage = 3' for a discount of 3 %"""
     discount_value = self.discount_value
     if not discount_value:
         return currency(0)
     subtotal = self.purchase_subtotal
     assert subtotal > 0, (u'the subtotal should not be zero '
                           u'at this point')
     total = subtotal - discount_value
     percentage = (1 - total / subtotal) * 100
     return quantize(percentage)
Exemplo n.º 45
0
    def _calc_st(self, invoice_item):
        self.v_bc_st = quantize(invoice_item.price * invoice_item.quantity)

        if self.bc_st_include_ipi and invoice_item.ipi_info:
            self.v_bc_st += invoice_item.ipi_info.v_ipi

        if self.p_red_bc_st is not None:
            self.v_bc_st -= self.v_bc_st * self.p_red_bc_st / 100
        if self.p_mva_st is not None:
            self.v_bc_st += self.v_bc_st * self.p_mva_st / 100

        if self.v_bc_st is not None and self.p_icms_st is not None:
            self.v_icms_st = self.v_bc_st * self.p_icms_st / 100
        if self.v_icms is not None and self.v_icms_st is not None:
            self.v_icms_st -= self.v_icms
Exemplo n.º 46
0
    def create_payments(self, payment_type, group, branch, value, due_dates):
        """Creates new payments
        The values of the individual payments are calculated by taking
        the value and dividing it by the number of payments.
        The number of payments is determined by the length of the due_dates
        sequence.

        :param payment_type: the kind of payment, in or out
        :param payment_group: a :class:`PaymentGroup` subclass
        :param branch: the :class:`branch <stoqlib.domain.person.Branch>'
          associated with the payments, for incoming payments this is the
          branch receiving the payment and for outgoing payments this is the
          branch sending the payment.
        :param value: value of payment
        :param due_dates: a list of datetime objects
        :returns: a list of :class:`payments <stoqlib.domain.payment.Payment>`
        """
        installments = len(due_dates)
        penalty = Decimal(0)

        normalized_value = self._calculate_payment_value(value, installments, payment_type, penalty)

        normalized_value = quantize(normalized_value)
        if penalty:
            penalty_total = normalized_value * installments - value
        else:
            penalty_total = Decimal(0)

        payments = []
        payments_total = Decimal(0)
        for i, due_date in enumerate(due_dates):
            payment = self.create_payment(
                payment_type,
                group,
                branch,
                normalized_value,
                due_date,
                description=self.describe_payment(group, i + 1, installments),
            )
            payments.append(payment)
            payments_total += normalized_value

        # Adjust the last payment so it the total will sum up nicely.
        difference = -(payments_total - penalty_total - value)
        if difference:
            payment.value += difference
        return payments
Exemplo n.º 47
0
    def create_payments(self, payment_type, group, branch, value, due_dates):
        """Creates new payments
        The values of the individual payments are calculated by taking
        the value and dividing it by the number of payments.
        The number of payments is determined by the length of the due_dates
        sequence.

        :param payment_type: the kind of payment, in or out
        :param payment_group: a |paymentgroup|
        :param branch: the |branch| associated with the payments, for incoming
          payments this is the  branch receiving the payment and for outgoing
          payments this is the branch sending the payment.
        :param value: total value of all payments
        :param due_dates: a list of datetime objects
        :returns: a list of |payments|
        """
        installments = len(due_dates)
        penalty = Decimal(0)

        normalized_value = self._calculate_payment_value(
            value, installments, payment_type, penalty)

        normalized_value = quantize(normalized_value)
        if penalty:
            penalty_total = normalized_value * installments - value
        else:
            penalty_total = Decimal(0)

        payments = []
        payments_total = Decimal(0)
        for i, due_date in enumerate(due_dates):
            payment = self.create_payment(payment_type,
                                          group,
                                          branch,
                                          normalized_value,
                                          due_date,
                                          description=self.describe_payment(
                                              group, i + 1, installments))
            payments.append(payment)
            payments_total += normalized_value

        # Adjust the last payment so it the total will sum up nicely.
        difference = -(payments_total - penalty_total - value)
        if difference:
            payment.value += difference
        return payments
Exemplo n.º 48
0
    def update_values(self, invoice_item):
        self.q_bc_prod = invoice_item.quantity

        # When the CST is contained in the list the calculation is not performed
        # because the taxpayer is exempt.
        if self.cst in [4, 5, 6, 7, 8, 9]:
            return
        # When the branch is Simples Nacional (CRT 1 or 2) and the pis is 99,
        # the values should be zero
        if self.cst == 99 and invoice_item.parent.branch.crt in [1, 2]:
            self.v_bc = 0
            self.p_pis = 0
            self.v_pis = 0
            return
        cost = self._get_item_cost(invoice_item)
        self.v_bc = quantize(invoice_item.quantity *
                             (invoice_item.price - cost))
        if self.p_pis is not None:
            self.v_pis = self.v_bc * self.p_pis / 100
Exemplo n.º 49
0
    def _calc_st(self, invoice_item):
        self.v_bc_st = quantize(invoice_item.price * invoice_item.quantity)

        if self.bc_st_include_ipi and invoice_item.ipi_info:
            self.v_bc_st += invoice_item.ipi_info.v_ipi

        if self.p_red_bc_st is not None:
            self.v_bc_st -= self.v_bc_st * self.p_red_bc_st / 100
        if self.p_mva_st is not None:
            self.v_bc_st += self.v_bc_st * self.p_mva_st / 100

        if self.v_bc_st is not None and self.p_icms_st is not None:
            self.v_icms_st = self.v_bc_st * self.p_icms_st / 100
        if self.v_icms is not None and self.v_icms_st is not None:
            self.v_icms_st -= self.v_icms

        if self.v_bc_st is not None and self.p_fcp_st is not None:
            self.v_fcp_st = self.v_bc_st * self.p_fcp_st / 100
        if self.v_fcp is not None and self.v_fcp_st is not None:
            self.v_fcp_st -= self.v_fcp
Exemplo n.º 50
0
    def _calculate_value(self):
        """Calculates the commission amount to be paid"""

        relative_percentage = self._get_payment_percentage()

        # The commission is calculated for all sellable items
        # in sale; a relative percentage is given for each payment
        # of the sale.
        # Eg:
        #   If a customer decides to pay a sale in two installments,
        #   Let's say divided in 20%, and 80% of the total value of the items
        #   which was bought in the sale. Then the commission received by the
        #   sales person is also going to be 20% and 80% of the complete
        #   commission amount for the sale when that specific payment is payed.
        value = Decimal(0)
        for sellable_item in self.sale.get_items():
            value += (self._get_commission(sellable_item.sellable) *
                      sellable_item.get_total() * relative_percentage)

        # The calculation above may have produced a number with more than two
        # digits. Round it to only two
        self.value = quantize(value)
Exemplo n.º 51
0
    def __init__(self, item, parent_item=None):
        self.purchase_item = item
        self.code = item.sellable.code
        self.barcode = item.sellable.barcode
        self.description = item.sellable.description
        self.category_description = item.sellable.get_category_description()
        self.unit_description = item.sellable.unit_description
        self.cost = currency(quantize(item.cost + item.unit_ipi_value))
        self.ipi_value = item.ipi_value
        self.icms_st_value = item.icms_st_value
        self.remaining_quantity = item.get_pending_quantity()
        self.storable = item.sellable.product_storable
        self.is_batch = self.storable and self.storable.is_batch
        self.need_adjust_batch = self.is_batch
        self.batches = {}
        if not self.is_batch:
            self.quantity = self.remaining_quantity

        self.parent_item = parent_item
        self.children_items = []
        for child in item.children_items:
            self.children_items.append(
                _TemporaryReceivingItem(child, parent_item=self))
Exemplo n.º 52
0
    def _calculate_value(self):
        """Calculates the commission amount to be paid"""

        relative_percentage = self._get_payment_percentage()

        # The commission is calculated for all sellable items
        # in sale; a relative percentage is given for each payment
        # of the sale.
        # Eg:
        #   If a customer decides to pay a sale in two installments,
        #   Let's say divided in 20%, and 80% of the total value of the items
        #   which was bought in the sale. Then the commission received by the
        #   sales person is also going to be 20% and 80% of the complete
        #   commission amount for the sale when that specific payment is payed.
        value = Decimal(0)
        for sellable_item in self.sale.get_items():
            value += (self._get_commission(sellable_item.sellable) *
                      sellable_item.get_total() *
                      relative_percentage)

        # The calculation above may have produced a number with more than two
        # digits. Round it to only two
        self.value = quantize(value)
Exemplo n.º 53
0
    def __init__(self, item, parent_item=None):
        self.purchase_item = item
        self.code = item.sellable.code
        self.barcode = item.sellable.barcode
        self.description = item.sellable.description
        self.category_description = item.sellable.get_category_description()
        self.unit_description = item.sellable.unit_description
        self.cost = currency(quantize(item.cost + item.unit_ipi_value))
        self.ipi_value = item.ipi_value
        self.icms_st_value = item.icms_st_value
        self.remaining_quantity = item.get_pending_quantity()
        self.storable = item.sellable.product_storable
        self.is_batch = self.storable and self.storable.is_batch
        self.need_adjust_batch = self.is_batch
        self.batches = {}
        if not self.is_batch:
            self.quantity = self.remaining_quantity

        self.parent_item = parent_item
        self.children_items = []
        for child in item.children_items:
            self.children_items.append(_TemporaryReceivingItem(child,
                                                               parent_item=self))
Exemplo n.º 54
0
 def _get_price_by_markup(self, markup, cost=None):
     if cost is None:
         cost = self.cost
     return currency(quantize(cost + (cost * (markup / currency(100)))))
Exemplo n.º 55
0
 def _calculate_state_tax(self, item, tax_values):
     if tax_values is None:
         return Decimal("0")
     total_item = quantize(item.price * item.quantity)
     state_tax = Decimal(tax_values.estadual) / 100
     return total_item * state_tax
Exemplo n.º 56
0
Arquivo: pos.py Projeto: pkaislan/stoq
 def total(self):
     # Sale items are suposed to have only 2 digits, but the value price
     # * quantity may have more than 2, so we need to round it.
     return quantize(currency(self.price * self.quantity))
Exemplo n.º 57
0
 def get_total_production_cost(self):
     return quantize(self.production_cost * self.quantity)
Exemplo n.º 58
0
 def _get_price_by_markup(self, markup, cost=None):
     if cost is None:
         cost = self.cost
     return currency(quantize(cost + (cost * (markup / currency(100)))))