Exemplo n.º 1
0
    def get_warning(self):
        """
        Return a warning message about this basket line if one is applicable

        This could be things like the price has changed
        """
        if not self.price_incl_tax:
            return
        if not self.product.has_stockrecord:
            msg = u"'%(product)s' is no longer available"
            return _(msg) % {'product': self.product.get_title()}

        current_price_incl_tax = self.product.stockrecord.price_incl_tax
        if current_price_incl_tax > self.price_incl_tax:
            return _(
                u"The price of '%(product)s' has increased from %(old_price)s to %(new_price)s since you added it to your basket") % {
                    'product': self.product.get_title(),
                    'old_price': currency(self.price_incl_tax),
                    'new_price': currency(current_price_incl_tax)}
        if current_price_incl_tax < self.price_incl_tax:
            return _(
                u"The price of '%(product)s' has decreased from %(old_price)s to %(new_price)s since you added it to your basket") % {
                    'product': self.product.get_title(),
                    'old_price': currency(self.price_incl_tax),
                    'new_price': currency(current_price_incl_tax)}
Exemplo n.º 2
0
 def get_warning(self):
     if self.stockrecord_source == self.PRODUCT_STOCKRECORD:
         super(Line, self).get_warning()
     if self.stockrecord_source == self.OPTIONS_CALCULATOR:
         if self.items_required is None:
             # In this case there is probably a bug in the code
             # execution should not continue
             raise ItemsRequiredException
         if not self.price_incl_tax:
             return
         try:
             current_price_incl_tax, nr_of_units, items_per_pack = (
                 self._get_unit_price_from_pricelist())
         except PriceNotAvailable:
             msg = u"'%(product)s' is no longer available"
             return _(msg) % {'product': self.product.get_title()}
         else:
             if current_price_incl_tax > self.price_incl_tax:
                 msg = ("The price of '%(product)s' has increased from "
                        "%(old_price)s to %(new_price)s since you added it "
                        "to your basket")
                 return _(msg) % {
                     'product': self.product.get_title(),
                     'old_price': currency(self.price_incl_tax),
                     'new_price': currency(current_price_incl_tax)}
             if current_price_incl_tax < self.price_incl_tax:
                 msg = ("The price of '%(product)s' has decreased from "
                        "%(old_price)s to %(new_price)s since you added it "
                        "to your basket")
                 return _(msg) % {
                     'product': self.product.get_title(),
                     'old_price': currency(self.price_incl_tax),
                     'new_price': currency(current_price_incl_tax)}
Exemplo n.º 3
0
    def get_warning(self):
        """
        Return a warning message about this basket line if one is applicable

        This could be things like the price has changed
        """
        if isinstance(self.purchase_info.availability, Unavailable):
            msg = "'%(product)s' is no longer available"
            return _(msg) % {'product': self.product.get_title()}

        if not self.price_incl_tax:
            return
        if not self.purchase_info.price.is_tax_known:
            return

        # Compare current price to price when added to basket
        current_price_incl_tax = self.purchase_info.price.incl_tax
        if current_price_incl_tax != self.price_incl_tax:
            product_prices = {
                'product': self.product.get_title(),
                'old_price': currency(self.price_incl_tax),
                'new_price': currency(current_price_incl_tax)
            }
            if current_price_incl_tax > self.price_incl_tax:
                warning = _("The price of '%(product)s' has increased from"
                            " %(old_price)s to %(new_price)s since you added"
                            " it to your basket")
                return warning % product_prices
            else:
                warning = _("The price of '%(product)s' has decreased from"
                            " %(old_price)s to %(new_price)s since you added"
                            " it to your basket")
                return warning % product_prices
Exemplo n.º 4
0
    def __unicode__(self):
        if self.type == self.PERCENTAGE:
            desc = _("%(value)s%% discount on %(range)s") % {
                'value': self.value,
                'range': unicode(self.range).lower()}
        elif self.type == self.MULTIBUY:
            desc = _("Cheapest product is free from %s") % (
                unicode(self.range).lower(),)
        elif self.type == self.FIXED_PRICE:
            desc = _("The products that meet the condition are "
                     "sold for %(amount)s") % {
                         'amount': currency(self.value)}
        elif self.type == self.SHIPPING_PERCENTAGE:
            desc = _("%(value)s%% off shipping cost") % {
                'value': self.value}
        elif self.type == self.SHIPPING_ABSOLUTE:
            desc = _("%(amount)s off shipping cost") % {
                'amount': currency(self.value)}
        elif self.type == self.SHIPPING_FIXED_PRICE:
            desc = _("Get shipping for %(amount)s") % {
                'amount': currency(self.value)}
        else:
            desc = _("%(amount)s discount on %(range)s") % {
                'amount': currency(self.value),
                'range': unicode(self.range).lower()}

        if self.max_affected_items:
            desc += ungettext(" (max %d item)", " (max %d items)", self.max_affected_items) % self.max_affected_items

        return desc
Exemplo n.º 5
0
    def __unicode__(self):
        if self.type == self.PERCENTAGE:
            desc = _("%(value)s%% discount on %(range)s") % {
                'value': self.value,
                'range': unicode(self.range).lower()}
        elif self.type == self.MULTIBUY:
            desc = _("Cheapest product is free from %s") % (
                unicode(self.range).lower(),)
        elif self.type == self.FIXED_PRICE:
            desc = _("The products that meet the condition are "
                     "sold for %(amount)s") % {
                         'amount': currency(self.value)}
        elif self.type == self.SHIPPING_PERCENTAGE:
            desc = _("%(value)s%% off shipping cost") % {
                'value': self.value}
        elif self.type == self.SHIPPING_ABSOLUTE:
            desc = _("%(amount)s off shipping cost") % {
                'amount': currency(self.value)}
        elif self.type == self.SHIPPING_FIXED_PRICE:
            desc = _("Get shipping for %(amount)s") % {
                'amount': currency(self.value)}
        else:
            desc = _("%(amount)s discount on %(range)s") % {
                'amount': currency(self.value),
                'range': unicode(self.range).lower()}

        if self.max_affected_items:
            desc += ungettext(" (max %d item)", " (max %d items)", self.max_affected_items) % self.max_affected_items

        return desc
