Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 170.15 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # from __future__ import unicode_literals, print_function  # @TODO переместить все u'' -> '' и раскомментировать
  3. import datetime
  4. import pymorphy2
  5. import decimal
  6. import json
  7. import os
  8. import re
  9. import sys
  10. import urllib
  11. import urllib2
  12. import uuid
  13. import requests
  14. import random
  15. import logging
  16. from calendar import timegm
  17. from collections import OrderedDict
  18. from collections import defaultdict
  19. from hashlib import md5
  20. from inspect import isclass
  21.  
  22. from django.conf import settings as django_settings
  23. from django.contrib.sitemaps import Sitemap
  24. from django.contrib.sitemaps.views import x_robots_tag
  25. from django.contrib.sites.models import Site
  26. from django.contrib.sites.requests import RequestSite
  27. from django.core.mail import send_mail, BadHeaderError
  28. from django.core.paginator import EmptyPage
  29. from django.core.paginator import PageNotAnInteger
  30. from django.core.serializers.json import DjangoJSONEncoder
  31. from django.core.urlresolvers import reverse_lazy, reverse
  32. from django.core.exceptions import ObjectDoesNotExist
  33. from django.db.models import Q
  34. from django.db.models import QuerySet
  35. from django.http import HttpResponse, HttpResponsePermanentRedirect
  36. from django.http.response import Http404, HttpResponseRedirect
  37. from django.shortcuts import redirect
  38. from django.template import RequestContext, loader
  39. from django.template.loader import render_to_string
  40. from django.template.response import TemplateResponse
  41. from django.utils import timezone
  42. from django.utils.encoding import force_unicode
  43. from django.utils.http import http_date
  44. from django.utils.six import text_type
  45. from django.utils.translation import get_language, gettext
  46. from django.utils.functional import cached_property
  47. from django.views import generic
  48. from django.views.decorators.csrf import csrf_exempt
  49. from django.contrib.auth.decorators import login_required
  50. from django_mobile import get_flavour
  51. from multisite.models import Alias
  52. from suds.cache import NoCache
  53. from suds.client import Client
  54. from django.contrib.admin.models import LogEntry
  55. from django.core.cache import cache
  56. from django.http.request import split_domain_port
  57. from django.utils.six.moves.urllib.parse import urlparse
  58. import ajaxcontroller
  59. from .models import Scripts, Robots, TextPage, News, Team, Player, Match, Stadium, Champ, Group, Fed, Zayavka, \
  60.     Price, OrderItem, Order, PayMethod, City, Tags, FeedBack, Caps, Reviews, SiteSettings, SiteTemplates
  61. from .forms import ContactForm, ContactFormCapcha, CorporateForm, ReviewsForm, CorporateFormCaptcha
  62. from .utils import get_current_hostname, get_object_or_404, get_current_alias, get_client_ip, get_paymethod, get_exception
  63.  
  64. from acquiring_client.helpers import acquiring
  65. from currency.models import Currency
  66. from django.views.decorators.csrf import ensure_csrf_cookie
  67. from django.contrib.auth.decorators import user_passes_test
  68.  
  69. from portal.extras import get_vip
  70.  
  71. EMAIL_FROM = getattr(django_settings, 'DEFAULT_FROM_EMAIL', 'info@confederationscup.net')
  72. logger = logging.getLogger("portal.views")
  73.  
  74. #Поисковые Переходы
  75. UTM_SOURCE = 'utm_source'
  76. UTM_MEDIUM = 'utm_medium'
  77. UTM_CAMPAIGN = 'utm_campaign'
  78. UTM_TERM = 'utm_term'
  79. UTM_CONTENT = 'utm_content'
  80. REFERER = 'referer'
  81.  
  82. UTM_CHOICES = (
  83.     (UTM_SOURCE, u'%s | Источник' % UTM_SOURCE),
  84.     (UTM_MEDIUM, u'%s | Тип источника (cpc, баннер, рассылка)' % UTM_MEDIUM),
  85.     (UTM_CAMPAIGN, u'%s | Название рекламной кампании' % UTM_CAMPAIGN),
  86.     (UTM_TERM, u'%s | Kлючевое слово' % UTM_TERM),
  87.     (REFERER, u'%s | Переход с сайта' % REFERER)
  88. )
  89.  
  90. ANALITYCS_KEY = '_analitycs'
  91.  
  92. def get_alias_related(host_name, alias):
  93.     table = [
  94.         ["confcuptickets.ru", "kontakti", "contacts"],
  95.         ["confcuptickets.ru", "matchi", "matches"],
  96.         ["confcuptickets.ru", "comands", "teams"],
  97.     ]
  98.  
  99.     for item in table:
  100.         try:
  101.             # it = item.index(force_unicode(alias))
  102.             if item[0] == host_name.domain:
  103.                 alias = item[1]
  104.         except ValueError:
  105.             pass
  106.  
  107.     return alias
  108.  
  109.  
  110. def active_menu(req):
  111.     alias = req.path.strip('/').split('/')[0]
  112.     if alias == '':
  113.         alias = 'index'
  114.  
  115.     return alias
  116.  
  117.  
  118. def choose_template(request, page):
  119.     tpl_path = '/'.join(filter(None, [{'mobile': 'mobile', 'full': ''}.get(get_flavour(request, '')), page]))
  120.     return loader.get_template('.'.join([tpl_path, 'html']))
  121.  
  122.  
  123. def get_host_vs_url(host_name, url, alias):
  124.     alias = alias
  125.     url_first = url.split('/')[1]
  126.     if url_first != '':
  127.         textpages = TextPage.objects.filter(~Q(alias="index"), host=host_name)
  128.         # textpage = textpages.get_object_or_404(alias=url_first)
  129.         try:
  130.             textpage = textpages.get(alias=url_first)
  131.             alias = url_first.encode('utf8')
  132.         except TextPage.DoesNotExist:
  133.             if alias == 'error-404':
  134.                 pass
  135.             else:
  136.                 raise Http404
  137.  
  138.     return alias
  139.  
  140.  
  141. def default_context(request, alias, object):
  142.     host = active_menu(request)
  143.     host_name = get_current_hostname(request)
  144.     if object == TextPage:
  145.         alias = get_host_vs_url(host_name, request.get_full_path().split('?')[0], alias)
  146.  
  147.     menu = TextPage.objects.prefetch_related('translations').language(get_language()).order_by('menuposition').filter(
  148.         ~Q(alias="index"), menushow=True,
  149.         host=host_name)
  150.     scripts = Scripts.objects.filter(host=host_name)
  151.     # russia = Team.objects.get(name="Россия")
  152.     # ru_matches = Match.objects.filter(Q(command_first=russia) | Q(command_second=russia)).order_by('datetime')
  153.     # try:
  154.     # champ = Champ.objects.language(get_language()).filter(host=host_name)
  155.     #    champ = Champ.objects.translated(get_language()).prefetch_re.filter(host=host_name)
  156.     # except ObjectDoesNotExist:
  157.     #    raise Http404
  158.     champ = get_object_or_404(Champ, name="Кубок конфедераций 2017", host=host_name)
  159.  
  160.     champs = Champ.objects.filter(host=host_name).distinct().order_by('translations__name')
  161.     last_news = News.objects.prefetch_related('translations').language(get_language()).filter(host=host_name).order_by(
  162.         'date')[:4]
  163.     stadium = Stadium.objects.prefetch_related('translations').language(get_language()).filter(host=host_name,
  164.                                                                                                menushow=True)
  165.     last_matches = Match.objects.prefetch_related('translations').language(get_language()).filter(
  166.         champ=champ, host=host_name, techmatch=False, menushow=True
  167.     ).order_by('datetime')[:5]
  168.     all_matches = Match.objects.prefetch_related('translations').language(get_language()).filter(
  169.         Q(command_first__translations__name='Россия') | Q(command_second__translations__name='Россия'),
  170.         champ__translations__name='Групповой этап', host=host_name).distinct().order_by('datetime')
  171.     last_matches_two = Match.objects.prefetch_related('translations').language(get_language()).filter(
  172.         champ=champ, host=host_name, techmatch=False
  173.     ).order_by('datetime')[5:10]
  174.     # teams = Team.objects.filter(fed=Fed.objects.get(name="УЕФА"),techteam=False).order_by('name')
  175.     # champ_teams = []
  176.     # champ_teams.append(champ.teams.get(name="Россия"))
  177.     # champ_teams.append(champ.teams.get(name="Германия"))
  178.     # champ_teams.append(champ.teams.get(name="Мексика"))
  179.     # champ_teams.append(champ.teams.get(name="Чили"))
  180.     # champ_teams.append(champ.teams.get(name="Австралия"))
  181.     # champ_teams.append(champ.teams.get(name="Новая Зеландия"))
  182.     # try :
  183.     # champ_teams.append(champ.teams.get(name="Португалия"))
  184.     # except Team.DoesNotExist :
  185.     # pass
  186.     champ_teams = champ.teams.order_by('id')
  187.     teams = champ_teams
  188.     teams_group = []
  189.     cur_site_url = request.get_host()
  190.     groups = Group.objects.prefetch_related('translations').select_related().language(get_language()).filter(
  191.         champ=champ, translations__name__contains="Группа"
  192.     ).order_by('translations__name')
  193.     for group in groups:
  194.         matches = Match.objects.select_related().filter(group=group)
  195.         temp_teams = []
  196.         for match in matches:
  197.             temp_teams.append(match.command_first)
  198.         temp_teams = list(set(temp_teams))
  199.         teams_group.append([group, temp_teams])
  200.     try:
  201.         data = object.objects.get(alias=alias, host=host_name)
  202.     except object.DoesNotExist:
  203.         raise Http404
  204.  
  205.     try:
  206.         if SiteSettings.objects.get(caps=Alias.objects.get(domain=cur_site_url)):
  207.             cap_site = True
  208.     except Exception:
  209.         cap_site = False
  210.         pass
  211.  
  212.     try:
  213.         if SiteSettings.objects.get(host__name=host_name):
  214.             curr_template = SiteTemplates.objects.get(settings=SiteSettings.objects.get(host__name=host_name), domain__domain=cur_site_url).template
  215.     except Exception:
  216.         curr_template = '1'
  217.         pass
  218.  
  219.     try:
  220.         if SiteSettings.objects.get(hide_ticks=Alias.objects.get(domain=cur_site_url)):
  221.             hide_sell_tickets = True
  222.     except Exception:
  223.         hide_sell_tickets = False
  224.         pass
  225.  
  226.     # корзина
  227.     mini_cart = Order.set_session(request=request)
  228.  
  229.     context_object = {
  230.         'host': host,
  231.         'host_name': host_name,
  232.         'cur_site_url': cur_site_url,
  233.         'menu': menu,
  234.         'scripts': scripts,
  235.         # 'ru_matches' : ru_matches,
  236.         'last_news': last_news,
  237.         'all_matches': all_matches,
  238.         'last_matches': last_matches,
  239.         'last_matches_two': last_matches_two,
  240.         'teams': teams,
  241.         'groups': groups,
  242.         'stadium': stadium,
  243.         'teamsAB': teams_group,
  244.         'champ_teams': champ_teams,
  245.         'champ': champ,
  246.         'champs': champs,
  247.         'data': data,
  248.         'order': None,
  249.         'mini_cart': mini_cart,
  250.         'cap_site': cap_site,
  251.         'hide_sell_tickets': hide_sell_tickets,
  252.         'curr_template': curr_template,
  253.         'paymethods': min(map(
  254.             lambda i: i.price.paymethods.all(),
  255.             OrderItem.objects.filter(order=mini_cart).all()
  256.         ) or [PayMethod.objects.all()], key=lambda _is: len(_is))
  257.     }
  258.  
  259.     return context_object
  260.  
  261.  
  262. @ensure_csrf_cookie
  263. def index(request):
  264.     error = None
  265.     success = None
  266.     if 'fifa18.center' in request.get_host():
  267.         return sell_ticket(request)
  268.     if 'hospitality' in request.get_host():
  269.         return vip(request)
  270.     if request.is_ajax():
  271.         success = 'gotovo'  # ну не пишите так, пишите finished, например
  272.         if request.POST['type'] == 'callback':
  273.             name = request.POST['name']
  274.             phone = request.POST['phone']
  275.             text = request.POST['text']
  276.  
  277.             subject = 'Заказ обратного звонка от ' + name.encode('utf8')
  278.             message = name.encode('utf8') + u' заказал обратный звонок на телефон ' + phone.encode(
  279.                 'utf8') + u'<br> Сообщение: ' + text.encode('utf8')
  280.             recipients = ['vladyan.s@yandex.ru', 'vladyan121@gmail.com']  # это нужно выносить в насйтройки
  281.  
  282.             send_mail(
  283.                 subject, message, EMAIL_FROM, recipients, html_message=message,
  284.                 fail_silently=not getattr(django_settings, 'DEBUG', False)
  285.             )
  286.             return HttpResponse(success)
  287.         elif request.POST['type'] == 'get_teams':
  288.             items = []
  289.             for i in Match.objects.filter(group=Group.objects.get(id=request.POST['group_id'])).order_by('datetime'):
  290.                 items.append({'command_first': i.command_first.name, 'command_second': i.command_second.name,
  291.                               'date': i.datetime.strftime('%d-%m-%Y'), 'city': i.stadium.city.name})
  292.             return HttpResponse(json.dumps(items, ensure_ascii=False).encode('utf8'))
  293.         elif request.POST['type'] == 'send_review':
  294.             item = Reviews(name=request.POST['name'], email=request.POST['email'], message=request.POST['message'])
  295.             item.save()
  296.             return HttpResponse('Success')
  297.     else:
  298.         template = choose_template(request, "index")
  299.  
  300.         context_data = default_context(request, "index", TextPage)
  301.  
  302.         news = News.objects.filter(host=context_data['host_name']).order_by('date')[:5]
  303.         stadiums = Stadium.objects.filter(
  304.             Q(city__translations__country='Россия') | Q(city__translations__country='Russia'),
  305.             host=context_data['host_name']).order_by('id').distinct().prefetch_related('translations')
  306.         matches_main = Match.objects.filter(Q(score=None),
  307.             Q(command_first__translations__name='Россия') | Q(command_second__translations__name='Россия'),
  308.             Q(champ__translations__name='Групповой этап')|Q(champ__translations__name='Плей-офф'),
  309.             host=context_data['host_name'], menushow=True, hide_match=False).order_by(
  310.             'datetime').distinct().prefetch_related('translations')
  311.         matches_samara = Match.objects.filter(
  312.             stadium__translations__name='Самара Арена', host=context_data['host_name'], hide_match=False).order_by(
  313.             'datetime').distinct().prefetch_related('translations')
  314.         tovar_matches = Match.objects.filter(Q(score=None), champ__translations__name='Товарищеские матчи',
  315.                                              host=context_data['host_name'], hide_match=False).distinct().order_by(
  316.             'datetime').prefetch_related('translations')
  317.         popular_matches = Match.objects.filter(Q(score=None),
  318.             Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  319.             host=context_data['host_name'], menushow=True, popular=True, hide_match=False).distinct().order_by(
  320.             'datetime').prefetch_related('translations')
  321.         groups = Group.objects.filter(
  322.             Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  323.             host__name=context_data['host_name']).distinct().order_by('menuposition').prefetch_related('translations')
  324.         cities = City.objects.filter(Q(translations__country='Россия') | Q(translations__country='Russia'),
  325.                                      host=context_data['host_name']).distinct().order_by(
  326.             'menuposition').prefetch_related('translations')
  327.         matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
  328.                                            host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  329.         matches_quarterfinals = Match.objects.filter(Q(score=None), group__translations__name='1/4 Финала',
  330.                                                      host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  331.         matches_semifinals = Match.objects.filter(Q(score=None), group__translations__name='1/2 Финала',
  332.                                                   host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  333.         final = Match.objects.filter(Q(score=None), group__translations__name='Финал',
  334.                                      host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  335.         match_for_3 = Match.objects.filter(Q(score=None), group__translations__name='Матч за 3-е место',
  336.                                            host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  337.  
  338.         supacup = Match.objects.filter(champ__translations__name='Суперкубок УЕФА').distinct()
  339.  
  340.         order_id = ''
  341.  
  342.         reviews = Reviews.objects.filter(published=True).order_by('id').reverse()[:5]
  343.  
  344.         ip = get_client_ip(request)
  345.         import pdb
  346.         pdb.set_trace()
  347.  
  348.         if request.method == 'POST':
  349.             cip = cache.get(ip, None)
  350.  
  351.             if cache.get('captcha') == None:
  352.                 try:
  353.                     if SiteSettings.objects.get(
  354.                             host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  355.                         cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  356.                     else:
  357.                         cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  358.                 except Exception:
  359.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  360.  
  361.             if cache.get('captcha') == True:
  362.                 if request.POST.get(u'g-recaptcha-response'):
  363.                     form = CorporateFormCaptcha(request.POST)
  364.                     try:
  365.                         cache.incr(ip, 1) # у тебя ip не число а увеличиваешь ты на 1 не знаю как это работает
  366.                     except ValueError:
  367.                         cache.set(ip, 1, django_settings.BLACK_TIME_IP)
  368.                 elif cip >= django_settings.BLACK_COUNT_TRYING_IP:
  369.                     try:
  370.                         cache.incr(ip, 1)
  371.                     except ValueError:  # на случай если вдруг в это время ключ уже удалился
  372.                         cache.set(ip, cip + 1, django_settings.BLACK_TIME_IP)
  373.                     # if cip == django_settings.BLACK_COUNT_TRYING_IP:
  374.                     #    form = ContactForm(request.POST)
  375.                     # else:
  376.                     form = CorporateFormCaptcha(request.POST)
  377.                 else:
  378.                     cache.set(ip, 1, django_settings.BLACK_TIME_IP)
  379.                     form = CorporateForm(request.POST)
  380.             else:
  381.                 form = CorporateForm(request.POST)
  382.  
  383.             order_id = -1
  384.  
  385.             if form.is_valid():
  386.                 name = form.cleaned_data['name']
  387.                 email = form.cleaned_data['email']
  388.                 # num = form.cleaned_data['num']
  389.                 # category = form.cleaned_data['category']
  390.                 phone = form.cleaned_data['phone']
  391.                 event = form.cleaned_data['event']
  392.                 message = form.cleaned_data['message']
  393.  
  394.                 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>'
  395.                 bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Сообщение: {message}'.format(
  396.                     message=message
  397.                 )
  398.  
  399.                 recipient_list = ['info@worldcup2018.me']
  400.  
  401.                 _hostname = context_data.get('host_name', None) or get_current_hostname(request)
  402.                 # try:
  403.                 #     send_mail(
  404.                 #         u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
  405.                 #         html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
  406.                 #     )
  407.                 # except (BadHeaderError, AttributeError):  # Защита от уязвимости
  408.                 #     error = 'Invalid header found'
  409.                 # except Exception:
  410.                 #     pass
  411.                 # Переходим на другую страницу, если сообщение отправлено
  412.                 success = 'Сообщение успешно отправлено!'
  413.  
  414.                 client = Client(
  415.                     getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  416.                     cache=NoCache(),
  417.                     timeout=15
  418.                 )
  419.  
  420.                 website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  421.                 source_id, _msg = request.seo.analytics_message()
  422.                 if request.user.is_authenticated():
  423.                     _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  424.  
  425.                 info = dict(
  426.                     info_ip=request.META['REMOTE_ADDR'],
  427.                     lang="0",
  428.                     site_name=website,
  429.                     pass_hash=md5(website).hexdigest(),
  430.                     is_operator='1' if request.user.is_authenticated() else '0',
  431.                     source=force_unicode(source_id)
  432.                 )
  433.  
  434.                 # func = client.service.addOrderSourceI
  435.                 #
  436.                 # try:
  437.                 #     order_id = func(
  438.                 #         info_fio=name,
  439.                 #         info_tel=phone,
  440.                 #         info_email=email,
  441.                 #         info_title=u'Корпоративная заявка',
  442.                 #         info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  443.                 #         #                        info_tc=num,
  444.                 #         info_cat=event,
  445.                 #         info_notes=u'<br/>'.join([bin_message, _msg]),
  446.                 #         **info
  447.                 #     )
  448.                 # except Exception as erra:
  449.                 #     pass
  450.  
  451.                 url = 'http://185.154.52.97:8001/api/create-order-from-site/'
  452.  
  453.                 new_bcontent = {
  454.                     "comment": u'Корпоративная завяка',
  455.                     "client_name": name,
  456.                     "client_phone": phone,
  457.                     # "client_phone_code": zone,
  458.                     # "client_address": addr,
  459.                     # "pay_type": paymethod,
  460.                     "site_name": request.get_host(),
  461.                     "old_bintranet_id": order_id,
  462.                     "client_comment": message
  463.                 }
  464.  
  465.                 item = requests.post(url, headers={'content-type': 'application/json',
  466.                                             'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
  467.                               data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
  468.                 order_id = item.json().get('pk', -1)
  469.  
  470.                 cart = context_data.get('mini_cart', Order.get_session(request=request))
  471.                 cart.phone = phone
  472.                 cart.email = email
  473.                 cart.fio = name
  474.                 cart.desc = bin_message.replace(u'<br>', u'\n')
  475.                 cart.website = website
  476.                 cart.bin_id = order_id
  477.                 cart.payment_processed = int(order_id) > 0
  478.                 cart.save()
  479.                 request.session.pop(django_settings.CART_SESSION_ID)
  480.  
  481.             else:
  482.                 error = 'В некоторых полях содержатся ошибки!'
  483.  
  484.         if cache.get('captcha') == None:
  485.             try:
  486.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  487.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  488.                 else:
  489.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  490.             except Exception:
  491.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  492.  
  493.         if cache.get('captcha') == True:
  494.             if cache.get(ip) >= django_settings.BLACK_COUNT_TRYING_IP:
  495.                 form = CorporateFormCaptcha()
  496.             else:
  497.                 form = CorporateForm()
  498.         else:
  499.             form = CorporateForm()
  500.  
  501.         context_data.update({
  502.             'supacup' : supacup,
  503.             'news': news,
  504.             'popular_matches': popular_matches,
  505.             'tovar_matches': tovar_matches,
  506.             'matches_main': matches_main,
  507.             'matches_samara': matches_samara,
  508.             'matches_1_8': matches_1_8,
  509.             'matches_quarterfinals': matches_quarterfinals,
  510.             'matches_semifinals': matches_semifinals,
  511.             'match_for_3': match_for_3,
  512.             'final': final,
  513.             'stadiums': stadiums,
  514.             'groups': groups,
  515.             'champ': champ,
  516.             'form': form,
  517.             'cities': cities,
  518.             'order_id': order_id,
  519.             'reviews': reviews,
  520.             'success': success,
  521.         })
  522.  
  523.         context = RequestContext(request, context_data)
  524.  
  525.         return HttpResponse(template.render(context))
  526.  
  527.  
  528. def index2(request):
  529.     template = choose_template(request, "index2")
  530.  
  531.     context_data = default_context(request, 'confcup17', TextPage)
  532.  
  533.     context = RequestContext(request, context_data)
  534.  
  535.     news = News.objects.filter(host=context_data['host_name']).order_by('date')[:5]
  536.     stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id');
  537.     matches = Match.objects.filter(champ__translations__name='Кубок конфедераций 2017',
  538.                                    host=context_data['host_name']).order_by('datetime').distinct()
  539.     form = CorporateForm()
  540.     context_data.update({
  541.         'news': news,
  542.         'matches': matches,
  543.         'stadiums': stadiums,
  544.         'champ': champ,
  545.         'form': form,
  546.     })
  547.  
  548.     return HttpResponse(template.render(context))
  549.  
  550.  
  551. def kkmatches(request):
  552.     template = choose_template(request, "matches-kk")
  553.  
  554.     context_data = default_context(request, 'kkmatches', TextPage)
  555.  
  556.     context = RequestContext(request, context_data)
  557.  
  558.     stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id');
  559.     matches = Match.objects.filter(champ__translations__name='Кубок конфедераций 2017',
  560.                                    host=context_data['host_name']).order_by('datetime')
  561.     form = CorporateForm()
  562.     context_data.update({
  563.         'matches': matches,
  564.         'stadiums': stadiums,
  565.         'champ': champ,
  566.         'form': form,
  567.     })
  568.  
  569.     return HttpResponse(template.render(context))
  570.  
  571.  
  572. def kkfanid(request):
  573.     template = choose_template(request, "kkfanid")
  574.  
  575.     context_data = default_context(request, 'kkfanid', TextPage)
  576.  
  577.     context = RequestContext(request, context_data)
  578.  
  579.     context_data.update({
  580.  
  581.     })
  582.  
  583.     return HttpResponse(template.render(context))
  584.  
  585.  
  586. def regions_page(request):
  587.     return HttpResponsePermanentRedirect('/teams/')
  588.  
  589.  
  590. def textpage(request, textpage_alias):
  591.     template = choose_template(request, "textpage")
  592.  
  593.     context_data = default_context(request, textpage_alias, TextPage)
  594.  
  595.     try:
  596.         if City.objects.get(alias=textpage_alias, host=context_data['host_name']):
  597.             item = TextPage.objects.filter(Q(translations__name='Города') | Q(translations__name='Citys'),
  598.                                            host=context_data['host_name']).distinct().first().alias
  599.  
  600.             return HttpResponsePermanentRedirect('/' + item + '/' + textpage_alias + '/')
  601.     except:
  602.         item = 1
  603.  
  604.     context = RequestContext(request, context_data)
  605.  
  606.     return HttpResponse(template.render(context))
  607.  
  608.  
  609. def mobile(request):
  610.     template = choose_template(request, "mobile/index")
  611.  
  612.     context_data = default_context(request, "mobile", TextPage)
  613.     context = RequestContext(request, context_data)
  614.  
  615.     return HttpResponse(template.render(context))
  616.  
  617.  
  618. # убираем спецсимволы и числа из названия поля
  619. def get_field_without_somechars(field):
  620.     return re.sub(r'[\\:\(\)]+|[_]{2}', r'', field).strip()
  621.  
  622.  
  623. def buypage(request):
  624.     # корзина
  625.     cart = Order.get_session(request=request)
  626.     # для пересылки на домен payment для оплаты
  627.     host = None
  628.     try:
  629.         host = (lambda h: h if h.find(":") == -1 else h[:h.find(":")])(request.META['HTTP_HOST'])
  630.     except Exception as e:
  631.         pass
  632.  
  633.  
  634.     host_referer, message = '', []
  635.     _utm_source = request.seo.analytics.get(UTM_SOURCE) or ''
  636.     status, status_text = request.seo.utm_sources.get(_utm_source, (None, u'(СЕО)'))
  637.     is_mobile = getattr(request, 'flavour', 'full') == 'mobile'
  638.     request.seo_host = request.get_host()
  639.  
  640.     refferers = request.seo.analytics.get('referer', []) or filter(
  641.         lambda x: x and request.seo_host not in urlparse(x).netloc,
  642.         request.seo.analytics.get('history', [])
  643.     )
  644.     referer = request.seo.last(refferers)
  645.     ref_netloc = urlparse(referer).netloc
  646.     if ref_netloc:
  647.         host_referer, _ = split_domain_port(ref_netloc)
  648.  
  649.     device = u'Mobile' if is_mobile else 'Desktop'
  650.     transition = u'Переход из' if host_referer else u'Нет перехода, но ' + status_text
  651.     advert = request.seo.analytics.get(UTM_MEDIUM, '')
  652.     advertising_company = request.seo.analytics.get(UTM_CAMPAIGN, '')
  653.     transition_string = request.seo.analytics.get(UTM_TERM, '')
  654.  
  655.     cart.utm = [{'device': device, 'transition': transition, 'advert': advert, 'advertising_company': advertising_company, 'transition_string': transition_string}]
  656.     cart.save()
  657.  
  658.     # конец поисковых переходов
  659.     domain = request.get_host()
  660.     domain_2 = domain.replace('payment.', '')
  661.     # if domain_2 == 'welcome2018.com.ru':
  662.     # domain_name = 'payment.{}'.format(domain_2)
  663.     domain_name = django_settings.ACQUIRING_CLIENT_HOST #'payment.welcome2018.me'
  664.  
  665.     if django_settings.IS_PAYMENT_REDIRECT and domain.split('.')[0] != 'en' and domain != 'worldcupticket.ru' and host != getattr(django_settings, "ACQUIRING_DOMEN_TEST", ""):
  666.         if domain != domain_name:
  667.             token = request.session.get(django_settings.CART_SESSION_ID)
  668.             return redirect('https://' + domain_name + '/buypage/?token=' + token)
  669.         else:
  670.             token = request.GET.get('token', None)
  671.  
  672.             if token:
  673.                 request.session[django_settings.CART_SESSION_ID] = token
  674.  
  675.  
  676.     template = choose_template(request, "buypage")
  677.     context_data = default_context(request, 'purchacing', TextPage)
  678.     order_id = -1
  679.  
  680.     ip = get_client_ip(request)
  681.     if request.method == 'POST':
  682.         cip = cache.get(ip, None)
  683.  
  684.         if cache.get('captcha') == None:
  685.             try:
  686.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  687.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  688.                 else:
  689.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  690.             except Exception:
  691.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  692.  
  693.         if cache.get('captcha') == True:
  694.             form = ContactFormCapcha(request.POST)
  695.         else:
  696.             form = ContactForm(request.POST)
  697.  
  698.         error = None
  699.         success = None
  700.         token = request.session.get(django_settings.CART_SESSION_ID)
  701.         order = OrderItem.objects.filter(order__token=uuid.UUID(token)).all() or OrderItem.objects.none()
  702.         mail_from = u'Заказ с сайта '
  703.  
  704.         if form.is_valid():
  705.             _default = u'Не указан'
  706.             name = form.cleaned_data.get('name', _default)
  707.             email = form.cleaned_data.get('email', _default)
  708.             addr = form.cleaned_data.get('addr', _default)
  709.             phone_code = form.cleaned_data.get('code_phone', "")
  710.             zone = request.POST.get('zone', 'RU')
  711.             # try:
  712.             #     zone = request.POST['zone']
  713.             # except Exception:
  714.             #     zone = 'RU'
  715.             phone = phone_code + form.cleaned_data.get('phone', _default)
  716.             payment = form.cleaned_data['payment']
  717.             total = 0
  718.             prev = ''
  719.             len = 0
  720.             match_name = ''
  721.             datee = []
  722.             town = []
  723.             category = []
  724.             for item in order:
  725.                 len += int(item.count)
  726.                 category.append([item.price.sector.encode('utf8'), item.count])
  727.                 if prev != item.price.match.command_first.name + ' - ' + item.price.match.command_second.name:
  728.                     match_name += item.price.match.command_first.name.encode(
  729.                         'utf8') + ' - ' + item.price.match.command_second.name.encode('utf8') + '; '
  730.                     datee.append(item.price.match.datetime)
  731.                     town.append(item.price.match.stadium)
  732.  
  733.                 prev = item.price.match.command_first.name + ' - ' + item.price.match.command_second.name
  734.                 if item.price.price.currency != "RUB":  # сумма для заказа формируется ниже
  735.                     a = Currency.objects.get(code="RUB").rate  # курс рубля
  736.                     b = Currency.objects.get(code=item.price.price.currency).rate
  737.                     total += item.price.price.amount * item.count * b / a
  738.                 else:
  739.                     total += item.price.price.amount * item.count
  740.                 mail_from = u'Заказ билетов успешно оформлен'
  741.                 # 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))
  742.  
  743.             text_category = ', '.join(
  744.                 map(lambda (l, r): ' '.join(map(force_unicode, [l, '- %sшт.' % r])), category))
  745.             _message_data = map(
  746.                 force_unicode,
  747.                 [name, email, phone, match_name, text_category, total, payment, addr,
  748.                  form.cleaned_data.get('message', u"Без сообщения")]
  749.             )
  750.             message = u'<b>Имя отправителя:</b> {}' \
  751.                       u'<br><b>E-mail: </b>{}' \
  752.                       u'<br><b>Телефон:</b>{}' \
  753.                       u'<br><div>Название мероприятия:{}' \
  754.                       u'</div><div>Выбранные билеты:</div>{}' \
  755.                       u'<div>Общая сумма заказа: {}' \
  756.                       u'</div><div>Способ оплаты: {}' \
  757.                       u'</div><div>Адрес: {}' \
  758.                       u'</div><div>Сообщение: {}' \
  759.                       u'</div>'.format(*_message_data)
  760.             recipient_list = filter(None, [email])
  761.  
  762.             make_decimal = (lambda z: decimal.Decimal(z) if hasattr(
  763.                 z, 'isdigit'
  764.             ) or isinstance(
  765.                 z, (decimal.Decimal, int, float)
  766.             ) else decimal.Decimal(0))
  767.  
  768.             #paymethod = getattr(PayMethod.objects.filter(pk=payment).first(), 'bin_id', 1)
  769.             # paymethod = get_paymethod(payment)
  770.             paymethod = PayMethod.objects.filter(pk=payment).first()
  771.             temp_tickets = defaultdict(OrderedDict)
  772.             db_tickets = []
  773.  
  774.             def make_temp_tickets(order):
  775.                 t_tickets = []
  776.  
  777.                 for item in order:
  778.                     temp_price = 0
  779.                     if item.price.price.currency != "RUB":  # сумма для заказа формируется ниже
  780.                         a = Currency.objects.get(code="RUB").rate  # курс рубля
  781.                         b = Currency.objects.get(code=item.price.price.currency).rate
  782.                         temp_price = item.price.price.amount * b / a
  783.                     else:
  784.                         temp_price = item.price.price.amount
  785.  
  786.                     t_tickets.append(
  787.                         ('-'.join([item.price.match.command_first.name, item.price.match.command_second.name]),
  788.                          item.price.sector,
  789.                          make_decimal(temp_price),
  790.                          make_decimal(item.count),
  791.                          item.price.match.datetime,
  792.                          item.price.match.stadium.city.name,
  793.                          item.price.match.stadium.name))
  794.                 return t_tickets
  795.  
  796.             for _title, _sector, _price, _count, _datetime, _city, _stadium in make_temp_tickets(order):
  797.                 # for _title, _sector, _price, _count, _datetime, _city, _stadium in map(
  798.                 #        lambda t: ('-'.join([
  799.                 #            t.price.match.command_first.name,
  800.                 #            t.price.match.command_second.name
  801.                 #        ]), 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),
  802.                 #        order
  803.                 # ):
  804.                 if not all([_count, _datetime]):
  805.                     continue
  806.                 _id = force_unicode(u':'.join([_title, _sector]))
  807.                 temp_tickets[_id].setdefault('title', _title)
  808.                 temp_tickets[_id].setdefault('count', 0)
  809.                 temp_tickets[_id].setdefault('price', _price)
  810.                 temp_tickets[_id].setdefault('datetime', _datetime)
  811.                 temp_tickets[_id].setdefault('category', _sector)
  812.                 temp_tickets[_id].setdefault('city', _city)
  813.                 temp_tickets[_id].setdefault('stadium', _stadium)
  814.                 temp_tickets[_id]['count'] += _count
  815.                 db_tickets.append(dict(
  816.                     count=_count,
  817.                     src="",
  818.                     title=_title,
  819.                     price=_price,
  820.                     id="",
  821.                     cats=[_title, _sector, ''],
  822.                     offer_id=""
  823.                 ))
  824.  
  825.             # total = sum(map(lambda s: s.get('price') * s.get('count'), temp_tickets.values()))
  826.             url = 'http://185.154.52.97:8001/api/create-order-from-site/'
  827.  
  828.             def bintrasend(request, order):
  829.                 new_btickets = []
  830.                 additionals = 0
  831.                 for item in order:
  832.                     event_name = '{} - {}'.format(item.price.match.command_first.name.encode('utf8'),
  833.                                                   item.price.match.command_second.name.encode('utf8'))
  834.                     new_btickets.append({
  835.                         "event_name": event_name.decode('utf8'),
  836.                         "event_place_name": item.price.match.stadium.name + ', ' + item.price.match.stadium.city.name,
  837.                         "event_time_datetime": item.price.match.datetime.strftime("%Y-%m-%dT%H:%M"),
  838.                         "sector_name": item.price.sector,
  839.                         "sale": str(item.price.price.amount)[:-3],
  840.                         "count": item.count,
  841.                         "predict_purchase": str(item.price.zakup.amount)[:-3],
  842.                         "event_carryall_id": item.price.match.id,
  843.                         "info": u'Номер матча: {}'.format(item.price.match.count_number)
  844.                     })
  845.  
  846.                 if item.price.status == '1':
  847.                     additionals += 1
  848.                 try:
  849.                     from_site = Order.objects.get(token=request.session.get(django_settings.CART_SESSION_ID))
  850.                 except Exception:
  851.                     from_site = cart
  852.  
  853.                 new_bcontent = {
  854.                     "tickets": new_btickets,
  855.                     "client_name": name,
  856.                     "client_phone": phone,
  857.                     "client_phone_code": zone,
  858.                     "client_address": addr,
  859.                     "pay_type": paymethod.bin_id,
  860.                     "site_name": request.get_host(),
  861.                     "device": from_site.utm[0]['device'],
  862.                     "transition": from_site.utm[0]['transition'],
  863.                     "advert": from_site.utm[0]['advert'],
  864.                     "advertising_company": from_site.utm[0]['advertising_company'],
  865.                     "transition_string": from_site.utm[0]['transition_string'],
  866.                     "info": _msg,
  867.                 }
  868.                 if additionals:
  869.                     new_bcontent.update({'additional_status': 8, "comment": u'Проверить наличие билетов'})
  870.  
  871.                 if email:
  872.                     new_bcontent.update({
  873.                         'client_email': email
  874.                     })
  875.                 try:
  876.                     item = requests.post(url, headers={'content-type': 'application/json',
  877.                                                    'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
  878.                                      data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
  879.                     try:
  880.                         r_dict = item.json()
  881.                     except Exception:
  882.                         r_dict = {}
  883.                     logger.debug(str(r_dict))
  884.                     order_id = r_dict.get('pk', -1)
  885.                     if order_id < 0:
  886.                         category_text = ''
  887.                         for i in category:
  888.                             category_text += force_unicode(i[0]) + u'- кол-во билетов: ' + str(i[1]) + u'<br>'
  889.  
  890.                         subject = u'Заказ не дошедший в бинтранет от ' + u''
  891.                         messaga = u'Инфо о заказе:<br>Имя: {}<br>Телефон: {}<br>Матч: {}<br>Дата матча: {}<br>Город матча: {}<br>Выбранные билеты: {}<br>Сумма заказа: {}<br>Ссылка на заказ в админке: http://welcome2018.me/admin/portal/order/{}/'.format(
  892.                             name, phone, match_name, datee[0].strftime('%d.%m.%Y %H:%M'),
  893.                             force_unicode(town[0].city.name),
  894.                             category_text, str(int(total)), str(uuid.UUID(token)))
  895.                         recipients = ['info@welcome2018.me']  # это нужно выносить в насйтройки
  896.  
  897.                         send_mail(
  898.                             subject, messaga, EMAIL_FROM, recipients, html_message=messaga,
  899.                             fail_silently=not getattr(django_settings, 'DEBUG', False)
  900.                         )
  901.                     Order.objects.filter(token=uuid.UUID(token)).update(
  902.                         d=timezone.now(),
  903.                         phone=phone,
  904.                         adr=addr,
  905.                         email=email,
  906.                         fio=name,
  907.                         paymethod=paymethod.id,
  908.                         tickets=json.dumps(new_btickets, cls=DjangoJSONEncoder),
  909.                         bin_id=order_id,
  910.                         website=request.get_host()
  911.                     )
  912.                 except Exception as e:
  913.                     error = get_exception()
  914.                     logger.error("paymethod: {}".format(paymethod))
  915.                     logger.error(error)
  916.                     order_id = -1
  917.  
  918.                 return order_id
  919.  
  920.             if temp_tickets:
  921.                 client = Client(
  922.                     getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  923.                     cache=NoCache(),
  924.                     timeout=15
  925.                 )
  926.  
  927.                 website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  928.                 logger.info(website)
  929.  
  930.                 source_id, _msg = request.seo.analytics_message()
  931.                 _xtra_msg = form.cleaned_data.get('message', None)
  932.                 if request.user.is_authenticated():
  933.                     _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  934.                 if _xtra_msg:
  935.                     _msg = u'<strong>Доп.инфо:</strong> {}<br/>'.format(_xtra_msg) + _msg
  936.  
  937.                 info = dict(
  938.                     info_ip=request.META['REMOTE_ADDR'],
  939.                     method_pay=paymethod,
  940.                     method_delivery="1",
  941.                     lang="0",
  942.                     source=force_unicode(source_id),
  943.                     site_name=website,
  944.                     pass_hash=md5(website).hexdigest(),
  945.                     is_operator='1' if request.user.is_authenticated() else '0'
  946.                 )
  947.  
  948.                 _total = 0
  949.                 for enum, _info in enumerate(temp_tickets.values()):
  950.                     # if item.price.price.currency != "RUB":  # сумма для заказа формируется ниже
  951.                     #    a = Currency.objects.get(code="RUB").rate  # курс рубля
  952.                     #    b = Currency.objects.get(code=item.price.price.currency).rate
  953.                     #    _total += int(item.price.price) * int(item.count) * b / a
  954.                     # else:
  955.                     #    total += int(item.price.price) * int(item.count)
  956.                     _total += _info.get('count') * _info.get('price')
  957.                     payload = dict(
  958.                         info_fio=name,
  959.                         info_tel=phone,
  960.                         info_email=email,
  961.                         info_adr=addr,
  962.                         info_title=_info.get('title') + ' ' + _info.get('city') + ', ' + _info.get('stadium'),
  963.                         info_d=_info.get('datetime').strftime('%Y-%m-%d %H:%M:%S'),
  964.                         info_tc=_info.get('count'),
  965.                         info_sum=_info.get('count') * _info.get('price'),
  966.                         info_cat=_info.get('category'),
  967.                         info_notes=_msg,
  968.                         **info
  969.                     )
  970.                     # try:
  971.                     #     if enum > 0:
  972.                     #         payload.update(**dict(order_id=order_id))
  973.                     #         client.service.addOrderExtra(**payload)
  974.                     #     elif enum < 1:
  975.                     #         order_id = client.service.addOrderSourceI(**payload)
  976.                     #         Order.objects.filter(token=uuid.UUID(token)).update(
  977.                     #             d=_info.get('datetime'),
  978.                     #             phone=phone,
  979.                     #             adr=addr,
  980.                     #             email=email,
  981.                     #             fio=name,
  982.                     #             paymethod=payment,
  983.                     #             tickets=json.dumps(db_tickets, cls=DjangoJSONEncoder),
  984.                     #             bin_id=order_id,
  985.                     #             website=request.get_host()
  986.                     #         )
  987.                     #         # # Переходим на другую страницу, если сообщение отправлено
  988.                     #         # success = 'Сообщение успешно отправлено!'
  989.                     #
  990.                     # except Exception as erra:
  991.                     #     if getattr(django_settings, 'DEBUG', False):
  992.                     #         print erra  # @TODO logger
  993.                     #         # logger.error(e)
  994.                     #     continue
  995.                 order_id = bintrasend(request, order)
  996.                 Order.objects.filter(token=uuid.UUID(token)).update(sum=_total)
  997.  
  998.                 if recipient_list:
  999.                     _tpl = render_to_string('_email_tpl.html', {
  1000.                         'name': name,
  1001.                         'email': email,
  1002.                         'phone': phone,
  1003.                         'order_id': order_id,
  1004.                         'total': _total,
  1005.                         'match_name': match_name,
  1006.                         'text_category': text_category,
  1007.                         'datee': datee,
  1008.                         'town': town,
  1009.                     })
  1010.  
  1011.                     # send_mail(
  1012.                     #    mail_from, message, EMAIL_FROM, recipient_list,
  1013.                     #    html_message=_tpl, fail_silently=not getattr(django_settings, 'DEBUG', False)
  1014.                     # )
  1015.  
  1016.                     if request.get_host().split('.')[0] == 'en':
  1017.                         cont = {
  1018.                             "api_key": "67qxhb31twhaaynhzep59sj78xzp9t8i8u8gszho",
  1019.                             "username": "info@welcome2018.me",
  1020.                             "message": {
  1021.                                 "template_engine": "velocity",
  1022.                                 "template_id": "bf32faf0-5916-11e8-aaf2-f2fba6545268",
  1023.                                 "subject": "Successful order on en.welcome2018.me",
  1024.                                 "from_email": "info@welcome2018.me",
  1025.                                 "from_name": "WorldCup 2018",
  1026.                                 "recipients": [
  1027.                                     {
  1028.                                         "email": email,
  1029.                                         "substitutions": {
  1030.                                             "info": {
  1031.                                                 "order_id": order_id,
  1032.                                                 "name": name,
  1033.                                                 "phone": phone,
  1034.                                                 "summ": str(_total),
  1035.                                                 "match_name": match_name,
  1036.                                                 "datetime": datee[0].strftime('%Y-%m-%d %H:%M'),
  1037.                                                 "city": town[0].name + ', ' + town[0].city.name,
  1038.                                                 "category": text_category,
  1039.                                                 "email": email
  1040.                                             }
  1041.                                         }
  1042.                                     }
  1043.                                 ],
  1044.                                 "attachments": [
  1045.                                     {
  1046.                                         "type": "text/pdf",
  1047.                                         "name": "test.pdf",
  1048.                                         "content": ""
  1049.                                     }
  1050.                                 ]
  1051.                             }
  1052.                         }
  1053.                         #requests.post('https://one.unisender.com/ru/transactional/api/v1/email/send.json',
  1054.                         #              json.dumps(cont))
  1055.                     else:
  1056.                         cont = {
  1057.                             "api_key": "67qxhb31twhaaynhzep59sj78xzp9t8i8u8gszho",
  1058.                             "username": "info@welcome2018.me",
  1059.                             "message": {
  1060.                                 "template_engine": "velocity",
  1061.                                 "template_id": "07128d68-5863-11e8-97fe-762f11e05f46",
  1062.                                 "subject": "Успешный заказ на сайте welcome2018.me",
  1063.                                 "from_email": "info@welcome2018.me",
  1064.                                 "from_name": "Чемпионат Мира 2018",
  1065.                                 "recipients": [
  1066.                                     {
  1067.                                         "email": email,
  1068.                                         "substitutions": {
  1069.                                             "info": {
  1070.                                                 "order_id": order_id,
  1071.                                                 "name": name,
  1072.                                                 "phone": phone,
  1073.                                                 "summ": str(_total),
  1074.                                                 "match_name": match_name,
  1075.                                                 "datetime": datee[0].strftime('%Y-%m-%d %H:%M'),
  1076.                                                 "city": town[0].name + ', ' + town[0].city.name,
  1077.                                                 "category": text_category,
  1078.                                                 "email": email
  1079.                                             }
  1080.                                         }
  1081.                                     }
  1082.                                 ]
  1083.                             }
  1084.                         }
  1085.                         #requests.post('https://one.unisender.com/ru/transactional/api/v1/email/send.json',
  1086.                         #              json.dumps(cont))
  1087.                 success = True
  1088.  
  1089.                 # ----------------------- Acquiring -------------------------------------------------------------
  1090.                 atol_tickets = []
  1091.                 for t in db_tickets:
  1092.                     atol_tickets.append({"count": int(t["count"]), "price": int(t["price"])})
  1093.  
  1094.                 # td = getattr(django_settings, "ACQUIRING_DOMEN_TEST", "")
  1095.                 # tp = getattr(django_settings, "ACQUIRING_DOMEN_PORT", "")
  1096.                 # test_host = "{}:{}".format(td, td) if td and tp else td
  1097.                 temp_order_id = str(uuid.uuid4()).replace("-", "")[
  1098.                                 :16]  # Длина заказа в сбере 32 символа, берем 16 так как поставляется в bintranet_id
  1099.  
  1100.                 try:
  1101.                     if order_id < 0 and host == getattr(django_settings, "ACQUIRING_DOMEN_TEST", ""):
  1102.                         order_id = temp_order_id
  1103.                 except:
  1104.                     pass
  1105.  
  1106.                 if int(payment) == 1 and int(_total) > 0 and order_id:
  1107.                     if host == getattr(django_settings, "ACQUIRING_DOMEN_TEST", "") or request.get_host()[:2] == "en":
  1108.                         host_acquiring = host  # прямая оплата
  1109.                     else:
  1110.                         host_acquiring = django_settings.ACQUIRING_CLIENT_HOST
  1111.                     response = acquiring(
  1112.                         request=request,
  1113.                         bintranet_id=order_id,
  1114.                         total_cost=int(_total),
  1115.                         host=host_acquiring,
  1116.                         customer_name=name,
  1117.                         phone=phone,
  1118.                         email=email,
  1119.                         ip=get_client_ip(request),  # 'geoip2.readthedocs.io'
  1120.                         test_host="",
  1121.                         tickets=atol_tickets,
  1122.                         # sources=resp_json['sources'],
  1123.                     )
  1124.                     if response == -1:
  1125.                         logger.info("Acquiring some error or don't have acquiring or payments rules w/o paying")
  1126.                         return redirect(reverse_lazy('payments:process'))
  1127.                     else:
  1128.                         return response  # redirect on payment
  1129.                 else:
  1130.                     return redirect(reverse_lazy('payments:process'))
  1131.  
  1132.                     # ----------------------- / Acquiring -------------------------------------------------------------
  1133.  
  1134.         else:
  1135.             error = True
  1136.  
  1137.             if cache.get('captcha') == None:
  1138.                 try:
  1139.                     if SiteSettings.objects.get(
  1140.                             host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  1141.                         cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  1142.                     else:
  1143.                         cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  1144.                 except Exception:
  1145.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  1146.  
  1147.             if cache.get('captcha') == True:
  1148.                 form = ContactFormCapcha()
  1149.             else:
  1150.                 form = ContactForm()
  1151.  
  1152.         logger.debug(str(context_data))
  1153.         context_data.update({
  1154.             'error': error,
  1155.             'success': success,
  1156.             'form': form,
  1157.             'order': order,
  1158.             'order_id': order_id,
  1159.             'cart': Order.set_session(request=request)
  1160.         })
  1161.  
  1162.     else:
  1163.         form = None
  1164.  
  1165.         if cache.get('captcha') == None:
  1166.             try:
  1167.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  1168.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  1169.                 else:
  1170.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  1171.             except Exception:
  1172.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  1173.  
  1174.         if cache.get('captcha') == True:
  1175.             form = ContactFormCapcha()
  1176.         else:
  1177.             form = ContactForm()
  1178.  
  1179.         logger.debug(str(context_data))
  1180.         context_data.update({
  1181.             'cart': Order.set_session(request=request),
  1182.             'form': form
  1183.         })
  1184.     context = RequestContext(request, context_data)
  1185.     response = HttpResponse(template.render(context))
  1186.     return response
  1187.  
  1188. def sell_ticket_final(request):
  1189.     if request.is_ajax():
  1190.         # для пересылки на домен payment для оплаты
  1191.         host = None
  1192.         try:
  1193.             host = (lambda h: h if h.find(":") == -1 else h[:h.find(":")])(request.META['HTTP_HOST'])
  1194.         except Exception as e:
  1195.             pass
  1196.  
  1197.         # Поисковые Переходы
  1198.  
  1199.         UTM_SOURCE = 'utm_source'
  1200.         UTM_MEDIUM = 'utm_medium'
  1201.         UTM_CAMPAIGN = 'utm_campaign'
  1202.         UTM_TERM = 'utm_term'
  1203.         UTM_CONTENT = 'utm_content'
  1204.         REFERER = 'referer'
  1205.  
  1206.         UTM_CHOICES = (
  1207.             (UTM_SOURCE, u'%s | Источник' % UTM_SOURCE),
  1208.             (UTM_MEDIUM, u'%s | Тип источника (cpc, баннер, рассылка)' % UTM_MEDIUM),
  1209.             (UTM_CAMPAIGN, u'%s | Название рекламной кампании' % UTM_CAMPAIGN),
  1210.             (UTM_TERM, u'%s | Kлючевое слово' % UTM_TERM),
  1211.             (REFERER, u'%s | Переход с сайта' % REFERER)
  1212.         )
  1213.  
  1214.         ANALITYCS_KEY = '_analitycs'
  1215.  
  1216.         host_referer, message = '', []
  1217.         _utm_source = request.seo.analytics.get(UTM_SOURCE) or ''
  1218.         status, status_text = request.seo.utm_sources.get(_utm_source, (None, u'(СЕО)'))
  1219.         is_mobile = getattr(request, 'flavour', 'full') == 'mobile'
  1220.         request.seo_host = request.get_host()
  1221.  
  1222.         refferers = request.seo.analytics.get('referer', []) or filter(
  1223.             lambda x: x and request.seo_host not in urlparse(x).netloc,
  1224.             request.seo.analytics.get('history', [])
  1225.         )
  1226.         referer = request.seo.last(refferers)
  1227.         ref_netloc = urlparse(referer).netloc
  1228.         if ref_netloc:
  1229.             host_referer, _ = split_domain_port(ref_netloc)
  1230.  
  1231.         device = u'Mobile' if is_mobile else 'Desktop'
  1232.         transition = u'Переход из' if host_referer else u'Нет перехода, но ' + status_text
  1233.         advert = request.seo.analytics.get(UTM_MEDIUM, '')
  1234.         advertising_company = request.seo.analytics.get(UTM_CAMPAIGN, '')
  1235.         transition_string = request.seo.analytics.get(UTM_TERM, '')
  1236.  
  1237.         # конец поисковых переходов
  1238.         data = json.loads(request.read())
  1239.  
  1240.         if data['type'] == 'get_middle_price':
  1241.             item = Price.objects.filter(match__id=data['price_match'], translations__sector=data['cat']).first()
  1242.             return HttpResponse(int(item.price))
  1243.         if data['type'] == 'send_tickets':
  1244.  
  1245.             _default = u''
  1246.             name = data['data']['name']
  1247.             city = data['data']['city']
  1248.             phone = data['data']['phone']
  1249.             message = u'Продажа билета:  {}, {}, Цена продажи: {}, Кол-во: {}, Билеты на руках: {}, Сектор: {}, ряд: {}, место: {}'.format(
  1250.                 data['data']['match'], data['data']['category'], data['data']['rec'], data['data']['count'],
  1251.                 data['data']['payment'], data['data']['sector'], data['data']['row'], data['data']['seat'])
  1252.  
  1253.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  1254.  
  1255.             items = {
  1256.                 "info_fio": name,
  1257.                 "info_tel": phone,
  1258.                 "info_adr": city,
  1259.                 "info_title": u'Продажа билета',  # название шоу
  1260.                 "info_d": unicode(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
  1261.                 "info_tc": 1,
  1262.                 "info_sum": int(data['data']['rec']) * int(data['data']['count']),
  1263.                 "info_cat": data['data']['category'],
  1264.                 "info_notes": message,
  1265.                 "info_ip": unicode(request.META['REMOTE_ADDR']),
  1266.                 "method_pay": int(1),
  1267.                 "method_delivery": int(0),
  1268.                 "lang": int(0),
  1269.                 "site_name": website,
  1270.                 "pass_hash": unicode(md5(website).hexdigest()),
  1271.             }
  1272.             print 'ready to sent... \n items: ', items
  1273.  
  1274.             # try:
  1275.             #     client = client = Client(
  1276.             #         getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  1277.             #         cache=NoCache(),
  1278.             #         timeout=15
  1279.             #     )
  1280.             #     order_id = client.service.addOrder(**items)
  1281.             # except Exception as e:
  1282.             #     with open('Vlad_errors__________.log', 'a') as log:
  1283.             #         log.write(str(e))
  1284.  
  1285.             url = 'http://185.154.52.97:8001/api/create-order-from-site/'
  1286.  
  1287.             def bintrasend2():
  1288.                 # new_btickets = []
  1289.                 # for item in order:
  1290.                 #     event_name = '{} - {}'.format(item.price.match.command_first.name.encode('utf8'),
  1291.                 #                                   item.price.match.command_second.name.encode('utf8'))
  1292.                 #     new_btickets.append({
  1293.                 #         "event_name": event_name.decode('utf8'),
  1294.                 #         "event_place_name": item.price.match.stadium.name,
  1295.                 #         "event_time_datetime": item.price.match.datetime.strftime("%Y-%m-%dT%H:%M"),
  1296.                 #         "sector_name": item.price.sector,
  1297.                 #         "sale": str(item.price.price.amount)[:-3],
  1298.                 #         "predict_purchase": str(item.price.zakup.amount)[:-3]
  1299.                 #     })
  1300.  
  1301.                 new_bcontent = {
  1302.                     "tickets": [],
  1303.                     "client_name": data['data']['name'],
  1304.                     "client_address": city,
  1305.                     "client_phone": data['data']['phone'],
  1306.                     "pay_type": 1,
  1307.                     "site_name": request.get_host(),
  1308.                     "comment": message,
  1309.                     "status": 12,
  1310.                     "device": device,
  1311.                     "transition": transition,
  1312.                     "advert": advert,
  1313.                     "advertising_company": advertising_company,
  1314.                     "transition_string": transition_string,
  1315.                 }
  1316.                 try:
  1317.                     item = requests.post(url, headers={'content-type': 'application/json',
  1318.                                                        'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
  1319.                                          data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
  1320.                     order_id = item.json().get('pk', -1)
  1321.                 except Exception as err:
  1322.                     pass
  1323.                 return order_id
  1324.  
  1325.             send_order = bintrasend2()
  1326.             return HttpResponse(send_order)
  1327.  
  1328. def sell_ticket(request):
  1329.     if request.is_ajax():
  1330.         # для пересылки на домен payment для оплаты
  1331.         host = None
  1332.         try:
  1333.             host = (lambda h: h if h.find(":") == -1 else h[:h.find(":")])(request.META['HTTP_HOST'])
  1334.         except Exception as e:
  1335.             pass
  1336.  
  1337.         # Поисковые Переходы
  1338.  
  1339.         UTM_SOURCE = 'utm_source'
  1340.         UTM_MEDIUM = 'utm_medium'
  1341.         UTM_CAMPAIGN = 'utm_campaign'
  1342.         UTM_TERM = 'utm_term'
  1343.         UTM_CONTENT = 'utm_content'
  1344.         REFERER = 'referer'
  1345.  
  1346.         UTM_CHOICES = (
  1347.             (UTM_SOURCE, u'%s | Источник' % UTM_SOURCE),
  1348.             (UTM_MEDIUM, u'%s | Тип источника (cpc, баннер, рассылка)' % UTM_MEDIUM),
  1349.             (UTM_CAMPAIGN, u'%s | Название рекламной кампании' % UTM_CAMPAIGN),
  1350.             (UTM_TERM, u'%s | Kлючевое слово' % UTM_TERM),
  1351.             (REFERER, u'%s | Переход с сайта' % REFERER)
  1352.         )
  1353.  
  1354.         ANALITYCS_KEY = '_analitycs'
  1355.  
  1356.         host_referer, message = '', []
  1357.         _utm_source = request.seo.analytics.get(UTM_SOURCE) or ''
  1358.         status, status_text = request.seo.utm_sources.get(_utm_source, (None, u'(СЕО)'))
  1359.         is_mobile = getattr(request, 'flavour', 'full') == 'mobile'
  1360.         request.seo_host = request.get_host()
  1361.  
  1362.         refferers = request.seo.analytics.get('referer', []) or filter(
  1363.             lambda x: x and request.seo_host not in urlparse(x).netloc,
  1364.             request.seo.analytics.get('history', [])
  1365.         )
  1366.         referer = request.seo.last(refferers)
  1367.         ref_netloc = urlparse(referer).netloc
  1368.         if ref_netloc:
  1369.             host_referer, _ = split_domain_port(ref_netloc)
  1370.  
  1371.         device = u'Mobile' if is_mobile else 'Desktop'
  1372.         transition = u'Переход из' if host_referer else u'Нет перехода, но ' + status_text
  1373.         advert = request.seo.analytics.get(UTM_MEDIUM, '')
  1374.         advertising_company = request.seo.analytics.get(UTM_CAMPAIGN, '')
  1375.         transition_string = request.seo.analytics.get(UTM_TERM, '')
  1376.  
  1377.         # конец поисковых переходов
  1378.         data = json.loads(request.read())
  1379.            
  1380.         if data['type'] == 'get_middle_price':
  1381.             item = Price.objects.filter(match__id=data['price_match'], translations__sector=data['cat']).first()
  1382.             return HttpResponse(int(item.price))
  1383.         else:
  1384.             return HttpResponse('-1')
  1385.  
  1386.     template = choose_template(request, "sell_ticket")
  1387.  
  1388.     context_data = default_context(request, 'prodat-bilet', TextPage)
  1389.  
  1390.     if request.method == 'POST':
  1391.         form = ContactForm(request.POST)
  1392.         error = ''
  1393.         success = ''
  1394.  
  1395.         if form.is_valid():
  1396.             _default = u''
  1397.             name = form.cleaned_data.get('name', _default)
  1398.             email = form.cleaned_data.get('email', _default)
  1399.             phone = form.cleaned_data.get('phone', _default)
  1400.             message = form.cleaned_data.get('message', _default)
  1401.  
  1402.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  1403.  
  1404.             items = {
  1405.                 "info_fio": name,
  1406.                 "info_tel": phone,
  1407.                 "info_email": email,
  1408.                 "info_adr": '',
  1409.                 "info_title": u'Продажа билета',  # название шоу
  1410.                 "info_d": unicode(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
  1411.                 "info_tc": 1,
  1412.                 "info_sum": int(0),
  1413.                 "info_cat": u'',
  1414.                 "info_notes": message,
  1415.                 "info_ip": unicode(request.META['REMOTE_ADDR']),
  1416.                 "method_pay": int(1),
  1417.                 "method_delivery": int(0),
  1418.                 "lang": int(0),
  1419.                 "site_name": website,
  1420.                 "pass_hash": unicode(md5(website).hexdigest()),
  1421.             }
  1422.             print 'ready to sent... \n items: ', items
  1423.  
  1424.             client = client = Client(
  1425.                 getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  1426.                 cache=NoCache(),
  1427.                 timeout=15
  1428.             )
  1429.             order_id = client.service.addOrder(**items)
  1430.  
  1431.             # order_id = 212
  1432.             success = 'Ваши данные успешно отправлены! Номер заказа #{}'.format(order_id)
  1433.  
  1434.         else:
  1435.             error = 'В некоторых полях содержатся ошибки!'
  1436.  
  1437.         form = ContactForm()
  1438.         context_data.update({
  1439.             'error': error,
  1440.             'success': success,
  1441.             'form': form,
  1442.             'order_id': order_id
  1443.         })
  1444.  
  1445.     else:
  1446.         form = ContactForm()
  1447.         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(
  1448.             group=Group.objects.filter(Q(translations__name='Товарищеские матчи'), host__name='worldcup2018.me').first())).distinct().order_by('group__menuposition',
  1449.                                                                                        'datetime')
  1450.  
  1451.         context_data.update({
  1452.             'cart': context_data['mini_cart'],
  1453.             'match_by_groups': match_by_groups,
  1454.             'form': form
  1455.         })
  1456.     context = RequestContext(request, context_data)
  1457.     return HttpResponse(template.render(context))
  1458.  
  1459.  
  1460. def send_sms(number, msg):
  1461.     params = {
  1462.         'login': 'bolshoi-tickets',
  1463.         'password': '0b1ZKx1DMjjarrJk',
  1464.         'to': number,
  1465.         'txt': msg.encode('utf-8'),
  1466.         'source': 'FIFA2018'
  1467.     }
  1468.     url = 'http://xn--80aa3adxha4f.xn----ptbkgfnb1a.xn--p1ai/lcabApi/sendSms.php?'
  1469.     req = urllib2.Request(
  1470.         url + urllib.urlencode(params),
  1471.         headers={
  1472.             'User-Agent': 'Mozilla/5.0',
  1473.             'Accept-Charset': 'utf-8'
  1474.         })
  1475.     try:
  1476.         page = urllib2.urlopen(req).read()
  1477.         # print page
  1478.         # logger.info(page)
  1479.     except Exception as e:
  1480.         pass
  1481.         # print e
  1482.         # logger.info('не удалось отослать sms')
  1483.         # logger.info(e)
  1484.  
  1485.  
  1486. def packages(request):
  1487.     template = choose_template(request, "packages")
  1488.  
  1489.     context_data = default_context(request, 'packages', TextPage)
  1490.  
  1491.     context = RequestContext(request, context_data)
  1492.  
  1493.     return HttpResponse(template.render(context))
  1494.  
  1495.  
  1496. def contacts(request):
  1497.     template = choose_template(request, "contacts")
  1498.  
  1499.     context_data = default_context(request, 'contacts', TextPage)
  1500.  
  1501.     context = RequestContext(request, context_data)
  1502.  
  1503.     return HttpResponse(template.render(context))
  1504.  
  1505.  
  1506. def news(request):
  1507.     template = choose_template(request, "news")
  1508.  
  1509.     context_data = default_context(request, "news", TextPage)
  1510.  
  1511.     if request.GET.get('tag'):
  1512.         tag = Tags.objects.get(eng_name=request.GET['tag'])
  1513.         news = News.objects.filter(host=context_data['host_name'], tags__in=[tag], menushow=True).order_by('-date')
  1514.         tags = Tags.objects.all()
  1515.         context_data.update({
  1516.             'news': news,
  1517.             'tags': tags,
  1518.             'tag': tag,
  1519.         })
  1520.     else:
  1521.         news = News.objects.filter(host=context_data['host_name'], menushow=True).order_by('-date')
  1522.         tags = Tags.objects.all()
  1523.         context_data.update({
  1524.             'news': news,
  1525.             'tags': tags,
  1526.         })
  1527.  
  1528.     context = RequestContext(request, context_data)
  1529.  
  1530.     return HttpResponse(template.render(context))
  1531.  
  1532.  
  1533. def news_item(request, news_alias):
  1534.     template = choose_template(request, "news_item")
  1535.  
  1536.     context_data = default_context(request, news_alias, News)
  1537.     try:
  1538.         _next = context_data['data'].get_next_by_date()
  1539.     except News.DoesNotExist:
  1540.         _next = None
  1541.     try:
  1542.         prev = context_data['data'].get_previous_by_date()
  1543.     except News.DoesNotExist:
  1544.         prev = None
  1545.  
  1546.     context_data.update({
  1547.         'next': _next,
  1548.         'prev': prev,
  1549.     })
  1550.  
  1551.     context = RequestContext(request, context_data)
  1552.  
  1553.     return HttpResponse(template.render(context))
  1554.  
  1555.  
  1556. def stadiums(request):
  1557.     template = choose_template(request, "stadiums")
  1558.  
  1559.     context_data = default_context(request, "stadiums", TextPage)
  1560.     stadiums = Stadium.objects.filter(Q(city__translations__country="Россия") | Q(city__translations__country="Russia"),
  1561.                                       host=context_data['host_name'], menushow=True).distinct().order_by('menuposition')
  1562.  
  1563.     context_data.update({
  1564.         'stadiums': stadiums,
  1565.     })
  1566.  
  1567.     context = RequestContext(request, context_data)
  1568.  
  1569.     return HttpResponse(template.render(context))
  1570.  
  1571.  
  1572. def champs(request):
  1573.     template = choose_template(request, "champs")
  1574.  
  1575.     context_data = default_context(request, "champs", TextPage)
  1576.     champs = Champ.objects.filter(~Q(translations__name='Товарищеские матчи'), ~Q(translations__name='Плей-офф'),
  1577.                                   host__name=context_data['host_name'])
  1578.  
  1579.     context_data.update({
  1580.         'champs': champs,
  1581.     })
  1582.  
  1583.     context = RequestContext(request, context_data)
  1584.  
  1585.     return HttpResponse(template.render(context))
  1586.  
  1587.  
  1588. @csrf_exempt
  1589. def paypage(request):
  1590.     template = choose_template(request, "paypage")
  1591.  
  1592.     context_data = default_context(request, "paypage", TextPage)
  1593.  
  1594.     if request.method == 'POST':
  1595.         if request.POST['method'] == 'qiwi':
  1596.             method = request.POST['method']
  1597.             sum = request.POST['sum']
  1598.             tovar = request.POST['tovar']
  1599.             qiwi_phone = request.POST['qiwi_phone']
  1600.             context_data.update({
  1601.                 'qiwi_phone': qiwi_phone,
  1602.                 'method': method,
  1603.                 'sum': sum,
  1604.                 'tovar': tovar,
  1605.             })
  1606.         else:
  1607.             method = request.POST['method']
  1608.             sum = request.POST['sum']
  1609.             tovar = request.POST['tovar']
  1610.             ya_type = request.POST['ya_type']
  1611.             successs = request.POST['successURL']
  1612.             koshel = request.POST['koshel']
  1613.             context_data.update({
  1614.                 'ya_type': ya_type,
  1615.                 'successs': successs,
  1616.                 'method': method,
  1617.                 'sum': sum,
  1618.                 'tovar': tovar,
  1619.                 'koshel': koshel,
  1620.             })
  1621.  
  1622.     context = RequestContext(request, context_data)
  1623.  
  1624.     return HttpResponse(template.render(context))
  1625.  
  1626.  
  1627. def town(request, alias):
  1628.     template = choose_template(request, "town")
  1629.  
  1630.     context_data = default_context(request, alias, City)
  1631.     get_object_or_404(TextPage, alias='towns', host=context_data['host_name'])
  1632.     matches = Match.objects.filter(
  1633.         Q(champ__translations__name='Плей-офф') | Q(champ__translations__name='Групповой этап'), stadium__city=city,
  1634.         host=context_data['host_name']).distinct().order_by('datetime')
  1635.     stadiums = Stadium.objects.filter(city=context_data['data'], host=context_data['host_name'])
  1636.  
  1637.     morph = pymorphy2.MorphAnalyzer()
  1638.  
  1639.     try:
  1640.         gent = morph.parse(City.objects.get(alias=alias, host=context_data['host_name']).name)[0].inflect({'datv'}).word
  1641.     except:
  1642.         gent = City.objects.get(alias=alias, host=context_data['host_name']).name
  1643.  
  1644.     context_data.update({
  1645.         'matches': matches,
  1646.         'stadiums': stadiums,
  1647.         'gent': gent,
  1648.     })
  1649.  
  1650.     context = RequestContext(request, context_data)
  1651.  
  1652.     return HttpResponse(template.render(context))
  1653.  
  1654.  
  1655. def cities(request):
  1656.     template = choose_template(request, "towns")
  1657.  
  1658.     context_data = default_context(request, 'cities', TextPage)
  1659.     get_object_or_404(TextPage, alias='cities', host=context_data['host_name'])
  1660.  
  1661.     goroda = City.objects.filter(translations__country='Россия', host=context_data['host_name']).distinct().order_by(
  1662.         'menuposition')
  1663.  
  1664.     context_data.update({
  1665.         'goroda': goroda,
  1666.     })
  1667.  
  1668.     context = RequestContext(request, context_data)
  1669.  
  1670.     return HttpResponse(template.render(context))
  1671.  
  1672.  
  1673. def goroda(request):
  1674.     template = choose_template(request, "towns")
  1675.  
  1676.     context_data = default_context(request, 'goroda', TextPage)
  1677.     get_object_or_404(TextPage, alias='goroda', host=context_data['host_name'])
  1678.  
  1679.     goroda = City.objects.filter(host=context_data['host_name']).distinct().order_by('menuposition')
  1680.  
  1681.     context_data.update({
  1682.         'goroda': goroda,
  1683.     })
  1684.  
  1685.     context = RequestContext(request, context_data)
  1686.  
  1687.     return HttpResponse(template.render(context))
  1688.  
  1689.  
  1690. def towns(request):
  1691.     template = choose_template(request, "towns")
  1692.  
  1693.     context_data = default_context(request, 'towns', TextPage)
  1694.     get_object_or_404(TextPage, alias='towns', host=context_data['host_name'])
  1695.  
  1696.     goroda = City.objects.filter(translations__country='Россия', host=context_data['host_name']).distinct().order_by(
  1697.         'menuposition')
  1698.  
  1699.     context_data.update({
  1700.         'goroda': goroda,
  1701.     })
  1702.  
  1703.     context = RequestContext(request, context_data)
  1704.  
  1705.     return HttpResponse(template.render(context))
  1706.  
  1707.  
  1708. def city(request, alias):
  1709.     template = choose_template(request, "town")
  1710.  
  1711.     context_data = default_context(request, alias, City)
  1712.     get_object_or_404(TextPage, alias='cities', host=context_data['host_name'])
  1713.     matches = Match.objects.filter(Q(score=None),
  1714.         Q(champ__translations__name='Плей-офф') | Q(champ__translations__name='Групповой этап'),
  1715.         stadium__city=context_data['data'], host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  1716.     stadiums = Stadium.objects.filter(city=context_data['data'], host=context_data['host_name'])
  1717.  
  1718.     morph = pymorphy2.MorphAnalyzer()
  1719.     try:
  1720.         gent = morph.parse(City.objects.get(alias=alias, host=context_data['host_name']).name)[0].inflect({'datv'}).word
  1721.     except:
  1722.         gent = City.objects.get(alias=alias, host=context_data['host_name']).name
  1723.  
  1724.     context_data.update({
  1725.         'stadiums': stadiums,
  1726.         'matches': matches,
  1727.         'gent': gent,
  1728.     })
  1729.  
  1730.     context = RequestContext(request, context_data)
  1731.  
  1732.     return HttpResponse(template.render(context))
  1733.  
  1734.  
  1735. def gorod(request, alias):
  1736.     template = choose_template(request, "town")
  1737.     context_data = default_context(request, alias, City)
  1738.     get_object_or_404(TextPage, alias='goroda', host=context_data['host_name'])
  1739.     matches = Match.objects.filter(Q(score=None), (Q(champ__translations__name='Плей-офф') | Q(champ__translations__name='Групповой этап')),
  1740.         stadium__city__translations__name=context_data['data'].name,
  1741.         host=context_data['host_name']).distinct().order_by('datetime')
  1742.     stadiums = Stadium.objects.filter(city__translations__name=context_data['data'].name,
  1743.                                       host=context_data['host_name']).distinct()
  1744.     morph = pymorphy2.MorphAnalyzer()
  1745.     try:
  1746.         gent = morph.parse(City.objects.get(alias=alias, host=context_data['host_name']).name)[0].inflect({'datv'}).word
  1747.     except:
  1748.         gent = City.objects.get(alias=alias, host=context_data['host_name']).name
  1749.  
  1750.     context_data.update({
  1751.         'stadiums': stadiums,
  1752.         'matches': matches,
  1753.         'gent': gent,
  1754.     })
  1755.  
  1756.     context = RequestContext(request, context_data)
  1757.  
  1758.     return HttpResponse(template.render(context))
  1759.  
  1760.  
  1761. def teams(request):
  1762.     template = choose_template(request, "teams")
  1763.  
  1764.     context_data = default_context(request, "teams", TextPage)
  1765.  
  1766.     champs = Champ.objects.filter(host__name='fifa18.ru').distinct().order_by('translations__name').distinct()
  1767.     main_persons = Champ.objects.filter(host__name='fifa18.ru',
  1768.                                         translations__name='Плей-офф').distinct().first().teams.all().order_by('fed')
  1769.  
  1770.     context_data.update({
  1771.         'champs': champs,
  1772.         'main_persons': main_persons,
  1773.     })
  1774.  
  1775.     context = RequestContext(request, context_data)
  1776.  
  1777.     return HttpResponse(template.render(context))
  1778.  
  1779.  
  1780. def teams_regions(request, champ_alias):
  1781.     template = choose_template(request, "teams_regions")
  1782.  
  1783.     context_data = default_context(request, champ_alias, TextPage)
  1784.  
  1785.     champ = Champ.objects.get(alias=champ_alias, host__name='fifa18.ru')
  1786.  
  1787.     context_data.update({
  1788.         'champ': champ,
  1789.     })
  1790.  
  1791.     context = RequestContext(request, context_data)
  1792.  
  1793.     return HttpResponse(template.render(context))
  1794.  
  1795.  
  1796. @ensure_csrf_cookie
  1797. def matches(request):
  1798.     template = choose_template(request, "matches")
  1799.  
  1800.     context_data = default_context(request, "matches", TextPage)
  1801.  
  1802.     order_id = -1
  1803.     success = ''
  1804.     error = ''
  1805.  
  1806.     ip = get_client_ip(request)
  1807.  
  1808.     if request.method == 'POST':
  1809.         cip = cache.get(ip, None)
  1810.  
  1811.         if cache.get('captcha') == None:
  1812.             try:
  1813.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  1814.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  1815.                 else:
  1816.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  1817.             except Exception:
  1818.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  1819.  
  1820.         if cache.get('captcha') == True:
  1821.             if request.POST.get(u'g-recaptcha-response'):
  1822.                 form = CorporateFormCaptcha(request.POST)
  1823.                 try:
  1824.                     cache.incr(ip, 1)
  1825.                 except ValueError:
  1826.                     cache.set(ip, 1, django_settings.BLACK_TIME_IP)
  1827.             elif cip >= django_settings.BLACK_COUNT_TRYING_IP:
  1828.                 try:
  1829.                     cache.incr(ip, 1)
  1830.                 except ValueError:  # на случай если вдруг в это время ключ уже удалился
  1831.                     cache.set(ip, cip + 1, django_settings.BLACK_TIME_IP)
  1832.                 # if cip == django_settings.BLACK_COUNT_TRYING_IP:
  1833.                 #    form = ContactForm(request.POST)
  1834.                 # else:
  1835.                 form = CorporateFormCaptcha(request.POST)
  1836.             else:
  1837.                 cache.set(ip, 1, django_settings.BLACK_TIME_IP)
  1838.                 form = CorporateForm(request.POST)
  1839.         else:
  1840.             form = CorporateForm(request.POST)
  1841.  
  1842.         if form.is_valid():
  1843.             name = form.cleaned_data['name']
  1844.             email = form.cleaned_data['email']
  1845.             # num = form.cleaned_data['num']
  1846.             # category = form.cleaned_data['category']
  1847.             phone = form.cleaned_data['phone']
  1848.             event = form.cleaned_data['event']
  1849.             message = form.cleaned_data['message']
  1850.  
  1851.             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>'
  1852.             bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Сообщение: {message}'.format(
  1853.                 message=message
  1854.             )
  1855.  
  1856.             recipient_list = ['info@worldcup2018.me']
  1857.  
  1858.             _hostname = context_data.get('host_name', None) or get_current_hostname(request)
  1859.             try:
  1860.                 send_mail(
  1861.                     u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
  1862.                     html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
  1863.                 )
  1864.             except (BadHeaderError, AttributeError):  # Защита от уязвимости
  1865.                 error = 'Invalid header found'
  1866.             # Переходим на другую страницу, если сообщение отправлено
  1867.             success = 'Сообщение успешно отправлено!'
  1868.  
  1869.             client = Client(
  1870.                 getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  1871.                 cache=NoCache(),
  1872.                 timeout=15
  1873.             )
  1874.  
  1875.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  1876.             source_id, _msg = request.seo.analytics_message()
  1877.             if request.user.is_authenticated():
  1878.                 _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  1879.  
  1880.             info = dict(
  1881.                 info_ip=request.META['REMOTE_ADDR'],
  1882.                 lang="0",
  1883.                 site_name=website,
  1884.                 pass_hash=md5(website).hexdigest(),
  1885.                 is_operator='1' if request.user.is_authenticated() else '0',
  1886.                 source=force_unicode(source_id)
  1887.             )
  1888.  
  1889.             func = client.service.addOrderSourceI
  1890.  
  1891.             try:
  1892.                 order_id = func(
  1893.                     info_fio=name,
  1894.                     info_tel=phone,
  1895.                     info_email=email,
  1896.                     info_title=u'Корпоративная заявка',
  1897.                     info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  1898.                     #                    info_tc=num,
  1899.                     info_cat=event,
  1900.                     info_notes=u'<br/>'.join([bin_message, _msg]),
  1901.                     **info
  1902.                 )
  1903.             except Exception as erra:
  1904.                 if getattr(django_settings, 'DEBUG', False):
  1905.                     print erra  # @TODO logger
  1906.             order_id = order_id
  1907.  
  1908.             url = 'http://185.154.52.97:8001/api/create-order-from-site/'
  1909.  
  1910.             new_bcontent = {
  1911.                 "comment": u'Корпоративная завяка',
  1912.                 "client_name": name,
  1913.                 "client_phone": phone,
  1914.                 # "client_phone_code": zone,
  1915.                 # "client_address": addr,
  1916.                 # "pay_type": paymethod,
  1917.                 "site_name": request.get_host(),
  1918.                 "old_bintranet_id": order_id,
  1919.                 "client_comment": message
  1920.             }
  1921.  
  1922.             requests.post(url, headers={'content-type': 'application/json',
  1923.                                         'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
  1924.                           data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
  1925.  
  1926.             cart = Order.set_session(request)
  1927.             cart.phone = phone
  1928.             cart.email = email
  1929.             cart.fio = name
  1930.             cart.desc = bin_message.replace(u'<br>', u'\n')
  1931.             cart.website = website
  1932.             cart.bin_id = order_id
  1933.             cart.payment_processed = int(order_id) > 0
  1934.             cart.save()
  1935.             request.session.pop(django_settings.CART_SESSION_ID)
  1936.  
  1937.         else:
  1938.             error = 'В некоторых полях содержатся ошибки!'
  1939.  
  1940.         form = CorporateForm()
  1941.         matches = Match.objects.filter(
  1942.             champ=Champ.objects.filter(translations__name="Групповой этап", host__name='fifa18.ru').first(),
  1943.             menushow=True, host__name='fifa18.ru', hide_match=False).order_by('datetime').distinct()
  1944.         match_by_groups = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
  1945.                                                champ=Champ.objects.filter(translations__name="Групповой этап",
  1946.                                                                           host=context_data[
  1947.                                                                               'host_name']).first()).distinct().order_by(
  1948.             'group__menuposition', 'datetime')
  1949.         champ_teamss = Champ.objects.filter(translations__name="Групповой этап",
  1950.                                             host=context_data['host_name']).first().teams.all()
  1951.         # Group.objects.filter(champ__translations__name="Групповой этап", host=context_data['host_name']).order_by('alias').distinct()
  1952.         matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
  1953.                                            host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  1954.         matches_quarterfinals = Match.objects.filter(Q(score=None),group__translations__name='1/4 Финала',
  1955.                                                      host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  1956.         matches_semifinals = Match.objects.filter(Q(score=None),group__translations__name='1/2 Финала',
  1957.                                                   host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  1958.         final = Match.objects.filter(Q(score=None),group__translations__name='Финал',
  1959.                                      host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  1960.         match_for_3 = Match.objects.filter(Q(score=None),group__translations__name='Матч за 3-е место',
  1961.                                            host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  1962.         # stadiums = Stadium.objects.filter(host=context_data['host_name'])
  1963.         cities = City.objects.filter(Q(translations__country='Россия'), host=context_data['host_name']).distinct()
  1964.         groups = Group.objects.filter(
  1965.             Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  1966.             host__name=context_data['host_name']).distinct().order_by('menuposition')
  1967.         match_by_dates = Match.objects.filter(Q(score=None), host=context_data['host_name'],
  1968.                                               champ=Champ.objects.filter(translations__name="Групповой этап",
  1969.                                                                          host=context_data[
  1970.                                                                              'host_name'], hide_match=False).first()).distinct().order_by(
  1971.             'datetime')
  1972.         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')
  1973.  
  1974.         context_data.update({
  1975.             'error': error,
  1976.             'success': success,
  1977.             'form': form,
  1978.             'cities': cities,
  1979.             'matches': matches,
  1980.             'matches_1_8': matches_1_8,
  1981.             'matches_quarterfinals': matches_quarterfinals,
  1982.             'matches_semifinals': matches_semifinals,
  1983.             'match_for_3': match_for_3,
  1984.             'final': final,
  1985.             'match_by_groups': match_by_groups,
  1986.             'groups': groups,
  1987.             'order_id': order_id,
  1988.             'match_by_dates': match_by_dates,
  1989.             'match_played': match_played
  1990.         })
  1991.     else:
  1992.         matches = Match.objects.filter(
  1993.             champ=Champ.objects.filter(translations__name="Групповой этап", host__name='fifa18.ru').first(),
  1994.             menushow=True, host__name='fifa18.ru', hide_match=False).order_by('datetime').distinct()
  1995.         match_by_groups = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
  1996.                                                champ=Champ.objects.filter(translations__name="Групповой этап",
  1997.                                                                           host=context_data[
  1998.                                                                               'host_name']).first()).distinct().order_by(
  1999.             'group__menuposition', 'datetime')
  2000.         champ_teamss = Champ.objects.filter(translations__name="Групповой этап",
  2001.                                             host=context_data['host_name']).first().teams.all()
  2002.         # Group.objects.filter(champ__translations__name="Групповой этап", host=context_data['host_name']).order_by('alias').distinct()
  2003.         matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
  2004.                                            host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2005.         matches_quarterfinals = Match.objects.filter(Q(score=None), group__translations__name='1/4 Финала',
  2006.                                                      host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2007.         matches_semifinals = Match.objects.filter(Q(score=None), group__translations__name='1/2 Финала',
  2008.                                                   host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2009.         final = Match.objects.filter(Q(score=None), group__translations__name='Финал',
  2010.                                      host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2011.         match_for_3 = Match.objects.filter(Q(score=None), group__translations__name='Матч за 3-е место',
  2012.                                            host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2013.         # stadiums = Stadium.objects.filter(host=context_data['host_name'])
  2014.         cities = City.objects.filter(Q(translations__country='Россия'), host=context_data['host_name']).distinct()
  2015.         groups = Group.objects.filter(
  2016.             Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  2017.             host__name=context_data['host_name']).distinct().order_by('menuposition')
  2018.         match_by_dates = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
  2019.                                               champ=Champ.objects.filter(translations__name="Групповой этап",
  2020.                                                                          host=context_data[
  2021.                                                                              'host_name']).first()).distinct().order_by(
  2022.             'datetime')
  2023.         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')
  2024.  
  2025.         if cache.get('captcha') == None:
  2026.             try:
  2027.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  2028.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  2029.                 else:
  2030.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  2031.             except Exception:
  2032.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  2033.  
  2034.         if cache.get('captcha') == True:
  2035.             if cache.get(ip) >= django_settings.BLACK_COUNT_TRYING_IP:
  2036.                 form = CorporateFormCaptcha()
  2037.             else:
  2038.                 form = CorporateForm()
  2039.         else:
  2040.             form = CorporateForm()
  2041.  
  2042.         context_data.update({
  2043.             'form': form,
  2044.             'cities': cities,
  2045.             'matches': matches,
  2046.             'matches_1_8': matches_1_8,
  2047.             'matches_quarterfinals': matches_quarterfinals,
  2048.             'matches_semifinals': matches_semifinals,
  2049.             'match_for_3': match_for_3,
  2050.             'final': final,
  2051.             'match_by_groups': match_by_groups,
  2052.             # 'stadiums': stadiums,
  2053.             'champ_teamss': champ_teamss,
  2054.             'groups': groups,
  2055.             'success': success,
  2056.             'match_by_dates': match_by_dates,
  2057.             'order_id': order_id,
  2058.             'match_played': match_played
  2059.         })
  2060.  
  2061.     context = RequestContext(request, context_data)
  2062.  
  2063.     return HttpResponse(template.render(context))
  2064.  
  2065.  
  2066. def matchi(request):
  2067.     template = choose_template(request, "matches")
  2068.  
  2069.     context_data = default_context(request, "matchi", TextPage)
  2070.  
  2071.     if request.method == 'POST':
  2072.         form = CorporateForm(request.POST)
  2073.         error = ''
  2074.         success = ''
  2075.         suces = -1
  2076.  
  2077.         if form.is_valid():
  2078.             name = form.cleaned_data['name']
  2079.             email = form.cleaned_data['email']
  2080.             num = form.cleaned_data['num']
  2081.             category = form.cleaned_data['category']
  2082.             phone = form.cleaned_data['phone']
  2083.             event = form.cleaned_data['event']
  2084.             message = form.cleaned_data['message']
  2085.             #            _message_data = map(
  2086.             #                force_unicode,
  2087.             #                [name, email, phone, match_name, category, type, num, form.cleaned_data.get(
  2088.             #                    'message', u"Без сообщения"
  2089.             #                )]
  2090.  
  2091.             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>'
  2092.             bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Матч: {event}<br> Категория: {category}<br> Сообщение: {message}'.format(
  2093.                 event=event, category=category, message=message
  2094.             )
  2095.  
  2096.             recipient_list = ['vladyan.s@yandex.ru']
  2097.  
  2098.             _hostname = context_data.get('host_name', None) or get_current_hostname(request)
  2099.             try:
  2100.                 send_mail(
  2101.                     u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
  2102.                     html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
  2103.                 )
  2104.             except BadHeaderError:  # Защита от уязвимости
  2105.                 error = 'Invalid header found'
  2106.             # Переходим на другую страницу, если сообщение отправлено
  2107.             success = 'Сообщение успешно отправлено!'
  2108.  
  2109.             client = Client(
  2110.                 getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  2111.                 cache=NoCache(),
  2112.                 timeout=15
  2113.             )
  2114.  
  2115.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  2116.             source_id, _msg = request.seo.analytics_message()
  2117.             if request.user.is_authenticated():
  2118.                 _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  2119.  
  2120.             info = dict(
  2121.                 info_ip=request.META['REMOTE_ADDR'],
  2122.                 lang="0",
  2123.                 site_name=website,
  2124.                 pass_hash=md5(website).hexdigest(),
  2125.                 is_operator='1' if request.user.is_authenticated() else '0',
  2126.                 source=force_unicode(source_id)
  2127.             )
  2128.  
  2129.             func = client.service.addOrderSourceI
  2130.  
  2131.             try:
  2132.                 order_id = func(
  2133.                     info_fio=name,
  2134.                     info_tel=phone,
  2135.                     info_email=email,
  2136.                     info_title=u'Корпоративная заявка',
  2137.                     info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  2138.                     info_tc=num,
  2139.                     info_cat=category,
  2140.                     info_notes=u'<br/>'.join([bin_message, _msg]),
  2141.                     **info
  2142.                 )
  2143.             except Exception as erra:
  2144.                 if getattr(django_settings, 'DEBUG', False):
  2145.                     print erra  # @TODO logger
  2146.             suces = order_id
  2147.  
  2148.             cart = Order.set_session(request)
  2149.             cart.phone = phone
  2150.             cart.email = email
  2151.             cart.fio = name
  2152.             cart.desc = bin_message.replace(u'<br>', u'\n')
  2153.             cart.website = website
  2154.             cart.bin_id = order_id
  2155.             cart.payment_processed = int(order_id) > 0
  2156.             cart.save()
  2157.             request.session.pop(django_settings.CART_SESSION_ID)
  2158.  
  2159.         else:
  2160.             error = 'В некоторых полях содержатся ошибки!'
  2161.  
  2162.         form = CorporateForm()
  2163.         context_data.update({
  2164.             'error': error,
  2165.             'success': success,
  2166.             'form': form,
  2167.             'suces': suces,
  2168.         })
  2169.     else:
  2170.         matches = Match.objects.filter(Q(score=None),
  2171.             champ=Champ.objects.filter(translations__name="Групповой этап", host__name=context_data['host_name']).first(),
  2172.             menushow=True, host__name=context_data['host_name']).order_by('datetime').distinct()
  2173.         champ_teamss = Group.objects.filter(champ__translations__name="Групповой этап",
  2174.                                             host__name=context_data['host_name']).order_by('alias').distinct()
  2175.         matches_1_8 = Match.objects.filter(group__translations__name='1/8 Финала',
  2176.                                            host=context_data['host_name']).distinct().order_by('datetime')
  2177.         matches_quarterfinals = Match.objects.filter(group__translations__name='1/4 Финала',
  2178.                                                      host=context_data['host_name']).distinct().order_by('datetime')
  2179.         matches_semifinals = Match.objects.filter(group__translations__name='1/2 Финала',
  2180.                                                   host=context_data['host_name']).distinct().order_by('datetime')
  2181.         final = Match.objects.filter(group__translations__name='Финал',
  2182.                                      host=context_data['host_name']).distinct().order_by('datetime')
  2183.         match_for_3 = Match.objects.filter(group__translations__name='Матч за 3-е место',
  2184.                                            host=context_data['host_name']).distinct().order_by('datetime')
  2185.         stadiums = Stadium.objects.filter(host=context_data['host_name'])
  2186.         form = CorporateForm()
  2187.  
  2188.         context_data.update({
  2189.             'form': form,
  2190.             'matches': matches,
  2191.             'matches_1_8': matches_1_8,
  2192.             'matches_quarterfinals': matches_quarterfinals,
  2193.             'matches_semifinals': matches_semifinals,
  2194.             'match_for_3': match_for_3,
  2195.             'final': final,
  2196.             'stadiums': stadiums,
  2197.             'champ_teamss': champ_teamss,
  2198.         })
  2199.  
  2200.     context = RequestContext(request, context_data)
  2201.  
  2202.     return HttpResponse(template.render(context))
  2203.  
  2204.  
  2205. def games(request):
  2206.     template = choose_template(request, "matches")
  2207.  
  2208.     context_data = default_context(request, "games", TextPage)
  2209.  
  2210.     if request.method == 'POST':
  2211.         form = CorporateForm(request.POST)
  2212.         error = ''
  2213.         success = ''
  2214.         suces = -1
  2215.  
  2216.         if form.is_valid():
  2217.             name = form.cleaned_data['name']
  2218.             email = form.cleaned_data['email']
  2219.             num = form.cleaned_data['num']
  2220.             category = form.cleaned_data['category']
  2221.             phone = form.cleaned_data['phone']
  2222.             event = form.cleaned_data['event']
  2223.             message = form.cleaned_data['message']
  2224.             #            _message_data = map(
  2225.             #                force_unicode,
  2226.             #                [name, email, phone, match_name, category, type, num, form.cleaned_data.get(
  2227.             #                    'message', u"Без сообщения"
  2228.             #                )]
  2229.  
  2230.             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>'
  2231.             bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Матч: {event}<br> Категория: {category}<br> Сообщение: {message}'.format(
  2232.                 event=event, category=category, message=message
  2233.             )
  2234.  
  2235.             recipient_list = ['vladyan.s@yandex.ru']
  2236.  
  2237.             _hostname = context_data.get('host_name', None) or get_current_hostname(request)
  2238.             try:
  2239.                 send_mail(
  2240.                     u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
  2241.                     html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
  2242.                 )
  2243.             except BadHeaderError:  # Защита от уязвимости
  2244.                 error = 'Invalid header found'
  2245.             # Переходим на другую страницу, если сообщение отправлено
  2246.             success = 'Сообщение успешно отправлено!'
  2247.  
  2248.             client = Client(
  2249.                 getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  2250.                 cache=NoCache(),
  2251.                 timeout=15
  2252.             )
  2253.  
  2254.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  2255.             source_id, _msg = request.seo.analytics_message()
  2256.             if request.user.is_authenticated():
  2257.                 _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  2258.  
  2259.             info = dict(
  2260.                 info_ip=request.META['REMOTE_ADDR'],
  2261.                 lang="0",
  2262.                 site_name=website,
  2263.                 pass_hash=md5(website).hexdigest(),
  2264.                 is_operator='1' if request.user.is_authenticated() else '0',
  2265.                 source=force_unicode(source_id)
  2266.             )
  2267.  
  2268.             func = client.service.addOrderSourceI
  2269.  
  2270.             try:
  2271.                 order_id = func(
  2272.                     info_fio=name,
  2273.                     info_tel=phone,
  2274.                     info_email=email,
  2275.                     info_title=u'Корпоративная заявка',
  2276.                     info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  2277.                     info_tc=num,
  2278.                     info_cat=category,
  2279.                     info_notes=u'<br/>'.join([bin_message, _msg]),
  2280.                     **info
  2281.                 )
  2282.             except Exception as erra:
  2283.                 if getattr(django_settings, 'DEBUG', False):
  2284.                     print erra  # @TODO logger
  2285.             suces = order_id
  2286.  
  2287.             cart = Order.set_session(request)
  2288.             cart.phone = phone
  2289.             cart.email = email
  2290.             cart.fio = name
  2291.             cart.desc = bin_message.replace(u'<br>', u'\n')
  2292.             cart.website = website
  2293.             cart.bin_id = order_id
  2294.             cart.payment_processed = int(order_id) > 0
  2295.             cart.save()
  2296.             request.session.pop(django_settings.CART_SESSION_ID)
  2297.  
  2298.         else:
  2299.             error = 'В некоторых полях содержатся ошибки!'
  2300.  
  2301.         form = CorporateForm()
  2302.         context_data.update({
  2303.             'error': error,
  2304.             'success': success,
  2305.             'form': form,
  2306.             'suces': suces,
  2307.         })
  2308.     else:
  2309.         matches = Match.objects.filter(
  2310.             champ=Champ.objects.filter(translations__name="Групповой этап", host__name='fifa18.ru').first(),
  2311.             menushow=True, host__name='fifa18.ru').order_by('datetime').distinct()
  2312.         champ_teamss = Group.objects.filter(champ__translations__name="Групповой этап",
  2313.                                             host__name='fifa18.ru').order_by('alias').distinct()
  2314.         matches_1_8 = Match.objects.filter(group__translations__name='1/8 Финала',
  2315.                                            host=context_data['host_name']).distinct().order_by('datetime')
  2316.         matches_quarterfinals = Match.objects.filter(group__translations__name='1/4 Финала',
  2317.                                                      host=context_data['host_name']).distinct().order_by('datetime')
  2318.         matches_semifinals = Match.objects.filter(group__translations__name='1/2 Финала',
  2319.                                                   host=context_data['host_name']).distinct().order_by('datetime')
  2320.         final = Match.objects.filter(group__translations__name='Финал',
  2321.                                      host=context_data['host_name']).distinct().order_by('datetime')
  2322.         match_for_3 = Match.objects.filter(group__translations__name='Матч за 3-е место',
  2323.                                            host=context_data['host_name']).distinct().order_by('datetime')
  2324.         stadiums = Stadium.objects.filter(host=context_data['host_name'])
  2325.         form = CorporateForm()
  2326.  
  2327.         context_data.update({
  2328.             'form': form,
  2329.             'matches': matches,
  2330.             'matches_1_8': matches_1_8,
  2331.             'matches_quarterfinals': matches_quarterfinals,
  2332.             'matches_semifinals': matches_semifinals,
  2333.             'match_for_3': match_for_3,
  2334.             'final': final,
  2335.             'stadiums': stadiums,
  2336.             'champ_teamss': champ_teamss,
  2337.         })
  2338.  
  2339.     context = RequestContext(request, context_data)
  2340.  
  2341.     return HttpResponse(template.render(context))
  2342.  
  2343.  
  2344. def team(request, team_alias):
  2345.     template = choose_template(request, "team")
  2346.  
  2347.     context_data = default_context(request, team_alias, Team)
  2348.  
  2349.     # teams_alias = get_host_vs_url( context_data['host_name'] , request.get_full_path() , 'teams' )
  2350.     # parent_textpage = TextPage.objects.get(alias=teams_alias,host=context_data['host_name'])
  2351.  
  2352.     teams_alias = get_alias_related(context_data['host_name'], 'teams')
  2353.     # if context_data['host_name'] == 'confcuptickets.ru' :
  2354.     # teams_alias = 'comands'
  2355.     morph = pymorphy2.MorphAnalyzer()
  2356.     try:
  2357.         gent = morph.parse(Team.objects.get(alias=team_alias, host=context_data['host_name']).name)[0].inflect(
  2358.             {'gent'}).word
  2359.     except:
  2360.         gent = Team.objects.get(alias=team_alias, host=context_data['host_name']).name
  2361.  
  2362.     breadcrumbs = [TextPage.objects.get(alias=teams_alias, host=context_data['host_name'])]
  2363.     groups = Group.objects.filter(teams=context_data['data'])
  2364.     matches = Match.objects.filter(
  2365.         Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  2366.         Q(command_first=context_data['data']) | Q(command_second=context_data['data']), Q(score=None),
  2367.         host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2368.     players = Player.objects.filter(team=context_data['data'])
  2369.     coaches = Player.objects.filter(Q(translations__position="тренер") | Q(translations__position="Тренер"),
  2370.                                     team=context_data['data'], team__alias=team_alias,
  2371.                                     host=context_data['host_name']).distinct()
  2372.     goalkeepers = Player.objects.filter(Q(translations__position="вратарь") | Q(translations__position="Вратарь"),
  2373.                                         team__alias=team_alias, host=context_data['host_name']).distinct()
  2374.     defenders = Player.objects.filter(Q(translations__position="защитник") | Q(translations__position="Защитник"),
  2375.                                       team__alias=team_alias, host=context_data['host_name']).distinct()
  2376.     midfielders = Player.objects.filter(
  2377.         Q(translations__position="полузащитник") | Q(translations__position="Полузащитник"), team__alias=team_alias,
  2378.         host=context_data['host_name']).distinct()
  2379.     attacks = Player.objects.filter(Q(translations__position="нападающий") | Q(translations__position="Нападающий"),
  2380.                                     team__alias=team_alias, host=context_data['host_name']).distinct()
  2381.  
  2382.     context_data.update({
  2383.         'gent': gent,
  2384.         'breadcrumbs': breadcrumbs,
  2385.         'groups': groups,
  2386.         'matches': matches,
  2387.         'players': players,
  2388.         'coaches': coaches,
  2389.         'goalkeepers': goalkeepers,
  2390.         'defenders': defenders,
  2391.         'midfielders': midfielders,
  2392.         'attacks': attacks,
  2393.     })
  2394.  
  2395.     context = RequestContext(request, context_data)
  2396.  
  2397.     return HttpResponse(template.render(context))
  2398.  
  2399.  
  2400. def team_matches(request, team_alias):
  2401.     template = choose_template(request, "team_matches")
  2402.  
  2403.     context_data = default_context(request, team_alias, Team)
  2404.  
  2405.     morph = pymorphy2.MorphAnalyzer()
  2406.     try:
  2407.         gent = morph.parse(Team.objects.get(alias=team_alias, host=context_data['host_name']).name)[0].inflect(
  2408.             {'datv'}).word
  2409.     except:
  2410.         gent = Team.objects.get(alias=team_alias, host=context_data['host_name']).name
  2411.  
  2412.     matches = Match.objects.filter(Q(command_first__alias=team_alias) | Q(command_second__alias=team_alias),
  2413.                                    host__name='fifa18.ru')
  2414.  
  2415.     context_data.update({
  2416.         'matches': matches,
  2417.         'gent': gent,
  2418.     })
  2419.  
  2420.     context = RequestContext(request, context_data)
  2421.  
  2422.     return HttpResponse(template.render(context))
  2423.  
  2424.  
  2425. def get_birth(data):
  2426.     if data.birth.year == 1:
  2427.         return u"Нет данных"
  2428.     else:
  2429.         return data.birth
  2430.  
  2431.  
  2432. def player_redierect(request, player_alias):
  2433.     template = choose_template(request, "player")
  2434.  
  2435.     try:
  2436.         player_item = Player.objects.get(alias=player_alias, host__name=get_current_hostname(request))
  2437.         return HttpResponsePermanentRedirect('/teams/' + player_item.team.alias + '/players/' + player_item.alias + '/')
  2438.     except Player.DoesNotExist:
  2439.         player_item = Http404
  2440.  
  2441.     context_data = default_context(request, player_item, Player)
  2442.  
  2443.     context = RequestContext(request, context_data)
  2444.  
  2445.     return HttpResponse(template.render(context))
  2446.  
  2447.  
  2448. def player(request, team_alias, player_alias):
  2449.     template = choose_template(request, "player")
  2450.  
  2451.     try:
  2452.         player_item = Player.objects.get(alias=player_alias, team__alias=team_alias,
  2453.                                          host__name=get_current_hostname(request)).alias
  2454.     except Player.DoesNotExist:
  2455.         player_item = Http404
  2456.  
  2457.     context_data = default_context(request, player_item, Player)
  2458.     team = default_context(request, team_alias, Team)
  2459.  
  2460.     matches = Match.objects.filter(
  2461.         Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  2462.         Q(command_first=team['data']) | Q(command_second=team['data']), Q(score=None),
  2463.         host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  2464.  
  2465.     teams_alias = get_alias_related(context_data['host_name'], 'teams')
  2466.     # if context_data['host_name'] == 'confcuptickets.ru' :
  2467.     # teams_alias = 'comands'
  2468.     #    breadcrumbs = [TextPage.objects.get(alias=player_alias, host=context_data['host_name']), context_data['data'].team]
  2469.     birth = get_birth(context_data['data'])
  2470.     gent = None
  2471.     try:
  2472.         morph = pymorphy2.MorphAnalyzer()
  2473.         gent = morph.parse(context_data['data'].team.name)[0].inflect({'gent'}).word
  2474.     except Exception:
  2475.         pass
  2476.     context_data.update({
  2477.         'gent': gent,
  2478.         'birth': birth,
  2479.         'matches': matches
  2480.     })
  2481.  
  2482.     context = RequestContext(request, context_data)
  2483.  
  2484.     return HttpResponse(template.render(context))
  2485.  
  2486.  
  2487. def team_players(request, team_alias):
  2488.     template = choose_template(request, "players")
  2489.  
  2490.     context_data = default_context(request, team_alias, Team)
  2491.  
  2492.     morph = pymorphy2.MorphAnalyzer()
  2493.     try:
  2494.         gent = morph.parse(Team.objects.get(alias=team_alias, host=context_data['host_name']).name)[0].inflect(
  2495.             {'gent'}).word
  2496.     except:
  2497.         gent = Team.objects.get(alias=team_alias, host=context_data['host_name']).name
  2498.  
  2499.     goalkeepers = Player.objects.filter(Q(translations__position="вратарь") | Q(translations__position="Вратарь"),
  2500.                                         team__alias=team_alias, host=context_data['host_name']).distinct()
  2501.     defenders = Player.objects.filter(Q(translations__position="защитник") | Q(translations__position="Защитник"),
  2502.                                       team__alias=team_alias, host=context_data['host_name']).distinct()
  2503.     midfielders = Player.objects.filter(
  2504.         Q(translations__position="полузащитник") | Q(translations__position="Полузащитник"), team__alias=team_alias,
  2505.         host=context_data['host_name']).distinct()
  2506.     attacks = Player.objects.filter(Q(translations__position="нападающий") | Q(translations__position="Нападающий"),
  2507.                                     team__alias=team_alias, host=context_data['host_name']).distinct()
  2508.  
  2509.     context_data.update({
  2510.         'gent': gent,
  2511.         'goalkeepers': goalkeepers,
  2512.         'defenders': defenders,
  2513.         'midfielders': midfielders,
  2514.         'attacks': attacks,
  2515.     })
  2516.  
  2517.     context = RequestContext(request, context_data)
  2518.  
  2519.     return HttpResponse(template.render(context))
  2520.  
  2521.  
  2522. def match(request, match_alias):
  2523.     template = choose_template(request, "match")
  2524.  
  2525.     url_path = TextPage.objects.filter(Q(translations__name='Матчи') | Q(translations__name='Расписание'),
  2526.                                        host__name=get_current_hostname(request)).first().alias
  2527.  
  2528.     try:
  2529.         if url_path != request.path.split('/')[1]:
  2530.             new_url = match_alias.lower().replace(' ', '-')
  2531.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2532.         elif match_alias == 'match010720181700':
  2533.             return HttpResponsePermanentRedirect('/' + url_path + '/rossiya-ispaniya/')
  2534.         elif match_alias == 'b1-a1-01-07-2018-17-00':
  2535.             return HttpResponsePermanentRedirect('/' + url_path + '/rossiya-ispaniya/')
  2536.         elif (match_alias.split('-')[0])[0].isupper():
  2537.             new_url = match_alias.lower().replace(' ', '-')
  2538.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2539.         elif (match_alias.split(' ')[1]) is not None:
  2540.             new_url = match_alias.lower().replace(' ', '-')
  2541.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2542.     except:
  2543.         pass
  2544.  
  2545.     context_data = default_context(request, match_alias, Match)
  2546.  
  2547.     matches_alias = get_alias_related(context_data['host_name'], 'matches')
  2548.     #    breadcrumbs = [TextPage.objects.get(alias=matches_alias, host=context_data['host_name'])]
  2549.  
  2550.     #    next_match = Match.objects.filter(score=None, host=context_data['host_name'], champ__translations__name='Групповой этап').distinct().order_by('datetime')[:2]
  2551.  
  2552.     try:
  2553.         next = context_data['data'].get_next_by_datetime()
  2554.     except Match.DoesNotExist:
  2555.         next = None
  2556.     try:
  2557.         prev = context_data['data'].get_previous_by_datetime()
  2558.     except Match.DoesNotExist:
  2559.         prev = None
  2560.  
  2561.     morph = pymorphy2.MorphAnalyzer()
  2562.     try:
  2563.         gent = \
  2564.         morph.parse(Team.objects.filter(translations__name=context_data['data'].command_first.name).first().name)[
  2565.             0].inflect({'gent'}).word
  2566.         gent2 = \
  2567.         morph.parse(Team.objects.filter(translations__name=context_data['data'].command_second.name).first().name)[
  2568.             0].inflect({'gent'}).word
  2569.     except:
  2570.         gent = Team.objects.filter(translations__name=context_data['data'].command_first.name).first().name
  2571.         gent2 = Team.objects.filter(translations__name=context_data['data'].command_second.name).first().name
  2572.  
  2573.     # _tickets = context_data.get('data').tickets(request=request)
  2574.     # print _tickets.tickets_by_sector(_tickets.sectors[0])[0].id
  2575.     # @TODO here goes tickets from parser and next line is fallback DB info
  2576.     tickets = Price.objects.filter(match=context_data['data']).order_by('order_id')
  2577.     stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id')
  2578.     team1matches = Match.objects.filter(
  2579.         Q(command_first=context_data['data'].command_first) | Q(command_second=context_data['data'].command_first),
  2580.         host=context_data['host_name'], champ__translations__name='Групповой этап', hide_match=False).distinct().order_by('datetime')
  2581.     team2matches = Match.objects.filter(
  2582.         Q(command_first=context_data['data'].command_second) | Q(command_second=context_data['data'].command_second),
  2583.         host=context_data['host_name'], champ__translations__name='Групповой этап', hide_match=False).distinct().order_by('datetime')
  2584.     player1 = Player.objects.filter(team__translations__name=context_data['data'].command_first.name,
  2585.                                     host=context_data['host_name']).distinct()
  2586.     player2 = Player.objects.filter(team__translations__name=context_data['data'].command_second.name,
  2587.                                     host=context_data['host_name']).distinct()
  2588.     reviews = Reviews.objects.filter(published=True).order_by('id').reverse()[:5]
  2589.  
  2590.     test = 'proverka'
  2591.  
  2592.     context_data.update({
  2593.         'tickets': tickets,
  2594.         'test': test,
  2595.         'stadiums': stadiums,
  2596.         'next': next,
  2597.         'prev': prev,
  2598.         'team1matches': team1matches,
  2599.         'team2matches': team2matches,
  2600.         'gent': gent,
  2601.         'gent2': gent2,
  2602.         'player1': player1,
  2603.         'player2': player2,
  2604.         'reviews': reviews,
  2605.     })
  2606.  
  2607.     context = RequestContext(request, context_data)
  2608.  
  2609.     return HttpResponse(template.render(context))
  2610.  
  2611.  
  2612. def match2(request, match_alias):
  2613.     template = choose_template(request, "match")
  2614.  
  2615.     url_path = TextPage.objects.filter(Q(translations__name='Матчи') | Q(translations__name='Расписание'),
  2616.                                        host__name=get_current_hostname(request)).first().alias
  2617.  
  2618.     try:
  2619.         if url_path != request.path.split('/')[1]:
  2620.             new_url = match_alias.lower().replace(' ', '-')
  2621.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2622.         elif (match_alias.split('-')[0])[0].isupper():
  2623.             new_url = match_alias.lower().replace(' ', '-')
  2624.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2625.         elif (match_alias.split(' ')[1]) is not None:
  2626.             new_url = match_alias.lower().replace(' ', '-')
  2627.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2628.     except:
  2629.         a = 123
  2630.  
  2631.     context_data = default_context(request, match_alias, Match)
  2632.  
  2633.     matches_alias = get_alias_related(context_data['host_name'], 'matches')
  2634.     #    breadcrumbs = [TextPage.objects.get(alias=matches_alias, host=context_data['host_name'])]
  2635.  
  2636.     next_match = Match.objects.filter(score=None, host=context_data['host_name']).order_by('datetime')[:2]
  2637.  
  2638.     try:
  2639.         next = context_data['data'].get_next_by_datetime()
  2640.     except Match.DoesNotExist:
  2641.         next = None
  2642.     try:
  2643.         prev = context_data['data'].get_previous_by_datetime()
  2644.     except Match.DoesNotExist:
  2645.         prev = None
  2646.  
  2647.     # _tickets = context_data.get('data').tickets(request=request)
  2648.     # print _tickets.tickets_by_sector(_tickets.sectors[0])[0].id
  2649.     # @TODO here goes tickets from parser and next line is fallback DB info
  2650.     tickets = Price.objects.filter(match=context_data['data']).order_by('id')
  2651.     stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id')
  2652.  
  2653.     context_data.update({
  2654.         #        'breadcrumbs': breadcrumbs,
  2655.         'tickets': tickets,
  2656.         'stadiums': stadiums,
  2657.         'next_match': next_match,
  2658.         'next': next,
  2659.         'prev': prev,
  2660.         #        'parse_tickets': _tickets.sectors,
  2661.         #        'svg': open(context_data.get('data').svg.path, 'r+').read() if context_data.get('data').svg else ''
  2662.     })
  2663.  
  2664.     context = RequestContext(request, context_data)
  2665.  
  2666.     return HttpResponse(template.render(context))
  2667.  
  2668.  
  2669. def game(request, match_alias):
  2670.     template = choose_template(request, "match")
  2671.  
  2672.     url_path = TextPage.objects.filter(Q(translations__name='Матчи') | Q(translations__name='Расписание'),
  2673.                                        host__name=get_current_hostname(request)).first().alias
  2674.  
  2675.     try:
  2676.         if url_path != request.path.split('/')[1]:
  2677.             new_url = match_alias.lower().replace(' ', '-')
  2678.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2679.         elif (match_alias.split('-')[0])[0].isupper():
  2680.             new_url = match_alias.lower().replace(' ', '-')
  2681.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2682.         elif (match_alias.split(' ')[1]) is not None:
  2683.             new_url = match_alias.lower().replace(' ', '-')
  2684.             return HttpResponsePermanentRedirect('/' + url_path + '/' + new_url + '/')
  2685.     except:
  2686.         a = 123
  2687.  
  2688.     context_data = default_context(request, match_alias, Match)
  2689.  
  2690.     matches_alias = get_alias_related(context_data['host_name'], 'matches')
  2691.     #    breadcrumbs = [TextPage.objects.get(alias=matches_alias, host=context_data['host_name'])]
  2692.  
  2693.     next_match = Match.objects.filter(score=None, host=context_data['host_name']).order_by('datetime')[:2]
  2694.  
  2695.     try:
  2696.         next = context_data['data'].get_next_by_datetime()
  2697.     except Match.DoesNotExist:
  2698.         next = None
  2699.     try:
  2700.         prev = context_data['data'].get_previous_by_datetime()
  2701.     except Match.DoesNotExist:
  2702.         prev = None
  2703.  
  2704.     # _tickets = context_data.get('data').tickets(request=request)
  2705.     # print _tickets.tickets_by_sector(_tickets.sectors[0])[0].id
  2706.     # @TODO here goes tickets from parser and next line is fallback DB info
  2707.     tickets = Price.objects.filter(match=context_data['data']).order_by('id')
  2708.     stadiums = Stadium.objects.filter(host=context_data['host_name']).order_by('id')
  2709.  
  2710.     context_data.update({
  2711.         #        'breadcrumbs': breadcrumbs,
  2712.         'tickets': tickets,
  2713.         'stadiums': stadiums,
  2714.         'next_match': next_match,
  2715.         'next': next,
  2716.         'prev': prev,
  2717.         #        'parse_tickets': _tickets.sectors,
  2718.         #        'svg': open(context_data.get('data').svg.path, 'r+').read() if context_data.get('data').svg else ''
  2719.     })
  2720.  
  2721.     context = RequestContext(request, context_data)
  2722.  
  2723.     return HttpResponse(template.render(context))
  2724.  
  2725.  
  2726. def stadium(request, stadium_alias):
  2727.     template = choose_template(request, "stadium")
  2728.  
  2729.     url_path = TextPage.objects.filter(Q(translations__name='Стадионы'),
  2730.                                        host__name=get_current_hostname(request)).first().alias
  2731.  
  2732.     try:
  2733.         if stadium_alias.split(' ')[1] is not None:
  2734.             new_alias = stadium_alias.replace(' ', '-')
  2735.             return HttpResponsePermanentRedirect('/stadiums/' + new_alias + '/')
  2736.     except:
  2737.         a = 123
  2738.  
  2739.     context_data = default_context(request, stadium_alias, Stadium)
  2740.     today = datetime.date.today()
  2741.     matches = Match.objects.filter(~Q(champ__translations__name='Кубок конфедераций 2017'),
  2742.                                    ~Q(group__translations__name='Товарищеские матчи'), datetime__gt=today,
  2743.                                    stadium=context_data['data'], host=context_data['host_name'], hide_match=False).order_by(
  2744.         'datetime').distinct().order_by('group__menuposition', 'datetime')
  2745.     news = News.objects.filter(host=context_data['host_name'], menushow=True).order_by('-date')
  2746.  
  2747.     context_data.update({
  2748.         'matches': matches,
  2749.         'news': news,
  2750.     })
  2751.  
  2752.     context = RequestContext(request, context_data)
  2753.  
  2754.     return HttpResponse(template.render(context))
  2755.  
  2756.  
  2757. def fed(request, fed_alias):
  2758.     template = choose_template(request, "fed")
  2759.  
  2760.     context_data = default_context(request, fed_alias, Fed)
  2761.     champs = Champ.objects.filter(fed=context_data['data'])
  2762.  
  2763.     context_data.update({
  2764.         'champs': champs
  2765.     })
  2766.  
  2767.     context = RequestContext(request, context_data)
  2768.  
  2769.     return HttpResponse(template.render(context))
  2770.  
  2771.  
  2772. def prices_api(request):
  2773.     template = loader.get_template('prices_api.html')
  2774.  
  2775.     matches = Match.objects.filter(Q(champ=Champ.objects.filter(translations__name="Групповой этап",
  2776.                                                                 host=Site.objects.get(
  2777.                                                                     name=get_current_hostname(request))).first()) | Q(
  2778.         group__translations__name='1/2 Финала') | Q(group__translations__name='1/4 Финала') | Q(
  2779.         group__translations__name='1/8 Финала') | Q(group__translations__name='Финал') | Q(
  2780.         group__translations__name='Матч за 3-е место'),
  2781.                                    host=Site.objects.get(name=get_current_hostname(request))).distinct().order_by(
  2782.         'group__menuposition', 'datetime')
  2783.  
  2784.     context = RequestContext(request, {
  2785.         'matches': matches
  2786.     })
  2787.     return HttpResponse(template.render(context))
  2788.  
  2789.  
  2790. @csrf_exempt
  2791. def test(request):
  2792.     template = choose_template(request, "test")
  2793.  
  2794.     context_data = default_context(request, "test", TextPage)
  2795.  
  2796.     items = Match.objects.filter(
  2797.         Q(champ=Champ.objects.filter(translations__name="Групповой этап", host=Site.objects.get(id=1)).first()),
  2798.         host=Site.objects.get(id=1)).distinct().order_by('group__menuposition', 'datetime')
  2799.  
  2800.     context_data.update({
  2801.         'test': test,
  2802.     })
  2803.  
  2804.     context = RequestContext(request, context_data)
  2805.  
  2806.     return HttpResponse(template.render(context))
  2807.  
  2808.  
  2809. @login_required
  2810. def match_builder(request):
  2811.     if request.is_ajax():
  2812.         data = json.loads(request.read())
  2813.         if data['type'] == 'get_site_info':
  2814.             items = []
  2815.             count = 0
  2816.             for i in Match.objects.filter(Q(champ=Champ.objects.filter(translations__name="Групповой этап",
  2817.                                                                        host=Site.objects.get(
  2818.                                                                                id=data['data'])).first()) | Q(
  2819.                     group__translations__name='1/2 Финала') | Q(group__translations__name='1/4 Финала') | Q(
  2820.                     group__translations__name='1/8 Финала') | Q(group__translations__name='Финал') | Q(
  2821.                     group__translations__name='Матч за 3-е место'),
  2822.                                           host=Site.objects.get(id=data['data'])).distinct().order_by(
  2823.                     'group__menuposition', 'datetime'):
  2824.                 items.append({'cmnd_frst_flg': i.command_first.get_flag_list()[1],
  2825.                               'cmnd_scnd_flg': i.command_second.get_flag_list()[1],
  2826.                               'command_first': i.command_first.name, 'command_second': i.command_second.name,
  2827.                               'id': i.id, 'prices': []})
  2828.                 its = Price.objects.filter(match=i, host=Site.objects.get(id=data['data'])).distinct()
  2829.                 for it in its:
  2830.                     items[count]['prices'].append({'price': int(it.price), 'sector': it.sector, 'id': it.id})
  2831.                 count += 1
  2832.             MyValue = json.dumps(items, ensure_ascii=False).encode('utf8')
  2833.         elif data['type'] == 'change_price':
  2834.             Price.objects.filter(id=data['data']['id']).update(price=int(data['data']['price']), status=data['data']['status'])
  2835.             MyValue = 'Good'
  2836.         return HttpResponse(MyValue)
  2837.     else:
  2838.         template = choose_template(request, "match_form")
  2839.  
  2840.         context_data = default_context(request, "match-builder", TextPage)
  2841.  
  2842.         sites = Site.objects.all()
  2843.         matches = Match.objects.filter(Q(score=None), Q(champ=Champ.objects.filter(translations__name="Групповой этап",
  2844.                                                                     host=Site.objects.get(
  2845.                                                                         name=context_data['host_name'])).first()) | Q(
  2846.             group__translations__name='1/2 Финала') | Q(group__translations__name='1/4 Финала') | Q(
  2847.             group__translations__name='1/8 Финала') | Q(group__translations__name='Финал') | Q(
  2848.             group__translations__name='Матч за 3-е место'),
  2849.                                        host=Site.objects.get(name=context_data['host_name'])).distinct().order_by(
  2850.             'datetime')
  2851.  
  2852.         context_data.update({
  2853.             'sites': sites,
  2854.             'matches': matches
  2855.         })
  2856.  
  2857.         context = RequestContext(request, context_data)
  2858.  
  2859.         return HttpResponse(template.render(context))
  2860.  
  2861.  
  2862. def googleverify(request):
  2863.     template = choose_template(request, "google30a074ebbcd9e045")
  2864.     context_data = default_context(request, "test", TextPage)
  2865.     context = RequestContext(request, context_data)
  2866.     return HttpResponse(template.render(context))
  2867.  
  2868.  
  2869. def zayavka(request, zayavka_alias):
  2870.     template = choose_template(request, "zayavka")
  2871.  
  2872.     context_data = default_context(request, zayavka_alias, Fed)
  2873.     breadcrumbs = [TextPage.objects.get(alias='zayavki', host=context_data['host_name'])]
  2874.  
  2875.     context_data.update({
  2876.         'breadcrumbs': breadcrumbs,
  2877.     })
  2878.  
  2879.     context = RequestContext(request, context_data)
  2880.  
  2881.     return HttpResponse(template.render(context))
  2882.  
  2883.  
  2884. def champ(request, champ_alias):
  2885.     template = choose_template(request, "champ")
  2886.  
  2887.     context_data = default_context(request, champ_alias, Champ)
  2888.     groups = Group.objects.filter(champ=Champ.objects.filter(alias=champ_alias).first(),
  2889.                                   host=context_data['host_name']).distinct().order_by('alias')
  2890.  
  2891.     context_data.update({
  2892.         'groups': groups,
  2893.     })
  2894.  
  2895.     context = RequestContext(request, context_data)
  2896.  
  2897.     return HttpResponse(template.render(context))
  2898.  
  2899.  
  2900. def groups(request):
  2901.     template = choose_template(request, "groups")
  2902.  
  2903.     context_data = default_context(request, "groups", TextPage)
  2904.     groups = Group.objects.filter(host=context_data['host_name'])
  2905.  
  2906.     context_data.update({
  2907.         'groups': groups
  2908.     })
  2909.  
  2910.     context = RequestContext(request, context_data)
  2911.  
  2912.     return HttpResponse(template.render(context))
  2913.  
  2914.  
  2915. def group(request, champ_alias, group_alias):
  2916.     template = choose_template(request, "group")
  2917.  
  2918.     try:
  2919.         group_item = Group.objects.filter(alias=group_alias, champ__alias=champ_alias).first().alias
  2920.     except Group.DoesNotExist:
  2921.         group_item = Http404
  2922.  
  2923.     context_data = default_context(request, group_item, Group)
  2924.     group = Group.objects.get(alias=group_alias, host=context_data['host_name'])
  2925.     matches = Match.objects.filter(group__alias=group_alias, group__champ__alias=champ_alias,
  2926.                                    host=context_data['host_name']).order_by('datetime')
  2927.  
  2928.     context_data.update({
  2929.         'group': group,
  2930.         'matches': matches,
  2931.     })
  2932.  
  2933.     context = RequestContext(request, context_data)
  2934.  
  2935.     return HttpResponse(template.render(context))
  2936.  
  2937.  
  2938. def get_field_value(object, field):
  2939.     from django.db.models.fields import IntegerField, DateField, DateTimeField
  2940.     from django.db.models.fields.files import ImageField
  2941.     from django.contrib.postgres.fields.jsonb import JSONField
  2942.     import json
  2943.  
  2944.     value = eval("object." + field)
  2945.     field_type = "other"
  2946.  
  2947.     if type(value) == bool:
  2948.         field_type = "bool"
  2949.         if value:
  2950.             value = "1"
  2951.         else:
  2952.             value = "0"
  2953.  
  2954.     elif isinstance(object._meta.get_field(field), IntegerField):
  2955.         field_type = "int"
  2956.         if value:
  2957.             value = str(value)
  2958.         else:
  2959.             value = "0"
  2960.  
  2961.     elif isinstance(object._meta.get_field(field), DateField):
  2962.         field_type = "date"
  2963.         if value:
  2964.             value = str(value.strftime("%d.%m.%Y"))
  2965.         else:
  2966.             value = "01.01.1900"
  2967.  
  2968.     elif isinstance(object._meta.get_field(field), DateTimeField):
  2969.         field_type = "datetime"
  2970.         if value:
  2971.             value = str(value.strftime("%d.%m.%Y,%H:%M"))
  2972.         else:
  2973.             value = "01.01.1900,00:00"
  2974.  
  2975.     elif isinstance(object._meta.get_field(field), ImageField):
  2976.         field_type = "image"
  2977.         if value:
  2978.             value = str(value).split("/")[-1]
  2979.         else:
  2980.             value = ""
  2981.  
  2982.     elif isinstance(object._meta.get_field(field), JSONField):
  2983.         field_type = "json"
  2984.         value = json.dumps(value, ensure_ascii=False, encoding='utf8')
  2985.  
  2986.     elif type(value) == unicode or type(value) == str:
  2987.         field_type = "str"
  2988.         value = value.encode('utf8').replace('"', '\\"')
  2989.  
  2990.     else:
  2991.         if value:
  2992.             value = str(value)
  2993.         else:
  2994.             value = ""
  2995.  
  2996.     return [field, value, field_type]
  2997.  
  2998.  
  2999. def export(request, export_type):
  3000.     template = loader.get_template('export.html')
  3001.     if export_type == 'team':
  3002.         object = Team
  3003.     elif export_type == 'match':
  3004.         object = Match
  3005.     elif export_type == 'player':
  3006.         object = Player
  3007.     elif export_type == 'stadium':
  3008.         object = Stadium
  3009.     elif export_type == 'champ':
  3010.         object = Champ
  3011.     elif export_type == 'champ':
  3012.         object = Champ
  3013.     elif export_type == 'fed':
  3014.         object = Fed
  3015.     elif export_type == 'group':
  3016.         object = Group
  3017.     elif export_type == 'textpage':
  3018.         object = TextPage
  3019.     else:
  3020.         object = Team
  3021.     fields = [field.name for field in object._meta.fields]
  3022.  
  3023.     # objects = object.objects.filter(host__name=request.get_host()).all()
  3024.  
  3025.     data = []
  3026.     for object in objects:
  3027.         item = []
  3028.         for field in fields:
  3029.             if field != 'id':
  3030.                 field_param = get_field_value(object, field)  # [field , value , type]
  3031.                 item.append(field_param)
  3032.         data.append(item)
  3033.  
  3034.     context = RequestContext(request, {
  3035.         'objects': objects,
  3036.         'fields': fields,
  3037.         'data': data,
  3038.     })
  3039.  
  3040.     return HttpResponse(template.render(context), content_type="text/plain;charset=utf-8")
  3041.  
  3042.  
  3043. def call_back(request):
  3044.     if request.is_ajax():
  3045.         success = 'ajax:no-method'
  3046.         if request.POST['type'] == 'callback':
  3047.             email = request.POST.get('email')
  3048.             phone_new = request.POST.get('phone')
  3049.             message = request.POST.get('message')
  3050.             form_order_id = request.POST.get('order_id')
  3051.             subject = u'Узнать статус закза #{}'.format(form_order_id)
  3052.             message = u'Некий господин/госпожа хочет узнать статус доставки на телефон {phone}. Email: {email} <br> Сообщение: {message}'.format(
  3053.                 email=email, phone=phone_new, message=message
  3054.             )
  3055.             recipients = ['vladyan.s@yandex.ru', 'vladyan121@gmail.com']
  3056.  
  3057.             # send_mail(
  3058.             #     subject, message, EMAIL_FROM, recipients, html_message=message,
  3059.             #     fail_silently=not getattr(django_settings, 'DEBUG', False)
  3060.             # )
  3061.  
  3062.             order_id = -1
  3063.             client = Client(
  3064.                 getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  3065.                 cache=NoCache(),
  3066.                 timeout=15
  3067.             )
  3068.  
  3069.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  3070.             source_id, _msg = request.seo.analytics_message()
  3071.             if request.user.is_authenticated():
  3072.                 _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  3073.  
  3074.             info = dict(
  3075.                 info_ip=request.META['REMOTE_ADDR'],
  3076.                 lang="0",
  3077.                 site_name=website,
  3078.                 pass_hash=md5(website).hexdigest(),
  3079.                 is_operator='1' if request.user.is_authenticated() else '0',
  3080.                 source=force_unicode(source_id)
  3081.             )
  3082.  
  3083.             # func = client.service.addOrderSourceI
  3084.             #
  3085.             # try:
  3086.             #     order_id = func(
  3087.             #         info_fio=u"",
  3088.             #         info_tel=phone_new,
  3089.             #         info_title=u'Узнать статус доставки',
  3090.             #         info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  3091.             #         info_cat=u'Узнать статус доставки',
  3092.             #         info_notes=u'<br/>'.join([message, _msg]),
  3093.             #         **info
  3094.             #     )
  3095.             # except Exception as erra:
  3096.             #     if getattr(django_settings, 'DEBUG', False):
  3097.             #         print erra  # @TODO logger
  3098.  
  3099.             url = 'http://185.154.52.97:8001/api/create-order-from-site/'
  3100.  
  3101.             new_bcontent = {
  3102.                 "comment": message,
  3103.                 "client_name":  u'Узнать статус доставки #{}'.format(form_order_id),
  3104.                 "client_phone": phone_new,
  3105.                 # "client_phone_code": zone,
  3106.                 # "client_address": addr,
  3107.                 # "pay_type": paymethod,
  3108.                 "site_name": request.get_host(),
  3109.                 "old_bintranet_id": order_id,
  3110.                 "status": 23,
  3111.             }
  3112.  
  3113.             send_message = requests.post(url, headers={'content-type': 'application/json',
  3114.                                         'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
  3115.                           data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
  3116.  
  3117.             success = send_message.json().get('pk', -1)
  3118.  
  3119.             cart = Order.set_session(request)
  3120.             cart.phone = phone_new
  3121.             cart.fio = u'Узнать статус доставки #{}'.format(order_id),
  3122.             cart.desc = u'\n'.join([u'Обратный звонок', message])
  3123.             cart.website = website
  3124.             cart.bin_id = order_id
  3125.             cart.payment_processed = int(order_id) > 0
  3126.             cart.save()
  3127.             request.session.pop(django_settings.CART_SESSION_ID)
  3128.  
  3129.         return HttpResponse(success)
  3130.     else:
  3131.         return HttpResponse('no-ajax method')
  3132.  
  3133.  
  3134. def vip_tickets(request):
  3135.     # VIP MATCHES
  3136.     lodge = request.POST.get('lodge')
  3137.     if lodge:
  3138.         return get_vip(request, lodge)
  3139.  
  3140. def vip(request):
  3141.     template = choose_template(request, "vip")
  3142.     context_data = default_context(request, "vip-hospitality", TextPage)
  3143.  
  3144.     order_id = ''
  3145.     groups = Group.objects.filter(
  3146.         Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  3147.         host__name=context_data['host_name']).distinct().order_by('menuposition')
  3148.     match_by_groups = Match.objects.filter(Q(score=None), host=context_data['host_name'], hide_match=False,
  3149.                                         champ=Champ.objects.filter(translations__name="Групповой этап",
  3150.                                                                     host=context_data[
  3151.                                                                         'host_name']).first()).distinct().order_by('group__menuposition', 'datetime')
  3152.     matches_1_8 = Match.objects.filter(Q(score=None), group__translations__name='1/8 Финала',
  3153.                             host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  3154.     matches_quarterfinals = Match.objects.filter(Q(score=None),group__translations__name='1/4 Финала',
  3155.                                                 host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  3156.     matches_semifinals = Match.objects.filter(Q(score=None),group__translations__name='1/2 Финала',
  3157.                                             host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  3158.     final = Match.objects.filter(Q(score=None),group__translations__name='Финал',
  3159.                                 host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  3160.     match_for_3 = Match.objects.filter(Q(score=None),group__translations__name='Матч за 3-е место',
  3161.                                     host=context_data['host_name'], hide_match=False).distinct().order_by('datetime')
  3162.  
  3163.     ip = get_client_ip(request)
  3164.  
  3165.     if request.method == 'POST':
  3166.         cip = cache.get(ip, None)
  3167.  
  3168.         # if cache.get('captcha') == None:
  3169.         #     try:
  3170.         #         if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  3171.         #             cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  3172.         #         else:
  3173.         #             cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  3174.         #     except Exception:
  3175.         #         cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  3176.         #
  3177.         # if cache.get('captcha') == True:
  3178.         #     if request.POST.get(u'g-recaptcha-response'):
  3179.         #         form = CorporateFormCaptcha(request.POST)
  3180.         #         try:
  3181.         #             cache.incr(ip, 1)
  3182.         #         except ValueError:
  3183.         #             cache.set(ip, 1, django_settings.BLACK_TIME_IP)
  3184.         #     elif cip >= django_settings.BLACK_COUNT_TRYING_IP:
  3185.         #         try:
  3186.         #             cache.incr(ip, 1)
  3187.         #         except ValueError:  # на случай если вдруг в это время ключ уже удалился
  3188.         #             cache.set(ip, cip + 1, django_settings.BLACK_TIME_IP)
  3189.         #         # if cip == django_settings.BLACK_COUNT_TRYING_IP:
  3190.         #         #    form = ContactForm(request.POST)
  3191.         #         # else:
  3192.         #         form = CorporateFormCaptcha(request.POST)
  3193.         #     else:
  3194.         #         cache.set(ip, 1, django_settings.BLACK_TIME_IP)
  3195.         #         form = CorporateForm(request.POST)
  3196.         # else:
  3197.         #     form = CorporateForm(request.POST)
  3198.         if cache.get('captcha') == None:
  3199.             try:
  3200.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  3201.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  3202.                 else:
  3203.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  3204.             except Exception:
  3205.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  3206.         if cache.get('captcha') == True:
  3207.             form = CorporateFormCaptcha(request.POST)
  3208.         else:
  3209.             form = CorporateForm(request.POST)
  3210.  
  3211.         error = ''
  3212.         success = ''
  3213.         order_id = -1
  3214.  
  3215.         if form.is_valid():
  3216.             name = form.cleaned_data['name']
  3217.             email = form.cleaned_data['email']
  3218.             # num = form.cleaned_data['num']
  3219.             # category = form.cleaned_data['category']
  3220.             phone = form.cleaned_data['phone']
  3221.             event = form.cleaned_data['event']
  3222.             message = form.cleaned_data['message']
  3223.  
  3224.             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>'
  3225.             bin_message = u'Корпоративная завявка с сайта condederationscup.net.<br> Сообщение: {message}'.format(
  3226.                 message=message
  3227.             )
  3228.  
  3229.             recipient_list = ['info@worldcup2018.me']
  3230.  
  3231.             _hostname = context_data.get('host_name', None) or get_current_hostname(request)
  3232.             # try:
  3233.             #     send_mail(
  3234.             #         u'Заказ с сайта {}'.format(_hostname.domain), message_html, EMAIL_FROM, recipient_list,
  3235.             #         html_message=message_html, fail_silently=not getattr(django_settings, 'DEBUG', False)
  3236.             #     )
  3237.             # except (BadHeaderError, AttributeError):  # Защита от уязвимости
  3238.             #     error = 'Invalid header found'
  3239.             # Переходим на другую страницу, если сообщение отправлено
  3240.             success = 'Сообщение успешно отправлено!'
  3241.  
  3242.             client = Client(
  3243.                 getattr(django_settings, 'BINTRANET_WSDL', 'http://bintranet.ru/soap/service.wsdl'),
  3244.                 cache=NoCache(),
  3245.                 timeout=15
  3246.             )
  3247.             website = getattr(django_settings, 'BINTRANET_WEBSITE', request.get_host())
  3248.             source_id, _msg = request.seo.analytics_message()
  3249.             if request.user.is_authenticated():
  3250.                 _msg += u'<br/>Оператор: {}<br/>'.format(request.user.get_full_name() or request.user.username)
  3251.  
  3252.             info = dict(
  3253.                 info_ip=request.META['REMOTE_ADDR'],
  3254.                 lang="0",
  3255.                 site_name=website,
  3256.                 pass_hash=md5(website).hexdigest(),
  3257.                 is_operator='1' if request.user.is_authenticated() else '0',
  3258.                 source=force_unicode(source_id)
  3259.             )
  3260.  
  3261.             # func = client.service.addOrderSourceI
  3262.             #
  3263.             # try:
  3264.             #     order_id = func(
  3265.             #         info_fio=name,
  3266.             #         info_tel=phone,
  3267.             #         info_email=email,
  3268.             #         info_title=u'Корпоративная заявка',
  3269.             #         info_d=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  3270.             #         #                    info_tc=num,
  3271.             #         info_cat=event,
  3272.             #         info_notes=u'<br/>'.join([bin_message, _msg]),
  3273.             #         **info
  3274.             #     )
  3275.             # except Exception as erra:
  3276.             #     pass
  3277.  
  3278.             url = 'http://185.154.52.97:8001/api/create-order-from-site/'
  3279.  
  3280.             new_bcontent = {
  3281.                 "comment": u'Корпоративная завяка',
  3282.                 "client_name": name,
  3283.                 "client_phone": phone,
  3284.                 # "client_phone_code": zone,
  3285.                 # "client_address": addr,
  3286.                 # "pay_type": paymethod,
  3287.                 "site_name": request.get_host(),
  3288.                 "client_comment": message
  3289.             }
  3290.  
  3291.             item = requests.post(url, headers={'content-type': 'application/json',
  3292.                                         'Authorization': 'Token {}'.format(django_settings.TOKEN_ACQUIRING)},
  3293.                           data=json.dumps(new_bcontent, ensure_ascii=False).encode('utf8'))
  3294.  
  3295.             order_id = item.json().get('pk', -1)
  3296.  
  3297.             cart = context_data.get('mini_cart', Order.get_session(request=request))
  3298.             cart.phone = phone
  3299.             cart.email = email
  3300.             cart.fio = name
  3301.             cart.desc = bin_message.replace(u'<br>', u'\n')
  3302.             cart.website = website
  3303.             cart.bin_id = order_id
  3304.             cart.payment_processed = int(order_id) > 0
  3305.             cart.save()
  3306.             request.session.pop(django_settings.CART_SESSION_ID)
  3307.  
  3308.         else:
  3309.             error = 'В некоторых полях содержатся ошибки!'
  3310.     else:
  3311.         if cache.get('captcha') == None:
  3312.             try:
  3313.                 if SiteSettings.objects.get(host__name=Alias.objects.get(domain=request.get_host()).site.name).captcha:
  3314.                     cache.set('captcha', True, django_settings.CAPTCHA_LIFE)
  3315.                 else:
  3316.                     cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  3317.             except Exception:
  3318.                 cache.set('captcha', False, django_settings.CAPTCHA_LIFE)
  3319.  
  3320.         if cache.get('captcha') == True:
  3321.             if cache.get(ip) >= django_settings.BLACK_COUNT_TRYING_IP:
  3322.                 form = CorporateFormCaptcha()
  3323.             else:
  3324.                 form = CorporateForm()
  3325.         else:
  3326.             form = CorporateForm()
  3327.  
  3328.     context_data.update({
  3329.         'stadiums': stadiums,
  3330.         'groups': groups,
  3331.         'champ': champ,
  3332.         'form': form,
  3333.         'cities': cities,
  3334.         'order_id': order_id,
  3335.         'matches_1_8': matches_1_8,
  3336.         'matches_quarterfinals': matches_quarterfinals,
  3337.         'matches_semifinals': matches_semifinals,
  3338.         'match_for_3': match_for_3,
  3339.         'final': final,
  3340.         'match_by_groups': match_by_groups
  3341.     })
  3342.  
  3343.     context = RequestContext(request, context_data)
  3344.  
  3345.     return HttpResponse(template.render(context))
  3346.  
  3347.  
  3348. def get_fields(request):
  3349.     if request.is_ajax():
  3350.         q = request.GET.get('term', '')
  3351.         drugs = Match.objects.filter(
  3352.             Q(command_first__translations__name__icontains=q) | Q(command_second__translations__name__icontains=q),
  3353.             Q(champ__translations__name='Групповой этап') | Q(champ__translations__name='Плей-офф'),
  3354.             host__name='worldcup2018.me', hide_match=False).distinct()
  3355.         drugs2 = Team.objects.filter(translations__name__icontains=q, host__name='worldcup2018.me').distinct()
  3356.         drugs3 = City.objects.filter(translations__name__icontains=q, host__name='worldcup2018.me').distinct()
  3357.         drugs4 = Stadium.objects.filter(translations__name__icontains=q, host__name='worldcup2018.me').distinct()
  3358.         results = []
  3359.         if request.get_host().split('.')[0] == 'en':
  3360.             for drug in drugs:
  3361.                 drug_json = {}
  3362.                 drug_json['name'] = drug.command_first.name + ' - ' + drug.command_second.name + u' - Buy tickets'
  3363.                 drug_json['alias'] = '/matches/' + drug.alias + '/'
  3364.                 results.append(drug_json)
  3365.             for drug in drugs2:
  3366.                 drug_json = {}
  3367.                 drug_json['name'] = drug.name + u' - information about the national team'
  3368.                 drug_json['alias'] = '/teams/' + drug.alias + '/'
  3369.                 results.append(drug_json)
  3370.             for drug in drugs3:
  3371.                 drug_json = {}
  3372.                 drug_json['name'] = drug.name + u' - matches in the city'
  3373.                 drug_json['alias'] = '/cities/' + drug.alias + '/'
  3374.                 results.append(drug_json)
  3375.             for drug in drugs4:
  3376.                 drug_json = {}
  3377.                 drug_json['name'] = drug.name + u' - matches on the stadium'
  3378.                 drug_json['alias'] = '/stadiums/' + drug.alias + '/'
  3379.                 results.append(drug_json)
  3380.         else:
  3381.             for drug in drugs:
  3382.                 drug_json = {}
  3383.                 drug_json['name'] = drug.command_first.name + ' - ' + drug.command_second.name + u' - купить билеты'
  3384.                 drug_json['alias'] = '/matches/' + drug.alias + '/'
  3385.                 results.append(drug_json)
  3386.             for drug in drugs2:
  3387.                 drug_json = {}
  3388.                 drug_json['name'] = drug.name + u' - информация о сборной'
  3389.                 drug_json['alias'] = '/teams/' + drug.alias + '/'
  3390.                 results.append(drug_json)
  3391.             for drug in drugs3:
  3392.                 drug_json = {}
  3393.                 drug_json['name'] = drug.name + u' - выбрать матчи в данном городе'
  3394.                 drug_json['alias'] = '/cities/' + drug.alias + '/'
  3395.                 results.append(drug_json)
  3396.             for drug in drugs4:
  3397.                 drug_json = {}
  3398.                 drug_json['name'] = drug.name + u' - выбрать матчи на данном стадионе'
  3399.                 drug_json['alias'] = '/stadiums/' + drug.alias + '/'
  3400.                 results.append(drug_json)
  3401.         data = json.dumps(results[:7])
  3402.     else:
  3403.         data = 'fail'
  3404.     mimetype = 'application/json'
  3405.     return HttpResponse(data, mimetype)
  3406.  
  3407.  
  3408. def ajax(request):
  3409.     cart = Order.get_session(request=request)
  3410.     if request.is_ajax():
  3411.         message = 'ajax:no-method'
  3412.         _id = ''
  3413.         if get_field_without_somechars(request.POST['type']) == 'del_item':
  3414.             try:
  3415.                 object = ajaxcontroller.del_item(
  3416.                     request.POST,
  3417.                 )
  3418.                 _id = object
  3419.             except KeyError:
  3420.                 _id = "Error"
  3421.                 pass
  3422.         elif get_field_without_somechars(request.POST['type']) == 'del_itemm':
  3423.             try:
  3424.                 object = ajaxcontroller.del_itemm(
  3425.                     request.POST,
  3426.                     request
  3427.                 )
  3428.                 _id = object
  3429.             except KeyError:
  3430.                 _id = "Error"
  3431.                 pass
  3432.         elif request.POST['type'] == 'send_feedback':
  3433.             a = FeedBack(content=request.POST['txt'], site=request.get_host())
  3434.             a.save()
  3435.             _id = 'Good!'
  3436.         elif get_field_without_somechars(request.POST['type']) == 'mass_add':
  3437.             json_data = json.loads(request.POST['data'])
  3438.             for item in json_data['items']:
  3439.                 price = get_object_or_404(Price, id=item['price'])
  3440.                 item = OrderItem(price=price, order=cart, count=item['count'])
  3441.                 item.save()
  3442.                 _id = item.id
  3443.         elif get_field_without_somechars(request.POST['type']) == 'one_add':
  3444.             added_id = request.POST.get('data', 0)
  3445.             if OrderItem.objects.filter(order=cart, price__id=added_id).count() == 1:
  3446.                 orderr = OrderItem.objects.get(order=cart, price__id=added_id)
  3447.                 orderr.count += 1
  3448.                 orderr.save()
  3449.                 _id = orderr.count
  3450.             else:
  3451.                 price = get_object_or_404(Price, id=added_id)
  3452.                 item = OrderItem(price=price, order=cart, count=1)
  3453.                 item.save()
  3454.                 _id = item.id
  3455.         elif get_field_without_somechars(request.POST['type']) == 'parser_add':
  3456.             price = OrderItem(price=request.POST['price'], order=cart, count=1)
  3457.         elif get_field_without_somechars(request.POST['type']) == 'get_user_cart_items':
  3458.             items = []
  3459.             for i in cart.item.all():
  3460.                 temp_price = 0
  3461.                 if i.price.price.currency != "RUB":  # сумма для заказа формируется ниже
  3462.                     a = Currency.objects.get(code="RUB").rate  # курс рубля
  3463.                     b = Currency.objects.get(code=i.price.price.currency).rate
  3464.                     temp_price = i.price.price.amount * b / a
  3465.                 else:
  3466.                     temp_price = i.price.price.amount
  3467.  
  3468.                 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)})
  3469.                 _id = json.dumps(items, ensure_ascii=False)
  3470.         return HttpResponse(text_type(_id))
  3471.  
  3472.     else:
  3473.         message = "Hello"
  3474.  
  3475.  
  3476. def fc(request):
  3477.     template = loader.get_template('fc/index.html')
  3478.  
  3479.     context_data = default_context(request, 'index', TextPage)
  3480.  
  3481.     context = RequestContext(request, context_data)
  3482.  
  3483.     return HttpResponse(template.render(context))
  3484.  
  3485.  
  3486. def updater(request):
  3487.     try:
  3488.         object_name = re.sub(r'[^\w\s]+|[\d]+|[_]{2}', r'', request.GET['type']).strip()
  3489.     except KeyError:
  3490.         return HttpResponse(u'Модель не определена!')
  3491.  
  3492.     sys.path.insert(0, os.path.join(django_settings.BASE_DIR, 'scripts'))
  3493.     import updater
  3494.  
  3495.     result = updater.init(object_name)
  3496.     return HttpResponse(result)
  3497.  
  3498.  
  3499. @csrf_exempt
  3500. def postupdater(request):
  3501.     try:
  3502.         object_name_m = re.sub(r'[^\w\s]+|[\d]+|[_]{2}', r'', request.POST['type']).strip()
  3503.     except KeyError:
  3504.         return HttpResponse(u'Модель не определена!')
  3505.  
  3506.     try:
  3507.         sys.path.insert(0, os.path.join(django_settings.BASE_DIR, 'scripts'))
  3508.         from umodels import init_rules
  3509.     except ImportError:
  3510.         return HttpResponse(u'Ошибка загрузки модуля "umodels"')
  3511.  
  3512.     result = u''
  3513.  
  3514.     object_name_arr = object_name_m.split(',')
  3515.     write_arr = force_unicode(request.POST.get('write', '')).split('@@')
  3516.  
  3517.     i = 0
  3518.     for object_name in object_name_arr:
  3519.         res = []
  3520.         if 'write' in request.POST:
  3521.             write = u''
  3522.  
  3523.             for wr in write_arr[i].split('::'):
  3524.                 write += u'\n\t' + wr
  3525.  
  3526.             _path = os.path.join(django_settings.BASE_DIR, 'scripts') + '/pr/' + object_name + '.pr'
  3527.             data = open(_path, 'w')
  3528.             write_obj = u'{"%s": [%s\n]}' % (object_name, write)
  3529.             data.write(write_obj.encode('utf-8'))
  3530.             data.close()
  3531.             os.chmod(_path, 0777)
  3532.  
  3533.         clb = init_rules(object_name)
  3534.         if isclass(clb) and hasattr(clb, 'run'):
  3535.             instance = clb(language=get_language() or 'ru')
  3536.             res = instance.run()
  3537.  
  3538.         for inst, created in res:
  3539.             result += u'"{}:{}" - {}\n'.format(
  3540.                 inst.__class__.__name__,
  3541.                 force_unicode(inst),
  3542.                 {True: u'создан', False: u'обновлен'}.get(created)
  3543.             )
  3544.  
  3545.         i += 1
  3546.     return HttpResponse(result)
  3547.  
  3548.  
  3549. # не работает(
  3550. def error_404(request):
  3551.     template = choose_template(request, "404")
  3552.  
  3553.     context_data = default_context(request, "error-404", TextPage)
  3554.  
  3555.     context = RequestContext(request, context_data)
  3556.  
  3557.     return HttpResponse(template.render(context))
  3558.  
  3559.  
  3560. # Карта сайта
  3561. class BaseSitemap(Sitemap):
  3562.     @cached_property
  3563.     def current_site(self):
  3564.         return Site.objects.get_current()
  3565.  
  3566.  
  3567. class StadiumSitemap(BaseSitemap):
  3568.     changefreq = "weekly"
  3569.     priority = 0.5
  3570.  
  3571.     def items(self):
  3572.         return Stadium.objects.filter(~Q(alias=None), host=self.current_site).all()
  3573.  
  3574.  
  3575. class GroupSitemap(BaseSitemap):
  3576.     changefreq = "weekly"
  3577.     priority = 0.5
  3578.  
  3579.     def items(self):
  3580.         return Group.objects.filter(~Q(alias=None), host=self.current_site).all()
  3581.  
  3582.  
  3583. class FedSitemap(BaseSitemap):
  3584.     changefreq = "weekly"
  3585.     priority = 0.5
  3586.  
  3587.     def items(self):
  3588.         return Fed.objects.filter(~Q(alias=None), host=self.current_site).all()
  3589.  
  3590.  
  3591. class ZayavkaSitemap(BaseSitemap):
  3592.     changefreq = "weekly"
  3593.     priority = 0.5
  3594.  
  3595.     def items(self):
  3596.         return Zayavka.objects.filter(~Q(alias=None), host=self.current_site).all()
  3597.  
  3598.  
  3599. class ChampSitemap(BaseSitemap):
  3600.     changefreq = "weekly"
  3601.     priority = 0.5
  3602.  
  3603.     def items(self):
  3604.         return Champ.objects.filter(~Q(alias=None), host=self.current_site).all()
  3605.  
  3606.  
  3607. class PlayerSitemap(BaseSitemap):
  3608.     changefreq = "weekly"
  3609.     priority = 0.5
  3610.  
  3611.     def items(self):
  3612.         return Player.objects.filter(~Q(team__alias=None), ~Q(alias=None), host=self.current_site).all()
  3613.  
  3614.  
  3615. class MatchSitemap(BaseSitemap):
  3616.     changefreq = "weekly"
  3617.     priority = 0.5
  3618.  
  3619.     def items(self):
  3620.         return Match.objects.filter(~Q(alias=None), host=self.current_site).all()
  3621.  
  3622.  
  3623. class TextPageSitemap(BaseSitemap):
  3624.     changefreq = "weekly"
  3625.     priority = 0.5
  3626.  
  3627.     def items(self):
  3628.         return TextPage.objects.filter(~Q(alias=None), host=self.current_site).all()
  3629.  
  3630.  
  3631. class TeamSitemap(BaseSitemap):
  3632.     changefreq = "weekly"
  3633.     priority = 0.5
  3634.  
  3635.     def items(self):
  3636.         return Team.objects.filter(~Q(alias=None), host=self.current_site).all()
  3637.  
  3638.  
  3639. class NewsSitemap(BaseSitemap):
  3640.     changefreq = "weekly"
  3641.     priority = 0.5
  3642.  
  3643.     def items(self):
  3644.         return News.objects.filter(~Q(alias=None), host=self.current_site).all()
  3645.  
  3646.  
  3647. def robots(request):
  3648.     # return render_to_response('robots.txt', content_type="text/plain")
  3649.     template = loader.get_template('robots.txt')
  3650.     # robots = get_object_or_404(Robots , name=request.get_host())
  3651.     alias = get_current_alias(request) or Alias.objects.first()
  3652.     robots = Robots.objects.filter(host=alias).first()
  3653.     data = getattr(robots, 'content', '')
  3654.  
  3655.     context = RequestContext(request, {
  3656.         'data': data,
  3657.     })
  3658.     return HttpResponse(template.render(context), content_type="text/plain")
  3659.  
  3660.  
  3661. def yandex_mail(request):
  3662.     template = loader.get_template('f1dbcc5c8003.html')
  3663.  
  3664.     context = RequestContext(request, {})
  3665.  
  3666.     return HttpResponse(template.render(context))
  3667.  
  3668.  
  3669. def yandex_verification(request, yandex_verification_number):
  3670.     template = loader.get_template('yandex_verification.html')
  3671.     context = RequestContext(request, {
  3672.         'yandex_verification_number': yandex_verification_number,
  3673.     })
  3674.     return HttpResponse(template.render(context))
  3675.  
  3676.  
  3677. def google_verification(request, google_verification_number):
  3678.     template = loader.get_template('google_verification.html')
  3679.     context = RequestContext(request, {
  3680.         'google_verification_number': google_verification_number,
  3681.     })
  3682.     return HttpResponse(template.render(context))
  3683.  
  3684.  
  3685. def mail_verification(request, mail_verification_number):
  3686.     template = loader.get_template('mail_verification.html')
  3687.     context = RequestContext(request, {
  3688.         'mail_verification_number': mail_verification_number,
  3689.     })
  3690.     return HttpResponse(template.render(context))
  3691.  
  3692.  
  3693. class Success(generic.DetailView):
  3694.     model = Order
  3695.     page = 'success'
  3696.     @property
  3697.     def template_name(self):
  3698.         tpl_path = '/'.join(
  3699.             filter(
  3700.                 None,
  3701.                 [{'mobile': 'mobile', 'full': ''}.get(get_flavour(self.request, '')), self.page]
  3702.             )
  3703.         )
  3704.         return '.'.join([tpl_path, 'html'])
  3705.  
  3706.     @property
  3707.     def token(self):
  3708.         return self.request.session.get(django_settings.CART_SESSION_ID)
  3709.  
  3710.     @token.deleter
  3711.     def token(self):
  3712.         self.request.session.pop(django_settings.CART_SESSION_ID)
  3713.  
  3714.     def get_object(self, queryset=None):
  3715.         if queryset is None:
  3716.             queryset = self.get_queryset()
  3717.         if self.token:
  3718.             queryset = queryset.filter(token=uuid.UUID(self.token)).first()
  3719.             del self.token
  3720.         return queryset
  3721.  
  3722.     def get_context_data(self, **kwargs):
  3723.         host_name = Site.objects.get_current()
  3724.         context = super(Success, self).get_context_data(**kwargs)
  3725.         context['menu'] = TextPage.objects.language(get_language()).order_by('menuposition').filter(
  3726.             ~Q(alias="index"), menushow=True, host=host_name
  3727.         )
  3728.         context['cur_site_url'] = host_name
  3729.         cur_site_url = self.request.get_host()
  3730.         try:
  3731.             if SiteSettings.objects.get(host__name=host_name):
  3732.                 if SiteSettings.objects.get(host__name=host_name):
  3733.                     curr_template = SiteTemplates.objects.get(settings=SiteSettings.objects.get(host__name=host_name),
  3734.                                                               domain__domain=cur_site_url).template
  3735.         except Exception:
  3736.             curr_template = '1'
  3737.             pass
  3738.  
  3739.         context['curr_template'] = curr_template
  3740.         return context
  3741.  
  3742.     def render_to_response(self, context, **resp_kw):
  3743.         if isinstance(context.get('object'), QuerySet):
  3744.             return HttpResponseRedirect(reverse_lazy('portal:index'))
  3745.         send_sms(self.object.phone,
  3746.                  gettext(u'Благодарим за заказ - #%(bin_id)s. Мы свяжемся с Вами в ближайшее время.') % dict(
  3747.                      bin_id=self.object.bin_id
  3748.                  ))
  3749.         return super(Success, self).render_to_response(context, **resp_kw)
  3750.  
  3751.  
  3752. class FailPage(Success):
  3753.     page = 'fail'
  3754.  
  3755.  
  3756. @x_robots_tag
  3757. def sitemap(request, sitemaps, section=None,
  3758.             template_name='sitemap.xml', content_type='application/xml'):
  3759.     req_protocol = request.scheme
  3760.     req_site = RequestSite(request)
  3761.  
  3762.     if section is not None:
  3763.         if section not in sitemaps:
  3764.             raise Http404("No sitemap available for section: %r" % section)
  3765.         maps = [sitemaps[section]]
  3766.     else:
  3767.         maps = sitemaps.values()
  3768.     page = request.GET.get("p", 1)
  3769.  
  3770.     urls = []
  3771.     for site in maps:
  3772.         try:
  3773.             if callable(site):
  3774.                 site = site()
  3775.             urls.extend(site.get_urls(page=page, site=req_site,
  3776.                                       protocol=req_protocol))
  3777.         except EmptyPage:
  3778.             raise Http404("Page %s empty" % page)
  3779.         except PageNotAnInteger:
  3780.             raise Http404("No page '%s'" % page)
  3781.     response = TemplateResponse(request, template_name, {'urlset': urls},
  3782.                                 content_type=content_type)
  3783.     if hasattr(site, 'latest_lastmod'):
  3784.         # if latest_lastmod is defined for site, set header so as
  3785.         # ConditionalGetMiddleware is able to send 304 NOT MODIFIED
  3786.         lastmod = site.latest_lastmod
  3787.         response['Last-Modified'] = http_date(
  3788.             timegm(
  3789.                 lastmod.utctimetuple() if isinstance(lastmod, datetime.datetime)
  3790.                 else lastmod.timetuple()
  3791.             )
  3792.         )
  3793.     return response
  3794.  
  3795.  
  3796. @user_passes_test(lambda u: u.is_superuser)
  3797. def clear_cache(request):
  3798.     cache.clear()
  3799.     LogEntry.objects.create(object_repr="Clear cache", action_flag=True, user=request.user)
  3800.     return HttpResponseRedirect(reverse_lazy('admin:index'))
  3801.  
  3802.  
  3803. '''
  3804. class PaymentResultSber(generic.View):
  3805.    def get(self, request):
  3806.        data = {"orderId": request.GET['orderId']}
  3807.  
  3808.        r = requests.post(django_settings.ACQUIRING_URL_SBER_RESULT, json=json.dumps(data),
  3809.                          headers={'Authorization': 'Token {}'.format(django_settings.ACQUIRING_TOKEN), })
  3810.        r_dict = json.loads(r.text)
  3811.  
  3812.        # order # bintranet_id, price
  3813.        # customer # email, phone,
  3814.        # tickets # price, count
  3815.        # host
  3816.  
  3817.        # Document Atol
  3818.        if r_dict['redirect'] == 'success_url':
  3819.            order = Order.objects.get(bin_id=r_dict["bintranet_id"])
  3820.            atol(
  3821.                bintranet_id=r_dict["bintranet_id"],
  3822.                total_price=order.sum,
  3823.                email=order.email,
  3824.                phone=order.phone,
  3825.                tickets=json.loads(order.tickets),
  3826.                host=django_settings.ATOL_SITE_HOST_IN_ACQUIRING
  3827.            )
  3828.  
  3829.            logger.info(json.loads(r.text))
  3830.  
  3831.            response = HttpResponseRedirect(
  3832.                reverse('portal:success'))  # +"?bintranet_id={}".format(transaction.cart_order.bintranet_id))
  3833.            # response.delete_cookie('cart_tickets')
  3834.            # response.delete_cookie('total_price')
  3835.            # response.delete_cookie('total_amount')
  3836.            return response
  3837.        else:
  3838.            return HttpResponseRedirect('/')
  3839.  
  3840. '''
  3841.  
  3842.  
  3843. def review_page(request):
  3844.     template = choose_template(request, "review_page")
  3845.  
  3846.     context_data = default_context(request, "review_page", TextPage)
  3847.     reviews = Reviews.objects.filter(published=True).order_by('id').reverse()
  3848.  
  3849.     context_data.update({
  3850.         'reviews': reviews,
  3851.     })
  3852.  
  3853.     context = RequestContext(request, context_data)
  3854.  
  3855.     return HttpResponse(template.render(context))
  3856.  
  3857.  
  3858. def services_page(request):
  3859.     template = choose_template(request, "services_page")
  3860.  
  3861.     context_data = default_context(request, "services_page", TextPage)
  3862.     context = RequestContext(request, context_data)
  3863.  
  3864.     return HttpResponse(template.render(context))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement