<commit_before>"""Voucher Utility Methods. """
import base64
import datetime
import hashlib
import logging
import uuid
import pytz

from django.conf import settings
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
from oscar.core.loading import get_model
from oscar.templatetags.currency_filters import currency
from edx_rest_api_client.client import EdxRestApiClient

from ecommerce.core.url_utils import get_ecommerce_url, get_lms_url
from ecommerce.invoice.models import Invoice

logger = logging.getLogger(__name__)

Basket = get_model('basket', 'Basket')
Benefit = get_model('offer', 'Benefit')
Condition = get_model('offer', 'Condition')
ConditionalOffer = get_model('offer', 'ConditionalOffer')
CouponVouchers = get_model('voucher', 'CouponVouchers')
Order = get_model('order', 'Order')
Product = get_model('catalogue', 'Product')
ProductCategory = get_model('catalogue', 'ProductCategory')
Range = get_model('offer', 'Range')
StockRecord = get_model('partner', 'StockRecord')
Voucher = get_model('voucher', 'Voucher')
VoucherApplication = get_model('voucher', 'VoucherApplication')


def generate_coupon_report(coupon_vouchers):
    """
    Generate coupon report data

    Args:
        coupon_vouchers (List[CouponVouchers]): List of coupon_vouchers the report should be generated for

    Returns:
        List[str]
        List[dict]
    """

    field_names = [
        _('Coupon Name'),
        _('Code'),
        _('Coupon Type'),
        _('URL'),
        _('CourseID'),
        _('Partner'),
        _('Client'),
        _('Category'),
        _('Note'),
        _('Price'),
        _('Invoiced Amount'),
        _('Discount Percentage'),
        _('Discount Amount'),
        _('Status'),
        _('Redeemed By ID'),
        _('Redeemed By Username'),
        _('Created By'),
        _('Create Date'),
        _('Coupon Start Date'),
        _('Coupon Expiry Date'),
    ]
    rows = []

    for coupon_voucher in coupon_vouchers:
        coupon = coupon_voucher.coupon

        # Get client based on the invoice that was created during coupon creation
        basket = Basket.objects.filter(lines__product_id=coupon.id).first()
        try:
            order = get_object_or_404(Order, basket=basket)
            invoice = get_object_or_404(Invoice, order=order)
            client = invoice.client.name
        except Http404:
            client = basket.owner.username

        for voucher in coupon_voucher.vouchers.all():
            offer = voucher.offers.all().first()

            stockrecords = offer.condition.range.catalog.stock_records.all()
            course_seat = Product.objects.filter(id__in=[sr.product.id for sr in stockrecords]).first()
            seat_stockrecord = course_seat.stockrecords.first()
            history = coupon.history.latest()

            coupon_stockrecord = StockRecord.objects.get(product=coupon)
            course_id = course_seat.course.id
            api = EdxRestApiClient(get_lms_url('api/courses/v1/'))
            course_organization = api.courses(course_id).get()['org']

            price = currency(seat_stockrecord.price_excl_tax)
            invoiced_amount = currency(coupon_stockrecord.price_excl_tax)
            datetime_now = pytz.utc.localize(datetime.datetime.now())
            in_datetime_interval = (
                voucher.start_datetime < datetime_now and
                voucher.end_datetime > datetime_now
            )
            discount_data = get_voucher_discount_info(offer.benefit, seat_stockrecord.price_excl_tax)
            coupon_type = _('Discount') if discount_data['is_discounted'] else _('Enrollment')
            if in_datetime_interval:
                status = _('Redeemed') if voucher.num_orders > 0 else _('Active')
            else:
                status = _('Inactive')

            discount_percentage = _("{percentage} %").format(percentage=discount_data['discount_percentage'])
            discount_amount = currency(discount_data['discount_percentage'])

            if voucher.num_orders > 0:
                voucher_applications = VoucherApplication.objects.filter(voucher=voucher).all()
                redemption_users = [application.user for application in voucher_applications]
                redemption_user_ids = ', '.join([str(user.id) for user in redemption_users])
                redemption_user_usernames = ', '.join([user.username for user in redemption_users])
            else:
                redemption_user_ids = redemption_user_usernames = ''

            URL = '{url}?code={code}'.format(url=get_ecommerce_url('/coupons/offer/'), code=voucher.code)
            author = history.history_user.full_name

            try:
                note = coupon.attr.note
            except AttributeError:
                note = ''<commit_msg>[SOL-1723] Fix the discount amount error in the Voucher Report<commit_after>"""Voucher Utility Methods. """
import base64
import datetime
import hashlib
import logging
import uuid
import pytz