Exemplo n.º 6
0
    def get_warning(self):
        """
        Return a warning message about this basket line if one is applicable

        This could be things like the price has changed
        """
        if not self.stockrecord:
            msg = u"'%(product)s' is no longer available"
            return _(msg) % {'product': self.product.get_title()}

        if not self.price_incl_tax:
            return
        if not self.purchase_info.price.is_tax_known:
            return

        # Compare current price to price when added to basket
        current_price_incl_tax = self.purchase_info.price.incl_tax
        if current_price_incl_tax != self.price_incl_tax:
            product_prices = {
                'product': self.product.get_title(),
                'old_price': currency(self.price_incl_tax),
                'new_price': currency(current_price_incl_tax)
            }
            if current_price_incl_tax > self.price_incl_tax:
                warning = _("The price of '%(product)s' has increased from"
                            " %(old_price)s to %(new_price)s since you added"
                            " it to your basket")
                return warning % product_prices
            else:
                warning = _("The price of '%(product)s' has decreased from"
                            " %(old_price)s to %(new_price)s since you added"
                            " it to your basket")
                return warning % product_prices
Exemplo n.º 7
0
    def get_warning(self):
        """
        Return a warning message about this basket line if one is applicable

        This could be things like the price has changed
        """
        if not self.price_incl_tax:
            return
        if not self.product.has_stockrecord:
            msg = u"'%(product)s' is no longer available"
            return _(msg) % {'product': self.product.get_title()}

        current_price_incl_tax = self.product.stockrecord.price_incl_tax
        if current_price_incl_tax > self.price_incl_tax:
            return _(
                u"The price of '%(product)s' has increased from %(old_price)s to %(new_price)s since you added it to your basket"
            ) % {
                'product': self.product.get_title(),
                'old_price': currency(self.price_incl_tax),
                'new_price': currency(current_price_incl_tax)
            }
        if current_price_incl_tax < self.price_incl_tax:
            return _(
                u"The price of '%(product)s' has decreased from %(old_price)s to %(new_price)s since you added it to your basket"
            ) % {
                'product': self.product.get_title(),
                'old_price': currency(self.price_incl_tax),
                'new_price': currency(current_price_incl_tax)
            }
Exemplo n.º 8
0
def _get_info_for_coupon_report(coupon, voucher):
    history = coupon.history.first()
    author = history.history_user.full_name
    category_name = ProductCategory.objects.get(product=coupon).category.name

    try:
        note = coupon.attr.note
    except AttributeError:
        note = ''

    offer = voucher.offers.first()
    if offer.condition.range.catalog:
        seat_stockrecord = offer.condition.range.catalog.stock_records.first()
        coupon_stockrecord = StockRecord.objects.get(product=coupon)
        invoiced_amount = currency(coupon_stockrecord.price_excl_tax)
        course_id = seat_stockrecord.product.attr.course_key
        course_organization = CourseKey.from_string(course_id).org
        price = currency(seat_stockrecord.price_excl_tax)
        discount_data = get_voucher_discount_info(offer.benefit, seat_stockrecord.price_excl_tax)
        coupon_type, discount_percentage, discount_amount = _get_discount_info(discount_data)
    else:
        # Note (multi-courses): Need to account for multiple seats.
        catalog_query = offer.condition.range.catalog_query
        course_seat_types = offer.condition.range.course_seat_types
        course_id = None
        invoiced_amount = None
        course_organization = None
        price = None
        coupon_type, discount_percentage, discount_amount = None, None, None

    coupon_data = {
        'Code': 'This row applies to all vouchers',
        'Category': category_name,
        'Coupon Expiry Date': voucher.end_datetime.strftime("%b %d, %y"),
        'Coupon Name': voucher.name,
        'Coupon Start Date': voucher.start_datetime.strftime("%b %d, %y"),
        'Coupon Type': coupon_type,
        'Created By': author,
        'Create Date': history.history_date.strftime("%b %d, %y"),
        'Discount Percentage': discount_percentage,
        'Discount Amount': discount_amount,
        'Email Domains': offer.email_domains,
        'Invoiced Amount': invoiced_amount,
        'Note': note,
        'Price': price
    }

    if course_id:
        coupon_data['Course ID'] = course_id
        coupon_data['Organization'] = course_organization
    else:
        coupon_data['Catalog Query'] = catalog_query
        coupon_data['Course Seat Types'] = course_seat_types

    return coupon_data
Exemplo n.º 9
0
def _get_info_for_coupon_report(coupon, voucher):
    history = coupon.history.first()
    author = history.history_user.full_name
    category_name = ProductCategory.objects.get(product=coupon).category.name

    try:
        note = coupon.attr.note
    except AttributeError:
        note = ''

    offer = voucher.offers.first()
    if offer.condition.range.catalog:
        seat_stockrecord = offer.condition.range.catalog.stock_records.first()
        coupon_stockrecord = StockRecord.objects.get(product=coupon)
        invoiced_amount = currency(coupon_stockrecord.price_excl_tax)
        course_id = seat_stockrecord.product.attr.course_key
        course_organization = CourseKey.from_string(course_id).org
        price = currency(seat_stockrecord.price_excl_tax)
        discount_data = get_voucher_discount_info(offer.benefit, seat_stockrecord.price_excl_tax)
        coupon_type, discount_percentage, discount_amount = _get_discount_info(discount_data)
    else:
        # Note (multi-courses): Need to account for multiple seats.
        catalog_query = offer.condition.range.catalog_query
        course_seat_types = offer.condition.range.course_seat_types
        course_id = None
        invoiced_amount = None
        course_organization = None
        price = None
        coupon_type, discount_percentage, discount_amount = None, None, None

    coupon_data = {
        'Code': 'This row applies to all vouchers',
        'Category': category_name,
        'Coupon Expiry Date': voucher.end_datetime.strftime("%b %d, %y"),
        'Coupon Name': voucher.name,
        'Coupon Start Date': voucher.start_datetime.strftime("%b %d, %y"),
        'Coupon Type': coupon_type,
        'Created By': author,
        'Create Date': history.history_date.strftime("%b %d, %y"),
        'Discount Percentage': discount_percentage,
        'Discount Amount': discount_amount,
        'Invoiced Amount': invoiced_amount,
        'Note': note,
        'Price': price
    }

    if course_id:
        coupon_data['Course ID'] = course_id
        coupon_data['Organization'] = course_organization
    else:
        coupon_data['Catalog Query'] = catalog_query
        coupon_data['Course Seat Types'] = course_seat_types

    return coupon_data
