<commit_before>from decimal import Decimal

from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

import go.billing.settings as app_settings
from go.base.models import UserProfile


class TagPool(models.Model):
    """Tag pool definition"""

    name = models.CharField(
        max_length=100, unique=True,
        help_text=_("The name of the tagpool."))

    description = models.TextField(
        blank=True,
        help_text=_("A description of the tagpool."))

    def __unicode__(self):
        return self.name


class Account(models.Model):
    """Represents a user account"""

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        help_text=_("The user the billing account belongs to."))

    account_number = models.CharField(
        max_length=100, unique=True,
        help_text=_("The account number associated with the user the account"
                    " belongs to."))

    description = models.TextField(
        blank=True,
        help_text=_("A description of this account."))

    credit_balance = models.DecimalField(
        max_digits=20, decimal_places=6, default=Decimal('0.0'),
        help_text=_("The current credit balance."))

    last_topup_balance = models.DecimalField(
        max_digits=20, decimal_places=6, default=Decimal('0.0'),
        help_text=_("The credits balance after the last credit top up. Used "
                    "in the calculation to determine when low-credits "
                    "notifications should be sent."))

    def __unicode__(self):
        return u"{0} ({1})".format(self.account_number, self.user.email)


def create_billing_account(sender, instance, created, **kwargs):
    if created:
        Account.objects.create(user=instance.user,
                               account_number=instance.user_account)


post_save.connect(
    create_billing_account, sender=UserProfile,
    dispatch_uid='go.billing.models.create_billing_account')


