def payment_form(request): context = {} context['page_title'] = u'Оплата услуг ПроБЕГу' user = request.user if 'btnPayment' in request.POST: form = PaymentForm(request.POST, user=request.user) if form.is_valid(): payment = form.save() payment.transaction_id = DESCRIPTION_PREFIX + unicode(payment.id) payment.is_test_mode = False payment.user = user if user.is_authenticated() else None payment.save() payment.refresh_from_db() payment.signature = get_payment_md5(payment) payment.save() models.write_log('Redirecting to {}'.format(get_redirect_url(payment))) # messages.success(request, u'Адрес для переадресации: {}'.format(get_redirect_url(payment))) return redirect(get_redirect_url(payment)) else: messages.warning(request, u"Пожалуйста, исправьте ошибки в форме.") else: form = PaymentForm(user=request.user) context['form'] = form return render(request, "payment/payment_form.html", context)
def klb_make_individual_payment(request, year): context = user_edit_vars(request.user) year = models.int_safe(year) if not models.is_active_klb_year(year, context['is_admin']): messages.warning(request, u'Сейчас нельзя заявиться в КЛБМатч–{}'.format(year)) return redirect(reverse('results:klb_match_summary', kwargs={'year': year})) participant = models.Klb_participant.objects.filter(klb_person__runner__user_id=request.user.id, match_year=year).first() if not participant: messages.warning(request, u'Вы ещё не заявлены в КЛБМатч–{}'.format(year)) return redirect(reverse('results:klb_application', kwargs={'year': year})) person = participant.klb_person if participant.paid_status != models.PAID_STATUS_NO: messages.warning(request, u'Вы уже оплатили участие в КЛБМатче–{}'.format(year)) return redirect(person) if participant.team and not participant.team.club.members_can_pay_themselves: messages.warning(request, u'Ваше участие в КЛБМатче может оплатить только капитан команды «{}»; Вам достаточно передать деньги ему.'.format( participant.team.name)) return redirect(person) payment = models.Payment_moneta.objects.create( amount=models_klb.get_participation_price(year), description=u'Оплата за себя: {} {}'.format(person.fname, person.lname), user=request.user, sender=request.user.get_full_name(), ) payment.refresh_from_db() payment.transaction_id = DESCRIPTION_PREFIX + unicode(payment.id) payment.signature = get_payment_md5(payment) payment.save() participant.payment = payment participant.save() models.write_log('klb_make_individual_payment: Redirecting to {}'.format(get_redirect_url(payment))) return redirect(get_redirect_url(payment))
def pay_url_tmp(request): params = request.POST if (request.method == 'POST') else request.GET models.write_log(u'At {} we received a response from Moneta. Method: {}. Params: {}'.format(timezone.now(), request.method, params)) response = models.Payment_moneta_response.objects.create( account_number=params.get('MNT_ID', ''), transaction_id=params.get('MNT_TRANSACTION_ID', ''), moneta_operation_id=params.get('MNT_OPERATION_ID', ''), moneta_subscriber_id=params.get('MNT_SUBSCRIBER_ID', ''), moneta_user_account=params.get('MNT_USER', ''), moneta_user_corr_account=params.get('MNT_CORRACCOUNT', ''), payment_system=params.get('paymentSystem_unitId', ''), withdraw_amount=params.get('MNT_AMOUNT', 0), fee=params.get('MNT_FEE', 0), currency=params.get('MNT_CURRENCY_CODE', ''), is_test_mode=(params.get('MNT_TEST_MODE') == '1'), signature=params.get('MNT_SIGNATURE', ''), ) response.refresh_from_db() response.is_signature_correct = (get_response_md5(response) == response.signature) response.save() payment = models.Payment_moneta.objects.filter(transaction_id=response.transaction_id).first() if payment is None: raise ValueError(u'Не найден платёж с id {}'.format(response.transaction_id)) to_return_ok = True if payment.response: raise ValueError(u'Получено повторное сообщение об оплате платежа с id {}. Скорее всего, всё хорошо!'.format(response.transaction_id)) payment.response = response payment.payment_time = timezone.now() payment.amount = response.withdraw_amount payment.withdraw_amount = response.withdraw_amount + response.fee payment.is_paid = True payment.save() participants_paid = [] participants_paid_before = [] medal_order = None for participant in payment.klb_participant_set.select_related('klb_person', 'team'): if participant.paid_status == models.PAID_STATUS_NO: participant.paid_status = models.PAID_STATUS_FREE if participant.wants_to_pay_zero else models.PAID_STATUS_FULL participant.wants_to_pay_zero = False participant.save() models.log_obj_create(payment.user, participant.klb_person, models.ACTION_KLB_PARTICIPANT_UPDATE, child_object=participant, field_list=['paid_status', 'wants_to_pay_zero'], comment=u'Платёж {}'.format(payment.id), verified_by=models.USER_ROBOT_CONNECTOR) participants_paid.append(participant) else: participants_paid_before.append(participant) if hasattr(payment, 'medal_order'): medal_order = payment.medal_order send_success_mail(payment, response, participants_paid, participants_paid_before, medal_order) return HttpResponse(u'SUCCESS' if to_return_ok else u'FAIL', content_type='text/plain')
def update_series_results(series, user, reverse_races=False): new_races = [] # print "Trying to read url {}".format(series.url_site + '/results/eventhistory/') url_history = series.url_site + '/results/eventhistory/' result, response, _ = results_util.read_url(url_history) if not result: models.send_panic_email( 'views_parkrun: update_series_results: problem with event history', u"Couldn't load event history for {}, id={}, from url {}".format( series.name, series.id, url_history)) return [] html = response.read().decode('utf-8') new_races_created = False parts = parkrun_result_history_re.findall(html) if reverse_races: parts.reverse() runners_touched = set() for item in parts: url_event, event_num, ev_day, ev_month, ev_year, n_runners = item event_date = datetime.date(results_util.int_safe(ev_year), results_util.int_safe(ev_month), results_util.int_safe(ev_day)) url_results = series.url_site + '/results' + url_event[2:] existed, race = get_or_create_parkrun_event_and_race( series, url_results, event_date, results_util.int_safe(event_num), user) if race.loaded != models.RESULTS_LOADED: models.write_log(u"New event found: {}".format(item)) n_results, new_runners_touched = load_race_results( race, url_results, user) runners_touched |= new_runners_touched new_races.append((race, n_results, existed)) if not existed: new_races_created = True elif not reverse_races: if new_races_created: # Maybe there were some extra parkruns, e.g. for New Year/Christmas fix_parkrun_numbers(race.event_id) break for runner in runners_touched: update_runner_stat(runner=runner) if runner.user: update_runner_stat(user=runner.user, update_club_members=False) return new_races, runners_touched
def create_future_parkruns(series, user, debug=False): events_created = 0 events = models.Event.objects.filter(series=series).order_by('-start_date') last_event = events.first() if last_event is None: models.write_log( u"Couldn't find any events for series {}, id {}. Stopped creating future events." .format(series, series.id), debug=debug) return 0 if last_event.number is None: if events.count() == 1: last_event.number = 1 if not last_event.name.endswith(u'№1'): last_event.name += u' №1' last_event.start_time = "09:00" last_event.save() else: models.write_log( u"Problem with event number for series {}, id {}. Stopped creating future events." .format(series, series.id), debug=debug) return 0 if (last_event.number == 1) and not last_event.race_set.exists( ): # So it's enough to create first event in series without any distances race = models.Race.objects.create(event=last_event, distance=PARKRUN_DISTANCE, created_by=user) race.clean() race.save() event_number = last_event.number + 1 event_date = last_event.start_date + datetime.timedelta(days=7) month_from_now = datetime.date.today() + datetime.timedelta(days=34) while event_date <= month_from_now: existed, race = get_or_create_parkrun_event_and_race( series, '', event_date, event_number, user) if not existed: events_created += 1 event_number += 1 event_date += datetime.timedelta(days=7) return events_created
def update_parkrun_results(email=""): models.write_log(u"{} Started parkrun update...".format( datetime.datetime.now())) new_races = [] runners_touched = set() future_events_created = 0 for series in models.Series.get_russian_parkruns().filter( is_parkrun_closed=False).order_by('id'): races, runners = update_series_results(series, models.USER_ROBOT_CONNECTOR) new_races += races runners_touched |= runners future_events_created += create_future_parkruns( series, models.USER_ROBOT_CONNECTOR) time.sleep(5) for runner in runners_touched: update_runner_stat(runner=runner) if runner.user: update_runner_stat(user=runner.user, update_club_members=False) update_results_count() update_events_count() models.write_log(u"{} Finished parkrun update.".format( datetime.datetime.now())) generate_parkrun_stat_table() models.write_log(u"{} Generated new parkrun statistics table.".format( datetime.datetime.now())) if email: return send_update_results(new_races, future_events_created, email)
def load_race_results(race, url_results, user, load_only_russians=False): result, response, _ = results_util.read_url(url_results) if not result: models.write_log( u"Couldn't load results for parkrun {}, id={}, from url {}".format( race.event, race.event.id, url_results)) return 0, set() html = response.read().decode('utf-8') race.result_set.filter(source=models.RESULT_SOURCE_DEFAULT).delete() results_added = 0 runners_touched = set() category_sizes = { category_size.name: category_size for category_size in race.category_size_set.all() } category_lower_to_orig = {name.lower(): name for name in category_sizes} new_results = [] for group in parkrun_result_re.finditer(html): groupdict = group.groupdict('') parkrun_id = results_util.int_safe(groupdict['parkrun_id']) lname, fname, midname = split_name(groupdict['name'].strip().title(), first_name_position=0) gender = models.string2gender(groupdict['gender'].strip()) if gender == models.GENDER_UNKNOWN: models.send_panic_email( 'views_parkrun: load_race_results: problem with gender', u"Problem with race id {}, url {} : gender '{}' cannot be parsed" .format(race.id, url_results, groupdict['gender']), ) runner, created = models.Runner.objects.get_or_create( parkrun_id=parkrun_id, defaults={ 'lname': lname, 'fname': fname, 'gender': gender }) centiseconds = models.string2centiseconds(groupdict['result']) if centiseconds == 0: models.send_panic_email( 'views_parkrun: load_race_results: problem with time', u"Problem with race id {}, url {} : time '{}' cannot be parsed" .format(race.id, url_results, groupdict['result']), ) category = groupdict['category'] if category: category_lower = category.lower() if category_lower not in category_lower_to_orig: category_sizes[category] = models.Category_size.objects.create( race=race, name=category) category_lower_to_orig[category_lower] = category new_results.append( models.Result( race=race, runner=runner, user=runner.user, parkrun_id=parkrun_id, name_raw=groupdict['name'], time_raw=groupdict['result'], club_raw=groupdict['club'], club_name=groupdict['club'], place_raw=results_util.int_safe(groupdict['place']), result=centiseconds, status=models.STATUS_FINISHED, status_raw=models.STATUS_FINISHED, category_size=category_sizes[ category_lower_to_orig[category_lower]] if category else None, category_raw=category, comment=groupdict['comment1'] + groupdict['comment2'], lname=lname, fname=fname, midname=midname, gender=gender, gender_raw=gender, loaded_by=user, loaded_from=url_results, )) runners_touched.add(runner) models.Result.objects.bulk_create(new_results) fill_places(race) fill_race_headers(race) if len(new_results) > 0: race.loaded = models.RESULTS_LOADED race.save() models.write_log(u"Race {}: {} results are loaded".format( race, len(new_results))) return len(new_results), runners_touched