Exemplo n.º 10
0
 def get_upsell_message(self, offer, basket):
     value_of_matches = self._get_value_of_matches(offer, basket)
     if value_of_matches > 0:
         return _('Spend %(value)s more from %(range)s') % {
             'value': currency(self.value - value_of_matches),
             'range': self.range
         }
Exemplo n.º 11
0
    def assert_report_row(self, row, coupon, voucher):
        """ Verify that the row fields contain the right data. """
        offer = voucher.offers.all().first()
        discount_data = get_voucher_discount_info(
            offer.benefit,
            offer.condition.range.catalog.stock_records.first().price_excl_tax)
        coupon_type = _('Discount') if discount_data['is_discounted'] else _(
            'Enrollment')
        discount_percentage = _("{percentage} %").format(
            percentage=discount_data['discount_percentage'])
        discount_amount = currency(discount_data['discount_value'])

        self.assertEqual(row['Coupon Type'], coupon_type)
        self.assertEqual(
            row['Category'],
            ProductCategory.objects.get(product=coupon).category.name)
        self.assertEqual(row['Discount Percentage'], discount_percentage)
        self.assertEqual(row['Discount Amount'], discount_amount)
        self.assertEqual(row['Client'], coupon.client.name)
        self.assertEqual(
            row['URL'],
            get_ecommerce_url() + self.REDEMPTION_URL.format(voucher.code))
        self.assertEqual(row['Note'], coupon.attr.note)
        self.assertEqual(row['Created By'],
                         coupon.history.first().history_user.full_name)
        self.assertEqual(
            row['Create Date'],
            coupon.history.latest().history_date.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Start Date'],
                         voucher.start_datetime.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Expiry Date'],
                         voucher.end_datetime.strftime("%b %d, %y"))
Exemplo n.º 12
0
 def __unicode__(self):
     description = _("Allocation of %(amount)s from type %(type)s") % {
         'amount': currency(self.amount_allocated, self.currency),
         'type': self.source_type}
     if self.reference:
         description += _(" (reference: %s)") % self.reference
     return description
Exemplo n.º 13
0
    def assert_report_first_row(self, row, coupon, voucher):
        """
        Verify that the first row fields contain the right data.
        Args:
            row (list): First row in report
            coupon (Product): Coupon for which the report is generated
            voucher (Voucher): Voucher associated with the Coupon
        """
        offer = voucher.offers.first()
        discount_data = get_voucher_discount_info(
            offer.benefit,
            offer.condition.range.catalog.stock_records.first().price_excl_tax
        )
        coupon_type = _('Discount') if discount_data['is_discounted'] else _('Enrollment')
        discount_percentage = _("{percentage} %").format(percentage=discount_data['discount_percentage'])
        discount_amount = currency(discount_data['discount_value'])

        self.assertEqual(row['Coupon Type'], coupon_type)
        self.assertEqual(row['Category'], ProductCategory.objects.get(product=coupon).category.name)
        self.assertEqual(row['Discount Percentage'], discount_percentage)
        self.assertEqual(row['Discount Amount'], discount_amount)
        self.assertEqual(row['Client'], coupon.client.name)
        self.assertEqual(row['Note'], coupon.attr.note)
        self.assertEqual(row['Created By'], coupon.history.first().history_user.full_name)
        self.assertEqual(row['Create Date'], coupon.history.latest().history_date.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Start Date'], voucher.start_datetime.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Expiry Date'], voucher.end_datetime.strftime("%b %d, %y"))
Exemplo n.º 14
0
 def clean_amount(self):
     amt = self.cleaned_data.get('amount')
     max_allocation = self.max_allocation
     if amt > max_allocation:
         raise forms.ValidationError(
             _("The maximum allocation is %s") % currency(max_allocation))
     return amt
Exemplo n.º 15
0
def get_messages(basket, offers_before, offers_after):
    """
    Return the messages about offer changes
    """
    # Look for changes in offers
    offers_lost = set(offers_before.keys()).difference(
        set(offers_after.keys()))
    offers_gained = set(offers_after.keys()).difference(
        set(offers_before.keys()))
    offer_messages = {messages.INFO: [],
                      messages.SUCCESS: [],
                      messages.WARNING: []}
    for offer_id in offers_lost:
        offer = offers_before[offer_id]
        offer_messages[messages.WARNING].append(
            _("Your basket no longer qualifies for the '%s' offer") % offer)
    for offer_id in offers_gained:
        offer = offers_after[offer_id]
        offer_messages[messages.SUCCESS].append(
            _("Your basket now qualifies for the '%s' offer") % offer)
    if not offers_lost and not offers_gained:
        msg = _("Basket total now %(total)s") % {
            'total': currency(basket.total_incl_tax)}
        offer_messages[messages.INFO].append(msg)

    return offer_messages
Exemplo n.º 16
0
def get_messages(basket, offers_before, offers_after):
    """
    Return the messages about offer changes
    """
    # Look for changes in offers
    offers_lost = set(offers_before.keys()).difference(set(
        offers_after.keys()))
    offers_gained = set(offers_after.keys()).difference(
        set(offers_before.keys()))
    offer_messages = {
        messages.INFO: [],
        messages.SUCCESS: [],
        messages.WARNING: []
    }
    for offer_id in offers_lost:
        offer = offers_before[offer_id]
        offer_messages[messages.WARNING].append(
            _("Your basket no longer qualifies for the '%s' offer") % offer)
    for offer_id in offers_gained:
        offer = offers_after[offer_id]
        offer_messages[messages.SUCCESS].append(
            _("Your basket now qualifies for the '%s' offer") % offer)
    if not offers_lost and not offers_gained:
        msg = _("Basket total now %(total)s") % {
            'total': currency(basket.total_incl_tax)
        }
        offer_messages[messages.INFO].append(msg)

    return offer_messages
Exemplo n.º 17
0
 def clean_amount(self):
     amt = self.cleaned_data['amount']
     max_amount = self.account.balance
     if amt > max_amount:
         raise forms.ValidationError(
             _("The account has only %s") % (currency(max_amount)))
     return amt
Exemplo n.º 18
0
    def assert_report_first_row(self, row, coupon, voucher):
        """
        Verify that the first row fields contain the right data.
        Args:
            row (list): First row in report
            coupon (Product): Coupon for which the report is generated
            voucher (Voucher): Voucher associated with the Coupon
        """
        offer = voucher.offers.first()
        discount_data = get_voucher_discount_info(
            offer.benefit,
            offer.condition.range.catalog.stock_records.first().price_excl_tax)
        coupon_type = _('Discount') if discount_data['is_discounted'] else _(
            'Enrollment')
        discount_percentage = _("{percentage} %").format(
            percentage=discount_data['discount_percentage'])
        discount_amount = currency(discount_data['discount_value'])

        self.assertEqual(row['Coupon Type'], coupon_type)
        self.assertEqual(
            row['Category'],
            ProductCategory.objects.get(product=coupon).category.name)
        self.assertEqual(row['Discount Percentage'], discount_percentage)
        self.assertEqual(row['Discount Amount'], discount_amount)
        self.assertEqual(row['Client'], coupon.client.name)
        self.assertEqual(row['Note'], coupon.attr.note)
        self.assertEqual(row['Created By'],
                         coupon.history.first().history_user.full_name)
        self.assertEqual(
            row['Create Date'],
            coupon.history.latest().history_date.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Start Date'],
                         voucher.start_datetime.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Expiry Date'],
                         voucher.end_datetime.strftime("%b %d, %y"))
Exemplo n.º 19
0
    def assert_report_row(self, row, coupon, voucher):
        """ Verify that the row fields contain the right data. """
        offer = voucher.offers.all().first()
        discount_data = get_voucher_discount_info(
            offer.benefit,
            offer.condition.range.catalog.stock_records.first().price_excl_tax
        )
        coupon_type = _('Discount') if discount_data['is_discounted'] else _('Enrollment')
        discount_percentage = _("{percentage} %").format(percentage=discount_data['discount_percentage'])
        discount_amount = currency(discount_data['discount_value'])

        self.assertEqual(row['Coupon Type'], coupon_type)
        self.assertEqual(row['Category'], ProductCategory.objects.get(product=coupon).category.name)
        self.assertEqual(row['Discount Percentage'], discount_percentage)
        self.assertEqual(row['Discount Amount'], discount_amount)
        self.assertEqual(row['Client'], coupon.client.name)
        self.assertEqual(
            row['URL'],
            get_ecommerce_url() + self.REDEMPTION_URL.format(voucher.code)
        )
        self.assertEqual(row['Note'], coupon.attr.note)
        self.assertEqual(row['Created By'], coupon.history.first().history_user.full_name)
        self.assertEqual(row['Create Date'], coupon.history.latest().history_date.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Start Date'], voucher.start_datetime.strftime("%b %d, %y"))
        self.assertEqual(row['Coupon Expiry Date'], voucher.end_datetime.strftime("%b %d, %y"))
Exemplo n.º 20
0
 def __footer_line(self):
     canvas = self.canv
     current_y, current_x = self.current_y, self.current_x
     current_y -= 2 * inch
     canvas.setFont(DEFAULT_FONTNAME, LARGE_FONTSIZE)
     canvas.setFillColor(colors.black)
     canvas.drawString(current_x, current_y, 'Invoice Number')
     canvas.drawString(PAGE_WIDTH/4, current_y, 'Invoice Date')
     canvas.drawString((PAGE_WIDTH/4) * 2, current_y, 'GST included')
     canvas.drawString((PAGE_WIDTH/4) * 3, current_y, 'Invoice Total')
     current_y -= 20
     canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE)
     canvas.drawString(current_x, current_y, self.invoice.reference)
     canvas.drawString(PAGE_WIDTH/4, current_y, self.invoice.created.strftime(DATE_FORMAT))
     canvas.drawString((PAGE_WIDTH/4) * 2, current_y, currency(self.invoice.amount - calculate_excl_gst(self.invoice.amount)))
     canvas.drawString((PAGE_WIDTH/4) * 3, current_y, currency(self.invoice.amount))
Exemplo n.º 21
0
def form_valid(form, request):
    # O formulario foi validado e o obj do type ferramenta foi criado
    object = form.save()
    ferramenta = object

    account = get_imported_user_account(form)
    amount = ferramenta.value
    try:
        transfer = facade.transfer(
            get_imported_source_account(),
            account,
            amount,
            user=form.cleaned_data.get("user"),
            description=
            _(f"Inserção da Ferramenta via arquivo de solicitações: {ferramenta.name}"
              ),
        )
        ferramenta.transfer = transfer
        ferramenta.save()
    except exceptions.AccountException as e:
        messages.error(
            resquest,
            _("Tive um problema para processar o arquivo de solicitação, procure o mario: %s"
              ) % e,
        )
    else:
        messages.success(
            request,
            _("%s adicionado ao seu saldo via arquivo de solicitações") %
            currency(amount))

    return render(request, 'import.html')
Exemplo n.º 22
0
    def test_format_benefit_value(self):
        """ format_benefit_value(benefit) should format benefit value based on benefit type """
        benefit_value = format_benefit_value(self.percentage_benefit)
        self.assertEqual(benefit_value, '35%')

        benefit_value = format_benefit_value(self.value_benefit)
        self.assertEqual(benefit_value, currency(self.seat_price - 10))
