def clean(self): data = super(NameAndAddressForm, self).clean() if not self._errors: d = '\n'.join([ self.cached_address["address1"], self.cached_address["address2"], self.cached_address["city"], self.cached_address["state"], self.cached_address["zip_code"], ]) m = md5() m.update(d) cs = m.hexdigest() d = Profile.objects.filter(shipping_checksum=cs).exclude(user=None) if hasattr(self, 'request') and self.request.user.is_authenticated(): d = d.exclude(user__id=self.request.user.id) for p in d: rp = MemberRentalPlan.get_current_plan(p.user) if not p.user.is_active or (rp and rp.status not in [RentalPlanStatus.Pending, RentalPlanStatus.Active, RentalPlanStatus.Delinquent, RentalPlanStatus.OnHold]): raise forms.ValidationError("This address has been used before for account that's no longer active") if self.melissa: from melissadata import MelissaNameError try: self.cached_name = self.melissa.inaccurate_name(**data) except MelissaNameError, e: raise forms.ValidationError(e) except Exception, e: raise forms.ValidationError(e[0] % e[1])
def cancel_membership_confirm(request, code): plan = MemberRentalPlan.get_current_plan(request.user) if not plan: return redirect('members:rent_list') # if plan.cancel_confirmation_code != code or plan.cancel_confirmation_timestamp < datetime.now() - timedelta(2): # return redirect('members:cancel_membership') for r in CancellationReason.objects.filter(user=request.user, confirmation_code=code): r.is_confirmed = True r.save() for order in RentOrder.objects.filter(user=request.user, status=RentOrderStatus.Pending): order.status = RentOrderStatus.Canceled order.list_item = None order.save() orders = RentOrder.objects.filter(user=request.user, status__in=[RentOrderStatus.Prepared, RentOrderStatus.Shipped]) if orders.count(): # Has games at home debug('Has games at home. Set status to be RentalPlanStatus.CanceledP') plan.status = RentalPlanStatus.CanceledP plan.cancellation_date = datetime.now() plan.cancel_confirmation_code = None plan.cancel_confirmation_timestamp = None plan.save() else: debug('Finish cancellation') plan.finish_cancellation() return redirect('members:rent_list') return { 'plan': plan, 'orders': orders, }
def do_old_rent_plans(self): i, j = 0, 0 for o in RentOrder.objects.filter(status=RentOrderStatus.Shipped).exclude(inventory=None).order_by('date_rent'): # if RentOrder.objects.filter(inventory=o.inventory, date_rent__gt=o.date_rent).count(): # i += 1 # o.status = RentOrderStatus.AutoCanceled # o.save() # elif RentOrder.objects.filter(status=RentOrderStatus.Returned, user=o.user, date_rent__gt=o.date_rent).count() > 5: # i += 1 # o.status = RentOrderStatus.AutoCanceledByAstral # o.save() # else: plan = MemberRentalPlan.get_current_plan(o.user) if plan: print plan.status # if plan and plan.status == RentalPlanStatus.Canceled: # print o.user.id, '\t', o.date_rent, '\t', o, plan # i += 1 # else: # claims = Claim.objects.filter(object_id=o.id).filter(Q(type=ClaimType.GameIsDamaged) | Q(type=ClaimType.DontRecieve)) # if claims.count(): # print o.user.id, '\t', o # for c in claims: # print ' ', c.get_title() # else: # print o.id, '\t', o.user.id, '\t', o.date_rent # elif o.incoming_tracking_number: # res = endicia.status_request(o.incoming_tracking_number) # print res j += 1 print i, 'of', j
def cancel_rent_account(request, user_id): if not request.user.is_superuser: raise Http404() u = get_object_or_404(User, id=user_id) plan = MemberRentalPlan.get_current_plan(u) if not plan or plan.status not in [RentalPlanStatus.CanceledP, RentalPlanStatus.Pending, RentalPlanStatus.Delinquent, RentalPlanStatus.Active, RentalPlanStatus.OnHold]: return redirect('staff:customer_view', u.id) plan.status = RentalPlanStatus.CanceledP plan.save() # for o in RentOrder.objects.filter(user=u, status=RentOrderStatus.Shipped): # o.status = RentOrderStatus.Canceled # o.cancel_penalty_payment() # o.save() # if o.inventory: # o.inventory.status = InventoryStatus.Lost # o.inventory.save() for o in RentOrder.objects.filter(user=u, status=RentOrderStatus.Pending): o.status = RentOrderStatus.Canceled o.save() if o.inventory: o.inventory.status = InventoryStatus.InStock o.inventory.save() return redirect('staff:customer_view', u.id)
def do_process_matrix(self): debug('Allocate inventory for buy orders...') self.do_allocate_inventory_for_buy_orders() debug('Canceling dead plans...') MemberRentalPlan.cancel_dead_plans() debug('Canceling expired plans...') MemberRentalPlan.cancel_expired_plans() debug('Calculating weights...') self.do_weight_matrix() debug('OK') debug('Processing matrix...') for o in RentList.get_priority1(): debug('--------------------------') debug('Allocation matrix for %s - %s %s (%s) %s', o.id, o.item, o.item.category, o.user, o.weight) RentAllocationMatrix.process_item(o) debug('OK')
def card_verification_callback(form, cleaned_data, aim_data): cc_changed = profile.get_billing_card_data().get('number') != cleaned_data.get('number') profile.set_billing_name_data(form.cached_name, False) profile.set_billing_address_data(form.cached_address, False) profile.set_billing_card_data(cleaned_data, False) plan = MemberRentalPlan.get_current_plan(request.user) if plan and plan.status in [RentalPlanStatus.Delinquent, RentalPlanStatus.Collection] and cc_changed: return plan.take_delinquent_payment(True, profile, aim_data) return None
def account_reactivate(request): profile = request.user.get_profile() plan = MemberRentalPlan.get_current_plan(profile.user, exclude_canceled=True) if not plan or plan.status != RentalPlanStatus.OnHold: return redirect('new_rent:change_plan') if request.method == 'POST': plan.reactivate() return redirect('members:put_on_hold') return {}
def import_rent_plan(self, user_id): ocursor = self.mconn.cursor() ocursor.execute("select id, ref_package, ref_order_status, signup_amount, billing_amount, included_tax_amount, billing_period, order_date, start_date, expire_date, next_billing_date, paypal_id, paypal_cc, paypal_cc_expire, paypal_nextbilling_date, paypal_status, paypal_amount, paypal_num_of_failed_payments, sent_count, wish_count, returned_count, prepared_count, items_to_send, items_to_send_basic, is_hotlist_order, next_payment_number, note, authorize_transaction_id, times_billed, ref_credit_card, takes_part_in_picklist, checked_paypal_transactions, non_recurring, promotional, paid_by_check, suspend_date, cancel_date, capture_authorization_failed, capture_authorization_attempts, capture_authorization_fail_date from orders where ref_user=%s order by id desc", [user_id,]) ro = ocursor.fetchall() if len(ro) > 0: field_names = map(lambda x: x[0], ocursor.description) r = dict(zip(field_names, ro[0])) if r['ref_package'] in self.PLAN_MAP and r['ref_order_status'] in self.PLAN_STATUS_MAP: mrp = MemberRentalPlan( user_id = user_id, plan = self.PLAN_MAP[r['ref_package']], # status = RentalPlanStatus.AutoCanceled, #self.PLAN_STATUS_MAP[r['ref_order_status']], status = self.PLAN_STATUS_MAP[r['ref_order_status']], created = r['order_date'], start_date = r['start_date'], expiration_date = r['cancel_date'], next_payment_date = r['next_billing_date'], next_payment_amount = decimal.Decimal('%.02f' % r['paypal_amount']), ) mrp.save()
def cancel_membership(request): current_plan = MemberRentalPlan.get_current_plan(request.user) if not current_plan: return redirect('members:change_rent_plan') if request.method == 'POST': if current_plan.status not in [RentalPlanStatus.Active, RentalPlanStatus.Delinquent, RentalPlanStatus.Pending, RentalPlanStatus.OnHold]: return redirect('members:cancel_membership') form = RentPlanCancellationForm(request.POST) if form.is_valid(): reason = form.save() reason.user = request.user reason.plan = current_plan.plan # current_plan.send_cancel_request(reason) request.session['rent_cancellation_started'] = True # return redirect('members:cancel_membership_confirm_message') return cancel_membership_confirm(request, reason.confirmation_code) else: form = RentPlanCancellationForm() return { 'rent_plan': MemberRentalPlan.get_current_plan(request.user), 'form': form, }
def create(user, order, status = CaseStatus.New, message = ''): from project.rent.models import MemberRentalPlan, RentalPlanStatus try: t = PersonalGameTicket.objects.exclude(status__in=[CaseStatus.AutoClosed, CaseStatus.Closed]).get(order=order) t.change_status(user, status, message) return t except PersonalGameTicket.DoesNotExist: t = Ticket.create(user, status, message, PersonalGameTicket, order=order) plan = MemberRentalPlan.get_current_plan(order.user) if plan: plan.status = RentalPlanStatus.PersonalGame plan.save() plan.send_personal_game_received() return t
def inc_strikes(self, amount=1, silent=False): self.strikes += amount if self.strikes > 3: self.strikes = 3 elif self.strikes < 0: self.strikes = 0 self.save() if self.strikes == 3: if not silent: self.suspend_rent_account() else: from project.rent.models import MemberRentalPlan, RentalPlanStatus plan = MemberRentalPlan.get_current_plan(self.user) if plan and plan.status == RentalPlanStatus.Suspended: plan.status = RentalPlanStatus.Active if plan.payment_fails_count == 0 else RentalPlanStatus.Delinquent plan.save()
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, }
def _get_wizard(request, all_plans=False): """ Returns wizard instance depending on user registration status """ if request.user.is_authenticated(): current_plan = MemberRentalPlan.get_current_plan(request.user) if current_plan: if current_plan.status in [RentalPlanStatus.CanceledP, RentalPlanStatus.Collection]: return redirect('members:rent_list') wizard = ChangeRentPlanWizard.create(request, all_plans=all_plans) else: wizard = MemberRentSignUpWizard.create(request) else: if not request.is_ajax(): return redirect('catalog:index') wizard = NonMemberRentSignUpWizard.create(request) return wizard(request)
def set_billing_card_data(self, data, save=True): from project.rent.models import MemberRentalPlan, RentalPlanStatus card = self.get_payment_card() card.type = data.get('type') card.data = { 'number': data.get('number'), 'exp_year': data.get('exp_year'), 'exp_month': data.get('exp_month'), 'code': data.get('code'), } card.update_display_number() rent_plan = MemberRentalPlan.get_current_plan(self.user) if rent_plan and rent_plan.status == RentalPlanStatus.AutoCanceled: rent_plan.delinquent_next_check = datetime.date.today() rent_plan.set_status(RentalPlanStatus.Delinquent) if save: card.save()
def process_item(rent_list_item): """ Blah """ user = rent_list_item.user profile = user.get_profile() zip_code = profile.shipping_zip rent_list = RentList.objects.filter(user=user, rent_order=None) def chain_objects(o1, objects=[]): return itertools.chain([o1] if o1 else [], itertools.ifilter(lambda x: x != o1, objects)) debug("Home DC: %s", profile.dropship) from project.inventory.models import Dropship dropships = list(chain_objects(profile.dropship, Dropship.list_by_distance(zip_code))) def find_dropship(item): for dropship in dropships: if dropship.is_game_available(item, for_rent=True): return dropship return None rent_plan = MemberRentalPlan.get_current_plan(user) for list_item in chain_objects(rent_list_item, rent_list): dc = find_dropship(list_item.item) debug("Processing: %s %s...", list_item.user, list_item.item) if not dc: # TODO: Create report debug("Create report") continue if not rent_plan.is_valid(): return False order = RentOrder.create(user, list_item, dc) debug("Rent order was created: %s", order) return True return False
def account_change_reactivation_date(request): profile = request.user.get_profile() plan = MemberRentalPlan.get_current_plan(profile.user, exclude_canceled=True) if not plan or plan.status != RentalPlanStatus.OnHold: return redirect('new_rent:change_plan') if request.method == 'POST': form = OnHoldForm(request.POST) if form.is_valid(): plan.put_on_hold(form.cleaned_date()) else: form = OnHoldForm() return { 'fromdate': (datetime.now()+timedelta(days=7)).strftime('%B %d, %Y'), 'todate': (datetime.now()+timedelta(days=30)).strftime('%B %d, %Y'), 'form': form, }
def rent_list(request): rent_plan = MemberRentalPlan.get_current_plan(request.user) rent_list = RentList.get(request=request) if request.user.is_authenticated(): rent_orders = RentOrder.objects.filter(user=request.user).order_by('-id') rent_orders = rent_orders.filter(status__in=[RentOrderStatus.Pending, RentOrderStatus.Prepared, RentOrderStatus.Shipped]) rent_orders = rent_orders.filter(list_item=None) else: rent_orders = None return { 'buy_list': request.buy_list, 'trade_list': TradeListItem.get(request), 'rent_plan': rent_plan, 'rent_list': rent_list, 'rent_orders': rent_orders, 'pending_credits': request.user.get_profile().get_pending_credits(), 'banners': [ListPageBanner.objects.get_random()], }
def do_take_penalty_payments(self): def list_claims(cls): qs = cls.objects.exclude(next_penalty_payment_date=None) qs = qs.filter(next_penalty_payment_date__lte=datetime.now()) return qs for c in itertools.chain(list_claims(GameIsDamagedClaim), list_claims(WrongGameClaim)): # ernestorx # refund Customers when no games have been shipped (current process) # and has minimum of seven (7) released games (date equal to or less than today) # on rent list for 15-day consecutive concurrent days. r, _aim_result = c.take_penalty_payment() if not r: if c.penalty_payment_tries > 5: c.next_penalty_payment_date = None c.save() plan = MemberRentalPlan.get_current_plan(c.user) plan.status = RentalPlanStatus.Collection plan.save()
def do_fix_2x_speed(self): for o in RentOrder.objects.filter(status=RentOrderStatus.Shipped, scanned_in_route=False, user__profile__strikes=0): plan = MemberRentalPlan.get_current_plan(o.user) if not plan or plan.status != RentalPlanStatus.Active: continue if Claim.list(o).count(): continue scans = o.incoming_tracking_scans or {} if "I" in scans or "D" in scans or "A" in scans: d = scans.get("I", scans.get("D", scans.get("A"))) d = datetime.strptime(d, "%Y-%m-%d %H:%M:%S") if not d or d <= datetime.datetime.now() - datetime.timedelta(7): continue o.scanned_in_route = True o.save() p = o.user.get_profile() p.extra_rent_slots += 1 p.save() print o
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, }
def do_fix_old_rent_orders(self): qs = RentOrder.objects.filter(status=RentOrderStatus.Shipped) i, count = 0, qs.count() for r in qs: i += 1 if i % 100 == 0: print '%s of %s' % (i, count) if not r.inventory: continue if r.inventory.status in [InventoryStatus.Lost, InventoryStatus.Sale, InventoryStatus.Sold]: r.status = RentOrderStatus.AutoCanceled r.save() elif r.inventory.status in [InventoryStatus.Damaged]: r.status = RentOrderStatus.AutoCanceled r.save() else: c = self._get_cursor() c.execute(''' select not_expected_to_return from entries e where e.code = %s ''', [r.inventory.barcode]) for not_expected_to_return, in c.fetchall(): if int(not_expected_to_return): r.inventory.not_expected_to_return = True r.inventory.save() r.status = RentOrderStatus.AutoCanceled r.save() break if r.status == RentOrderStatus.Shipped: plan = MemberRentalPlan.get_current_plan(r.user) if not plan or plan.status == RentalPlanStatus.Canceled: r.status = RentOrderStatus.AutoCanceled r.save() r.inventory.status = InventoryStatus.Unknown r.inventory.save()
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
def is_rental_active(self): from project.rent.models import MemberRentalPlan plan = MemberRentalPlan.get_current_plan(self.user) if plan: return True return False
def get_rental_status(self, exclude_canceled=True): from project.rent.models import MemberRentalPlan plan = MemberRentalPlan.get_current_plan(self.user, exclude_canceled) return plan.get_status_display() if plan else 'No rental plan'
def suspend_rent_account(self): from project.rent.models import MemberRentalPlan plan = MemberRentalPlan.get_current_plan(self.user) if plan: plan.suspend_plan()
def balalayka(request): if request.is_ajax(): def img(n): f = settings.STATIC_URL + 'img/banners/balalayka/%s.jpg' return f % (n + '-b'), f % (n + '-s') def g(id): try: return Item.objects.get(id=id).get_absolute_url() except Item.DoesNotExist: return None banners = [ { 'banner_class': 'banner-rent-1', 'links': [('/Rent/SignUp/', 'link-dialog')], 'images': img('rent-1'), }, { 'banner_class': 'banner-rent-2', 'links': [('/Rent/Destination/', None)], 'images': img('rent-2'), }, { 'banner_class': 'banner-freetrial', 'links': [('/Rent/SignUp/', 'link-dialog')], 'images': img('freetrial'), }, { 'banner_class': 'banner-wimgw', 'links': [(g(id), None) for id in [100000325, 10000040, 100000013]], 'images': img('wimgw'), }, { 'banner_class': 'banner-trade', 'links': [('/Trade/', None)], 'images': img('trade'), }, { 'banner_class': 'banner-newsletter', 'links': [(reverse('subscription:signup'), 'link-dialog')], 'images': img('newsletter'), }, { 'banner_class': 'banner-buy', 'links': [('/Buy/', None)], 'images': img('buy'), }, ] if request.user.is_authenticated(): if MemberRentalPlan.get_current_plan(request.user): banner_set = [1, 3, 4, 6] else: banner_set = [0, 3, 4, 6] else: if 'subscription-done' in request.COOKIES: banner_set = [0, 3, 4, 6] else: banner_set = [0, 3, 4, 5, 6] if is_eligible_for_free_trial(request): banner_set[0] = 2 return JsonResponse({ 'banners': [banners[x] for x in banner_set],}) if not settings.DEBUG: return redirect('/')
def do_purge(self): MemberRentalPlan.purge_expired_plans() MemberRentalPlan.cleanup_expired_cancellations() RentList.purge()
def view(request, user_id): user = get_object_or_404(User, id=user_id) profile = Profile.objects.get(user=user) if 'impersonate' in request.GET: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect('/') not_activated_user = not user.is_active and profile.activation_code account_is_blocked = not user.is_active and not profile.activation_code can_block_account = request.user.is_superuser can_change_extra_slots = request.user.is_superuser #or request.user.get_profile().group in [Group.DC_Manager] if request.is_ajax(): status = 'FAIL' action = request.REQUEST.get('action') if action == 'resend-activation-link': if not_activated_user: profile.send_email_confirmation_mail() status = 'OK' elif action == 'block': if can_block_account: profile.block_account() status = 'OK' elif action == 'unblock': if can_block_account: profile.unblock_account() status = 'OK' elif action == 'add-extra-slot': if can_change_extra_slots: profile.extra_rent_slots += 1 profile.save() status = 'OK' elif action == 'rm-extra-slot': if can_change_extra_slots: profile.extra_rent_slots -= 1 if profile.extra_rent_slots < 0: profile.extra_rent_slots = 0 profile.save() status = 'OK' elif action == 'reactivate': if request.user.is_superuser: plan = MemberRentalPlan.get_current_plan(user) if plan and plan.status in [RentalPlanStatus.Delinquent, RentalPlanStatus.Collection]: plan.take_delinquent_payment(True) status = 'OK' return JsonResponse({'status': status}) last_orders_buy = BuyOrder.list_recent(user) last_order_buy = last_orders_buy[0] if last_orders_buy.count() > 0 else None last_order_trade = user.tradeorder_set.order_by('-id') last_order_trade = last_order_trade[0] if len(last_order_trade) > 0 else None last_order_rent = user.rentorder_set.order_by('-id') last_order_rent = last_order_rent[0] if len(last_order_rent) > 0 else None rent_plan = MemberRentalPlan.get_current_plan(user) rent_plan_cancelable = rent_plan and rent_plan.status in [RentalPlanStatus.CanceledP, RentalPlanStatus.Pending, RentalPlanStatus.Delinquent, RentalPlanStatus.Active, RentalPlanStatus.OnHold] stat = { 'buy': { 'last_date': last_order_buy.create_date if last_order_buy else '', 'status': 'Active' if last_order_buy else 'Inactive', 'earned_total': user.buyorder_set.aggregate(Sum('total'))['total__sum'] or 0, 'earned_avg': user.buyorder_set.aggregate(Avg('total'))['total__avg'] or 0, }, 'trade': { 'last_date': last_order_trade.create_date if last_order_trade else '', 'status': 'Active' if last_order_trade else 'Inactive', 'earned_total': user.tradeorder_set.aggregate(Sum('total'))['total__sum'] or 0, 'earned_avg': user.tradeorder_set.aggregate(Avg('total'))['total__avg'] or 0, }, 'rent': { 'last_date': last_order_rent.date_rent if last_order_rent else '', 'status': profile.get_rental_status(False), 'cancelable': rent_plan_cancelable, 'earned_total': user.billinghistory_set.filter(status=0, type=1).aggregate(Sum('debit'))['debit__sum'] or 0, 'earned_avg': user.billinghistory_set.filter(status=0, type=1).aggregate(Avg('debit'))['debit__avg'] or 0, 'rent_plan': rent_plan, 'hold_until': rent_plan.hold_reactivate_timestamp if (rent_plan and rent_plan.status == RentalPlanStatus.OnHold) else None, }, } stat['earned_total'] = (stat['buy']['earned_total'] + stat['trade']['earned_total'] + stat['rent']['earned_total']) / 3 stat['earned_avg'] = (stat['buy']['earned_avg'] + stat['trade']['earned_avg'] + stat['rent']['earned_avg']) / 3 last_order = {} last_order['buy'] = last_orders_buy last_order['trade'] = last_order_trade last_order['rent'] = last_order_rent buy_cart, created = BuyCart.objects.get_or_create(user=user) #@UnusedVariable trade_list = user.tradelist.all() return { 'current_view': 'customer_view', 'user': user, 'billing_address': user.get_profile().get_billing_address_data(), 'stat': stat, 'last_order': last_order, 'cart': buy_cart, 'cart_total': sum([item.get_retail_price() * item.quantity for item in buy_cart.items.all()]), 'trade_list': trade_list, 'trade_total': sum([item.get_price() for item in trade_list]), 'not_activated_user': not_activated_user, 'account_is_blocked': account_is_blocked, 'can_block_account': can_block_account, 'can_change_extra_slots': can_change_extra_slots, 'claims': Claim.objects.filter(user=user), }