Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # from __future__ import unicode_literals, print_function # @TODO переместить все u'' -> '' и раскомментировать
- import datetime
- import pymorphy2
- import decimal
- import json
- import os
- import re
- import sys
- import urllib
- import urllib2
- import uuid
- import requests
- import random
- import logging
- from calendar import timegm
- from collections import OrderedDict
- from collections import defaultdict
- from hashlib import md5
- from inspect import isclass
- from django.conf import settings as django_settings
- from django.contrib.sitemaps import Sitemap
- from django.contrib.sitemaps.views import x_robots_tag
- from django.contrib.sites.models import Site
- from django.contrib.sites.requests import RequestSite
- from django.core.mail import send_mail, BadHeaderError
- from django.core.paginator import EmptyPage
- from django.core.paginator import PageNotAnInteger
- from django.core.serializers.json import DjangoJSONEncoder
- from django.core.urlresolvers import reverse_lazy, reverse
- from django.core.exceptions import ObjectDoesNotExist
- from django.db.models import Q
- from django.db.models import QuerySet
- from django.http import HttpResponse, HttpResponsePermanentRedirect
- from django.http.response import Http404, HttpResponseRedirect
- from django.shortcuts import redirect
- from django.template import RequestContext, loader
- from django.template.loader import render_to_string
- from django.template.response import TemplateResponse
- from django.utils import timezone
- from django.utils.encoding import force_unicode
- from django.utils.http import http_date
- from django.utils.six import text_type
- from django.utils.translation import get_language, gettext
- from django.utils.functional import cached_property
- from django.views import generic
- from django.views.decorators.csrf import csrf_exempt
- from django.contrib.auth.decorators import login_required
- from django_mobile import get_flavour
- from multisite.models import Alias
- from suds.cache import NoCache
- from suds.client import Client
- from django.contrib.admin.models import LogEntry
- from django.core.cache import cache
- from django.http.request import split_domain_port
- from django.utils.six.moves.urllib.parse import urlparse
- import ajaxcontroller
- from .models import Scripts, Robots, TextPage, News, Team, Player, Match, Stadium, Champ, Group, Fed, Zayavka, \
- Price, OrderItem, Order, PayMethod, City, Tags, FeedBack, Caps, Reviews, SiteSettings, SiteTemplates
- from .forms import ContactForm, ContactFormCapcha, CorporateForm, ReviewsForm, CorporateFormCaptcha
- from .utils import get_current_hostname, get_object_or_404, get_current_alias, get_client_ip, get_paymethod, get_exception
- from acquiring_client.helpers import acquiring
- from currency.models import Currency
- from django.views.decorators.csrf import ensure_csrf_cookie
- from django.contrib.auth.decorators import user_passes_test
- from portal.extras import get_vip
- EMAIL_FROM = getattr(django_settings, 'DEFAULT_FROM_EMAIL', 'info@confederationscup.net')
- logger = logging.getLogger("portal.views")
- #Поисковые Переходы
- UTM_SOURCE = 'utm_source'
- UTM_MEDIUM = 'utm_medium'
- UTM_CAMPAIGN = 'utm_campaign'
- UTM_TERM = 'utm_term'
- UTM_CONTENT = 'utm_content'
- REFERER = 'referer'
- UTM_CHOICES = (
- (UTM_SOURCE, u'%s | Источник' % UTM_SOURCE),
- (UTM_MEDIUM, u'%s | Тип источника (cpc, баннер, рассылка)' % UTM_MEDIUM),
- (UTM_CAMPAIGN, u'%s | Название рекламной кампании' % UTM_CAMPAIGN),
- (UTM_TERM, u'%s | Kлючевое слово' % UTM_TERM),
- (REFERER, u'%s | Переход с сайта' % REFERER)
- )
- ANALITYCS_KEY = '_analitycs'
- def get_alias_related(host_name, alias):
- table = [
- ["confcuptickets.ru", "kontakti", "contacts"],
- ["confcuptickets.ru", "matchi", "matches"],
- ["confcuptickets.ru", "comands", "teams"],
- ]
- for item in table:
- try:
- # it = item.index(force_unicode(alias))
- if item[0] == host_name.domain:
- alias = item[1]
- except ValueError:
- pass
- return alias
- def active_menu(req):
- alias = req.path.strip('/').split('/')[0]
- if alias == '':
- alias = 'index'
- return alias
- def choose_template(request, page):
- tpl_path = '/'.join(filter(None, [{'mobile': 'mobile', 'full': ''}.get(get_flavour(request, '')), page]))
- return loader.get_template('.'.join([tpl_path, 'html']))
- def get_host_vs_url(host_name, url, alias):
- alias = alias
- url_first = url.split('/')[1]
- if url_first != '':
- textpages = TextPage.objects.filter(~Q(alias="index"), host=host_name)
- # textpage = textpages.get_object_or_404(alias=url_first)
- try:
- textpage = textpages.get(alias=url_first)
- alias = url_first.encode('utf8')
- except TextPage.DoesNotExist:
- if alias == 'error-404':
- pass
- else:
- raise Http404
- return alias
- def default_context(request, alias, object):
- host = active_menu(request)
- host_name = get_current_hostname(request)
- if object == TextPage:
- alias = get_host_vs_url(host_name, request.get_full_path().split('?')[0], alias)
- menu = TextPage.objects.prefetch_related('translations').language(get_language()).order_by('menuposition').filter(
- ~Q(alias="index"), menushow=True,
- host=host_name)
- scripts = Scripts.objects.filter(host=host_name)
- # russia = Team.objects.get(name="Россия")
- # ru_matches = Match.objects.filter(Q(command_first=russia) | Q(command_second=russia)).order_by('datetime')
- # try:
- # champ = Champ.objects.language(get_language()).filter(host=host_name)
- # champ = Champ.objects.translated(get_language()).prefetch_re.filter(host=host_name)
- # except ObjectDoesNotExist:
- # raise Http404
- champ = get_object_or_404(Champ, name="Кубок конфедераций 2017", host=host_name)
- champs = Champ.objects.filter(host=host_name).distinct().order_by('translations__name')
- last_news = News.objects.prefetch_related('translations').language(get_language()).filter(host=host_name).order_by(
- 'date')[:4]
- stadium = Stadium.objects.prefetch_related('translations').language(get_language()).filter(host=host_name,
- menushow=True)
- last_matches = Match.objects.prefetch_related('translations').language(get_language()).filter(
- champ=champ, host=host_name, techmatch=False, menushow=True
- ).order_by('datetime')[:5]
- all_matches = Match.objects.prefetch_related('translations').language(get_language()).filter(
- Q(command_first__translations__name='Россия') | Q(command_second__translations__name='Россия'),
- champ__translations__name='Групповой этап', host=host_name).distinct().order_by('datetime')
- last_matches_two = Match.objects.prefetch_related('translations').language(get_language()).filter(
- champ=champ, host=host_name, techmatch=False
- ).order_by('datetime')[5:10]
- # teams = Team.objects.filter(fed=Fed.objects.get(name="УЕФА"),techteam=False).order_by('name')
- # champ_teams = []
- # champ_teams.append(champ.teams.get(name="Россия"))
- # champ_teams.append(champ.teams.get(name="Германия"))
- # champ_teams.append(champ.teams.get(name="Мексика"))
- # champ_teams.append(champ.teams.get(name="Чили"))
- # champ_teams.append(champ.teams.get(name="Австралия"))
- # champ_teams.append(champ.teams.get(name="Новая Зеландия"))
- # try :
- # champ_teams.append(champ.teams.get(name="Португалия"))
- # except Team.DoesNotExist :
- # pass
- champ_teams = champ.teams.order_by('id')
- teams = champ_teams
- teams_group = []
- cur_site_url = request.get_host()
- groups = Group.objects.prefetch_related('translations').select_related().language(get_language()).filter(
- champ=champ, translations__name__contains="Группа"
- ).order_by('translations__name')
- for group in groups:
- matches = Match.objects.select_related().filter(group=group)
- temp_teams = []
- for match in matches:
- temp_teams.append(match.command_first)
- temp_teams = list(set(temp_teams))
- teams_group.append([group, temp_teams])
- try:
- data = object.objects.get(alias=alias, host=host_name)
- except object.DoesNotExist:
- raise Http404
- try:
- if SiteSettings.objects.get(caps=Alias.objects.get(domain=cur_site_url)):
- cap_site = True
- except Exception:
- cap_site = False
- pass
- try:
- if SiteSettings.objects.get(host__name=host_name):
- curr_template = SiteTemplates.objects.get(settings=SiteSettings.objects.get(host__name=host_name), domain__domain=cur_site_url).template
- except Exception:
- curr_template = '1'
- pass
- try:
- if SiteSettings.objects.get(hide_ticks=Alias.objects.get(domain=cur_site_url)):
- hide_sell_tickets = True
- except Exception:
- hide_sell_tickets = False
- pass
- # корзина
- mini_cart = Order.set_session(request=request)
- context_object = {
- 'host': host,
- 'host_name': host_name,
- 'cur_site_url': cur_site_url,
- 'menu': menu,
- 'scripts': scripts,
- # 'ru_matches' : ru_matches,
- 'last_news': last_news,
- 'all_matches': all_matches,
- 'last_matches': last_matches,
- 'last_matches_two': last_matches_two,
- 'teams': teams,
- 'groups': groups,
- 'stadium': stadium,
- 'teamsAB': teams_group,
- 'champ_teams': champ_teams,
- 'champ': champ,
- 'champs': champs,
- 'data': data,
- 'order': None,
- 'mini_cart': mini_cart,
- 'cap_site': cap_site,
- 'hide_sell_tickets': hide_sell_tickets,
- 'curr_template': curr_template,
- 'paymethods': min(map(
- lambda i: i.price.paymethods.all(),
- OrderItem.objects.filter(order=mini_cart).all()
- ) or [PayMethod.objects.all()], key=lambda _is: len(_is))
- }
- return context_object
- @ensure_csrf_cookie
- def index(request):
- error = None
- success = None
- if 'fifa18.center' in request.get_host():
- return sell_ticket(request)
- if 'hospitality' in request.get_host():
- return vip(request)
- if request.is_ajax():
- success = 'gotovo' # ну не пишите так, пишите finished, например
- if request.POST['type'] == 'callback':
- name = request.POST['name']
- phone = request.POST['phone']
- text = request.POST['text']
- subject = 'Заказ обратного звонка от ' + name.encode('utf8')
- message = name.encode('utf8') + u' заказал обратный звонок на телефон ' + phone.encode(
- 'utf8') + u'<br> Сообщение: ' + text.encode('utf8')
- recipients = ['vladyan.s@yandex.ru', 'vladyan121@gmail.com'] # это нужно выносить в насйтройки
- send_mail(
- subject, message, EMAIL_FROM, recipients, html_message=message,
- fail_silently=not getattr(django_settings, 'DEBUG', False)
- )
- return HttpResponse(success)
- elif request.POST['type'] == 'get_teams':
- items = []
- for i in Match.objects.filter(group=Group.objects.get(id=request.POST['group_id'])).order_by('datetime'):
- items.append({'command_first': i.command_first.name, 'command_second': i.command_second.name,
- 'date': i.datetime.strftime('%d-%m-%Y'), 'city': i.stadium.city.name})
- return HttpResponse(json.dumps(items, ensure_ascii=False).encode('utf8'))
- elif request.POST['type'] == 'send_review':
- item = Reviews(name=request.POST['name'], email=request.POST['email'], message=request.POST['message'])
- item.save()
- return HttpResponse('Success')
- else:
- template = choose_template(request, "index")
- context_data = default_context(request, "index", TextPage)
- news = News.objects.filter(host=context_data['host_name']).order_by('date')[:5]
- stadiums = Stadium.objects.filter(
- Q(city__translations__country='Россия') | Q(city__translations__country='Russia'),
- host=context_data['host_name']).order_by('id').distinct().prefetch_related('translations')
- matches_main = Match.objects.filter(Q(score=None),
- Q(command_first__translations__name='Россия') | Q(command_second__translations__name='Россия'),
- Q(champ__translations__name='Групповой этап')|Q(champ__translations__name='Плей-офф'),
- host=context_data['host_name'], menushow=True, hide_match=False).order_by(
- 'datetime').distinct().prefetch_related('translations')
- matches_samara = Match.objects.filter(
- stadium__translations__name='Самара Арена', host=context_data['host_name'], hide_match=False).order_by(
- 'datetime').distinct().prefetch_related('translations')
- tovar_matches = Match.objects.filter(Q(score=None), champ__translations__name='Товарищеские матчи',
- host=context_data['host_name'], hide_match=False).distinct().order_by(
- 'datetime').prefetch_related('translations')
- popular_matches = Match.objects.filter(Q(score=None),
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- host=context_data['host_name'], menushow=True, popular=True, hide_match=False).distinct().order_by(
- 'datetime').prefetch_related('translations')
- groups = Group.objects.filter(
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- host__name=context_data['host_name']).distinct().order_by('menuposition').prefetch_related('translations')
- cities = City.objects.filter(Q(translations__country='Россия') | Q(translations__country='Russia'),
- host=context_data['host_name']).distinct().order_by(
- 'menuposition').prefetch_related('translations')
- matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_quarterfinals = Match.objects.filter(Q(score=None), group__translations__name='1/4 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_semifinals = Match.objects.filter(Q(score=None), group__translations__name='1/2 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- final = Match.objects.filter(Q(score=None), group__translations__name='Финал',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- match_for_3 = Match.objects.filter(Q(score=None), group__translations__name='Матч за 3-е место',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- supacup = Match.objects.filter(champ__translations__name='Суперкубок УЕФА').distinct()
- order_id = ''
- reviews = Reviews.objects.filter(published=True).order_by('id').reverse()[:5]
- ip = get_client_ip(request)
- import pdb
- pdb.set_trace()
- if request.method == 'POST':
- cip = cache.get(ip, None)
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(
- host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- if request.POST.get(u'g-recaptcha-response'):
- form = CorporateFormCaptcha(request.POST)
- try:
- cache.incr(ip, 1) # у тебя ip не число а увеличиваешь ты на 1 не знаю как это работает
- except ValueError:
- cache.set(ip, 1, django_settings.BLACK_TIME_IP)
- elif cip >= django_settings.BLACK_COUNT_TRYING_IP:
- try:
- cache.incr(ip, 1)
- except ValueError: # на случай если вдруг в это время ключ уже удалился
- cache.set(ip, cip + 1, django_settings.BLACK_TIME_IP)
- # if cip == django_settings.BLACK_COUNT_TRYING_IP:
- # form = ContactForm(request.POST)
- # else:
- form = CorporateFormCaptcha(request.POST)
- else:
- cache.set(ip, 1, django_settings.BLACK_TIME_IP)
- form = CorporateForm(request.POST)
- else:
- form = CorporateForm(request.POST)
- order_id = -1
- if form.is_valid():
- name = form.cleaned_data['name']
- email = form.cleaned_data['email']
- # num = form.cleaned_data['num']
- # category = form.cleaned_data['category']
- phone = form.cleaned_data['phone']
- event = form.cleaned_data['event']
- message = form.cleaned_data['message']
- message_html = u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + u'</div><div>Категория билетов:' + event + u'</div><div>Email:' + email + u'</div><div>Сообщение: ' + message + u'</div>' # u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + '</div><div>Email:' + email + u'</div><div>Матч:' + event + u'</div><div>Категория: ' + category + u', Количество: ' + num + u'</div><div>Сообщение: ' + message + '</div>'
- bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Сообщение: {message}'.format(
- message=message
- )
- recipient_list = ['info@worldcup2018.me']
- _hostname = context_data.get('host_name', None) or get_current_hostname(request)
- # try:
- # send_mail(
- # u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
- # html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
- # )
- # except (BadHeaderError, AttributeError): # Защита от уязвимости
- # error = 'Invalid header found'
- # except Exception:
- # pass
- # Переходим на другую страницу, если сообщение отправлено
- success = 'Сообщение успешно отправлено!'
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- source_id, _msg = request.seo.analytics_message()
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- lang="0",
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0',
- source=force_unicode(source_id)
- )
- # func = client.service.addOrderSourceI
- #
- # try:
- # order_id = func(
- # info_fio=name,
- # info_tel=phone,
- # info_email=email,
- # info_title=u'Корпоративная заявка',
- # info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
- # # info_tc=num,
- # info_cat=event,
- # info_notes=u'<br/>'.join([bin_message, _msg]),
- # **info
- # )
- # except Exception as erra:
- # pass
- url = 'http://185.154.52.97:8001/api/create-order-from-site/'
- new_bcontent = {
- "comment": u'Корпоративная завяка',
- "client_name": name,
- "client_phone": phone,
- # "client_phone_code": zone,
- # "client_address": addr,
- # "pay_type": paymethod,
- "site_name": request.get_host(),
- "old_bintranet_id": order_id,
- "client_comment": message
- }
- item = requests.post(url, headers={'content-type': 'application/json',
- 'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
- data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
- order_id = item.json().get('pk', -1)
- cart = context_data.get('mini_cart', Order.get_session(request=request))
- cart.phone = phone
- cart.email = email
- cart.fio = name
- cart.desc = bin_message.replace(u'<br>', u'\n')
- cart.website = website
- cart.bin_id = order_id
- cart.payment_processed = int(order_id) > 0
- cart.save()
- request.session.pop(django_settings.CART_SESSION_ID)
- else:
- error = 'В некоторых полях содержатся ошибки!'
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- if cache.get(ip) >= django_settings.BLACK_COUNT_TRYING_IP:
- form = CorporateFormCaptcha()
- else:
- form = CorporateForm()
- else:
- form = CorporateForm()
- context_data.update({
- 'supacup' : supacup,
- 'news': news,
- 'popular_matches': popular_matches,
- 'tovar_matches': tovar_matches,
- 'matches_main': matches_main,
- 'matches_samara': matches_samara,
- 'matches_1_8': matches_1_8,
- 'matches_quarterfinals': matches_quarterfinals,
- 'matches_semifinals': matches_semifinals,
- 'match_for_3': match_for_3,
- 'final': final,
- 'stadiums': stadiums,
- 'groups': groups,
- 'champ': champ,
- 'form': form,
- 'cities': cities,
- 'order_id': order_id,
- 'reviews': reviews,
- 'success': success,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def index2(request):
- template = choose_template(request, "index2")
- context_data = default_context(request, 'confcup17', TextPage)
- context = RequestContext(request, context_data)
- news = News.objects.filter(host=context_data['host_name']).order_by('date')[:5]
- stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id');
- matches = Match.objects.filter(champ__translations__name='Кубок конфедераций 2017',
- host=context_data['host_name']).order_by('datetime').distinct()
- form = CorporateForm()
- context_data.update({
- 'news': news,
- 'matches': matches,
- 'stadiums': stadiums,
- 'champ': champ,
- 'form': form,
- })
- return HttpResponse(template.render(context))
- def kkmatches(request):
- template = choose_template(request, "matches-kk")
- context_data = default_context(request, 'kkmatches', TextPage)
- context = RequestContext(request, context_data)
- stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id');
- matches = Match.objects.filter(champ__translations__name='Кубок конфедераций 2017',
- host=context_data['host_name']).order_by('datetime')
- form = CorporateForm()
- context_data.update({
- 'matches': matches,
- 'stadiums': stadiums,
- 'champ': champ,
- 'form': form,
- })
- return HttpResponse(template.render(context))
- def kkfanid(request):
- template = choose_template(request, "kkfanid")
- context_data = default_context(request, 'kkfanid', TextPage)
- context = RequestContext(request, context_data)
- context_data.update({
- })
- return HttpResponse(template.render(context))
- def regions_page(request):
- return HttpResponsePermanentRedirect('/teams/')
- def textpage(request, textpage_alias):
- template = choose_template(request, "textpage")
- context_data = default_context(request, textpage_alias, TextPage)
- try:
- if City.objects.get(alias=textpage_alias, host=context_data['host_name']):
- item = TextPage.objects.filter(Q(translations__name='Города') | Q(translations__name='Citys'),
- host=context_data['host_name']).distinct().first().alias
- return HttpResponsePermanentRedirect('/' + item + '/' + textpage_alias + '/')
- except:
- item = 1
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def mobile(request):
- template = choose_template(request, "mobile/index")
- context_data = default_context(request, "mobile", TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- # убираем спецсимволы и числа из названия поля
- def get_field_without_somechars(field):
- return re.sub(r'[\\:\(\)]+|[_]{2}', r'', field).strip()
- def buypage(request):
- # корзина
- cart = Order.get_session(request=request)
- # для пересылки на домен payment для оплаты
- host = None
- try:
- host = (lambda h: h if h.find(":") == -1 else h[:h.find(":")])(request.META['HTTP_HOST'])
- except Exception as e:
- pass
- host_referer, message = '', []
- _utm_source = request.seo.analytics.get(UTM_SOURCE) or ''
- status, status_text = request.seo.utm_sources.get(_utm_source, (None, u'(СЕО)'))
- is_mobile = getattr(request, 'flavour', 'full') == 'mobile'
- request.seo_host = request.get_host()
- refferers = request.seo.analytics.get('referer', []) or filter(
- lambda x: x and request.seo_host not in urlparse(x).netloc,
- request.seo.analytics.get('history', [])
- )
- referer = request.seo.last(refferers)
- ref_netloc = urlparse(referer).netloc
- if ref_netloc:
- host_referer, _ = split_domain_port(ref_netloc)
- device = u'Mobile' if is_mobile else 'Desktop'
- transition = u'Переход из' if host_referer else u'Нет перехода, но ' + status_text
- advert = request.seo.analytics.get(UTM_MEDIUM, '')
- advertising_company = request.seo.analytics.get(UTM_CAMPAIGN, '')
- transition_string = request.seo.analytics.get(UTM_TERM, '')
- cart.utm = [{'device': device, 'transition': transition, 'advert': advert, 'advertising_company': advertising_company, 'transition_string': transition_string}]
- cart.save()
- # конец поисковых переходов
- domain = request.get_host()
- domain_2 = domain.replace('payment.', '')
- # if domain_2 == 'welcome2018.com.ru':
- # domain_name = 'payment.{}'.format(domain_2)
- domain_name = django_settings.ACQUIRING_CLIENT_HOST #'payment.welcome2018.me'
- if django_settings.IS_PAYMENT_REDIRECT and domain.split('.')[0] != 'en' and domain != 'worldcupticket.ru' and host != getattr(django_settings, "ACQUIRING_DOMEN_TEST", ""):
- if domain != domain_name:
- token = request.session.get(django_settings.CART_SESSION_ID)
- return redirect('https://' + domain_name + '/buypage/?token=' + token)
- else:
- token = request.GET.get('token', None)
- if token:
- request.session[django_settings.CART_SESSION_ID] = token
- template = choose_template(request, "buypage")
- context_data = default_context(request, 'purchacing', TextPage)
- order_id = -1
- ip = get_client_ip(request)
- if request.method == 'POST':
- cip = cache.get(ip, None)
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- form = ContactFormCapcha(request.POST)
- else:
- form = ContactForm(request.POST)
- error = None
- success = None
- token = request.session.get(django_settings.CART_SESSION_ID)
- order = OrderItem.objects.filter(order__token=uuid.UUID(token)).all() or OrderItem.objects.none()
- mail_from = u'Заказ с сайта '
- if form.is_valid():
- _default = u'Не указан'
- name = form.cleaned_data.get('name', _default)
- email = form.cleaned_data.get('email', _default)
- addr = form.cleaned_data.get('addr', _default)
- phone_code = form.cleaned_data.get('code_phone', "")
- zone = request.POST.get('zone', 'RU')
- # try:
- # zone = request.POST['zone']
- # except Exception:
- # zone = 'RU'
- phone = phone_code + form.cleaned_data.get('phone', _default)
- payment = form.cleaned_data['payment']
- total = 0
- prev = ''
- len = 0
- match_name = ''
- datee = []
- town = []
- category = []
- for item in order:
- len += int(item.count)
- category.append([item.price.sector.encode('utf8'), item.count])
- if prev != item.price.match.command_first.name + ' - ' + item.price.match.command_second.name:
- match_name += item.price.match.command_first.name.encode(
- 'utf8') + ' - ' + item.price.match.command_second.name.encode('utf8') + '; '
- datee.append(item.price.match.datetime)
- town.append(item.price.match.stadium)
- prev = item.price.match.command_first.name + ' - ' + item.price.match.command_second.name
- if item.price.price.currency != "RUB": # сумма для заказа формируется ниже
- a = Currency.objects.get(code="RUB").rate # курс рубля
- b = Currency.objects.get(code=item.price.price.currency).rate
- total += item.price.price.amount * item.count * b / a
- else:
- total += item.price.price.amount * item.count
- mail_from = u'Заказ билетов успешно оформлен'
- # tickets += '<div>Матч: {} - {}, {}, кол-во: {}</div>'.format(item.price.match.command_first.name.encode('utf8'), item.price.match.command_second.name.encode('utf8'), item.price.sector.encode('utf8'), str(item.count))
- text_category = ', '.join(
- map(lambda (l, r): ' '.join(map(force_unicode, [l, '- %sшт.' % r])), category))
- _message_data = map(
- force_unicode,
- [name, email, phone, match_name, text_category, total, payment, addr,
- form.cleaned_data.get('message', u"Без сообщения")]
- )
- message = u'<b>Имя отправителя:</b> {}' \
- u'<br><b>E-mail: </b>{}' \
- u'<br><b>Телефон:</b>{}' \
- u'<br><div>Название мероприятия:{}' \
- u'</div><div>Выбранные билеты:</div>{}' \
- u'<div>Общая сумма заказа: {}' \
- u'</div><div>Способ оплаты: {}' \
- u'</div><div>Адрес: {}' \
- u'</div><div>Сообщение: {}' \
- u'</div>'.format(*_message_data)
- recipient_list = filter(None, [email])
- make_decimal = (lambda z: decimal.Decimal(z) if hasattr(
- z, 'isdigit'
- ) or isinstance(
- z, (decimal.Decimal, int, float)
- ) else decimal.Decimal(0))
- #paymethod = getattr(PayMethod.objects.filter(pk=payment).first(), 'bin_id', 1)
- # paymethod = get_paymethod(payment)
- paymethod = PayMethod.objects.filter(pk=payment).first()
- temp_tickets = defaultdict(OrderedDict)
- db_tickets = []
- def make_temp_tickets(order):
- t_tickets = []
- for item in order:
- temp_price = 0
- if item.price.price.currency != "RUB": # сумма для заказа формируется ниже
- a = Currency.objects.get(code="RUB").rate # курс рубля
- b = Currency.objects.get(code=item.price.price.currency).rate
- temp_price = item.price.price.amount * b / a
- else:
- temp_price = item.price.price.amount
- t_tickets.append(
- ('-'.join([item.price.match.command_first.name, item.price.match.command_second.name]),
- item.price.sector,
- make_decimal(temp_price),
- make_decimal(item.count),
- item.price.match.datetime,
- item.price.match.stadium.city.name,
- item.price.match.stadium.name))
- return t_tickets
- for _title, _sector, _price, _count, _datetime, _city, _stadium in make_temp_tickets(order):
- # for _title, _sector, _price, _count, _datetime, _city, _stadium in map(
- # lambda t: ('-'.join([
- # t.price.match.command_first.name,
- # t.price.match.command_second.name
- # ]), t.price.sector, make_decimal(t.price.price.amount), make_decimal(t.count), t.price.match.datetime, t.price.match.stadium.city.name, t.price.match.stadium.name),
- # order
- # ):
- if not all([_count, _datetime]):
- continue
- _id = force_unicode(u':'.join([_title, _sector]))
- temp_tickets[_id].setdefault('title', _title)
- temp_tickets[_id].setdefault('count', 0)
- temp_tickets[_id].setdefault('price', _price)
- temp_tickets[_id].setdefault('datetime', _datetime)
- temp_tickets[_id].setdefault('category', _sector)
- temp_tickets[_id].setdefault('city', _city)
- temp_tickets[_id].setdefault('stadium', _stadium)
- temp_tickets[_id]['count'] += _count
- db_tickets.append(dict(
- count=_count,
- src="",
- title=_title,
- price=_price,
- id="",
- cats=[_title, _sector, ''],
- offer_id=""
- ))
- # total = sum(map(lambda s: s.get('price') * s.get('count'), temp_tickets.values()))
- url = 'http://185.154.52.97:8001/api/create-order-from-site/'
- def bintrasend(request, order):
- new_btickets = []
- additionals = 0
- for item in order:
- event_name = '{} - {}'.format(item.price.match.command_first.name.encode('utf8'),
- item.price.match.command_second.name.encode('utf8'))
- new_btickets.append({
- "event_name": event_name.decode('utf8'),
- "event_place_name": item.price.match.stadium.name + ', ' + item.price.match.stadium.city.name,
- "event_time_datetime": item.price.match.datetime.strftime("%Y-%m-%dT%H:%M"),
- "sector_name": item.price.sector,
- "sale": str(item.price.price.amount)[:-3],
- "count": item.count,
- "predict_purchase": str(item.price.zakup.amount)[:-3],
- "event_carryall_id": item.price.match.id,
- "info": u'Номер матча: {}'.format(item.price.match.count_number)
- })
- if item.price.status == '1':
- additionals += 1
- try:
- from_site = Order.objects.get(token=request.session.get(django_settings.CART_SESSION_ID))
- except Exception:
- from_site = cart
- new_bcontent = {
- "tickets": new_btickets,
- "client_name": name,
- "client_phone": phone,
- "client_phone_code": zone,
- "client_address": addr,
- "pay_type": paymethod.bin_id,
- "site_name": request.get_host(),
- "device": from_site.utm[0]['device'],
- "transition": from_site.utm[0]['transition'],
- "advert": from_site.utm[0]['advert'],
- "advertising_company": from_site.utm[0]['advertising_company'],
- "transition_string": from_site.utm[0]['transition_string'],
- "info": _msg,
- }
- if additionals:
- new_bcontent.update({'additional_status': 8, "comment": u'Проверить наличие билетов'})
- if email:
- new_bcontent.update({
- 'client_email': email
- })
- try:
- item = requests.post(url, headers={'content-type': 'application/json',
- 'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
- data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
- try:
- r_dict = item.json()
- except Exception:
- r_dict = {}
- logger.debug(str(r_dict))
- order_id = r_dict.get('pk', -1)
- if order_id < 0:
- category_text = ''
- for i in category:
- category_text += force_unicode(i[0]) + u'- кол-во билетов: ' + str(i[1]) + u'<br>'
- subject = u'Заказ не дошедший в бинтранет от ' + u''
- messaga = u'Инфо о заказе:<br>Имя: {}<br>Телефон: {}<br>Матч: {}<br>Дата матча: {}<br>Город матча: {}<br>Выбранные билеты: {}<br>Сумма заказа: {}<br>Ссылка на заказ в админке: http://welcome2018.me/admin/portal/order/{}/'.format(
- name, phone, match_name, datee[0].strftime('%d.%m.%Y %H:%M'),
- force_unicode(town[0].city.name),
- category_text, str(int(total)), str(uuid.UUID(token)))
- recipients = ['info@welcome2018.me'] # это нужно выносить в насйтройки
- send_mail(
- subject, messaga, EMAIL_FROM, recipients, html_message=messaga,
- fail_silently=not getattr(django_settings, 'DEBUG', False)
- )
- Order.objects.filter(token=uuid.UUID(token)).update(
- d=timezone.now(),
- phone=phone,
- adr=addr,
- email=email,
- fio=name,
- paymethod=paymethod.id,
- tickets=json.dumps(new_btickets, cls=DjangoJSONEncoder),
- bin_id=order_id,
- website=request.get_host()
- )
- except Exception as e:
- error = get_exception()
- logger.error("paymethod: {}".format(paymethod))
- logger.error(error)
- order_id = -1
- return order_id
- if temp_tickets:
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- logger.info(website)
- source_id, _msg = request.seo.analytics_message()
- _xtra_msg = form.cleaned_data.get('message', None)
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- if _xtra_msg:
- _msg = u'<strong>Доп.инфо:</strong> {}<br/>'.format(_xtra_msg) + _msg
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- method_pay=paymethod,
- method_delivery="1",
- lang="0",
- source=force_unicode(source_id),
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0'
- )
- _total = 0
- for enum, _info in enumerate(temp_tickets.values()):
- # if item.price.price.currency != "RUB": # сумма для заказа формируется ниже
- # a = Currency.objects.get(code="RUB").rate # курс рубля
- # b = Currency.objects.get(code=item.price.price.currency).rate
- # _total += int(item.price.price) * int(item.count) * b / a
- # else:
- # total += int(item.price.price) * int(item.count)
- _total += _info.get('count') * _info.get('price')
- payload = dict(
- info_fio=name,
- info_tel=phone,
- info_email=email,
- info_adr=addr,
- info_title=_info.get('title') + ' ' + _info.get('city') + ', ' + _info.get('stadium'),
- info_d=_info.get('datetime').strftime('%Y-%m-%d %H:%M:%S'),
- info_tc=_info.get('count'),
- info_sum=_info.get('count') * _info.get('price'),
- info_cat=_info.get('category'),
- info_notes=_msg,
- **info
- )
- # try:
- # if enum > 0:
- # payload.update(**dict(order_id=order_id))
- # client.service.addOrderExtra(**payload)
- # elif enum < 1:
- # order_id = client.service.addOrderSourceI(**payload)
- # Order.objects.filter(token=uuid.UUID(token)).update(
- # d=_info.get('datetime'),
- # phone=phone,
- # adr=addr,
- # email=email,
- # fio=name,
- # paymethod=payment,
- # tickets=json.dumps(db_tickets, cls=DjangoJSONEncoder),
- # bin_id=order_id,
- # website=request.get_host()
- # )
- # # # Переходим на другую страницу, если сообщение отправлено
- # # success = 'Сообщение успешно отправлено!'
- #
- # except Exception as erra:
- # if getattr(django_settings, 'DEBUG', False):
- # print erra # @TODO logger
- # # logger.error(e)
- # continue
- order_id = bintrasend(request, order)
- Order.objects.filter(token=uuid.UUID(token)).update(sum=_total)
- if recipient_list:
- _tpl = render_to_string('_email_tpl.html', {
- 'name': name,
- 'email': email,
- 'phone': phone,
- 'order_id': order_id,
- 'total': _total,
- 'match_name': match_name,
- 'text_category': text_category,
- 'datee': datee,
- 'town': town,
- })
- # send_mail(
- # mail_from, message, EMAIL_FROM, recipient_list,
- # html_message=_tpl, fail_silently=not getattr(django_settings, 'DEBUG', False)
- # )
- if request.get_host().split('.')[0] == 'en':
- cont = {
- "api_key": "67qxhb31twhaaynhzep59sj78xzp9t8i8u8gszho",
- "username": "info@welcome2018.me",
- "message": {
- "template_engine": "velocity",
- "template_id": "bf32faf0-5916-11e8-aaf2-f2fba6545268",
- "subject": "Successful order on en.welcome2018.me",
- "from_email": "info@welcome2018.me",
- "from_name": "WorldCup 2018",
- "recipients": [
- {
- "email": email,
- "substitutions": {
- "info": {
- "order_id": order_id,
- "name": name,
- "phone": phone,
- "summ": str(_total),
- "match_name": match_name,
- "datetime": datee[0].strftime('%Y-%m-%d %H:%M'),
- "city": town[0].name + ', ' + town[0].city.name,
- "category": text_category,
- "email": email
- }
- }
- }
- ],
- "attachments": [
- {
- "type": "text/pdf",
- "name": "test.pdf",
- "content": ""
- }
- ]
- }
- }
- #requests.post('https://one.unisender.com/ru/transactional/api/v1/email/send.json',
- # json.dumps(cont))
- else:
- cont = {
- "api_key": "67qxhb31twhaaynhzep59sj78xzp9t8i8u8gszho",
- "username": "info@welcome2018.me",
- "message": {
- "template_engine": "velocity",
- "template_id": "07128d68-5863-11e8-97fe-762f11e05f46",
- "subject": "Успешный заказ на сайте welcome2018.me",
- "from_email": "info@welcome2018.me",
- "from_name": "Чемпионат Мира 2018",
- "recipients": [
- {
- "email": email,
- "substitutions": {
- "info": {
- "order_id": order_id,
- "name": name,
- "phone": phone,
- "summ": str(_total),
- "match_name": match_name,
- "datetime": datee[0].strftime('%Y-%m-%d %H:%M'),
- "city": town[0].name + ', ' + town[0].city.name,
- "category": text_category,
- "email": email
- }
- }
- }
- ]
- }
- }
- #requests.post('https://one.unisender.com/ru/transactional/api/v1/email/send.json',
- # json.dumps(cont))
- success = True
- # ----------------------- Acquiring -------------------------------------------------------------
- atol_tickets = []
- for t in db_tickets:
- atol_tickets.append({"count": int(t["count"]), "price": int(t["price"])})
- # td = getattr(django_settings, "ACQUIRING_DOMEN_TEST", "")
- # tp = getattr(django_settings, "ACQUIRING_DOMEN_PORT", "")
- # test_host = "{}:{}".format(td, td) if td and tp else td
- temp_order_id = str(uuid.uuid4()).replace("-", "")[
- :16] # Длина заказа в сбере 32 символа, берем 16 так как поставляется в bintranet_id
- try:
- if order_id < 0 and host == getattr(django_settings, "ACQUIRING_DOMEN_TEST", ""):
- order_id = temp_order_id
- except:
- pass
- if int(payment) == 1 and int(_total) > 0 and order_id:
- if host == getattr(django_settings, "ACQUIRING_DOMEN_TEST", "") or request.get_host()[:2] == "en":
- host_acquiring = host # прямая оплата
- else:
- host_acquiring = django_settings.ACQUIRING_CLIENT_HOST
- response = acquiring(
- request=request,
- bintranet_id=order_id,
- total_cost=int(_total),
- host=host_acquiring,
- customer_name=name,
- phone=phone,
- email=email,
- ip=get_client_ip(request), # 'geoip2.readthedocs.io'
- test_host="",
- tickets=atol_tickets,
- # sources=resp_json['sources'],
- )
- if response == -1:
- logger.info("Acquiring some error or don't have acquiring or payments rules w/o paying")
- return redirect(reverse_lazy('payments:process'))
- else:
- return response # redirect on payment
- else:
- return redirect(reverse_lazy('payments:process'))
- # ----------------------- / Acquiring -------------------------------------------------------------
- else:
- error = True
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(
- host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- form = ContactFormCapcha()
- else:
- form = ContactForm()
- logger.debug(str(context_data))
- context_data.update({
- 'error': error,
- 'success': success,
- 'form': form,
- 'order': order,
- 'order_id': order_id,
- 'cart': Order.set_session(request=request)
- })
- else:
- form = None
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- form = ContactFormCapcha()
- else:
- form = ContactForm()
- logger.debug(str(context_data))
- context_data.update({
- 'cart': Order.set_session(request=request),
- 'form': form
- })
- context = RequestContext(request, context_data)
- response = HttpResponse(template.render(context))
- return response
- def sell_ticket_final(request):
- if request.is_ajax():
- # для пересылки на домен payment для оплаты
- host = None
- try:
- host = (lambda h: h if h.find(":") == -1 else h[:h.find(":")])(request.META['HTTP_HOST'])
- except Exception as e:
- pass
- # Поисковые Переходы
- UTM_SOURCE = 'utm_source'
- UTM_MEDIUM = 'utm_medium'
- UTM_CAMPAIGN = 'utm_campaign'
- UTM_TERM = 'utm_term'
- UTM_CONTENT = 'utm_content'
- REFERER = 'referer'
- UTM_CHOICES = (
- (UTM_SOURCE, u'%s | Источник' % UTM_SOURCE),
- (UTM_MEDIUM, u'%s | Тип источника (cpc, баннер, рассылка)' % UTM_MEDIUM),
- (UTM_CAMPAIGN, u'%s | Название рекламной кампании' % UTM_CAMPAIGN),
- (UTM_TERM, u'%s | Kлючевое слово' % UTM_TERM),
- (REFERER, u'%s | Переход с сайта' % REFERER)
- )
- ANALITYCS_KEY = '_analitycs'
- host_referer, message = '', []
- _utm_source = request.seo.analytics.get(UTM_SOURCE) or ''
- status, status_text = request.seo.utm_sources.get(_utm_source, (None, u'(СЕО)'))
- is_mobile = getattr(request, 'flavour', 'full') == 'mobile'
- request.seo_host = request.get_host()
- refferers = request.seo.analytics.get('referer', []) or filter(
- lambda x: x and request.seo_host not in urlparse(x).netloc,
- request.seo.analytics.get('history', [])
- )
- referer = request.seo.last(refferers)
- ref_netloc = urlparse(referer).netloc
- if ref_netloc:
- host_referer, _ = split_domain_port(ref_netloc)
- device = u'Mobile' if is_mobile else 'Desktop'
- transition = u'Переход из' if host_referer else u'Нет перехода, но ' + status_text
- advert = request.seo.analytics.get(UTM_MEDIUM, '')
- advertising_company = request.seo.analytics.get(UTM_CAMPAIGN, '')
- transition_string = request.seo.analytics.get(UTM_TERM, '')
- # конец поисковых переходов
- data = json.loads(request.read())
- if data['type'] == 'get_middle_price':
- item = Price.objects.filter(match__id=data['price_match'], translations__sector=data['cat']).first()
- return HttpResponse(int(item.price))
- if data['type'] == 'send_tickets':
- _default = u''
- name = data['data']['name']
- city = data['data']['city']
- phone = data['data']['phone']
- message = u'Продажа билета: {}, {}, Цена продажи: {}, Кол-во: {}, Билеты на руках: {}, Сектор: {}, ряд: {}, место: {}'.format(
- data['data']['match'], data['data']['category'], data['data']['rec'], data['data']['count'],
- data['data']['payment'], data['data']['sector'], data['data']['row'], data['data']['seat'])
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- items = {
- "info_fio": name,
- "info_tel": phone,
- "info_adr": city,
- "info_title": u'Продажа билета', # название шоу
- "info_d": unicode(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
- "info_tc": 1,
- "info_sum": int(data['data']['rec']) * int(data['data']['count']),
- "info_cat": data['data']['category'],
- "info_notes": message,
- "info_ip": unicode(request.META['REMOTE_ADDR']),
- "method_pay": int(1),
- "method_delivery": int(0),
- "lang": int(0),
- "site_name": website,
- "pass_hash": unicode(md5(website).hexdigest()),
- }
- print 'ready to sent... \n items: ', items
- # try:
- # client = client = Client(
- # getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- # cache=NoCache(),
- # timeout=15
- # )
- # order_id = client.service.addOrder(**items)
- # except Exception as e:
- # with open('Vlad_errors__________.log', 'a') as log:
- # log.write(str(e))
- url = 'http://185.154.52.97:8001/api/create-order-from-site/'
- def bintrasend2():
- # new_btickets = []
- # for item in order:
- # event_name = '{} - {}'.format(item.price.match.command_first.name.encode('utf8'),
- # item.price.match.command_second.name.encode('utf8'))
- # new_btickets.append({
- # "event_name": event_name.decode('utf8'),
- # "event_place_name": item.price.match.stadium.name,
- # "event_time_datetime": item.price.match.datetime.strftime("%Y-%m-%dT%H:%M"),
- # "sector_name": item.price.sector,
- # "sale": str(item.price.price.amount)[:-3],
- # "predict_purchase": str(item.price.zakup.amount)[:-3]
- # })
- new_bcontent = {
- "tickets": [],
- "client_name": data['data']['name'],
- "client_address": city,
- "client_phone": data['data']['phone'],
- "pay_type": 1,
- "site_name": request.get_host(),
- "comment": message,
- "status": 12,
- "device": device,
- "transition": transition,
- "advert": advert,
- "advertising_company": advertising_company,
- "transition_string": transition_string,
- }
- try:
- item = requests.post(url, headers={'content-type': 'application/json',
- 'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
- data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
- order_id = item.json().get('pk', -1)
- except Exception as err:
- pass
- return order_id
- send_order = bintrasend2()
- return HttpResponse(send_order)
- def sell_ticket(request):
- if request.is_ajax():
- # для пересылки на домен payment для оплаты
- host = None
- try:
- host = (lambda h: h if h.find(":") == -1 else h[:h.find(":")])(request.META['HTTP_HOST'])
- except Exception as e:
- pass
- # Поисковые Переходы
- UTM_SOURCE = 'utm_source'
- UTM_MEDIUM = 'utm_medium'
- UTM_CAMPAIGN = 'utm_campaign'
- UTM_TERM = 'utm_term'
- UTM_CONTENT = 'utm_content'
- REFERER = 'referer'
- UTM_CHOICES = (
- (UTM_SOURCE, u'%s | Источник' % UTM_SOURCE),
- (UTM_MEDIUM, u'%s | Тип источника (cpc, баннер, рассылка)' % UTM_MEDIUM),
- (UTM_CAMPAIGN, u'%s | Название рекламной кампании' % UTM_CAMPAIGN),
- (UTM_TERM, u'%s | Kлючевое слово' % UTM_TERM),
- (REFERER, u'%s | Переход с сайта' % REFERER)
- )
- ANALITYCS_KEY = '_analitycs'
- host_referer, message = '', []
- _utm_source = request.seo.analytics.get(UTM_SOURCE) or ''
- status, status_text = request.seo.utm_sources.get(_utm_source, (None, u'(СЕО)'))
- is_mobile = getattr(request, 'flavour', 'full') == 'mobile'
- request.seo_host = request.get_host()
- refferers = request.seo.analytics.get('referer', []) or filter(
- lambda x: x and request.seo_host not in urlparse(x).netloc,
- request.seo.analytics.get('history', [])
- )
- referer = request.seo.last(refferers)
- ref_netloc = urlparse(referer).netloc
- if ref_netloc:
- host_referer, _ = split_domain_port(ref_netloc)
- device = u'Mobile' if is_mobile else 'Desktop'
- transition = u'Переход из' if host_referer else u'Нет перехода, но ' + status_text
- advert = request.seo.analytics.get(UTM_MEDIUM, '')
- advertising_company = request.seo.analytics.get(UTM_CAMPAIGN, '')
- transition_string = request.seo.analytics.get(UTM_TERM, '')
- # конец поисковых переходов
- data = json.loads(request.read())
- if data['type'] == 'get_middle_price':
- item = Price.objects.filter(match__id=data['price_match'], translations__sector=data['cat']).first()
- return HttpResponse(int(item.price))
- else:
- return HttpResponse('-1')
- template = choose_template(request, "sell_ticket")
- context_data = default_context(request, 'prodat-bilet', TextPage)
- if request.method == 'POST':
- form = ContactForm(request.POST)
- error = ''
- success = ''
- if form.is_valid():
- _default = u''
- name = form.cleaned_data.get('name', _default)
- email = form.cleaned_data.get('email', _default)
- phone = form.cleaned_data.get('phone', _default)
- message = form.cleaned_data.get('message', _default)
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- items = {
- "info_fio": name,
- "info_tel": phone,
- "info_email": email,
- "info_adr": '',
- "info_title": u'Продажа билета', # название шоу
- "info_d": unicode(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
- "info_tc": 1,
- "info_sum": int(0),
- "info_cat": u'',
- "info_notes": message,
- "info_ip": unicode(request.META['REMOTE_ADDR']),
- "method_pay": int(1),
- "method_delivery": int(0),
- "lang": int(0),
- "site_name": website,
- "pass_hash": unicode(md5(website).hexdigest()),
- }
- print 'ready to sent... \n items: ', items
- client = client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- order_id = client.service.addOrder(**items)
- # order_id = 212
- success = 'Ваши данные успешно отправлены! Номер заказа #{}'.format(order_id)
- else:
- error = 'В некоторых полях содержатся ошибки!'
- form = ContactForm()
- context_data.update({
- 'error': error,
- 'success': success,
- 'form': form,
- 'order_id': order_id
- })
- else:
- form = ContactForm()
- match_by_groups = Match.objects.filter(Q(champ=Champ.objects.filter(id=33).first()), host__name='worldcup2018.me', datetime__gte=datetime.datetime.now(), hide_match=False).filter(~Q(
- group=Group.objects.filter(Q(translations__name='Товарищеские матчи'), host__name='worldcup2018.me').first())).distinct().order_by('group__menuposition',
- 'datetime')
- context_data.update({
- 'cart': context_data['mini_cart'],
- 'match_by_groups': match_by_groups,
- 'form': form
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def send_sms(number, msg):
- params = {
- 'login': 'bolshoi-tickets',
- 'password': '0b1ZKx1DMjjarrJk',
- 'to': number,
- 'txt': msg.encode('utf-8'),
- 'source': 'FIFA2018'
- }
- url = 'http://xn--80aa3adxha4f.xn----ptbkgfnb1a.xn--p1ai/lcabApi/sendSms.php?'
- req = urllib2.Request(
- url + urllib.urlencode(params),
- headers={
- 'User-Agent': 'Mozilla/5.0',
- 'Accept-Charset': 'utf-8'
- })
- try:
- page = urllib2.urlopen(req).read()
- # print page
- # logger.info(page)
- except Exception as e:
- pass
- # print e
- # logger.info('не удалось отослать sms')
- # logger.info(e)
- def packages(request):
- template = choose_template(request, "packages")
- context_data = default_context(request, 'packages', TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def contacts(request):
- template = choose_template(request, "contacts")
- context_data = default_context(request, 'contacts', TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def news(request):
- template = choose_template(request, "news")
- context_data = default_context(request, "news", TextPage)
- if request.GET.get('tag'):
- tag = Tags.objects.get(eng_name=request.GET['tag'])
- news = News.objects.filter(host=context_data['host_name'], tags__in=[tag], menushow=True).order_by('-date')
- tags = Tags.objects.all()
- context_data.update({
- 'news': news,
- 'tags': tags,
- 'tag': tag,
- })
- else:
- news = News.objects.filter(host=context_data['host_name'], menushow=True).order_by('-date')
- tags = Tags.objects.all()
- context_data.update({
- 'news': news,
- 'tags': tags,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def news_item(request, news_alias):
- template = choose_template(request, "news_item")
- context_data = default_context(request, news_alias, News)
- try:
- _next = context_data['data'].get_next_by_date()
- except News.DoesNotExist:
- _next = None
- try:
- prev = context_data['data'].get_previous_by_date()
- except News.DoesNotExist:
- prev = None
- context_data.update({
- 'next': _next,
- 'prev': prev,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def stadiums(request):
- template = choose_template(request, "stadiums")
- context_data = default_context(request, "stadiums", TextPage)
- stadiums = Stadium.objects.filter(Q(city__translations__country="Россия") | Q(city__translations__country="Russia"),
- host=context_data['host_name'], menushow=True).distinct().order_by('menuposition')
- context_data.update({
- 'stadiums': stadiums,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def champs(request):
- template = choose_template(request, "champs")
- context_data = default_context(request, "champs", TextPage)
- champs = Champ.objects.filter(~Q(translations__name='Товарищеские матчи'), ~Q(translations__name='Плей-офф'),
- host__name=context_data['host_name'])
- context_data.update({
- 'champs': champs,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- @csrf_exempt
- def paypage(request):
- template = choose_template(request, "paypage")
- context_data = default_context(request, "paypage", TextPage)
- if request.method == 'POST':
- if request.POST['method'] == 'qiwi':
- method = request.POST['method']
- sum = request.POST['sum']
- tovar = request.POST['tovar']
- qiwi_phone = request.POST['qiwi_phone']
- context_data.update({
- 'qiwi_phone': qiwi_phone,
- 'method': method,
- 'sum': sum,
- 'tovar': tovar,
- })
- else:
- method = request.POST['method']
- sum = request.POST['sum']
- tovar = request.POST['tovar']
- ya_type = request.POST['ya_type']
- successs = request.POST['successURL']
- koshel = request.POST['koshel']
- context_data.update({
- 'ya_type': ya_type,
- 'successs': successs,
- 'method': method,
- 'sum': sum,
- 'tovar': tovar,
- 'koshel': koshel,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def town(request, alias):
- template = choose_template(request, "town")
- context_data = default_context(request, alias, City)
- get_object_or_404(TextPage, alias='towns', host=context_data['host_name'])
- matches = Match.objects.filter(
- Q(champ__translations__name='Плей-офф') | Q(champ__translations__name='Групповой этап'), stadium__city=city,
- host=context_data['host_name']).distinct().order_by('datetime')
- stadiums = Stadium.objects.filter(city=context_data['data'], host=context_data['host_name'])
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = morph.parse(City.objects.get(alias=alias, host=context_data['host_name']).name)[0].inflect({'datv'}).word
- except:
- gent = City.objects.get(alias=alias, host=context_data['host_name']).name
- context_data.update({
- 'matches': matches,
- 'stadiums': stadiums,
- 'gent': gent,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def cities(request):
- template = choose_template(request, "towns")
- context_data = default_context(request, 'cities', TextPage)
- get_object_or_404(TextPage, alias='cities', host=context_data['host_name'])
- goroda = City.objects.filter(translations__country='Россия', host=context_data['host_name']).distinct().order_by(
- 'menuposition')
- context_data.update({
- 'goroda': goroda,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def goroda(request):
- template = choose_template(request, "towns")
- context_data = default_context(request, 'goroda', TextPage)
- get_object_or_404(TextPage, alias='goroda', host=context_data['host_name'])
- goroda = City.objects.filter(host=context_data['host_name']).distinct().order_by('menuposition')
- context_data.update({
- 'goroda': goroda,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def towns(request):
- template = choose_template(request, "towns")
- context_data = default_context(request, 'towns', TextPage)
- get_object_or_404(TextPage, alias='towns', host=context_data['host_name'])
- goroda = City.objects.filter(translations__country='Россия', host=context_data['host_name']).distinct().order_by(
- 'menuposition')
- context_data.update({
- 'goroda': goroda,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def city(request, alias):
- template = choose_template(request, "town")
- context_data = default_context(request, alias, City)
- get_object_or_404(TextPage, alias='cities', host=context_data['host_name'])
- matches = Match.objects.filter(Q(score=None),
- Q(champ__translations__name='Плей-офф') | Q(champ__translations__name='Групповой этап'),
- stadium__city=context_data['data'], host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- stadiums = Stadium.objects.filter(city=context_data['data'], host=context_data['host_name'])
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = morph.parse(City.objects.get(alias=alias, host=context_data['host_name']).name)[0].inflect({'datv'}).word
- except:
- gent = City.objects.get(alias=alias, host=context_data['host_name']).name
- context_data.update({
- 'stadiums': stadiums,
- 'matches': matches,
- 'gent': gent,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def gorod(request, alias):
- template = choose_template(request, "town")
- context_data = default_context(request, alias, City)
- get_object_or_404(TextPage, alias='goroda', host=context_data['host_name'])
- matches = Match.objects.filter(Q(score=None), (Q(champ__translations__name='Плей-офф') | Q(champ__translations__name='Групповой этап')),
- stadium__city__translations__name=context_data['data'].name,
- host=context_data['host_name']).distinct().order_by('datetime')
- stadiums = Stadium.objects.filter(city__translations__name=context_data['data'].name,
- host=context_data['host_name']).distinct()
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = morph.parse(City.objects.get(alias=alias, host=context_data['host_name']).name)[0].inflect({'datv'}).word
- except:
- gent = City.objects.get(alias=alias, host=context_data['host_name']).name
- context_data.update({
- 'stadiums': stadiums,
- 'matches': matches,
- 'gent': gent,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def teams(request):
- template = choose_template(request, "teams")
- context_data = default_context(request, "teams", TextPage)
- champs = Champ.objects.filter(host__name='fifa18.ru').distinct().order_by('translations__name').distinct()
- main_persons = Champ.objects.filter(host__name='fifa18.ru',
- translations__name='Плей-офф').distinct().first().teams.all().order_by('fed')
- context_data.update({
- 'champs': champs,
- 'main_persons': main_persons,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def teams_regions(request, champ_alias):
- template = choose_template(request, "teams_regions")
- context_data = default_context(request, champ_alias, TextPage)
- champ = Champ.objects.get(alias=champ_alias, host__name='fifa18.ru')
- context_data.update({
- 'champ': champ,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- @ensure_csrf_cookie
- def matches(request):
- template = choose_template(request, "matches")
- context_data = default_context(request, "matches", TextPage)
- order_id = -1
- success = ''
- error = ''
- ip = get_client_ip(request)
- if request.method == 'POST':
- cip = cache.get(ip, None)
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- if request.POST.get(u'g-recaptcha-response'):
- form = CorporateFormCaptcha(request.POST)
- try:
- cache.incr(ip, 1)
- except ValueError:
- cache.set(ip, 1, django_settings.BLACK_TIME_IP)
- elif cip >= django_settings.BLACK_COUNT_TRYING_IP:
- try:
- cache.incr(ip, 1)
- except ValueError: # на случай если вдруг в это время ключ уже удалился
- cache.set(ip, cip + 1, django_settings.BLACK_TIME_IP)
- # if cip == django_settings.BLACK_COUNT_TRYING_IP:
- # form = ContactForm(request.POST)
- # else:
- form = CorporateFormCaptcha(request.POST)
- else:
- cache.set(ip, 1, django_settings.BLACK_TIME_IP)
- form = CorporateForm(request.POST)
- else:
- form = CorporateForm(request.POST)
- if form.is_valid():
- name = form.cleaned_data['name']
- email = form.cleaned_data['email']
- # num = form.cleaned_data['num']
- # category = form.cleaned_data['category']
- phone = form.cleaned_data['phone']
- event = form.cleaned_data['event']
- message = form.cleaned_data['message']
- message_html = u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + u'</div><div>Категория билетов:' + event + u'</div><div>Email:' + email + u'</div><div>Сообщение: ' + message + u'</div>' # u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + '</div><div>Email:' + email + u'</div><div>Матч:' + event + u'</div><div>Категория: ' + category + u', Количество: ' + num + u'</div><div>Сообщение: ' + message + '</div>'
- bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Сообщение: {message}'.format(
- message=message
- )
- recipient_list = ['info@worldcup2018.me']
- _hostname = context_data.get('host_name', None) or get_current_hostname(request)
- try:
- send_mail(
- u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
- html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
- )
- except (BadHeaderError, AttributeError): # Защита от уязвимости
- error = 'Invalid header found'
- # Переходим на другую страницу, если сообщение отправлено
- success = 'Сообщение успешно отправлено!'
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- source_id, _msg = request.seo.analytics_message()
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- lang="0",
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0',
- source=force_unicode(source_id)
- )
- func = client.service.addOrderSourceI
- try:
- order_id = func(
- info_fio=name,
- info_tel=phone,
- info_email=email,
- info_title=u'Корпоративная заявка',
- info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
- # info_tc=num,
- info_cat=event,
- info_notes=u'<br/>'.join([bin_message, _msg]),
- **info
- )
- except Exception as erra:
- if getattr(django_settings, 'DEBUG', False):
- print erra # @TODO logger
- order_id = order_id
- url = 'http://185.154.52.97:8001/api/create-order-from-site/'
- new_bcontent = {
- "comment": u'Корпоративная завяка',
- "client_name": name,
- "client_phone": phone,
- # "client_phone_code": zone,
- # "client_address": addr,
- # "pay_type": paymethod,
- "site_name": request.get_host(),
- "old_bintranet_id": order_id,
- "client_comment": message
- }
- requests.post(url, headers={'content-type': 'application/json',
- 'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
- data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
- cart = Order.set_session(request)
- cart.phone = phone
- cart.email = email
- cart.fio = name
- cart.desc = bin_message.replace(u'<br>', u'\n')
- cart.website = website
- cart.bin_id = order_id
- cart.payment_processed = int(order_id) > 0
- cart.save()
- request.session.pop(django_settings.CART_SESSION_ID)
- else:
- error = 'В некоторых полях содержатся ошибки!'
- form = CorporateForm()
- matches = Match.objects.filter(
- champ=Champ.objects.filter(translations__name="Групповой этап", host__name='fifa18.ru').first(),
- menushow=True, host__name='fifa18.ru', hide_match=False).order_by('datetime').distinct()
- match_by_groups = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
- champ=Champ.objects.filter(translations__name="Групповой этап",
- host=context_data[
- 'host_name']).first()).distinct().order_by(
- 'group__menuposition', 'datetime')
- champ_teamss = Champ.objects.filter(translations__name="Групповой этап",
- host=context_data['host_name']).first().teams.all()
- # Group.objects.filter(champ__translations__name="Групповой этап", host=context_data['host_name']).order_by('alias').distinct()
- matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_quarterfinals = Match.objects.filter(Q(score=None),group__translations__name='1/4 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_semifinals = Match.objects.filter(Q(score=None),group__translations__name='1/2 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- final = Match.objects.filter(Q(score=None),group__translations__name='Финал',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- match_for_3 = Match.objects.filter(Q(score=None),group__translations__name='Матч за 3-е место',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- # stadiums = Stadium.objects.filter(host=context_data['host_name'])
- cities = City.objects.filter(Q(translations__country='Россия'), host=context_data['host_name']).distinct()
- groups = Group.objects.filter(
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- host__name=context_data['host_name']).distinct().order_by('menuposition')
- match_by_dates = Match.objects.filter(Q(score=None), host=context_data['host_name'],
- champ=Champ.objects.filter(translations__name="Групповой этап",
- host=context_data[
- 'host_name'], hide_match=False).first()).distinct().order_by(
- 'datetime')
- match_played = Match.objects.filter(~Q(score=None), host=context_data['host_name'], hide_match=False, champ=Champ.objects.filter(translations__name="Групповой этап", host=context_data['host_name']).first()).distinct().order_by('datetime')
- context_data.update({
- 'error': error,
- 'success': success,
- 'form': form,
- 'cities': cities,
- 'matches': matches,
- 'matches_1_8': matches_1_8,
- 'matches_quarterfinals': matches_quarterfinals,
- 'matches_semifinals': matches_semifinals,
- 'match_for_3': match_for_3,
- 'final': final,
- 'match_by_groups': match_by_groups,
- 'groups': groups,
- 'order_id': order_id,
- 'match_by_dates': match_by_dates,
- 'match_played': match_played
- })
- else:
- matches = Match.objects.filter(
- champ=Champ.objects.filter(translations__name="Групповой этап", host__name='fifa18.ru').first(),
- menushow=True, host__name='fifa18.ru', hide_match=False).order_by('datetime').distinct()
- match_by_groups = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
- champ=Champ.objects.filter(translations__name="Групповой этап",
- host=context_data[
- 'host_name']).first()).distinct().order_by(
- 'group__menuposition', 'datetime')
- champ_teamss = Champ.objects.filter(translations__name="Групповой этап",
- host=context_data['host_name']).first().teams.all()
- # Group.objects.filter(champ__translations__name="Групповой этап", host=context_data['host_name']).order_by('alias').distinct()
- matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_quarterfinals = Match.objects.filter(Q(score=None), group__translations__name='1/4 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_semifinals = Match.objects.filter(Q(score=None), group__translations__name='1/2 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- final = Match.objects.filter(Q(score=None), group__translations__name='Финал',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- match_for_3 = Match.objects.filter(Q(score=None), group__translations__name='Матч за 3-е место',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- # stadiums = Stadium.objects.filter(host=context_data['host_name'])
- cities = City.objects.filter(Q(translations__country='Россия'), host=context_data['host_name']).distinct()
- groups = Group.objects.filter(
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- host__name=context_data['host_name']).distinct().order_by('menuposition')
- match_by_dates = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
- champ=Champ.objects.filter(translations__name="Групповой этап",
- host=context_data[
- 'host_name']).first()).distinct().order_by(
- 'datetime')
- match_played = Match.objects.filter(~Q(score=None), host=context_data['host_name'], hide_match=False, champ=Champ.objects.filter(translations__name="Групповой этап", host=context_data['host_name']).first()).distinct().order_by('group__menuposition', 'datetime')
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- if cache.get(ip) >= django_settings.BLACK_COUNT_TRYING_IP:
- form = CorporateFormCaptcha()
- else:
- form = CorporateForm()
- else:
- form = CorporateForm()
- context_data.update({
- 'form': form,
- 'cities': cities,
- 'matches': matches,
- 'matches_1_8': matches_1_8,
- 'matches_quarterfinals': matches_quarterfinals,
- 'matches_semifinals': matches_semifinals,
- 'match_for_3': match_for_3,
- 'final': final,
- 'match_by_groups': match_by_groups,
- # 'stadiums': stadiums,
- 'champ_teamss': champ_teamss,
- 'groups': groups,
- 'success': success,
- 'match_by_dates': match_by_dates,
- 'order_id': order_id,
- 'match_played': match_played
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def matchi(request):
- template = choose_template(request, "matches")
- context_data = default_context(request, "matchi", TextPage)
- if request.method == 'POST':
- form = CorporateForm(request.POST)
- error = ''
- success = ''
- suces = -1
- if form.is_valid():
- name = form.cleaned_data['name']
- email = form.cleaned_data['email']
- num = form.cleaned_data['num']
- category = form.cleaned_data['category']
- phone = form.cleaned_data['phone']
- event = form.cleaned_data['event']
- message = form.cleaned_data['message']
- # _message_data = map(
- # force_unicode,
- # [name, email, phone, match_name, category, type, num, form.cleaned_data.get(
- # 'message', u"Без сообщения"
- # )]
- message_html = u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + '</div><div>Email:' + email + u'</div><div>Матч:' + event + u'</div><div>Категория: ' + category + u', Количество: ' + num + u'</div><div>Сообщение: ' + message + '</div>'
- bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Матч: {event}<br> Категория: {category}<br> Сообщение: {message}'.format(
- event=event, category=category, message=message
- )
- recipient_list = ['vladyan.s@yandex.ru']
- _hostname = context_data.get('host_name', None) or get_current_hostname(request)
- try:
- send_mail(
- u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
- html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
- )
- except BadHeaderError: # Защита от уязвимости
- error = 'Invalid header found'
- # Переходим на другую страницу, если сообщение отправлено
- success = 'Сообщение успешно отправлено!'
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- source_id, _msg = request.seo.analytics_message()
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- lang="0",
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0',
- source=force_unicode(source_id)
- )
- func = client.service.addOrderSourceI
- try:
- order_id = func(
- info_fio=name,
- info_tel=phone,
- info_email=email,
- info_title=u'Корпоративная заявка',
- info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
- info_tc=num,
- info_cat=category,
- info_notes=u'<br/>'.join([bin_message, _msg]),
- **info
- )
- except Exception as erra:
- if getattr(django_settings, 'DEBUG', False):
- print erra # @TODO logger
- suces = order_id
- cart = Order.set_session(request)
- cart.phone = phone
- cart.email = email
- cart.fio = name
- cart.desc = bin_message.replace(u'<br>', u'\n')
- cart.website = website
- cart.bin_id = order_id
- cart.payment_processed = int(order_id) > 0
- cart.save()
- request.session.pop(django_settings.CART_SESSION_ID)
- else:
- error = 'В некоторых полях содержатся ошибки!'
- form = CorporateForm()
- context_data.update({
- 'error': error,
- 'success': success,
- 'form': form,
- 'suces': suces,
- })
- else:
- matches = Match.objects.filter(Q(score=None),
- champ=Champ.objects.filter(translations__name="Групповой этап", host__name=context_data['host_name']).first(),
- menushow=True, host__name=context_data['host_name']).order_by('datetime').distinct()
- champ_teamss = Group.objects.filter(champ__translations__name="Групповой этап",
- host__name=context_data['host_name']).order_by('alias').distinct()
- matches_1_8 = Match.objects.filter(group__translations__name='1/8 Финала',
- host=context_data['host_name']).distinct().order_by('datetime')
- matches_quarterfinals = Match.objects.filter(group__translations__name='1/4 Финала',
- host=context_data['host_name']).distinct().order_by('datetime')
- matches_semifinals = Match.objects.filter(group__translations__name='1/2 Финала',
- host=context_data['host_name']).distinct().order_by('datetime')
- final = Match.objects.filter(group__translations__name='Финал',
- host=context_data['host_name']).distinct().order_by('datetime')
- match_for_3 = Match.objects.filter(group__translations__name='Матч за 3-е место',
- host=context_data['host_name']).distinct().order_by('datetime')
- stadiums = Stadium.objects.filter(host=context_data['host_name'])
- form = CorporateForm()
- context_data.update({
- 'form': form,
- 'matches': matches,
- 'matches_1_8': matches_1_8,
- 'matches_quarterfinals': matches_quarterfinals,
- 'matches_semifinals': matches_semifinals,
- 'match_for_3': match_for_3,
- 'final': final,
- 'stadiums': stadiums,
- 'champ_teamss': champ_teamss,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def games(request):
- template = choose_template(request, "matches")
- context_data = default_context(request, "games", TextPage)
- if request.method == 'POST':
- form = CorporateForm(request.POST)
- error = ''
- success = ''
- suces = -1
- if form.is_valid():
- name = form.cleaned_data['name']
- email = form.cleaned_data['email']
- num = form.cleaned_data['num']
- category = form.cleaned_data['category']
- phone = form.cleaned_data['phone']
- event = form.cleaned_data['event']
- message = form.cleaned_data['message']
- # _message_data = map(
- # force_unicode,
- # [name, email, phone, match_name, category, type, num, form.cleaned_data.get(
- # 'message', u"Без сообщения"
- # )]
- message_html = u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + '</div><div>Email:' + email + u'</div><div>Матч:' + event + u'</div><div>Категория: ' + category + u', Количество: ' + num + u'</div><div>Сообщение: ' + message + '</div>'
- bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Матч: {event}<br> Категория: {category}<br> Сообщение: {message}'.format(
- event=event, category=category, message=message
- )
- recipient_list = ['vladyan.s@yandex.ru']
- _hostname = context_data.get('host_name', None) or get_current_hostname(request)
- try:
- send_mail(
- u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
- html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
- )
- except BadHeaderError: # Защита от уязвимости
- error = 'Invalid header found'
- # Переходим на другую страницу, если сообщение отправлено
- success = 'Сообщение успешно отправлено!'
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- source_id, _msg = request.seo.analytics_message()
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- lang="0",
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0',
- source=force_unicode(source_id)
- )
- func = client.service.addOrderSourceI
- try:
- order_id = func(
- info_fio=name,
- info_tel=phone,
- info_email=email,
- info_title=u'Корпоративная заявка',
- info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
- info_tc=num,
- info_cat=category,
- info_notes=u'<br/>'.join([bin_message, _msg]),
- **info
- )
- except Exception as erra:
- if getattr(django_settings, 'DEBUG', False):
- print erra # @TODO logger
- suces = order_id
- cart = Order.set_session(request)
- cart.phone = phone
- cart.email = email
- cart.fio = name
- cart.desc = bin_message.replace(u'<br>', u'\n')
- cart.website = website
- cart.bin_id = order_id
- cart.payment_processed = int(order_id) > 0
- cart.save()
- request.session.pop(django_settings.CART_SESSION_ID)
- else:
- error = 'В некоторых полях содержатся ошибки!'
- form = CorporateForm()
- context_data.update({
- 'error': error,
- 'success': success,
- 'form': form,
- 'suces': suces,
- })
- else:
- matches = Match.objects.filter(
- champ=Champ.objects.filter(translations__name="Групповой этап", host__name='fifa18.ru').first(),
- menushow=True, host__name='fifa18.ru').order_by('datetime').distinct()
- champ_teamss = Group.objects.filter(champ__translations__name="Групповой этап",
- host__name='fifa18.ru').order_by('alias').distinct()
- matches_1_8 = Match.objects.filter(group__translations__name='1/8 Финала',
- host=context_data['host_name']).distinct().order_by('datetime')
- matches_quarterfinals = Match.objects.filter(group__translations__name='1/4 Финала',
- host=context_data['host_name']).distinct().order_by('datetime')
- matches_semifinals = Match.objects.filter(group__translations__name='1/2 Финала',
- host=context_data['host_name']).distinct().order_by('datetime')
- final = Match.objects.filter(group__translations__name='Финал',
- host=context_data['host_name']).distinct().order_by('datetime')
- match_for_3 = Match.objects.filter(group__translations__name='Матч за 3-е место',
- host=context_data['host_name']).distinct().order_by('datetime')
- stadiums = Stadium.objects.filter(host=context_data['host_name'])
- form = CorporateForm()
- context_data.update({
- 'form': form,
- 'matches': matches,
- 'matches_1_8': matches_1_8,
- 'matches_quarterfinals': matches_quarterfinals,
- 'matches_semifinals': matches_semifinals,
- 'match_for_3': match_for_3,
- 'final': final,
- 'stadiums': stadiums,
- 'champ_teamss': champ_teamss,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def team(request, team_alias):
- template = choose_template(request, "team")
- context_data = default_context(request, team_alias, Team)
- # teams_alias = get_host_vs_url( context_data['host_name'] , request.get_full_path() , 'teams' )
- # parent_textpage = TextPage.objects.get(alias=teams_alias,host=context_data['host_name'])
- teams_alias = get_alias_related(context_data['host_name'], 'teams')
- # if context_data['host_name'] == 'confcuptickets.ru' :
- # teams_alias = 'comands'
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = morph.parse(Team.objects.get(alias=team_alias, host=context_data['host_name']).name)[0].inflect(
- {'gent'}).word
- except:
- gent = Team.objects.get(alias=team_alias, host=context_data['host_name']).name
- breadcrumbs = [TextPage.objects.get(alias=teams_alias, host=context_data['host_name'])]
- groups = Group.objects.filter(teams=context_data['data'])
- matches = Match.objects.filter(
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- Q(command_first=context_data['data']) | Q(command_second=context_data['data']), Q(score=None),
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- players = Player.objects.filter(team=context_data['data'])
- coaches = Player.objects.filter(Q(translations__position="тренер") | Q(translations__position="Тренер"),
- team=context_data['data'], team__alias=team_alias,
- host=context_data['host_name']).distinct()
- goalkeepers = Player.objects.filter(Q(translations__position="вратарь") | Q(translations__position="Вратарь"),
- team__alias=team_alias, host=context_data['host_name']).distinct()
- defenders = Player.objects.filter(Q(translations__position="защитник") | Q(translations__position="Защитник"),
- team__alias=team_alias, host=context_data['host_name']).distinct()
- midfielders = Player.objects.filter(
- Q(translations__position="полузащитник") | Q(translations__position="Полузащитник"), team__alias=team_alias,
- host=context_data['host_name']).distinct()
- attacks = Player.objects.filter(Q(translations__position="нападающий") | Q(translations__position="Нападающий"),
- team__alias=team_alias, host=context_data['host_name']).distinct()
- context_data.update({
- 'gent': gent,
- 'breadcrumbs': breadcrumbs,
- 'groups': groups,
- 'matches': matches,
- 'players': players,
- 'coaches': coaches,
- 'goalkeepers': goalkeepers,
- 'defenders': defenders,
- 'midfielders': midfielders,
- 'attacks': attacks,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def team_matches(request, team_alias):
- template = choose_template(request, "team_matches")
- context_data = default_context(request, team_alias, Team)
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = morph.parse(Team.objects.get(alias=team_alias, host=context_data['host_name']).name)[0].inflect(
- {'datv'}).word
- except:
- gent = Team.objects.get(alias=team_alias, host=context_data['host_name']).name
- matches = Match.objects.filter(Q(command_first__alias=team_alias) | Q(command_second__alias=team_alias),
- host__name='fifa18.ru')
- context_data.update({
- 'matches': matches,
- 'gent': gent,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def get_birth(data):
- if data.birth.year == 1:
- return u"Нет данных"
- else:
- return data.birth
- def player_redierect(request, player_alias):
- template = choose_template(request, "player")
- try:
- player_item = Player.objects.get(alias=player_alias, host__name=get_current_hostname(request))
- return HttpResponsePermanentRedirect('/teams/' + player_item.team.alias + '/players/' + player_item.alias + '/')
- except Player.DoesNotExist:
- player_item = Http404
- context_data = default_context(request, player_item, Player)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def player(request, team_alias, player_alias):
- template = choose_template(request, "player")
- try:
- player_item = Player.objects.get(alias=player_alias, team__alias=team_alias,
- host__name=get_current_hostname(request)).alias
- except Player.DoesNotExist:
- player_item = Http404
- context_data = default_context(request, player_item, Player)
- team = default_context(request, team_alias, Team)
- matches = Match.objects.filter(
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- Q(command_first=team['data']) | Q(command_second=team['data']), Q(score=None),
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- teams_alias = get_alias_related(context_data['host_name'], 'teams')
- # if context_data['host_name'] == 'confcuptickets.ru' :
- # teams_alias = 'comands'
- # breadcrumbs = [TextPage.objects.get(alias=player_alias, host=context_data['host_name']), context_data['data'].team]
- birth = get_birth(context_data['data'])
- gent = None
- try:
- morph = pymorphy2.MorphAnalyzer()
- gent = morph.parse(context_data['data'].team.name)[0].inflect({'gent'}).word
- except Exception:
- pass
- context_data.update({
- 'gent': gent,
- 'birth': birth,
- 'matches': matches
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def team_players(request, team_alias):
- template = choose_template(request, "players")
- context_data = default_context(request, team_alias, Team)
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = morph.parse(Team.objects.get(alias=team_alias, host=context_data['host_name']).name)[0].inflect(
- {'gent'}).word
- except:
- gent = Team.objects.get(alias=team_alias, host=context_data['host_name']).name
- goalkeepers = Player.objects.filter(Q(translations__position="вратарь") | Q(translations__position="Вратарь"),
- team__alias=team_alias, host=context_data['host_name']).distinct()
- defenders = Player.objects.filter(Q(translations__position="защитник") | Q(translations__position="Защитник"),
- team__alias=team_alias, host=context_data['host_name']).distinct()
- midfielders = Player.objects.filter(
- Q(translations__position="полузащитник") | Q(translations__position="Полузащитник"), team__alias=team_alias,
- host=context_data['host_name']).distinct()
- attacks = Player.objects.filter(Q(translations__position="нападающий") | Q(translations__position="Нападающий"),
- team__alias=team_alias, host=context_data['host_name']).distinct()
- context_data.update({
- 'gent': gent,
- 'goalkeepers': goalkeepers,
- 'defenders': defenders,
- 'midfielders': midfielders,
- 'attacks': attacks,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def match(request, match_alias):
- template = choose_template(request, "match")
- url_path = TextPage.objects.filter(Q(translations__name='Матчи') | Q(translations__name='Расписание'),
- host__name=get_current_hostname(request)).first().alias
- try:
- if url_path != request.path.split('/')[1]:
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- elif match_alias == 'match010720181700':
- return HttpResponsePermanentRedirect('/' + url_path + '/rossiya-ispaniya/')
- elif match_alias == 'b1-a1-01-07-2018-17-00':
- return HttpResponsePermanentRedirect('/' + url_path + '/rossiya-ispaniya/')
- elif (match_alias.split('-')[0])[0].isupper():
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- elif (match_alias.split(' ')[1]) is not None:
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- except:
- pass
- context_data = default_context(request, match_alias, Match)
- matches_alias = get_alias_related(context_data['host_name'], 'matches')
- # breadcrumbs = [TextPage.objects.get(alias=matches_alias, host=context_data['host_name'])]
- # next_match = Match.objects.filter(score=None, host=context_data['host_name'], champ__translations__name='Групповой этап').distinct().order_by('datetime')[:2]
- try:
- next = context_data['data'].get_next_by_datetime()
- except Match.DoesNotExist:
- next = None
- try:
- prev = context_data['data'].get_previous_by_datetime()
- except Match.DoesNotExist:
- prev = None
- morph = pymorphy2.MorphAnalyzer()
- try:
- gent = \
- morph.parse(Team.objects.filter(translations__name=context_data['data'].command_first.name).first().name)[
- 0].inflect({'gent'}).word
- gent2 = \
- morph.parse(Team.objects.filter(translations__name=context_data['data'].command_second.name).first().name)[
- 0].inflect({'gent'}).word
- except:
- gent = Team.objects.filter(translations__name=context_data['data'].command_first.name).first().name
- gent2 = Team.objects.filter(translations__name=context_data['data'].command_second.name).first().name
- # _tickets = context_data.get('data').tickets(request=request)
- # print _tickets.tickets_by_sector(_tickets.sectors[0])[0].id
- # @TODO here goes tickets from parser and next line is fallback DB info
- tickets = Price.objects.filter(match=context_data['data']).order_by('order_id')
- stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id')
- team1matches = Match.objects.filter(
- Q(command_first=context_data['data'].command_first) | Q(command_second=context_data['data'].command_first),
- host=context_data['host_name'], champ__translations__name='Групповой этап', hide_match=False).distinct().order_by('datetime')
- team2matches = Match.objects.filter(
- Q(command_first=context_data['data'].command_second) | Q(command_second=context_data['data'].command_second),
- host=context_data['host_name'], champ__translations__name='Групповой этап', hide_match=False).distinct().order_by('datetime')
- player1 = Player.objects.filter(team__translations__name=context_data['data'].command_first.name,
- host=context_data['host_name']).distinct()
- player2 = Player.objects.filter(team__translations__name=context_data['data'].command_second.name,
- host=context_data['host_name']).distinct()
- reviews = Reviews.objects.filter(published=True).order_by('id').reverse()[:5]
- test = 'proverka'
- context_data.update({
- 'tickets': tickets,
- 'test': test,
- 'stadiums': stadiums,
- 'next': next,
- 'prev': prev,
- 'team1matches': team1matches,
- 'team2matches': team2matches,
- 'gent': gent,
- 'gent2': gent2,
- 'player1': player1,
- 'player2': player2,
- 'reviews': reviews,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def match2(request, match_alias):
- template = choose_template(request, "match")
- url_path = TextPage.objects.filter(Q(translations__name='Матчи') | Q(translations__name='Расписание'),
- host__name=get_current_hostname(request)).first().alias
- try:
- if url_path != request.path.split('/')[1]:
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- elif (match_alias.split('-')[0])[0].isupper():
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- elif (match_alias.split(' ')[1]) is not None:
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- except:
- a = 123
- context_data = default_context(request, match_alias, Match)
- matches_alias = get_alias_related(context_data['host_name'], 'matches')
- # breadcrumbs = [TextPage.objects.get(alias=matches_alias, host=context_data['host_name'])]
- next_match = Match.objects.filter(score=None, host=context_data['host_name']).order_by('datetime')[:2]
- try:
- next = context_data['data'].get_next_by_datetime()
- except Match.DoesNotExist:
- next = None
- try:
- prev = context_data['data'].get_previous_by_datetime()
- except Match.DoesNotExist:
- prev = None
- # _tickets = context_data.get('data').tickets(request=request)
- # print _tickets.tickets_by_sector(_tickets.sectors[0])[0].id
- # @TODO here goes tickets from parser and next line is fallback DB info
- tickets = Price.objects.filter(match=context_data['data']).order_by('id')
- stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id')
- context_data.update({
- # 'breadcrumbs': breadcrumbs,
- 'tickets': tickets,
- 'stadiums': stadiums,
- 'next_match': next_match,
- 'next': next,
- 'prev': prev,
- # 'parse_tickets': _tickets.sectors,
- # 'svg': open(context_data.get('data').svg.path, 'r+').read() if context_data.get('data').svg else ''
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def game(request, match_alias):
- template = choose_template(request, "match")
- url_path = TextPage.objects.filter(Q(translations__name='Матчи') | Q(translations__name='Расписание'),
- host__name=get_current_hostname(request)).first().alias
- try:
- if url_path != request.path.split('/')[1]:
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- elif (match_alias.split('-')[0])[0].isupper():
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- elif (match_alias.split(' ')[1]) is not None:
- new_url = match_alias.lower().replace(' ', '-')
- return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
- except:
- a = 123
- context_data = default_context(request, match_alias, Match)
- matches_alias = get_alias_related(context_data['host_name'], 'matches')
- # breadcrumbs = [TextPage.objects.get(alias=matches_alias, host=context_data['host_name'])]
- next_match = Match.objects.filter(score=None, host=context_data['host_name']).order_by('datetime')[:2]
- try:
- next = context_data['data'].get_next_by_datetime()
- except Match.DoesNotExist:
- next = None
- try:
- prev = context_data['data'].get_previous_by_datetime()
- except Match.DoesNotExist:
- prev = None
- # _tickets = context_data.get('data').tickets(request=request)
- # print _tickets.tickets_by_sector(_tickets.sectors[0])[0].id
- # @TODO here goes tickets from parser and next line is fallback DB info
- tickets = Price.objects.filter(match=context_data['data']).order_by('id')
- stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id')
- context_data.update({
- # 'breadcrumbs': breadcrumbs,
- 'tickets': tickets,
- 'stadiums': stadiums,
- 'next_match': next_match,
- 'next': next,
- 'prev': prev,
- # 'parse_tickets': _tickets.sectors,
- # 'svg': open(context_data.get('data').svg.path, 'r+').read() if context_data.get('data').svg else ''
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def stadium(request, stadium_alias):
- template = choose_template(request, "stadium")
- url_path = TextPage.objects.filter(Q(translations__name='Стадионы'),
- host__name=get_current_hostname(request)).first().alias
- try:
- if stadium_alias.split(' ')[1] is not None:
- new_alias = stadium_alias.replace(' ', '-')
- return HttpResponsePermanentRedirect('/stadiums/' + new_alias + '/')
- except:
- a = 123
- context_data = default_context(request, stadium_alias, Stadium)
- today = datetime.date.today()
- matches = Match.objects.filter(~Q(champ__translations__name='Кубок конфедераций 2017'),
- ~Q(group__translations__name='Товарищеские матчи'), datetime__gt=today,
- stadium=context_data['data'], host=context_data['host_name'], hide_match=False).order_by(
- 'datetime').distinct().order_by('group__menuposition', 'datetime')
- news = News.objects.filter(host=context_data['host_name'], menushow=True).order_by('-date')
- context_data.update({
- 'matches': matches,
- 'news': news,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def fed(request, fed_alias):
- template = choose_template(request, "fed")
- context_data = default_context(request, fed_alias, Fed)
- champs = Champ.objects.filter(fed=context_data['data'])
- context_data.update({
- 'champs': champs
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def prices_api(request):
- template = loader.get_template('prices_api.html')
- matches = Match.objects.filter(Q(champ=Champ.objects.filter(translations__name="Групповой этап",
- host=Site.objects.get(
- name=get_current_hostname(request))).first()) | Q(
- group__translations__name='1/2 Финала') | Q(group__translations__name='1/4 Финала') | Q(
- group__translations__name='1/8 Финала') | Q(group__translations__name='Финал') | Q(
- group__translations__name='Матч за 3-е место'),
- host=Site.objects.get(name=get_current_hostname(request))).distinct().order_by(
- 'group__menuposition', 'datetime')
- context = RequestContext(request, {
- 'matches': matches
- })
- return HttpResponse(template.render(context))
- @csrf_exempt
- def test(request):
- template = choose_template(request, "test")
- context_data = default_context(request, "test", TextPage)
- items = Match.objects.filter(
- Q(champ=Champ.objects.filter(translations__name="Групповой этап", host=Site.objects.get(id=1)).first()),
- host=Site.objects.get(id=1)).distinct().order_by('group__menuposition', 'datetime')
- context_data.update({
- 'test': test,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- @login_required
- def match_builder(request):
- if request.is_ajax():
- data = json.loads(request.read())
- if data['type'] == 'get_site_info':
- items = []
- count = 0
- for i in Match.objects.filter(Q(champ=Champ.objects.filter(translations__name="Групповой этап",
- host=Site.objects.get(
- id=data['data'])).first()) | Q(
- group__translations__name='1/2 Финала') | Q(group__translations__name='1/4 Финала') | Q(
- group__translations__name='1/8 Финала') | Q(group__translations__name='Финал') | Q(
- group__translations__name='Матч за 3-е место'),
- host=Site.objects.get(id=data['data'])).distinct().order_by(
- 'group__menuposition', 'datetime'):
- items.append({'cmnd_frst_flg': i.command_first.get_flag_list()[1],
- 'cmnd_scnd_flg': i.command_second.get_flag_list()[1],
- 'command_first': i.command_first.name, 'command_second': i.command_second.name,
- 'id': i.id, 'prices': []})
- its = Price.objects.filter(match=i, host=Site.objects.get(id=data['data'])).distinct()
- for it in its:
- items[count]['prices'].append({'price': int(it.price), 'sector': it.sector, 'id': it.id})
- count += 1
- MyValue = json.dumps(items, ensure_ascii=False).encode('utf8')
- elif data['type'] == 'change_price':
- Price.objects.filter(id=data['data']['id']).update(price=int(data['data']['price']), status=data['data']['status'])
- MyValue = 'Good'
- return HttpResponse(MyValue)
- else:
- template = choose_template(request, "match_form")
- context_data = default_context(request, "match-builder", TextPage)
- sites = Site.objects.all()
- matches = Match.objects.filter(Q(score=None), Q(champ=Champ.objects.filter(translations__name="Групповой этап",
- host=Site.objects.get(
- name=context_data['host_name'])).first()) | Q(
- group__translations__name='1/2 Финала') | Q(group__translations__name='1/4 Финала') | Q(
- group__translations__name='1/8 Финала') | Q(group__translations__name='Финал') | Q(
- group__translations__name='Матч за 3-е место'),
- host=Site.objects.get(name=context_data['host_name'])).distinct().order_by(
- 'datetime')
- context_data.update({
- 'sites': sites,
- 'matches': matches
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def googleverify(request):
- template = choose_template(request, "google30a074ebbcd9e045")
- context_data = default_context(request, "test", TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def zayavka(request, zayavka_alias):
- template = choose_template(request, "zayavka")
- context_data = default_context(request, zayavka_alias, Fed)
- breadcrumbs = [TextPage.objects.get(alias='zayavki', host=context_data['host_name'])]
- context_data.update({
- 'breadcrumbs': breadcrumbs,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def champ(request, champ_alias):
- template = choose_template(request, "champ")
- context_data = default_context(request, champ_alias, Champ)
- groups = Group.objects.filter(champ=Champ.objects.filter(alias=champ_alias).first(),
- host=context_data['host_name']).distinct().order_by('alias')
- context_data.update({
- 'groups': groups,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def groups(request):
- template = choose_template(request, "groups")
- context_data = default_context(request, "groups", TextPage)
- groups = Group.objects.filter(host=context_data['host_name'])
- context_data.update({
- 'groups': groups
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def group(request, champ_alias, group_alias):
- template = choose_template(request, "group")
- try:
- group_item = Group.objects.filter(alias=group_alias, champ__alias=champ_alias).first().alias
- except Group.DoesNotExist:
- group_item = Http404
- context_data = default_context(request, group_item, Group)
- group = Group.objects.get(alias=group_alias, host=context_data['host_name'])
- matches = Match.objects.filter(group__alias=group_alias, group__champ__alias=champ_alias,
- host=context_data['host_name']).order_by('datetime')
- context_data.update({
- 'group': group,
- 'matches': matches,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def get_field_value(object, field):
- from django.db.models.fields import IntegerField, DateField, DateTimeField
- from django.db.models.fields.files import ImageField
- from django.contrib.postgres.fields.jsonb import JSONField
- import json
- value = eval("object." + field)
- field_type = "other"
- if type(value) == bool:
- field_type = "bool"
- if value:
- value = "1"
- else:
- value = "0"
- elif isinstance(object._meta.get_field(field), IntegerField):
- field_type = "int"
- if value:
- value = str(value)
- else:
- value = "0"
- elif isinstance(object._meta.get_field(field), DateField):
- field_type = "date"
- if value:
- value = str(value.strftime("%d.%m.%Y"))
- else:
- value = "01.01.1900"
- elif isinstance(object._meta.get_field(field), DateTimeField):
- field_type = "datetime"
- if value:
- value = str(value.strftime("%d.%m.%Y,%H:%M"))
- else:
- value = "01.01.1900,00:00"
- elif isinstance(object._meta.get_field(field), ImageField):
- field_type = "image"
- if value:
- value = str(value).split("/")[-1]
- else:
- value = ""
- elif isinstance(object._meta.get_field(field), JSONField):
- field_type = "json"
- value = json.dumps(value, ensure_ascii=False, encoding='utf8')
- elif type(value) == unicode or type(value) == str:
- field_type = "str"
- value = value.encode('utf8').replace('"', '\\"')
- else:
- if value:
- value = str(value)
- else:
- value = ""
- return [field, value, field_type]
- def export(request, export_type):
- template = loader.get_template('export.html')
- if export_type == 'team':
- object = Team
- elif export_type == 'match':
- object = Match
- elif export_type == 'player':
- object = Player
- elif export_type == 'stadium':
- object = Stadium
- elif export_type == 'champ':
- object = Champ
- elif export_type == 'champ':
- object = Champ
- elif export_type == 'fed':
- object = Fed
- elif export_type == 'group':
- object = Group
- elif export_type == 'textpage':
- object = TextPage
- else:
- object = Team
- fields = [field.name for field in object._meta.fields]
- # objects = object.objects.filter(host__name=request.get_host()).all()
- data = []
- for object in objects:
- item = []
- for field in fields:
- if field != 'id':
- field_param = get_field_value(object, field) # [field , value , type]
- item.append(field_param)
- data.append(item)
- context = RequestContext(request, {
- 'objects': objects,
- 'fields': fields,
- 'data': data,
- })
- return HttpResponse(template.render(context), content_type="text/plain;charset=utf-8")
- def call_back(request):
- if request.is_ajax():
- success = 'ajax:no-method'
- if request.POST['type'] == 'callback':
- email = request.POST.get('email')
- phone_new = request.POST.get('phone')
- message = request.POST.get('message')
- form_order_id = request.POST.get('order_id')
- subject = u'Узнать статус закза #{}'.format(form_order_id)
- message = u'Некий господин/госпожа хочет узнать статус доставки на телефон {phone}. Email: {email} <br> Сообщение: {message}'.format(
- email=email, phone=phone_new, message=message
- )
- recipients = ['vladyan.s@yandex.ru', 'vladyan121@gmail.com']
- # send_mail(
- # subject, message, EMAIL_FROM, recipients, html_message=message,
- # fail_silently=not getattr(django_settings, 'DEBUG', False)
- # )
- order_id = -1
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- source_id, _msg = request.seo.analytics_message()
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- lang="0",
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0',
- source=force_unicode(source_id)
- )
- # func = client.service.addOrderSourceI
- #
- # try:
- # order_id = func(
- # info_fio=u"",
- # info_tel=phone_new,
- # info_title=u'Узнать статус доставки',
- # info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
- # info_cat=u'Узнать статус доставки',
- # info_notes=u'<br/>'.join([message, _msg]),
- # **info
- # )
- # except Exception as erra:
- # if getattr(django_settings, 'DEBUG', False):
- # print erra # @TODO logger
- url = 'http://185.154.52.97:8001/api/create-order-from-site/'
- new_bcontent = {
- "comment": message,
- "client_name": u'Узнать статус доставки #{}'.format(form_order_id),
- "client_phone": phone_new,
- # "client_phone_code": zone,
- # "client_address": addr,
- # "pay_type": paymethod,
- "site_name": request.get_host(),
- "old_bintranet_id": order_id,
- "status": 23,
- }
- send_message = requests.post(url, headers={'content-type': 'application/json',
- 'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
- data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
- success = send_message.json().get('pk', -1)
- cart = Order.set_session(request)
- cart.phone = phone_new
- cart.fio = u'Узнать статус доставки #{}'.format(order_id),
- cart.desc = u'\n'.join([u'Обратный звонок', message])
- cart.website = website
- cart.bin_id = order_id
- cart.payment_processed = int(order_id) > 0
- cart.save()
- request.session.pop(django_settings.CART_SESSION_ID)
- return HttpResponse(success)
- else:
- return HttpResponse('no-ajax method')
- def vip_tickets(request):
- # VIP MATCHES
- lodge = request.POST.get('lodge')
- if lodge:
- return get_vip(request, lodge)
- def vip(request):
- template = choose_template(request, "vip")
- context_data = default_context(request, "vip-hospitality", TextPage)
- order_id = ''
- groups = Group.objects.filter(
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- host__name=context_data['host_name']).distinct().order_by('menuposition')
- match_by_groups = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
- champ=Champ.objects.filter(translations__name="Групповой этап",
- host=context_data[
- 'host_name']).first()).distinct().order_by('group__menuposition', 'datetime')
- matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_quarterfinals = Match.objects.filter(Q(score=None),group__translations__name='1/4 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- matches_semifinals = Match.objects.filter(Q(score=None),group__translations__name='1/2 Финала',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- final = Match.objects.filter(Q(score=None),group__translations__name='Финал',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- match_for_3 = Match.objects.filter(Q(score=None),group__translations__name='Матч за 3-е место',
- host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
- ip = get_client_ip(request)
- if request.method == 'POST':
- cip = cache.get(ip, None)
- # if cache.get('captcha') == None:
- # try:
- # if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- # cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- # else:
- # cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- # except Exception:
- # cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- #
- # if cache.get('captcha') == True:
- # if request.POST.get(u'g-recaptcha-response'):
- # form = CorporateFormCaptcha(request.POST)
- # try:
- # cache.incr(ip, 1)
- # except ValueError:
- # cache.set(ip, 1, django_settings.BLACK_TIME_IP)
- # elif cip >= django_settings.BLACK_COUNT_TRYING_IP:
- # try:
- # cache.incr(ip, 1)
- # except ValueError: # на случай если вдруг в это время ключ уже удалился
- # cache.set(ip, cip + 1, django_settings.BLACK_TIME_IP)
- # # if cip == django_settings.BLACK_COUNT_TRYING_IP:
- # # form = ContactForm(request.POST)
- # # else:
- # form = CorporateFormCaptcha(request.POST)
- # else:
- # cache.set(ip, 1, django_settings.BLACK_TIME_IP)
- # form = CorporateForm(request.POST)
- # else:
- # form = CorporateForm(request.POST)
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- form = CorporateFormCaptcha(request.POST)
- else:
- form = CorporateForm(request.POST)
- error = ''
- success = ''
- order_id = -1
- if form.is_valid():
- name = form.cleaned_data['name']
- email = form.cleaned_data['email']
- # num = form.cleaned_data['num']
- # category = form.cleaned_data['category']
- phone = form.cleaned_data['phone']
- event = form.cleaned_data['event']
- message = form.cleaned_data['message']
- message_html = u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + u'</div><div>Категория билетов:' + event + u'</div><div>Email:' + email + u'</div><div>Сообщение: ' + message + u'</div>' # u'Корпоративная завявка с сайта condederationscup.net<div>Имя: ' + name + u'</div><div>Телефон: ' + phone + '</div><div>Email:' + email + u'</div><div>Матч:' + event + u'</div><div>Категория: ' + category + u', Количество: ' + num + u'</div><div>Сообщение: ' + message + '</div>'
- bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Сообщение: {message}'.format(
- message=message
- )
- recipient_list = ['info@worldcup2018.me']
- _hostname = context_data.get('host_name', None) or get_current_hostname(request)
- # try:
- # send_mail(
- # u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
- # html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
- # )
- # except (BadHeaderError, AttributeError): # Защита от уязвимости
- # error = 'Invalid header found'
- # Переходим на другую страницу, если сообщение отправлено
- success = 'Сообщение успешно отправлено!'
- client = Client(
- getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
- cache=NoCache(),
- timeout=15
- )
- website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
- source_id, _msg = request.seo.analytics_message()
- if request.user.is_authenticated():
- _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
- info = dict(
- info_ip=request.META['REMOTE_ADDR'],
- lang="0",
- site_name=website,
- pass_hash=md5(website).hexdigest(),
- is_operator='1' if request.user.is_authenticated() else '0',
- source=force_unicode(source_id)
- )
- # func = client.service.addOrderSourceI
- #
- # try:
- # order_id = func(
- # info_fio=name,
- # info_tel=phone,
- # info_email=email,
- # info_title=u'Корпоративная заявка',
- # info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
- # # info_tc=num,
- # info_cat=event,
- # info_notes=u'<br/>'.join([bin_message, _msg]),
- # **info
- # )
- # except Exception as erra:
- # pass
- url = 'http://185.154.52.97:8001/api/create-order-from-site/'
- new_bcontent = {
- "comment": u'Корпоративная завяка',
- "client_name": name,
- "client_phone": phone,
- # "client_phone_code": zone,
- # "client_address": addr,
- # "pay_type": paymethod,
- "site_name": request.get_host(),
- "client_comment": message
- }
- item = requests.post(url, headers={'content-type': 'application/json',
- 'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
- data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
- order_id = item.json().get('pk', -1)
- cart = context_data.get('mini_cart', Order.get_session(request=request))
- cart.phone = phone
- cart.email = email
- cart.fio = name
- cart.desc = bin_message.replace(u'<br>', u'\n')
- cart.website = website
- cart.bin_id = order_id
- cart.payment_processed = int(order_id) > 0
- cart.save()
- request.session.pop(django_settings.CART_SESSION_ID)
- else:
- error = 'В некоторых полях содержатся ошибки!'
- else:
- if cache.get('captcha') == None:
- try:
- if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
- cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
- else:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- except Exception:
- cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
- if cache.get('captcha') == True:
- if cache.get(ip) >= django_settings.BLACK_COUNT_TRYING_IP:
- form = CorporateFormCaptcha()
- else:
- form = CorporateForm()
- else:
- form = CorporateForm()
- context_data.update({
- 'stadiums': stadiums,
- 'groups': groups,
- 'champ': champ,
- 'form': form,
- 'cities': cities,
- 'order_id': order_id,
- 'matches_1_8': matches_1_8,
- 'matches_quarterfinals': matches_quarterfinals,
- 'matches_semifinals': matches_semifinals,
- 'match_for_3': match_for_3,
- 'final': final,
- 'match_by_groups': match_by_groups
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def get_fields(request):
- if request.is_ajax():
- q = request.GET.get('term', '')
- drugs = Match.objects.filter(
- Q(command_first__translations__name__icontains=q) | Q(command_second__translations__name__icontains=q),
- Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
- host__name='worldcup2018.me', hide_match=False).distinct()
- drugs2 = Team.objects.filter(translations__name__icontains=q, host__name='worldcup2018.me').distinct()
- drugs3 = City.objects.filter(translations__name__icontains=q, host__name='worldcup2018.me').distinct()
- drugs4 = Stadium.objects.filter(translations__name__icontains=q, host__name='worldcup2018.me').distinct()
- results = []
- if request.get_host().split('.')[0] == 'en':
- for drug in drugs:
- drug_json = {}
- drug_json['name'] = drug.command_first.name + ' - ' + drug.command_second.name + u' - Buy tickets'
- drug_json['alias'] = '/matches/' + drug.alias + '/'
- results.append(drug_json)
- for drug in drugs2:
- drug_json = {}
- drug_json['name'] = drug.name + u' - information about the national team'
- drug_json['alias'] = '/teams/' + drug.alias + '/'
- results.append(drug_json)
- for drug in drugs3:
- drug_json = {}
- drug_json['name'] = drug.name + u' - matches in the city'
- drug_json['alias'] = '/cities/' + drug.alias + '/'
- results.append(drug_json)
- for drug in drugs4:
- drug_json = {}
- drug_json['name'] = drug.name + u' - matches on the stadium'
- drug_json['alias'] = '/stadiums/' + drug.alias + '/'
- results.append(drug_json)
- else:
- for drug in drugs:
- drug_json = {}
- drug_json['name'] = drug.command_first.name + ' - ' + drug.command_second.name + u' - купить билеты'
- drug_json['alias'] = '/matches/' + drug.alias + '/'
- results.append(drug_json)
- for drug in drugs2:
- drug_json = {}
- drug_json['name'] = drug.name + u' - информация о сборной'
- drug_json['alias'] = '/teams/' + drug.alias + '/'
- results.append(drug_json)
- for drug in drugs3:
- drug_json = {}
- drug_json['name'] = drug.name + u' - выбрать матчи в данном городе'
- drug_json['alias'] = '/cities/' + drug.alias + '/'
- results.append(drug_json)
- for drug in drugs4:
- drug_json = {}
- drug_json['name'] = drug.name + u' - выбрать матчи на данном стадионе'
- drug_json['alias'] = '/stadiums/' + drug.alias + '/'
- results.append(drug_json)
- data = json.dumps(results[:7])
- else:
- data = 'fail'
- mimetype = 'application/json'
- return HttpResponse(data, mimetype)
- def ajax(request):
- cart = Order.get_session(request=request)
- if request.is_ajax():
- message = 'ajax:no-method'
- _id = ''
- if get_field_without_somechars(request.POST['type']) == 'del_item':
- try:
- object = ajaxcontroller.del_item(
- request.POST,
- )
- _id = object
- except KeyError:
- _id = "Error"
- pass
- elif get_field_without_somechars(request.POST['type']) == 'del_itemm':
- try:
- object = ajaxcontroller.del_itemm(
- request.POST,
- request
- )
- _id = object
- except KeyError:
- _id = "Error"
- pass
- elif request.POST['type'] == 'send_feedback':
- a = FeedBack(content=request.POST['txt'], site=request.get_host())
- a.save()
- _id = 'Good!'
- elif get_field_without_somechars(request.POST['type']) == 'mass_add':
- json_data = json.loads(request.POST['data'])
- for item in json_data['items']:
- price = get_object_or_404(Price, id=item['price'])
- item = OrderItem(price=price, order=cart, count=item['count'])
- item.save()
- _id = item.id
- elif get_field_without_somechars(request.POST['type']) == 'one_add':
- added_id = request.POST.get('data', 0)
- if OrderItem.objects.filter(order=cart, price__id=added_id).count() == 1:
- orderr = OrderItem.objects.get(order=cart, price__id=added_id)
- orderr.count += 1
- orderr.save()
- _id = orderr.count
- else:
- price = get_object_or_404(Price, id=added_id)
- item = OrderItem(price=price, order=cart, count=1)
- item.save()
- _id = item.id
- elif get_field_without_somechars(request.POST['type']) == 'parser_add':
- price = OrderItem(price=request.POST['price'], order=cart, count=1)
- elif get_field_without_somechars(request.POST['type']) == 'get_user_cart_items':
- items = []
- for i in cart.item.all():
- temp_price = 0
- if i.price.price.currency != "RUB": # сумма для заказа формируется ниже
- a = Currency.objects.get(code="RUB").rate # курс рубля
- b = Currency.objects.get(code=i.price.price.currency).rate
- temp_price = i.price.price.amount * b / a
- else:
- temp_price = i.price.price.amount
- items.append({"id": i.id, "price_id": i.price.id, "match": i.price.match.command_first.name + ' - ' + i.price.match.command_second.name + ', ' + i.price.sector, "price" : int(temp_price), "count" : i.count, "total" : int(temp_price * i.count)})
- _id = json.dumps(items, ensure_ascii=False)
- return HttpResponse(text_type(_id))
- else:
- message = "Hello"
- def fc(request):
- template = loader.get_template('fc/index.html')
- context_data = default_context(request, 'index', TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def updater(request):
- try:
- object_name = re.sub(r'[^\w\s]+|[\d]+|[_]{2}', r'', request.GET['type']).strip()
- except KeyError:
- return HttpResponse(u'Модель не определена!')
- sys.path.insert(0, os.path.join(django_settings.BASE_DIR, 'scripts'))
- import updater
- result = updater.init(object_name)
- return HttpResponse(result)
- @csrf_exempt
- def postupdater(request):
- try:
- object_name_m = re.sub(r'[^\w\s]+|[\d]+|[_]{2}', r'', request.POST['type']).strip()
- except KeyError:
- return HttpResponse(u'Модель не определена!')
- try:
- sys.path.insert(0, os.path.join(django_settings.BASE_DIR, 'scripts'))
- from umodels import init_rules
- except ImportError:
- return HttpResponse(u'Ошибка загрузки модуля "umodels"')
- result = u''
- object_name_arr = object_name_m.split(',')
- write_arr = force_unicode(request.POST.get('write', '')).split('@@')
- i = 0
- for object_name in object_name_arr:
- res = []
- if 'write' in request.POST:
- write = u''
- for wr in write_arr[i].split('::'):
- write += u'\n\t' + wr
- _path = os.path.join(django_settings.BASE_DIR, 'scripts') + '/pr/' + object_name + '.pr'
- data = open(_path, 'w')
- write_obj = u'{"%s": [%s\n]}' % (object_name, write)
- data.write(write_obj.encode('utf-8'))
- data.close()
- os.chmod(_path, 0777)
- clb = init_rules(object_name)
- if isclass(clb) and hasattr(clb, 'run'):
- instance = clb(language=get_language() or 'ru')
- res = instance.run()
- for inst, created in res:
- result += u'"{}:{}" - {}\n'.format(
- inst.__class__.__name__,
- force_unicode(inst),
- {True: u'создан', False: u'обновлен'}.get(created)
- )
- i += 1
- return HttpResponse(result)
- # не работает(
- def error_404(request):
- template = choose_template(request, "404")
- context_data = default_context(request, "error-404", TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- # Карта сайта
- class BaseSitemap(Sitemap):
- @cached_property
- def current_site(self):
- return Site.objects.get_current()
- class StadiumSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Stadium.objects.filter(~Q(alias=None), host=self.current_site).all()
- class GroupSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Group.objects.filter(~Q(alias=None), host=self.current_site).all()
- class FedSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Fed.objects.filter(~Q(alias=None), host=self.current_site).all()
- class ZayavkaSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Zayavka.objects.filter(~Q(alias=None), host=self.current_site).all()
- class ChampSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Champ.objects.filter(~Q(alias=None), host=self.current_site).all()
- class PlayerSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Player.objects.filter(~Q(team__alias=None), ~Q(alias=None), host=self.current_site).all()
- class MatchSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Match.objects.filter(~Q(alias=None), host=self.current_site).all()
- class TextPageSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return TextPage.objects.filter(~Q(alias=None), host=self.current_site).all()
- class TeamSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return Team.objects.filter(~Q(alias=None), host=self.current_site).all()
- class NewsSitemap(BaseSitemap):
- changefreq = "weekly"
- priority = 0.5
- def items(self):
- return News.objects.filter(~Q(alias=None), host=self.current_site).all()
- def robots(request):
- # return render_to_response('robots.txt', content_type="text/plain")
- template = loader.get_template('robots.txt')
- # robots = get_object_or_404(Robots , name=request.get_host())
- alias = get_current_alias(request) or Alias.objects.first()
- robots = Robots.objects.filter(host=alias).first()
- data = getattr(robots, 'content', '')
- context = RequestContext(request, {
- 'data': data,
- })
- return HttpResponse(template.render(context), content_type="text/plain")
- def yandex_mail(request):
- template = loader.get_template('f1dbcc5c8003.html')
- context = RequestContext(request, {})
- return HttpResponse(template.render(context))
- def yandex_verification(request, yandex_verification_number):
- template = loader.get_template('yandex_verification.html')
- context = RequestContext(request, {
- 'yandex_verification_number': yandex_verification_number,
- })
- return HttpResponse(template.render(context))
- def google_verification(request, google_verification_number):
- template = loader.get_template('google_verification.html')
- context = RequestContext(request, {
- 'google_verification_number': google_verification_number,
- })
- return HttpResponse(template.render(context))
- def mail_verification(request, mail_verification_number):
- template = loader.get_template('mail_verification.html')
- context = RequestContext(request, {
- 'mail_verification_number': mail_verification_number,
- })
- return HttpResponse(template.render(context))
- class Success(generic.DetailView):
- model = Order
- page = 'success'
- @property
- def template_name(self):
- tpl_path = '/'.join(
- filter(
- None,
- [{'mobile': 'mobile', 'full': ''}.get(get_flavour(self.request, '')), self.page]
- )
- )
- return '.'.join([tpl_path, 'html'])
- @property
- def token(self):
- return self.request.session.get(django_settings.CART_SESSION_ID)
- @token.deleter
- def token(self):
- self.request.session.pop(django_settings.CART_SESSION_ID)
- def get_object(self, queryset=None):
- if queryset is None:
- queryset = self.get_queryset()
- if self.token:
- queryset = queryset.filter(token=uuid.UUID(self.token)).first()
- del self.token
- return queryset
- def get_context_data(self, **kwargs):
- host_name = Site.objects.get_current()
- context = super(Success, self).get_context_data(**kwargs)
- context['menu'] = TextPage.objects.language(get_language()).order_by('menuposition').filter(
- ~Q(alias="index"), menushow=True, host=host_name
- )
- context['cur_site_url'] = host_name
- cur_site_url = self.request.get_host()
- try:
- if SiteSettings.objects.get(host__name=host_name):
- if SiteSettings.objects.get(host__name=host_name):
- curr_template = SiteTemplates.objects.get(settings=SiteSettings.objects.get(host__name=host_name),
- domain__domain=cur_site_url).template
- except Exception:
- curr_template = '1'
- pass
- context['curr_template'] = curr_template
- return context
- def render_to_response(self, context, **resp_kw):
- if isinstance(context.get('object'), QuerySet):
- return HttpResponseRedirect(reverse_lazy('portal:index'))
- send_sms(self.object.phone,
- gettext(u'Благодарим за заказ - #%(bin_id)s. Мы свяжемся с Вами в ближайшее время.') % dict(
- bin_id=self.object.bin_id
- ))
- return super(Success, self).render_to_response(context, **resp_kw)
- class FailPage(Success):
- page = 'fail'
- @x_robots_tag
- def sitemap(request, sitemaps, section=None,
- template_name='sitemap.xml', content_type='application/xml'):
- req_protocol = request.scheme
- req_site = RequestSite(request)
- if section is not None:
- if section not in sitemaps:
- raise Http404("No sitemap available for section: %r" % section)
- maps = [sitemaps[section]]
- else:
- maps = sitemaps.values()
- page = request.GET.get("p", 1)
- urls = []
- for site in maps:
- try:
- if callable(site):
- site = site()
- urls.extend(site.get_urls(page=page, site=req_site,
- protocol=req_protocol))
- except EmptyPage:
- raise Http404("Page %s empty" % page)
- except PageNotAnInteger:
- raise Http404("No page '%s'" % page)
- response = TemplateResponse(request, template_name, {'urlset': urls},
- content_type=content_type)
- if hasattr(site, 'latest_lastmod'):
- # if latest_lastmod is defined for site, set header so as
- # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
- lastmod = site.latest_lastmod
- response['Last-Modified'] = http_date(
- timegm(
- lastmod.utctimetuple() if isinstance(lastmod, datetime.datetime)
- else lastmod.timetuple()
- )
- )
- return response
- @user_passes_test(lambda u: u.is_superuser)
- def clear_cache(request):
- cache.clear()
- LogEntry.objects.create(object_repr="Clear cache", action_flag=True, user=request.user)
- return HttpResponseRedirect(reverse_lazy('admin:index'))
- '''
- class PaymentResultSber(generic.View):
- def get(self, request):
- data = {"orderId": request.GET['orderId']}
- r = requests.post(django_settings.ACQUIRING_URL_SBER_RESULT, json=json.dumps(data),
- headers={'Authorization': 'Token {}'.format(django_settings.ACQUIRING_TOKEN), })
- r_dict = json.loads(r.text)
- # order # bintranet_id, price
- # customer # email, phone,
- # tickets # price, count
- # host
- # Document Atol
- if r_dict['redirect'] == 'success_url':
- order = Order.objects.get(bin_id=r_dict["bintranet_id"])
- atol(
- bintranet_id=r_dict["bintranet_id"],
- total_price=order.sum,
- email=order.email,
- phone=order.phone,
- tickets=json.loads(order.tickets),
- host=django_settings.ATOL_SITE_HOST_IN_ACQUIRING
- )
- logger.info(json.loads(r.text))
- response = HttpResponseRedirect(
- reverse('portal:success')) # +"?bintranet_id={}".format(transaction.cart_order.bintranet_id))
- # response.delete_cookie('cart_tickets')
- # response.delete_cookie('total_price')
- # response.delete_cookie('total_amount')
- return response
- else:
- return HttpResponseRedirect('/')
- '''
- def review_page(request):
- template = choose_template(request, "review_page")
- context_data = default_context(request, "review_page", TextPage)
- reviews = Reviews.objects.filter(published=True).order_by('id').reverse()
- context_data.update({
- 'reviews': reviews,
- })
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
- def services_page(request):
- template = choose_template(request, "services_page")
- context_data = default_context(request, "services_page", TextPage)
- context = RequestContext(request, context_data)
- return HttpResponse(template.render(context))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement