def downgrade_confirm(request):
    target_tier_name = request.POST.get('target_tier_name', None)
    # validate
    if target_tier_name in dict(tiers.CHOICES):
        target_tier_obj = tiers.Tier(target_tier_name)

        would_lose = tiers.user_warnings_for_downgrade(target_tier_name)
        data = {}
        data['tier_name'] = target_tier_name
        data['paypal_sandbox'] = getattr(settings, 'PAYPAL_TEST', False)
        data['can_modify'] = _generate_can_modify()[target_tier_name]
        data['paypal_url'] = get_paypal_form_submission_url()
        data['paypal_email'] = tiers.get_paypal_email_address()
        data['paypal_email_acct'] = tiers.get_paypal_email_address()
        data['target_tier_obj'] = target_tier_obj
        data['would_lose_admin_usernames'] = tiers.push_number_of_admins_down(target_tier_obj.admins_limit())
        data['customtheme_nag'] = ('customtheme' in would_lose)
        data['advertising_nag'] = ('advertising' in would_lose)
        data['customdomain_nag'] = ('customdomain' in would_lose)
        data['css_nag'] = ('css' in would_lose)
        data['videos_nag'] = ('videos' in would_lose)
        data['videos_over_limit'] = tiers.hide_videos_above_limit(target_tier_obj)
        data['new_theme_name'] = tiers.switch_to_a_bundled_theme_if_necessary(target_tier_obj)
        data['payment_secret'] = SiteSettings.objects.get_current().tierinfo.get_payment_secret()
        return render_to_response('localtv/admin/downgrade_confirm.html', data,
                                  context_instance=RequestContext(request))

    # In some weird error case, redirect back to tiers page
    return HttpResponseRedirect(reverse('localtv_admin_tier'))
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 upgrade(request):
    SWITCH_TO = 'Switch to this'
    UPGRADE = 'Upgrade Your Account'

    switch_messages = {}
    tier_info = TierInfo.objects.get_current()
    if tier_info.tier_name in ('premium', 'max'):
        switch_messages['plus'] = SWITCH_TO
    else:
        switch_messages['plus'] = UPGRADE

    if tier_info.tier_name == 'max':
        switch_messages['premium'] = SWITCH_TO
    else:
        switch_messages['premium'] = UPGRADE

    # Would you lose anything?
    would_lose = {}
    for tier_name in ['basic', 'plus', 'premium', 'max']:
        if tier_name == tier_info.tier_name:
            would_lose[tier_name] = False
        else:
            would_lose[tier_name] = tiers.user_warnings_for_downgrade(tier_name)

    upgrade_extra_payments = {}
    for target_tier_name in ['basic', 'plus', 'premium', 'max']:
        if (tier_info.in_free_trial or
            (tiers.Tier(target_tier_name).dollar_cost() <=
             tier_info.get_tier().dollar_cost()) or
            not tier_info.payment_due_date):
            upgrade_extra_payments[target_tier_name] = None
            continue
        upgrade_extra_payments[target_tier_name] = generate_payment_amount_for_upgrade(
            tier_info.tier_name, target_tier_name,
            tier_info.payment_due_date)

    data = {
        'upgrade_extra_payments': upgrade_extra_payments,
        'can_modify_mapping': _generate_can_modify(),
        'tier_info': tier_info,
        'would_lose_for_tier': would_lose,
        'switch_messages': switch_messages,
        'payment_secret': tier_info.get_payment_secret(),
        'offer_free_trial': tier_info.free_trial_available,
        'skip_paypal': getattr(settings, 'LOCALTV_SKIP_PAYPAL', False),
        'paypal_email_acct': tiers.get_paypal_email_address(),
        'tier_to_price': tiers.Tier.NAME_TO_COST(),
    }
    if not data['skip_paypal']:
        data['paypal_url'] = get_paypal_form_submission_url()

    return render_to_response('localtv/admin/upgrade.html', data,
                              context_instance=RequestContext(request))
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)