コード例 #1
0
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))
コード例 #2
0
ファイル: views_payment.py プロジェクト: comcur/ProBEG
def all_payments(request, user_id=None):
    if 'btnCreateReport' in request.POST:
        start_date = None
        if request.POST.get('start_date'):
            start_date = datetime.datetime.strptime(
                request.POST.get('start_date'), '%Y-%m-%d').date()
        end_date = None
        if request.POST.get('end_date'):
            end_date = datetime.datetime.strptime(request.POST.get('end_date'),
                                                  '%Y-%m-%d').date()

        fname = create_report(start_date=start_date, end_date=end_date)
        # messages.success(request, u'Файл {} создан'.format(fname.split('/')[-1]))
        response = FileResponse(open(fname, 'rb'),
                                content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(
            fname.split('/')[-1])
        return response

    context = {}
    user = None
    if user_id:
        user = get_object_or_404(User, pk=user_id)

    # context['payments'] = models.Payment_moneta.objects.filter(pk__gte=60).select_related('response', 'user').order_by('-added_time')
    price = get_participation_price(models.CUR_KLB_YEAR)
    context['payments'] = models.Payment_moneta.objects.select_related(
        'response', 'user').annotate(
            Count('klb_participant'),
            n_participants_paid=price * Count(
                Case(When(klb_participant__paid_status=models.PAID_STATUS_FULL,
                          then=1),
                     output_field=IntegerField()))).order_by('-added_time')

    context['show_unpaid_payments'] = (
        'show_unpaid_payments' in request.POST) or (user_id and
                                                    (request.method == 'GET'))
    if not context['show_unpaid_payments']:
        context['payments'] = context['payments'].filter(
            is_paid=True, added_time__gte=datetime.date(2018, 12, 1))

    if user:
        context['page_title'] = u'Все платежи пользователя {}'.format(
            user.get_full_name())
        context['cur_user'] = user
        context['payments'] = context['payments'].filter(user=user)
    else:
        context['page_title'] = u'Вообще все платежи'

    return render(request, "editor/payment/all_payments.html", context)
コード例 #3
0
ファイル: views_payment.py プロジェクト: comcur/ProBEG
def payment_details(request, payment_id):
    payment = get_object_or_404(models.Payment_moneta, pk=payment_id)
    context = {}
    context['payment'] = payment
    context['page_title'] = u'Платёж № {}'.format(payment_id)
    context['participants'] = payment.klb_participant_set.select_related(
        'klb_person', 'team').order_by('klb_person__lname',
                                       'klb_person__fname')
    context['CUR_KLB_YEAR'] = models.CUR_KLB_YEAR
    context['price'] = get_participation_price(models.CUR_KLB_YEAR)
    context['participants_amount_sum'] = context['participants'].filter(
        paid_status=models.PAID_STATUS_FULL).count() * context['price']

    return render(request, "editor/payment/payment_details.html", context)
コード例 #4
0
ファイル: views_klb.py プロジェクト: comcur/ProBEG
def application_payment(request, year=models.CUR_KLB_YEAR):
    context = user_edit_vars(request.user)
    year = models.int_safe(year)
    if not models.is_active_klb_year(year, context['is_admin']):
        year = models.CUR_KLB_YEAR
    context['year'] = year
    context['price'] = models_klb.get_participation_price(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:
        club = participant.team.club
        if not club.members_can_pay_themselves:
            messages.warning(
                request,
                u'Ваше участие в КЛБМатче может оплатить только капитан команды; Вам достаточно передать деньги ему.'
            )
            return redirect(person)
        context['club'] = club

    if participant.is_senior:
        context['can_pay_zero'] = True
        age = year - person.birthday.year
        context['reason'] = u'на конец {} года Вам будет {} {}'.format(
            year, age, plural_ending_11(age))
    elif person.disability_group != 0:
        context['can_pay_zero'] = True
        context['reason'] = u'у Вас {} группа инвалидности'.format(
            person.disability_group)
    else:
        context['can_pay_zero'] = False
    return render(request, 'klb/application_payment.html', context)
コード例 #5
0
def team_or_club_payment(request, team_id=None, club_id=None):
    team, club, team_or_club, year, context, target, participants = get_team_club_year_context_target(
        request, team_id, club_id)
    if target:
        return target

    unfinished_payment_ids = set(
        participants.exclude(payment=None).filter(
            payment__is_paid=False).values_list('payment_id', flat=True))
    context['unfinished_payments'] = models.Payment_moneta.objects.filter(
        is_active=True, pk__in=unfinished_payment_ids).select_related(
            'user__user_profile').order_by('-added_time')

    context['participants'] = participants.filter(
        paid_status=models.PAID_STATUS_NO,
        payment=None).select_related('klb_person').order_by(
            'klb_person__lname', 'klb_person__fname', 'klb_person__midname')
    context['n_participants'] = context['participants'].count()

    if (context['n_participants']
            == 0) and (context['unfinished_payments'].count() == 0):
        messages.success(
            request, u'Участие в матче уже оплачено за {}. Ура!'.format(
                u'всю команду' if team else u'все команды клуба'))
        return redirect(team_or_club)

    context['page_title'] = u'{} «{}» в КЛБМатче–{}: оплата участия'.format(
        u'Команда' if team else u'Клуб', team_or_club.name, year)
    context['team'] = team
    context['club'] = club
    context['year'] = year
    context['price'] = get_participation_price(year)
    context['n_paid_participants'] = participants.exclude(
        paid_status=models.PAID_STATUS_NO).count()
    context['initial_total'] = context['n_participants'] * context['price']
    context['SENIOR_AGE_MALE'] = results_util.SENIOR_AGE_MALE
    context['SENIOR_AGE_FEMALE'] = results_util.SENIOR_AGE_FEMALE
    return render(request, 'klb/team_payment.html', context)
コード例 #6
0
ファイル: views_payment.py プロジェクト: comcur/ProBEG
def payment_add_participant(request, payment_id):
    if 'btnAddParticipant' in request.POST:
        payment = get_object_or_404(models.Payment_moneta, pk=payment_id)
        participant_id = models.int_safe(
            request.POST.get('select_participant'))
        participant = get_object_or_404(models.Klb_participant,
                                        pk=participant_id)
        person = participant.klb_person
        year = participant.match_year

        if not models.is_active_klb_year(year):
            messages.warning(
                request,
                u'Сейчас нельзя менять платежи за {} год'.format(year))
        elif participant.payment_id:
            messages.warning(
                request,
                u'Участник {} за {} год уже привязан к платежу с id {}'.format(
                    person, year, participant.payment_id))
        elif not payment.is_paid:
            messages.warning(
                request,
                u'Платёж с id {} ещё не оплачен. Такие редактировать нельзя'.
                format(payment.id))
        elif participant.paid_status != models.PAID_STATUS_NO:
            messages.warning(
                request,
                u'Участник {} за {} год и так помечен как оплативший участие. Что-то не то'
                .format(person, year))
        else:
            participant.payment = payment
            participant.is_paid_through_site = False
            amount_str = request.POST.get('amount')
            if amount_str == '0':
                participant.paid_status = models.PAID_STATUS_FREE
                participant.save()
                models.log_obj_create(
                    request.user,
                    person,
                    models.ACTION_KLB_PARTICIPANT_UPDATE,
                    child_object=participant,
                    field_list=[
                        'payment', 'is_paid_through_site', 'paid_status'
                    ],
                    comment=u'Добавлен к платежу {}'.format(payment.id),
                    verified_by=models.USER_ROBOT_CONNECTOR)
                messages.success(
                    request,
                    u'Участник {} за {} год добавлен к платежу как участвующий бесплатно'
                    .format(person, year))
            else:
                amount = models.int_safe(amount_str)
                if amount == get_participation_price(year):
                    participant.paid_status = models.PAID_STATUS_FULL
                    participant.save()
                    models.log_obj_create(
                        request.user,
                        person,
                        models.ACTION_KLB_PARTICIPANT_UPDATE,
                        child_object=participant,
                        field_list=[
                            'payment', 'is_paid_through_site', 'paid_status'
                        ],
                        comment=u'Добавлен к платежу {}'.format(payment.id),
                        verified_by=models.USER_ROBOT_CONNECTOR)
                    messages.success(
                        request,
                        u'Участник {} за {} год добавлен к платежу как участвующий за полную стоимость'
                        .format(person, year))
                else:
                    messages.warning(
                        request,
                        u'Участник {} за {} год не привязан к платежу: недопустимая цена участия {}'
                        .format(person, year, amount))
    return redirect(payment)
コード例 #7
0
def send_success_mail(payment, response, participants_paid, participants_paid_before, medal_order):
	body = u' Добрый день!\n\nТолько что, {}, нам перевели {} рублей.'.format(localtime(response.added_time), response.withdraw_amount)

	body += u'\nЗачислено {} ₽. Комиссия: {} ₽ ({:.2f} %).'.format(response.get_amount(), -response.fee, 100 * (-response.fee) / response.withdraw_amount)

	if not payment.is_active:
		body += u'\n\nЧто-то странное: этот платёж неактивен. По идее такие нельзя оплатить!'

	if response.moneta_subscriber_id:
		user = User.objects.filter(pk=response.moneta_subscriber_id).first()
		profile = user.user_profile if (user and hasattr(user, 'user_profile')) else None
	else:
		user = None
		profile = None

	if profile:
		body += u'\n\nПользователь: {} {}{}'.format(user.get_full_name(), models.SITE_URL, profile.get_absolute_url())
	else:
		body += u'\n\nПользователь неизвестен (id {})'.format(response.moneta_subscriber_id)
		if payment and payment.sender:
			body += u'.\nПлательщик указал имя {}'.format(payment.sender)

	if payment:
		body += u'\n\nНазначение платежа: «{}»'.format(payment.description)
	else:
		body += u'\n\nНазначение платежа потерялось.'
		n_responses = models.Payment_moneta_response.objects.filter(transaction_id=response.transaction_id).count()
		if n_responses > 1:
			body += u'\nЭто уже поступление № {} с таким ID платежа на нашем сайте.'.format(n_responses)
		elif n_responses == 0:
			body += u'\nПока у нас просто не создавалось платежей с таким ID.'

	body += u'\n\nID платежа на нашем сайте: {}'.format(response.transaction_id)

	body += u'\n\nID операции у Монеты: {}'.format(response.moneta_operation_id)

	if response.is_signature_correct:
		body += u'\n\nПодпись операции подлинная.'
	else:
		body += u'\n\nПодпись операции неверная. Возможно, где-то рядом враги!'

	if participants_paid:
		if len(participants_paid) > 1:
			body += u'\n\nОплачено {} участников КЛБМатча:'.format(len(participants_paid))
		else: 
			body += u'\n\nОплачен один участник КЛБМатча:'
		for participant in participants_paid:
			team_name = participant.team.name if participant.team else u'индивидуальный участник'
			amount = models_klb.get_participation_price(participant.match_year) if (participant.paid_status == models.PAID_STATUS_FULL) else 0
			body += u'\n{} год, {} ₽, {}, {}, {}{}'.format(participant.match_year, amount, participant.klb_person.get_full_name_with_birthday(), team_name,
				models.SITE_URL, participant.klb_person.get_absolute_url())

	if participants_paid_before:
		body += u'\n\nПовторно заплатили за {} участников КЛБМатча, нужно разобраться:'.format(len(participants_paid_before))
		for participant in participants_paid_before:
			team_name = participant.team.name if participant.team else u'индивидуальный участник'
			body += u'\n{} год, {}, {}, {}{}'.format(participant.match_year, participant.klb_person.get_full_name_with_birthday(), team_name,
				models.SITE_URL, participant.klb_person.get_absolute_url())

	if medal_order:
		delivery_method = medal_order.delivery_method
		body += u'\n\nСпособ доставки: {}.'.format(medal_order.get_delivery_method_short())
		if delivery_method == 2:
			body += u'\nАдрес: {} {}.'.format(medal_order.zipcode, medal_order.address)
		if medal_order.email:
			body += u'\nE-mail: {}'.format(medal_order.email)
		if medal_order.phone_number:
			body += u'\nТелефон: {}'.format(medal_order.phone_number)
		if medal_order.comment:
			body += u'\nКомментарий: {}'.format(medal_order.comment)
		body += u'\n\nВсе платежи за медали: {}{}'.format(models.SITE_URL, reverse('editor:all_medal_payments'))

	if profile:
		body += u'\n\nВсе платежи этого пользователя ({}): {}{}'.format(user.payment_moneta_set.count(), models.SITE_URL, profile.get_all_payments_url())

	body += u'\n\nВообще все платежи: {}{}'.format(models.SITE_URL, reverse('editor:all_payments'))

	body += u'\n\nХорошего дня!\n\nВаш робот'
	message_from_site = models.Message_from_site.objects.create(
		sender_name=models.USER_ROBOT_CONNECTOR.get_full_name(),
		sender_email=models.ROBOT_MAIL_HEADER,
		target_email=models.TOP_MAIL,
		# target_email='*****@*****.**',
		title=u'ПроБЕГ: Проведена успешная оплата',
		body=body,
	)
	message_from_site.try_send(attach_file=False)
コード例 #8
0
def klb_make_team_or_club_payment(request, team_id=None, club_id=None):
	team, club, team_or_club, year, context, target, participants = get_team_club_year_context_target(request, team_id, club_id)
	if target:
		return target

	if 'btnPayForTeam' not in request.POST:
		return redirect(team_or_club.get_payment_url())

	good_participant_ids = set(participants.filter(payment=None).values_list('pk', flat=True))
	bad_participant_ids = set(participants.exclude(payment=None).values_list('pk', flat=True))
	good_participants = []
	bad_participants = []

	total_amount = models.int_safe(request.POST.get('total_amount', 0))
	price = get_participation_price(year)
	sum_of_prices = 0

	user = request.user
	for key, val in request.POST.items():
		if key.startswith("amount_"):
			participant_id = models.int_safe(key[len("amount_"):])
			if participant_id in bad_participant_ids:
				bad_participants.append((participant_id, u'Участие уже оплачено'))
			elif participant_id not in good_participant_ids:
				bad_participants.append((participant_id, u'Участник не выступает за нужную команду'))
			else: # So participant_id is in good_participant_ids
				participant = models.Klb_participant.objects.get(pk=participant_id)
				person = participant.klb_person

				participant_price = models.int_safe(val)
				if participant_price not in (0, price):
					bad_participants.append((participant_id, u'Недопустимая цена участия: {}'.format(participant_price)))
				elif (participant_price == 0) and (not participant.is_senior) and (person.disability_group == 0):
					bad_participants.append((participant_id, u'Цена участия — 0, хотя участник молод и здоров'))
				else:
					good_participants.append((participant, participant_price == 0))
					sum_of_prices += participant_price

	problems_desc = ''
	if bad_participants:
		problems_desc = u'\n'.join(u'{}: {}'.format(participant_id, desc) for participant_id, desc in bad_participants)
	elif sum_of_prices != total_amount:
		problems_desc = u'Общая цена — {}, но сумма по отдельным участникам — {}'.format(total_amount, sum_of_prices)

	if problems_desc:
		models.send_panic_email(
			u'Problem when paying for club {} (id {}), team {} (id {})'.format(club.name, club.id,
				team.name if team else '-', team.id if team else '-'),
			u'User {} {}{} was trying to pay for this club. Correct participants: {}. Incorrect participants: {}. Problems:\n\n{}'.format(
				user.get_full_name(), models.SITE_URL, user.user_profile.get_absolute_url(), len(good_participants), len(bad_participants), problems_desc),
			to_all=True
		)
		messages.warning(request, (u'К сожалению, при создании заказа возникла проблема. Администраторы уже знают об этом. '
			+ u'Вы можете попробовать ещё раз или подождать письма от нас о том, что проблема исправлена.'))
		return redirect(team_or_club.get_payment_url())

	if len(good_participants) == 0:
		messages.warning(request, u'Похоже, вы пытались заплатить за 0 человек. Не стоит этого делать :)')
		return redirect(team_or_club)

	if total_amount == 0:
		payment = models.Payment_moneta.objects.create(
			amount=0,
			is_dummy=True,
			is_paid=True,
			user=user,
		)
		payment.transaction_id = models.PAYMENT_DUMMY_PREFIX + unicode(payment.id)
		payment.save()

		for participant, _ in good_participants:
			participant.payment = payment
			participant.paid_status = models.PAID_STATUS_FREE
			participant.save()
			models.log_obj_create(request.user, participant.klb_person, models.ACTION_KLB_PARTICIPANT_UPDATE, child_object=participant,
				field_list=['paid_status', 'payment'], comment=u'Платёж {}'.format(payment.id), verified_by=models.USER_ROBOT_CONNECTOR)
		messages.success(request, u'Вы оплатили участие {} человек на общую сумму 0 рублей. Ура!'.format(len(good_participants)))
		return redirect(team_or_club)

	payment = models.Payment_moneta.objects.create(
		amount=total_amount,
		description=u'Оплата за {} участник{} {} {} в КЛБМатче–{}'.format(
			len(good_participants), results_util.plural_ending_new(len(good_participants), 16), u'команды' if team else u'клуба',
			team_or_club.name, year),
		user=user,
		sender=user.get_full_name(),
	)
	payment.refresh_from_db()
	payment.transaction_id = DESCRIPTION_PREFIX + unicode(payment.id)
	payment.signature = get_payment_md5(payment)
	payment.save()

	for participant, wants_to_pay_zero in good_participants:
		participant.payment = payment
		participant.wants_to_pay_zero = wants_to_pay_zero
		participant.save()
		models.log_obj_create(request.user, participant.klb_person, models.ACTION_KLB_PARTICIPANT_UPDATE, child_object=participant,
			field_list=['wants_to_pay_zero', 'payment'], comment=u'Платёж {}'.format(payment.id), verified_by=models.USER_ROBOT_CONNECTOR)
	redirect_url = get_redirect_url(payment)
	return redirect(redirect_url)