Exemplo n.º 23
0
 def __unicode__(self):
     description = _("Allocation of %(amount)s from type %(type)s") % {
         'amount': currency(self.amount_allocated, self.currency),
         'type': self.source_type}
     if self.reference:
         description += _(" (reference: %s)") % self.reference
     return description
Exemplo n.º 24
0
    def test_format_benefit_value(self):
        """ format_benefit_value(benefit) should format benefit value based on benefit type """
        benefit_value = format_benefit_value(self.percentage_benefit)
        self.assertEqual(benefit_value, '35%')

        benefit_value = format_benefit_value(self.value_benefit)
        self.assertEqual(benefit_value, currency(self.seat_price - 10))
Exemplo n.º 25
0
 def __footer_line(self):
     canvas = self.canv
     current_y, current_x = self.current_y, self.current_x
     current_y -= 2 * inch
     canvas.setFont(DEFAULT_FONTNAME, LARGE_FONTSIZE)
     canvas.setFillColor(colors.black)
     canvas.drawString(current_x, current_y, 'Invoice Number')
     canvas.drawString(PAGE_WIDTH/4, current_y, 'Invoice Date')
     canvas.drawString((PAGE_WIDTH/4) * 2, current_y, 'GST included')
     canvas.drawString((PAGE_WIDTH/4) * 3, current_y, 'Invoice Total')
     current_y -= 20
     canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE)
     canvas.drawString(current_x, current_y, self.invoice.reference)
     canvas.drawString(PAGE_WIDTH/4, current_y, self.invoice.created.strftime(DATE_FORMAT))
     canvas.drawString((PAGE_WIDTH/4) * 2, current_y, currency(self.invoice.amount - calculate_excl_gst(self.invoice.amount)))
     canvas.drawString((PAGE_WIDTH/4) * 3, current_y, currency(self.invoice.amount))
Exemplo n.º 26
0
    def form_valid(self, form):
        # O formulario foi validado e o obj do type ferramenta foi criado
        self.object = form.save()
        ferramenta = self.object

        account = self._get_user_account(form)
        amount = ferramenta.value
        try:
            transfer = facade.transfer(
                self._get_source_account(),
                account,
                amount,
                user=form.cleaned_data.get("user"),
                description=_(f"Inserção da Ferramenta: {ferramenta.name}"),
            )
            ferramenta.transfer = transfer
            ferramenta.save()
        except exceptions.AccountException as e:
            messages.error(
                self.request,
                _("Tive um problema para inserir a sua ferramenta, procure o mario: %s"
                  ) % e,
            )
        else:
            messages.success(
                self.request,
                _("%s adicionado ao seu saldo") % currency(amount))

        return HttpResponseRedirect(self.get_success_url())
Exemplo n.º 27
0
 def get_upsell_message(self, offer, basket):
     value_of_matches = self._get_value_of_matches(offer, basket)
     delta = self.value - value_of_matches
     if delta > 0:
         return _('Spend %(value)s more from %(range)s') % {
             'value': currency(delta, basket.currency),
             'range': self.range,
         }
Exemplo n.º 28
0
 def clean_amount(self):
     amt = self.cleaned_data['amount']
     max_amount = settings.ACCOUNTS_MAX_ACCOUNT_VALUE - self.account.balance
     if amt > max_amount:
         raise forms.ValidationError(_(
             "The maximum permitted top-up amount is %s") % (
                 currency(max_amount)))
     return amt
Exemplo n.º 29
0
 def clean_amount(self):
     amt = self.cleaned_data['amount']
     max_amount = settings.ACCOUNTS_MAX_ACCOUNT_VALUE - self.account.balance
     if amt > max_amount:
         raise forms.ValidationError(
             _("The maximum permitted top-up amount is %s") %
             (currency(max_amount)))
     return amt
Exemplo n.º 30
0
 def clean_amount(self):
     amt = self.cleaned_data['amount']
     max_amount = self.account.balance
     if amt > max_amount:
         raise forms.ValidationError(_(
             "The account has only %s") % (
                 currency(max_amount)))
     return amt
Exemplo n.º 31
0
 def get_upsell_message(self, offer, basket):
     value_of_matches = self._get_value_of_matches(offer, basket)
     condition_value = self.get_condition_value(basket)
     return _('Spend %(value)s more from %(range)s') % {
         'value': currency(condition_value - value_of_matches,
                           self.currency),
         'range': self.range
     }
Exemplo n.º 32
0
 def clean_amount(self):
     amt = self.cleaned_data.get('amount')
     max_allocation = self.max_allocation
     if amt > max_allocation:
         raise forms.ValidationError(_(
             "The maximum allocation is %s") % currency(
                 max_allocation))
     return amt
Exemplo n.º 33
0
 def __str__(self):
     description = _(
         "You chose to pay an amount of %(amount)s via %(type)s") % {
             'amount': currency(self.amount_allocated, self.currency),
             'type': self.source_type
         }
     if self.reference:
         description += _(" (reference: %s)") % self.reference
     return description
Exemplo n.º 34
0
 def __unicode__(self):
     if self.type == self.COUNT:
         return _("Basket includes %(count)d item(s) from %(range)s") % {
             'count': self.value, 'range': unicode(self.range).lower()}
     elif self.type == self.COVERAGE:
         return _("Basket includes %(count)d distinct products from %(range)s") % {
             'count': self.value, 'range': unicode(self.range).lower()}
     return _("Basket includes %(amount)s from %(range)s") % {
         'amount': currency(self.value),
         'range': unicode(self.range).lower()}
Exemplo n.º 35
0
 def name(self):
     return self._description % {
         'amount':
         currency(self.value),
         'tax':
         _('tax-inclusive') if self._tax_inclusive else _('tax-exclusive'),
         'range':
         six.text_type(self.range).lower()
         if self.range else _('product range')
     }