from django.conf import settings
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
from oscar.core.loading import get_model
from oscar.templatetags.currency_filters import currency
from edx_rest_api_client.client import EdxRestApiClient

from ecommerce.core.url_utils import get_ecommerce_url, get_lms_url
from ecommerce.invoice.models import Invoice

logger = logging.getLogger(__name__)

Basket = get_model('basket', 'Basket')
Benefit = get_model('offer', 'Benefit')
Condition = get_model('offer', 'Condition')
ConditionalOffer = get_model('offer', 'ConditionalOffer')
CouponVouchers = get_model('voucher', 'CouponVouchers')
Order = get_model('order', 'Order')
Product = get_model('catalogue', 'Product')
ProductCategory = get_model('catalogue', 'ProductCategory')
Range = get_model('offer', 'Range')
StockRecord = get_model('partner', 'StockRecord')
Voucher = get_model('voucher', 'Voucher')
VoucherApplication = get_model('voucher', 'VoucherApplication')


def generate_coupon_report(coupon_vouchers):
    """
    Generate coupon report data

    Args:
        coupon_vouchers (List[CouponVouchers]): List of coupon_vouchers the report should be generated for

    Returns:
        List[str]
        List[dict]
    """

    field_names = [
        _('Coupon Name'),
        _('Code'),
        _('Coupon Type'),
        _('URL'),
        _('CourseID'),
        _('Partner'),
        _('Client'),
        _('Category'),
        _('Note'),
        _('Price'),
        _('Invoiced Amount'),
        _('Discount Percentage'),
        _('Discount Amount'),
        _('Status'),
        _('Redeemed By ID'),
        _('Redeemed By Username'),
        _('Created By'),
        _('Create Date'),
        _('Coupon Start Date'),
        _('Coupon Expiry Date'),
    ]
    rows = []

    for coupon_voucher in coupon_vouchers:
        coupon = coupon_voucher.coupon

        # Get client based on the invoice that was created during coupon creation
        basket = Basket.objects.filter(lines__product_id=coupon.id).first()
        try:
            order = get_object_or_404(Order, basket=basket)
            invoice = get_object_or_404(Invoice, order=order)
            client = invoice.client.name
        except Http404:
            client = basket.owner.username

        for voucher in coupon_voucher.vouchers.all():
            offer = voucher.offers.all().first()

            stockrecords = offer.condition.range.catalog.stock_records.all()
            course_seat = Product.objects.filter(id__in=[sr.product.id for sr in stockrecords]).first()
            seat_stockrecord = course_seat.stockrecords.first()
            history = coupon.history.latest()

            coupon_stockrecord = StockRecord.objects.get(product=coupon)
            course_id = course_seat.course.id
            api = EdxRestApiClient(get_lms_url('api/courses/v1/'))
            course_organization = api.courses(course_id).get()['org']

            price = currency(seat_stockrecord.price_excl_tax)
            invoiced_amount = currency(coupon_stockrecord.price_excl_tax)
            datetime_now = pytz.utc.localize(datetime.datetime.now())
            in_datetime_interval = (
                voucher.start_datetime < datetime_now and
                voucher.end_datetime > datetime_now
            )
            discount_data = get_voucher_discount_info(offer.benefit, seat_stockrecord.price_excl_tax)
            coupon_type = _('Discount') if discount_data['is_discounted'] else _('Enrollment')
            if in_datetime_interval:
                status = _('Redeemed') if voucher.num_orders > 0 else _('Active')
            else:
                status = _('Inactive')

            discount_percentage = _("{percentage} %").format(percentage=discount_data['discount_percentage'])
            discount_amount = currency(discount_data['discount_value'])

            if voucher.num_orders > 0:
                voucher_applications = VoucherApplication.objects.filter(voucher=voucher).all()
                redemption_users = [application.user for application in voucher_applications]
                redemption_user_ids = ', '.join([str(user.id) for user in redemption_users])
                redemption_user_usernames = ', '.join([user.username for user in redemption_users])
            else:
                redemption_user_ids = redemption_user_usernames = ''

            URL = '{url}?code={code}'.format(url=get_ecommerce_url('/coupons/offer/'), code=voucher.code)
            author = history.history_user.full_name

            try:
                note = coupon.attr.note
            except AttributeError:
                note = ''
{'fraction_non_alphanumeric': 0.10643310796967835, 'fraction_numerical': 0.0045072730997746365, 'mean_word_length': 2.869599682917162, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6597070', 'n_tokens_mistral': 3009, 'n_tokens_neox': 2864, 'n_words': 575}