Esempio n. 1
0
    def do_fix_rental_plans(self):
        today = datetime.datetime.now().date()
        def calc_next_payment_date(start_date, period):
            d = start_date.date() if isinstance(start_date, datetime.datetime) else start_date
            while d < today:
                d = inc_months(d, period, start_date)
            return d

        debug("Fixing rental plans...")
        qs = MemberRentalPlan.objects.filter(status=RentalPlanStatus.Active)
        debug("Going to fix %d of plans...", qs.count())
        for p, i in itertools.izip(qs, itertools.count(1)):
            if i % 100 == 0:
                debug(i)
            expire_in = RentalPlan.get_expire_in(p.plan)
            if expire_in:
                p.expiration_date = inc_months(p.start_date, expire_in, p.start_date)
                p.next_payment_amount = None
                p.next_payment_date = None
                if p.status == RentalPlanStatus.Active and p.expiration_date < today:
                    p.set_status(RentalPlanStatus.CanceledP, save=False)
            else:
                p.expiration_date = None
                _pd, amount = RentalPlan.get_next_payment(p.plan, p.start_date, datetime.datetime.now())
                reccuring_period = RentalPlan.get_reccuring_period(p.plan)
                p.next_payment_amount = amount
                p.next_payment_date = calc_next_payment_date(p.start_date, reccuring_period)
            p.save()
Esempio n. 2
0
 def do_fix_next_payment_none(self):
     logger = logging.getLogger()
     hdlr = logging.FileHandler("d://planissue.log" )
     formatter = logging.Formatter('[%(asctime)s]%(levelname)-8s"%(message)s"','%Y-%m-%d %a %H:%M:%S') 
     hdlr.setFormatter(formatter)        
     logger.addHandler(hdlr)
     logger.setLevel(logging.INFO)
     date_x = datetime.now().date()
     qs = MemberRentalPlan.objects.filter(user__email__in=self.plan_with_billing_problem,status=RentalPlanStatus.Active)
     logger.info('total plans %d ' % qs.count())
     for member_plan in qs:
         try:
             if member_plan.start_date is None:
                 member_plan.start_date = date_x
                 member_plan.save()
             if member_plan.next_payment_date is None:
                 np = RentalPlan.get_next_payment(member_plan.plan, member_plan.start_date, member_plan.start_date)               
                 member_plan.next_payment_date, member_plan.next_payment_amount = np
                 member_plan.save()
             if member_plan.next_payment_date <= date_x:
                 if member_plan.scheduled_plan is not None:
                     member_plan.activate_scheduled_plan(fix_next_payment_none=member_plan.next_payment_date)
                 else:
                    if member_plan.take_recurring_billing(force_future_date=False):
                        logger.info('%s charged' % member_plan.user.id )
                    else:
                        logger.info('%s failed' % member_plan.user.email )
                    
         except Exception, _e:
             print _e
             pass
Esempio n. 3
0
def account_terms_and_details(request):
    plan = MemberRentalPlan.get_current_plan(request.user)

    if not plan or plan.status in [RentalPlanStatus.CanceledP, RentalPlanStatus.Collection]:
        return redirect('members:rent_list')

    allowed_games = '2' if plan.plan == RentalPlan.PlanA else 'unlimited'
    price_first_month, price_thereafter_months = RentalPlan.get_prices(plan.plan)
    return {
        'plan': plan,
        'plan_regular': plan.plan == RentalPlan.PlanA or plan.plan == RentalPlan.PlanB or plan.plan == RentalPlan.PlanC,
        'allowed_games': allowed_games,
        'price_first_month': price_first_month,
        'price_thereafter_months': price_thereafter_months,
        'membership_terms': RentalPlan.get_membership_terms(plan.plan) if plan else None,
    }
