From 2663e08e2d556c53eaaf0c40f678b2e2f4eed1e1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?=
Date: Tue, 19 Jan 2021 22:08:54 +0100
Subject: [PATCH] trivial: apply black
---
auquotidien/auquotidien.py | 14 +-
.../modules/abelium_domino_workflow.py | 1 +
auquotidien/modules/admin.py | 22 +-
auquotidien/modules/backoffice.py | 2 +
auquotidien/modules/categories_admin.py | 63 ++++--
auquotidien/modules/clicrdv.py | 1 +
auquotidien/modules/formpage.py | 4 +
auquotidien/modules/myspace.py | 86 ++++----
auquotidien/modules/payments.py | 181 ++++++++++------
auquotidien/modules/payments_ui.py | 175 +++++++++-------
auquotidien/modules/root.py | 198 ++++++++++++------
auquotidien/modules/saml2.py | 93 ++++++--
auquotidien/modules/template.py | 4 +-
setup.py | 61 +++---
tests/test_admin_pages.py | 9 +
tests/test_backoffice_pages.py | 8 +-
tests/test_payment.py | 1 +
tests/test_user_pages.py | 6 +
tests/utilities.py | 6 +-
19 files changed, 603 insertions(+), 332 deletions(-)
diff --git a/auquotidien/auquotidien.py b/auquotidien/auquotidien.py
index 9a5384f..1ff3f10 100644
--- a/auquotidien/auquotidien.py
+++ b/auquotidien/auquotidien.py
@@ -27,9 +27,17 @@ rdb.register_menu_item('payments/', _('Payments'))
rdb.register_directory('settings', admin.SettingsDirectory())
import wcs.admin.forms
+
wcs.admin.forms.FormsDirectory.categories = categories_admin.CategoriesDirectory()
import wcs.categories
-wcs.categories.Category.XML_NODES = [('name', 'str'), ('url_name', 'str'),
- ('description', 'str'), ('position', 'int'),
- ('homepage_position', 'str'), ('redirect_url', 'str'), ('limit', 'int')]
+
+wcs.categories.Category.XML_NODES = [
+ ('name', 'str'),
+ ('url_name', 'str'),
+ ('description', 'str'),
+ ('position', 'int'),
+ ('homepage_position', 'str'),
+ ('redirect_url', 'str'),
+ ('limit', 'int'),
+]
diff --git a/auquotidien/modules/abelium_domino_workflow.py b/auquotidien/modules/abelium_domino_workflow.py
index 40737c7..7b301c1 100644
--- a/auquotidien/modules/abelium_domino_workflow.py
+++ b/auquotidien/modules/abelium_domino_workflow.py
@@ -1,4 +1,5 @@
from wcs.workflows import WorkflowStatusItem
+
class AbeliumDominoRegisterFamilyWorkflowStatusItem(WorkflowStatusItem):
key = 'abelium-domino-register-family'
diff --git a/auquotidien/modules/admin.py b/auquotidien/modules/admin.py
index 050f18d..6d2a986 100644
--- a/auquotidien/modules/admin.py
+++ b/auquotidien/modules/admin.py
@@ -36,13 +36,21 @@ class PanelDirectory(Directory):
def permissions(self):
permissions_cfg = get_cfg('aq-permissions', {})
form = Form(enctype='multipart/form-data')
- form.add(SingleSelectWidget, 'forms', title = _('Admin role for forms'),
- value = permissions_cfg.get('forms', None),
- options = [(None, _('Nobody'), None)] + get_user_roles())
+ form.add(
+ SingleSelectWidget,
+ 'forms',
+ title=_('Admin role for forms'),
+ value=permissions_cfg.get('forms', None),
+ options=[(None, _('Nobody'), None)] + get_user_roles(),
+ )
if get_publisher().has_site_option('auquotidien-payments'):
- form.add(SingleSelectWidget, 'payments', title = _('Admin role for payments'),
- value = permissions_cfg.get('payments', None),
- options = [(None, _('Nobody'), None)] + get_user_roles())
+ form.add(
+ SingleSelectWidget,
+ 'payments',
+ title=_('Admin role for payments'),
+ value=permissions_cfg.get('payments', None),
+ options=[(None, _('Nobody'), None)] + get_user_roles(),
+ )
form.add_submit('submit', _('Submit'))
form.add_submit('cancel', _('Cancel'))
@@ -58,6 +66,7 @@ class PanelDirectory(Directory):
return r.getvalue()
else:
from wcs.admin.settings import cfg_submit
+
cfg_submit(form, 'aq-permissions', ('forms', 'payments'))
return redirect('..')
@@ -83,4 +92,5 @@ class SettingsDirectory(wcs.admin.settings.SettingsDirectory):
return PanelDirectory()
return super(SettingsDirectory, self)._q_lookup(component)
+
from . import categories_admin
diff --git a/auquotidien/modules/backoffice.py b/auquotidien/modules/backoffice.py
index c4f3659..6367c53 100644
--- a/auquotidien/modules/backoffice.py
+++ b/auquotidien/modules/backoffice.py
@@ -17,6 +17,7 @@ from wcs.qommon.form import *
CURRENT_USER = object()
+
def check_visibility(target, user=CURRENT_USER):
if not get_publisher().has_site_option('auquotidien-%s' % target):
# option not explicitely enabled, -> off.
@@ -48,4 +49,5 @@ class BackofficeRootDirectory(wcs.backoffice.root.RootDirectory):
def home(self):
return redirect('management/')
+
get_publisher_class().backoffice_directory_class = BackofficeRootDirectory
diff --git a/auquotidien/modules/categories_admin.py b/auquotidien/modules/categories_admin.py
index 0a6d559..1e81cb6 100644
--- a/auquotidien/modules/categories_admin.py
+++ b/auquotidien/modules/categories_admin.py
@@ -26,6 +26,7 @@ from wcs.qommon.backoffice.menu import html_top
from wcs.qommon.admin.menu import command_icon, error_page
import wcs.admin.categories
+
class CategoryUI:
def __init__(self, category):
self.category = category
@@ -34,28 +35,47 @@ class CategoryUI:
def get_form(self):
form = Form(enctype='multipart/form-data')
- form.add(StringWidget, 'name', title = _('Category Name'), required = True, size=30,
- value = self.category.name)
- form.add(TextWidget, 'description', title = _('Description'), cols = 80, rows = 10,
- value = self.category.description)
+ form.add(
+ StringWidget, 'name', title=_('Category Name'), required=True, size=30, value=self.category.name
+ )
+ form.add(
+ TextWidget,
+ 'description',
+ title=_('Description'),
+ cols=80,
+ rows=10,
+ value=self.category.description,
+ )
homepage_redirect_url = get_cfg('misc', {}).get('homepage-redirect-url')
if not homepage_redirect_url:
- form.add(SingleSelectWidget, 'homepage_position',
- title=_('Position on homepage'),
- value=self.category.get_homepage_position(),
- options = [('1st', _('First Column')),
- ('2nd', _('Second Column')),
- ('side', _('Sidebar')),
- ('none', _('None'))])
- form.add(IntWidget, 'limit',
- title=_('Limit number of items displayed on homepage'),
- value=self.category.get_limit())
+ form.add(
+ SingleSelectWidget,
+ 'homepage_position',
+ title=_('Position on homepage'),
+ value=self.category.get_homepage_position(),
+ options=[
+ ('1st', _('First Column')),
+ ('2nd', _('Second Column')),
+ ('side', _('Sidebar')),
+ ('none', _('None')),
+ ],
+ )
+ form.add(
+ IntWidget,
+ 'limit',
+ title=_('Limit number of items displayed on homepage'),
+ value=self.category.get_limit(),
+ )
- form.add(StringWidget, 'redirect_url', size=32,
- title=_('URL Redirection'),
- hint=_('If set, redirect the site category page to the given URL.'),
- value=self.category.redirect_url)
+ form.add(
+ StringWidget,
+ 'redirect_url',
+ size=32,
+ title=_('URL Redirection'),
+ hint=_('If set, redirect the site category page to the given URL.'),
+ value=self.category.redirect_url,
+ )
form.add_submit('submit', _('Submit'))
form.add_submit('cancel', _('Cancel'))
@@ -66,7 +86,7 @@ class CategoryUI:
self.category.name = form.get_widget('name').parse()
category = self.category
else:
- category = Category(name = form.get_widget('name').parse())
+ category = Category(name=form.get_widget('name').parse())
name = form.get_widget('name').parse()
category_names = [x.name for x in Category.select() if x.id != category.id]
@@ -85,7 +105,6 @@ class CategoryUI:
category.store()
-
class CategoryPage(wcs.admin.categories.CategoryPage):
def __init__(self, component):
self.category = Category.get(component)
@@ -97,7 +116,7 @@ class CategoriesDirectory(wcs.admin.categories.CategoriesDirectory):
label = N_('Categories')
def new(self):
- get_response().breadcrumb.append( ('new', _('New')) )
+ get_response().breadcrumb.append(('new', _('New')))
category_ui = CategoryUI(None)
form = category_ui.get_form()
if form.get_widget('cancel').parse():
@@ -111,7 +130,7 @@ class CategoriesDirectory(wcs.admin.categories.CategoriesDirectory):
else:
return redirect('.')
- html_top('categories', title = _('New Category'))
+ html_top('categories', title=_('New Category'))
r = TemplateIO(html=True)
r += htmltext('%s
') % _('New Category')
r += form.render()
diff --git a/auquotidien/modules/clicrdv.py b/auquotidien/modules/clicrdv.py
index 4f1d229..b7636f8 100644
--- a/auquotidien/modules/clicrdv.py
+++ b/auquotidien/modules/clicrdv.py
@@ -2,6 +2,7 @@ class AppointmentPart(object):
def view(self):
return ''
+
class AppointmentErrorPart(object):
def view(self):
return ''
diff --git a/auquotidien/modules/formpage.py b/auquotidien/modules/formpage.py
index 11da23b..113e2bb 100644
--- a/auquotidien/modules/formpage.py
+++ b/auquotidien/modules/formpage.py
@@ -17,6 +17,7 @@ from wcs.qommon import emails
OldFormPage = wcs.forms.root.FormPage
+
class AlternateFormPage(OldFormPage):
def __call__(self):
# Fix missing trailing slash; lose query string on purpose.
@@ -31,6 +32,7 @@ class AlternateFormPage(OldFormPage):
get_response().filter['steps'] = form_side_html
return
+
wcs.forms.root.FormPage = AlternateFormPage
wcs.forms.root.PublicFormStatusPage.form_page_class = AlternateFormPage
wcs.forms.preview.PreviewFormPage.__bases__ = (AlternateFormPage,)
@@ -38,9 +40,11 @@ wcs.forms.preview.PreviewFormPage.__bases__ = (AlternateFormPage,)
OldFormsRootDirectory = wcs.forms.root.RootDirectory
+
class AlternateFormsRootDirectory(OldFormsRootDirectory):
def form_list(self, *args, **kwargs):
form_list = OldFormsRootDirectory.form_list(self, *args, **kwargs)
return htmltext(str(form_list).replace('h2>', 'h3>'))
+
wcs.forms.root.RootDirectory = AlternateFormsRootDirectory
diff --git a/auquotidien/modules/myspace.py b/auquotidien/modules/myspace.py
index f1498b5..ea7ce38 100644
--- a/auquotidien/modules/myspace.py
+++ b/auquotidien/modules/myspace.py
@@ -28,6 +28,7 @@ import wcs.myspace
from .payments import Invoice, Regie, is_payment_supported
+
class MyInvoicesDirectory(Directory):
_q_exports = ['']
@@ -49,8 +50,7 @@ class MyInvoicesDirectory(Directory):
r += get_session().display_message()
invoices = []
- invoices.extend(Invoice.get_with_indexed_value(
- str('user_id'), str(user.id)))
+ invoices.extend(Invoice.get_with_indexed_value(str('user_id'), str(user.id)))
invoices.sort(key=lambda x: (str(x.regie_id), -x.date.toordinal()))
last_regie_id = None
@@ -88,8 +88,10 @@ class MyInvoicesDirectory(Directory):
r += _('paid on %s') % misc.localstrftime(invoice.paid_date)
r += ' - '
button = _('Details')
- r += htmltext('%s' % (get_publisher().get_frontoffice_url(),
- invoice.id, button))
+ r += htmltext(
+ '%s'
+ % (get_publisher().get_frontoffice_url(), invoice.id, button)
+ )
r += htmltext('')
if last_regie_id:
@@ -102,8 +104,8 @@ class MyInvoicesDirectory(Directory):
class JsonDirectory(Directory):
- '''Export of several lists in json, related to the current user or the
- SAMLv2 NameID we'd get in the URL'''
+ """Export of several lists in json, related to the current user or the
+ SAMLv2 NameID we'd get in the URL"""
_q_exports = ['forms']
@@ -119,14 +121,12 @@ class JsonDirectory(Directory):
formdefs = FormDef.select(order_by='name', ignore_errors=True)
user_forms = []
for formdef in formdefs:
- user_forms.extend(formdef.data_class().get_with_indexed_value(
- 'user_id', self.user.id))
+ user_forms.extend(formdef.data_class().get_with_indexed_value('user_id', self.user.id))
epoch = time.localtime(1970)
user_forms.sort(key=lambda x: x.receipt_time or epoch)
get_response().set_content_type('application/json')
-
forms_output = []
for form in user_forms:
visible_status = form.get_visible_status(user=self.user)
@@ -136,21 +136,16 @@ class JsonDirectory(Directory):
name = form.formdef.name
id = form.get_display_id()
status = visible_status.name
- title = _('%(name)s #%(id)s (%(status)s)') % {
- 'name': name,
- 'id': id,
- 'status': status
- }
+ title = _('%(name)s #%(id)s (%(status)s)') % {'name': name, 'id': id, 'status': status}
url = form.get_url()
- d = { 'title': title, 'url': url }
+ d = {'title': title, 'url': url}
d.update(form.get_substitution_variables(minimal=True))
forms_output.append(d)
return json.dumps(forms_output, cls=misc.JSONEncoder)
class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
- _q_exports = ['', 'profile', 'new', 'password', 'remove', 'drafts', 'forms',
- 'invoices', 'json']
+ _q_exports = ['', 'profile', 'new', 'password', 'remove', 'drafts', 'forms', 'invoices', 'json']
invoices = MyInvoicesDirectory()
json = JsonDirectory()
@@ -161,15 +156,13 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
# Migrate custom text settings
texts_cfg = get_cfg('texts', {})
- if 'text-aq-top-of-profile' in texts_cfg and (
- not 'text-top-of-profile' in texts_cfg):
+ if 'text-aq-top-of-profile' in texts_cfg and (not 'text-top-of-profile' in texts_cfg):
texts_cfg['text-top-of-profile'] = texts_cfg['text-aq-top-of-profile']
del texts_cfg['text-aq-top-of-profile']
get_publisher().write_cfg()
return Directory._q_traverse(self, path)
-
def _q_index(self):
user = get_request().user
if not user:
@@ -186,8 +179,7 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
formdefs = FormDef.select(order_by='name', ignore_errors=True)
user_forms = []
for formdef in formdefs:
- user_forms.extend(formdef.data_class().get_with_indexed_value(
- 'user_id', user.id))
+ user_forms.extend(formdef.data_class().get_with_indexed_value('user_id', user.id))
epoch = time.localtime(1970)
user_forms.sort(key=lambda x: x.receipt_time or epoch)
@@ -223,15 +215,20 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
pass
else:
r += htmltext('')
- r += _('You can delete your account freely from the services portal. '
- 'This action is irreversible; it will destruct your personal '
- 'datas and destruct the access to your request history.')
- r += htmltext(' %s.') % _('Delete My Account')
+ r += _(
+ 'You can delete your account freely from the services portal. '
+ 'This action is irreversible; it will destruct your personal '
+ 'datas and destruct the access to your request history.'
+ )
+ r += htmltext(' %s.') % _(
+ 'Delete My Account'
+ )
r += htmltext('
')
if user_forms:
r += htmltext('') % _('My Forms')
from . import root
+
r += root.FormsRootDirectory().user_forms(user_forms)
return r.getvalue()
@@ -267,10 +264,14 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
ident_method = 'idp'
if form_data and ident_method != 'idp':
- r += htmltext('%s
') % _('Edit My Profile')
+ r += htmltext('%s
') % _(
+ 'Edit My Profile'
+ )
if ident_method == 'password' and passwords_cfg.get('can_change', False):
- r += htmltext('%s
') % _('Change My Password')
+ r += htmltext('%s
') % _(
+ 'Change My Password'
+ )
return r.getvalue()
@@ -279,9 +280,9 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
if not user or user.anonymous:
raise errors.AccessUnauthorizedError()
- form = Form(enctype = 'multipart/form-data')
+ form = Form(enctype='multipart/form-data')
formdef = user.get_formdef()
- formdef.add_fields_to_form(form, form_data = user.form_data)
+ formdef.add_fields_to_form(form, form_data=user.form_data)
form.add_submit('submit', _('Apply Changes'))
form.add_submit('cancel', _('Cancel'))
@@ -314,11 +315,9 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
if not user or user.anonymous:
raise errors.AccessUnauthorizedError()
- form = Form(enctype = 'multipart/form-data')
- form.add(PasswordWidget, 'new_password', title = _('New Password'),
- required=True)
- form.add(PasswordWidget, 'new2_password', title = _('New Password (confirm)'),
- required=True)
+ form = Form(enctype='multipart/form-data')
+ form.add(PasswordWidget, 'new_password', title=_('New Password'), required=True)
+ form.add(PasswordWidget, 'new2_password', title=_('New Password (confirm)'), required=True)
form.add_submit('submit', _('Change Password'))
form.add_submit('cancel', _('Cancel'))
@@ -351,7 +350,7 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
if not get_request().user or not get_request().user.anonymous:
raise errors.AccessUnauthorizedError()
- form = Form(enctype = 'multipart/form-data')
+ form = Form(enctype='multipart/form-data')
formdef = get_publisher().user_class.get_formdef()
if formdef:
formdef.add_fields_to_form(form)
@@ -376,15 +375,15 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
template.html_top(_('Welcome'))
return form.render()
-
def remove(self):
user = get_request().user
if not user or user.anonymous:
raise errors.AccessUnauthorizedError()
- form = Form(enctype = 'multipart/form-data')
- form.widgets.append(HtmlWidget('%s
' % _(
- 'Are you really sure you want to remove your account?')))
+ form = Form(enctype='multipart/form-data')
+ form.widgets.append(
+ HtmlWidget('%s
' % _('Are you really sure you want to remove your account?'))
+ )
form.add_submit('submit', _('Remove my account'))
form.add_submit('cancel', _('Cancel'))
@@ -394,7 +393,7 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
if form.is_submitted() and not form.has_errors():
user = get_request().user
account = PasswordAccount.get_on_index(user.id, str('user_id'))
- get_session_manager().expire_session()
+ get_session_manager().expire_session()
account.remove_self()
return redirect(get_publisher().get_root_url())
@@ -402,7 +401,4 @@ class MyspaceDirectory(wcs.myspace.MyspaceDirectory):
return form.render()
-TextsDirectory.register('aq-myspace-invoice',
- N_('Message on top of invoices page'),
- category = N_('Invoices'))
-
+TextsDirectory.register('aq-myspace-invoice', N_('Message on top of invoices page'), category=N_('Invoices'))
diff --git a/auquotidien/modules/payments.py b/auquotidien/modules/payments.py
index 3026ef0..ad94c81 100644
--- a/auquotidien/modules/payments.py
+++ b/auquotidien/modules/payments.py
@@ -8,8 +8,7 @@ from decimal import Decimal
from django.utils.six.moves.urllib import parse as urllib
-from quixote import (redirect, get_publisher, get_request, get_session,
- get_response)
+from quixote import redirect, get_publisher, get_request, get_session, get_response
from quixote.directory import Directory
from quixote.html import TemplateIO, htmltext
@@ -26,14 +25,14 @@ from wcs.qommon import _, N_
from wcs.qommon import force_str
from wcs.qommon import errors, get_logger, get_cfg, emails
from wcs.qommon.storage import StorableObject
-from wcs.qommon.form import htmltext, StringWidget, TextWidget, SingleSelectWidget, \
- WidgetDict
+from wcs.qommon.form import htmltext, StringWidget, TextWidget, SingleSelectWidget, WidgetDict
from wcs.qommon.misc import simplify
from wcs.formdef import FormDef
from wcs.formdata import Evolution
from wcs.workflows import WorkflowStatusItem, register_item_class, template_on_formdata
+
def is_payment_supported():
if not eopayment:
return False
@@ -49,8 +48,7 @@ class Regie(StorableObject):
service_options = None
def get_payment_object(self):
- return eopayment.Payment(kind=self.service,
- options=self.service_options)
+ return eopayment.Payment(kind=self.service, options=self.service_options)
class Invoice(StorableObject):
@@ -97,12 +95,14 @@ class Invoice(StorableObject):
r = random.SystemRandom()
self.fresh = True
while True:
- id = '-'.join([
- dt.now().strftime('%Y%m%d'),
- 'r%s' % (self.regie_id or 'x'),
- 'f%s' % (self.formdef_id or 'x'),
- ''.join([r.choice(string.digits) for x in range(5)])
- ])
+ id = '-'.join(
+ [
+ dt.now().strftime('%Y%m%d'),
+ 'r%s' % (self.regie_id or 'x'),
+ 'f%s' % (self.formdef_id or 'x'),
+ ''.join([r.choice(string.digits) for x in range(5)]),
+ ]
+ )
crc = '%0.2d' % (hashlib.md5(id.encode('utf-8')).digest()[0] % 100)
id = id + '-' + crc
if not self.has_key(id):
@@ -119,6 +119,7 @@ class Invoice(StorableObject):
return int(id[-2:]) == (hashlib.md5(id[:-3].encode('utf-8')).digest()[0] % 100)
except:
return False
+
check_crc = classmethod(check_crc)
def pay(self):
@@ -150,11 +151,16 @@ class Invoice(StorableObject):
INVOICE_EVO_VIEW = {
'create': N_('Create Invoice %(id)s: %(subject)s - %(amount)s €'),
- 'pay': N_('Invoice %(id)s is paid with transaction number %(transaction_order_id)s'),
+ 'pay': N_(
+ 'Invoice %(id)s is paid with transaction number %(transaction_order_id)s'
+ ),
'cancel': N_('Cancel Invoice %(id)s'),
- 'try': N_('Try paying invoice %(id)s with transaction number %(transaction_order_id)s'),
+ 'try': N_(
+ 'Try paying invoice %(id)s with transaction number %(transaction_order_id)s'
+ ),
}
+
class InvoiceEvolutionPart:
action = None
id = None
@@ -180,8 +186,9 @@ class InvoiceEvolutionPart:
return ''
if self.transaction:
vars['transaction_order_id'] = self.transaction.order_id
- return htmltext('' % self.action + \
- _(INVOICE_EVO_VIEW[self.action]) % vars + '
')
+ return htmltext(
+ '' % self.action + _(INVOICE_EVO_VIEW[self.action]) % vars + '
'
+ )
class Transaction(StorableObject):
@@ -206,8 +213,10 @@ class Transaction(StorableObject):
id = ''.join([r.choice(string.digits) for x in range(16)])
if not cls.has_key(id):
return id
+
get_new_id = classmethod(get_new_id)
+
class PaymentWorkflowStatusItem(WorkflowStatusItem):
description = N_('Payment Creation')
key = 'payment'
@@ -224,6 +233,7 @@ class PaymentWorkflowStatusItem(WorkflowStatusItem):
def is_available(self, workflow=None):
return is_payment_supported()
+
is_available = classmethod(is_available)
def render_as_line(self):
@@ -236,38 +246,49 @@ class PaymentWorkflowStatusItem(WorkflowStatusItem):
return _('Payable (not completed)')
def get_parameters(self):
- return ('subject', 'details', 'amount', 'regie_id', 'next_status',
- 'request_kwargs')
+ return ('subject', 'details', 'amount', 'regie_id', 'next_status', 'request_kwargs')
def add_parameters_widgets(self, form, parameters, prefix='', formdef=None):
if 'subject' in parameters:
- form.add(StringWidget, '%ssubject' % prefix, title=_('Subject'),
- value=self.subject, size=40)
+ form.add(StringWidget, '%ssubject' % prefix, title=_('Subject'), value=self.subject, size=40)
if 'details' in parameters:
- form.add(TextWidget, '%sdetails' % prefix, title=_('Details'),
- value=self.details, cols=80, rows=10)
+ form.add(
+ TextWidget, '%sdetails' % prefix, title=_('Details'), value=self.details, cols=80, rows=10
+ )
if 'amount' in parameters:
form.add(StringWidget, '%samount' % prefix, title=_('Amount'), value=self.amount)
if 'regie_id' in parameters:
- form.add(SingleSelectWidget, '%sregie_id' % prefix,
- title=_('Regie'), value=self.regie_id,
- options = [(None, '---')] + [(x.id, x.label) for x in Regie.select()])
+ form.add(
+ SingleSelectWidget,
+ '%sregie_id' % prefix,
+ title=_('Regie'),
+ value=self.regie_id,
+ options=[(None, '---')] + [(x.id, x.label) for x in Regie.select()],
+ )
if 'next_status' in parameters:
- form.add(SingleSelectWidget, '%snext_status' % prefix,
- title=_('Status after validation'), value = self.next_status,
- hint=_('Used only if the current status of the form does not contain any "Payment Validation" item'),
- options = [(None, '---')] + [(x.id, x.name) for x in self.parent.parent.possible_status])
+ form.add(
+ SingleSelectWidget,
+ '%snext_status' % prefix,
+ title=_('Status after validation'),
+ value=self.next_status,
+ hint=_(
+ 'Used only if the current status of the form does not contain any "Payment Validation" item'
+ ),
+ options=[(None, '---')] + [(x.id, x.name) for x in self.parent.parent.possible_status],
+ )
if 'request_kwargs' in parameters:
keys = ['name', 'email', 'address', 'phone', 'info1', 'info2', 'info3']
hint = ''
- hint +=_('If the value starts by = it will be '
- 'interpreted as a Python expression.')
+ hint += _('If the value starts by = it will be ' 'interpreted as a Python expression.')
hint += ' '
hint += _('Standard keys are: %s.') % (', '.join(keys))
- form.add(WidgetDict, 'request_kwargs',
+ form.add(
+ WidgetDict,
+ 'request_kwargs',
title=_('Parameters for the payment system'),
hint=hint,
- value = self.request_kwargs)
+ value=self.request_kwargs,
+ )
def perform(self, formdata):
invoice = Invoice(regie_id=self.regie_id, formdef_id=formdata.formdef.id)
@@ -278,8 +299,9 @@ class PaymentWorkflowStatusItem(WorkflowStatusItem):
invoice.subject = template_on_formdata(formdata, self.compute(self.subject))
else:
invoice.subject = _('%(form_name)s #%(formdata_id)s') % {
- 'form_name': formdata.formdef.name,
- 'formdata_id': formdata.id }
+ 'form_name': formdata.formdef.name,
+ 'formdata_id': formdata.id,
+ }
invoice.details = template_on_formdata(formdata, self.compute(self.details))
invoice.amount = Decimal(self.compute(self.amount))
invoice.date = dt.now()
@@ -300,8 +322,10 @@ class PaymentWorkflowStatusItem(WorkflowStatusItem):
# redirect the user to "my invoices"
return get_publisher().get_frontoffice_url() + '/myspace/invoices/'
+
register_item_class(PaymentWorkflowStatusItem)
+
class PaymentCancelWorkflowStatusItem(WorkflowStatusItem):
description = N_('Payment Cancel')
key = 'payment-cancel'
@@ -313,6 +337,7 @@ class PaymentCancelWorkflowStatusItem(WorkflowStatusItem):
def is_available(self, workflow=None):
return is_payment_supported()
+
is_available = classmethod(is_available)
def render_as_line(self):
@@ -332,13 +357,16 @@ class PaymentCancelWorkflowStatusItem(WorkflowStatusItem):
def add_parameters_widgets(self, form, parameters, prefix='', formdef=None):
if 'reason' in parameters:
- form.add(StringWidget, '%sreason' % prefix, title=_('Reason'),
- value=self.reason, size=40)
+ form.add(StringWidget, '%sreason' % prefix, title=_('Reason'), value=self.reason, size=40)
if 'regie_id' in parameters:
- form.add(SingleSelectWidget, '%sregie_id' % prefix,
- title=_('Regie'), value=self.regie_id,
- options = [(None, '---'), ('_all', _('All Regies'))] + \
- [(x.id, x.label) for x in Regie.select()])
+ form.add(
+ SingleSelectWidget,
+ '%sregie_id' % prefix,
+ title=_('Regie'),
+ value=self.regie_id,
+ options=[(None, '---'), ('_all', _('All Regies'))]
+ + [(x.id, x.label) for x in Regie.select()],
+ )
def perform(self, formdata):
invoices_id = []
@@ -356,8 +384,9 @@ class PaymentCancelWorkflowStatusItem(WorkflowStatusItem):
# security filter: check user
invoices = [i for i in invoices if i.user_id == formdata.user_id]
# security filter: check formdata & formdef
- invoices = [i for i in invoices if (i.formdata_id == formdata.id) \
- and (i.formdef_id == formdata.formdef.id)]
+ invoices = [
+ i for i in invoices if (i.formdata_id == formdata.id) and (i.formdef_id == formdata.formdef.id)
+ ]
evo = Evolution()
evo.time = time.localtime()
for invoice in invoices:
@@ -370,6 +399,7 @@ class PaymentCancelWorkflowStatusItem(WorkflowStatusItem):
formdata.store()
return get_publisher().get_frontoffice_url() + '/myspace/invoices/'
+
register_item_class(PaymentCancelWorkflowStatusItem)
@@ -377,8 +407,8 @@ def request_payment(invoice_ids, url, add_regie=True):
for invoice_id in invoice_ids:
if not Invoice.check_crc(invoice_id):
raise errors.QueryError()
- invoices = [ Invoice.get(invoice_id) for invoice_id in invoice_ids ]
- invoices = [ i for i in invoices if not (i.paid or i.canceled) ]
+ invoices = [Invoice.get(invoice_id) for invoice_id in invoice_ids]
+ invoices = [i for i in invoices if not (i.paid or i.canceled)]
regie_ids = set([invoice.regie_id for invoice in invoices])
# Do not apply if more than one regie is used or no invoice is not paid or canceled
if len(invoices) == 0 or len(regie_ids) != 1:
@@ -420,8 +450,7 @@ def request_payment(invoice_ids, url, add_regie=True):
evo = Evolution()
evo.time = time.localtime()
evo.status = formdata.status
- evo.add_part(InvoiceEvolutionPart('try', invoice,
- transaction=transaction))
+ evo.add_part(InvoiceEvolutionPart('try', invoice, transaction=transaction))
if not formdata.evolution:
formdata.evolution = []
formdata.evolution.append(evo)
@@ -434,15 +463,20 @@ def request_payment(invoice_ids, url, add_regie=True):
else:
raise NotImplementedError()
+
def return_eopayment_form(form):
r = TemplateIO(html=True)
r += htmltext('')
- r += htmltext('')
- cats = Category.select(order_by = 'name')
+ cats = Category.select(order_by='name')
cats = [x for x in cats if x.url_name != 'consultations' and x.get_homepage_position() == 'side']
Category.sort_by_position(cats)
if cats:
@@ -574,7 +635,9 @@ class AlternateRootDirectory(OldRootDirectory):
r += htmltext('%s
') % _('My Space')
r += htmltext('
'''
+ ),
+)
-TextsDirectory.register('aq-home-page', N_('Home Page'), wysiwyg = True)
+TextsDirectory.register('aq-home-page', N_('Home Page'), wysiwyg=True)
diff --git a/auquotidien/modules/saml2.py b/auquotidien/modules/saml2.py
index b670eb9..b63ef0a 100644
--- a/auquotidien/modules/saml2.py
+++ b/auquotidien/modules/saml2.py
@@ -9,8 +9,8 @@ import wcs.qommon.saml2
class Saml2Directory(wcs.qommon.saml2.Saml2Directory):
def extract_attributes(self, session, login):
- '''Separate attributes as two dictionaries: one for last value, one for
- the list of values.'''
+ """Separate attributes as two dictionaries: one for last value, one for
+ the list of values."""
d = {}
m = {}
@@ -59,7 +59,7 @@ class Saml2Directory(wcs.qommon.saml2.Saml2Directory):
# name field, this only works if there's a single field for the name
field_name_values = users_cfg.get('field_name')
if field_name_values:
- if type(field_name_values) is str: # it was a string in previous versions
+ if type(field_name_values) is str: # it was a string in previous versions
field_name_values = [field_name_values]
if len(field_name_values) == 1:
user.form_data[field_name_values[0]] = d.get('cn')
@@ -67,18 +67,81 @@ class Saml2Directory(wcs.qommon.saml2.Saml2Directory):
# other fields, matching is done on known LDAP attribute names and
# common variable names
extra_field_mappings = [
- ('gn', ('firstname', 'prenom')),
- ('givenName', ('firstname', 'prenom')),
- ('surname', ('surname', 'name', 'nom',)),
- ('sn', ('surname', 'name', 'nom',)),
- ('personalTitle', ('personalTitle', 'civilite',)),
- ('l', ('location', 'commune', 'ville',)),
- ('streetAddress', ('streetAddress', 'address', 'adresse', 'street',)),
- ('street', ('streetAddress', 'address', 'adresse', 'street',)),
- ('postalCode', ('postalCode', 'codepostal', 'cp',)),
- ('telephoneNumber', ('telephoneNumber', 'telephonefixe', 'telephone',)),
- ('mobile', ('mobile', 'telephonemobile',)),
- ('faxNumber', ('faxNumber', 'fax')),
+ ('gn', ('firstname', 'prenom')),
+ ('givenName', ('firstname', 'prenom')),
+ (
+ 'surname',
+ (
+ 'surname',
+ 'name',
+ 'nom',
+ ),
+ ),
+ (
+ 'sn',
+ (
+ 'surname',
+ 'name',
+ 'nom',
+ ),
+ ),
+ (
+ 'personalTitle',
+ (
+ 'personalTitle',
+ 'civilite',
+ ),
+ ),
+ (
+ 'l',
+ (
+ 'location',
+ 'commune',
+ 'ville',
+ ),
+ ),
+ (
+ 'streetAddress',
+ (
+ 'streetAddress',
+ 'address',
+ 'adresse',
+ 'street',
+ ),
+ ),
+ (
+ 'street',
+ (
+ 'streetAddress',
+ 'address',
+ 'adresse',
+ 'street',
+ ),
+ ),
+ (
+ 'postalCode',
+ (
+ 'postalCode',
+ 'codepostal',
+ 'cp',
+ ),
+ ),
+ (
+ 'telephoneNumber',
+ (
+ 'telephoneNumber',
+ 'telephonefixe',
+ 'telephone',
+ ),
+ ),
+ (
+ 'mobile',
+ (
+ 'mobile',
+ 'telephonemobile',
+ ),
+ ),
+ ('faxNumber', ('faxNumber', 'fax')),
]
for attribute_key, field_varnames in extra_field_mappings:
diff --git a/auquotidien/modules/template.py b/auquotidien/modules/template.py
index 2a1bdd0..e59a5d3 100644
--- a/auquotidien/modules/template.py
+++ b/auquotidien/modules/template.py
@@ -10,6 +10,7 @@ from wcs.categories import Category
wcs_error_page = template.error_page
wcs_get_decorate_vars = template.get_decorate_vars
+
def get_decorate_vars(body, response, generate_breadcrumb=True, template_context=None, **kwargs):
if template_context and 'form_side' in template_context:
# force rendering as it will put new variables in the context
@@ -30,7 +31,7 @@ def render_response(publisher, body):
body = str(body)
root_url = publisher.get_root_url()
- wcs_path = publisher.get_request().get_path()[len(root_url):]
+ wcs_path = publisher.get_request().get_path()[len(root_url) :]
section = wcs_path.split('/')[0]
if section in ('backoffice', 'admin'):
@@ -78,6 +79,7 @@ def error_page(*args, **kwargs):
get_response().filter['title'] = None
return htmltext('%s
' % title) + error_page + htmltext('')
+
template.error_page = error_page
template.get_decorate_vars = get_decorate_vars
get_publisher_class().render_response = render_response
diff --git a/setup.py b/setup.py
index 4da6058..9eda6ef 100644
--- a/setup.py
+++ b/setup.py
@@ -12,16 +12,17 @@ from setuptools import setup
def get_version():
- '''Use the VERSION, if absent generates a version with git describe, if not
- tag exists, take 0.0- and add the length of the commit log.
- '''
+ """Use the VERSION, if absent generates a version with git describe, if not
+ tag exists, take 0.0- and add the length of the commit log.
+ """
if os.path.exists('VERSION'):
with open('VERSION', 'r') as v:
return v.read()
if os.path.exists('.git'):
p = subprocess.Popen(
['git', 'describe', '--dirty=.dirty', '--match=v*'],
- stdout=subprocess.PIPE, stderr=subprocess.PIPE
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
)
result = p.communicate()[0]
if p.returncode == 0:
@@ -33,9 +34,7 @@ def get_version():
version = result
return version
else:
- return '0.0.post%s' % len(
- subprocess.check_output(
- ['git', 'rev-list', 'HEAD']).splitlines())
+ return '0.0.post%s' % len(subprocess.check_output(['git', 'rev-list', 'HEAD']).splitlines())
return '0.0'
@@ -44,7 +43,7 @@ def data_tree(destdir, sourcedir):
r = []
for root, dirs, files in os.walk(sourcedir):
l = [os.path.join(root, x) for x in files if os.path.splitext(x)[1] in extensions]
- r.append( (root.replace(sourcedir, destdir, 1), l) )
+ r.append((root.replace(sourcedir, destdir, 1), l))
if 'CVS' in dirs:
dirs.remove('CVS')
if '.svn' in dirs:
@@ -65,6 +64,7 @@ class compile_translations(Command):
def run(self):
try:
from django.core.management import call_command
+
for path, dirs, files in os.walk('auquotidien'):
if 'locale' not in dirs:
continue
@@ -87,7 +87,6 @@ class install_lib(_install_lib):
class eo_sdist(sdist):
-
def run(self):
print("creating VERSION file")
if os.path.exists('VERSION'):
@@ -101,21 +100,31 @@ class eo_sdist(sdist):
if os.path.exists('VERSION'):
os.remove('VERSION')
+
setup(
- name = 'wcs-au-quotidien',
- version = get_version(),
- maintainer = 'Frederic Peters',
- maintainer_email = 'fpeters@entrouvert.com',
- package_dir = {'auquotidien': 'auquotidien'},
- packages = ['auquotidien', 'auquotidien.modules'],
- cmdclass={'build': build,
- 'compile_translations': compile_translations,
- 'install_lib': install_lib,
- 'sdist': eo_sdist},
- include_package_data=True,
- data_files = data_tree('share/wcs/texts', 'texts') +\
- data_tree('share/wcs/themes/auquotidien', 'theme') +\
- data_tree('share/wcs/themes/', 'data/themes/') + \
- data_tree('share/auquotidien/apache-errors', 'apache-errors') +\
- [('share/wcs/', ['au-quotidien-wcs-settings.xml',])]
- )
+ name='wcs-au-quotidien',
+ version=get_version(),
+ maintainer='Frederic Peters',
+ maintainer_email='fpeters@entrouvert.com',
+ package_dir={'auquotidien': 'auquotidien'},
+ packages=['auquotidien', 'auquotidien.modules'],
+ cmdclass={
+ 'build': build,
+ 'compile_translations': compile_translations,
+ 'install_lib': install_lib,
+ 'sdist': eo_sdist,
+ },
+ include_package_data=True,
+ data_files=data_tree('share/wcs/texts', 'texts')
+ + data_tree('share/wcs/themes/auquotidien', 'theme')
+ + data_tree('share/wcs/themes/', 'data/themes/')
+ + data_tree('share/auquotidien/apache-errors', 'apache-errors')
+ + [
+ (
+ 'share/wcs/',
+ [
+ 'au-quotidien-wcs-settings.xml',
+ ],
+ )
+ ],
+)
diff --git a/tests/test_admin_pages.py b/tests/test_admin_pages.py
index b764a47..222178b 100644
--- a/tests/test_admin_pages.py
+++ b/tests/test_admin_pages.py
@@ -23,6 +23,7 @@ from wcs import fields
from utilities import get_app, login, create_temporary_pub
+
def setup_module(module):
cleanup()
@@ -35,6 +36,7 @@ def setup_module(module):
pub.cfg['identification'] = {'methods': ['password']}
pub.write_cfg()
+
def create_superuser():
global user1
if pub.user_class.has_key('admin'):
@@ -56,19 +58,23 @@ def create_superuser():
pub.cfg['identification'] = {'methods': ['password']}
pub.write_cfg()
+
def create_role():
Role.wipe()
role = Role(name='foobar')
role.store()
return role
+
def teardown_module(module):
shutil.rmtree(pub.APP_DIR)
+
@pytest.fixture
def empty_siteoptions():
open(os.path.join(pub.app_dir, 'site-options.cfg'), 'w').close()
+
def test_with_superuser():
create_superuser()
app = login(get_app(pub))
@@ -76,6 +82,7 @@ def test_with_superuser():
# this makes sure the extension loaded properly
assert 'Publik' in resp.text
+
def test_general_admin_permissions():
create_superuser()
app = login(get_app(pub))
@@ -89,6 +96,7 @@ def test_general_admin_permissions():
del pub.cfg['admin-permissions']
pub.write_cfg()
+
def test_aq_permissions_panel(empty_siteoptions):
create_superuser()
app = login(get_app(pub))
@@ -105,6 +113,7 @@ def test_aq_permissions_panel(empty_siteoptions):
assert 'aq/permissions' in resp.text
resp = app.get('/backoffice/settings/aq/permissions')
+
def test_menu_items(empty_siteoptions):
create_superuser()
role = create_role()
diff --git a/tests/test_backoffice_pages.py b/tests/test_backoffice_pages.py
index ccc90b2..af6c85d 100644
--- a/tests/test_backoffice_pages.py
+++ b/tests/test_backoffice_pages.py
@@ -18,6 +18,7 @@ from wcs import fields
from utilities import get_app, login, create_temporary_pub
+
def setup_module(module):
cleanup()
@@ -30,6 +31,7 @@ def setup_module(module):
pub.cfg['identification'] = {'methods': ['password']}
pub.write_cfg()
+
def create_agent():
if pub.user_class.has_key('agent'):
return
@@ -48,6 +50,7 @@ def create_agent():
return user1
+
def create_role():
Role.wipe()
role = Role(name='foobar')
@@ -55,9 +58,11 @@ def create_role():
role.store()
return role
+
def teardown_module(module):
shutil.rmtree(pub.APP_DIR)
+
def test_with_agent():
user = create_agent()
app = login(get_app(pub), username='agent', password='agent')
@@ -71,6 +76,7 @@ def test_with_agent():
# check user is automatically redirected to management/
assert resp.location == 'http://example.net/backoffice/management/'
+
def test_with_agent_submitter():
user = create_agent()
role = create_role()
@@ -89,7 +95,7 @@ def test_with_agent_submitter():
formdef.backoffice_submission_roles = [role.id]
formdef.store()
- resp = app.get('/backoffice/', status=200) # no redirect
+ resp = app.get('/backoffice/', status=200) # no redirect
# check the management and submission links are presend twice, once in the
# sidebar and once in the page body
assert resp.text.count('//example.net/backoffice/management/') == 2
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 558ef93..4ca7eab 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -6,6 +6,7 @@ from auquotidien.modules import payments
from utilities import get_app, login, create_temporary_pub
+
def setup_module(module):
cleanup()
diff --git a/tests/test_user_pages.py b/tests/test_user_pages.py
index 8e7b3c0..d235261 100644
--- a/tests/test_user_pages.py
+++ b/tests/test_user_pages.py
@@ -18,6 +18,7 @@ from wcs import fields
from utilities import get_app, login, create_temporary_pub
+
def setup_module(module):
cleanup()
@@ -30,6 +31,7 @@ def setup_module(module):
pub.cfg['identification'] = {'methods': ['password']}
pub.write_cfg()
+
def create_user():
if pub.user_class.has_key('user'):
return
@@ -48,6 +50,7 @@ def create_user():
return user1
+
def create_formdef():
FormDef.wipe()
formdef = FormDef()
@@ -56,15 +59,18 @@ def create_formdef():
formdef.store()
return formdef
+
def teardown_module(module):
shutil.rmtree(pub.APP_DIR)
+
def test_with_user():
user = create_user()
app = login(get_app(pub), username='user', password='user')
resp = app.get('/', status=200)
resp = app.get('/myspace/', status=200)
+
def test_myspace_with_user_forms():
user = create_user()
formdef = create_formdef()
diff --git a/tests/utilities.py b/tests/utilities.py
index 18f8433..5c0e3a7 100644
--- a/tests/utilities.py
+++ b/tests/utilities.py
@@ -16,12 +16,14 @@ import wcs.middleware
wcs.middleware.AfterJobsMiddleware.ASYNC = False
+
def create_temporary_pub():
config = ConfigParser.ConfigParser()
APP_DIR = tempfile.mkdtemp()
compat.CompatWcsPublisher.APP_DIR = APP_DIR
compat.CompatWcsPublisher.DATA_DIR = os.path.abspath(
- os.path.join(os.path.dirname(wcs.__file__), '..', 'data'))
+ os.path.join(os.path.dirname(wcs.__file__), '..', 'data')
+ )
compat.CompatWcsPublisher.cronjobs = None
config.add_section('extra')
config.set('extra', 'auquotidien', os.path.join(os.path.dirname(__file__), '..', 'auquotidien'))
@@ -34,6 +36,7 @@ def create_temporary_pub():
os.mkdir(pub.app_dir)
return pub
+
def get_app(pub, https=False):
extra_environ = {'HTTP_HOST': 'example.net', 'REMOTE_ADDR': '127.0.0.1'}
if https:
@@ -43,6 +46,7 @@ def get_app(pub, https=False):
extra_environ['HTTPS'] = 'off'
return TestApp(wcs.wsgi.application, extra_environ=extra_environ)
+
def login(app, username='admin', password='admin'):
login_page = app.get('/login/')
login_form = login_page.forms['login-form']