You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
280 lines
11 KiB
280 lines
11 KiB
# -*- coding: utf-8 -*-
|
|
import os
|
|
import json
|
|
import tempfile
|
|
from email.header import Header
|
|
|
|
from django.shortcuts import render, redirect, get_object_or_404
|
|
from django.core.files import File
|
|
from django.views.decorators.csrf import csrf_protect
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.template.loader import render_to_string
|
|
from django.core.mail import EmailMessage
|
|
from django.utils.encoding import smart_str
|
|
from django.conf import settings
|
|
from django.http import Http404, HttpResponse
|
|
|
|
# from sorl.thumbnail import get_thumbnail
|
|
from easy_thumbnails.files import get_thumbnailer
|
|
|
|
from project.commons.pdf_tools import render_pdf_to_string, pdf_to_response
|
|
|
|
from .. import models, forms
|
|
from ..decorators import license_required
|
|
from ..utils import raise_if_no_profile
|
|
|
|
|
|
PDF_PROFILE_NAME = u'Реквизиты.pdf'
|
|
SUPPORT_EMAIL = getattr(settings, 'SUPPORT_EMAIL', '')
|
|
|
|
|
|
# -----------------------------------------------------------------------------
|
|
|
|
@login_required
|
|
@csrf_protect
|
|
def profile_view(request):
|
|
"""Просмотр профиля пользователя, фильтрация реквизитов, скачать/отправить реквизиты по почте."""
|
|
raise_if_no_profile(request)
|
|
|
|
template_name = 'customer/profile/view.html'
|
|
|
|
profile = request.user.profile
|
|
|
|
accounts = models.BankAccount.objects.get_all(profile)
|
|
|
|
filters_form_class = forms.get_profile_filters_form_class(profile.profile_type)
|
|
filters = models.UserProfileFilters.objects.get_or_create_filters(user=request.user)
|
|
|
|
if request.method == 'POST':
|
|
filters_form = filters_form_class(data=request.POST, instance=filters, profile=profile, accounts=accounts)
|
|
if filters_form.is_valid():
|
|
filters = filters_form.save()
|
|
|
|
if 'download-pdf' in request.POST:
|
|
#return _profile_get_pdf(request, profile, filters.bank_account, filters) # для отладки
|
|
return profile_as_pdf(request, profile, filters.bank_account, filters)
|
|
elif 'email-pdf' in request.POST:
|
|
return redirect('customer_profile_email')
|
|
|
|
return redirect('customer_profile_view') # редирект на себя, чтобы не сабмитили форму по F5
|
|
else:
|
|
filters_form = filters_form_class(instance=filters, label_suffix='', profile=profile, accounts=accounts)
|
|
|
|
dictionary = {
|
|
'profile': profile,
|
|
'accounts': accounts,
|
|
'filters_form': filters_form,
|
|
'email_profile_form': forms.EmailProfileForm(),
|
|
}
|
|
return render(request, template_name, dictionary)
|
|
|
|
|
|
@login_required
|
|
@csrf_protect
|
|
def profile_edit(request):
|
|
"""Редактировать профиль пользователя."""
|
|
raise_if_no_profile(request)
|
|
|
|
template_name = 'customer/profile/edit.html'
|
|
success_url = 'customer_profile_view'
|
|
|
|
if request.method == 'POST' and '_cancel' in request.POST:
|
|
return redirect(success_url)
|
|
|
|
profile = request.user.profile
|
|
|
|
form_class = forms.get_profile_form_class(profile.profile_type)
|
|
|
|
accounts = models.BankAccount.objects.get_all(profile)
|
|
bank_account_form = forms.BankAccountForm(initial={'company': profile})
|
|
|
|
if request.method == 'POST':
|
|
form = form_class(data=request.POST, files=request.FILES, instance=profile)
|
|
if form.is_valid():
|
|
item = form.save(commit=False)
|
|
for img_url in ('tmb_logo', 'tmb_boss_sign', 'tmb_glavbuh_sign', 'tmb_stamp'):
|
|
if form.cleaned_data[img_url]:
|
|
chg_file = open(settings.MEDIA_ROOT + '/cache/imgs/' + \
|
|
form.cleaned_data[img_url])
|
|
item_attr = img_url[4:]
|
|
getattr(item, item_attr).save('%s.%s' % \
|
|
(item_attr, form.cleaned_data[img_url].split('.')[-1]),
|
|
File(chg_file))
|
|
chg_file.close()
|
|
elif form.cleaned_data:
|
|
pass
|
|
item.save()
|
|
return redirect(success_url)
|
|
else:
|
|
form = form_class(instance=profile)
|
|
|
|
dictionary = {
|
|
'form': form,
|
|
'profile': profile,
|
|
'accounts': accounts,
|
|
'bank_account_form': bank_account_form,
|
|
}
|
|
return render(request, template_name, dictionary)
|
|
|
|
|
|
def tmp_upload(request):
|
|
SIZES = {'id_boss_sign': (170, 65), 'id_glavbuh_sign': (170, 65), 'id_stamp': (170, 170), 'id_logo': (170, 170)}
|
|
elm_id = request.REQUEST['elm_id']
|
|
file_ = request.FILES.values()[0]
|
|
if not file_.content_type.startswith('image'):
|
|
return {'res': 'bad'}
|
|
|
|
if not os.path.exists(settings.MEDIA_ROOT +
|
|
'/cache/imgs/'):
|
|
os.makedirs(settings.MEDIA_ROOT +
|
|
'/cache/imgs/')
|
|
|
|
tmp_dir = tempfile.mkdtemp('img_tmp', settings.MEDIA_ROOT +
|
|
'/cache/imgs/')
|
|
os.chmod(tmp_dir, 0755)
|
|
open(tmp_dir + '/' + file_.name, "w").write(file_.read())
|
|
tmp_url_partial = os.path.basename(tmp_dir) + '/' + file_.name
|
|
thumbnailer = get_thumbnailer(tmp_dir + '/' + file_.name)
|
|
# im = get_thumbnail(tmp_dir + '/' + file_.name, SIZES[elm_id], quality=75)
|
|
thumbnail_options = {'size': SIZES[elm_id]}
|
|
im = thumbnailer.get_thumbnail(thumbnail_options) # Возвращает в url полный путь, поэтому придётся резать
|
|
im_url = os.path.join(settings.MEDIA_URL, os.path.relpath(im.url, settings.MEDIA_ROOT))
|
|
data = {'res': 'ok', 'pic': im_url, 'full_pic': tmp_url_partial}
|
|
data.update(request.REQUEST)
|
|
return HttpResponse(json.dumps(data), mimetype='application/json')
|
|
|
|
|
|
def del_tmp_photo(request, article_pk):
|
|
# wedding, wedding_guests = get_wedding_n_guests(request)
|
|
try:
|
|
pass
|
|
# article = WedPage.objects.get(pk=article_pk)
|
|
# article.main_photo.delete()
|
|
except:
|
|
return {'res': 'bad'}
|
|
|
|
return {'res': 'ok'}
|
|
|
|
|
|
@login_required
|
|
def _profile_get_pdf(request, profile=None, account=None, filters=None):
|
|
"""Создать профиль пользователя в PDF и вернуть как строку."""
|
|
template_name = 'customer/profile/as_pdf.html'
|
|
dictionary = {
|
|
'profile': profile,
|
|
'account': account,
|
|
'filters': filters,
|
|
}
|
|
return render_pdf_to_string(request, template_name, dictionary)
|
|
|
|
|
|
@login_required
|
|
def profile_as_pdf(request, profile=None, account=None, filters=None):
|
|
"""Вывести профиль пользователя в формате PDF в HttpResponse."""
|
|
pdf = _profile_get_pdf(request, profile, account, filters)
|
|
return pdf_to_response(pdf, PDF_PROFILE_NAME)
|
|
|
|
|
|
def _send_profile_email(subject, to, body, pdf_content):
|
|
"""Отправка письма."""
|
|
template_name = 'customer/profile/profile_email.txt'
|
|
dict_context = {'body': body, 'support_email': SUPPORT_EMAIL}
|
|
email_body = render_to_string(template_name, dict_context)
|
|
email = EmailMessage(
|
|
subject=subject,
|
|
to=(to,),
|
|
body=email_body,
|
|
attachments = [(smart_str(Header(PDF_PROFILE_NAME, 'cp1251')), pdf_content, 'application/pdf'),]
|
|
)
|
|
return email.send()
|
|
|
|
|
|
@login_required
|
|
@login_required
|
|
@csrf_protect
|
|
def profile_email(request):
|
|
"""Форма отправки профиля пользователя на email аттачем в PDF."""
|
|
raise_if_no_profile(request)
|
|
|
|
template_name = 'customer/profile/email.html'
|
|
success_url = 'customer_profile_view'
|
|
|
|
form_class = forms.EmailProfileForm
|
|
|
|
if request.method == 'POST' and '_cancel' in request.POST:
|
|
return redirect('customer_profile_view')
|
|
|
|
profile = request.user.profile
|
|
|
|
filters = models.UserProfileFilters.objects.get_or_create_filters(user=request.user)
|
|
|
|
if request.method == 'POST':
|
|
form = form_class(data=request.POST)
|
|
if form.is_valid():
|
|
_send_profile_email(
|
|
subject = u'Реквизиты %s' % profile.get_company_name(),
|
|
to = form.cleaned_data['to'],
|
|
body = form.cleaned_data['body'],
|
|
pdf_content = _profile_get_pdf(request, profile, filters.bank_account, filters)
|
|
)
|
|
return redirect(success_url)
|
|
else:
|
|
form = form_class()
|
|
|
|
return render(request, template_name, {'form': form, 'profile': profile,})
|
|
|
|
|
|
#@login_required
|
|
#@csrf_protect
|
|
#def profile_settings(request):
|
|
# """Редактировать настройки пользователя."""
|
|
# template_name='customer/profile/settings.html'
|
|
#
|
|
# profile = get_object_or_404(models.UserProfile, user=request.user)
|
|
# form_class = forms.UserProfileSettingsForm #TODO remove this view
|
|
#
|
|
# # пути к уже загруженным подписям/штампу
|
|
# curr_files = {'boss_sign': None, 'glavbuh_sign': None, 'stamp': None,}
|
|
# if profile.boss_sign:
|
|
# curr_files['boss_sign'] = profile.boss_sign.path
|
|
# if profile.glavbuh_sign:
|
|
# curr_files['glavbuh_sign'] = profile.glavbuh_sign.path
|
|
# if profile.stamp:
|
|
# curr_files['stamp'] = profile.stamp.path
|
|
#
|
|
# if request.method == "POST" and '_cancel' not in request.POST:
|
|
# post = request.POST
|
|
# files = request.FILES
|
|
# form = form_class(user=request.user, data=post, files=files, instance=profile)
|
|
#
|
|
# if form.is_valid():
|
|
# def delete_file(path):
|
|
# """Удалить файл. Если ошибка - сообщить в консоль."""
|
|
# try:
|
|
# os.remove(path)
|
|
# except:
|
|
# print "Can't delete file:", path
|
|
# # --- удалить старые файлы
|
|
# for field, path in curr_files.iteritems():
|
|
# if not path:
|
|
# continue
|
|
# # если стоит галочка 'очистить'
|
|
# if '%s-clear' % field in post:
|
|
# delete_file(path)
|
|
# continue
|
|
# # если загружен новый файл
|
|
# if field in files:
|
|
# delete_file(path)
|
|
# continue
|
|
# # --- изменить пароль
|
|
# if 'new_password1' in post:
|
|
# request.user.set_password(post.get('new_password1'))
|
|
# request.user.save()
|
|
# messages.add_message(request, messages.INFO, u'Пароль успешно изменен.')
|
|
#
|
|
# form.save()
|
|
# return redirect('customer_profile_settings')
|
|
# else:
|
|
# form = form_class(user=request.user, instance=profile)
|
|
#
|
|
# return render(request, template_name, {'profile': profile, 'form': form,})
|
|
|