Esempio n. 4
0
def get_all_rental_plans_info(request):
    result = []
    # Campaign #6 -- Commission Junction
    # Campaign #13 -- Neverblue
    if not request.user.is_authenticated() and request.campaign_id in ['6', '13']:
        plans = [RentalPlan.PlanA, RentalPlan.PlanB]
    else:
        plans = [RentalPlan.PlanA, RentalPlan.PlanB, RentalPlan.PlanD,
                 RentalPlan.PlanE, RentalPlan.PlanC]
    for plan in plans:
        _plan = RentalPlan.get_details2(plan, request) or {}
        _plan.update({
            'price_display': RentalPlan.get_price_display(plan),
            'allowed': RentalPlan.get_allowed_games_amount(plan),
            })
        result.append(_plan)
    return result
Esempio n. 5
0
def account_billing_history(request):
    history = {}
    qs = BillingHistory.objects.filter(user=request.user,
                                       status__in=[TransactionStatus.Passed],
                                       type__in=[TransactionType.RentPayment, TransactionType.BuyCheckout])
    years = [y.year for y in qs.dates('timestamp', 'year')]
    years.sort()
    months = [m for m in qs.dates('timestamp', 'month')]
    months.sort()
    for m in months:
        history[m] = qs.filter(timestamp__year=m.year, timestamp__month=m.month)

    plan = MemberRentalPlan.get_current_plan(request.user)

    return {
        'title': 'Billing History',
        'price': RentalPlan.get_price_display(plan.plan) if plan else None,
        'membership_terms': RentalPlan.get_membership_terms(plan.plan) if plan else None,
        'years': years,
        'months': months,
        'history': history,
    }
Esempio n. 6
0
    def create(request, initial=None, all_plans=False):
        plan = request.POST.get('0-plan')
        if plan is not None:
            plan = RentalPlan.get_details2(int(plan), request)
        profile = request.user.get_profile()
        cc_data = profile.get_billing_card_data()
        initial = {
            1: cc_data,
        }

        if all_plans:
            plan_form = AllPlansPaymentPlanForm
            all_plans_info = get_all_rental_plans_info(request)
        else:
            plan_form = PaymentPlanForm
            all_plans_info = get_all_rental_plans_info(request)

        # Setting context
        # current_rental_plan already here from context processor
        plans = NewRentalPlan.objects.available_for_change(request)
        limited_plans = [p for p in plans if p.out_per_month]
        unlimited_plans = [p for p in plans if not p.out_per_month]
        # ---

        request.rent_wizard = ChangeRentPlanWizard('members/rent/wizards/change_plan.html',
            [plan_form, ConfirmPlanChangingForm],
            initial=initial,
            title='Change Plan',
            form_kwargs={
                0: {'request': request, },
                1: {'request': request,
                    'billing_address': profile.get_billing_data(),
                    'shipping_address': profile.get_shipping_data(),
                },
            },
            context={'plan': plan,
                     'cc_data': profile.get_payment_card() if cc_data['number'] else None,
                     'rental_plans': get_rental_plans_info(request),
                     'all_plans': all_plans_info,
                     "limited_plans": limited_plans,
                     "unlimited_plans": unlimited_plans,
                     })
        return request.rent_wizard
Esempio n. 7
0
    def create(request, initial={}):
        plan = request.POST.get('0-plan')
        if plan is not None:
            plan = plan or '0'
            plan = RentalPlan.get_details(int(plan))

        keys = ['1-first_name', '1-last_name', '1-address1', '1-address2',
                '1-city', '1-state', '1-zip_code']
        shipping_info = dict([(x[2:], request.POST[x]) for x in
                              filter(lambda z: z in keys, request.POST.keys())])
        billing_info = initial.get(2)
        email = request.POST.get('1-email')
        free_trial = False
        all_plans = NewRentalPlan.objects.available_for_signup(request)
        if "free_trial" in [p.slug for p in all_plans]:
            free_trial = True

        request.rent_wizard = NonMemberRentSignUpWizard(
            'members/rent/wizards/non-member-signup.html',
            [PaymentPlanForm, ProfileAndShippingForm, FinishRentalPlanForm],
            initial=initial,
            title='Rental Signup',
            form_kwargs={
                0: {"request": request},
                1: {'melissa': get_melissa(), 'activate_correction': True, },
                2: {'melissa': get_melissa(),
                    'activate_correction': True,
                    'request': request,
                    'email': email,
                    'shipping_address': shipping_info,
                    'aim': create_aim()},
            },
            context={
                'plan': plan,
                'all_plans': all_plans,
                'shipping_info': shipping_info,
                'billing_info': billing_info,
                "free_trial": free_trial,
            }
        )
        return request.rent_wizard
Esempio n. 8
0
 def do_fix_next_payments(self):
     today = datetime.now().date()
     for p in MemberRentalPlan.objects.filter(status=RentalPlanStatus.Active):
         nd = p.next_payment_date
         b = None
         for b in BillingHistory.objects.filter(user=p.user, type=TransactionType.RentPayment, status=TransactionStatus.Passed):
             break
         if not b:
             continue
         if b.timestamp >= datetime(2010, 11, 04):
             continue
         nnp = RentalPlan.get_next_payment(p.plan, p.start_date, b.timestamp.date())
         if not nnp:
             continue
         date, _amount = nnp
         if nd == date:
             continue
         if date <= today:
             continue
         p.next_payment_date = date
         p.save()
Esempio n. 9
0
    def create(request, initial=None):
        plan = request.POST.get('0-plan')
        if plan is not None:
            plan = RentalPlan.get_details(int(plan))
        profile = request.user.get_profile()
        form2_initial = profile.get_billing_data()
        form2_initial.update(profile.get_billing_card_data())
        initial = {
            1: profile.get_shipping_data(),
            2: form2_initial,
        }

        keys = ['1-first_name', '1-last_name', '1-address1', '1-address2',
                '1-city', '1-state', '1-zip_code']
        shipping_info = dict([(x[2:], request.POST[x]) for x in
                              filter(lambda z: z in keys, request.POST.keys())])
        billing_info = form2_initial

        request.rent_wizard = MemberRentSignUpWizard('members/rent/wizards/member-signup.html',
            [PaymentPlanForm, ShippingInformationForm, FinishRentalPlanForm],
            initial=initial,
            title='Rental Signup',
            form_kwargs={
                1: {'melissa': get_melissa(), 'activate_correction': True, },
                2: {'melissa': get_melissa(),
                    'activate_correction': True,
                    'request': request,
                    'shipping_address': shipping_info,
                    'aim': create_aim()},
            },
            context={
                'plan': plan,
                'rental_plans': get_rental_plans_info(request),
                'all_plans': get_all_rental_plans_info(request),
                'shipping_info': shipping_info,
                'billing_info': billing_info,
            })
        return request.rent_wizard
Esempio n. 10
0
def get_details(plan, request=None):
    return {
        RentalPlan.PlanA: {
            "plan": plan,
            "title": "Limited Monthly 1 Game Plan",
            "slug": "limited",
            "allowed_games": 1,
            "out_per_month": 2,
            "amount_to_charge": RentalPlan.get_start_payment_amount(plan),
            "price": RentalPlan.get_prices(plan)[1],
            "price_first_month": RentalPlan.get_prices(plan)[0],
        },
        RentalPlan.PlanB: {
            "plan": plan,
            "title": "Unlimited Monthly 2 Game Plan",
            "slug": "unlimited",
            "allowed_games": 2,
            "out_per_month": None,
            "amount_to_charge": RentalPlan.get_start_payment_amount(plan),
            "price": RentalPlan.get_prices(plan)[1],
            "price_first_month": RentalPlan.get_prices(plan)[0],
        },
    }[plan]
Esempio n. 11
0
 def test_rental_plan(self):
     self.assertTrue(RentalPlan._RentalPlan__get(0))
Esempio n. 12
0
 def _(plan):
     return {
         'price_display': RentalPlan.get_price_display(plan),
     }
Esempio n. 13
0
    def clean(self):
        data = super(ConfirmPlanChangingForm, self).clean()
        if not self._errors:
            request = self.request

            wizard = self.request.rent_wizard

            f = wizard.get_form(0, self.request.POST)
            f.is_valid()  # it's a long way to get info from here

            plan = int(f.cleaned_data['plan'])

            _profile = request.user.get_profile()
            current_plan = MemberRentalPlan.get_current_plan(_profile.user)
            self.current_plan = current_plan

            if current_plan and current_plan.plan == plan:
                self.rent_plan = None
                return data

            card = self.cached_card['data']
            card['display_number'] = self.cached_card['display_number']
            aim_data = {
                'x_customer_ip': self.request.META.get('REMOTE_ADDR'),
                'x_cust_id': _profile.user.id,
                'x_email': _profile.user.email,
            }

            shipping_address = _profile.get_shipping_address_data()
            shipping_address.update(_profile.get_name_data())
            shipping_address['country'] = 'USA'
            billing_address = _profile.get_billing_data()
            billing_address['country'] = 'USA'

            downgrade = current_plan and plan <= current_plan.plan
            self.downgrade = downgrade
            if downgrade:
                return data

            self.rent_plan = MemberRentalPlan.create(_profile.user, plan, downgrade)
            self.billing_history = None

            amount = RentalPlan.get_start_payment_amount(plan)

            #malcala: changs to capture money
            #do_capture = False
            do_capture = True
            if current_plan:
                last_payment = current_plan.get_last_payment()
                if last_payment and last_payment.status == TransactionStatus.Passed:
                    orders = RentOrder.objects.filter(
                        user=current_plan.user,
                        date_rent__gte=current_plan.created
                        ).exclude(status__in=[RentOrderStatus.Prepared, RentOrderStatus.Canceled])
                    if orders.count():
                        if last_payment.debit < amount:
                            amount -= (current_plan.next_payment_amount or
                                       RentalPlan.get_start_payment_amount(current_plan.plan))
                        do_capture = True

            tax = Tax.get_value(billing_address['state'], billing_address['county'])
            tax_amount = decimal.Decimal('%.2f' % (amount * tax / decimal.Decimal('100.0')))

            aim_data['x_tax'] = tax_amount

            self.billing_history = BillingHistory.create(_profile.user, card['display_number'],
                    debit=amount, reason='rent', type=TransactionType.RentPayment)
            self.billing_history.tax = tax_amount

            invoice_num, description = self.rent_plan.get_payment_description(False, self.billing_history.id)
            self.billing_history.description = description
            self.billing_history.save()

            if do_capture:
                res, aim_response, applied_credits, applied_amount = self.rent_plan.take_money(amount, tax_amount, invoice_num, description,
                    card=card, shipping_data=shipping_address, billing_data=billing_address, aim_data=aim_data,
                    profile=_profile)
                self.billing_history.applied_credits = applied_credits
                self.billing_history.status = TransactionStatus.Passed
                self.billing_history.setted = True
            else:
                res, aim_response = self.rent_plan.authorize_money(amount, tax_amount, invoice_num, description,
                    card=card, shipping_data=shipping_address, billing_data=billing_address, aim_data=aim_data)
                self.billing_history.status = TransactionStatus.Authorized
                self.billing_history.setted = False
            if aim_response:
                self.billing_history.aim_transaction_id = aim_response.transaction_id
                self.billing_history.aim_response  = aim_response._as_dict
                self.billing_history.message = aim_response.response_reason_text
            if not res:
                self.billing_history.status = TransactionStatus.Declined
                self.billing_history.save()
                self.rent_plan.delete()
                raise forms.ValidationError(self.rent_plan.status_message)
            self.billing_history.card_data = self.cached_card['data']
            self.billing_history.save()
        return data