Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Atende plonegovbr/portalpadrao.release#11 #36

Merged
merged 2 commits into from
Oct 11, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,24 @@ sudo: false
cache:
directories:
- eggs
- parts/node
env:
- PLONE_VERSION=4.2
- PLONE_VERSION=4.3
matrix:
- PLONE_VERSION=4.2
# Nos demais pacotes plonegovbr, como não testo as versões além do Plone
# 4.3 (ou seja, por padrão testo sõ a 4.3), não uso a variável
# PLONE_VERSION, apenas a MASTER e a PENDING_RELEASE.
- PLONE_VERSION=4.3 MASTER=true
- PLONE_VERSION=4.3 PENDING_RELEASE=true
matrix:
allow_failures:
- env: PLONE_VERSION=4.2
- env: PLONE_VERSION=4.3 MASTER=true
fast_finish: true
install:
# Remova a linha que aponta para o versions do novo release, por padrão 4.3,
# se o job for o 4.2 ou o que tem que pegar do master.
- test "$MASTER" -o "$PLONE_VERSION" = 4.2 && sed -ie '/https:\/\/raw\.githubusercontent\.com\/plonegovbr\/portal\.buildout\/master\/buildout\.d\/versions\.cfg/d' buildout.cfg || true
- sed -ie "s#test-4.3#test-$PLONE_VERSION#" buildout.cfg
- python bootstrap.py
- bin/buildout annotate
Expand All @@ -20,6 +34,8 @@ script:
- bin/code-analysis
- bin/test
after_success:
# vcge, no momento, não possui testes do tipo "Robots", ao contrário dos
# demais pacotes em plonegovbr.
- bin/createcoverage -t "--layer=!Robot"
- pip install coveralls
- coveralls
Expand Down
1 change: 1 addition & 0 deletions buildout.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
extends =
https://raw.github.com/collective/buildout.plonetest/master/test-4.3.x.cfg
https://raw.github.com/collective/buildout.plonetest/master/qa.cfg
https://raw.githubusercontent.com/plonegovbr/portal.buildout/master/buildout.d/versions.cfg

