def handle_recurring_profile_modify(sender, **kwargs):
    ipn_obj = sender

    # If the thing is invalid, do not process any further.
    if ipn_obj.flag:
        return

    site_settings = SiteSettings.objects.get_current()
    tier_info = TierInfo.objects.get_current()

    if (tier_info.current_paypal_profile_id != sender.subscr_id) and (tier_info.use_zendesk()):
        # then we had better notify staff indicating that the old one
        # should be cancelled.
        message_body = render_to_string('mirocommunity_saas/tiers_emails/disable_old_recurring_payment.txt',
                                        {'paypal_email_address': tiers.get_paypal_email_address(),
                                         'profile_on_file': tier_info.current_paypal_profile_id,
                                         'site_domain': site_settings.site.domain,
                                         'surprising_profile': ipn_obj.subscr_id})
        zendesk.create_ticket("Eek, you should check on this MC site",
                                      message_body,
                                      use_configured_assignee=False)
        return

    # Okay, well at this point, we need to adjust the site tier to match.
    amount = float(ipn_obj.amount3)
    if tier_info.get_tier().dollar_cost() == amount:
        pass
    else:
        # Find the right tier to move to
        try:
            target_tier_name = tiers.Tier.get_by_cost(amount)
        except ValueError:
            # then we had better notify staff indicating that the
            # amount is bizarre.
            if tier_info.use_zendesk():
                message_body = render_to_string('mirocommunity_saas/tiers_emails/confused_modify_wrong_amount.txt',
                                                {'paypal_email_address': tiers.get_paypal_email_address(),
                                                 'profile_on_file': tier_info.current_paypal_profile_id,
                                                 'site_domain': site_settings.site.domain,
                                                 'surprising_profile': ipn_obj.subscr_id})
                zendesk.create_ticket("Eek, you should check on this MC site",
                                              message_body,
                                              use_configured_assignee=False)
            return
        _actually_switch_tier(target_tier_name)
def handle_recurring_profile_start(sender, **kwargs):
    ipn_obj = sender
    # If the thing is invalid, do not process any further.
    if ipn_obj.flag:
        return

    site_settings = SiteSettings.objects.get_current()
    tier_info = TierInfo.objects.get_current()
    current_confirmed_tier_obj = tier_info.get_fully_confirmed_tier()
    if current_confirmed_tier_obj:
        current_tier_obj = current_confirmed_tier_obj
    else:
        current_tier_obj = tier_info.get_tier()

    if tier_info.current_paypal_profile_id:
        # then we had better notify staff that the old one should be
        # cancelled.
        message_body = render_to_string('mirocommunity_saas/tiers_emails/disable_old_recurring_payment.txt',
                                        {'paypal_email_address': tiers.get_paypal_email_address(),
                                         'old_profile': tier_info.current_paypal_profile_id,
                                         'site_domain': site_settings.site.domain,
                                         'new_profile': ipn_obj.subscr_id})
        if tier_info.use_zendesk():
            zendesk.create_ticket("Eek, you should cancel a recurring payment profile",
                                          message_body, use_configured_assignee=True)

    expected_due_date = None
    # Okay. Now it's save to overwrite the subscription ID that is the current one.
    if tier_info.free_trial_available:
        tier_info.free_trial_available = False
    # Is this an upgrade that required an initial payment period?
    elif (tier_info.current_paypal_profile_id and
          float(ipn_obj.amount3) != current_tier_obj.dollar_cost() and
          ipn_obj.amount1 and float(ipn_obj.amount1)):
        # Validate the IPN: time period
        num, format = ipn_obj.period1.split(' ')
        num = int(num)
        if format.upper() != 'D':
            raise ValueError
        expected_due_date = ipn_obj.subscr_date + datetime.timedelta(days=num)
        if abs( (expected_due_date - tier_info.payment_due_date).days) > 2:
            raise ValueError, "There is something weird going on with the due date of the new subscription."
        # Validate the IPN: payment amount
        total_diff = float(ipn_obj.amount3) - current_tier_obj.dollar_cost()
        prorated_diff = (num / 30.0) * total_diff
        if int(ipn_obj.amount1) < int(prorated_diff):
            raise ValueError, "Monkey business."
    else:
        # Validate that there isn't a "trial" for no reason.
        if not tier_info.in_free_trial:
            # sanity-check that there is no period1 or period2 value
            paypal_event_contains_free_trial = ipn_obj.period1 or ipn_obj.period2
            if paypal_event_contains_free_trial and tier_info.use_zendesk():
                zendesk.create_ticket(
                    "Eek, the user tried to create a free trial incorrectly",
                    "Check on the state of the " + site_settings.site.domain + ""
                    " site",
                    use_configured_assignee=False)
                return

    tier_info.current_paypal_profile_id = ipn_obj.subscr_id
    tier_info.user_has_successfully_performed_a_paypal_transaction = True
    if expected_due_date:
        tier_info.payment_due_date = expected_due_date
    else:
        tier_info.payment_due_date = datetime.timedelta(days=30) + ipn_obj.subscr_date
    tier_info.save()

    # If we get the IPN, and we have not yet adjusted the tier name
    # to be at that level, now is a *good* time to do so.
    amount = float(ipn_obj.amount3)
    if current_tier_obj.dollar_cost() != amount:
        # Find the right tier to move to
        target_tier_name = tiers.Tier.get_by_cost(amount)
        _actually_switch_tier(target_tier_name)