def user_edit_vars(user, series=None, club=None): context = {} context['is_admin'] = False context['is_editor'] = False context['is_extended_editor'] = False context['to_show_rating'] = True if user.is_authenticated: if models.is_admin(user): context['is_admin'] = True else: if series: if models.Series_editor.objects.filter(user=user, series=series).exists(): context['is_editor'] = True if hasattr(user, 'user_profile'): context[ 'is_extended_editor'] = user.user_profile.is_extended_editor elif club: context['is_editor'] = models.Club_editor.objects.filter( user=user, club=club).exists() else: context['is_editor'] = user.groups.filter( name="editors").exists() context['is_club_leader'] = user.club_editor_set.exists() return context
def runners_list(request, runner_id=None, race_id=None): results = [] user = request.user query = request.GET.get('query', '').strip() runners = models.Runner.objects.select_related('city__region__country') if len(query) >= MIN_QUERY_LENGTH: if models.is_admin(user): query_as_number = results_util.int_safe(query) if query_as_number: runners = runners.filter(pk=query_as_number) else: runners = filter_by_name(runners, query) if runner_id: # When merging runner with id=runner_id with other runner runners = runners.exclude(pk=runner_id) elif race_id: # When choosing only runners without results on current race race = models.Race.objects.filter(pk=race_id).first() if race: runners_in_race = set(race.result_set.values_list('runner_id', flat=True)) runners = runners.exclude(pk__in=runners_in_race) elif user.club_editor_set.exists(): # When club manager wants to enter club members' unofficial results runners = filter_by_name(runners.filter(pk__in=models.get_runner_ids_for_user(user)), query) for runner in runners.order_by('lname', 'fname', 'birthday')[:(2 * MAX_ENTRIES)]: results.append({ 'id': runner.id, 'text': runner.get_name_for_ajax_select(), }) res = json.dumps(results) return HttpResponse(res, content_type='application/json')
def claim_result(request, result_id): result = get_object_or_404(models.Result, pk=result_id) race = result.race event = race.event user = request.user will_be_counted_for_klb = False reason = '' if result.status == models.STATUS_FINISHED: is_klb_participant, can_be_counted_for_klb, _ = check_event_for_klb( user, event) if is_klb_participant and can_be_counted_for_klb: klb_status = result.race.get_klb_status() will_be_counted_for_klb = (klb_status == models.KLB_STATUS_OK) reason = models.KLB_STATUSES[klb_status][1] res, message = result.claim_for_runner(user, user.runner, comment=request.GET.get( 'comment', ''), is_for_klb=will_be_counted_for_klb) if res: messages.success( request, u'Результат {} на забеге «{}» успешно Вам засчитан.'.format( result, race)) if will_be_counted_for_klb: if models.is_admin(user): create_klb_result( result, user.runner.klb_person, user, comment=u'При добавлении себе результата со страницы забега' ) messages.success(request, u'Он засчитан Вам в КЛБМатч.') else: messages.success( request, u'Он будет засчитан Вам в КЛБМатч после одобрения модератором.' ) elif reason: messages.warning( request, u'Он не будет учтён в КЛБМатче. Причина: '.format(reason)) runner = result.runner update_runner_stat(runner=runner) if runner.user: update_runner_stat(user=runner.user, update_club_members=False) if result.place_gender == 1: race.fill_winners_info() else: messages.warning( request, u'Результат {} на забеге «{}» не засчитан Вам. Причина: {}'.format( result, race, message)) return redirect(race)
def delete_unofficial_result(request, result_id): result = get_object_or_404(models.Result, pk=result_id) result_user = result.user race = result.race user = request.user if hasattr(result, 'klb_result'): messages.warning( request, u'Вы не можете удалить результат, учтённый в КЛБМатче. Если это не Ваш результат, пожалуйста, напишите нам на {}' ).format(models.INFO_MAIL) elif (result_user != user) and (not models.is_admin(user)) and ( result.runner not in user.user_profile.get_runners_to_add_results()): messages.warning(request, u'Вы не можете удалить чужой результат.') elif result.source == models.RESULT_SOURCE_DEFAULT: messages.warning( request, u'Вы не можете удалить этот результат – он взят из протокола соревнований.' ) else: runner = result.runner models.log_obj_create(user, race.event, models.ACTION_RESULT_DELETE, child_object=result) result.delete() update_runner_stat(runner=runner) if result_user: update_runner_stat(user=result_user, update_club_members=False) if result_user == user: messages.success( request, u'Ваш неофициальный результат на забеге {} успешно удалён.'. format(race.name_with_event())) else: runner_name = '' if result_user: runner_name = result_user.get_full_name() elif runner: runner_name = runner.name() messages.success( request, u'Неофициальный результат бегуна {} на забеге {} успешно удалён.' .format(runner_name, race.name_with_event())) return redirect(race)
def payment_delete(request, payment_id): payment = get_object_or_404(models.Payment_moneta, pk=payment_id, is_active=True) if payment.is_paid: messages.success(request, u'Заказ с номером {} на сумму {} ₽ уже оплачен'.format(payment.transaction_id, payment.amount)) return redirect('results:my_payments') if payment.is_dummy: messages.success(request, u'Заказ с номером {} — ненастоящий. Его нельзя удалить.'.format(payment.transaction_id)) return redirect('results:my_payments') if (not models.is_admin(request.user)) and (payment.user_id != request.user.id): user_club_ids = set(request.user.club_editor_set.values_list('club_id', flat=True)) payment_participants_club_ids = set(payment.klb_participant_set.exclude(team=None).values_list('team__club_id', flat=True)) if not (user_club_ids & payment_participants_club_ids): messages.warning(request, u'Заказ с номером {} — не Ваш. Оплатить его может только его создатель.'.format(payment.transaction_id)) return redirect('results:my_payments') if 'btnDeletePayment' in request.POST: payment.is_active = False payment.save() payment.klb_participant_set.update(payment=None, wants_to_pay_zero=False) messages.success(request, u'Заказ с номером {} успешно удалён'.format(payment.transaction_id)) return redirect('results:my_payments')
def remove_from_match(request, year): year = models.int_safe(year) target = redirect( reverse('results:klb_match_summary', kwargs={'year': year})) if not models.is_active_klb_year(year, models.is_admin(request.user)): messages.warning( request, u'Участников КЛБМатча–{} сейчас нельзя редактировать'.format(year)) return target participant = None user = request.user if hasattr(user, 'runner'): person = user.runner.klb_person if person: participant = person.klb_participant_set.filter( match_year=year).first() if participant is None: messages.warning(request, u'Вы и не были заявлены в КЛБМатч–{}'.format(year)) return target if person.klb_result_set.filter( race__event__start_date__year=year).exists(): messages.warning(request, ( u'У Вас уже есть результаты в зачёт КЛБМатча–{}. Если Вы всё равно хотите отказаться от участия, ' + u'пожалуйста, напишите нам на {}').format(year, models.KLB_MAIL)) return target if participant.team: messages.warning( request, (u'Вы заявлены в КЛБМатч–{} за команду «{}». ' + u'Для отзаявки обратитесь, пожалуйста, к руководителю клуба' ).format(year, participant.team.name)) return target models.log_klb_participant_delete(user, participant) participant.delete() messages.warning(request, u'Вы успешно отзаявлены из КЛБМатча–{}'.format(year)) return target
def add_review(request): context = {} message_text = '' res = {} res['success'] = 0 if request.method == 'POST': user = request.user form = forms.AddReviewForm(request.POST, request.FILES) if form.is_valid(): event = get_object_or_404(models.Event, pk=form.cleaned_data['event_id']) attachment = request.FILES.get('attachment', None) doc_type = results_util.int_safe(form.cleaned_data['doc_type']) doc_type_name = u'отчёт' if doc_type == models.DOC_TYPE_IMPRESSIONS else u'фотоальбом' doc = models.Document.objects.create( event=event, document_type=doc_type, loaded_type=models.LOAD_TYPE_LOADED if attachment else models.LOAD_TYPE_NOT_LOADED, upload=attachment, url_original=form.cleaned_data['url'], author=form.cleaned_data['author'], created_by=user) models.log_obj_create(user, event, models.ACTION_DOCUMENT_CREATE, child_object=doc) doc.process_review_or_photo() generate_last_added_reviews() res['success'] = 1 res['link'] = models.SITE_URL + event.get_absolute_url() if not models.is_admin(user): message_from_site = models.Message_from_site.objects.create( sender_name=user.first_name + ' ' + user.last_name, sender_email=models.ROBOT_MAIL_HEADER, target_email=models.INFO_MAIL, # target_email='*****@*****.**', title=u'Добавлен новый {} к забегу {} ({})'.format( doc_type_name, event.name, event.date(with_nobr=False)), attachment=attachment, ) if attachment: body = u'Только что пользователь {} ({}{}) добавил на сайт отчёт к забегу «{}»:\n\n {}/{}\n\n'.format( user.get_full_name(), models.SITE_URL, user.user_profile.get_absolute_url(), unicode(event), models.SITE_URL_OLD, message_from_site.attachment.name) else: body = u'Только что пользователь {} ({}{}) добавил на сайт ссылку на {} к забегу «{}»:\n{}\n\n'.format( user.get_full_name(), models.SITE_URL, user.user_profile.get_absolute_url(), doc_type_name, unicode(event), form.cleaned_data['url']) body += u'Все документы забега: {}{}\n\n'.format( models.SITE_URL, event.get_absolute_url()) body += u'Успешных стартов!\nВаш робот' message_from_site.body = body message_from_site.save() message_from_site.try_send(attach_file=False) else: res['error'] = get_first_form_error(form) else: res['error'] = u'Запрос не получен.' return HttpResponse(json.dumps(res), content_type='application/json')
def send_messages_with_results(): user_ids = set(models.Result_for_mail.objects.filter(is_sent=False).values_list('user_id', flat=True)) yesterday = timezone.now() - datetime.timedelta(days=1) checked_users_added_to_teams = set() users_added_to_teams = {} for added_data in models.User_added_to_team_or_club.objects.filter(added_time__gte=yesterday, team__isnull=False).select_related( 'user', 'team', 'added_by__user_profile').order_by('-added_time'): if added_data.user in checked_users_added_to_teams: continue participant = added_data.team.klb_participant_set.filter(klb_person__runner__user=added_data.user).first() if participant: users_added_to_teams[added_data.user] = { 'team': added_data.team, 'added_by': added_data.added_by, 'added_data': added_data, 'date_registered': participant.date_registered, 'added_by_admin': models.is_admin(added_data.added_by), } user_ids.add(added_data.user.id) # print 'Adding for user', added_data.user.id, ':', users_added_to_teams[added_data.user] checked_users_added_to_teams.add(added_data.user) checked_users_added_to_clubs = set() users_added_to_clubs = {} for added_data in models.User_added_to_team_or_club.objects.filter(added_time__gte=yesterday, club__isnull=False).select_related( 'user', 'club', 'added_by__user_profile').order_by('-added_time'): if (added_data.user.id, added_data.club.id) in checked_users_added_to_clubs: continue club_member = added_data.club.club_member_set.filter(runner__user=added_data.user).first() if club_member: if added_data.user not in users_added_to_clubs: users_added_to_clubs[added_data.user] = [] users_added_to_clubs[added_data.user].append({ 'added_data': added_data, 'club_member': club_member, 'added_by_admin': models.is_admin(added_data.added_by), }) user_ids.add(added_data.user.id) checked_users_added_to_clubs.add((added_data.user.id, added_data.club.id)) n_messages_sent = 0 n_messages_error = 0 for user_id in user_ids: # ['37']: # for user_id in ['1']: # if not models.is_admin(user): # continue user = User.objects.get(pk=user_id) if not hasattr(user, 'user_profile'): continue profile = user.user_profile if user.email == '': continue if not user.is_active: continue if not profile.email_is_verified: continue if not profile.ok_to_send_results: continue added_to_team_data = users_added_to_teams.get(user) added_to_club_data = users_added_to_clubs.get(user) result = send_user_results_letter(user, models.USER_ROBOT_CONNECTOR, get_context_for_user_letter(user=user, added_to_team_data=added_to_team_data, added_to_club_data=added_to_club_data)) if result['success']: n_messages_sent += 1 user.result_for_mail_set.filter(is_sent=False).update(is_sent=True, sent_time=timezone.now()) if added_to_team_data: added_to_team_data['added_data'].sent_time = timezone.now() added_to_team_data['added_data'].save() # if added_to_club_data: # for item in added_to_club_data: # item['added_data'].sent_time = timezone.now() # item['added_data'].save() else: print u'Error with sending message to user {} (id {}): {}'.format(user.get_full_name(), user.id, result['error']) n_messages_error += 1 print '{} Messages with results sent: {}, errors: {}'.format(datetime.datetime.now(), n_messages_sent, n_messages_error)