Exemplo n.º 36
0
 def description(self):
     return self._description % {
         'amount':
         currency(self.value),
         'tax':
         _('tax-inclusive') if self._tax_inclusive else _('tax-exclusive'),
         'range':
         utils.range_anchor(self.range)
         if self.range else _('product range')
     }
Exemplo n.º 37
0
    def availability_restrictions(self):
        restrictions = []
        if self.is_suspended:
            restrictions.append({"description": _("Offer is suspended"), "is_satisfied": False})

        if self.max_global_applications:
            remaining = self.max_global_applications - self.num_applications
            desc = _("Limited to %(total)d uses " "(%(remainder)d remaining)") % {
                "total": self.max_global_applications,
                "remainder": remaining,
            }
            restrictions.append({"description": desc, "is_satisfied": remaining > 0})

        if self.max_user_applications:
            if self.max_user_applications == 1:
                desc = _("Limited to 1 use per user")
            else:
                desc = _("Limited to %(total)d uses per user") % {"total": self.max_user_applications}
            restrictions.append({"description": desc, "is_satisfied": True})

        if self.max_basket_applications:
            if self.max_user_applications == 1:
                desc = _("Limited to 1 use per basket")
            else:
                desc = _("Limited to %(total)d uses per basket") % {"total": self.max_basket_applications}
            restrictions.append({"description": desc, "is_satisfied": True})

        def hide_time_if_zero(dt):
            # Only show hours/minutes if they have been specified
            localtime = dt.astimezone(get_current_timezone())
            if localtime.hour == 0 and localtime.minute == 0:
                return date_filter(localtime, settings.DATE_FORMAT)
            return date_filter(localtime, settings.DATETIME_FORMAT)

        if self.start_datetime or self.end_datetime:
            today = now()
            if self.start_datetime and self.end_datetime:
                desc = _("Available between %(start)s and %(end)s") % {
                    "start": hide_time_if_zero(self.start_datetime),
                    "end": hide_time_if_zero(self.end_datetime),
                }
                is_satisfied = self.start_datetime <= today <= self.end_datetime
            elif self.start_datetime:
                desc = _("Available from %(start)s") % {"start": hide_time_if_zero(self.start_datetime)}
                is_satisfied = today >= self.start_datetime
            elif self.end_datetime:
                desc = _("Available until %(end)s") % {"end": hide_time_if_zero(self.end_datetime)}
                is_satisfied = today <= self.end_datetime
            restrictions.append({"description": desc, "is_satisfied": is_satisfied})

        if self.max_discount:
            desc = _("Limited to a cost of %(max)s") % {"max": currency(self.max_discount)}
            restrictions.append({"description": desc, "is_satisfied": self.total_discount < self.max_discount})

        return restrictions
Exemplo n.º 38
0
 def form_valid(self, form):
     account = self.object
     amount = form.cleaned_data['amount']
     try:
         facade.transfer(form.get_source_account(), account, amount,
                         user=self.request.user,
                         description=_("Top-up account"))
     except exceptions.AccountException as e:
         messages.error(self.request,
                        _("Unable to top-up account: %s") % e)
     else:
         messages.success(
             self.request, _("%s added to account") % currency(amount))
     return http.HttpResponseRedirect(reverse('accounts-detail',
                                              kwargs={'pk': account.id}))
 def form_valid(self, form):
     account = self.object
     amount = form.cleaned_data['amount']
     try:
         facade.transfer(form.get_source_account(), account, amount,
                         user=self.request.user,
                         description=_("Top-up account"))
     except exceptions.AccountException as e:
         messages.error(self.request,
                        _("Unable to top-up account: %s") % e)
     else:
         messages.success(
             self.request, _("%s added to account") % currency(amount))
     return http.HttpResponseRedirect(reverse('accounts-detail',
                                              kwargs={'pk': account.id}))
Exemplo n.º 40
0
 def form_valid(self, form):
     account = self.object
     amount = form.cleaned_data['amount']
     try:
         facade.transfer(account, form.get_source_account(), amount,
                         user=self.request.user,
                         description=_("Return funds to source account"))
     except exceptions.AccountException as e:
         messages.error(self.request,
                        _("Unable to withdraw funds from account: %s") % e)
     else:
         messages.success(
             self.request,
             _("%s withdrawn from account") % currency(amount))
     return http.HttpResponseRedirect(reverse('dashboard:accounts-detail',
                                              kwargs={'pk': account.id}))
Exemplo n.º 41
0
 def form_valid(self, form):
     account = self.object
     amount = form.cleaned_data['amount']
     try:
         facade.transfer(account, form.get_source_account(), amount,
                         user=self.request.user,
                         description=_("Return funds to source account"))
     except exceptions.AccountException as e:
         messages.error(self.request,
                        _("Unable to withdraw funds from account: %s") % e)
     else:
         messages.success(
             self.request,
             _("%s withdrawn from account") % currency(amount))
     return http.HttpResponseRedirect(reverse('accounts_dashboard:accounts-detail',
                                              kwargs={'pk': account.id}))
Exemplo n.º 42
0
 def _create_group_product_fields(self, item):
     """
     Adds the fields for a "group"-type product (eg, a parent product with a
     list of variants.
     """
     choices = []
     for variant in item.variants.all():
         if variant.has_stockrecord:
             attr_summary = variant.attribute_summary()
             if attr_summary:
                 attr_summary = "(%s)" % attr_summary
             summary = u"%s %s - %s" % (variant.get_title(), attr_summary,
                                        currency(variant.stockrecord.price_incl_tax))
             choices.append((variant.id, summary))
     self.fields['product_id'] = forms.ChoiceField(choices=tuple(choices),
                                                   label="Variant")
Exemplo n.º 43
0
 def _create_group_product_fields(self, item):
     """
     Adds the fields for a "group"-type product (eg, a parent product with a
     list of variants.
     """
     choices = []
     for variant in item.variants.all():
         if variant.has_stockrecord:
             attr_summary = variant.attribute_summary()
             if attr_summary:
                 attr_summary = "(%s)" % attr_summary
                 summary = u"%s %s - %s" % (
                     variant.get_title(), attr_summary,
                     currency(variant.stockrecord.price_incl_tax))
                 choices.append((variant.id, summary))
                 self.fields['product_id'] = forms.ChoiceField(
                     choices=tuple(choices), label=_("Variant"))
