def get_queryset(self): qs = super(UserListView, self).get_queryset().prefetch_related( Prefetch('card_statuses', CardStatus.objects.filter(season=season()).select_related('pickup_location'), to_attr='card_status_list')) self.filter = UserFilter(self.request.GET, queryset=qs) qs = self.filter.qs return qs.distinct()
def get_top_scorers(): current_year = season() goals = Goal.objects.filter(match__competition_year__year=current_year).select_related('scorer').prefetch_related( 'match__competition_year__competition') competition_years = CompetitionYear.objects.filter(year=current_year).select_related() competition_dct = OrderedDict() competitions = OrderedDict() for competition_year in competition_years: # if competition_year.year == current_year: competition_dct[competition_year.competition_id] = 0 competitions[competition_year.competition_id] = competition_year.competition.name players = OrderedDict() for goal in goals: if goal.own_goal: continue competition_id = goal.match.competition_year.competition_id if goal.scorer not in players: players[goal.scorer] = {} players[goal.scorer]['competitions'] = competition_dct.copy() players[goal.scorer]['total'] = 0 players[goal.scorer]['competitions'][competition_id] += 1 players[goal.scorer]['total'] += 1 players = OrderedDict(sorted(players.items(), key=lambda item: item[1]['total'], reverse=True)) context = { 'players': players, 'competitions': competitions } return context
def get_top_scorers(): current_year = season() goals = Goal.objects.filter( match__competition_year__year=current_year).select_related( 'scorer').prefetch_related('match__competition_year__competition') competition_years = CompetitionYear.objects.filter( year=current_year).select_related() competition_dct = OrderedDict() competitions = OrderedDict() for competition_year in competition_years: # if competition_year.year == current_year: competition_dct[competition_year.competition_id] = 0 competitions[competition_year. competition_id] = competition_year.competition.name players = OrderedDict() for goal in goals: if goal.own_goal: continue competition_id = goal.match.competition_year.competition_id if goal.scorer not in players: players[goal.scorer] = {} players[goal.scorer]['competitions'] = competition_dct.copy() players[goal.scorer]['total'] = 0 players[goal.scorer]['competitions'][competition_id] += 1 players[goal.scorer]['total'] += 1 players = OrderedDict( sorted(players.items(), key=lambda item: item[1]['total'], reverse=True)) context = {'players': players, 'competitions': competitions} return context
def get_queryset(self): qs = super(UserListView, self).get_queryset().prefetch_related( Prefetch('card_statuses', CardStatus.objects.filter( season=season()).select_related('pickup_location'), to_attr='card_status_list')) self.filter = UserFilter(self.request.GET, queryset=qs) qs = self.filter.qs return qs.distinct()
def save(self, *args, **kwargs): super().save(*args, **kwargs) CardStatus.objects.update_or_create( user=self.instance, season=season(), defaults={ 'status': 'Awaiting Approval', 'pickup_location': self.cleaned_data['pickup_location'] })
def approve(self): if not self.devil_no: max_devil_no = User.objects.aggregate(Max('devil_no'))['devil_no__max'] if max_devil_no is None: max_devil_no = 100 self.devil_no = max_devil_no + 1 self.status = 'Member' self.save() card_status, __ = CardStatus.objects.update_or_create(user=self, season=season(), defaults={'status': 'Awaiting Print'}) card_status.notify()
def card_status(self): if hasattr(self, 'card_status_list'): lst = self.card_status_list if lst: return lst[0].status else: return '' try: return self.card_statuses.get(season=season()).status except CardStatus.DoesNotExist: return ''
def pickup_location(self): if hasattr(self, 'card_status_list'): lst = self.card_status_list if lst: return lst[0].pickup_location or '' else: return '' try: return self.card_statuses.get(season=season()).pickup_location or '' except CardStatus.DoesNotExist: return ''
def card_status(self): if hasattr(self, 'card_status_list'): lst = self.card_status_list if lst: return lst[0].status else: return '' try: return self.card_statuses.get(season=season()).status except CardStatus.DoesNotExist: return ''
def pickup_location(self): if hasattr(self, 'card_status_list'): lst = self.card_status_list if lst: return lst[0].pickup_location or '' else: return '' try: return self.card_statuses.get( season=season()).pickup_location or '' except CardStatus.DoesNotExist: return ''
def approve(self): if not self.devil_no: max_devil_no = User.objects.aggregate( Max('devil_no'))['devil_no__max'] if max_devil_no is None: max_devil_no = 100 self.devil_no = max_devil_no + 1 self.status = 'Member' card_status, __ = CardStatus.objects.update_or_create( user=self, season=season(), defaults={'status': 'Awaiting Print'}) card_status.notify() self.save()
def esewa_success(request): # {u'oid': [u'm_2_2015'], u'amt': [u'150'], u'refId': [u'0000ELD']} response = dict(request.GET) if not request.user.is_authenticated: messages.error( request, 'An error occurred. Please contact us to complete your registration.' ) mail_admins('[MUSCN] Esewa Failure: No user session', str(response)) return redirect('/') user = request.user payment_type = 'Renewal' if user.status == 'Expired' else 'Membership' amount = response.get('amt') if type(amount) == list: amount = amount[0] amount = float(amount) ref_id = response['refId'][0] pid = response['oid'][0] user_id = int(pid.split('_')[1]) if request.user.id != user_id: messages.error( request, 'An error occurred. Please contact us to complete your registration.' ) mail_admins('[MUSCN] Esewa Failure: Invalid user id in product id', str(response)) return redirect('/') payment = Payment(user=request.user, amount=amount, type=payment_type) if payment.amount < MembershipSetting.get_solo().membership_fee: messages.error(request, 'You did not pay the full amount.') esewa_payment = EsewaPayment(amount=payment.amount, pid=pid, ref_id=ref_id) if esewa_payment.verify(unique=True): payment.save() esewa_payment.payment = payment # esewa_payment.get_details() esewa_payment.save() messages.success(request, 'Thank you for registering to be a member.') user.status = 'Pending Approval' user.save() try: cs = CardStatus.objects.get(user=user, season=season()) messages.success( request, 'You can pickup your package from %s after you are notified of it\'s availability.' % cs.pickup_location) return redirect(cs.pickup_location.get_absolute_url()) except CardStatus.DoesNotExist: mail_admins('[MUSCN] Esewa Warning: No card pickup location.', str(response)) return redirect('/') else: messages.error(request, 'Payment via eSewa failed!') return redirect(reverse_lazy('membership_form'))
def get_top_scorers_summary(): current_year = season() goals = Goal.objects.filter(match__competition_year__year=current_year, match__competition_year__competition__friendly=False).select_related('scorer') players = OrderedDict() for goal in goals: if goal.own_goal: continue if goal.scorer not in players: players[goal.scorer] = 0 players[goal.scorer] += 1 players = OrderedDict(sorted(players.items(), key=lambda item: item[1], reverse=True)) return players
def get_queryset(self): qs = User.objects.none() if 'q' in self.request.GET: qs = User.objects.all().prefetch_related( Prefetch( 'card_statuses', CardStatus.objects.filter( season=season()).select_related('pickup_location'), to_attr='card_status_list')) q = self.request.GET['q'] qs = qs.filter( Q(username__icontains=q) | Q(full_name__icontains=q) | Q(email__icontains=q) | Q(devil_no__contains=q) | Q(mobile__contains=q)) return qs
def get_queryset(self): qs = User.objects.none() if 'q' in self.request.GET: qs = User.objects.all().prefetch_related( Prefetch('card_statuses', CardStatus.objects.filter(season=season()).select_related('pickup_location'), to_attr='card_status_list')) q = self.request.GET['q'] qs = qs.filter( Q(username__icontains=q) | Q(full_name__icontains=q) | Q(email__icontains=q) | Q(devil_no__contains=q) | Q(mobile__contains=q) ) return qs
def get_top_scorers_summary(): current_year = season() goals = Goal.objects.filter( match__competition_year__year=current_year, match__competition_year__competition__friendly=False).select_related( 'scorer') players = OrderedDict() for goal in goals: if goal.own_goal: continue if goal.scorer not in players: players[goal.scorer] = 0 players[goal.scorer] += 1 players = OrderedDict( sorted(players.items(), key=lambda item: item[1], reverse=True)) return players
def esewa_success(request): # {u'oid': [u'm_2_2015'], u'amt': [u'150'], u'refId': [u'0000ELD']} response = dict(request.GET) if not request.user.is_authenticated: messages.error(request, 'An error occurred. Please contact us to complete your registration.') mail_admins('[MUSCN] Esewa Failure: No user session', str(response)) return redirect('/') user = request.user payment_type = 'Renewal' if user.status == 'Expired' else 'Membership' amount = response.get('amt') if type(amount) == list: amount = amount[0] amount = float(amount) ref_id = response['refId'][0] pid = response['oid'][0] user_id = int(pid.split('_')[1]) if request.user.id != user_id: messages.error(request, 'An error occurred. Please contact us to complete your registration.') mail_admins('[MUSCN] Esewa Failure: Invalid user id in product id', str(response)) return redirect('/') payment = Payment(user=request.user, amount=amount, type=payment_type) if payment.amount < MembershipSetting.get_solo().membership_fee: messages.error(request, 'You did not pay the full amount.') esewa_payment = EsewaPayment(amount=payment.amount, pid=pid, ref_id=ref_id) if esewa_payment.verify(unique=True): payment.save() esewa_payment.payment = payment # esewa_payment.get_details() esewa_payment.save() messages.success(request, 'Thank you for registering to be a member.') user.status = 'Pending Approval' user.save() try: cs = CardStatus.objects.get(user=user, season=season()) messages.success(request, 'You can pickup your package from %s after you are notified of it\'s availability.' % cs.pickup_location) return redirect(cs.pickup_location.get_absolute_url()) except CardStatus.DoesNotExist: mail_admins('[MUSCN] Esewa Warning: No card pickup location.', str(response)) return redirect('/') else: messages.error(request, 'Payment via eSewa failed!') return redirect(reverse_lazy('membership_form'))
def get_new_cards(): in_memory_file = BytesIO() awaiting_cards = CardStatus.objects.filter( status='Awaiting Print', user__status='Member', season=season()).select_related('user') zip_file = zipfile.ZipFile(in_memory_file, 'w') min = float('inf') max = 0 for awaiting_card in awaiting_cards: if awaiting_card.user.devil_no: fake_file = BytesIO() devil_no = awaiting_card.user.devil_no if devil_no < min: min = devil_no if devil_no > max: max = devil_no card = awaiting_card.user.get_card() card.save(fake_file, "png") zip_file.writestr(str(devil_no) + '.png', fake_file.getvalue()) zip_file.close() name = str(min) + '-' + str(max) + '.zip' return name, in_memory_file
def save(self, *args, **kwargs): super().save(*args, **kwargs) CardStatus.objects.update_or_create(user=self.instance, season=season(), defaults={'status': 'Awaiting Approval', 'pickup_location': self.cleaned_data[ 'pickup_location']})
def get_new_cards(): in_memory_file = BytesIO() awaiting_cards = CardStatus.objects.filter(status='Awaiting Print', user__status='Member', season=season()).select_related( 'user') zip_file = zipfile.ZipFile(in_memory_file, 'w') min = float('inf') max = 0 for awaiting_card in awaiting_cards: if awaiting_card.user.devil_no: fake_file = BytesIO() devil_no = awaiting_card.user.devil_no if devil_no < min: min = devil_no if devil_no > max: max = devil_no card = awaiting_card.user.get_card() card.save(fake_file, "png") zip_file.writestr(str(devil_no) + '.png', fake_file.getvalue()) zip_file.close() name = str(min) + '-' + str(max) + '.zip' return name, in_memory_file
def scrape(self): # url = 'http://calendar.manutd.com/Manchester_United.ics' # url = 'http://hackeragenda.urlab.be/events/events.ics' url = 'https://calendar.google.com/calendar/ical/ov0dk4m6dedaob7oqse4nrda4s%40group.calendar.google.com/public/basic.ics' cal_content = self.get_url_content(url) if cal_content: if (cal_content, bytes): cal_content = str(cal_content, 'utf-8') cal_content = cal_content.replace('RATE:', 'RDATE:') # cal = Calendar(cal_content.decode('iso-8859-1').replace('\n\n', ' ')) cal = Calendar(cal_content.replace('\n\n', ' ')) for event in cal.events: dt = event.begin.datetime try: fixture = Fixture.objects.get(datetime=dt) except Fixture.DoesNotExist: fixture = Fixture(datetime=dt) except Fixture.MultipleObjectsReturned: [ fix.delete() for fix in Fixture.objects.filter( datetime=dt).order_by('id')[1:] ] fixture = Fixture.objects.get(datetime=dt) # get match and competition_name from description splits = event.description.splitlines()[0].split(' - ') competition_name = splits[1].strip().split('.')[0] if competition_name == u'English Barclays Premier League': try: competition = Competition.objects.get( name='English Premier League') except Competition.DoesNotExist: competition = Competition.objects.create( name='English Premier League', short_name='EPL') elif competition_name == u'English FA Cup': try: competition = Competition.objects.get(name='FA Cup') except Competition.DoesNotExist: competition = Competition.objects.create(name='FA Cup') else: try: competition = Competition.objects.get( name=competition_name) except Competition.DoesNotExist: # raise Exception('Please add a competition with name : ' + competition_name) competition = Competition.objects.create( name=competition_name) # Check for pre-season matches year = str(season(fixture.datetime.date())) try: competition_year = CompetitionYear.objects.get( competition=competition, year=year) except CompetitionYear.DoesNotExist: # raise Exception('Please add a competition year with name and year : ' + competition_name + ' , ' + year) competition_year = CompetitionYear.objects.create( competition=competition, year=year) fixture.competition_year = competition_year if splits[0][:17] == 'Manchester United': fixture.is_home_game = True opponent_team_name = splits[0][20:].strip() else: fixture.is_home_game = False opponent_team_name = splits[0][:-20].strip() opponent_team_name = fix_unicode(opponent_team_name) try: opponent_team = Team.get(opponent_team_name) except Team.DoesNotExist: # raise Exception('Please add a team with name : ' + opponent_team_name) opponent_team = Team.objects.create( name=opponent_team_name) fixture.opponent = opponent_team try: fixture.venue = event.location.split('-')[1].strip() except IndexError: fixture.venue = event.location fixture.save()
def membership(self, request): if request.method == 'GET': if request.user.is_authenticated: data = UserSerializer(self.request.user, many=False).data data['membership_fee'] = MembershipSetting.get_solo().membership_fee data['pickup_locations'] = PartnerSer(Partner.objects.filter(pickup_location=True), many=True).data return Response(data) return Response({'status': 'error', 'detail': 'Not authenticated.'}, 401) if request.method == 'POST': user = request.user if not user.is_authenticated: return Response({'status': 'error', 'detail': 'Not authenticated.'}, 401) data = request.data if user.status == 'Pending Approval': raise APIException('Your membership request in pending approval.') if user.status == 'Member': raise APIException('You are already a member.') membership_setting = MembershipSetting.get_solo() if not data.get('full_name'): raise APIException('Full name is required.') if not data.get('mobile'): raise APIException('Mobile number is required.') if not data.get('pickup_location'): raise APIException('Pickup Location is required') user.full_name = data.get('full_name') user.mobile = data.get('mobile') user.save() CardStatus.objects.update_or_create(user=user, season=season(), defaults={'status': 'Awaiting Approval', 'pickup_location_id': data.get( 'pickup_location')}) payment_type = 'Renewal' if user.status == 'Expired' else 'Membership' payment = Payment(user=user, amount=float(membership_setting.membership_fee), type=payment_type, channel='Android') if data.get('esewa'): response = json.loads(data.get('esewa_response')) if float(response['totalAmount']) < float(payment.amount): raise APIException('You did not pay the full amount.') esewa_payment = EsewaPayment(amount=payment.amount, pid=response['productId'], ref_id=response['transactionDetails']['referenceId']) if esewa_payment.verify(): payment.save() esewa_payment.payment = payment esewa_payment.get_details() esewa_payment.save() else: raise APIException('Payment via eSewa failed!') elif data.get('receipt'): receipt_no = data.get('receipt_no') if not receipt_no: raise APIException('Receipt number is required.') elif not receipt_no.isdigit(): raise APIException('Invalid receipt number.') elif not ReceiptData.objects.filter(active=True, from_no__lte=receipt_no, to_no__gte=receipt_no).exists(): raise APIException('Invalid receipt number.') elif DirectPayment.objects.filter(receipt_no=receipt_no, payment__verified_by__isnull=False).exists(): raise APIException('Invalid receipt number.') else: payment.save() DirectPayment.objects.create(payment=payment, receipt_no=receipt_no) elif data.get('deposit'): if not request.data.get('voucher_image'): raise APIException('Voucher image is required.') else: payment.save() bd = BankDeposit.objects.create(payment=payment, voucher_image=request.data.get('voucher_image'), bank=BankAccount.objects.first()) if not bd.voucher_image: payment.delete() raise APIException('Could not save voucher image.') else: raise APIException('No payment method specified.') user.status = 'Pending Approval' user.save() data = UserSerializer(user, many=False).data return Response(data)
def scrape(self): # url = 'http://calendar.manutd.com/Manchester_United.ics' # url = 'http://hackeragenda.urlab.be/events/events.ics' url = 'https://calendar.google.com/calendar/ical/ov0dk4m6dedaob7oqse4nrda4s%40group.calendar.google.com/public/basic.ics' cal_content = self.get_url_content(url) if cal_content: if (cal_content, bytes): cal_content = str(cal_content, 'utf-8') cal_content = cal_content.replace('RATE:', 'RDATE:') # cal = Calendar(cal_content.decode('iso-8859-1').replace('\n\n', ' ')) cal = Calendar(cal_content.replace('\n\n', ' ')) for event in cal.events: dt = event.begin.datetime try: fixture = Fixture.objects.get(datetime=dt) except Fixture.DoesNotExist: fixture = Fixture(datetime=dt) except Fixture.MultipleObjectsReturned: [fix.delete() for fix in Fixture.objects.filter(datetime=dt).order_by('id')[1:]] fixture = Fixture.objects.get(datetime=dt) # get match and competition_name from description splits = event.description.splitlines()[0].split(' - ') competition_name = splits[1].strip().split('.')[0] if competition_name == u'English Barclays Premier League': try: competition = Competition.objects.get(name='English Premier League') except Competition.DoesNotExist: competition = Competition.objects.create(name='English Premier League', short_name='EPL') elif competition_name == u'English FA Cup': try: competition = Competition.objects.get(name='FA Cup') except Competition.DoesNotExist: competition = Competition.objects.create(name='FA Cup') else: try: competition = Competition.objects.get(name=competition_name) except Competition.DoesNotExist: # raise Exception('Please add a competition with name : ' + competition_name) competition = Competition.objects.create(name=competition_name) # Check for pre-season matches year = str(season(fixture.datetime.date())) try: competition_year = CompetitionYear.objects.get(competition=competition, year=year) except CompetitionYear.DoesNotExist: # raise Exception('Please add a competition year with name and year : ' + competition_name + ' , ' + year) competition_year = CompetitionYear.objects.create(competition=competition, year=year) fixture.competition_year = competition_year if splits[0][:17] == 'Manchester United': fixture.is_home_game = True opponent_team_name = splits[0][20:].strip() else: fixture.is_home_game = False opponent_team_name = splits[0][:-20].strip() opponent_team_name = fix_unicode(opponent_team_name) try: opponent_team = Team.get(opponent_team_name) except Team.DoesNotExist: # raise Exception('Please add a team with name : ' + opponent_team_name) opponent_team = Team.objects.create(name=opponent_team_name) fixture.opponent = opponent_team try: fixture.venue = event.location.split('-')[1].strip() except IndexError: fixture.venue = event.location fixture.save()
def get_queryset(self): return super(UserListView, self).get_queryset().prefetch_related( Prefetch('card_statuses', CardStatus.objects.filter( season=season()).select_related('pickup_location'), to_attr='card_status_list'))