package-name = brasil.gov.vcge
package-extras = [test, archetypes, dexterity]
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
zip_safe=False,
install_requires=[
'Plone >=4.2',
'plone.api',
'collective.z3cform.widgets',
'raptus.autocompletewidget',
'rdflib',
Expand Down
14 changes: 6 additions & 8 deletions src/brasil/gov/vcge/at/extender.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from Products.Archetypes import public as atapi
from Products.Archetypes.interfaces import IBaseContent
from raptus.autocompletewidget.widget import AutocompleteMultiSelectionWidget
from zope.component import adapts
from zope.interface import implements
from zope.component import adapter
from zope.interface import implementer

AcMSW = AutocompleteMultiSelectionWidget

Expand All @@ -18,17 +18,15 @@ class ExtensionLinesField(ExtensionField, atapi.LinesField):
"""


# Este adaptador sera aplicado a todos os tipos baseados em Archetypes
@adapter(IBaseContent)
# We use both orderable and browser layer aware sensitive properties
@implementer(IBrowserLayerAwareExtender)
class VCGEExtender(object):
""" Adaptador que extende os tipos de conteudo base do Plone
com o campo skos (representando o VCGE)
"""

# Este adaptador sera aplicado a todos os tipos baseados em Archetypes
adapts(IBaseContent)

# We use both orderable and browser layer aware sensitive properties
implements(IBrowserLayerAwareExtender)

layer = IVCGEInstalado

fields = [
Expand Down
9 changes: 6 additions & 3 deletions src/brasil/gov/vcge/browser/viewlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from Acquisition import aq_base
from Acquisition import aq_inner
from plone.app.layout.viewlets import ViewletBase
from Products.CMFPlone.utils import safe_hasattr
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from urllib import urlencode
from zope.component import queryUtility
Expand All @@ -27,7 +28,7 @@ def skos(self):
'''
context = aq_base(aq_inner(self.context))
uris = []
if hasattr(context, 'skos'):
if safe_hasattr(context, 'skos'):
uris = self.context.skos or []
name = 'brasil.gov.vcge'
util = queryUtility(IVocabularyFactory, name)
Expand All @@ -38,8 +39,10 @@ def skos(self):
params = urlencode({'skos:list': uri})
skos.append({'id': uri,
'title': title,
'url': '%s/@@search?%s' % (self.nav_root_url,
params)})
'url': '{0}/@@search?{1}'.format(
self.nav_root_url,
params
)})
return skos

def rel(self):
Expand Down
6 changes: 3 additions & 3 deletions src/brasil/gov/vcge/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding:utf-8 -*-
from Products.CMFPlone import interfaces as plone_interfaces
from Products.CMFQuickInstallerTool import interfaces as qi_interfaces
from zope.interface import implements
from zope.interface import implementer

PROJECTNAME = 'brasil.gov.vcge'

Expand All @@ -10,19 +10,19 @@
NAMESPACE = 'http://www.w3.org/2004/02/skos/core#'


@implementer(qi_interfaces.INonInstallable)
class HiddenProducts(object):
""" Oculta produtos do QuickInstaller """
implements(qi_interfaces.INonInstallable)

def getNonInstallableProducts(self):
return [
'brasil.gov.vcge.upgrades.v2000',
]


@implementer(plone_interfaces.INonInstallable)
class HiddenProfiles(object):
""" Oculta profiles da tela inicial de criacao do site """
implements(plone_interfaces.INonInstallable)

def getNonInstallableProfiles(self):
return [
Expand Down
10 changes: 5 additions & 5 deletions src/brasil/gov/vcge/contentrules/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
from plone.app.contentrules.browser.formhelper import EditForm
from plone.contentrules.rule.interfaces import IExecutable
from plone.contentrules.rule.interfaces import IRuleElementData
from zope.component import adapts
from zope.component import adapter
from zope.formlib import form
from zope.interface import implements
from zope.interface import implementer
from zope.interface import Interface
from zope.schema import Bool
from zope.schema import Choice
Expand Down Expand Up @@ -41,10 +41,10 @@ class IVCGEAction(Interface):
value_type=Choice(vocabulary=VOCAB))


@implementer(IVCGEAction, IRuleElementData)
class VCGEAction(SimpleItem):
""" A implementacao persistente para a acao VCGE
"""
implements(IVCGEAction, IRuleElementData)

element = 'brasil.gov.vcge.actions.VCGE'
same_as_parent = False
Expand All @@ -62,12 +62,12 @@ def summary(self):
return msg


@adapter(Interface, IVCGEAction, Interface)
@implementer(IExecutable)
class VCGEActionExecutor(object):
""" O executor para esta acao.
Este codigo esta registrado como adaptador no configure.zcml
"""
implements(IExecutable)
adapts(Interface, IVCGEAction, Interface)

def __init__(self, context, element, event):
self.context = context
Expand Down
10 changes: 5 additions & 5 deletions src/brasil/gov/vcge/contentrules/condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
from plone.app.contentrules.browser.formhelper import EditForm
from plone.contentrules.rule.interfaces import IExecutable
from plone.contentrules.rule.interfaces import IRuleElementData
from zope.component import adapts
from zope.component import adapter
from zope.formlib import form
from zope.interface import implements
from zope.interface import implementer
from zope.interface import Interface
from zope.schema import Choice
from zope.schema import Set
Expand Down Expand Up @@ -37,10 +37,10 @@ class IVCGECondition(Interface):
value_type=Choice(vocabulary=VOCAB))


@implementer(IVCGECondition, IRuleElementData)
class VCGECondition(SimpleItem):
""" A implementacao persistente para a condicao VCGE
"""
implements(IVCGECondition, IRuleElementData)

skos = []
element = 'brasil.gov.vcge.conditions.VCGE'
Expand All @@ -56,12 +56,12 @@ def summary(self):
return msg


@adapter(Interface, IVCGECondition, Interface)
@implementer(IExecutable)
class VCGEConditionExecutor(object):
""" O executor para esta condicao.
Este codigo esta registrado como adaptador no configure.zcml
"""
implements(IExecutable)
adapts(Interface, IVCGECondition, Interface)

def __init__(self, context, element, event):
self.context = context
Expand Down
7 changes: 4 additions & 3 deletions src/brasil/gov/vcge/contentrules/utils.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
# -*- coding:utf-8 -*-
from Acquisition import aq_base
from Products.CMFPlone.utils import safe_hasattr


def vcge_available(obj):
""" Valida se o objeto tem o atributo de
armazenamento do VCGE
"""
return hasattr(aq_base(obj), 'skos')
return safe_hasattr(aq_base(obj), 'skos')


def vcge_for_object(obj):
""" Retorna valores armazenados no atributo
VCGE de um objeto
"""
skos = []
if hasattr(aq_base(obj), 'skos'):
if safe_hasattr(aq_base(obj), 'skos'):
skos = obj.skos
return skos

Expand All @@ -23,6 +24,6 @@ def set_vcge(obj, skos):
""" Armazena valores no atributo
VCGE de um objeto
"""
if hasattr(aq_base(obj), 'skos'):
if safe_hasattr(aq_base(obj), 'skos'):
obj.skos = skos
return True
84 changes: 50 additions & 34 deletions src/brasil/gov/vcge/dx/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,56 +26,72 @@ class SkosWidget(widget.SequenceWidget):
maxResults = 10
mustMatch = False
matchContains = True

# Não é necessário dar "escape" em "{" e "}" aqui uma vez que essas variáveis
# são usadas de forma literal como parâmetro do format: só precisamos dar
# "escape" quando é a string que será aplicada o format (como o js_template)
formatItem = 'function(row, idx, count, value) { return row[1]; }'
formatResult = 'function(row, idx, count) { return ''; }'
#

# Lembre-se de que para conseguir usar { e } de forma literal nas aberturas
# e fechamento de funções do js, você precisa usar {{ e }} respectivamente.
# https://docs.python.org/3/library/string.html#formatstrings
js_template = """\
(function($) {
$().ready(function() {
$('#formfield-form-widgets-IVCGE-skos #%(id)s').each(function() {
$('#formfield-form-widgets-IVCGE-skos').append('<input name="%(name)s-input" type="text" id="%(id)s-input" />');
(function($) {{
$().ready(function() {{
$('#formfield-form-widgets-IVCGE-skos #{id}').each(function() {{
$('#formfield-form-widgets-IVCGE-skos').append('<input name="{name}-input" type="text" id="{id}-input" />');
$(this).remove();
$('#formfield-form-widgets-IVCGE-skos #%(id)s-input').autocomplete('%(url)s/@@token-search?f=%(id)s', {
$('#formfield-form-widgets-IVCGE-skos #{id}-input').autocomplete('{url}/@@token-search?f={id}', {{
autoFill: false,
minChars: %(minChars)d,
max: %(maxResults)d,
mustMatch: %(mustMatch)s,
matchContains: %(matchContains)s,
formatItem: %(formatItem)s,
formatResult: %(formatResult)s
}).result(%(js_callback)s);
})
});
})(jQuery);
minChars: {minChars},
max: {maxResults},
mustMatch: {mustMatch},
matchContains: {matchContains},
formatItem: {formatItem},
formatResult: {formatResult}
}}).result({js_callback});
}})
}});
}})(jQuery);
"""

# Lembre-se de que para conseguir usar { e } de forma literal nas aberturas
# e fechamento de funções do js, você precisa usar {{ e }} respectivamente.
# https://docs.python.org/3/library/string.html#formatstrings
js_callback_template = """\
function(event, data, formatted) {
function(event, data, formatted) {{
var field = $('#formfield-form-widgets-IVCGE-skos input[type="checkbox"][value="' + data[0] + '"]');
if(field.length == 0)
$('#formfield-form-widgets-IVCGE-skos #%(id)s-input').before("<" + "label class='plain'><" + "input type='checkbox' name='%(name)s' checked='checked' value='" + data[0] + "' /> " + data[1] + "</label><br />");
$('#formfield-form-widgets-IVCGE-skos #{id}-input').before("<" + "label class='plain'><" + "input type='checkbox' name='{name}' checked='checked' value='" + data[0] + "' /> " + data[1] + "</label><br />");
else
field.each(function() { this.checked = true });
field.each(function() {{ this.checked = true }});
if(data[0])
$('#formfield-form-widgets-IVCGE-skos #%(id)s-input').val('');
}
$('#formfield-form-widgets-IVCGE-skos #{id}-input').val('');
}}
"""

def js(self):
context = self.context
form_url = context.absolute_url()
js_callback = self.js_callback_template % dict(id=self.id, name=self.name)
return self.js_template % dict(
id=self.id,
name=self.name,
url=form_url,
minChars=self.minChars,
maxResults=self.maxResults,
mustMatch=str(self.mustMatch).lower(),
matchContains=str(self.matchContains).lower(),
formatItem=self.formatItem,
formatResult=self.formatResult,
js_callback=js_callback,)
js_callback = self.js_callback_template.format(
**dict(id=self.id, name=self.name)
)
return self.js_template.format(
**dict(
id=self.id,
name=self.name,
url=form_url,
minChars=self.minChars,
maxResults=self.maxResults,
mustMatch=str(self.mustMatch).lower(),
matchContains=str(self.matchContains).lower(),
formatItem=self.formatItem,
formatResult=self.formatResult,
js_callback=js_callback,
)
)

def vocab(self):
name = 'brasil.gov.vcge'
Expand Down Expand Up @@ -164,7 +180,7 @@ def __call__(self):
if query in i.title.lower()]

results = sorted(results, key=lambda pair: len(pair[1]))
return '\n'.join(['%s|%s' % (value, title)
return '\n'.join(['{0}|{1}'.format(value, title)
for value, title in results])


Expand All @@ -175,5 +191,5 @@ def __call__(self):
results = results.split('\n')
query = self.request.get('q', '')
for r in results:
if r.startswith(u'%s|' % safe_unicode(query)):
if r.startswith(u'{0}|'.format(safe_unicode(query))):
return r
Loading