Exemplo n.º 44
0
 def availability_description(self):
     """
     Return a description of when this offer is available
     """
     sentences = []
     if self.max_global_applications:
         desc = _("Can be used %(total)d times "
                  "(%(remainder)d remaining)") % {
                      'total': self.max_global_applications,
                      'remainder':
                      self.max_global_applications - self.num_applications
                  }
         sentences.append(desc)
     if self.max_user_applications:
         if self.max_user_applications == 1:
             desc = _("Can be used once per user")
         else:
             desc = _("Can be used %(total)d times per user") % {
                 'total': self.max_user_applications
             }
         sentences.append(desc)
     if self.max_basket_applications:
         if self.max_user_applications == 1:
             desc = _("Can be used once per basket")
         else:
             desc = _("Can be used %(total)d times per basket") % {
                 'total': self.max_basket_applications
             }
         sentences.append(desc)
     if self.start_date and self.end_date:
         desc = _("Available between %(start)s and %(end)s") % {
             'start': self.start_date,
             'end': self.end_date
         }
         sentences.append(desc)
     elif self.start_date:
         sentences.append(
             _("Available until %(start)s") % {'start': self.start_date})
     elif self.end_date:
         sentences.append(
             _("Available until %(end)s") % {'end': self.end_date})
     if self.max_discount:
         sentences.append(
             _("Available until a discount of %(max)s "
               "has been awarded") % {'max': currency(self.max_discount)})
     return "<br/>".join(sentences)
Exemplo n.º 45
0
def _get_discount_info(discount_data):
    """Retrieve voucher discount info.

    Arguments:
        discount_data (dict)

    Returns
        coupon_type (str)
        discount_amount (str)
        discount_percentage (str)
    """
    if discount_data:
        coupon_type = _('Discount') if discount_data['is_discounted'] else _('Enrollment')
        discount_percentage = _("{percentage} %").format(percentage=discount_data['discount_percentage'])
        discount_amount = currency(discount_data['discount_value'])
        return coupon_type, discount_percentage, discount_amount
    logger.warning('Unable to get voucher discount info. Discount data not provided.')
    return None, None, None
Exemplo n.º 46
0
def _get_discount_info(discount_data):
    """Retrieve voucher discount info.

    Arguments:
        discount_data (dict)

    Returns
        coupon_type (str)
        discount_amount (str)
        discount_percentage (str)
    """
    if discount_data:
        coupon_type = _('Discount') if discount_data['is_discounted'] else _('Enrollment')
        discount_percentage = _("{percentage} %").format(percentage=discount_data['discount_percentage'])
        discount_amount = currency(discount_data['discount_value'])
        return coupon_type, discount_percentage, discount_amount
    logger.warning('Unable to get voucher discount info. Discount data not provided.')
    return None, None, None
Exemplo n.º 47
0
 def availability_description(self):
     """
     Return a description of when this offer is available
     """
     sentences = []
     if self.max_global_applications:
         desc = _(
             "Can be used %(total)d times "
             "(%(remainder)d remaining)") % {
                 'total': self.max_global_applications,
                 'remainder': self.max_global_applications - self.num_applications}
         sentences.append(desc)
     if self.max_user_applications:
         if self.max_user_applications == 1:
             desc = _("Can be used once per user")
         else:
             desc = _(
                 "Can be used %(total)d times per user") % {
                     'total': self.max_user_applications}
         sentences.append(desc)
     if self.max_basket_applications:
         if self.max_user_applications == 1:
             desc = _("Can be used once per basket")
         else:
             desc = _(
                 "Can be used %(total)d times per basket") % {
                     'total': self.max_basket_applications}
         sentences.append(desc)
     if self.start_date and self.end_date:
         desc = _("Available between %(start)s and %(end)s") % {
                 'start': self.start_date,
                 'end': self.end_date}
         sentences.append(desc)
     elif self.start_date:
         sentences.append(_("Available until %(start)s") % {
             'start': self.start_date})
     elif self.end_date:
         sentences.append(_("Available until %(end)s") % {
             'end': self.end_date})
     if self.max_discount:
         sentences.append(_("Available until a discount of %(max)s "
                            "has been awarded") % {
             'max': currency(self.max_discount)})
     return "<br/>".join(sentences)
Exemplo n.º 48
0
def format_benefit_value(benefit):
    """
    Format benefit value for display based on the benefit type

    Arguments:
        benefit (Benefit): Benefit to be displayed

    Returns:
        benefit_value (str): String value containing formatted benefit value and type.
    """
    benefit_value = _remove_exponent_and_trailing_zeros(
        Decimal(str(benefit.value)))
    if benefit.type == Benefit.PERCENTAGE:
        benefit_value = _(
            '{benefit_value}%'.format(benefit_value=benefit_value))
    else:
        benefit_value = _(
            '{benefit_value}'.format(benefit_value=currency(benefit_value)))
    return benefit_value
Exemplo n.º 49
0
    def _create_group_product_fields(self, item):
        """
        Adds the fields for a "group"-type product (eg, a parent product with a
        list of variants.

        Currently requires that a stock record exists for the variant
        """
        choices = []
        for variant in item.variants.all():
            if variant.has_stockrecord:
                title = variant.get_title()
                attr_summary = variant.attribute_summary
                price = currency(variant.stockrecord.price_incl_tax)
                if attr_summary:
                    summary = u"%s (%s) - %s" % (title, attr_summary, price)
                else:
                    summary = u"%s - %s" % (title, price)
                choices.append((variant.id, summary))
                self.fields['product_id'] = forms.ChoiceField(
                    choices=tuple(choices), label=_("Variant"))