class MessageCost(models.Model):
    """Specifies the cost of a single message.

    The cost of a message is defined in terms of the tag pool and the message
    direction. The cost can optionally be overridden on a per account basis.

    """

    DIRECTION_INBOUND = 'Inbound'
    DIRECTION_OUTBOUND = 'Outbound'
    DIRECTION_CHOICES = (
        (DIRECTION_INBOUND, DIRECTION_INBOUND),
        (DIRECTION_OUTBOUND, DIRECTION_OUTBOUND),
    )

    @classmethod
    def apply_markup_and_convert_to_credits(cls, cost, markup_percent,
                                            context=None):
        """
        Takes a cost (in cents), applies markup and converts the resulting
        amount to credits.
        """
        cost = cost + (cost * markup_percent / Decimal('100.0'))
        credits = cost * Decimal(app_settings.CREDIT_CONVERSION_FACTOR)
        return credits.quantize(app_settings.QUANTIZATION_EXPONENT,
                                context=context)

    @classmethod
    def calculate_message_credit_cost(cls, message_cost, markup_percent,
                                      context=None):
        """
        Return the cost per message (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            message_cost, markup_percent, context=context)

    @classmethod
    def calculate_storage_credit_cost(cls, storage_cost, markup_percent,
                                      context=None):
        """
        Return the storage cost per message (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            storage_cost, markup_percent, context=context)

    @classmethod
    def calculate_session_credit_cost(cls, session_cost, markup_percent,
                                      context=None):
        """
        Return the cost per session (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            session_cost, markup_percent, context=context)

    @classmethod
    def calculate_session_unit_credit_cost(
            cls, session_length_cost, markup_percent, context=None):
        """
        Return the cost per session length (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            session_length_cost, markup_percent, context=context)

    @classmethod
    def calculate_session_length_credit_cost(
            cls, session_length_cost, markup_percent, context=None):
        """
        Return the cost of a session length (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            session_length_cost, markup_percent, context=context)

    @classmethod
    def calculate_credit_cost(cls, message_cost, storage_cost, markup_percent,
                              session_cost, session_created, context=None):
        """
        Return the total cost for both the message and the session, if any,
        in credits.
        """
        base_cost = message_cost + storage_cost
        if session_created:
            base_cost += session_cost
        return cls.apply_markup_and_convert_to_credits(
            base_cost, markup_percent, context=context)

    class Meta:
        unique_together = [
            ['account', 'tag_pool', 'message_direction'],<commit_msg>Change parameter name in calculate_session_unit_credit_cost to be less ambiguous.<commit_after>from decimal import Decimal

from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

import go.billing.settings as app_settings
from go.base.models import UserProfile


class TagPool(models.Model):
    """Tag pool definition"""

    name = models.CharField(
        max_length=100, unique=True,
        help_text=_("The name of the tagpool."))

    description = models.TextField(
        blank=True,
        help_text=_("A description of the tagpool."))

    def __unicode__(self):
        return self.name


class Account(models.Model):
    """Represents a user account"""

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        help_text=_("The user the billing account belongs to."))

    account_number = models.CharField(
        max_length=100, unique=True,
        help_text=_("The account number associated with the user the account"
                    " belongs to."))

    description = models.TextField(
        blank=True,
        help_text=_("A description of this account."))

    credit_balance = models.DecimalField(
        max_digits=20, decimal_places=6, default=Decimal('0.0'),
        help_text=_("The current credit balance."))

    last_topup_balance = models.DecimalField(
        max_digits=20, decimal_places=6, default=Decimal('0.0'),
        help_text=_("The credits balance after the last credit top up. Used "
                    "in the calculation to determine when low-credits "
                    "notifications should be sent."))

    def __unicode__(self):
        return u"{0} ({1})".format(self.account_number, self.user.email)


def create_billing_account(sender, instance, created, **kwargs):
    if created:
        Account.objects.create(user=instance.user,
                               account_number=instance.user_account)


post_save.connect(
    create_billing_account, sender=UserProfile,
    dispatch_uid='go.billing.models.create_billing_account')


class MessageCost(models.Model):
    """Specifies the cost of a single message.

    The cost of a message is defined in terms of the tag pool and the message
    direction. The cost can optionally be overridden on a per account basis.

    """

    DIRECTION_INBOUND = 'Inbound'
    DIRECTION_OUTBOUND = 'Outbound'
    DIRECTION_CHOICES = (
        (DIRECTION_INBOUND, DIRECTION_INBOUND),
        (DIRECTION_OUTBOUND, DIRECTION_OUTBOUND),
    )

    @classmethod
    def apply_markup_and_convert_to_credits(cls, cost, markup_percent,
                                            context=None):
        """
        Takes a cost (in cents), applies markup and converts the resulting
        amount to credits.
        """
        cost = cost + (cost * markup_percent / Decimal('100.0'))
        credits = cost * Decimal(app_settings.CREDIT_CONVERSION_FACTOR)
        return credits.quantize(app_settings.QUANTIZATION_EXPONENT,
                                context=context)

    @classmethod
    def calculate_message_credit_cost(cls, message_cost, markup_percent,
                                      context=None):
        """
        Return the cost per message (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            message_cost, markup_percent, context=context)

    @classmethod
    def calculate_storage_credit_cost(cls, storage_cost, markup_percent,
                                      context=None):
        """
        Return the storage cost per message (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            storage_cost, markup_percent, context=context)

    @classmethod
    def calculate_session_credit_cost(cls, session_cost, markup_percent,
                                      context=None):
        """
        Return the cost per session (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            session_cost, markup_percent, context=context)

    @classmethod
    def calculate_session_unit_credit_cost(
            cls, session_unit_cost, markup_percent, context=None):
        """
        Return the cost per session length (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            session_unit_cost, markup_percent, context=context)

    @classmethod
    def calculate_session_length_credit_cost(
            cls, session_length_cost, markup_percent, context=None):
        """
        Return the cost of a session length (in credits).
        """
        return cls.apply_markup_and_convert_to_credits(
            session_length_cost, markup_percent, context=context)

    @classmethod
    def calculate_credit_cost(cls, message_cost, storage_cost, markup_percent,
                              session_cost, session_created, context=None):
        """
        Return the total cost for both the message and the session, if any,
        in credits.
        """
        base_cost = message_cost + storage_cost
        if session_created:
            base_cost += session_cost
        return cls.apply_markup_and_convert_to_credits(
            base_cost, markup_percent, context=context)

    class Meta:
        unique_together = [
            ['account', 'tag_pool', 'message_direction'],
{'fraction_non_alphanumeric': 0.08027223568898005, 'fraction_numerical': 0.004102181614767854, 'mean_word_length': 2.5309414088215934, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1507742', 'n_tokens_mistral': 3007, 'n_tokens_neox': 2886, 'n_words': 733}