Exemplo n.º 50
0
    def _create_group_product_fields(self, item):
        """
        Adds the fields for a "group"-type product (eg, a parent product with a
        list of variants.

        Currently requires that a stock record exists for the variant
        """
        choices = []
        for variant in item.variants.all():
            if variant.has_stockrecord:
                title = variant.get_title()
                attr_summary = variant.attribute_summary
                price = currency(variant.stockrecord.price_incl_tax)
                if attr_summary:
                    summary = u"%s (%s) - %s" % (title, attr_summary, price)
                else:
                    summary = u"%s - %s" % (title, price)
                choices.append((variant.id, summary))
                self.fields['product_id'] = forms.ChoiceField(
                    choices=tuple(choices), label=_("Variant"))
Exemplo n.º 51
0
 def get_upsell_message(self, basket):
     value_of_matches = self._get_value_of_matches(basket)
     return _("Spend %(value)s more from %(range)s") % {
         "value": currency(self.value - value_of_matches),
         "range": self.range,
     }
Exemplo n.º 52
0
 def description(self):
     return self._description % {"amount": currency(self.value), "range": range_anchor(self.range)}
Exemplo n.º 53
0
 def name(self):
     return self._description % {"amount": currency(self.value), "range": unicode(self.range).lower()}
Exemplo n.º 54
0
 def description(self):
     return self._description % {"amount": currency(self.value)}
Exemplo n.º 55
0
 def __unicode__(self):
     return self._description % {"amount": currency(self.value)}
Exemplo n.º 56
0
 def name(self):
     return self._description % {"value": currency(self.value), "range": self.range.name.lower()}
Exemplo n.º 57
0
    template_name = 'accounts/dashboard/account_top_up.html'
    form_class = forms.TopUpAccountForm

    def form_valid(self, form):
        account = self.object
        amount = form.cleaned_data['amount']
        try:
            facade.transfer(form.get_source_account(), account, amount,
                            user=self.request.user,
                            description=_("Top-up account"))
        except exceptions.AccountException, e:
            messages.error(self.request,
                           _("Unable to top-up account: %s") % e)
        else:
            messages.success(
                self.request, _("%s added to account") % currency(amount))
        return http.HttpResponseRedirect(reverse('accounts-detail',
                                                 kwargs={'pk': account.id}))

    def get_success_url(self):
        messages.success(self.request, _("Account re-opened"))
        return reverse('accounts-list')


class AccountTransactionsView(generic.ListView):
    model = Transaction
    context_object_name = 'transactions'
    template_name = 'accounts/dashboard/account_detail.html'

    def get(self, request, *args, **kwargs):
        self.account = get_object_or_404(Account, id=kwargs['pk'])
Exemplo n.º 58
0
 def description(self):
     return self._description % {
         'amount': currency(self.value),
         'range': range_anchor(self.range)
     }
Exemplo n.º 59
0
def _get_info_for_coupon_report(coupon, voucher):
    offer = voucher.offers.all().first()
    if offer.condition.range.catalog:
        coupon_stockrecord = StockRecord.objects.get(product=coupon)
        invoiced_amount = currency(coupon_stockrecord.price_excl_tax)
        seat_stockrecord = offer.condition.range.catalog.stock_records.first()
        course_id = seat_stockrecord.product.attr.course_key
        course_organization = CourseKey.from_string(course_id).org
        price = currency(seat_stockrecord.price_excl_tax)
        discount_data = get_voucher_discount_info(offer.benefit, seat_stockrecord.price_excl_tax)
    else:
        # Note (multi-courses): Need to account for multiple seats.
        catalog_query = offer.condition.range.catalog_query
        course_seat_types = offer.condition.range.course_seat_types
        course_id = None
        coupon_stockrecord = None
        invoiced_amount = None
        seat_stockrecord = None
        course_organization = None
        price = None
        discount_data = None

    history = coupon.history.first()
    coupon_type, discount_percentage, discount_amount = _get_discount_info(discount_data)
    status = _get_voucher_status(voucher, offer)
    path = '{path}?code={code}'.format(path=reverse('coupons:offer'), code=voucher.code)
    url = get_ecommerce_url(path)
    author = history.history_user.full_name.encode('utf8')

    try:
        note = coupon.attr.note.encode('utf8')
    except AttributeError:
        note = ''

    product_categories = ProductCategory.objects.filter(product=coupon)
    if product_categories:
        category_names = ', '.join([pc.category.name for pc in product_categories])
    else:
        category_names = ''

    # Set the max_uses_count for single-use vouchers to 1,
    # for other usage limitations (once per customer and multi-use)
    # which don't have the max global applications limit set,
    # set the max_uses_count to 10000 which is the arbitrary limit Oscar sets:
    # https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/offer/abstract_models.py#L253
    redemption_count = offer.num_applications
    if voucher.usage == Voucher.SINGLE_USE:
        max_uses_count = 1
        redemption_count = voucher.num_orders
    elif voucher.usage != Voucher.SINGLE_USE and offer.max_global_applications is None:
        max_uses_count = 10000
    else:
        max_uses_count = offer.max_global_applications

    coupon_data = {
        'Coupon Name': voucher.name.encode('utf8'),
        'Code': voucher.code,
        'Coupon Type': coupon_type,
        'URL': url,
        'Category': category_names,
        'Note': note,
        'Price': price,
        'Invoiced Amount': invoiced_amount,
        'Discount Percentage': discount_percentage,
        'Discount Amount': discount_amount,
        'Status': status,
        'Created By': author,
        'Create Date': history.history_date.strftime("%b %d, %y"),
        'Coupon Start Date': voucher.start_datetime.strftime("%b %d, %y"),
        'Coupon Expiry Date': voucher.end_datetime.strftime("%b %d, %y"),
        'Maximum Coupon Usage': max_uses_count,
        'Redemption Count': redemption_count,
    }

    if course_id:
        coupon_data['Course ID'] = course_id
        coupon_data['Organization'] = course_organization
    else:
        coupon_data['Catalog Query'] = catalog_query
        coupon_data['Course Seat Types'] = course_seat_types

    return coupon_data