code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
from Products.validation.interfaces import ivalidator
from Products.validation import validation
from Products.validation.validators.RegexValidator import RegexValidator
from Products.plonehrm import PloneHrmMessageFactory as _
from zope.i18n import translate
class MaxDaysPerWeek:
__implements__ = (ivalidator,)
def __init__(self, name):
self.name = name
def __call__(self, value, *args, **kwargs):
value = int(value)
maxdays = 7
if value < 0 or value > maxdays:
error = _("Please enter 0 to 7 days.")
return translate(error)
return value
# Allow both commas and dots as decimal points. And do not allow
# exponentials (like 5.0e2).
isCurrency = RegexValidator(
'isCurrency',
r'^([+-]?)(?=\d|[,\.]\d)\d*([,\.]\d*)?$',
title='', description='',
errmsg='is not a decimal number.')
validation.register(isCurrency)
| [
[
1,
0,
0.0323,
0.0323,
0,
0.66,
0,
842,
0,
1,
0,
0,
842,
0,
0
],
[
1,
0,
0.0645,
0.0323,
0,
0.66,
0.1429,
195,
0,
1,
0,
0,
195,
0,
0
],
[
1,
0,
0.0968,
0.0323,
0,
... | [
"from Products.validation.interfaces import ivalidator",
"from Products.validation import validation",
"from Products.validation.validators.RegexValidator import RegexValidator",
"from Products.plonehrm import PloneHrmMessageFactory as _",
"from zope.i18n import translate",
"class MaxDaysPerWeek:\n __i... |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
PROJECTNAME = "plonehrm.contracts"
product_globals = globals()
| [
[
14,
0,
0.2,
0.2,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.4,
0.2,
0,
0.66,
0.3333,
959,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.8,
0.2,
0,
0.66,
0.6667,
... | [
"__author__ = \"\"\"Jean-Paul Ladage <j.ladage@zestsoftware.nl>\"\"\"",
"__docformat__ = 'plaintext'",
"PROJECTNAME = \"plonehrm.contracts\"",
"product_globals = globals()"
] |
import logging
from zope.component import queryMultiAdapter
from Products.CMFCore.utils import getToolByName
logger = logging.getLogger('plonehrm.contracts.events')
def apply_template(object, event, rename=True):
"""After initializing a contract, set text and title based on template.
If rename is True (the default) we will rename the object after
setting its title. Within tests this may fail, so there it can
help to set it to False. Yes, this is a hack.
"""
view = queryMultiAdapter((object, object.REQUEST),
name=u'substituter')
if view is None:
raise ValueError('Components are not properly configured, could '
'not find "substituter" view')
tool = getToolByName(object, 'portal_contracts', None)
if tool is None:
logger.error("portal_contracts cannot be found.")
return
# Get the text from the template
pages = [t for t in tool.listTemplates()
if t.getId() == object.template]
if not pages:
logger.warn("Template %r cannot be found." % object.template)
return
template_page = pages[0]
template_text = template_page.getText()
# Save the substituted text on the object.
resulting_text = view.substitute(template_text)
object.setText(resulting_text)
# Set the title to the title of the template (appending 1, 2,
# 3...), if it has not been set explicitly.
if object.Title():
return
employee = object.get_employee()
title = template_page.Title()
if employee is not None:
numbers = [0]
for contract in employee.getFolderContents(
dict(portal_type=object.portal_type)):
if not contract.Title.startswith(title):
continue
number = contract.Title.split(' ')[-1]
try:
numbers.append(int(number))
except ValueError:
continue
title += ' %d' % (max(numbers) + 1)
object.title = title
# Now we have a title, we rename the object to something nicer
# than 'contract.2009-05-15.1869364249'.
if not rename:
return
object._renameAfterCreation()
| [
[
1,
0,
0.0159,
0.0159,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0476,
0.0159,
0,
0.66,
0.25,
353,
0,
1,
0,
0,
353,
0,
0
],
[
1,
0,
0.0635,
0.0159,
0,
0.... | [
"import logging",
"from zope.component import queryMultiAdapter",
"from Products.CMFCore.utils import getToolByName",
"logger = logging.getLogger('plonehrm.contracts.events')",
"def apply_template(object, event, rename=True):\n \"\"\"After initializing a contract, set text and title based on template.\n\... |
from zope.interface import Interface
from zope.component import adapts
from zope.formlib.form import FormFields
from zope.interface import implements
from zope.schema import Bool
from zope.schema import Int
from plone.app.controlpanel.form import ControlPanelForm
from Products.CMFCore.utils import getToolByName
from Products.CMFDefault.formlib.schema import SchemaAdapterBase
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm.config import PLONEHRM_PROPERTIES
BIRTHDAY_DAYS = PLONEHRM_PROPERTIES['birthday_notification_period']['default']
CONTRACT_EXPIRY_DAYS = \
PLONEHRM_PROPERTIES['contract_expiry_notification_period']['default']
TRIAL_ENDING_DAYS = \
PLONEHRM_PROPERTIES['trial_ending_notification_period']['default']
class IHRMNotificationsPanelSchema(Interface):
birthday_notification = Bool(
title=_(u'title_birthday_notification',
default=u'Give birthday notification'),
description=_(u'description_birthday_notification',
default= u"Give notification when a birthday nears."),
default=True)
birthday_notification_period = Int(
title=_(u'title_birthday_notification_period',
default=u'Birthday notification period'),
description=_(u'description_birthday_notification_period',
default= u"Number of days before the birth day of an "
"Employee at which we give a notification."),
default=BIRTHDAY_DAYS,
required=False)
contract_expiry_notification = Bool(
title=_(u'title_contract_expiry_notification',
default=u'Give contract expiry notification'),
description=_(u'description_contract_expiry_notification',
default= u"Give notification when a contract nears "
"the expiration date."),
default=True)
contract_expiry_notification_period = Int(
title=_(u'title_contract_expiry_notification_period',
default=u'Contract expiry notification period'),
description=_(u'description_contract_expiry_notification_period',
u"Number of days before the expiry of a contract "
"at which we give a notification."),
default=CONTRACT_EXPIRY_DAYS,
required=False)
trial_ending_notification = Bool(
title=_(u'title_trial_ending_notification',
default=u'Give trial period ending notification'),
description=_(u'description_trial_ending_notification',
default= u"Give notification when the end of the "
"trial period draws near."),
default=True)
trial_ending_notification_period = Int(
title=_(u'title_trial_ending_notification_period',
default=u'Trial period ending notification period'),
description=_(u'description_trial_ending_notification_period',
u"Number of days before the end of the trial period "
"of an Employee at which we give a notification."),
default=TRIAL_ENDING_DAYS,
required=False)
class HRMNotificationsPanelAdapter(SchemaAdapterBase):
adapts(IPloneSiteRoot)
implements(IHRMNotificationsPanelSchema)
def __init__(self, context):
super(HRMNotificationsPanelAdapter, self).__init__(context)
self.portal = context
pprop = getToolByName(self.portal, 'portal_properties')
self.context = pprop.plonehrm_properties
def get_birthday_notification_period(self):
period = self.context.getProperty('birthday_notification_period',
BIRTHDAY_DAYS)
return period
def set_birthday_notification_period(self, value):
if value is not None and isinstance(value, int):
self.context._updateProperty('birthday_notification_period',
value)
else:
self.context._updateProperty('birthday_notification_period',
BIRTHDAY_DAYS)
birthday_notification_period = property(
get_birthday_notification_period, set_birthday_notification_period)
def get_birthday_notification(self):
period = self.context.getProperty('birthday_notification', True)
return period
def set_birthday_notification(self, value):
if value is not None:
self.context._updateProperty('birthday_notification', bool(value))
else:
self.context._updateProperty('birthday_notification', True)
birthday_notification = property(
get_birthday_notification, set_birthday_notification)
def get_contract_expiry_notification_period(self):
period = self.context.getProperty(
'contract_expiry_notification_period',
CONTRACT_EXPIRY_DAYS)
return period
def set_contract_expiry_notification_period(self, value):
if value is not None and isinstance(value, int):
self.context._updateProperty('contract_expiry_notification_period',
value)
else:
self.context._updateProperty('contract_expiry_notification_period',
CONTRACT_EXPIRY_DAYS)
contract_expiry_notification_period = property(
get_contract_expiry_notification_period,
set_contract_expiry_notification_period)
def get_contract_expiry_notification(self):
period = self.context.getProperty(
'contract_expiry_notification', True)
return period
def set_contract_expiry_notification(self, value):
if value is not None:
self.context._updateProperty('contract_expiry_notification',
bool(value))
else:
self.context._updateProperty('contract_expiry_notification', True)
contract_expiry_notification = property(
get_contract_expiry_notification,
set_contract_expiry_notification)
def get_trial_ending_notification_period(self):
period = self.context.getProperty(
'trial_ending_notification_period',
TRIAL_ENDING_DAYS)
return period
def set_trial_ending_notification_period(self, value):
if value is not None and isinstance(value, int):
self.context._updateProperty('trial_ending_notification_period',
value)
else:
self.context._updateProperty('trial_ending_notification_period',
TRIAL_ENDING_DAYS)
trial_ending_notification_period = property(
get_trial_ending_notification_period,
set_trial_ending_notification_period)
def get_trial_ending_notification(self):
period = self.context.getProperty(
'trial_ending_notification', True)
return period
def set_trial_ending_notification(self, value):
if value is not None:
self.context._updateProperty('trial_ending_notification',
bool(value))
else:
self.context._updateProperty('trial_ending_notification',
True)
trial_ending_notification = property(
get_trial_ending_notification,
set_trial_ending_notification)
class HRMNotificationsPanel(ControlPanelForm):
form_fields = FormFields(IHRMNotificationsPanelSchema)
label = _("Plone HRM notification settings")
description = _("Settings for the Plone HRM notification periods.")
form_name = _("Plone HRM notification settings")
| [
[
1,
0,
0.0052,
0.0052,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0104,
0.0052,
0,
0.66,
0.0588,
353,
0,
1,
0,
0,
353,
0,
0
],
[
1,
0,
0.0156,
0.0052,
0,
... | [
"from zope.interface import Interface",
"from zope.component import adapts",
"from zope.formlib.form import FormFields",
"from zope.interface import implements",
"from zope.schema import Bool",
"from zope.schema import Int",
"from plone.app.controlpanel.form import ControlPanelForm",
"from Products.CM... |
import logging
from zope.component import queryMultiAdapter
from zope.i18n import translate
from Products.CMFCore.utils import getToolByName
from zope.event import notify
from Products.Archetypes.event import ObjectInitializedEvent
from Acquisition import aq_parent
from Products.plonehrm import utils
from Products.plonehrm import PloneHrmMessageFactory as _
logger = logging.getLogger("plonehrm")
def update_worklocations(context):
"""Make sure all work locations have all the plonehrm placeful workflow.
"""
catalog = getToolByName(context, 'portal_catalog')
for brain in catalog(portal_type='WorkLocation'):
try:
worklocation = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
utils.set_plonehrm_workflow_policy(worklocation)
logger.info('Set the plonehrm workflow policy in all work locations.')
workflow = getToolByName(context, 'portal_workflow')
workflow.updateRoleMappings()
logger.info('Updated the role mappings in the site.')
def merge_personal_data(context):
"""Merge personal data from old separate object in employee itself.
When adding a new Employee, we used to create an object 'personal'
inside this employee. That would contain most of the fields of
the employee. This worked mostly but not completely and gave some
problems. And it was hackish and complex anyway, so we got rid of
it.
What we do in this migration is to go over each Employee object
and get the info from its personal object, put that inside the
employee itself and remove the personal object.
"""
logger.info("Starting migration of personal data to employee.")
# First we remove PersonalData from the portal_types_to_create
# property.
catalog = getToolByName(context, 'portal_catalog')
employee_brains = catalog.searchResults(
portal_type=('Employee'))
logger.info("Found %s Employees.", len(employee_brains))
for brain in employee_brains:
try:
employee = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
try:
personal = employee.personal
except AttributeError:
logger.debug("Employee already migrated: %s",
employee.absolute_url())
continue
logger.info("Migrating employee at %s", employee.absolute_url())
# Now we can get the values of the fields of the old personal
# object and put them in the employee object.
employee.setBirthDate(personal.getBirthDate())
employee.setAddress(personal.getAddress())
employee.setPostalCode(personal.getPostalCode())
employee.setCity(personal.getCity())
employee.setState(personal.getState())
employee.setCountry(personal.getCountry())
employee.setTelephone(personal.getTelephone())
employee.setMobilePhone(personal.getMobilePhone())
employee.setEmail(personal.getEmail())
employee.setPlaceOfBirth(personal.getPlaceOfBirth())
employee.setGender(personal.getGender())
employee.setCivilStatus(personal.getCivilStatus())
employee.setIdType(personal.getIdType())
employee.setIdNumber(personal.getIdNumber())
employee.setIdEndDate(personal.getIdEndDate())
employee.setNationality(personal.getNationality())
employee.setSocialSecurityNumber(personal.getSocialSecurityNumber())
employee.setBankNumber(personal.getBankNumber())
employee.setWorkStartDate(personal.getWorkStartDate())
# We delete the 'personal' object
employee._delObject('personal')
# This seems a good time to reindex the employee for good measure.
employee.reindexObject()
def cleanup_portal_types_to_create(context):
portal_props = getToolByName(context,
'portal_properties', None)
if portal_props is not None:
hrm_props = portal_props.get('plonehrm_properties', None)
if hrm_props is not None:
create = list(hrm_props.getProperty('portal_types_to_create', []))
try:
create.remove('PersonalData,personal')
hrm_props._updateProperty('portal_types_to_create', create)
logger.info("Removed PersonalData,personal from "
"portal_types_to_create.")
except ValueError:
# Already removed
pass
def remove_old_import_step(context):
# context is portal_setup which is nice
registry = context.getImportStepRegistry()
old_step = u'register_personaldata'
if old_step in registry.listSteps():
try:
registry.unregisterStep(old_step)
except AttributeError:
# BBB for GS 1.3
del registry._registered[old_step]
# Unfortunately we manually have to signal the context
# (portal_setup) that it has changed otherwise this change is
# not persisted.
context._p_changed = True
logger.info("Old %s import step removed from import registry.",
old_step)
gender_mapping = dict(
man='male',
vrouw='female',
)
def update_employee_vocabularies(context):
"""Use the values from new vocabularies.
This works when until now you have used Dutch values in the
personaldata_properties. Else you will have to write your own, sorry.
gender field:
- man -> male
- vrouw -> female
For the civilStatus field we did the same, but undid that later...:
- gehuwd -> married
- ongehuwd -> not_married
"""
logger.info("Starting migration of gender and civilStatus of employees.")
catalog = getToolByName(context, 'portal_catalog')
employee_brains = catalog.searchResults(portal_type='Employee')
logger.info("Found %s Employees.", len(employee_brains))
language_tool = getToolByName(context, 'portal_languages')
if language_tool:
language = language_tool.getDefaultLanguage()
else:
language = 'en'
married = _('label_married', u'married')
not_married = _('label_not_married', u'not married')
civilStatus_mapping = dict(
married=translate(married, target_language=language),
notmarried=translate(not_married, target_language=language),
)
for brain in employee_brains:
try:
employee = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
gender = employee.getGender()
if isinstance(gender, basestring):
gender = gender.lower()
new = gender_mapping.get(gender)
if new:
employee.setGender(new)
logger.info("Setting gender %s for %s", new, employee.Title())
civilStatus = employee.getCivilStatus()
new = civilStatus_mapping.get(civilStatus)
if new:
employee.setCivilStatus(new)
logger.info("Setting civilStatus %s for %s", new, employee.Title())
def update_worklocations_addresses(context):
"""Make sure all work locations address are well converted from list
to string.
"""
logger.info('Updating addresses of work locations to strings.')
catalog = getToolByName(context, 'portal_catalog')
for brain in catalog(portal_type='WorkLocation'):
try:
worklocation = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
old_wl_address = worklocation.getRawAddress()
old_company_address = worklocation.getRawCompanyAddress()
if isinstance(old_wl_address, tuple):
worklocation.setAddress("; ".join(old_wl_address))
if isinstance(old_company_address, tuple):
worklocation.setCompanyAddress("; ".join(old_company_address))
logger.info('Updated worklocations addresses.')
def reindex_employees(context):
"""Reindex all employees, needed to display the Facebook has two
new metadata have been added.
"""
logger.info("Starting reindexing employees.")
catalog = getToolByName(context, 'portal_catalog')
employee_brains = catalog.searchResults(portal_type='Employee')
logger.info("Found %s Employees.", len(employee_brains))
for employee in employee_brains:
employee = employee.getObject()
employee.reindexObject()
def replace_old_substitution_parameters(context):
"""Replace old substitution parameters.
Sometimes we rename substitution parameters, e.g.
[company_official_name] was renamed to [company_legal_name].
In this upgrade step we go through all the pages within our tools
and update their text when old parameters are found.
Note that in default Plone HRM the tools (portal_contracts and
portal_jobperformance) are always in the root of the site, but in
third party deployments there may be several instances throughout
the site.
"""
logger.info("Starting migrating old substitution parameters.")
view = queryMultiAdapter((context, context.REQUEST),
name=u'substituter')
try:
old_parameters = view.old_parameters
except AttributeError:
logger.warn("AttributeError getting old_parameters from substituter "
"view. Aborting migration.")
return
if not old_parameters:
logger.info("No old parameters known. Stopping migration.")
return
catalog = getToolByName(context, 'portal_catalog')
page_brains = catalog.searchResults(portal_type='Document')
logger.info("Found %s pages.", len(page_brains))
count = 0
for brain in page_brains:
url = brain.getURL()
parent_id = url.split('/')[-2]
if parent_id not in ('portal_contracts', 'portal_jobperformance'):
continue
try:
page = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", url)
continue
text = page.getText()
for old, new in old_parameters.items():
text = text.replace(old, new)
if text != page.getText():
count += 1
logger.info("Replaced parameters in page at %s", url)
page.setText(text)
page.reindexObject()
logger.info("%d templates needed updating.", count)
def create_template(template_location, template_type, old_template):
""" Code factorization for the update_template method.
"""
new_id = template_location.generateUniqueId('Template')
template_location.invokeFactory('Template',
id=new_id,
title=old_template.title,
type=template_type)
new_template = getattr(template_location, new_id)
new_template.description = old_template.description
new_template.setText(old_template.getText())
new_template.changeOwnership(old_template.getOwner())
new_template.unmarkCreationFlag()
new_template._renameAfterCreation()
notify(ObjectInitializedEvent(new_template))
if template_type == 'undefined':
logger.warn("Could not assign type to %s, please specify it" % \
new_template.title)
else:
logger.info('Created template %s with type %s' % \
(new_template.title, template_type))
return new_template
def update_templates(context):
""" This method migrates old templates (pages in portal_contract,
portal_jobperformance, portal_absence) to Template archetype.
It also change Absence Evaluation. The previous ones were created using
JobPerformance archetype. This class seeks for templates in
portal_jobperformance. With this upgrade, templates for absence
evaluations are stored in portal_absence and it we can not update absence
evaluation as templates are not found.
So we delete every JobPerformance located in absences, and create a real
EvaluationInterview objects with the values of the previous JobPerformance.
It tries to automatically sets the new type of the template by looking
where it was used.
The table below explains the cases and were the new template is located
and its new type.
Old location | Used in | New type | New location
------------------------------------------------------------------------------------------
portal_contracts | never used | undefined | portal_contracts
------------------------------------------------------------------------------------------
portal_contracts | contracts only | contract | portal_contracts
------------------------------------------------------------------------------------------
portal_contracts | letters only | letter | portal_contracts
------------------------------------------------------------------------------------------
portal_contracts | letters and contracts | undefined | portal_contracts
------------------------------------------------------------------------------------------
portal_jobperformance | never user | undefined | portal_jobperformance
------------------------------------------------------------------------------------------
portal_jobperformance | job perfomance only | job_performance | portal_jobperformance
------------------------------------------------------------------------------------------
portal_jobperformance | absence only | absence_evaluation | portal_absence
------------------------------------------------------------------------------------------
portal_jobperformance | both | job_performance | portal_jobperformance
| | absence_evaluation | portal_absence
------------------------------------------------------------------------------------------
"""
logger.info("Starting migrating old templates.")
catalog = getToolByName(context, 'portal_catalog')
logger.info("Migrating portal_contract templates.")
portal_contracts = getToolByName(context, 'portal_contracts')
contentFilter = {'portal_type': 'Document'}
old_templates = portal_contracts.getFolderContents(
contentFilter=contentFilter)
# The list of objects that should be deleted after the upgrade
# mainly old templates and some job performance interviews.
to_delete = []
# We get all contracts and letters.
contracts = [contract.getObject() for contract in
catalog.searchResults(portal_type='Contract')]
letters = [contract.getObject() for contract in
catalog.searchResults(portal_type='Letter')]
for old_template in old_templates:
# We look how much contracts used this template.
old_template = old_template.getObject()
# We get contracts and letters using this template.
concerned_contracts = [contract for contract in contracts
if contract.getTemplate() == old_template.id]
concerned_letters = [letter for letter in letters
if letter.getTemplate() == old_template.id]
template_type = 'undefined'
if concerned_contracts and not concerned_letters:
template_type = 'contract'
elif concerned_letters and not concerned_contracts:
template_type = 'letter'
# We create the new template
new_template = create_template(portal_contracts,
template_type,
old_template)
# We updates the contracts and letter.
# Note: the only interrest is to define default template of the next
# contract/letter.
for contract in concerned_contracts:
contract.setTemplate(new_template.id)
for letter in concerned_letters:
letter.setTemplate(new_template.id)
to_delete.append(old_template)
# Now we do the same thing for Job performances/Evaluation template.
logger.info("Migrating portal_jobperformance templates.")
portal_absence = getToolByName(context, 'portal_absence')
portal_jobperformance = getToolByName(context, 'portal_jobperformance')
interviews = [interview.getObject() for interview in
catalog.searchResults(portal_type='JobPerformanceInterview')]
evaluations = [evaluation.getObject() for evaluation in
catalog.searchResults(portal_type='EvaluationInterview')]
# We do not look for old template in portal_absence as this tool
# never accepted simple documents as templates.
contentFilter = {'portal_type': 'Document'}
old_templates = portal_jobperformance.getFolderContents(
contentFilter=contentFilter)
for old_template in old_templates:
old_template = old_template.getObject()
# We get interviews and contracts using this template.
concerned_interviews = [
interview for interview in interviews
if interview.getTemplate() == old_template.id]
concerned_evaluations = [
evaluation for evaluation in evaluations
if evaluation.getTemplate() == old_template.id]
# We create the template.
# Depending on the case, we create an undefined template
# in portal_jobperformances, a job_performance template
# in portal_jobperformance, a absence_evaluation in
# portal absence or two templates.
if not concerned_interviews and not concerned_evaluations:
create_template(portal_jobperformance, 'undefined', old_template)
if concerned_interviews:
new_jp_template = create_template(portal_jobperformance,
'job_performance',
old_template)
# We update the interviews.
for interview in concerned_interviews:
interview.setTemplate(new_jp_template.id)
if concerned_evaluations:
new_abs_template = create_template(portal_absence,
'absence_evaluation',
old_template)
for evaluation in concerned_evaluations:
if evaluation.__class__.__name__ == 'JobPerformanceInterview':
# We create a new EvaluationInterview with the
# data of the previous interview as the actual object
# is a JobPerformance, not a real EvaluationInterview.
logger.info("Found EvaluationInterview with bad type.")
absence = aq_parent(evaluation)
new_id = absence.generateUniqueId('EvaluationInterview')
absence.invokeFactory('EvaluationInterview',
id=new_id,
title=evaluation.title)
new_evaluation = getattr(absence, new_id)
new_evaluation.setTemplate(new_abs_template.id)
new_evaluation.setDate(evaluation.getDate())
new_evaluation.setText(evaluation.getText())
new_evaluation.setImprovementAreas(
evaluation.getImprovementAreas())
new_evaluation.changeOwnership(evaluation.getOwner())
new_evaluation.unmarkCreationFlag()
new_evaluation._renameAfterCreation()
notify(ObjectInitializedEvent(new_evaluation))
logger.info("Created new EvaluationInterview in %s." % \
absence.title)
to_delete.append(evaluation)
else:
evaluation.setTemplate(new_abs_template.id)
to_delete.append(old_template)
logger.info("Deleting useless objects. %s objects to delete" % \
len(to_delete))
for obj in to_delete:
obj_id = obj.id
obj_context = aq_parent(obj)
obj_context._delObject(obj_id)
logger.info("Deleted %s" % obj_id)
logger.info("Migrating templates finished.")
def update_absence_workflow(context):
""" This migration step is needed with the creation of the absence
workflow.
It seeks for every absence and checks if an end date has been set. In
this case, the state will be 'closed', in the other case the absence
will be in the state 'opened'.
"""
logger.info("Starting applying absence workflow.")
catalog = getToolByName(context, 'portal_catalog')
absences = catalog.searchResults(portal_type='Absence')
workflowTool = getToolByName(context, "portal_workflow")
absence_count = 0
for absence in absences:
absence = absence.getObject()
status = workflowTool.getStatusOf("absence_workflow", absence)
if absence.getEndDate():
try:
workflowTool.doActionFor(absence, "close")
absence_count += 1
except:
# The absence might already be closed.
pass
logger.info("%s absences changed state" % absence_count)
def update_employees_overview_viewlets(context):
""" Removes plonehrm.checklist viewlet from the employeesOverview
(default view of a worklocation) and add three more viewlets:
- plonehrm.address
- plonehrm.zipcode
- plonehrm.city
"""
portal_props = getToolByName(context, 'portal_properties', None)
if portal_props is not None:
hrm_props = getattr(portal_props, 'plonehrm_properties', None)
if hrm_props is not None:
viewlets = hrm_props.getProperty('EmployeesOverviewViewlets', ())
if viewlets:
viewlets = list(viewlets)
if 'plonehrm.checklist' in viewlets:
viewlets.remove('plonehrm.checklist')
new = ['plonehrm.address',
'plonehrm.zipcode',
'plonehrm.city']
for viewlet in new:
if not viewlet in viewlets:
viewlets.append(viewlet)
viewlets = tuple(viewlets)
hrm_props.EmployeesOverviewViewlets = viewlets
def run_workflow_step(context):
context.runImportStepFromProfile('profile-Products.plonehrm:default',
'workflow')
# Run the update security on the workflow tool.
logger.info('Updating security settings. This may take a while...')
wf_tool = getToolByName(context, 'portal_workflow')
wf_tool.updateRoleMappings()
logger.info('Done updating security settings.')
| [
[
1,
0,
0.0017,
0.0017,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0052,
0.0017,
0,
0.66,
0.0435,
353,
0,
1,
0,
0,
353,
0,
0
],
[
1,
0,
0.007,
0.0017,
0,
0... | [
"import logging",
"from zope.component import queryMultiAdapter",
"from zope.i18n import translate",
"from Products.CMFCore.utils import getToolByName",
"from zope.event import notify",
"from Products.Archetypes.event import ObjectInitializedEvent",
"from Acquisition import aq_parent",
"from Products.... |
import cStringIO
from Acquisition import Explicit
from zope.i18n import translate
from zope.interface import implements
from zope.viewlet.interfaces import IViewlet
from Products.Five import BrowserView
from datetime import date
from Acquisition import aq_chain, aq_parent
from Products.CMFCore.utils import getToolByName
from zope.i18n import translate
try:
from plonehrm.absence.absence import IAbsenceAdapter
except ImportError:
IAbsenceAdapter = None
from Products.plonehrm import PloneHrmMessageFactory as _
from plonehrm.absence import AbsenceMessageFactory as _a
from Products.CMFPlone import PloneMessageFactory as _p
from unicode_csv import UnicodeDictWriter
class AbsenceView(Explicit):
"""Return the number of sick days of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'Number of sickdays'
def render(self):
if self.is_sick():
days = self.days_absent()
return [days, days]
class AbsenceExportView(BrowserView):
""" Produces a CSV file.
"""
def _fieldnames(self):
return ['employee',
'sofi',
'reason',
'isaccident',
'startdate',
'enddate',
'lenght']
def get_lang(self):
props = getToolByName(self.context, 'portal_properties')
return props.site_properties.getProperty('default_language')
def _header(self):
""" Returns a dictionnary describing columns of the CSV export.
"""
lang = self.get_lang()
header = {}
header['employee'] = translate(_p(u'Employee'),
target_language=lang,
context=self.request)
header['sofi'] = translate(_(u'label_socialSecurityNumber'),
target_language=lang)
header['reason'] = translate(_a(u'heading_reason'),
target_language=lang)
header['isaccident'] = translate(_a(u'heading_accident'),
target_language=lang)
header['startdate'] = translate(_a(u'label_start_date'),
target_language=lang)
header['enddate'] = translate(_a(u'label_end_date'),
target_language=lang)
header['lenght'] = translate(_a(u'label_days_absent'),
target_language=lang)
return header
def absence_to_row(self, absence, is_arbo, start_date, end_date):
""" Produces a dictionnary form an absence. This dictionnary can
be used as an input row for UnicodeDictWriter.
"""
lang = self.get_lang()
toLocalizedTime = self.context.restrictedTraverse('@@plone').toLocalizedTime
employee = aq_parent(absence)
row = {}
row['employee'] = employee.officialName()
row['sofi'] = employee.getSocialSecurityNumber()
row['reason'] = absence.title
if absence.is_accident:
row['isaccident'] = translate(_p(u'Yes', default=u'Yes'),
target_language=lang,
context=self.request)
else:
row['isaccident'] = translate(_p(u'No', default=u'No'),
target_language=lang,
context=self.request)
row['startdate'] = toLocalizedTime(absence.start_date.isoformat())
if absence.end_date:
row['enddate'] = toLocalizedTime(absence.end_date.isoformat())
else:
row['enddate'] = u''
length = absence.days_absent(is_arbo, start_date, end_date)
# Use comma instead of dots
row['lenght'] = ','.join(str(length).split('.'))
return row
def filter_absences(self, start_date, end_date):
""" Returns the list of absences covering the period
between start_date and end_date.
"""
absences = []
employees = self.context.getFolderContents(
contentFilter={'portal_type': 'Employee'})
for emp in employees:
emp = emp.getObject()
emp_absences = emp.getFolderContents(
contentFilter={'portal_type': 'Absence'})
for absence in emp_absences:
absence = absence.getObject()
# We only chose absences for the covered period.
if absence.end_date:
if not absence.end_date.toordinal() < \
start_date.toordinal() and \
not absence.start_date.toordinal() > \
end_date.toordinal():
absences.append(absence)
else:
if not absence.start_date.toordinal() > \
end_date.toordinal():
absences.append(absence)
return absences
def check_form(self, form):
""" Checks the submitted form and returns start and end date
in a suitable format.
"""
# We check that fields have been submitted.
fields = ['export_end_date_day',
'export_end_date_month',
'export_end_date_year',
'export_start_date_day',
'export_start_date_month',
'export_start_date_year']
for field in fields:
if not field in form:
# Should not hapen.
return
try:
start_day = int(form['export_start_date_day'])
start_month = int(form['export_start_date_month'])
start_year = int(form['export_start_date_year'])
start_date = date(start_year, start_month, start_day)
except:
start_date = date.today()
try:
end_day = int(form['export_end_date_day'])
end_month = int(form['export_end_date_month'])
end_year = int(form['export_end_date_year'])
end_date = date(end_year, end_month, end_day)
except:
end_date = date.today()
return start_date, end_date
def __call__(self):
form = self.request.form
membership = getToolByName(self.context, 'portal_membership')
is_arbo = membership.checkPermission('plonehrm: manage Arbo content',
self.context)
try:
start_date, end_date = self.check_form(form)
except:
# Some fields were missing, should not happen.
return
# We get all absences
absences = self.filter_absences(start_date, end_date)
# Now we can make the CSV export.
fileobj = cStringIO.StringIO()
writer = UnicodeDictWriter(fileobj, self._fieldnames(),
extrasaction='ignore', dialect='excel',
delimiter=';')
writer.writerow(self._header())
for absence in absences:
writer.writerow(self.absence_to_row(absence, is_arbo,
start_date, end_date))
fileobj.seek(0)
filename='export-absences.csv'
self.request.response.setHeader('Cache-Control',
'no-store, no-cache, must-revalidate')
self.request.response.setHeader('Content-Type',
'text/comma-separated-values')
self.request.response.setHeader('Content-Disposition',
'attachment; filename="%s"' % filename)
self.request.response.write(fileobj.read())
| [
[
1,
0,
0.0045,
0.0045,
0,
0.66,
0,
764,
0,
1,
0,
0,
764,
0,
0
],
[
1,
0,
0.0135,
0.0045,
0,
0.66,
0.0625,
62,
0,
1,
0,
0,
62,
0,
0
],
[
1,
0,
0.018,
0.0045,
0,
0.6... | [
"import cStringIO",
"from Acquisition import Explicit",
"from zope.i18n import translate",
"from zope.interface import implements",
"from zope.viewlet.interfaces import IViewlet",
"from Products.Five import BrowserView",
"from datetime import date",
"from Acquisition import aq_chain, aq_parent",
"fr... |
from kss.core import kssaction, KSSView
from zope.event import notify
from Products.Archetypes.event import ObjectInitializedEvent
from Products.Archetypes.config import RENAME_AFTER_CREATION_ATTEMPTS
from Products.CMFCore import utils as cmfutils
from Acquisition import aq_inner
from Products.plonehrm import PloneHrmMessageFactory as _
class FileKssView(KSSView):
""" Class managing the 'File' viewlet.
"""
def _findUniqueId(self, id):
"""Find a unique id in this context.
This is based on the given id, by appending -n, where n is a
number between 1 and the constant
RENAME_AFTER_CREATION_ATTEMPTS, set in
Archetypes/config.py. If no id can be found, return None.
Method is slightly adapted from Archetypes/BaseObject.py
Most important changes:
- Do not rename image.jpg to image.jpg-1 but image-1.jpg
- If no good id can be found, just return the original id;
that way the same errors happens as would without any
renaming.
This method was written for the PloneFlashUpload product:
http://plone.org/products/ploneflashupload
"""
context = aq_inner(self.context)
ids = context.objectIds()
valid_id = lambda id: id not in ids
if valid_id(id):
return id
# 'image.name.gif'.rsplit('.', 1) -> ['image.name', 'gif']
splitted = id.rsplit('.', 1)
if len(splitted) == 1:
splitted.append('')
head, tail = splitted
idx = 1
while idx <= RENAME_AFTER_CREATION_ATTEMPTS:
if tail:
new_id = '%s-%d.%s' % (head, idx, tail)
else:
new_id = '%s-%d' % (head, idx)
if valid_id(new_id):
return new_id
idx += 1
# Just return the id.
return id
def replaceViewlet(self, show_list = True):
""" As code to display form or list is almost the same,
we factorise the code in this method.
The show_list parameter is used to know if we display the
field list or the upload form instead.
"""
# First, we get the viewlet manager.
view = self.context.restrictedTraverse('@@plonehrm.files')
# We configure it.
view.show_list = show_list
# We get the content displayed by in the viewlet.
rendered = view.render()
# We replace the content of the viewlet by the new one.
core = self.getCommandSet('core')
selector = core.getHtmlIdSelector('plonehrmFileViewlet')
core.replaceHTML(selector, rendered)
@kssaction
def display_form(self):
""" This action is used to display the add form
in the viewlet.
"""
self.replaceViewlet(False)
@kssaction
def display_list(self):
""" This action is used to display the list of files.
"""
self.getCommandSet('plone').issuePortalMessage('')
self.replaceViewlet(True)
def add_file(self):
""" This action is called when adding a new file. This action is
not called with KSS, but directly after submitting the form.
"""
# Tests if the page '*/kss_add_file/' has been called directly,
# in this case, we redirect to the context view.
if not 'new_file_file' in self.request.form:
self.request.response.redirect(self.context.absolute_url())
return
# If no file has been provided, then we redirect to
# the employee view.
# Note: this shall not append, as there is a Javascript validation
# on the form and the form can only be shown with Javascript.
# So this should only append if the user disable Javascript once the
# form is displayed.
if not self.request.new_file_file:
self.request.response.redirect(self.context.absolute_url())
return
# We get the uploaded file.
uploaded_file = self.request.new_file_file
filename = uploaded_file.filename
file_desc = self.request.form['file_desc']
# If no title has been specified, we use the filename as title.
if self.request.form['file_title']:
file_title = self.request.form['file_title']
else:
file_title = filename
# We create the file.
plone_tool = cmfutils.getToolByName(self.context, 'plone_utils')
new_id = plone_tool.normalizeString(filename)
new_id = self._findUniqueId(new_id)
self.context.invokeFactory('File',
id=new_id,
title=filename)
new_file = getattr(self.context, new_id)
new_file.setFile(uploaded_file)
new_file.setTitle(file_title)
new_file.setDescription(file_desc)
new_file.unmarkCreationFlag()
new_file._renameAfterCreation()
notify(ObjectInitializedEvent(new_file))
self.context.plone_utils.addPortalMessage(_(u'msg_file_added',
u'File added'))
# We redirect to the employee view.
self.request.response.redirect(self.context.absolute_url())
| [
[
1,
0,
0.0066,
0.0066,
0,
0.66,
0,
653,
0,
2,
0,
0,
653,
0,
0
],
[
1,
0,
0.0132,
0.0066,
0,
0.66,
0.1429,
293,
0,
1,
0,
0,
293,
0,
0
],
[
1,
0,
0.0199,
0.0066,
0,
... | [
"from kss.core import kssaction, KSSView",
"from zope.event import notify",
"from Products.Archetypes.event import ObjectInitializedEvent",
"from Products.Archetypes.config import RENAME_AFTER_CREATION_ATTEMPTS",
"from Products.CMFCore import utils as cmfutils",
"from Acquisition import aq_inner",
"from... |
from datetime import date
from datetime import timedelta
from DateTime import DateTime
import logging
from Acquisition import Explicit
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile
from zope.component import getMultiAdapter
from zope.viewlet.interfaces import IViewlet
from zope.component import getAdapters
logger = logging.getLogger('Products.plonehrm')
class EmployeeDetails(object):
def __init__(self, context, request, view):
self.context = context
self.request = request
self.__parent__ = view
def update(self):
"""See zope.contentprovider.interfaces.IContentProvider"""
self.__updated = True
# Find all content providers for the region
viewlets = getAdapters(
(self.context, self.request, self.__parent__, self),
IViewlet)
viewlets = self.filter(viewlets)
viewlets = self.sort(viewlets)
# Just use the viewlets from now on
self.viewlets = [viewlet for name, viewlet in viewlets]
# Update all viewlets
[viewlet.update() for viewlet in self.viewlets]
self.columns = ([], [])
left_column = True
for viewlet in self.viewlets:
if left_column:
self.columns[0].append(viewlet)
else:
self.columns[1].append(viewlet)
left_column = not left_column
def sort(self, viewlets):
columns = ()
portal_props = getToolByName(self.context, 'portal_properties', None)
if portal_props is not None:
hrm_props = getattr(portal_props, 'plonehrm_properties', None)
if hrm_props is not None:
columns = hrm_props.getProperty('EmployeeDetailsViewlets', ())
results = []
for item in columns:
for name, viewlet in viewlets:
if name == item:
results.append((name, viewlet))
return results
class EmployeesOverview(Explicit):
index = ZopeTwoPageTemplateFile('employees.pt')
worklocationview_attribute = 'active_employees'
hrm_viewlet_property = 'EmployeesOverviewViewlets'
def __init__(self, context, request, view):
self.context = context
self.request = request
self.__parent__ = view
def update(self):
columns = ()
portal_props = getToolByName(self.context, 'portal_properties', None)
if portal_props is not None:
hrm_props = getattr(portal_props, 'plonehrm_properties', None)
if hrm_props is not None:
columns = hrm_props.getProperty(self.hrm_viewlet_property, ())
rows = []
view = self.context.restrictedTraverse('@@worklocationview')
for brain in getattr(view, self.worklocationview_attribute):
try:
value = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
rows.append(
[getMultiAdapter(
(value, self.request, self.__parent__, self),
IViewlet, name=colname)
for colname in columns])
[entry.update() for entry in rows[-1]]
self.rows = rows
def render(self, *args, **kw):
return self.index(*args, **kw)
class InactiveEmployeesOverview(EmployeesOverview):
index = ZopeTwoPageTemplateFile('employees.pt')
worklocationview_attribute = 'inactive_employees'
class EmployeesImprovementsOverview(EmployeesOverview):
hrm_viewlet_property = 'EmployeesImprovementsOverviewViewlets'
class EmployeesAbsenceOverview(EmployeesOverview):
hrm_viewlet_property = 'EmployeesAbsenceViewlets'
index = ZopeTwoPageTemplateFile('absences.pt')
def __init__(self, context, request, view):
self.context = context
self.request = request
self.__parent__ = view
self.average_percentage = 0
self.average_total = 0
self.average_count = 0
def get_employee_absences_number(self, employee):
""" Gets every absences of an employee for this year.
"""
year = date.today().year
total = 0
absences = employee.contentValues({'portal_type': 'Absence'})
return len([absence for absence in absences
if absence.start_date.year == year])
def get_employee_absences(self, employee, as_list=True, startdate = None):
""" Computes the number of days an employee was absent
for the current year.
If as_list is set to True, a list of absences for each month
is returned, else the total for the year is returned.
"""
today = date.today()
year = today.year
months = {}
total = 0
for month in range(1, 13):
months[month] = 0
absences = employee.contentValues({'portal_type': 'Absence'})
if startdate is None:
this_day = date(year, 1, 1) # 1 January of this year
else:
this_day = startdate
days_handled = 0 # We use this as safety against never-ending loops
for absence in absences:
if absence.end_date and absence.end_date.year < today.year:
# irrelevant
continue
if absence.start_date.year > today.year:
# This and all next absences start in the future.
break
# We have found a relevant absence.
if absence.end_date:
end_date = absence.end_date.date()
else:
end_date = today
start_date = absence.start_date.date()
days_absent = absence.days_absent()
full_duration = end_date - start_date
if full_duration.days == 0:
# Avoid ZeroDivisionError
full_duration = days_absent or 1
else:
full_duration = full_duration.days
if days_absent > full_duration:
# A bit weird. Possibly we are looking at an
# earlier year (which is not supported yet in the
# UI, but can happen when you are setting 'today'
# to something else when testing/hacking).
days_absent = full_duration
# What percentage are we adding per day?
per_day = days_absent / float(full_duration)
# Find the next absence.
while start_date > this_day and days_handled <= 366:
days_handled += 1
this_day += timedelta(1)
if days_handled > 366:
# No relevant dates anymore
break
# Add the 'per_day' amount to the current month until
# we find the end_date of the current absence.
while end_date >= this_day and days_handled <= 366:
months[this_day.month] += per_day
days_handled += 1
this_day += timedelta(1)
if days_handled > 366:
# No relevant dates anymore
break
for month in range(1, 13):
total += months[month]
if as_list:
return months
else:
return total
def absence_percentage(self, employee):
""" Provides percentage of days missed for the current year.
"""
def date_key(item):
return item.getStartdate()
today = DateTime()
year_begin = DateTime(today.year(), 1, 1)
# We get employee contracts and letters
contracts = employee.contentValues({'portal_type': 'Contract'})
letters = employee.contentValues({'portal_type': 'Letter'})
# Number of days worked from first of january to now.
worked_days = 0
# Date from which we start counting worked days (basically, 1st
# of january or first contract start date).
# We initialize it to today and adjust its value when looking
# at the contracts.
period_begin_date = today
# True if the first of january covered by a contract.
is_first_of_january_covered = False
contracts = sorted(contracts, key=date_key)
for contract in contracts:
# We look if the contract covers the period between
# 1st january and today.
if contract.expiry_date() < year_begin or \
contract.getStartdate() > today:
continue
# We get the number of days covered by this contract
begin = max([contract.getStartdate(), year_begin])
end = min([contract.expiry_date(), today])
# We look if this contract covers the 1st of january.
if year_begin > contract.getStartdate() and \
year_begin < contract.expiry_date():
is_first_of_january_covered = True
period_begin_date = year_begin
# If no contract covers the 1st a january, we set the value of
# period_begin_date to the first contract found.
if not is_first_of_january_covered and \
contract.getStartdate() < period_begin_date:
period_begin_date = contract.getStartdate()
# We get the letters covering his period
applicable_letters = [letter for letter in letters \
if letter.getStartdate() > begin and \
letter.getStartdate() < end]
if not applicable_letters:
# We compute the number of days that were supposed to be worked
# during this period
contract_days = end - begin
worked_days += contract_days * (contract.getDaysPerWeek() / 7.0)
else:
# In this case, we have to split the contract period
# to get every changes due to letters.
applicable_letters = sorted(applicable_letters,
key = date_key)
# We compute days covered by the basic contract.
end = applicable_letters[0].getStartdate()
contract_days = end - begin
worked_days += contract_days * (contract.getDaysPerWeek() / 7.0)
i = 1
for letter in applicable_letters:
# We compute days covered by each letter.
if i == len(applicable_letters):
end = min([contract.expiry_date(), today])
else:
end = min([applicable_letters[i].getStartdate(), today])
begin = letter.getStartdate()
i += 1
letter_days = end - begin
worked_days += letter_days * (letter.getDaysPerWeek() / 7.0)
# We compute the sickdays. We can not use the one computed for the total
# as this total takes into account all absences for the year, we just
# need absences for the period covered by contracts.
# We also need to cast period_begin_date form DateTime to date.
period_begin_date = date(period_begin_date.year(),
period_begin_date.month(),
period_begin_date.day())
sickdays = self.get_employee_absences(employee, as_list=False,
startdate = period_begin_date)
if worked_days:
# We finally compare number of sickdays and number of worked days.
absence_percentage = int((sickdays / worked_days) * 100)
# There is some weird cases where we get more than 100% of absences
# over the year, for example when the first contract is signed
# during an absence.
# To prevent this, we return 100%.
if absence_percentage > 100:
return 100
else:
return absence_percentage
def get_arbo_absence(self, employee):
""" This method computes number of absence days each month,
and the percentage of missed day for the whole year.
Contrary to the previous methods, it does not take into account
number of absence days specified in the absence, but the beginning
and ending of an absence and compares is to how days are spread
during a week.
To do this, we will compute two dictionnaries. The key will be the
dates and the value floats.
The first dictionnary tells if the day was worked, the second one if
the employee was present (and how much if the absence did not start
in the morning).
"""
def date_key(item):
return item.getStartdate()
def date_caster(day):
""" Casts a DateTime object to datetime.date
"""
return date(day.year(), day.month(), day.day())
# Some important dates
today = date.today()
year = today.year
first_day = date(year, 1, 1)
# The dictionnaries of worked/absence days.
worked_days = {}
absence_days = {}
for i in range(0, today.toordinal() - first_day.toordinal() + 1):
worked_days[first_day + timedelta(i)] = 0
absence_days[first_day + timedelta(i)] = 0
# Number of not-worked days per month
months = {}
for month in range(1, 13):
months[month] = 0
# Count of absences for this year.
absence_count = 0
# Total of absence days.
absence_days_total = 0
# Total of worked days.
worked_days_total = 0
# We get employee absences.
absences = employee.contentValues({'portal_type': 'Absence'})
# First, we compute the absence days.
for absence in absences:
if absence.end_date and not absence.end_date.year == year:
# This absence is not in the range of interresting absences.
continue
absence_count += 1
# We compute the days that was supposed to be worked during
# the absence.
if absence.end_date:
days = employee.get_worked_days(absence.start_date,
absence.end_date)
else:
days = employee.get_worked_days(absence.start_date,
today)
for day in days:
if days[day]:
absence_days[day] = 1
else:
absence_days[day] = 0
# We update the first cell of the dictionnary for
# absence starting on a partial day.
casted_start_date = date(absence.start_date.year,
absence.start_date.month,
absence.start_date.day)
if casted_start_date in absence_days:
absence_days[casted_start_date] = \
absence.get_first_day_percentage()
# Now we compute which days were supposed to be worked.
worked_days = employee.get_worked_days(first_day, today)
# Now, we can compute for each day if the employee
# worked or was absent.
# We substract absence days to worked days to know how long
# the employee worked this day.
for day in worked_days:
if day.toordinal() > today.toordinal() or \
not day in absence_days:
continue
if worked_days[day]:
worked_days_total += 1
worked_time = 1 - absence_days[day]
if worked_time != 1:
absence_days_total += absence_days[day]
if day.month in months:
months[day.month] += absence_days[day]
# Now we can create the row that will be displayed.
# First, we add the name of the employee.
fullname = getMultiAdapter(
(employee, self.request, self.__parent__, self),
IViewlet, name='plonehrm.fullname')
fullname.update()
result = [fullname.render()]
# Then, one cell for each month.
for month in months:
value = months[month]
result.append(value)
# Then, the total of absence days.
result.append(absence_days_total)
# Then, the percentage of absences.
if worked_days_total:
result.append(str(int(
(float(absence_days_total)/worked_days_total) * 100)) + '%')
else:
result.append('0%')
# And to finish, the count of absences.
result.append(absence_count)
return result
def update(self):
today = date.today()
year = today.year
columns = ()
portal_props = getToolByName(self.context, 'portal_properties', None)
if portal_props is not None:
hrm_props = getattr(portal_props, 'plonehrm_properties', None)
if hrm_props is not None:
columns = hrm_props.getProperty(self.hrm_viewlet_property, ())
rows = []
view = self.context.restrictedTraverse('@@worklocationview')
# We check if the user has the ARBO manager role.
membership = getToolByName(self.context, 'portal_membership')
is_arbo = membership.checkPermission('plonehrm: manage Arbo content',
self.context)
for brain in getattr(view, self.worklocationview_attribute):
employee = brain.getObject()
# For Arbo manager, we use a special method to compute rows.
if is_arbo:
rows.append(self.get_arbo_absence(employee))
continue
cols = []
fullname = getMultiAdapter(
(employee, self.request, self.__parent__, self),
IViewlet, name='plonehrm.fullname')
fullname.update()
cols.append(fullname.render())
# Now calculate absence days.
months = self.get_employee_absences(employee)
total = 0
for month in range(1, 13):
value = int(round(months[month]))
total += value
cols.append(value)
cols.append(total)
# Now computes the percentage of absences.
percentage = self.absence_percentage(employee)
if percentage:
percentage = str(percentage) + '%'
else:
percentage = '0%'
cols.append(percentage)
# And now the total of absences
cols.append(self.get_employee_absences_number(employee))
rows.append(cols)
self.rows = rows
# Now we compute the average percentage/total and count of absences.
for row in self.rows:
self.average_count += row[-1]
self.average_total += row[-3]
try:
# We have to remove last character in percentage row and cast it
# to an integer.
self.average_percentage += int(row[-2][:-1])
except ValueError:
pass
if self.rows:
self.average_count /= len(self.rows)
self.average_percentage /= len(self.rows)
self.average_total /= len(self.rows)
else:
self.average_count = 0
self.average_percentage = 0
self.average_total = 0
self.average_percentage = str(self.average_percentage) + '%'
def render(self, *args, **kw):
return self.index(*args, **kw)
| [
[
1,
0,
0.0019,
0.0019,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0037,
0.0019,
0,
0.66,
0.0667,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0056,
0.0019,
0,
... | [
"from datetime import date",
"from datetime import timedelta",
"from DateTime import DateTime",
"import logging",
"from Acquisition import Explicit",
"from Products.CMFCore.utils import getToolByName",
"from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile",
"from zope.component i... |
from zope.interface import implements
from plone.app.contentmenu.menu import WorkflowMenu
from plone.app.contentmenu.interfaces import IWorkflowMenu
class PloneHrmWorkflowMenu(WorkflowMenu):
""" Overrides the Plone default class to display workflow menus in
order to hide them in the absence view.
"""
implements(IWorkflowMenu)
def getMenuItems(self, context, request):
if context.getPortalTypeName() in ['Absence', 'Employee']:
return []
else:
return WorkflowMenu.getMenuItems(self, context, request)
| [
[
1,
0,
0.0667,
0.0667,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.1333,
0.0667,
0,
0.66,
0.3333,
25,
0,
1,
0,
0,
25,
0,
0
],
[
1,
0,
0.2,
0.0667,
0,
0.66,... | [
"from zope.interface import implements",
"from plone.app.contentmenu.menu import WorkflowMenu",
"from plone.app.contentmenu.interfaces import IWorkflowMenu",
"class PloneHrmWorkflowMenu(WorkflowMenu):\n \"\"\" Overrides the Plone default class to display workflow menus in\n order to hide them in the abs... |
from zope.interface import implements
from zope.i18n import translate
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Acquisition import aq_inner, aq_parent, aq_chain
from DateTime import DateTime
from Products.Five import BrowserView
from Products.CMFPlone.utils import getSiteEncoding
from plone.app.portlets.portlets import base
from Products.CMFPlone import PloneLocalesMessageFactory as PLMF
from Products.plonehrm.interfaces import IEmployee
from Products.plonehrm.interfaces import IWorkLocation
from Products.plonehrm.browser.interfaces import ISubstitutionPortlet
from Products.plonehrm import PloneHrmMessageFactory as _
from plonehrm.contracts.interfaces import IContract
class BaseSubstitutionView(BrowserView):
"""Substitute some variables or print the available variables.
Only useful to call on Document-like content types. It has two uses:
- When called on a Document within one of the template tools of
plonehrm modules, like portal_contracts and
portal_jobperformance, it can list parameters that are available
for substitution.
- When called on a child of an Employee (e.g. Contract or
JobPerformanceInterview), you can substitute variables mentioned
in those documents.
Inherit from this in your employee module.
"""
# override this mapping to localize the substitution terms (yes, one
# language per site only)
substitution_translations = {
'[company_address]': '[company_address]',
'[company_city]': '[company_city]',
'[company_legal_name]': '[company_legal_name]',
'[company_postal_code]': '[company_postal_code]',
'[contract_days_per_week]': '[contract_days_per_week]',
'[contract_duration]': '[contract_duration]',
'[contract_expirydate]': '[contract_expirydate]',
'[contract_function]': '[contract_function]',
'[contract_hours_per_week]': '[contract_hours_per_week]',
'[contract_part_full_time]': '[contract_part_full_time]',
'[contract_startdate]': '[contract_startdate]',
'[contract_trial_period]': '[contract_trial_period]',
'[contract_wage]': '[contract_wage]',
'[employee_address]': '[employee_address]',
'[employee_city]': '[employee_city]',
'[employee_date_of_birth]': '[employee_date_of_birth]',
'[employee_first_name]': '[employee_first_name]',
'[employee_full_name]': '[employee_full_name]',
'[employee_initials]': '[employee_initials]',
'[employee_last_name]': '[employee_last_name]',
'[employee_official_name]': '[employee_official_name]',
'[employee_place_of_birth]': '[employee_place_of_birth]',
'[employee_postal_code]': '[employee_postal_code]',
'[employee_title]': '[employee_title]',
'[employee_formal_title]': '[employee_formal_title]',
'[first_contract_startdate]': '[first_contract_startdate]',
'[previous_contract_startdate]': '[previous_contract_startdate]',
'[today]': '[today]',
'[today_written_month]': '[today_written_month]',
'[worklocation_address]': '[worklocation_address]',
'[worklocation_city]': '[worklocation_city]',
'[worklocation_pay_period]': '[worklocation_pay_period]',
'[worklocation_postal_code]': '[worklocation_postal_code]',
'[worklocation_trade_name]': '[worklocation_trade_name]',
'[worklocation_vacation_days]': '[worklocation_vacation_days]',
'[worklocation_contactperson]': '[worklocation_contactperson]'
}
# For migration. See
# Products.plonehrm.migration.replace_old_substitution_parameters
old_parameters = {
# old: new
'[company_official_name]': '[company_legal_name]',
}
def __init__(self, context, request):
self.context = aq_inner(context)
# We're called on a child of an employee. So we need to
# grab our parent (=employee) and our grandparent
# (=worklocation).
self.employee = self.get_employee()
self.worklocation = aq_parent(aq_inner(self.employee))
if not IWorkLocation.providedBy(self.worklocation):
self.worklocation = None
# Call an update method. Now you might only need to override
# that method when you want to customize this view.
self.params = self.calcParams()
# keys is no longer used by calcParams (because it builds a new
# sorted list), but it does get used for displaying the available
# terms in the views
self.keys = self.substitution_translations.values()
self.keys.sort()
def get_employee(self):
"""Get the employee that this context is in.
Note that we probably are in the portal_factory, so our direct
parent is not an Employee. But we can traverse up the
acquisition chain to find it. Or there may be other reasons
why the employee is not our parent, but e.g. our grand parent.
"""
context = aq_inner(self.context)
for parent in aq_chain(context):
if IEmployee.providedBy(parent):
return parent
def calcParams(self):
"""Calculate the values of the parameters for substitution.
"""
r = {}
ploneview = self.context.restrictedTraverse('@@plone')
pps = self.context.restrictedTraverse('@@plone_portal_state')
language = pps.default_language()
# We ignore [naam_formule] but make a note of it anyway.
r['[employee_official_name]'] = self.employee and \
self.employee.officialName()
if self.employee:
gender = self.employee.getGender()
if gender == 'male':
formal_title = _(u'formal_title_male',
default=u'Dear Sir ')
else:
formal_title = _(u'formal_title_female',
default=u'Dear Madam ')
r['[employee_formal_title]'] = \
translate(formal_title,
target_language=language)
# Now try to translate the gender. Note that there might
# be old values that are not in the current DisplayList.
# Just display those literally.
vocabulary = self.employee._genderVocabulary()
value = vocabulary.getValue(gender)
if value:
gender = translate(value, target_language=language)
# We compute the employe initials.
initials = self.employee.getInitials()
if not initials:
fnames = self.employee.getFirstName().split(' ')
for fname in fnames:
if len(fname):
initials += fname[0] + '.'
# We compute the first contract start date.
first_contract_startdate = self.employee.getWorkStartDate()
if not first_contract_startdate:
content_filter = {'portal_type': 'Contract'}
contracts = self.employee.getFolderContents(
contentFilter=content_filter)
for contract in [c.getObject() for c in contracts]:
if contract.getStartdate() < first_contract_startdate or \
not first_contract_startdate:
first_contract_startdate = contract.getStartdate()
first_contract_startdate = ploneview.toLocalizedTime(
first_contract_startdate)
r['[employee_title]'] = self.employee and gender
r['[employee_initials]'] = self.employee and initials
r['[employee_first_name]'] = self.employee and \
self.employee.getFirstName()
r['[employee_full_name]'] = self.employee and \
self.employee.Title()
r['[employee_last_name]'] = self.employee and (
self.employee.getMiddleName() + ' ' +
self.employee.getLastName()).strip()
r['[employee_address]'] = self.employee and self.employee.getAddress()
r['[employee_postal_code]'] = self.employee and \
self.employee.getPostalCode()
r['[employee_city]'] = self.employee and self.employee.getCity()
r['[employee_place_of_birth]'] = self.employee and \
self.employee.getPlaceOfBirth()
r['[employee_date_of_birth]'] = self.employee and \
ploneview.toLocalizedTime(self.employee.getBirthDate())
# Totally skip the contract parameters when you are in the
# FunctioningTool
if self.context.Type() in ['Contract', 'Letter']:
contract = self.context
if not IContract.providedBy(contract):
contract = None
r['[contract_startdate]'] = contract and ploneview.toLocalizedTime(
contract.getStartdate())
r['[contract_part_full_time]'] = contract and \
contract.getEmploymentType()
r['[contract_hours_per_week]'] = contract and contract.getHours()
r['[contract_days_per_week]'] = contract \
and contract.getDaysPerWeek()
r['[contract_function]'] = contract and contract.getFunction()
r['[contract_wage]'] = contract and contract.getWage()
r['[contract_trial_period]'] = contract and \
contract.getTrialPeriod()
r['[contract_duration]'] = contract and contract.getDuration()
r['[contract_expirydate]'] = contract and contract.expiry_date() \
and ploneview.toLocalizedTime(contract.expiry_date())
previous_contract = contract and contract.base_contract()
r['[previous_contract_startdate]'] = previous_contract and \
ploneview.toLocalizedTime(previous_contract.getStartdate())
# Note: Do something with the CAO?
# Start date
r['[first_contract_startdate]'] = self.employee and \
first_contract_startdate
# Work Location:
r['[worklocation_trade_name]'] = self.worklocation and \
self.worklocation.Title()
r['[worklocation_address]'] = self.worklocation and \
self.worklocation.getAddress()
r['[worklocation_postal_code]'] = self.worklocation and \
self.worklocation.getPostalCode()
r['[worklocation_city]'] = self.worklocation and \
self.worklocation.getCity()
if self.worklocation:
pay_period = self.worklocation.getPayPeriod()
vocabulary = self.worklocation._payPeriodVocabulary()
value = vocabulary.getValue(pay_period)
if value:
pay_period = translate(value, target_language=language)
r['[worklocation_pay_period]'] = self.worklocation and pay_period
r['[worklocation_vacation_days]'] = self.worklocation and \
self.worklocation.getVacationDays()
r['[worklocation_contactperson]'] = self.worklocation and \
self.worklocation.getContactPerson()
# Company:
r['[company_legal_name]'] = self.worklocation and \
self.worklocation.getOfficialName()
r['[company_address]'] = self.worklocation and \
self.worklocation.getCompanyAddress()
r['[company_postal_code]'] = self.worklocation and \
self.worklocation.getCompanyPostalCode()
r['[company_city]'] = self.worklocation and \
self.worklocation.getCompanyCity()
today = DateTime()
r['[today]'] = ploneview.toLocalizedTime(today)
# The today's date with written month will be a bit tricky,
# mainly because
# of english (and french, but maybe other languages ) dates
# in which the day's number can be completed.
# For example:
# - 1st of january 2009 (en)
# - 1er janvier 2009 (french)
# - 1 januari 2009 (dutch)
# So we'll create translations for those days, even if for some
# languages it will just be the same value.
year = today.year()
month = today.aMonth()
day = today.day()
# Here come the ugly part :/
# As i18n dude makes a static interpretation of the code, we
# can not simply generate ids and default values.
if day == 1:
day = _(u'day_1', default=u'1')
elif day == 2:
day = _(u'day_2', default=u'2')
elif day == 3:
day = _(u'day_3', default=u'3')
elif day == 4:
day = _(u'day_4', default=u'4')
elif day == 5:
day = _(u'day_5', default=u'5')
elif day == 6:
day = _(u'day_6', default=u'6')
elif day == 7:
day = _(u'day_7', default=u'7')
elif day == 8:
day = _(u'day_8', default=u'8')
elif day == 9:
day = _(u'day_9', default=u'9')
elif day == 10:
day = _(u'day_10', default=u'10')
elif day == 11:
day = _(u'day_11', default=u'11')
elif day == 12:
day = _(u'day_12', default=u'12')
elif day == 13:
day = _(u'day_13', default=u'13')
elif day == 14:
day = _(u'day_14', default=u'14')
elif day == 15:
day = _(u'day_15', default=u'15')
elif day == 16:
day = _(u'day_16', default=u'16')
elif day == 17:
day = _(u'day_17', default=u'17')
elif day == 18:
day = _(u'day_18', default=u'18')
elif day == 19:
day = _(u'day_19', default=u'19')
elif day == 20:
day = _(u'day_20', default=u'20')
elif day == 21:
day = _(u'day_21', default=u'21')
elif day == 22:
day = _(u'day_22', default=u'22')
elif day == 23:
day = _(u'day_23', default=u'23')
elif day == 24:
day = _(u'day_24', default=u'24')
elif day == 25:
day = _(u'day_25', default=u'25')
elif day == 26:
day = _(u'day_26', default=u'26')
elif day == 27:
day = _(u'day_27', default=u'27')
elif day == 28:
day = _(u'day_28', default=u'28')
elif day == 29:
day = _(u'day_29', default=u'29')
elif day == 30:
day = _(u'day_30', default=u'30')
elif day == 31:
day = _(u'day_31', default=u'31')
day = translate(day, target_language=language)
month = translate(PLMF(u'month_%s' % month.lower()),
target_language=language)
# Now we declare our own 'builder' to assemble all these data.
month_written = _(u"${day} ${month} ${year}",
mapping=dict(day=day,
month=month,
year=year))
r['[today_written_month]'] = translate(month_written,
target_language=language)
return r
def substitute(self, text):
keytuples = self.substitution_translations.items()
# We will reverse the keys as otherwise $NAME would also match
# $NAMELIST or so.
# Actually, we switched to [name] so that would never match
# [namelist], but let's keep this reversal for those who prefer
# their paramaters prefixed with a dollar sign.
keytuples.sort(key=lambda a: -len(a[1]))
encoding = getSiteEncoding(self.context)
for key, translated_key in keytuples:
if key in self.params:
value = self.params[key]
if isinstance(value, unicode):
value = value.encode(encoding)
if value is None:
value = '…'
if not isinstance(value, str):
# e.g. an integer
value = str(value)
text = text.replace(translated_key, value)
return text
class Assignment(base.Assignment):
implements(ISubstitutionPortlet)
@property
def title(self):
return _(u"Available parameters")
class Renderer(base.Renderer):
_template = ViewPageTemplateFile('parameters.pt')
@property
def available(self):
"""Should the portlet be shown?
Portlet is available when there are keys.
They are only handy for showing when viewing (editing really)
a Document within portal_jobperformance or portal_contracts.
"""
url = self.context.absolute_url()
tool_ids = ('portal_jobperformance', 'portal_contracts')
for tool_id in tool_ids:
if tool_id in url:
if url.split('/')[-1] != tool_id:
return len(self.keys) > 0
return False
return False
def render(self):
return self._template()
@property
def keys(self):
context = aq_inner(self.context)
view = context.restrictedTraverse('@@substituter')
return view.keys
class AddForm(base.AddForm):
form_fields = form.Fields(ISubstitutionPortlet)
label = _(u"Add Substitution parameters Portlet")
description = _(u"This portlet displays substitution parameters.")
def create(self, data):
return Assignment()
class EditForm(base.EditForm):
form_fields = form.Fields(ISubstitutionPortlet)
label = _(u"Edit Substitution parameters Portlet")
description = _(u"This portlet displays substitution parameters.")
| [
[
1,
0,
0.0023,
0.0023,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0046,
0.0023,
0,
0.66,
0.0526,
500,
0,
1,
0,
0,
500,
0,
0
],
[
1,
0,
0.0069,
0.0023,
0,
... | [
"from zope.interface import implements",
"from zope.i18n import translate",
"from zope.formlib import form",
"from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile",
"from Acquisition import aq_inner, aq_parent, aq_chain",
"from DateTime import DateTime",
"from Products.Five import Bro... |
import cStringIO
import codecs
import csv
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
MvL modified the original version from the Python documentation
since that version use codecs.getincrementalencoder which is
introduced in version 2.5 and thus not available in our 2.4.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getencoder(encoding)
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder(data)
# write to the target stream
self.stream.write(data[0])
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
class UnicodeDictWriter:
"""Unicode ready version of csv.DictWriter.
Taken from http://www.halley.cc/code/?python/ucsv.py
Made writing of the header optional and did some pep8 changes.
"""
def __init__(self, f, fieldnames, restval="", extrasaction="raise",
dialect="excel", header=False, *args, **kwds):
self.fieldnames = fieldnames # list of keys for the dict
self.restval = restval # for writing short dicts
if extrasaction.lower() not in ("raise", "ignore"):
raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'" %
extrasaction)
self.extrasaction = extrasaction
self.writer = UnicodeWriter(f, dialect, *args, **kwds)
if header:
self.writer.writerow(fieldnames)
def _dict_to_list(self, rowdict):
if self.extrasaction == "raise":
for k in rowdict.keys():
if k not in self.fieldnames:
raise ValueError("dict contains fields not in fieldnames")
return [rowdict.get(key, self.restval) for key in self.fieldnames]
def writerow(self, rowdict):
return self.writer.writerow(self._dict_to_list(rowdict))
def writerows(self, rowdicts):
rows = []
for rowdict in rowdicts:
rows.append(self._dict_to_list(rowdict))
return self.writer.writerows(rows)
| [
[
1,
0,
0.0135,
0.0135,
0,
0.66,
0,
764,
0,
1,
0,
0,
764,
0,
0
],
[
1,
0,
0.027,
0.0135,
0,
0.66,
0.25,
220,
0,
1,
0,
0,
220,
0,
0
],
[
1,
0,
0.0405,
0.0135,
0,
0.6... | [
"import cStringIO",
"import codecs",
"import csv",
"class UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n\n MvL modified the original version from the Python documentation\n since that version use codecs.getincrementale... |
from zope.interface import Interface, Attribute
from zope.viewlet.interfaces import IViewletManager
from plone.portlets.interfaces import IPortletDataProvider
class IEmployeeView(Interface):
def extraItems():
""" Return all non hrm specific items
"""
class IWorkLocationView(Interface):
def alternative_views():
"""List of dictionaries with url, title to alternative views.
"""
def active_employees():
"""Return list of active employees.
"""
def inactive_employees():
"""Return list of inactive employees.
"""
class IWorkLocationState(Interface):
def is_worklocation():
"""Return whether the current context is a worklocation."""
def current_worklocation():
"""Return the worklocation in the acquisition chain."""
def in_worklocation():
"""Return if there is a worklocation in the acquisition chain."""
def all_worklocations():
"""Return the brains of all available worklocations."""
class ISubstitutionView(Interface):
params = Attribute("Keys and substitution values")
keys = Attribute("Keys available for substitution")
class ISubstitutionPortlet(IPortletDataProvider):
pass
class IEmployeeDetails(IViewletManager):
"""A viewlet manager that renders all viewlets registered by extension
modules.
"""
class IEmployeesOverview(IViewletManager):
"""A viewlet manager that renders all viewlets registered by extension
modules.
"""
| [
[
1,
0,
0.0161,
0.0161,
0,
0.66,
0,
443,
0,
2,
0,
0,
443,
0,
0
],
[
1,
0,
0.0323,
0.0161,
0,
0.66,
0.1111,
229,
0,
1,
0,
0,
229,
0,
0
],
[
1,
0,
0.0484,
0.0161,
0,
... | [
"from zope.interface import Interface, Attribute",
"from zope.viewlet.interfaces import IViewletManager",
"from plone.portlets.interfaces import IPortletDataProvider",
"class IEmployeeView(Interface):\n\n def extraItems():\n \"\"\" Return all non hrm specific items\n \"\"\"",
" def extra... |
import csv
from Products.Five import BrowserView
from zope.i18n import translate
from zope.event import notify
from Products.Archetypes.event import ObjectInitializedEvent
from Products.CMFPlone.utils import safe_unicode
from Acquisition import aq_inner
from Products.plonehrm.content.employee import Employee, Employee_schema
class CSVImport(BrowserView):
def __init__(self, context, request):
self.context = context
self.request = request
# Employees created form the CSV file.
self.created_employees = []
self.no_file = False
self.invalid_file = False
def reverse_translate(self, value, vocab_method):
""" Try to find the database name for a value from
its translation in the current language.
"""
if not vocab_method in dir(Employee):
# Should not happen.
return value
vocabulary = eval('Employee(self.context).%s()' % vocab_method)
if type(vocabulary) in [tuple, list]:
# In this case there is no translations, so the value is the one
# stored in the database.
return value
for name, label in vocabulary.items():
if value.lower() == translate(label,
context = self.request).lower():
return name
# If we arrive here, that means that we did not find a suitable
# translation.
return None
def make_title(self, data):
""" Basically a copy/paste of Employee.Title.
"""
fields = ['firstName', 'middleName', 'lastName']
parts = []
for field in fields:
if field in data:
parts.append(data[field])
if not parts:
return u''
# Filter out the empty bits:
parts = [safe_unicode(part) for part in parts if part]
return u' '.join(parts)
def __call__(self):
form = self.request.form
# The form has not been submitted.
if not 'file' in form:
return self.index()
if not form['file']:
self.no_file = True
return self.index()
data = csv.DictReader(form['file'])
# A dictionnary representing employee fields and their translation
# in the current language.
# The key is the translation and the value is the field created in
# the schema.
employee_fields = {}
for field in Employee_schema.fields():
field_translation = translate(field.widget.label,
context=self.request)
employee_fields[field_translation] = field
row = data.next()
while row:
# We build a dictionnary that looks like those
# received when submitting a form.
emp_data = {}
for item in row:
field = None
for emp_f in employee_fields:
if emp_f.lower() == item.lower():
field = employee_fields[emp_f]
break
if not field:
continue
# Check if we have to translate the field.
if field.vocabulary:
value = self.reverse_translate(row[item],
field.vocabulary)
else:
value = row[item]
emp_data[field.getName()] = value
emp_data['title'] = self.make_title(emp_data)
context = aq_inner(self.context)
new_id = context.generateUniqueId('Employee')
context.invokeFactory("Employee", id=new_id,
title=emp_data['title'])
new_emp = getattr(context, new_id)
# We store the informations.
new_emp.update(**emp_data)
new_emp._renameAfterCreation()
new_emp.unmarkCreationFlag()
notify(ObjectInitializedEvent(new_emp))
self.created_employees.append(new_emp)
try:
row = data.next()
except:
row=None
return self.index()
| [
[
1,
0,
0.0074,
0.0074,
0,
0.66,
0,
312,
0,
1,
0,
0,
312,
0,
0
],
[
1,
0,
0.0222,
0.0074,
0,
0.66,
0.125,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.0296,
0.0074,
0,
0... | [
"import csv",
"from Products.Five import BrowserView",
"from zope.i18n import translate",
"from zope.event import notify",
"from Products.Archetypes.event import ObjectInitializedEvent",
"from Products.CMFPlone.utils import safe_unicode",
"from Acquisition import aq_inner",
"from Products.plonehrm.con... |
from DateTime import DateTime
from Acquisition import aq_inner, aq_parent, aq_chain
from Products.CMFCore.utils import getToolByName
from Products.Five import BrowserView
from zope.i18n import translate
from zope.component import getMultiAdapter
from zope.viewlet.interfaces import IViewletManager
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm.browser.interfaces import IWorkLocationState
from Products.plonehrm.interfaces import IWorkLocation
class AbsenceOverview(BrowserView):
""" Provides an overview of every absences in every worklocations.
"""
def __call__(self):
""" When calling the view, we compute 4 different things.
- the average count of absences
- the average percentage of days absent
- the average total of absences
- a dictionnary containing all data needed to be displayed.
This dictionnary looks like this.
{worklocation: {'rows': [rows generated by plonehrm.employees-absence],
'average_total': average total of absence for this WL,
'average_percentage': average percentage of absences for this WL,
'average_count': avserage count of absences for this worklocation}}
"""
self.data = {}
self.average_count = 0
self.average_percentage = 0
self.average_total = 0
self.employees_total = 0
# First, we find every worklocations.
worklocation_state = getMultiAdapter((self.context, self.request),
name=u'worklocation_state')
location_brains = worklocation_state.all_worklocations()
for brain in location_brains:
worklocation = brain.getObject()
# Get the viewlet for this WL and computes data.
viewlet = getMultiAdapter((worklocation, self.request, self),
IViewletManager,
name='plonehrm.employees-absence')
viewlet.update()
for row in viewlet.rows:
self.employees_total += 1
self.average_count += row[-1]
self.average_percentage += int(row[-2][:-1])
self.average_total += row[-3]
self.data[worklocation] = {'rows': viewlet.rows,
'average_total': viewlet.average_total,
'average_percentage': viewlet.average_percentage,
'average_count': viewlet.average_count}
if self.employees_total:
self.average_count /= self.employees_total
self.average_percentage /= self.employees_total
self.average_total /= self.employees_total
return self.index()
| [
[
1,
0,
0.0145,
0.0145,
0,
0.66,
0,
556,
0,
1,
0,
0,
556,
0,
0
],
[
1,
0,
0.029,
0.0145,
0,
0.66,
0.1,
62,
0,
3,
0,
0,
62,
0,
0
],
[
1,
0,
0.0435,
0.0145,
0,
0.66,
... | [
"from DateTime import DateTime",
"from Acquisition import aq_inner, aq_parent, aq_chain",
"from Products.CMFCore.utils import getToolByName",
"from Products.Five import BrowserView",
"from zope.i18n import translate",
"from zope.component import getMultiAdapter",
"from zope.viewlet.interfaces import IVi... |
from Acquisition import Explicit
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.interface import implements
from zope.viewlet.interfaces import IViewlet
class FileViewlet(Explicit):
implements(IViewlet)
render = ViewPageTemplateFile('file.pt')
def __init__(self, context, request, view=None, manager=None):
self.__parent__ = view
self.context = context
self.request = request
self.view = view
self.manager = manager
# This attribute is used to know how the viewlet is
# displayed.
# If True, the list of File is displayed. If false,
# the upload form is displayed.
self.show_list = True
def update(self):
pass
def add_url(self):
""" Add new file
"""
# check Add permission on employee
# return None if we don't have permission
mtool = getToolByName(self.context, 'portal_membership')
if mtool.checkPermission('ATContentTypes: Add File', self.context):
url = self.context.absolute_url() + '/createObject?type_name=File'
return url
def file_list(self):
# Return image too while we are at it.
contentFilter = {'portal_type': ('File', 'Image')}
brains = self.context.getFolderContents(contentFilter=contentFilter)
def date_key(item):
return item['created']
items = sorted(brains, key=date_key)
items.reverse()
return items
| [
[
1,
0,
0.0208,
0.0208,
0,
0.66,
0,
62,
0,
1,
0,
0,
62,
0,
0
],
[
1,
0,
0.0417,
0.0208,
0,
0.66,
0.2,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.0625,
0.0208,
0,
0.66,... | [
"from Acquisition import Explicit",
"from Products.CMFCore.utils import getToolByName",
"from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile",
"from zope.interface import implements",
"from zope.viewlet.interfaces import IViewlet",
"class FileViewlet(Explicit):\n implements(IViewlet... |
# make me a python package | [] | [] |
from DateTime import DateTime
from Acquisition import aq_inner, aq_parent, aq_chain
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone import Batch
from Products.Five import BrowserView
from plone.memoize.view import memoize
from zope.interface import implements
from kss.core import kssaction, KSSView
from zope.i18n import translate
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm.browser.interfaces import IWorkLocationState
from Products.plonehrm.interfaces import IWorkLocation
class AltView(BrowserView):
def can_import_csv(self):
membership = getToolByName(self.context, 'portal_membership')
return membership.checkPermission('plonehrm: import CSV',
self.context)
def alternative_views(self):
"""List of dictionaries with url, title to alternative views.
"""
views = []
context_view = self.context.restrictedTraverse('@@plone_context_state')
template_id = context_view.current_base_url().split('/')[-1]
# default view
if context_view.is_view_template():
url = False
else:
url = context_view.canonical_object_url()
views.append(dict(url = url,
title = _(u"Hired")))
# improvement areas view
if template_id == "improvements":
url = False
else:
url = context_view.canonical_object_url() + "/improvements"
views.append(dict(url = url,
title = _(u"Improvement areas")))
# improvement areas view
if template_id == "absence":
url = False
else:
url = context_view.canonical_object_url() + "/absence"
views.append(dict(url = url,
title = _(u"Absences")))
# facebook view
if template_id == "facebook":
url = False
else:
url = context_view.canonical_object_url() + "/facebook"
views.append(dict(url = url,
title = _(u"Facebook")))
# checklist view
if template_id == "checklist":
url = False
else:
url = context_view.canonical_object_url() + "/checklist"
views.append(dict(url = url,
title = _(u"Tasks")))
# inactive employees view
if template_id == "inactive_employees":
url = False
else:
url = context_view.canonical_object_url() + "/inactive_employees"
views.append(dict(url = url,
title = _(u"Dismissed")))
if self.can_import_csv():
# inactive employees view
if template_id == "import_csv":
url = False
else:
url = context_view.canonical_object_url() + "/import_csv"
views.append(dict(url = url,
title = _(u"Import")))
return views
class WorkLocationView(BrowserView):
@property
def active_employees(self):
"""Return list of active employees.
"""
contentFilter = {'portal_type': 'Employee',
'review_state': 'active'}
return self.context.getFolderContents(contentFilter=contentFilter)
@property
def inactive_employees(self):
"""Return list of inactive employees.
"""
contentFilter = {'portal_type': 'Employee',
'review_state': 'inactive'}
return self.context.getFolderContents(contentFilter=contentFilter)
class WorkLocationState(BrowserView):
implements(IWorkLocationState)
@memoize
def is_worklocation(self):
"""Return whether the current context is a worklocation."""
return IWorkLocation.providedBy(self.context)
@memoize
def current_worklocation(self):
"""Return the worklocation in the acquisition chain."""
item = aq_inner(self.context)
while (item is not None and
not IWorkLocation.providedBy(item)):
item = aq_parent(item)
return item
@memoize
def in_worklocation(self):
"""Return if there is a worklocation in the acquisition chain."""
if self.current_worklocation() is not None:
return True
return False
@memoize
def all_worklocations(self):
"""Return the brains of all available worklocations."""
catalog = getToolByName(self.context, 'portal_catalog')
brains = catalog.searchResults(portal_type='WorkLocation')
return brains
class ChecklistInlineEditDate(BrowserView):
""" Page called with jQuery to update an item date.
"""
def __call__(self):
if 'date' in self.request:
date = self.request.date
else:
return
if 'item_id' in self.request:
item_id = self.request.item_id
else:
return
# We get the item
ids = item_id.split('-')
if not len(ids) == 2:
return
# We get the employee.
catalog = getToolByName(self.context, 'portal_catalog')
employees = catalog.searchResults(portal_type='Employee')
employee = None
for emp in employees:
if emp.UID == ids[0]:
employee = emp.getObject()
if not employee:
return
# We get the item
try:
checklist = employee['checklist']
except:
return
item = checklist.findItem(id=int(ids[1]))
if not item:
return
# We get a date that can be used
if date:
date_split = date.split('-')
if not len(date_split) == 3:
return
date = "%s/%s/%s" % (date_split[2],
date_split[1],
date_split[0])
date = DateTime(date)
item.date = date
msg = _(u'msg_checklist_inline_done',
u'Due date has been updated')
props = getToolByName(self.context, 'portal_properties')
lang = props.site_properties.getProperty('default_language')
# This is ugly. But the dd element of kssPortalMessage does not
# have id or class, so we can not directly inject text in it with
# jQuery.
return '<dt>Info</dt><dd>%s</dd>' % \
translate(msg, target_language=lang)
class ChecklistView(BrowserView):
""" Displays a page with all checklist items.
"""
def __init__(self, context, request):
self.context = context
self.request = request
self.items = {}
self.sorted_items = []
@property
def isContextWorklocation(self):
""" Returns True if the current context is a worklocation.
"""
return self.context.getPortalTypeName() == 'WorkLocation'
def make_date(self, date):
""" Transforms a date into dd-mm-yyyy format.
We do not use 'toLocalizedTime' for the moment, as the site might
use other languages than Dutch (and so other date format)
"""
def prepend_zero(value):
if len(value) == 1:
return '0' + value
else:
return value
day = prepend_zero(str(date.day()))
month = prepend_zero(str(date.month()))
year = str(date.year())
return '%s-%s-%s' % (day, month, year)
def get_items(self):
""" Returns a dictionnary representing the items and the objects
we need to display (worklocation and employee)
The dictionnary looks like this:
{ item : [employee, worklocation],
item : ... }
"""
# We get every checklist (we can not get directly the items).
catalog = getToolByName(self.context, 'portal_catalog')
checklists = [checklist.getObject() for checklist in
catalog.searchResults(portal_type='Checklist')
if self.context in aq_chain(checklist.getObject())]
for checklist in checklists:
for item in checklist.items:
self.items[item] = [aq_parent(checklist),
aq_parent(aq_parent(checklist))]
# We create the sorted_items list, which will give the order
# to read the dictionnary (dictionnaries can not be sorted).
def employee_name_key(item):
return item[1][0].getLastName()
self.sorted_items = [key for key, value in
sorted(self.items.items(),
key=employee_name_key)]
return self.items
def __call__(self):
""" Process the form and shows the page again.
"""
form = self.request.form
catalog = getToolByName(self.context, 'portal_catalog')
props = getToolByName(self.context, 'portal_properties')
lang = props.site_properties.getProperty('default_language')
for item in form:
# We check that the name and the value are identical, which
# means that we are treating an checkbox item, not a date field.
if not form[item] == item:
continue
# The item value defines two ids, the employee UID
# and the item id.
ids = item.split('-')
if not len(ids) == 2:
continue
# We get the right employee
employees = catalog.searchResults(portal_type='Employee')
employee = None
for emp in employees:
if emp.UID == ids[0]:
employee = emp.getObject()
if not employee:
continue
try:
checklist = employee['checklist']
except:
continue
checklist.checkItem(id=int(ids[1]))
# We finally mark the item as done.
self.context.plone_utils.addPortalMessage(translate(
_(u'msg_items_updated',
u'Tasks have been marked as done.'),
target_language=lang))
return self.index()
| [
[
1,
0,
0.0032,
0.0032,
0,
0.66,
0,
556,
0,
1,
0,
0,
556,
0,
0
],
[
1,
0,
0.0063,
0.0032,
0,
0.66,
0.0625,
62,
0,
3,
0,
0,
62,
0,
0
],
[
1,
0,
0.0095,
0.0032,
0,
0.... | [
"from DateTime import DateTime",
"from Acquisition import aq_inner, aq_parent, aq_chain",
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFPlone import Batch",
"from Products.Five import BrowserView",
"from plone.memoize.view import memoize",
"from zope.interface import implements",... |
from Acquisition import Explicit
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone import Batch
from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.i18n import translate
from zope.interface import Interface, implements
from zope.viewlet.interfaces import IViewlet
from Products.plonehrm import utils
from Products.plonehrm import PloneHrmMessageFactory as _
try:
from plonehrm.absence.absence import IAbsenceAdapter
except ImportError:
IAbsenceAdapter = None
class IPersonalDataView(Interface):
pass
class PersonalDataView(Explicit):
"""Viewlet that renders the personal data
Shown within the employee viewlet manager.
"""
implements(IViewlet)
render = ViewPageTemplateFile('personaldata.pt')
def __init__(self, context, request, view=None, manager=None):
self.__parent__ = view
self.context = context
self.request = request
self.view = view
self.manager = manager
def age(self):
return utils.age(self.context)
class PhoneView(Explicit):
"""Return the phone number of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'Phone'
def render(self):
return self.context.getTelephone()
class MobileView(Explicit):
"""Return the mobile number of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'Mobile'
def render(self):
return self.context.getMobilePhone()
class AddressView(Explicit):
"""Return the address of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'Address'
def render(self):
return self.context.getAddress()
class ZipCodeView(Explicit):
"""Return the zip code of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'ZipCode'
def render(self):
return self.context.getPostalCode()
class CityView(Explicit):
"""Return the city of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'City'
def render(self):
return self.context.getCity()
class EmployeeView(BrowserView):
@property
def extraItems(self):
all = self.context.getFolderContents()
# Filter out the employee module items.
moduleTypes = []
portal_props = getToolByName(self.context,
'portal_properties', None)
if portal_props is not None:
hrm_props = getattr(portal_props, 'plonehrm_properties', None)
if hrm_props is not None:
moduleTypes = hrm_props.getProperty(
'employee_module_portal_types', ())
rest = [item for item in all
if item['portal_type'] not in moduleTypes]
# Turn 'rest' into a batch for the benefit of the tabular folder
# macro.
b_start = 0
b_size = 1000
rest = Batch(rest, b_size, b_start, orphan=0)
return rest
class FullnameView(Explicit):
"""Return the fullname of the current employee"""
implements(IViewlet)
def __init__(self, context, request, view, manager):
self.context = context
self.request = request
self.view = view
self.manager = manager
def header(self):
return 'Fullname'
def is_arbo(self):
""" Checks if the user has Arbo manager rights.
"""
membership = getToolByName(self.context, 'portal_membership')
return membership.checkPermission('plonehrm: manage Arbo content',
self.context)
def render(self):
absence_html = u''
if self.is_sick():
days = self.days_absent()
if days == 1:
absence = _('1_day_absent',
default=u'(1 day absent)')
else:
absence = _(u'x_days_absent',
default=u'(${days} days absent)',
mapping={'days': days})
absence = translate(absence, context=self.request)
absence_html = '<span class="absencetext">%s</span>' % absence
link_html = '<a href="%s">%s</a>' % (
self.context.absolute_url(),
self.context.Title())
return u' '.join([link_html, absence_html])
def is_sick(self):
if IAbsenceAdapter is None:
return False
absences = IAbsenceAdapter(self.context)
return bool(absences.current_absence())
def days_absent(self):
if IAbsenceAdapter is None or not self.is_sick():
return None
absences = IAbsenceAdapter(self.context)
absence = absences.current_absence()
return absence.days_absent(self.is_arbo())
| [
[
1,
0,
0.0051,
0.0051,
0,
0.66,
0,
62,
0,
1,
0,
0,
62,
0,
0
],
[
1,
0,
0.0102,
0.0051,
0,
0.66,
0.0526,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.0153,
0.0051,
0,
0.... | [
"from Acquisition import Explicit",
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFPlone import Batch",
"from Products.Five import BrowserView",
"from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile",
"from zope.i18n import translate",
"from zope.interface impor... |
from zope.interface import implements
from plone.app.workflow.interfaces import ISharingPageRole
# Please keep this 'PMF' and not '_' as otherwise i18ndude picks it
# up, does not realize it is for the plone domain and puts it in the
# pot/po files of plonehrm. Alternatively: exclude this file in
# rebuild_i18n.sh
from Products.CMFPlone import PloneMessageFactory as PMF
# Only managers can manage these
class HrmManagerRole(object):
implements(ISharingPageRole)
title = PMF(u"title_hrm_manager_role",
default="HRM manager")
required_permission = 'Manage portal'
class WorklocationManagerRole(object):
implements(ISharingPageRole)
title = PMF(u"title_worklocation_manager_role",
default="HRM worklocation manager")
required_permission = 'Manage portal'
| [
[
1,
0,
0.0385,
0.0385,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0769,
0.0385,
0,
0.66,
0.25,
868,
0,
1,
0,
0,
868,
0,
0
],
[
1,
0,
0.3077,
0.0385,
0,
0.... | [
"from zope.interface import implements",
"from plone.app.workflow.interfaces import ISharingPageRole",
"from Products.CMFPlone import PloneMessageFactory as PMF",
"class HrmManagerRole(object):\n implements(ISharingPageRole)\n\n title = PMF(u\"title_hrm_manager_role\",\n default=\"HRM man... |
from Products.validation.interfaces import ivalidator
from DateTime import DateTime
from zope.i18n import translate
from Products.plonehrm import PloneHrmMessageFactory as _
class DateValidator:
__implements__ = (ivalidator, )
def __init__(self, name):
self.name = name
def __call__(self, value, *args, **kwargs):
now = DateTime()
value = DateTime(value)
if value > now:
if value.year() > now.year():
error = _("Date is supposed to be in the past, "
"please enter a valid year.")
elif value.month() > now.month():
error = _("Date is supposed to be in the past, "
"please enter a valid month.")
elif value.day() > now.day():
error = _("Date is supposed to be in the past, "
"please enter a valid day.")
else:
error = ''
if error:
return translate(error, context=kwargs['REQUEST'])
return True
class AgeValidator:
__implements__ = (ivalidator, )
def __init__(self, name):
self.name = name
def __call__(self, value, *args, **kwargs):
if not value:
return True
now = DateTime()
try:
value = DateTime(value)
except:
error = _("error_invalid_date")
return translate(error, context=kwargs['REQUEST'])
if value.year() > now.year()-12:
error = _("You are too young")
return translate(error, context=kwargs['REQUEST'])
return True
class BSNValidator:
""" This validator ensures that a BSN number is valid.
It takes as input a string, composed of digits and dots. It returns
True if the value is a correct BSN number and a string indicating the
problem in the other cases.
XXX Note: this is valid for Dutch SOFI/BurgerServiceNumbers. We
may want to let this work for other countries as well.
We create an instance of the validator.
>>> bsnValid = BSNValidator('bsn')
Now we check its behavior.
It first removes the dots form the string.
>>> bsnValid.remove_dots('')
''
>>> bsnValid.remove_dots('123')
'123'
>>> bsnValid.remove_dots('.123')
'123'
>>> bsnValid.remove_dots('123.')
'123'
>>> bsnValid.remove_dots('1.2.3')
'123'
>>> bsnValid.remove_dots('.')
''
>>> bsnValid.remove_dots('..')
''
Then it checks the length of the string and that it contains only
valid characters.
This one contains an invalid character.
>>> bsnValid.validate('123.45.6a.38')
u'bsn_validation_bad_input'
This one too.
>>> bsnValid.validate('123.45.67,38')
u'bsn_validation_bad_input'
This one could be valid if it was long enough
>>> bsnValid.validate('16.51')
u'bsn_validation_bad_length'
Then, it computes the sum of digits, multiplied by their rank.
For example, it the BSN number is ac.bd.ef.ghi, the sum will be
a*9 + b*8 + c*7 + d*6 + e*5 + f*4 + g*3 + h*2 + i*-1
(note the minus for the last digit)
>>> bsnValid.make_number_sum(0)
0
>>> bsnValid.make_number_sum(1)
-1
This shall return 4*3 + 5*2 + 6*-1
>>> bsnValid.make_number_sum(456)
16
>>> bsnValid.make_number_sum(32154876)
117
Just to check.
>>> 6*-1 + 7*2 + 8*3 + 4*4 + 5*5 + 1*6 + 2*7 + 3*8
117
With a supposedly real BSN.
>>> bsnValid.make_number_sum(736160231)
176
If the sum of the number can be divided by 11, then the number is correct.
This one is correct.
>>> bsnValid.validate('73.61.60.231')
True
It is still correct with a 0 at the beginning.
>>> bsnValid.validate('073.61.60.231')
True
This one is not correct.
>>> bsnValid.validate('073.61.60.221')
u'bsn_validation_failed'
"""
__implements__ = (ivalidator, )
def remove_dots(self, value):
""" This method removes dots from a string.
We assume that the BSN number entered by the user only
contains digits and dots.
"""
return ''.join(value.split('.'))
def make_number_sum(self, value):
""" Compute the sum of digits in a number multiplied by their rank.
Only some numbers are valid. Each digit gets multiplied
depending on its position.
"""
# special case for the last digit: multiply by a negative number
total = (value % 10) * -1
value = value / 10
for i in range(2, 11):
total += i * (value % 10)
value = value / 10
return total
def validate(self, value):
""" Validates a BSN number. Returns True if the value is a valid
BSN number or a message instead.
We extracted this function to allow unitary testing.
"""
# First, we remove the dots.
value = self.remove_dots(value)
# Then we check the length of the string. We do it before casting
# it into an integer, as we might lose the first zeros.
if not len(value) in [9, 10]:
return _(u'bsn_validation_bad_length',
u'BSN numbers are supposed to have 9 or 10' + \
' characters (excluding dots).')
# Now we cast it and ensures that there is only digits in the string.
try:
value = int(value)
except:
return _(u'bsn_validation_bad_input',
u'The BSN number can only contain digits and dots.')
total = self.make_number_sum(value)
if total % 11 == 0:
return True
return _(u'bsn_validation_failed',
u'This is not a valid BSN number.')
def __init__(self, name):
self.name = name
def __call__(self, value, *args, **kwargs):
result = self.validate(value)
if result == True:
return True
else:
return translate(result, context=kwargs['REQUEST'])
| [
[
1,
0,
0.0048,
0.0048,
0,
0.66,
0,
842,
0,
1,
0,
0,
842,
0,
0
],
[
1,
0,
0.0095,
0.0048,
0,
0.66,
0.1667,
556,
0,
1,
0,
0,
556,
0,
0
],
[
1,
0,
0.0143,
0.0048,
0,
... | [
"from Products.validation.interfaces import ivalidator",
"from DateTime import DateTime",
"from zope.i18n import translate",
"from Products.plonehrm import PloneHrmMessageFactory as _",
"class DateValidator:\n __implements__ = (ivalidator, )\n\n def __init__(self, name):\n self.name = name\n\n ... |
from Products.ATContentTypes.content.document import ATDocument
from Products.ATContentTypes.content.document import ATDocumentSchema
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import registerType
from Products.plonehrm.config import PROJECTNAME
from Products.plonehrm import PloneHrmMessageFactory as _
TemplateSchema = ATDocumentSchema.copy() + Schema((
StringField(
name='type',
required=True,
vocabulary=['undefined', 'contract', 'letter',
'job_performance', 'absence_evaluation'],
widget=SelectionWidget(
label=_(u'label_templateType',
default=u'Template type'),
),
),
),
)
for schema_key in TemplateSchema.keys():
if not TemplateSchema[schema_key].schemata == 'default':
TemplateSchema[schema_key].widget.visible={'edit':'invisible',
'view':'invisible'}
class Template(ATDocument):
""" This archetype is used to store every templates that can be
defined in plone HRM:
- contracts templates
- letter templates
- job performance templates
- absence evaluation templates
"""
schema = TemplateSchema
meta_type = "Template"
registerType(Template, PROJECTNAME)
| [
[
1,
0,
0.0227,
0.0227,
0,
0.66,
0,
880,
0,
1,
0,
0,
880,
0,
0
],
[
1,
0,
0.0455,
0.0227,
0,
0.66,
0.0909,
880,
0,
1,
0,
0,
880,
0,
0
],
[
1,
0,
0.0682,
0.0227,
0,
... | [
"from Products.ATContentTypes.content.document import ATDocument",
"from Products.ATContentTypes.content.document import ATDocumentSchema",
"from Products.Archetypes.atapi import StringField",
"from Products.Archetypes.atapi import SelectionWidget",
"from Products.Archetypes.atapi import Schema",
"from Pr... |
# -*- coding: utf-8 -*-
import worklocation
import employee
import template
| [
[
1,
0,
0.5,
0.25,
0,
0.66,
0,
128,
0,
1,
0,
0,
128,
0,
0
],
[
1,
0,
0.75,
0.25,
0,
0.66,
0.5,
70,
0,
1,
0,
0,
70,
0,
0
],
[
1,
0,
1,
0.25,
0,
0.66,
1,
549,... | [
"import worklocation",
"import employee",
"import template"
] |
__author__ = """Reinout van Rees <reinout@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from AccessControl import ClassSecurityInfo
from Products.ATContentTypes.content.folder import ATFolder
from Products.ATContentTypes.content.folder import ATFolderSchema
from Products.Archetypes.public import BaseFolder
from Products.Archetypes.public import BaseFolderSchema
from Products.Archetypes.atapi import DisplayList
from Products.Archetypes.atapi import LinesField
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import StringWidget
from Products.Archetypes.atapi import IntegerField
from Products.Archetypes.atapi import IntegerWidget
from Products.Archetypes.atapi import registerType
from Products.Archetypes.atapi import BooleanField
from Products.Archetypes.atapi import BooleanWidget
from zope.interface import implements
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm import config
from Products.plonehrm.interfaces import IWorkLocation
schema = Schema((
StringField(
name='address',
widget=StringWidget(
label=_(u'plonehrm_label_address',
default=u'Work Location Address'),
description=_(
u'plonehrm_help_address',
default=u'Visiting address of the actual work location'),
),
),
StringField(
name='postalCode',
widget=StringWidget(
label=_(u'plonehrm_label_postalCode',
default=u'Work Location Zip Code'),
),
),
StringField(
name='city',
widget=StringWidget(
label=_(u'plonehrm_label_city',
default=u'Work Location City'),
),
),
StringField(
name='contactPerson',
widget=StringWidget(
label=_(u'plonehrm_label_contactperson',
default=u'Contact person'),
),
),
StringField(
name='telephone',
widget=StringWidget(
label=_(u'plonehrm_label_telephone', default=u'Phone number'),
),
),
StringField(
name='officialName',
widget=StringWidget(
label=_(u'plonehrm_label_officialName',
default=u'Legal company name'),
),
),
StringField(
name='companyAddress',
widget=StringWidget(
label=_(u'plonehrm_label_companyAddress',
default=u'Company Address'),
description=_(u'plonehrm_help_companyAddress',
default=u'Postal address of the main office'),
),
),
StringField(
name='companyPostalCode',
widget=StringWidget(
label=_(u'plonehrm_label_companyPostalCode',
default=u'Company Zip Code'),
),
),
StringField(
name='companyCity',
widget=StringWidget(
label=_(u'plonehrm_label_companyCity',
default=u'Company City'),
),
),
IntegerField(
name='vacationDays',
widget=IntegerWidget(
label=_(u'plonehrm_label_vacationDays', default=u'Vacation days'),
description=_(u'plonehrm_help_vacationDays',
default=u'Number of vacation days per year'),
),
),
StringField(
name='payPeriod',
widget=SelectionWidget(
label=_(u'label_pay_period', default=u'Pay period'),
),
vocabulary='_payPeriodVocabulary',
),
StringField(
name='insuranceName',
widget=StringWidget(
label=_(u'label_insurance_name', default=u'Company name'),
),
schemata = 'insurance',
),
StringField(
name='insuranceNumber',
widget=StringWidget(
label=_(u'label_insurance_number', default=u'Insurance number'),
),
schemata = 'insurance',
),
StringField(
name='insuranceContact',
widget=StringWidget(
label=_(u'label_insurance_contact', default=u'Contact name'),
),
schemata = 'insurance',
),
StringField(
name='insuranceAddress',
widget=StringWidget(
label=_(u'label_insurance_address', default=u'Address'),
),
schemata = 'insurance',
),
StringField(
name='insuranceZipCode',
widget=StringWidget(
label=_(u'label_insurance_zipcode', default=u'Zip code'),
),
schemata = 'insurance',
),
StringField(
name='insuranceCity',
widget=StringWidget(
label=_(u'label_insurance_city', default=u'City'),
),
schemata = 'insurance',
),
StringField(
name='insurancePhone',
widget=StringWidget(
label=_(u'label_insurance_phone', default=u'Phone'),
),
schemata = 'insurance',
),
BooleanField(
name='createLetterWhenExpiry',
default=False,
widget = BooleanWidget(
label=_(u'contract_label_createLetterWhenExpiry',
u'Create a letter when contract expires?'),
description = _(u'contract_desc_createLetterWhenExpiry',
u'By default, a task will be created to inform'
' you that a new contract should be created. If'
' you check this box, the task will propose you'
' to create a new letter instead.'),
),
),
),
)
WorkLocation_schema = BaseFolderSchema.copy() + schema.copy()
WorkLocation_schema['title'].widget.label = _(
u'plonehrm_label_trade_name', default=u'Trade Name')
# Move description field out of the way:
WorkLocation_schema['description'].schemata = 'categorization'
for schema_key in WorkLocation_schema.keys():
if WorkLocation_schema[schema_key].schemata in ['metadata',
'categorization']:
WorkLocation_schema[schema_key].widget.visible={'edit':'invisible',
'view':'invisible'}
class WorkLocation(BaseFolder):
"""
"""
security = ClassSecurityInfo()
__implements__ = (getattr(BaseFolder, '__implements__', ()), )
implements(IWorkLocation)
_at_rename_after_creation = True
schema = WorkLocation_schema
security.declarePublic('_payPeriodVocabulary')
def _payPeriodVocabulary(self):
"""Return vocabulary for payPeriod.
Well, they are titles really.
"""
return DisplayList([
('month', _('label_pay_period_month', u'month')),
('4weeks', _('label_pay_period_four_weeks', u'4 weeks')),
('1week', _('label_pay_period_one_week', u'1 week')),
])
registerType(WorkLocation, config.PROJECTNAME)
| [
[
1,
0,
0.0204,
0.0204,
0,
0.66,
0,
227,
0,
1,
0,
0,
227,
0,
0
],
[
1,
0,
0.0612,
0.0204,
0,
0.66,
0.05,
284,
0,
1,
0,
0,
284,
0,
0
],
[
1,
0,
0.0816,
0.0204,
0,
0.... | [
"from AccessControl import ClassSecurityInfo",
"from Products.ATContentTypes.content.folder import ATFolder",
"from Products.ATContentTypes.content.folder import ATFolderSchema",
"from Products.Archetypes.public import BaseFolder",
"from Products.Archetypes.public import BaseFolderSchema",
"from Products.... |
__author__ = """Reinout van Rees <reinout@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from datetime import date, timedelta
from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import BaseFolder
from Products.Archetypes.atapi import BaseFolderSchema
from Products.Archetypes.atapi import CalendarWidget
from Products.Archetypes.atapi import ComputedField
from Products.Archetypes.atapi import DateTimeField
from Products.Archetypes.atapi import DisplayList
from Products.Archetypes.atapi import registerType
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import StringWidget
from Products.Archetypes.atapi import ImageField
from Products.Archetypes.atapi import ImageWidget
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone import PloneMessageFactory as PMF
from Products.CMFPlone.interfaces.structure import INonStructuralFolder
from Products.CMFPlone.utils import safe_unicode
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm import config
from Products.plonehrm.interfaces import IEmployee
from zope.interface import implements
from zope.annotation.interfaces import IAnnotations
from persistent.dict import PersistentDict
from persistent.list import PersistentList
from persistent import Persistent
schema = Schema((
StringField(
name='employeeNumber',
widget=StringWidget(
label=_(u'label_employeeNumber', default=u'Employee number'),
),
),
StringField(
name='firstName',
widget=StringWidget(
label=_(u'plonehrm_label_firstName', default=u'Firstname'),
),
),
StringField(
name='middleName',
widget=StringWidget(
label=_(u'plonehrm_label_middleName', default=u'Middle name'),
),
),
StringField(
name='lastName',
widget=StringWidget(
label=_(u'plonehrm_label_lastName', default=u'Last name'),
),
required=1
),
StringField(
name='initials',
widget=StringWidget(
label=_(u'plonehrm_label_initials', default=u'Initials'),
)
),
StringField(
name='address',
widget=StringWidget(
label=_(u'label_address', default='Address'),
),
),
StringField(
name='postalCode',
widget=StringWidget(
label=_(u'label_postalCode', default=u'Postalcode'),
),
),
StringField(
name='city',
widget=StringWidget(
label=_(u'label_city', default=u'City'),
),
),
StringField(
name='state',
widget=StringWidget(
label=_(u'label_state', default=u'State/Province'),
),
),
StringField(
name='country',
widget=StringWidget(
label=_(u'label_country', default=u'Country'),
),
),
StringField(
name='telephone',
widget=StringWidget(
label=_(u'label_telephone', default=u'Phone'),
),
),
StringField(
name='mobilePhone',
widget=StringWidget(
label=_(u'label_mobilePhone', default=u'Mobilephone'),
),
),
StringField(
name='email',
widget=StringWidget(
label=_(u'label_email', default=u'Email'),
),
),
DateTimeField(
name='birthDate',
required=0,
validators=("isDateBeforeToday", "checkIfTooYoung"),
widget=CalendarWidget(
starting_year=1940,
show_hm=0,
label=_(u'label_birthDate', default=u'Birth date'),
),
),
StringField(
name='placeOfBirth',
widget=StringWidget(
label=_(u'label_placeOfBirth', default=u'Place of birth'),
),
),
StringField(
name='gender',
widget=SelectionWidget(
format="select",
label=_(u'label_gender', default=u'Gender'),
),
vocabulary='_genderVocabulary'
),
StringField(
name='civilStatus',
widget=SelectionWidget(
format="select",
label=_(u'label_civilStatus', default=u'Civil status'),
),
vocabulary='_civilStatusVocabulary'
),
StringField(
name='idType',
widget=SelectionWidget(
format="select",
label=_(u'label_idType', default=u'Type of ID'),
),
vocabulary='_idTypeVocabulary'
),
StringField(
name='idNumber',
widget=StringWidget(
label=_(u'label_idNumber', default=u'ID number'),
),
),
DateTimeField(
name='idEndDate',
widget=CalendarWidget(
show_hm=0,
starting_year=2007,
label=_(u'label_idEndDate', default=u'Expiration date'),
),
),
StringField(
name='nationality',
widget=StringWidget(
label=_(u'label_nationality', default=u'Nationality'),
),
),
StringField(
name='socialSecurityNumber',
validators=("isBSNValid"),
widget=StringWidget(
label=_(u'label_socialSecurityNumber',
default=u'Social security number'),
),
),
StringField(
name='bankNumber',
widget=StringWidget(
label=_(u'label_bankNumber', default=u'Bank number'),
),
),
DateTimeField(
name='workStartDate',
validators=("isDateBeforeToday"),
),
ImageField(
name='portrait',
widget=ImageWidget(
label= PMF(u'label_portrait', default=u'Portrait'),
),
original_size=(128, 128),
),
ComputedField(
searchable=True,
name='title',
widget=ComputedField._properties['widget'](
label=_(u'plonehrm_label_title', default=u'Title'),
),
accessor="Title"
),
),
)
Employee_schema = BaseFolderSchema.copy() + schema.copy()
Employee_schema.moveField('description', after='initials')
Employee_schema['title'].widget.visible = 0
Employee_schema['state'].widget.condition = 'object/showState'
Employee_schema['country'].widget.condition = 'object/showCountry'
Employee_schema['workStartDate'].widget.visible = {'edit': 'hidden',
'view': 'invisible'}
for schema_key in Employee_schema.keys():
if not Employee_schema[schema_key].schemata == 'default':
Employee_schema[schema_key].widget.visible={'edit':'invisible',
'view':'invisible'}
class Employee(BaseFolder):
"""
"""
security = ClassSecurityInfo()
__implements__ = (BaseFolder.__implements__, )
implements(IEmployee, INonStructuralFolder)
_at_rename_after_creation = True
schema = Employee_schema
security.declarePublic('Title')
def Title(self):
"""Return title, composed of the first/middle/last names.
"""
# parts = [self.getFirstName(),self.getMiddleName(),self.getLastName()]
parts = [self.getLastName(),self.getMiddleName(),self.getFirstName()]
# Filter out the empty bits:
parts = [safe_unicode(part) for part in parts if part]
return u' '.join(parts)
security.declarePublic('getInitials')
def getInitials(self):
"""Get the initials and possibly add dots
"""
try:
initials = self.initials
except AttributeError:
# Sometimes officialName gets called (to be catalogued)
# before the initials attribute exists.
return u''
if initials and initials.find('.') == -1:
# Add dots here - we have to remove the spaces as they can cause
# weird results (A E T will become A. .E. .T.)
initials = '.'.join(initials.replace(' ', '')) + '.'
return initials
security.declarePublic('officialName')
def officialName(self):
"""
"""
# parts = [self.getInitials(),self.getMiddleName(),self.getLastName()]
# parts = [self.getLastName(),self.getMiddleName(),self.getInitials()]
parts = [self.getLastName(),self.getMiddleName(),self.getFirstName()]
# Filter out the empty bits:
parts = [safe_unicode(part) for part in parts if part]
return u' '.join(parts)
security.declarePublic('hasPortrait')
@property
def hasPortrait(self):
""" Checks if a portrait has been set for this employee.
"""
return bool(self.getPortrait())
security.declarePublic('showState')
def showState(self):
"""Should the state widget be shown?
"""
return self._extractVocabulary(name='show_state',
default=True)
security.declarePublic('showCountry')
def showCountry(self):
"""Should the country widget be shown?
"""
return self._extractVocabulary(name='show_country',
default=True)
security.declarePublic('_genderVocabulary')
def _genderVocabulary(self):
"""Return vocabulary for gender.
Well, they are titles really.
"""
return DisplayList([
('female', _('label_madam', u'Madam')),
('male', _('label_sir', u'Sir')),
])
security.declarePublic('_civilStatusVocabulary')
def _civilStatusVocabulary(self):
"""Return vocabulary for civil status.
"""
return self._extractVocabulary(name='civil_status_vocabulary',
default=[])
security.declarePublic('_idTypeVocabulary')
def _idTypeVocabulary(self):
"""Return vocabulary for ID type.
"""
return self._extractVocabulary(name='id_type_vocabulary',
default=[])
def _extractVocabulary(self, name='', default=True):
"""Return vocabulary by name.
"""
pp = getToolByName(self, 'portal_properties')
pdp = getattr(pp, 'personaldata_properties', None)
if not pdp:
return default
return pdp.getProperty(name, default)
def _getEndEmployeeAnnotations(self):
""" Returns the Annotations linked to the employee.
If they do not exists, it created them.
"""
anno_key = 'plonehrm.employee'
portal = getToolByName(self, 'portal_url').getPortalObject()
annotations = IAnnotations(self)
metadata = annotations.get(anno_key, None)
if metadata is None:
annotations[anno_key] = PersistentDict()
metadata = annotations[anno_key]
metadata['endEmployment'] = PersistentDict()
return metadata
security.declarePublic('getEndEmploymentDate')
def getEndEmploymentDate(self):
""" Returns the date when the employee stopped woking for the
company.
"""
anno = self._getEndEmployeeAnnotations()
if not 'endEmploymentDate' in anno:
return None
return anno['endEmploymentDate']
security.declarePublic('setEndEmploymentDate')
def setEndEmploymentDate(self, date):
anno = self._getEndEmployeeAnnotations()
anno['endEmploymentDate'] = date
# We copy the default end employment checklist items.
try:
portal_checklist = self.portal_checklist
except:
# Should not happen.
return
try:
checklist = self.checklist
except:
# Should not happen.
return
for item in portal_checklist.getEndContractItems():
checklist.addItem(item.text)
security.declarePublic('getEndEmploymentReason')
def getEndEmploymentReason(self):
""" Returns the reason why the employee stopped woking for the
company.
"""
anno = self._getEndEmployeeAnnotations()
if not 'endEmploymentReason' in anno:
return None
return anno['endEmploymentReason']
security.declarePublic('setEndEmploymentReason')
def setEndEmploymentReason(self, reason):
anno = self._getEndEmployeeAnnotations()
anno['endEmploymentReason'] = reason
def get_worked_days(self, start_date, end_date):
""" Provides a dictionnary of boolean to know if
a day was worked or not for the given period.
The keys of the dictionnary are the dates between
start_date and end_date.
Only works for Arbo managers, as we use the way days
are spread in a contract to compute the dictionnary.
"""
def date_key(item):
return item.getStartdate()
def date_caster(day):
""" Casts a DateTime object to datetime.date
"""
return date(day.year(), day.month(), day.day())
# We cast potential datetime to simple dates.
try:
start_date = start_date.date()
except:
pass
try:
end_date = end_date.date()
except:
pass
worked_days = {}
for i in range(0, end_date.toordinal() - start_date.toordinal() + 1):
worked_days[start_date + timedelta(i)] = False
contracts = self.contentValues({'portal_type': 'Contract'})
letters = self.contentValues({'portal_type': 'Letter'})
contracts = sorted(contracts, key = date_key)
for contract in contracts:
try:
contract_end_date = date_caster(contract.expiry_date())
contract_start_date = date_caster(contract.getStartdate())
except:
# One of the date has not been set, the contract can not
# be used to compute worked days.
continue
# Check if the contract covers the period we want.
if contract_end_date.toordinal() < start_date.toordinal() or \
contract_start_date.toordinal() > end_date.toordinal():
continue
# We get the sub-period covered by this contract.
if contract_start_date.toordinal() < start_date.toordinal():
begin = start_date
else:
begin = contract_start_date
if contract_end_date.toordinal() > end_date.toordinal():
end = end_date
else:
end = contract_end_date
end += timedelta(1)
# We get the letters applicable during the contract.
applicable_letters = [letter for letter in letters \
if letter.getStartdate() > \
contract.getStartdate() and \
letter.getStartdate() < \
contract.expiry_date()]
# We sort the letter by start date.
applicable_letters = sorted(applicable_letters,
key = date_key)
# Now, we look for each day from begin to end and will
# mark it as worked or not.
for i in range(0, end.toordinal() - begin.toordinal()):
day = begin + timedelta(i)
if not day in worked_days:
# Should not happen.
continue
letter = None
# We look if a letter covers this period.
for j in reversed(range(0, len(applicable_letters))):
if date_caster(applicable_letters[j].getStartdate()).toordinal() <=\
day.toordinal():
letter = applicable_letters[j]
break
# We get the way hours were spread.
hour_spread = None
if letter:
hour_spread = letter.hour_spread
else:
hour_spread = contract.hour_spread
# We get the information used to know if this
# day was worked.
day_number = day.weekday()
week_number = day.isocalendar()[1]
if week_number % 2:
week_type = 'odd'
else:
week_type = 'even'
# We update the 'worked_days' dictionnary.
key = week_type + '_' + str(day_number)
if key in hour_spread.hours:
worked_days[day] = hour_spread.hours[key] > 0
else:
worked_days[day] = False
return worked_days
def get_last_contract(self):
""" Fetches the last contract (or letter) of the
employee (last in the meaning 'The one that ends the later'
not 'The last one created'.)
"""
contentFilter = {'portal_type': ['Contract', 'Letter']}
brains = self.getFolderContents(contentFilter=contentFilter)
if not brains:
return None
lastContract = brains[0].getObject()
for brain in brains:
contract = brain.getObject()
if contract.expiry_date() > lastContract.expiry_date():
lastContract = contract
return lastContract
registerType(Employee, config.PROJECTNAME)
| [
[
14,
0,
0.0019,
0.0019,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0037,
0.0019,
0,
0.66,
0.0263,
959,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0074,
0.0019,
0,
0.... | [
"__author__ = \"\"\"Reinout van Rees <reinout@zestsoftware.nl>\"\"\"",
"__docformat__ = 'plaintext'",
"from datetime import date, timedelta",
"from AccessControl import ClassSecurityInfo",
"from Products.Archetypes.atapi import BaseFolder",
"from Products.Archetypes.atapi import BaseFolderSchema",
"from... |
from Products.CMFCore.utils import getToolByName
from Products.CMFQuickInstallerTool.interfaces import INonInstallable
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
from zope.app.container.interfaces import INameChooser
from zope.component import getUtility, getMultiAdapter
from zope.interface import implements
import transaction
from Products.plonehrm import config
from Products.plonehrm import utils
from Products.plonehrm.browser import substitution as parameter_portlet
class HiddenProducts(object):
implements(INonInstallable)
def getNonInstallableProducts(self):
return [
u'plonehrm.jobperformance',
u'plonehrm.checklist',
u'plonehrm.contracts',
u'plonehrm.personaldata',
u'plonehrm.notes',
u'plonehrm.absence',
]
def setup(context):
# This is the main method that gets called by genericsetup.
if context.readDataFile('plonehrm.txt') is None:
return
site = context.getSite()
logger = context.getLogger('plonehrm')
install_dependencies(site, logger)
install_placeful_workflow(site, logger)
update_employees(site, logger)
unindex_tools(site, logger)
install_parameter_portlet(site, logger)
add_properties(site, logger)
def install_dependencies(site, logger):
# Since plone 3.1, genericsetup handles dependencies, where we did it by
# hand. I've decided to keep it that way as we're reinstalling everything
# every time. [reinout]
setup = getToolByName(site, 'portal_setup')
qi = getToolByName(site, 'portal_quickinstaller')
for product in config.QI_DEPS:
if not qi.isProductInstalled(product):
qi.installProduct(product, locked=True, hidden=True)
transaction.savepoint(optimistic=True)
logger.info("Installed %s.", product)
# Now reinstall all products for good measure.
qi.reinstallProducts(config.QI_DEPS)
logger.info("Reinstalled %s.", config.QI_DEPS)
def install_placeful_workflow(site, logger):
"""Install our placeful workflow.
We cannot guarantee that CMFPlacefulWorkflow is installed (with
the install_dependencies method) *before* our portal_workflow.xml
has been processed. So we explicitly to process it (again)
afterwards.
"""
logger.info('Explicitly running our portal_placeful_workflow step.')
setup = getToolByName(site, 'portal_setup')
setup.runImportStepFromProfile('profile-Products.plonehrm:default',
'placeful_workflow')
def unindex_tools(site, logger):
# Tools that are added by dependencies unfortunately end up
# visible in the folder_contents. Should possibly be fixed in
# GenericSetup/tool.py:importToolset(). Let's fix it here
# temporarily afterwards for all tool ids that we expect.
possible_ids = ['portal_contracts', 'portal_jobperformance',
'portal_checklist', 'portal_absence']
for id_ in possible_ids:
tool = getToolByName(site, id_, None)
if tool is not None:
tool.unindexObject()
def update_employees(site, logger):
"""Upon a reinstall, make sure all employees have all modules.
"""
catalog = getToolByName(site, 'portal_catalog')
for brain in catalog(portal_type='Employee'):
try:
employee = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
utils.updateEmployee(employee)
logger.info('Updated the employees')
def install_parameter_portlet(site, logger):
"""Add parameter portlets to the right column in the tools.
Note that we cannot do this with portlets.xml, as that doesn't handle
assignments that are not in the portal root, apparently.
"""
contracts = getToolByName(site, 'portal_contracts')
jobperformance = getToolByName(site, 'portal_jobperformance')
tools = (contracts, jobperformance)
for tool in tools:
column = getUtility(IPortletManager, name="plone.rightcolumn",
context=tool)
manager = getMultiAdapter((tool, column), IPortletAssignmentMapping)
portletnames = [v.title for v in manager.values()]
chooser = INameChooser(manager)
assignment = parameter_portlet.Assignment()
title = assignment.title
if title not in portletnames:
manager[chooser.chooseName(title, assignment)] = assignment
def add_properties(site, logger):
"""Add properties to portal_properties.plonehrm_properties.
We do that in python code instead of in propertiestool.xml to
avoid overwriting changes by the user.
Same for personaldata_properties.
"""
portal_props = getToolByName(site, 'portal_properties')
props = portal_props.plonehrm_properties
for propname, propdata in config.PLONEHRM_PROPERTIES.items():
if not props.hasProperty(propname):
props._setProperty(propname, propdata['default'], propdata['type'])
logger.info('Added property %r with default value %r',
propname, propdata['default'])
props = portal_props.personaldata_properties
for propname, propdata in config.PERSONALDATA_PROPERTIES.items():
if not props.hasProperty(propname):
props._setProperty(propname, propdata['default'], propdata['type'])
logger.info('Added property %r with default value %r',
propname, propdata['default'])
| [
[
1,
0,
0.007,
0.007,
0,
0.66,
0,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.014,
0.007,
0,
0.66,
0.0556,
224,
0,
1,
0,
0,
224,
0,
0
],
[
1,
0,
0.021,
0.007,
0,
0.66,
... | [
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFQuickInstallerTool.interfaces import INonInstallable",
"from plone.portlets.interfaces import IPortletAssignmentMapping",
"from plone.portlets.interfaces import IPortletManager",
"from zope.app.container.interfaces import INameChooser",
... |
__author__ = """Reinout van Rees <reinout@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from zope.component.interfaces import IObjectEvent
from zope.interface import Interface
class IHRMCheckEvent(IObjectEvent):
""" An event that is fired at a regular interval
This can be triggered using a cron job.
"""
class IEmployee(Interface):
""" Marker interface for an Employee """
class IEmployeeModule(Interface):
""" Marker interface for an EmployeeModule """
class IWorkLocation(Interface):
""" Marker interface for a WorkLocation """
class ITemplate(Interface):
""" Marker interface for a Template """
| [
[
14,
0,
0.0385,
0.0385,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0769,
0.0385,
0,
0.66,
0.125,
959,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1538,
0.0385,
0,
0.6... | [
"__author__ = \"\"\"Reinout van Rees <reinout@zestsoftware.nl>\"\"\"",
"__docformat__ = 'plaintext'",
"from zope.component.interfaces import IObjectEvent",
"from zope.interface import Interface",
"class IHRMCheckEvent(IObjectEvent):\n \"\"\" An event that is fired at a regular interval\n This can be t... |
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile
from Products.CMFCore.utils import getToolByName
from zope.event import notify
from zope.interface import implements
import logging
from Products.plonehrm import utils as hrmutils
from Products.plonehrm.controlpanel import IHRMNotificationsPanelSchema
from plonehrm.notifications.emailer import HRMEmailer
from plonehrm.notifications.interfaces import INotified
from plonehrm.notifications.utils import get_employees_for_checking
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm.notifications.events import BirthdayNearsEvent
from Products.plonehrm.notifications.interfaces import IPersonalDataEmailer
from Products.plonehrm.utils import next_anniversary
logger = logging.getLogger("plonehrm:")
class PersonalDataEmailer(HRMEmailer):
implements(IPersonalDataEmailer)
def birthday_checker(object, event):
"""Check if the the birthday of Employees is nearing
object is likely the portal, but try not to depend on that.
"""
now = DateTime().earliestTime()
portal = getToolByName(object, 'portal_url').getPortalObject()
panel = IHRMNotificationsPanelSchema(object)
if not panel.birthday_notification:
logger.info("Birthday notification is switched off.")
return
days_warning = panel.birthday_notification_period
limit = now + days_warning
employees = get_employees_for_checking(portal)
for brain in employees:
try:
employee = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
birthday = employee.getBirthDate()
if birthday is None:
logger.debug("Birth date unknown for %s" % employee.officialName())
logger.debug("Please fix at %s" % employee.absolute_url())
continue
anniversary = next_anniversary(employee)
if now <= anniversary <= limit:
# Check if we have already warned about this.
notification_text = u"plonehrm: Birthday %s" % \
anniversary.year()
notified = INotified(employee)
if notified.has_notification(notification_text):
continue
template = ZopeTwoPageTemplateFile('birthday_nears.pt')
options = dict(employee_name = employee.officialName(),
anniversary = anniversary)
addresses = hrmutils.email_adresses_of_local_managers(employee)
recipients = (addresses['worklocation_managers'] +
addresses['hrm_managers'])
email = HRMEmailer(employee,
template=template,
options=options,
recipients=recipients,
subject=_(u'Birthday of ${name}',
mapping=dict(name=employee.Title())))
email.send()
notify(BirthdayNearsEvent(employee))
notified.add_notification(notification_text)
| [
[
1,
0,
0.0132,
0.0132,
0,
0.66,
0,
556,
0,
1,
0,
0,
556,
0,
0
],
[
1,
0,
0.0263,
0.0132,
0,
0.66,
0.0588,
624,
0,
1,
0,
0,
624,
0,
0
],
[
1,
0,
0.0395,
0.0132,
0,
... | [
"from DateTime import DateTime",
"from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile",
"from Products.CMFCore.utils import getToolByName",
"from zope.event import notify",
"from zope.interface import implements",
"import logging",
"from Products.plonehrm import utils as hrmutils"... |
from plonehrm.notifications.interfaces import IHRMModuleEvent
from plonehrm.notifications.interfaces import IHRMEmailer
class IPersonalDataEvent(IHRMModuleEvent):
pass
class IPersonalDataEmailer(IHRMEmailer):
pass
| [
[
1,
0,
0.1,
0.1,
0,
0.66,
0,
835,
0,
1,
0,
0,
835,
0,
0
],
[
1,
0,
0.2,
0.1,
0,
0.66,
0.3333,
835,
0,
1,
0,
0,
835,
0,
0
],
[
3,
0,
0.55,
0.2,
0,
0.66,
0.6667,... | [
"from plonehrm.notifications.interfaces import IHRMModuleEvent",
"from plonehrm.notifications.interfaces import IHRMEmailer",
"class IPersonalDataEvent(IHRMModuleEvent):\n pass",
"class IPersonalDataEmailer(IHRMEmailer):\n pass"
] |
# | [] | [] |
from zope.i18n import translate
from zope.interface import implements
from zope.component.interfaces import ObjectEvent
from Products.CMFCore.utils import getToolByName
from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm.notifications.interfaces import IPersonalDataEvent
from Products.plonehrm.utils import next_anniversary
class BirthdayNearsEvent(ObjectEvent):
"""Employee is almost having his birthday.
"""
implements(IPersonalDataEvent)
# Does a (HRM) Manager need to handle it?
for_manager = False
def __init__(self, *args, **kwargs):
super(BirthdayNearsEvent, self).__init__(*args, **kwargs)
birthdate = self.object.getBirthDate()
anniversary = next_anniversary(self.object)
age = anniversary.year() - birthdate.year()
anniversary = self.object.restrictedTraverse('@@plone').toLocalizedTime(anniversary)
text = _(u"Turns ${age} at ${anniversary}.",
mapping=dict(age=age,
anniversary=anniversary))
props = getToolByName(self.object, 'portal_properties')
lang = props.site_properties.getProperty('default_language')
self.message = translate(text, target_language=lang)
| [
[
1,
0,
0.0323,
0.0323,
0,
0.66,
0,
500,
0,
1,
0,
0,
500,
0,
0
],
[
1,
0,
0.0645,
0.0323,
0,
0.66,
0.1429,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0968,
0.0323,
0,
... | [
"from zope.i18n import translate",
"from zope.interface import implements",
"from zope.component.interfaces import ObjectEvent",
"from Products.CMFCore.utils import getToolByName",
"from Products.plonehrm import PloneHrmMessageFactory as _",
"from Products.plonehrm.notifications.interfaces import IPersona... |
from Products.plonehrm.tests.base import MainTestCase
def test_suite():
from unittest import TestSuite
from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite
s = ZopeDocFileSuite('permissions.txt',
package='Products.plonehrm.doc',
test_class=MainTestCase)
return TestSuite((s, ))
| [
[
1,
0,
0.0909,
0.0909,
0,
0.66,
0,
313,
0,
1,
0,
0,
313,
0,
0
],
[
2,
0,
0.6818,
0.7273,
0,
0.66,
1,
852,
0,
0,
1,
0,
0,
0,
2
],
[
1,
1,
0.4545,
0.0909,
1,
0.98,
... | [
"from Products.plonehrm.tests.base import MainTestCase",
"def test_suite():\n from unittest import TestSuite\n from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite\n\n s = ZopeDocFileSuite('permissions.txt',\n package='Products.plonehrm.doc',\n tes... |
import transaction
from AccessControl import SecurityManagement
from Products.Five import fiveconfigure
from Products.Five import zcml
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase import layer
from Testing import ZopeTestCase as ztc
# Ourselves
import Products.plonehrm
# Regular components
import plonehrm.checklist
import plonehrm.jobperformance
import plonehrm.notes
import plonehrm.contracts
try:
import plonehrm.absence
except ImportError:
plonehrm.absence = None
ptc.setupPloneSite()
def login_as_portal_owner(app):
uf = app.acl_users
owner = uf.getUserById(ptc.portal_owner)
if not hasattr(owner, 'aq_base'):
owner = owner.__of__(uf)
SecurityManagement.newSecurityManager(None, owner)
return owner
def get_portal():
app = ztc.app()
login_as_portal_owner(app)
return getattr(app, ptc.portal_name)
class PlonehrmLayer(layer.PloneSite):
@classmethod
def setUp(cls):
fiveconfigure.debug_mode = True
zcml.load_config('configure.zcml',
Products.plonehrm)
zcml.load_config('configure.zcml',
plonehrm.checklist)
zcml.load_config('configure.zcml',
plonehrm.jobperformance)
zcml.load_config('configure.zcml',
plonehrm.notes)
zcml.load_config('configure.zcml',
plonehrm.contracts)
if plonehrm.absence:
zcml.load_config('configure.zcml',
plonehrm.absence)
ztc.installProduct('plonehrm')
ztc.installPackage('plonehrm.checklist')
ztc.installPackage('plonehrm.jobperformance')
#ztc.installPackage('plonehrm.notes')
ztc.installPackage('plonehrm.contracts')
if plonehrm.absence:
ztc.installPackage('plonehrm.absence')
portal = get_portal()
portal.portal_quickinstaller.installProduct('plonehrm')
transaction.commit()
fiveconfigure.debug_mode = False
class MainTestCase(ptc.PloneTestCase):
"""Base TestCase for plonehrm."""
layer = PlonehrmLayer
| [
[
1,
0,
0.0132,
0.0132,
0,
0.66,
0,
502,
0,
1,
0,
0,
502,
0,
0
],
[
1,
0,
0.0263,
0.0132,
0,
0.66,
0.0588,
227,
0,
1,
0,
0,
227,
0,
0
],
[
1,
0,
0.0395,
0.0132,
0,
... | [
"import transaction",
"from AccessControl import SecurityManagement",
"from Products.Five import fiveconfigure",
"from Products.Five import zcml",
"from Products.PloneTestCase import PloneTestCase as ptc",
"from Products.PloneTestCase import layer",
"from Testing import ZopeTestCase as ztc",
"import P... |
from Products.plonehrm.tests.base import MainTestCase
import doctest
OPTIONFLAGS = (doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE)
def test_suite():
from unittest import TestSuite
from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite
s = ZopeDocFileSuite('worklocation.txt',
package='Products.plonehrm.doc',
optionflags=OPTIONFLAGS,
test_class=MainTestCase)
return TestSuite((s, ))
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
313,
0,
1,
0,
0,
313,
0,
0
],
[
1,
0,
0.125,
0.0625,
0,
0.66,
0.3333,
614,
0,
1,
0,
0,
614,
0,
0
],
[
14,
0,
0.2812,
0.125,
0,
0... | [
"from Products.plonehrm.tests.base import MainTestCase",
"import doctest",
"OPTIONFLAGS = (doctest.ELLIPSIS |\n doctest.NORMALIZE_WHITESPACE)",
"def test_suite():\n from unittest import TestSuite\n from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite\n\n s = ZopeDocFileSuite('w... |
__author__ = """Maurits van Rees <reinout@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from Products.plonehrm.tests.base import MainTestCase
import doctest
OPTIONFLAGS = (doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE)
class testOverview(MainTestCase):
"""Test-cases for class(es) ."""
pass
def test_suite():
from unittest import TestSuite
from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite
s = ZopeDocFileSuite('notifications.txt',
optionflags=OPTIONFLAGS,
package='Products.plonehrm.doc',
test_class=testOverview)
return TestSuite((s, ))
| [
[
14,
0,
0.0417,
0.0417,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0833,
0.0417,
0,
0.66,
0.1667,
959,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1667,
0.0417,
0,
0.... | [
"__author__ = \"\"\"Maurits van Rees <reinout@zestsoftware.nl>\"\"\"",
"__docformat__ = 'plaintext'",
"from Products.plonehrm.tests.base import MainTestCase",
"import doctest",
"OPTIONFLAGS = (doctest.ELLIPSIS |\n doctest.NORMALIZE_WHITESPACE)",
"class testOverview(MainTestCase):\n \"\"\"... |
from Products.plonehrm.tests.base import MainTestCase
import doctest
OPTIONFLAGS = (doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE)
def test_suite():
from unittest import TestSuite
from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite
s = ZopeDocFileSuite('overview.txt',
package='Products.plonehrm.doc',
optionflags=OPTIONFLAGS,
test_class=MainTestCase)
return TestSuite((s, ))
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
313,
0,
1,
0,
0,
313,
0,
0
],
[
1,
0,
0.125,
0.0625,
0,
0.66,
0.3333,
614,
0,
1,
0,
0,
614,
0,
0
],
[
14,
0,
0.2812,
0.125,
0,
0... | [
"from Products.plonehrm.tests.base import MainTestCase",
"import doctest",
"OPTIONFLAGS = (doctest.ELLIPSIS |\n doctest.NORMALIZE_WHITESPACE)",
"def test_suite():\n from unittest import TestSuite\n from Testing.ZopeTestCase.zopedoctest import ZopeDocFileSuite\n\n s = ZopeDocFileSuite('o... |
#
| [] | [] |
__author__ = """Reinout van Rees <reinout@zestsoftware.nl>"""
__docformat__ = 'plaintext'
import logging
logger = logging.getLogger('plonehrm')
logger.debug('Installing Product')
from zope.i18nmessageid import MessageFactory
PloneHrmMessageFactory = MessageFactory(u'plonehrm')
from Products.Archetypes import listTypes
from Products.Archetypes.atapi import process_types
from Products.CMFCore.utils import ContentInit
from Products.CMFCore.DirectoryView import registerDirectory
from Products.plonehrm import config
from Products.validation import validation
from validator import DateValidator, AgeValidator, BSNValidator
validation.register(DateValidator('isDateBeforeToday'))
validation.register(AgeValidator('checkIfTooYoung'))
validation.register(BSNValidator('isBSNValid'))
registerDirectory('skins', config.product_globals)
def initialize(context):
# imports packages and types for registration
import content
permissions = dict(WorkLocation='plonehrm: Add worklocation',
Employee='plonehrm: Add employee',
Template='plonehrm: Add template')
# Initialize portal content
content_types, constructors, ftis = process_types(
listTypes(config.PROJECTNAME),
config.PROJECTNAME)
allTypes = zip(content_types, constructors)
for atype, constructor in allTypes:
kind = "%s: %s" % (config.PROJECTNAME, atype.archetype_name)
ContentInit(
kind,
content_types = (atype, ),
permission = permissions[atype.portal_type],
extra_constructors = (constructor, ),
).initialize(context)
| [
[
14,
0,
0.0222,
0.0222,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0444,
0.0222,
0,
0.66,
0.0556,
959,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0889,
0.0222,
0,
0.... | [
"__author__ = \"\"\"Reinout van Rees <reinout@zestsoftware.nl>\"\"\"",
"__docformat__ = 'plaintext'",
"import logging",
"logger = logging.getLogger('plonehrm')",
"logger.debug('Installing Product')",
"from zope.i18nmessageid import MessageFactory",
"PloneHrmMessageFactory = MessageFactory(u'plonehrm')",... |
# | [] | [] |
PROJECTNAME = "plonehrm"
product_globals = globals()
QI_DEPS = (
'CMFPlacefulWorkflow',
'plonehrm.jobperformance',
'plonehrm.checklist',
'plonehrm.contracts',
'plonehrm.notes',
'plonehrm.absence',
)
# Make a dict of dicts to list the properties.
PLONEHRM_PROPERTIES = {}
PLONEHRM_PROPERTIES['birthday_notification_period'] = \
dict(default=7, type='int')
PLONEHRM_PROPERTIES['contract_expiry_notification_period'] = \
dict(default=6*7, type='int')
PLONEHRM_PROPERTIES['trial_ending_notification_period'] = \
dict(default=2*7, type='int')
PLONEHRM_PROPERTIES['birthday_notification'] = \
dict(default=True, type='boolean')
PLONEHRM_PROPERTIES['contract_expiry_notification'] = \
dict(default=True, type='boolean')
PLONEHRM_PROPERTIES['trial_ending_notification'] = \
dict(default=True, type='boolean')
PLONEHRM_PROPERTIES['EmployeeDetailsViewlets'] = \
dict(default=('plonehrm.personaldata',
'plonehrm.contract',
'plonehrm.notes',
'plonehrm.jobperformance',
'plonehrm.checklist',
'plonehrm.absence',
'plonehrm.files',
), type='lines')
PLONEHRM_PROPERTIES['EmployeesOverviewViewlets'] = \
dict(default=('plonehrm.fullname',
'plonehrm.phone',
'plonehrm.mobile',
# 'plonehrm.checklist',
'plonehrm.address',
'plonehrm.zipcode',
'plonehrm.city',
), type='lines')
PLONEHRM_PROPERTIES['EmployeesAbsenceViewlets'] = \
dict(default=('plonehrm.fullname',
# 'plonehrm.sicknespermonth',
# 'plonehrm.totalsickdays',
# 'plonehrm.annualpercentagesick',
), type='lines')
PLONEHRM_PROPERTIES['EmployeesImprovementsOverviewViewlets'] = \
dict(default=('plonehrm.fullname',
'plonehrm.improvements',
), type='lines')
# We do the same for the personaldata_properties sheet.
PERSONALDATA_PROPERTIES = {}
PERSONALDATA_PROPERTIES['show_state'] = \
dict(default=False, type='boolean')
PERSONALDATA_PROPERTIES['show_country'] = \
dict(default=False, type='boolean')
PERSONALDATA_PROPERTIES['civil_status_vocabulary'] = \
dict(default=("Married",
"Not married",
), type='lines')
PERSONALDATA_PROPERTIES['id_type_vocabulary'] = \
dict(default=("passport",
), type='lines')
| [
[
14,
0,
0.0132,
0.0132,
0,
0.66,
0,
239,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0263,
0.0132,
0,
0.66,
0.0556,
298,
3,
0,
0,
0,
926,
10,
1
],
[
14,
0,
0.0987,
0.1053,
0,
... | [
"PROJECTNAME = \"plonehrm\"",
"product_globals = globals()",
"QI_DEPS = (\n 'CMFPlacefulWorkflow',\n 'plonehrm.jobperformance',\n 'plonehrm.checklist',\n 'plonehrm.contracts',\n 'plonehrm.notes',\n 'plonehrm.absence',\n )",
"PLONEHRM_PROPERTIES = {}",
"PLONEHRM_PROPERTIES['birthday_noti... |
from Products.plonehrm.utils import set_plonehrm_workflow_policy
def worklocationCreated(object, event):
"""A Worklocation has been created. Give it a placeful workflow."""
set_plonehrm_workflow_policy(object)
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
75,
0,
1,
0,
0,
75,
0,
0
],
[
2,
0,
0.8333,
0.5,
0,
0.66,
1,
977,
0,
2,
0,
0,
0,
0,
1
],
[
8,
1,
0.8333,
0.1667,
1,
0.95,
0,... | [
"from Products.plonehrm.utils import set_plonehrm_workflow_policy",
"def worklocationCreated(object, event):\n \"\"\"A Worklocation has been created. Give it a placeful workflow.\"\"\"\n set_plonehrm_workflow_policy(object)",
" \"\"\"A Worklocation has been created. Give it a placeful workflow.\"\"\"... |
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| [
[
7,
0,
0.6667,
0.8333,
0,
0.66,
0,
0,
0,
1,
0,
0,
0,
0,
3
],
[
8,
1,
0.5,
0.1667,
1,
0.71,
0,
736,
3,
1,
0,
0,
0,
0,
2
],
[
1,
1,
0.8333,
0.1667,
1,
0.71,
0,
... | [
"try:\n __import__('pkg_resources').declare_namespace(__name__)\nexcept ImportError:\n from pkgutil import extend_path\n __path__ = extend_path(__path__, __name__)",
" __import__('pkg_resources').declare_namespace(__name__)",
" from pkgutil import extend_path",
" __path__ = extend_path(__pat... |
#
| [] | [] |
from zope import schema
from zope.interface import Interface
from Products.plonecrm import plonecrmMessageFactory as _
class Iorganization(Interface):
"""an organization unite"""
# -*- schema definition goes here -*-
newfield = schema.TextLine(
title=_(u"register capital"),
required=False,
description=_(u"register capital"),
)
#
fax = schema.TextLine(
title=_(u"fax number"),
required=False,
description=_(u"fax number"),
)
#
website = schema.TextLine(
title=_(u"website"),
required=False,
description=_(u"the website of organization"),
)
#
postcode = schema.TextLine(
title=_(u"New Field"),
required=False,
description=_(u"post code"),
)
#
business = schema.TextLine(
title=_(u"main business"),
required=False,
description=_(u"this organization provided main business"),
)
#
type = schema.TextLine(
title=_(u"organization type"),
required=False,
description=_(u"this organization's type"),
)
#
account = schema.TextLine(
title=_(u"bank account"),
required=False,
description=_(u"bank account"),
)
#
master = schema.TextLine(
title=_(u"organization legal person"),
required=False,
description=_(u"organization legal person or board chairman"),
)
#
name = schema.TextLine(
title=_(u"organization name"),
required=True,
description=_(u"this organization legal regeistered name"),
)
#
| [
[
1,
0,
0.0156,
0.0156,
0,
0.66,
0,
603,
0,
1,
0,
0,
603,
0,
0
],
[
1,
0,
0.0312,
0.0156,
0,
0.66,
0.3333,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0625,
0.0156,
0,
... | [
"from zope import schema",
"from zope.interface import Interface",
"from Products.plonecrm import plonecrmMessageFactory as _",
"class Iorganization(Interface):\n \"\"\"an organization unite\"\"\"\n\n # -*- schema definition goes here -*-\n newfield = schema.TextLine(\n title=_(u\"register cap... |
# -*- extra stuff goes here -*-
from contact import Icontact
from organization import Iorganization
| [
[
1,
0,
0.6667,
0.3333,
0,
0.66,
0,
357,
0,
1,
0,
0,
357,
0,
0
],
[
1,
0,
1,
0.3333,
0,
0.66,
1,
239,
0,
1,
0,
0,
239,
0,
0
]
] | [
"from contact import Icontact",
"from organization import Iorganization"
] |
from zope import schema
from zope.interface import Interface
from Products.plonecrm import plonecrmMessageFactory as _
class Icontact(Interface):
"""contact person"""
# -*- schema definition goes here -*-
portrait = schema.Bytes(
title=_(u"personal photo"),
required=False,
description=_(u"personal photo"),
)
#
comments = schema.TextLine(
title=_(u"comments"),
required=False,
description=_(u"Field description"),
)
#
duty = schema.TextLine(
title=_(u"work duty"),
required=False,
description=_(u"work duty"),
)
#
resume = schema.TextLine(
title=_(u"person resume"),
required=False,
description=_(u"person resume"),
)
#
background = schema.TextLine(
title=_(u"home background"),
required=False,
description=_(u"home background"),
)
#
habit = schema.TextLine(
title=_(u"habits"),
required=False,
description=_(u"habits"),
)
#
email = schema.TextLine(
title=_(u"email"),
required=False,
description=_(u"email address"),
)
#
position = schema.TextLine(
title=_(u"position"),
required=False,
description=_(u"work position"),
)
#
addr = schema.TextLine(
title=_(u"address"),
required=False,
description=_(u"address"),
)
#
mobile = schema.TextLine(
title=_(u"mobile phone"),
required=False,
description=_(u"mobile phone number"),
)
#
homephone = schema.TextLine(
title=_(u"home phone"),
required=False,
description=_(u"home phone number"),
)
#
officephone = schema.TextLine(
title=_(u"New Field"),
required=False,
description=_(u"office phone number"),
)
#
department = schema.TextLine(
title=_(u"New Field"),
required=False,
description=_(u"Field description"),
)
#
gender = schema.TextLine(
title=_(u"gender"),
required=False,
description=_(u"gender"),
)
#
name = schema.TextLine(
title=_(u"contact name"),
required=False,
description=_(u"contact name"),
)
#
| [
[
1,
0,
0.01,
0.01,
0,
0.66,
0,
603,
0,
1,
0,
0,
603,
0,
0
],
[
1,
0,
0.02,
0.01,
0,
0.66,
0.3333,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.04,
0.01,
0,
0.66,
0.... | [
"from zope import schema",
"from zope.interface import Interface",
"from Products.plonecrm import plonecrmMessageFactory as _",
"class Icontact(Interface):\n \"\"\"contact person\"\"\"\n\n # -*- schema definition goes here -*-\n portrait = schema.Bytes(\n title=_(u\"personal photo\"),\n ... |
from zope.interface import implements, Interface
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from Products.plonecrm import plonecrmMessageFactory as _
class IorganizationView(Interface):
"""
organization view interface
"""
def test():
""" test method"""
class organizationView(BrowserView):
"""
organization browser view
"""
implements(IorganizationView)
def __init__(self, context, request):
self.context = context
self.request = request
@property
def portal_catalog(self):
return getToolByName(self.context, 'portal_catalog')
@property
def portal(self):
return getToolByName(self.context, 'portal_url').getPortalObject()
def test(self):
"""
test method
"""
dummy = _(u'a dummy string')
return {'dummy': dummy}
| [
[
1,
0,
0.0238,
0.0238,
0,
0.66,
0,
443,
0,
2,
0,
0,
443,
0,
0
],
[
1,
0,
0.0714,
0.0238,
0,
0.66,
0.2,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.0952,
0.0238,
0,
0.6... | [
"from zope.interface import implements, Interface",
"from Products.Five import BrowserView",
"from Products.CMFCore.utils import getToolByName",
"from Products.plonecrm import plonecrmMessageFactory as _",
"class IorganizationView(Interface):\n \"\"\"\n organization view interface\n \"\"\"\n\n d... |
#
| [] | [] |
from zope.interface import implements, Interface
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from Products.plonecrm import plonecrmMessageFactory as _
class IcontactView(Interface):
"""
contact view interface
"""
def test():
""" test method"""
class contactView(BrowserView):
"""
contact browser view
"""
implements(IcontactView)
def __init__(self, context, request):
self.context = context
self.request = request
@property
def portal_catalog(self):
return getToolByName(self.context, 'portal_catalog')
@property
def portal(self):
return getToolByName(self.context, 'portal_url').getPortalObject()
def test(self):
"""
test method
"""
dummy = _(u'a dummy string')
return {'dummy': dummy}
| [
[
1,
0,
0.0238,
0.0238,
0,
0.66,
0,
443,
0,
2,
0,
0,
443,
0,
0
],
[
1,
0,
0.0714,
0.0238,
0,
0.66,
0.2,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.0952,
0.0238,
0,
0.6... | [
"from zope.interface import implements, Interface",
"from Products.Five import BrowserView",
"from Products.CMFCore.utils import getToolByName",
"from Products.plonecrm import plonecrmMessageFactory as _",
"class IcontactView(Interface):\n \"\"\"\n contact view interface\n \"\"\"\n\n def test():... |
"""Definition of the organization content type
"""
from zope.interface import implements
from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content import schemata
from Products.plonecrm import plonecrmMessageFactory as _
from Products.plonecrm.interfaces import Iorganization
from Products.plonecrm.config import PROJECTNAME
organizationSchema = folder.ATFolderSchema.copy() + atapi.Schema((
# -*- Your Archetypes field definitions here ... -*-
atapi.StringField(
'newfield',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"register capital"),
description=_(u"register capital"),
),
),
atapi.StringField(
'fax',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"fax number"),
description=_(u"fax number"),
),
),
atapi.StringField(
'website',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"website"),
description=_(u"the website of organization"),
),
),
atapi.StringField(
'postcode',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"New Field"),
description=_(u"post code"),
),
),
atapi.StringField(
'business',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"main business"),
description=_(u"this organization provided main business"),
),
),
atapi.StringField(
'type',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"organization type"),
description=_(u"this organization's type"),
),
),
atapi.StringField(
'account',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"bank account"),
description=_(u"bank account"),
),
),
atapi.StringField(
'master',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"organization legal person"),
description=_(u"organization legal person or board chairman"),
),
),
atapi.StringField(
'name',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"organization name"),
description=_(u"this organization legal regeistered name"),
),
required=True,
),
))
# Set storage on fields copied from ATFolderSchema, making sure
# they work well with the python bridge properties.
organizationSchema['title'].storage = atapi.AnnotationStorage()
organizationSchema['description'].storage = atapi.AnnotationStorage()
schemata.finalizeATCTSchema(
organizationSchema,
folderish=True,
moveDiscussion=False
)
class organization(folder.ATFolder):
"""an organization unite"""
implements(Iorganization)
meta_type = "organization"
schema = organizationSchema
title = atapi.ATFieldProperty('title')
description = atapi.ATFieldProperty('description')
# -*- Your ATSchema to Python Property Bridges Here ... -*-
newfield = atapi.ATFieldProperty('newfield')
fax = atapi.ATFieldProperty('fax')
website = atapi.ATFieldProperty('website')
postcode = atapi.ATFieldProperty('postcode')
business = atapi.ATFieldProperty('business')
type = atapi.ATFieldProperty('type')
account = atapi.ATFieldProperty('account')
master = atapi.ATFieldProperty('master')
name = atapi.ATFieldProperty('name')
atapi.registerType(organization, PROJECTNAME)
| [
[
8,
0,
0.0097,
0.013,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.026,
0.0065,
0,
0.66,
0.0769,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.039,
0.0065,
0,
0.66,
... | [
"\"\"\"Definition of the organization content type\n\"\"\"",
"from zope.interface import implements",
"from Products.Archetypes import atapi",
"from Products.ATContentTypes.content import folder",
"from Products.ATContentTypes.content import schemata",
"from Products.plonecrm import plonecrmMessageFactory... |
#
| [] | [] |
"""Definition of the contact content type
"""
from zope.interface import implements
from Products.Archetypes import atapi
from Products.ATContentTypes.content import base
from Products.ATContentTypes.content import schemata
from Products.plonecrm import plonecrmMessageFactory as _
from Products.plonecrm.interfaces import Icontact
from Products.plonecrm.config import PROJECTNAME
contactSchema = schemata.ATContentTypeSchema.copy() + atapi.Schema((
# -*- Your Archetypes field definitions here ... -*-
atapi.ImageField(
'portrait',
storage=atapi.AnnotationStorage(),
widget=atapi.ImageWidget(
label=_(u"personal photo"),
description=_(u"personal photo"),
),
validators=('isNonEmptyFile'),
),
atapi.StringField(
'comments',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"comments"),
description=_(u"Field description"),
),
),
atapi.StringField(
'duty',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"work duty"),
description=_(u"work duty"),
),
),
atapi.StringField(
'resume',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"person resume"),
description=_(u"person resume"),
),
),
atapi.StringField(
'background',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"home background"),
description=_(u"home background"),
),
),
atapi.StringField(
'habit',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"habits"),
description=_(u"habits"),
),
),
atapi.StringField(
'email',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"email"),
description=_(u"email address"),
),
validators=('isEmail'),
),
atapi.StringField(
'position',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"position"),
description=_(u"work position"),
),
),
atapi.StringField(
'addr',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"address"),
description=_(u"address"),
),
),
atapi.StringField(
'mobile',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"mobile phone"),
description=_(u"mobile phone number"),
),
),
atapi.StringField(
'homephone',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"home phone"),
description=_(u"home phone number"),
),
),
atapi.StringField(
'officephone',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"New Field"),
description=_(u"office phone number"),
),
),
atapi.StringField(
'department',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"New Field"),
description=_(u"Field description"),
),
),
atapi.StringField(
'gender',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"gender"),
description=_(u"gender"),
),
),
atapi.StringField(
'name',
storage=atapi.AnnotationStorage(),
widget=atapi.StringWidget(
label=_(u"contact name"),
description=_(u"contact name"),
),
),
))
# Set storage on fields copied from ATContentTypeSchema, making sure
# they work well with the python bridge properties.
contactSchema['title'].storage = atapi.AnnotationStorage()
contactSchema['description'].storage = atapi.AnnotationStorage()
schemata.finalizeATCTSchema(contactSchema, moveDiscussion=False)
class contact(base.ATCTContent):
"""contact person"""
implements(Icontact)
meta_type = "contact"
schema = contactSchema
title = atapi.ATFieldProperty('title')
description = atapi.ATFieldProperty('description')
# -*- Your ATSchema to Python Property Bridges Here ... -*-
portrait = atapi.ATFieldProperty('portrait')
comments = atapi.ATFieldProperty('comments')
duty = atapi.ATFieldProperty('duty')
resume = atapi.ATFieldProperty('resume')
background = atapi.ATFieldProperty('background')
habit = atapi.ATFieldProperty('habit')
email = atapi.ATFieldProperty('email')
position = atapi.ATFieldProperty('position')
addr = atapi.ATFieldProperty('addr')
mobile = atapi.ATFieldProperty('mobile')
homephone = atapi.ATFieldProperty('homephone')
officephone = atapi.ATFieldProperty('officephone')
department = atapi.ATFieldProperty('department')
gender = atapi.ATFieldProperty('gender')
name = atapi.ATFieldProperty('name')
atapi.registerType(contact, PROJECTNAME)
| [
[
8,
0,
0.0067,
0.009,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0179,
0.0045,
0,
0.66,
0.0769,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0269,
0.0045,
0,
0.66,... | [
"\"\"\"Definition of the contact content type\n\"\"\"",
"from zope.interface import implements",
"from Products.Archetypes import atapi",
"from Products.ATContentTypes.content import base",
"from Products.ATContentTypes.content import schemata",
"from Products.plonecrm import plonecrmMessageFactory as _",... |
"""Test setup for integration and functional tests.
When we import PloneTestCase and then call setupPloneSite(), all of
Plone's products are loaded, and a Plone site will be created. This
happens at module level, which makes it faster to run each test, but
slows down test runner startup.
"""
from Products.Five import zcml
from Products.Five import fiveconfigure
from Testing import ZopeTestCase as ztc
from Products.PloneTestCase import PloneTestCase as ptc
from Products.PloneTestCase.layer import onsetup
# When ZopeTestCase configures Zope, it will *not* auto-load products
# in Products/. Instead, we have to use a statement such as:
# ztc.installProduct('SimpleAttachment')
# This does *not* apply to products in eggs and Python packages (i.e.
# not in the Products.*) namespace. For that, see below.
# All of Plone's products are already set up by PloneTestCase.
@onsetup
def setup_product():
"""Set up the package and its dependencies.
The @onsetup decorator causes the execution of this body to be
deferred until the setup of the Plone site testing layer. We could
have created our own layer, but this is the easiest way for Plone
integration tests.
"""
# Load the ZCML configuration for the example.tests package.
# This can of course use <include /> to include other packages.
fiveconfigure.debug_mode = True
import Products.plonecrm
zcml.load_config('configure.zcml', Products.plonecrm)
fiveconfigure.debug_mode = False
# We need to tell the testing framework that these products
# should be available. This can't happen until after we have loaded
# the ZCML. Thus, we do it here. Note the use of installPackage()
# instead of installProduct().
# This is *only* necessary for packages outside the Products.*
# namespace which are also declared as Zope 2 products, using
# <five:registerPackage /> in ZCML.
# We may also need to load dependencies, e.g.:
# ztc.installPackage('borg.localrole')
ztc.installPackage('Products.plonecrm')
# The order here is important: We first call the (deferred) function
# which installs the products we need for this product. Then, we let
# PloneTestCase set up this product on installation.
setup_product()
ptc.setupPloneSite(products=['Products.plonecrm'])
class TestCase(ptc.PloneTestCase):
"""We use this base class for all the tests in this package. If
necessary, we can put common utility or setup code in here. This
applies to unit test cases.
"""
class FunctionalTestCase(ptc.FunctionalTestCase):
"""We use this class for functional integration tests that use
doctest syntax. Again, we can put basic common utility or setup
code in here.
"""
def afterSetUp(self):
roles = ('Member', 'Contributor')
self.portal.portal_membership.addMember('contributor',
'secret',
roles, [])
| [
[
8,
0,
0.0494,
0.0864,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1111,
0.0123,
0,
0.66,
0.1,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.1235,
0.0123,
0,
0.66,
... | [
"\"\"\"Test setup for integration and functional tests.\n\nWhen we import PloneTestCase and then call setupPloneSite(), all of\nPlone's products are loaded, and a Plone site will be created. This\nhappens at module level, which makes it faster to run each test, but\nslows down test runner startup.\n\"\"\"",
"from... |
#
| [] | [] |
"""Main product initializer
"""
from zope.i18nmessageid import MessageFactory
from Products.plonecrm import config
from Products.Archetypes import atapi
from Products.CMFCore import utils
# Define a message factory for when this product is internationalised.
# This will be imported with the special name "_" in most modules. Strings
# like _(u"message") will then be extracted by i18n tools for translation.
plonecrmMessageFactory = MessageFactory('Products.plonecrm')
def initialize(context):
"""Initializer called when used as a Zope 2 product.
This is referenced from configure.zcml. Regstrations as a "Zope 2 product"
is necessary for GenericSetup profiles to work, for example.
Here, we call the Archetypes machinery to register our content types
with Zope and the CMF.
"""
# Retrieve the content types that have been registered with Archetypes
# This happens when the content type is imported and the registerType()
# call in the content type's module is invoked. Actually, this happens
# during ZCML processing, but we do it here again to be explicit. Of
# course, even if we import the module several times, it is only run
# once.
content_types, constructors, ftis = atapi.process_types(
atapi.listTypes(config.PROJECTNAME),
config.PROJECTNAME)
# Now initialize all these content types. The initialization process takes
# care of registering low-level Zope 2 factories, including the relevant
# add-permission. These are listed in config.py. We use different
# permissions for each content type to allow maximum flexibility of who
# can add which content types, where. The roles are set up in rolemap.xml
# in the GenericSetup profile.
for atype, constructor in zip(content_types, constructors):
utils.ContentInit('%s: %s' % (config.PROJECTNAME, atype.portal_type),
content_types=(atype, ),
permission=config.ADD_PERMISSIONS[atype.portal_type],
extra_constructors=(constructor,),
).initialize(context)
| [
[
8,
0,
0.03,
0.04,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.08,
0.02,
0,
0.66,
0.1667,
311,
0,
1,
0,
0,
311,
0,
0
],
[
1,
0,
0.1,
0.02,
0,
0.66,
0.3333,... | [
"\"\"\"Main product initializer\n\"\"\"",
"from zope.i18nmessageid import MessageFactory",
"from Products.plonecrm import config",
"from Products.Archetypes import atapi",
"from Products.CMFCore import utils",
"plonecrmMessageFactory = MessageFactory('Products.plonecrm')",
"def initialize(context):\n ... |
"""Common configuration constants
"""
PROJECTNAME = 'Products.plonecrm'
ADD_PERMISSIONS = {
# -*- extra stuff goes here -*-
'contact': 'Products.plonecrm: Add contact',
'organization': 'Products.plonecrm: Add organization',
}
| [
[
8,
0,
0.15,
0.2,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4,
0.1,
0,
0.66,
0.5,
239,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.8,
0.5,
0,
0.66,
1,
783,
... | [
"\"\"\"Common configuration constants\n\"\"\"",
"PROJECTNAME = 'Products.plonecrm'",
"ADD_PERMISSIONS = {\n # -*- extra stuff goes here -*-\n 'contact': 'Products.plonecrm: Add contact',\n 'organization': 'Products.plonecrm: Add organization',\n}"
] |
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| [
[
7,
0,
0.6667,
0.8333,
0,
0.66,
0,
0,
0,
1,
0,
0,
0,
0,
3
],
[
8,
1,
0.5,
0.1667,
1,
0.07,
0,
736,
3,
1,
0,
0,
0,
0,
2
],
[
1,
1,
0.8333,
0.1667,
1,
0.07,
0,
... | [
"try:\n __import__('pkg_resources').declare_namespace(__name__)\nexcept ImportError:\n from pkgutil import extend_path\n __path__ = extend_path(__path__, __name__)",
" __import__('pkg_resources').declare_namespace(__name__)",
" from pkgutil import extend_path",
" __path__ = extend_path(__pat... |
# -*- coding: utf-8 -*-
"""
This module contains the tool of Products.plonecrm
"""
import os
from setuptools import setup, find_packages
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
version = '1.0'
long_description = (
read('README.txt')
+ '\n' +
'Change history\n'
'**************\n'
+ '\n' +
read('CHANGES.txt')
+ '\n' +
'Detailed Documentation\n'
'**********************\n'
+ '\n' +
read('Products', 'plonecrm', 'README.txt')
+ '\n' +
'Contributors\n'
'************\n'
+ '\n' +
read('CONTRIBUTORS.txt')
+ '\n' +
'Download\n'
'********\n')
tests_require = ['zope.testing']
setup(name='Products.plonecrm',
version=version,
description="a customer relative management system besed plone",
long_description=long_description,
# Get more strings from
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Framework :: Plone',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
],
keywords='',
author='',
author_email='',
url='http://svn.plone.org/svn/collective/',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['Products', ],
include_package_data=True,
zip_safe=False,
install_requires=['setuptools',
# -*- Extra requirements: -*-
],
tests_require=tests_require,
extras_require=dict(tests=tests_require),
test_suite='Products.plonecrm.tests.test_docs.test_suite',
entry_points="""
# -*- entry_points -*-
[z3c.autoinclude.plugin]
target = plone
""",
setup_requires=["PasteScript"],
paster_plugins=["ZopeSkel"],
)
| [
[
8,
0,
0.0429,
0.0429,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0714,
0.0143,
0,
0.66,
0.1429,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0857,
0.0143,
0,
0.66... | [
"\"\"\"\nThis module contains the tool of Products.plonecrm\n\"\"\"",
"import os",
"from setuptools import setup, find_packages",
"def read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()",
" return open(os.path.join(os.path.dirname(__file__), *rnames)).read()",
"ver... |
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| [
[
7,
0,
0.6667,
0.8333,
0,
0.66,
0,
0,
0,
1,
0,
0,
0,
0,
3
],
[
8,
1,
0.5,
0.1667,
1,
0.1,
0,
736,
3,
1,
0,
0,
0,
0,
2
],
[
1,
1,
0.8333,
0.1667,
1,
0.1,
0,
... | [
"try:\n __import__('pkg_resources').declare_namespace(__name__)\nexcept ImportError:\n from pkgutil import extend_path\n __path__ = extend_path(__path__, __name__)",
" __import__('pkg_resources').declare_namespace(__name__)",
" from pkgutil import extend_path",
" __path__ = extend_path(__pat... |
from BeautifulSoup import BeautifulSoup
def getPostUrlFromForum(res, position=0):
soup = BeautifulSoup(res.body)
posts = soup.findAll('a', attrs={'class':'state-active'})
return posts[position].attrMap['href']
def getReplyUrlFromConversation(res, position=0):
soup = BeautifulSoup(res.body)
return soup.findAll('input', value='Reply to this')[position].parent.attrs[0][1].split('#')[0]
def getForumUrlsFromBoard(res):
soup = BeautifulSoup(res.body)
return [f.attrMap['href'] for f in soup.findAll('a', attrs={'class':'state-memberposting'})]
| [
[
1,
0,
0.0714,
0.0714,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
2,
0,
0.3214,
0.2857,
0,
0.66,
0.3333,
748,
0,
2,
1,
0,
0,
0,
2
],
[
14,
1,
0.2857,
0.0714,
1,
0... | [
"from BeautifulSoup import BeautifulSoup",
"def getPostUrlFromForum(res, position=0):\n soup = BeautifulSoup(res.body)\n posts = soup.findAll('a', attrs={'class':'state-active'})\n return posts[position].attrMap['href']",
" soup = BeautifulSoup(res.body)",
" posts = soup.findAll('a', attrs={'cl... |
## Script (Python) "lock_board.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Locks board
##
if context.portal_type != 'Ploneboard': return
for f1 in context.objectValues('PloneboardForum'):
for c1 in f1.objectValues('PloneboardConversation'):
for m1 in c1.objectValues('PloneboardComment'):
m1.manage_permission('Modify portal content', (), acquire=0)
m1.manage_permission('Delete objects', (), acquire=0)
c1.manage_permission('Modify portal content', (), acquire=0)
f1.manage_permission('Ploneboard: Add Comment', (), acquire=0)
f1.manage_permission('Ploneboard: Add Conversation', (), acquire=0)
f1.manage_permission('Ploneboard: Retract Comment', (), acquire=0)
| [
[
4,
0,
0.55,
0.05,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
13,
1,
0.55,
0.05,
1,
0.67,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.8,
0.45,
0,
0.66,
1,
282,
... | [
"if context.portal_type != 'Ploneboard': return",
"if context.portal_type != 'Ploneboard': return",
"for f1 in context.objectValues('PloneboardForum'):\n for c1 in f1.objectValues('PloneboardConversation'):\n for m1 in c1.objectValues('PloneboardComment'):\n m1.manage_permission('Modify por... |
## Script (Python) "list_pending_search.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=obj=None
##title=Searches for pending comments in moderated boards
# $Id: moderation_count_search.py 53223 2007-11-06 10:26:29Z glenfant $
if obj is None:
obj = context
query = {}
query['review_state'] = 'pending'
query['portal_type'] = 'Ploneboard Comment'
query['path'] = '/'+ '/'.join(obj.getPhysicalPath()[1:])
reqget = context.REQUEST.get
# FIXME: this function seems useless
def supplement_query(field, index_name=None, reqget=reqget, query=query):
if not index_name: index_name = field
val = reqget(field, None)
if val:
query[index_name] = val
return len(context.getInternalCatalog()(REQUEST=query))
| [
[
4,
0,
0.4107,
0.0714,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.4286,
0.0357,
1,
0.19,
0,
505,
2,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5,
0.0357,
0,
0.66,
0.... | [
"if obj is None:\n obj = context",
" obj = context",
"query = {}",
"query['review_state'] = 'pending'",
"query['portal_type'] = 'Ploneboard Comment'",
"query['path'] = '/'+ '/'.join(obj.getPhysicalPath()[1:])",
"reqget = context.REQUEST.get",
"def supplement_query(field, index_name=None, reqget=... |
## Script (Python) "moderation.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Searches for pending comments in moderated boards
##
# Search the catalog, and depending on where the script is called from, filter
# and massage results until it is suitable for displaying. The main concern is
# too large number of search results.
# Massaging the results means getting the objects, which might not be that bad
# as we are going to write to them anyway (moderate) soon.
# Returned results might be forum objects, conversation objects or comment objects
# if returned number of pending comments is less than 100: display everything
# if context is conversation, display everything
# if context is board, only display link to forums with more than 50 pending comments
# if context is forum, only display link to conversations with more than 10 pending comments
query = {}
query['sort_on'] = 'created'
query['review_state'] = 'pending'
query['portal_type'] = 'PloneboardComment'
query['path'] = '/'.join(context.getPhysicalPath())
reqget = context.REQUEST.get
def supplement_query(field, index_name=None, reqget=reqget, query=query):
if not index_name: index_name = field
val = reqget(field, None)
if val:
query[index_name] = val
catalogresult = context.portal_catalog(query)
if context.portal_type == 'PloneboardConversation' or len(catalogresult) < 100:
return [r.getObject() for r in catalogresult]
result = []
if context.portal_type == 'Ploneboard':
for forum in context.contentValues('PloneboardForum'):
query['path'] = '/'+ '/'.join(forum.getPhysicalPath()[1:])
forumresult = context.portal_catalog(query)
if len(forumresult) > 50:
result.append(forum)
else:
result.extend([r.getObject() for r in forumresult])
return result
if context.portal_type == 'PloneboardForum':
# We need a dynamic programming solution here as search for each
# conversation is prohibitively expensive
forumid = context.getId()
conversations = {} # {id, [commentbrains, ]}
for item in catalogresult:
pathlist = item.getPath().split('/')
conversationid = pathlist[pathlist.index(forumid)+1]
if conversations.has_key(conversationid):
conversations[conversationid].append(item)
else:
conversations[conversationid] = [item]
for key in conversations.keys():
if len(conversations[key]) > 10:
# Could use a wrapper to store the conversation + length of pending comment
# queue to avoid catalog calls in the moderation_form template
result.append(context.getConversation(key))
else:
result.extend([i.getObject() for i in conversations[key]])
return result | [
[
14,
0,
0.2958,
0.0141,
0,
0.66,
0,
546,
0,
0,
0,
0,
0,
6,
0
],
[
14,
0,
0.3099,
0.0141,
0,
0.66,
0.0833,
0,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.3239,
0.0141,
0,
0.6... | [
"query = {}",
"query['sort_on'] = 'created'",
"query['review_state'] = 'pending'",
"query['portal_type'] = 'PloneboardComment'",
"query['path'] = '/'.join(context.getPhysicalPath())",
"reqget = context.REQUEST.get",
"def supplement_query(field, index_name=None, reqget=reqget, query=query):\n if not i... |
## Script (Python) "moderateComment"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=action,cameFrom=None
##title=Moderate the given comment, and return to referer
##
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.WorkflowCore import WorkflowException
workflow = getToolByName(context, 'portal_workflow')
workflow.doActionFor(context, action)
if cameFrom is None:
cameFrom = context.REQUEST.get('HTTP_REFERER', context.absolute_url())
context.REQUEST.RESPONSE.redirect(cameFrom) | [
[
1,
0,
0.5789,
0.0526,
0,
0.66,
0,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.6316,
0.0526,
0,
0.66,
0.2,
184,
0,
1,
0,
0,
184,
0,
0
],
[
14,
0,
0.7368,
0.0526,
0,
0.... | [
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFCore.WorkflowCore import WorkflowException",
"workflow = getToolByName(context, 'portal_workflow')",
"workflow.doActionFor(context, action)",
"if cameFrom is None:\n cameFrom = context.REQUEST.get('HTTP_REFERER', context.absolute_url()... |
## Script (Python) "comment_redirect_to_conversation"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Redirect from a comment to it's conversation
##
# XXX if we ever do batching, we need extra logic here.
redirect_target = context.getConversation()
anchor = context.getId()
conv = context.getConversation()
query = {'object_implements' : 'Products.Ploneboard.interfaces.IComment',
'sort_on' : 'created',
'path' : '/'.join(conv.getPhysicalPath()),
}
catalog=conv.getCatalog()
res = [ x.getId for x in catalog(query) ]
if anchor in res:
pos = res.index(anchor)
batchSize = conv.getForum().getConversationBatchSize()
offset = batchSize * int(pos / batchSize)
else:
offset = 0
target_url = '%s?b_start=%d#%s' % (redirect_target.absolute_url(), offset, anchor)
response = context.REQUEST.get('RESPONSE', None)
if response is not None:
response.redirect(target_url)
print "Redirecting to %s" % target_url
return printed
| [
[
14,
0,
0.3636,
0.0303,
0,
0.66,
0,
252,
3,
0,
0,
0,
774,
10,
1
],
[
14,
0,
0.3939,
0.0303,
0,
0.66,
0.1111,
26,
3,
0,
0,
0,
591,
10,
1
],
[
14,
0,
0.4545,
0.0303,
0,
... | [
"redirect_target = context.getConversation()",
"anchor = context.getId()",
"conv = context.getConversation()",
"query = {'object_implements' : 'Products.Ploneboard.interfaces.IComment',\n 'sort_on' : 'created',\n 'path' : '/'.join(conv.getPhysicalPath()),\n }",
... |
## Script (Python) "lock_board.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Unlocks board
##
if context.portal_type != 'Ploneboard': return
for f1 in context.objectValues('PloneboardForum'):
for c1 in f1.objectValues('PloneboardConversation'):
for m1 in c1.objectValues('PloneboardComment'):
m1.manage_permission('Modify portal content', ('Manager', 'Owner'), acquire=0)
m1.manage_permission('Delete objects', ('Manager',), acquire=0)
c1.manage_permission('Modify portal content', ('Manager', 'Owner'), acquire=0)
f1.manage_permission('Ploneboard: Add Comment', ('Manager', 'Member', 'Reviewer'), acquire=0)
f1.manage_permission('Ploneboard: Add Conversation', ('Manager', 'Member', 'Reviewer'), acquire=0)
f1.manage_permission('Ploneboard: Retract Comment', ('Manager', 'Reviewer'), acquire=0)
| [
[
4,
0,
0.55,
0.05,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
13,
1,
0.55,
0.05,
1,
0.52,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
6,
0,
0.8,
0.45,
0,
0.66,
1,
282,
... | [
"if context.portal_type != 'Ploneboard': return",
"if context.portal_type != 'Ploneboard': return",
"for f1 in context.objectValues('PloneboardForum'):\n for c1 in f1.objectValues('PloneboardConversation'):\n for m1 in c1.objectValues('PloneboardComment'):\n m1.manage_permission('Modify por... |
## Script (Python) "getKeyedForums"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=forums=None
##title=Get forums keyed on category
##
if forums is None:
forums = context.getForums()
result = {}
for forum in forums:
if hasattr(forum, 'getCategory'):
categories = forum.getCategory()
if not categories:
categories = None
if not same_type(categories, ()) and not same_type(categories, []):
categories = categories,
for category in categories:
try:
categoryforums = result.get(category, [])
categoryforums.append(forum)
result[category] = categoryforums
except TypeError: # category is list?!
result[', '.join(category)] = forum
return result | [
[
4,
0,
0.3833,
0.0667,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
1
],
[
14,
1,
0.4,
0.0333,
1,
0.87,
0,
763,
3,
0,
0,
0,
929,
10,
1
],
[
14,
0,
0.4667,
0.0333,
0,
0.66,
... | [
"if forums is None:\n forums = context.getForums()",
" forums = context.getForums()",
"result = {}",
"for forum in forums:\n if hasattr(forum, 'getCategory'):\n categories = forum.getCategory()\n if not categories:\n categories = None\n if not same_type(categories, ())... |
from Products.PortalTransforms.interfaces import itransform
from ZODB.PersistentMapping import PersistentMapping
from Products.CMFCore.utils import getToolByName
from Products.Ploneboard.utils import TransformDataProvider
import re
import copy
class EmoticonDataProvider(TransformDataProvider):
def __init__(self):
""" We need to redefine config and config_metadata
in base class.
"""
self.config = PersistentMapping()
self.config_metadata = PersistentMapping()
self.config.update({ 'inputs' : self.defaultEmoticons()})
self.config_metadata.update({
'inputs' : {
'key_label' : 'emoticon code',
'value_label' : 'image name',
'description' : 'Emoticons to images mapping'}
})
def defaultEmoticons():
emoticons = { ':)' : '<img src="smiley_smile.png" alt=":)" title="Smile" />'
, ':(' : '<img src="smiley_sad.png" alt=":(" title="Sad" />'
, '8-)' : '<img src="smiley_cool.png" alt="8)" title="Cool" />'
, ':D' : '<img src="smiley_lol.png" alt=":D" title="Big grin" />'
, ':|' : '<img src="smiley_skeptic.png" alt=":|" title="Skeptic" />'
, ':o' : '<img src="smiley_surprised.png" alt=":o" title="Surprised" />'
, ':P' : '<img src="smiley_tongue.png" alt=":P" title="Tongue-in-cheek" />'
, ';)' : '<img src="smiley_wink.png" alt=";)" title="Wink" />'
, ':-)' : '<img src="smiley_smile.png" alt=":)" title="Smile" />'
, ':-(' : '<img src="smiley_sad.png" alt=":(" title="Sad" />'
, ':-D' : '<img src="smiley_lol.png" alt=":D" title="Big grin" />'
, ':-|' : '<img src="smiley_skeptic.png" alt=":|" title="Skeptic" />'
, ':-o' : '<img src="smiley_surprised.png" alt=":o" title="Surprised" />'
, ':-P' : '<img src="smiley_tongue.png" alt=":P" title="Tongue-in-cheek" />'
, ';-)' : '<img src="smiley_wink.png" alt=";)" title="Wink" />'
}
return emoticons
defaultEmoticons=staticmethod(defaultEmoticons)
def registerDataProvider():
return EmoticonDataProvider()
class TextToEmoticons:
"""transform which replaces text emoticons into urls to emoticons images"""
__implements__ = itransform
__name__ = "text_to_emoticons"
output = "text/plain"
def __init__(self, name=None, inputs=('text/plain',)):
self.config = { 'inputs' : inputs, }
self.config_metadata = {
'inputs' : ('list', 'Inputs', 'Input(s) MIME type. Change with care.'),
}
if name:
self.__name__ = name
def name(self):
return self.__name__
def __getattr__(self, attr):
if attr == 'inputs':
return self.config['inputs']
if attr == 'output':
return self.config['output']
raise AttributeError(attr)
def convert(self, orig, data, **kwargs):
""" Replace in 'orig' all occurences of any key in the given
dictionary by its corresponding value. Returns the new string.
"""
# Get acquisition context
context = kwargs.get('context')
url_tool = getToolByName(context, 'portal_url')
dict = EmoticonDataProvider.defaultEmoticons()
# Here we need to find relative images path to the root of site
# This is done for image cashing.
dictionary = copy.deepcopy(dict)
rev_dict = {}
for k, v in dict.items():
rev_dict[v] = k
obj_ids = tuple(dict.values())
# To speed up search we are narrowing search path
start_path = url_tool.getPortalPath() + '/portal_skins'
start_obj = context.restrictedTraverse(start_path + '/custom')
results = context.PrincipiaFind(start_obj, obj_ids=obj_ids, obj_metatypes=('Image', ), search_sub=1)
start_obj = context.restrictedTraverse(start_path + '/ploneboard_templates')
results.extend(context.PrincipiaFind(start_obj, obj_ids=obj_ids, obj_metatypes=('Image', ), search_sub=1))
for rec in results:
obj = rec[1]
dictionary[rev_dict[obj.getId()]] = '<img src="%s" />' % url_tool.getRelativeContentURL(obj)
#based on ASPN recipe - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
# Create a regular expression from the dictionary keys
regex = re.compile("(%s)(?!\")" % "|".join(map(re.escape, dictionary.keys())))
# For each match, look-up corresponding value in dictionary
newdata = regex.sub(lambda mo, d=dictionary: d[mo.string[mo.start():mo.end()]], orig)
data.setData(newdata)
return data
def register():
return TextToEmoticons()
| [
[
1,
0,
0.0089,
0.0089,
0,
0.66,
0,
415,
0,
1,
0,
0,
415,
0,
0
],
[
1,
0,
0.0179,
0.0089,
0,
0.66,
0.1111,
375,
0,
1,
0,
0,
375,
0,
0
],
[
1,
0,
0.0268,
0.0089,
0,
... | [
"from Products.PortalTransforms.interfaces import itransform",
"from ZODB.PersistentMapping import PersistentMapping",
"from Products.CMFCore.utils import getToolByName",
"from Products.Ploneboard.utils import TransformDataProvider",
"import re",
"import copy",
"class EmoticonDataProvider(TransformDataP... |
from Products.PortalTransforms.interfaces import itransform
import re
hider = "##HIDE"
schemematcher = re.compile ("(mailto|telnet|gopher|http|https|ftp)", re.I)
hiddenschemematcher = re.compile ("(mailto|telnet|gopher|http|https|ftp)" + hider, re.I)
elementmatcher = re.compile("<[^>]+>")
emailRegexp = re.compile(r'["=]?(\b[A-Z0-9._%+=?\*^-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}\b)', re.I|re.S|re.U)
urlmatcher = re.compile(
r"\b(?P<url>(?P<scheme>http|https|ftp|telnet|mailto|gopher):(?P<interfix>//)"
r"(?:(?P<login>(?P<username>[a-zA-Z0-9]+)(?::(?P<password>[A-Za-z0-9]+))?)@)?"
r"(?P<hostname>[A-Za-z0-9.-]+(?::(?P<port>[0-9]+))?)"
r"(?P<path>[A-Za-z0-9@~_=?/.&;%#+-]*))", re.I)
class URLToHyperlink:
"""transform which replaces urls and email into hyperlinks"""
__implements__ = itransform
__name__ = "url_to_hyperlink"
output = "text/plain"
def __init__(self, name=None, inputs=('text/plain',)):
self.config = { 'inputs' : inputs, }
self.config_metadata = {
'inputs' : ('list', 'Inputs', 'Input(s) MIME type. Change with care.'),
}
if name:
self.__name__ = name
def name(self):
return self.__name__
def __getattr__(self, attr):
if attr == 'inputs':
return self.config['inputs']
if attr == 'output':
return self.config['output']
raise AttributeError(attr)
def linkify(input):
def hidescheme(match):
text=input[match.start():match.end()]
text=text.replace("@", "@"+hider)
return schemematcher.sub("\\1"+hider, text)
def replaceEmail(match):
url = match.groups()[0]
return '<a href="mailto:%s">%s</a>' % (url, url)
buf=elementmatcher.sub(hidescheme, input)
buf=urlmatcher.sub(r'<a href="\1">\1</a>', buf)
buf=emailRegexp.subn(replaceEmail, buf)[0]
buf=buf.replace(hider, "")
return buf
linkify=staticmethod(linkify)
def convert(self, orig, data, **kwargs):
text = orig
if not isinstance(text, unicode):
text = unicode(text, 'utf-8', 'replace')
text = self.linkify(text)
data.setData(text.encode('utf-8'))
return data
def register():
return URLToHyperlink()
__all__ = [ "URLToHyperlink", "register" ]
| [
[
1,
0,
0.0139,
0.0139,
0,
0.66,
0,
415,
0,
1,
0,
0,
415,
0,
0
],
[
1,
0,
0.0278,
0.0139,
0,
0.66,
0.1,
540,
0,
1,
0,
0,
540,
0,
0
],
[
14,
0,
0.0556,
0.0139,
0,
0.... | [
"from Products.PortalTransforms.interfaces import itransform",
"import re",
"hider = \"##HIDE\"",
"schemematcher = re.compile (\"(mailto|telnet|gopher|http|https|ftp)\", re.I)",
"hiddenschemematcher = re.compile (\"(mailto|telnet|gopher|http|https|ftp)\" + hider, re.I)",
"elementmatcher = re.compile(\"<[^... |
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import getFSVersionTuple
def install(self, reinstall=False):
tool=getToolByName(self, "portal_setup")
if getFSVersionTuple()[0]>=3:
tool.runAllImportStepsFromProfile(
"profile-Products.Ploneboard:ploneboard",
purge_old=False)
else:
plone_base_profileid = "profile-CMFPlone:plone"
tool.setImportContext(plone_base_profileid)
tool.setImportContext("profile-Products.Ploneboard:default")
tool.runAllImportSteps(purge_old=False)
tool.setImportContext(plone_base_profileid)
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.125,
0.0625,
0,
0.66,
0.5,
99,
0,
1,
0,
0,
99,
0,
0
],
[
2,
0,
0.625,
0.8125,
0,
0.66,
... | [
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFPlone.utils import getFSVersionTuple",
"def install(self, reinstall=False):\n tool=getToolByName(self, \"portal_setup\")\n\n if getFSVersionTuple()[0]>=3:\n tool.runAllImportStepsFromProfile(\n \"profile-Products.P... |
from Acquisition import aq_inner, aq_parent
from Products.Ploneboard.interfaces import IConversation, IComment
def autopublish_script(self, sci):
"""Publish the conversation along with the comment"""
object = sci.object
wftool = sci.getPortal().portal_workflow
# Try to make sure that conversation and contained messages are in sync
if IComment.providedBy(object):
parent = aq_parent(aq_inner(object))
if IConversation.providedBy(parent):
try:
if wftool.getInfoFor(parent,'review_state', None) in (sci.old_state.getId(), 'pending'):
wftool.doActionFor(parent, 'publish')
except:
pass
def publish_script(self, sci):
"""Publish the conversation along with comment"""
object = sci.object
wftool = sci.getPortal().portal_workflow
if IComment.providedBy(object):
parent = aq_parent(aq_inner(object))
if IConversation.providedBy(parent):
try:
if wftool.getInfoFor(parent,'review_state', None) in (sci.old_state.getId(), 'pending'):
wftool.doActionFor(parent, 'publish')
except:
pass
def reject_script(self, sci):
"""Reject conversation along with comment"""
# Dispatch to more easily customizable methods
object = sci.object
# We don't have notifyPublished method anymore
#object.notifyRetracted()
wftool = sci.getPortal().portal_workflow
# Try to make sure that conversation and contained messages are in sync
if IComment.providedBy(object):
parent = aq_parent(aq_inner(object))
if IConversation.providedBy(parent):
try:
if wftool.getInfoFor(parent,'review_state', None) in (sci.old_state.getId(), 'pending'):
wftool.doActionFor(parent, 'reject')
except:
pass
def lock_or_unlock(self, sci):
""" locks or unlocks board """
obj = sci.object
if sci.old_state.id == 'locked':
obj.unlock_board()
elif sci.new_state.id == 'locked':
obj.lock_board()
| [
[
1,
0,
0.0161,
0.0161,
0,
0.66,
0,
62,
0,
2,
0,
0,
62,
0,
0
],
[
1,
0,
0.0323,
0.0161,
0,
0.66,
0.2,
895,
0,
2,
0,
0,
895,
0,
0
],
[
2,
0,
0.1935,
0.2419,
0,
0.66,... | [
"from Acquisition import aq_inner, aq_parent",
"from Products.Ploneboard.interfaces import IConversation, IComment",
"def autopublish_script(self, sci):\n \"\"\"Publish the conversation along with the comment\"\"\"\n object = sci.object\n\n wftool = sci.getPortal().portal_workflow\n\n # Try to make ... |
# this file is here to make Install.py importable.
# we need to make it non-zero size to make winzip cooperate
| [] | [] |
from datetime import datetime
from dateutil.parser import parse as dateparse
from zope.i18n import translate
from DateTime.DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone import PloneMessageFactory as _plone
from Products.CMFPlone import PloneLocalesMessageFactory as _locales
from Products.Ploneboard.interfaces import IConversation, IComment
import time
class defer(object):
"""Defer function call until actually used. Useful for date components in translations"""
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __str__(self):
return self.func(*self.args, **self.kwargs)
def toPloneboardTime(context, request, time_=None):
"""Return time formatted for Ploneboard"""
ploneboard_time=None
ts = getToolByName(context, 'translation_service')
format = '%Y;%m;%d;%w;%H;%M;%S'
# fallback formats, english
young_format_en = '%A %H:%M'
old_format_en = '%B %d. %Y'
if not time_:
return 'Unknown date'
try:
if isinstance(time_, DateTime):
time_ = datetime.fromtimestamp(time_.timeTime())
else:
time_ = dateparse(str(time_))
(year, month, day, hours, minutes, seconds, wday, _, dst) = time_.timetuple()
translated_date_elements = { 'year' : year
, 'month' : defer(translate, _locales(ts.month_msgid(month)), context=request)
, 'day' : day
, 'wday' : defer(translate, _locales(ts.day_msgid((wday+1)%7)), context=request)
, 'hours' : hours
, 'minutes': minutes
, 'seconds': seconds
}
if time.time() - time.mktime(time_.timetuple()) < 604800: # 60*60*24*7
ploneboard_time = translate(_plone( 'young_date_format: ${wday} ${hours}:${minutes}'
, default = unicode(time_.strftime(young_format_en))
, mapping=translated_date_elements)
, context=request
)
else:
ploneboard_time = translate( _plone( 'old_date_format: ${year} ${month} ${day} ${hours}:${minutes}'
, default = unicode(time_.strftime(old_format_en))
, mapping = translated_date_elements)
, context=request
)
except IndexError:
pass
return ploneboard_time
def getNumberOfComments(node, catalog=None):
"""Returns the number of comments to this forum."""
if catalog is None:
catalog = getToolByName(node, 'portal_catalog')
return len(catalog(
object_provides=IComment.__identifier__,
path='/'.join(node.getPhysicalPath())))
def getNumberOfConversations(node, catalog=None):
"""Returns the number of conversations in this forum."""
if catalog is None:
catalog = getToolByName(node, 'portal_catalog')
return len(catalog(
object_provides=IConversation.__identifier__,
path='/'.join(node.getPhysicalPath())))
| [
[
1,
0,
0.0116,
0.0116,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0233,
0.0116,
0,
0.66,
0.0833,
194,
0,
1,
0,
0,
194,
0,
0
],
[
1,
0,
0.0349,
0.0116,
0,
... | [
"from datetime import datetime",
"from dateutil.parser import parse as dateparse",
"from zope.i18n import translate",
"from DateTime.DateTime import DateTime",
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFPlone import PloneMessageFactory as _plone",
"from Products.CMFPlone impor... |
from zope.schema import Tuple
from zope.schema import Choice
from zope.interface import implements
from zope.interface import Interface
from zope.formlib.form import FormFields
from zope.component import adapts
from plone.app.controlpanel.form import ControlPanelForm
from plone.app.controlpanel.widgets import MultiCheckBoxVocabularyWidget
from Products.CMFCore.utils import getToolByName
from Products.CMFDefault.formlib.schema import SchemaAdapterBase
from Products.CMFPlone.interfaces import IPloneSiteRoot
from Products.Ploneboard.utils import PloneboardMessageFactory as _
class ITransformSchema(Interface):
enabled_transforms = Tuple(
title=_(u"label_transforms",
default=u"Transforms"),
description=_(u"help_transforms",
default=u"Select the text transformations that should be "
u"used for comments posted in Ploneboard "
u"conversations. Text transformations alter the "
u"text entered by the user, either to remove "
u"potentially malicious HTML tags, or to add "
u"additional functionality, such as making links "
u"clickable."),
required=True,
missing_value=set(),
value_type=Choice(
vocabulary="Products.Ploneboard.AvailableTransforms"))
class ControlPanelAdapter(SchemaAdapterBase):
adapts(IPloneSiteRoot)
implements(ITransformSchema)
def __init__(self, context):
super(ControlPanelAdapter, self).__init__(context)
self.tool=getToolByName(self.context, "portal_ploneboard")
def get_enabled_transforms(self):
return self.tool.getEnabledTransforms()
def set_enabled_transforms(self, value):
pb=getToolByName(self.context, "portal_ploneboard")
for t in self.tool.getTransforms():
self.tool.enableTransform(t, t in value)
enabled_transforms=property(get_enabled_transforms, set_enabled_transforms)
class ControlPanel(ControlPanelForm):
form_fields = FormFields(ITransformSchema)
form_fields["enabled_transforms"].custom_widget=MultiCheckBoxVocabularyWidget
label = _(u"ploneboard_configuration",
default=u"Ploneboard configuration")
description = _(u"description_ploneboard_config",
default=u"Here you can configure site settings for Ploneboard.")
form_name = _(u"ploneboard_transform_panel",
default=u"Text transformations")
| [
[
1,
0,
0.0161,
0.0161,
0,
0.66,
0,
30,
0,
1,
0,
0,
30,
0,
0
],
[
1,
0,
0.0323,
0.0161,
0,
0.66,
0.0714,
30,
0,
1,
0,
0,
30,
0,
0
],
[
1,
0,
0.0484,
0.0161,
0,
0.66... | [
"from zope.schema import Tuple",
"from zope.schema import Choice",
"from zope.interface import implements",
"from zope.interface import Interface",
"from zope.formlib.form import FormFields",
"from zope.component import adapts",
"from plone.app.controlpanel.form import ControlPanelForm",
"from plone.a... |
from DateTime import DateTime
from Products import Five
from plone.memoize.view import memoize
from Products.CMFCore.utils import getToolByName
from Products.Ploneboard.batch import Batch
from Products.Ploneboard.browser.utils import toPloneboardTime, getNumberOfComments, getNumberOfConversations
from Products.Ploneboard.interfaces import IConversation, IComment
class ForumView(Five.BrowserView):
"""View methods for forum type
"""
def __init__(self, context, request):
Five.BrowserView.__init__(self, context, request)
self.catalog = getToolByName(context, 'portal_catalog')
self.mt = getToolByName(context,'portal_membership')
@memoize
def canStartConverstation(self):
return self.mt.checkPermission('Ploneboard: Add Comment', self.context) \
and self.mt.checkPermission('Add portal content', self.context)
@memoize
def last_login(self):
member = self.mt.getAuthenticatedMember()
last_login = member.getProperty('last_login_time', None)
if isinstance(last_login, basestring):
last_login = DateTime(last_login)
return last_login
@memoize
def getNumberOfConversations(self):
"""Returns the number of conversations in this forum."""
return getNumberOfConversations(self.context, self.catalog)
def getConversations(self, limit=20, offset=0):
"""Returns conversations."""
catalog = self.catalog
# We also have to look up member info and preferably cache that member info.
res = []
for conversation in \
catalog(object_provides=IConversation.__identifier__,
sort_on='modified',
sort_order='reverse',
sort_limit=(offset+limit),
path='/'.join(self.context.getPhysicalPath()))[offset:offset+limit]:
data = dict(review_state=conversation.review_state,
absolute_url=conversation.getURL(),
getNumberOfComments=conversation.num_comments,
modified=conversation.modified,
Title=conversation.Title,
Creator=conversation.Creator,
getLastCommentAuthor=None,# Depending on view rights to last comment
getLastCommentDate=None,
getLastCommentUrl=None,
)
# Get last comment
# THIS IS RATHER EXPENSIVE, AS WE DO CATALOG SEARCH FOR EVERY CONVERSATION
# Investigate improved caching or something...
tmp = self.catalog(
object_provides=IComment.__identifier__,
sort_on='created', sort_order='reverse', sort_limit=1,
path=conversation.getPath())
if tmp:
lastcomment = tmp[0]
data['getLastCommentUrl'] = lastcomment.getURL()
data['getLastCommentAuthor'] = lastcomment.Creator # Register member id for later lookup
data['getLastCommentDate'] = self.toPloneboardTime(lastcomment.created)
res.append(data)
return res
def toPloneboardTime(self, time_=None):
"""Return time formatted for Ploneboard"""
return toPloneboardTime(self.context, self.request, time_)
| [
[
1,
0,
0.0128,
0.0128,
0,
0.66,
0,
556,
0,
1,
0,
0,
556,
0,
0
],
[
1,
0,
0.0256,
0.0128,
0,
0.66,
0.1429,
803,
0,
1,
0,
0,
803,
0,
0
],
[
1,
0,
0.0385,
0.0128,
0,
... | [
"from DateTime import DateTime",
"from Products import Five",
"from plone.memoize.view import memoize",
"from Products.CMFCore.utils import getToolByName",
"from Products.Ploneboard.batch import Batch",
"from Products.Ploneboard.browser.utils import toPloneboardTime, getNumberOfComments, getNumberOfConver... |
from zope.component import getMultiAdapter
from zope.component import getUtility
from plone.i18n.normalizer.interfaces import IIDNormalizer
from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
class SearchView(BrowserView):
template = ViewPageTemplateFile("search.pt")
def __init__(self, context, request):
BrowserView.__init__(self, context, request)
sp=getToolByName(context, "portal_properties").site_properties
plone=getMultiAdapter((self.context, self.request), name="plone")
def crop(text):
return plone.cropText(text,
sp.search_results_description_length, sp.ellipsis)
self.crop=crop
self.normalize=getUtility(IIDNormalizer).normalize
self.icons=plone.icons_visible()
self.portal=getMultiAdapter((context, request),
name="plone_portal_state").portal_url()+"/"
def update(self):
if "q" not in self.request.form:
self.results=[]
return
text=self.request.form["q"]
for char in [ "(", ")" ]:
text=text.replace(char, '"%s"' % char)
ct=getToolByName(self.context, "portal_catalog")
self.results=ct(
object_provides="Products.Ploneboard.interfaces.IComment",
SearchableText=text)
def info(self, brain):
"""Return display-information for a search result.
"""
obj=brain.getObject()
conv=obj.getConversation()
forum=obj.getForum()
text=obj.Schema()["text"].get(obj, mimetype="text/plain").strip()
return dict(
author = brain.Creator,
title = brain.Title,
description = self.crop(text),
url = brain.getURL()+"/view",
icon = self.icons and self.portal+brain.getIcon or None,
forum_url = forum.absolute_url(),
forum_title = forum.title_or_id(),
conv_url = conv.absolute_url(),
conv_title = conv.title_or_id(),
review_state = self.normalize(brain.review_state),
portal_type = self.normalize(brain.portal_type),
relevance = brain.data_record_normalized_score_)
def board_url(self):
state=getMultiAdapter((self.context, self.request), name="plone_context_state")
return state.view_url()
def __call__(self):
self.update()
return self.template()
| [
[
1,
0,
0.0139,
0.0139,
0,
0.66,
0,
353,
0,
1,
0,
0,
353,
0,
0
],
[
1,
0,
0.0278,
0.0139,
0,
0.66,
0.1667,
353,
0,
1,
0,
0,
353,
0,
0
],
[
1,
0,
0.0417,
0.0139,
0,
... | [
"from zope.component import getMultiAdapter",
"from zope.component import getUtility",
"from plone.i18n.normalizer.interfaces import IIDNormalizer",
"from Products.Five import BrowserView",
"from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile",
"from Products.CMFCore.utils import getTo... |
from zope.interface import Interface
class IConversationView(Interface):
def comments():
"""Return all comments in the conversation.
"""
def conversation():
"""Return active conversation.
"""
def root_comments():
"""Return all of the root comments for a conversation.
"""
def children(comment):
"""Return all of the children comments for a parent comment.
"""
class ICommentView(Interface):
def comment():
"""Return active comment.
"""
def author():
"""Return the name of the author of this comment.
If no full name is known the userid is returned.
"""
def quotedBody():
"""Return the body of the comment, quoted for a reply.
"""
| [
[
1,
0,
0.0286,
0.0286,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
3,
0,
0.3,
0.4571,
0,
0.66,
0.5,
947,
0,
4,
0,
0,
270,
0,
0
],
[
2,
1,
0.1429,
0.0857,
1,
0.09,
... | [
"from zope.interface import Interface",
"class IConversationView(Interface):\n def comments():\n \"\"\"Return all comments in the conversation.\n \"\"\"\n\n def conversation():\n \"\"\"Return active conversation.\n \"\"\"",
" def comments():\n \"\"\"Return all comment... |
from Products import Five
from Products.CMFCore.utils import getToolByName
from Products.Ploneboard.browser.utils import toPloneboardTime, getNumberOfConversations
from Products.Ploneboard.interfaces import IForum, IComment
class BoardView(Five.BrowserView):
"""View methods for board type
"""
def __init__(self, context, request):
Five.BrowserView.__init__(self, context, request)
def getKeyedForums(self, sitewide=False):
"""Return all the forums in a board."""
catalog = getToolByName(self.context, 'portal_catalog')
query = {'object_provides':IForum.__identifier__}
if not sitewide:
query['path'] = '/'.join(self.context.getPhysicalPath())
result = {}
for f in catalog(query):
obj = f._unrestrictedGetObject()
data = dict(absolute_url=f.getURL(),
Title=f.Title,
Description=f.Description,
getNumberOfConversations=getNumberOfConversations(obj, catalog), # XXX THIS AND CATEGORY IS WHY WE NEED GETOBJECT, TRY CACHING
getLastCommentDate=None,
getLastCommentAuthor=None,
)
lastcomment = catalog(object_provides=IComment.__identifier__,
sort_on='created',
sort_order='reverse',
sort_limit=1,
path='/'.join(obj.getPhysicalPath()))
if lastcomment:
lastcomment = lastcomment[0]
data['getLastCommentDate'] = self.toPloneboardTime(lastcomment.created)
data['getLastCommentAuthor'] = lastcomment.Creator
try:
categories = obj.getCategory()
except AttributeError:
categories = None
if not categories:
categories = None
if not isinstance(categories, (tuple,list)):
categories = categories,
for category in categories:
try:
categoryforums = result.get(category, [])
categoryforums.append(data)
result[category] = categoryforums
except TypeError: # category is list?!
result[', '.join(category)] = data
return result
def toPloneboardTime(self, time_=None):
"""Return time formatted for Ploneboard"""
return toPloneboardTime(self.context, self.request, time_)
| [
[
1,
0,
0.0161,
0.0161,
0,
0.66,
0,
803,
0,
1,
0,
0,
803,
0,
0
],
[
1,
0,
0.0323,
0.0161,
0,
0.66,
0.25,
287,
0,
1,
0,
0,
287,
0,
0
],
[
1,
0,
0.0484,
0.0161,
0,
0.... | [
"from Products import Five",
"from Products.CMFCore.utils import getToolByName",
"from Products.Ploneboard.browser.utils import toPloneboardTime, getNumberOfConversations",
"from Products.Ploneboard.interfaces import IForum, IComment",
"class BoardView(Five.BrowserView):\n \"\"\"View methods for board ty... |
#
| [] | [] |
"""
$Id: comment.py 99041 2009-10-06 06:38:21Z sureshvv $
"""
from zope import interface
from Acquisition import aq_base
from DateTime.DateTime import DateTime
from Products import Five
from Products.CMFCore import utils as cmf_utils
from Products.CMFCore.utils import getToolByName
from Products.Ploneboard import permissions
from Products.Ploneboard.batch import Batch
from Products.Ploneboard.browser.interfaces import IConversationView
from Products.Ploneboard.browser.interfaces import ICommentView
from Products.Ploneboard.browser.utils import toPloneboardTime
from Products.Ploneboard.utils import PloneboardMessageFactory as _
class CommentViewableView(Five.BrowserView):
"""Any view that might want to interact with comments should inherit
from this base class.
"""
def __init__(self, context, request):
Five.BrowserView.__init__(self, context, request)
self.portal_actions = cmf_utils.getToolByName(self.context, 'portal_actions')
self.plone_utils = cmf_utils.getToolByName(self.context, 'plone_utils')
self.portal_membership = cmf_utils.getToolByName(self.context, 'portal_membership')
self.portal_workflow = cmf_utils.getToolByName(self.context, 'portal_workflow')
def _buildDict(self, comment):
"""Produce a dict representative of all the important properties
of a comment.
"""
checkPermission = self.portal_membership.checkPermission
actions = self.portal_actions.listFilteredActionsFor(comment)
res= {
'Title': comment.title_or_id(),
'Creator': comment.Creator(),
'creation_date': self.toPloneboardTime(comment.CreationDate()),
'getId': comment.getId(),
'getText': comment.getText(),
'absolute_url': comment.absolute_url(),
'getAttachments': comment.getAttachments(),
'canEdit': checkPermission(permissions.EditComment, comment),
'canDelete': checkPermission(permissions.DeleteComment, comment),
'canReply': checkPermission(permissions.AddComment, comment),
'getObject': comment,
'workflowActions' : actions['workflow'],
'review_state' : self.portal_workflow.getInfoFor(comment, 'review_state'),
'reviewStateTitle' : self.plone_utils.getReviewStateTitleFor(comment),
'UID': comment.UID(),
}
return res
def toPloneboardTime(self, time_=None):
"""Return time formatted for Ploneboard"""
return toPloneboardTime(self.context, self.request, time_)
class CommentView(CommentViewableView):
"""A view for getting information about one specific comment.
"""
interface.implements(ICommentView)
def comment(self):
return self._buildDict(self.context)
def author(self):
creator = self.context.Creator()
info = self.portal_membership.getMemberInfo(creator)
if info is None:
return creator
fullname_or_id = info.get('fullname') or info.get('username') or creator
return fullname_or_id
def quotedBody(self):
text = self.context.getText()
if text:
return _("label_quote", u"Previously ${author} wrote: ${quote}", {"author": unicode(self.author(), 'utf-8'),
"quote": unicode("<blockquote>%s</blockquote></br>" % (self.context.getText()), 'utf-8')})
else:
return ''
class ConversationView(CommentView):
"""A view component for querying conversations.
"""
interface.implements(IConversationView)
def conversation(self):
checkPermission = self.portal_membership.checkPermission
conv = self.context
forum = conv.getForum()
return {
'maximumAttachments' : forum.getMaxAttachments(),
'maximumAttachmentSize' : forum.getMaxAttachmentSize(),
'canAttach': forum.getMaxAttachments()>0 and \
checkPermission(permissions.AddAttachment,conv),
}
def comments(self):
conv = self.context
forum = conv.getForum()
batchSize = forum.getConversationBatchSize()
batchStart = self.request.get('b_start', 0)
if type(batchStart) == type('a'):
batchStart = int(batchStart.split('#')[0])
numComments = conv.getNumberOfComments()
return Batch(self._getComments, numComments, batchSize, batchStart, orphan=1)
def root_comments(self):
rootcomments = self.context.getRootComments()
for ob in rootcomments:
yield self._buildDict(ob)
def children(self, comment):
if type(comment) is dict:
comment = comment['getObject']
for ob in comment.getReplies():
yield self._buildDict(ob)
def _getComments(self, limit, offset):
"""Dictify comments before returning them to the batch
"""
return [self._buildDict(ob) for ob in self.context.getComments(limit=limit, offset=offset)]
class RecentConversationsView(CommentViewableView):
"""Find recent conversations
"""
def __init__(self, context, request):
Five.BrowserView.__init__(self, context, request)
self.portal_workflow = cmf_utils.getToolByName(self.context, 'portal_workflow')
self.plone_utils = cmf_utils.getToolByName(self.context, 'plone_utils')
self.portal_catalog = cmf_utils.getToolByName(self.context, 'portal_catalog')
self.portal_membership = cmf_utils.getToolByName(self.context, 'portal_membership')
def num_conversations(self):
catalog = self.portal_catalog
results = catalog(object_provides='Products.Ploneboard.interfaces.IConversation',
path='/'.join(self.context.getPhysicalPath()),)
return len(results)
def results(self, limit=20, offset=0):
catalog = self.portal_catalog
results = catalog(object_provides='Products.Ploneboard.interfaces.IConversation',
sort_on='modified',
sort_order='reverse',
sort_limit=(offset+limit),
path='/'.join(self.context.getPhysicalPath()))[offset:offset+limit]
return filter(None, [self._buildDict(r.getObject()) for r in results])
def _buildDict(self, ob):
forum = ob.getForum()
wfstate = self.portal_workflow.getInfoFor(ob, 'review_state')
wfstate = self.plone_utils.normalizeString(wfstate)
creator = ob.Creator()
creatorInfo = self.portal_membership.getMemberInfo(creator)
if creatorInfo is not None and creatorInfo.get('fullname', "") != "":
creator = creatorInfo['fullname']
lastComment = ob.getLastComment()
if lastComment is None:
return None
canAccessLastComment = self.portal_membership.checkPermission('View', lastComment)
lastCommentCreator = lastComment.Creator()
creatorInfo = self.portal_membership.getMemberInfo(lastCommentCreator)
if creatorInfo is not None and creatorInfo.get('fullname', '') != "":
lastCommentCreator = creatorInfo['fullname']
return { 'Title': ob.title_or_id(),
'Description' : ob.Description(),
'absolute_url': ob.absolute_url(),
'forum_title' : forum.title_or_id(),
'forum_url' : forum.absolute_url(),
'review_state_normalized' : wfstate,
'num_comments' : ob.getNumberOfComments(),
'creator' : creator,
'last_comment_id' : lastComment.getId(),
'last_comment_creator' : lastCommentCreator,
'last_comment_date' : lastComment.created(),
'can_access_last_comment' : canAccessLastComment,
'is_new' : self._is_new(ob.modified()),
}
def _is_new(self, modified):
llt = getattr(aq_base(self), '_last_login_time', [])
if llt == []:
m = self.portal_membership.getAuthenticatedMember()
if m.has_role('Anonymous'):
llt = self._last_login_time = None
else:
llt = self._last_login_time = m.getProperty('last_login_time', 0)
if llt is None: # not logged in
return False
elif llt == 0: # never logged in before
return True
else:
return (modified >= DateTime(llt))
class UnansweredConversationsView(RecentConversationsView):
"""Find unanswered conversations
"""
def num_conversations(self):
catalog = self.portal_catalog
results = catalog(object_provides='Products.Ploneboard.interfaces.IConversation',
num_comments=1,
path='/'.join(self.context.getPhysicalPath()),)
return len(results)
def results(self, limit=20, offset=0):
catalog = self.portal_catalog
results = catalog(object_provides='Products.Ploneboard.interfaces.IConversation',
num_comments=1,
sort_on='modified',
sort_order='reverse',
sort_limit=(offset+limit),
path='/'.join(self.context.getPhysicalPath()))[offset:offset+limit]
return [self._buildDict(r.getObject()) for r in results]
def _buildDict(self, ob):
forum = ob.getForum()
wfstate = self.portal_workflow.getInfoFor(ob, 'review_state')
wfstate = self.plone_utils.normalizeString(wfstate)
creator = ob.Creator()
creatorInfo = self.portal_membership.getMemberInfo(creator)
if creatorInfo is not None and creatorInfo.get('fullname', "") != "":
creator = creatorInfo['fullname']
return { 'Title': ob.title_or_id(),
'Description' : ob.Description(),
'created' : ob.created(),
'absolute_url': ob.absolute_url(),
'forum_title' : forum.title_or_id(),
'forum_url' : forum.absolute_url(),
'review_state_normalized' : wfstate,
'creator' : creator,
'is_new' : self._is_new(ob.modified()),
}
class DeleteCommentView(Five.BrowserView):
"""Delete the current comment. If the comment is the root comment
of a conversation, delete the entire conversation instead.
"""
def __call__(self):
redirect = self.request.response.redirect
comment = self.context
conversation = comment.getConversation()
plone_utils = cmf_utils.getToolByName(comment, 'plone_utils')
if len(conversation.getComments()) == 1:
forum = conversation.getForum()
conversation.delete()
msg = _(u'Conversation deleted')
plone_utils.addPortalMessage(msg)
redirect(forum.absolute_url())
else:
comment.delete()
msg = _(u'Comment deleted')
plone_utils.addPortalMessage(msg)
redirect(conversation.absolute_url())
| [
[
8,
0,
0.0073,
0.0109,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0146,
0.0036,
0,
0.66,
0.0556,
603,
0,
1,
0,
0,
603,
0,
0
],
[
1,
0,
0.0182,
0.0036,
0,
0.66... | [
"\"\"\"\n$Id: comment.py 99041 2009-10-06 06:38:21Z sureshvv $\n\"\"\"",
"from zope import interface",
"from Acquisition import aq_base",
"from DateTime.DateTime import DateTime",
"from Products import Five",
"from Products.CMFCore import utils as cmf_utils",
"from Products.CMFCore.utils import getToolB... |
from zope.interface import implements
from zope import schema
from zope.component import getUtility
from zope.component import getMultiAdapter
from zope.formlib.form import Fields
from plone.memoize.view import memoize
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.i18n.normalizer.interfaces import IIDNormalizer
from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider
from Products.Ploneboard.utils import PloneboardMessageFactory as _
class IRecentConversationsPortlet(IPortletDataProvider):
"""A portlet which shows recent Ploneboard conversations.
"""
title = schema.TextLine(title=_(u"title_title",
default=u"Portlet title"),
required=True,
default=u"Recent messages")
count = schema.Int(title=_(u"title_count",
default=u"Number of items to display"),
description=_(u"help_count",
default=u"How many items to list."),
required=True,
default=5)
class Assignment(base.Assignment):
implements(IRecentConversationsPortlet)
title = u"Recent messages"
count = 5
def __init__(self, title=None, count=None):
if title is not None:
self.title=title
if count is not None:
self.count=count
class Renderer(base.Renderer):
def __init__(self, context, request, view, manager, data):
base.Renderer.__init__(self, context, request, view, manager, data)
@memoize
def results(self):
ct=getToolByName(self.context, "portal_catalog")
normalize=getUtility(IIDNormalizer).normalize
icons=getMultiAdapter((self.context, self.request),
name="plone").icons_visible()
if icons:
portal=getMultiAdapter((self.context, self.request),
name="plone_portal_state").portal_url()+"/"
brains=ct(
object_provides="Products.Ploneboard.interfaces.IConversation",
sort_on="modified",
sort_order="reverse",
sort_limit=self.data.count)[:self.data.count]
def morph(brain):
obj=brain.getObject()
forum=obj.getForum()
return dict(
title = brain.Title,
description = brain.Description,
url = brain.getURL()+"/view",
icon = icons and portal+brain.getIcon or None,
forum_url = forum.absolute_url(),
forum_title = forum.title_or_id(),
review_state = normalize(brain.review_state),
portal_type = normalize(brain.portal_type),
date = brain.modified)
return [morph(brain) for brain in brains]
@property
def available(self):
return len(self.results())>0
def update(self):
self.conversations=self.results()
@property
def title(self):
return self.data.title
@property
def next_url(self):
state=getMultiAdapter((self.context, self.request),
name="plone_portal_state")
return state.portal_url()+"/ploneboard_recent"
render = ViewPageTemplateFile("recent.pt")
class AddForm(base.AddForm):
form_fields = Fields(IRecentConversationsPortlet)
label = _(u"label_add_portlet",
default=u"Add recent conversations portlet.")
description = _(u"help_add_portlet",
default=u"This portlet shows conversations with recent comments.")
def create(self, data):
return Assignment(title=data.get("title"), count=data.get("count"))
class EditForm(base.EditForm):
form_fields = Fields(IRecentConversationsPortlet)
label = _(u"label_add_portlet",
default=u"Add recent conversations portlet.")
description = _(u"help_add_portlet",
default=u"This portlet shows conversations with recent comments.")
| [
[
1,
0,
0.0083,
0.0083,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0167,
0.0083,
0,
0.66,
0.0625,
603,
0,
1,
0,
0,
603,
0,
0
],
[
1,
0,
0.025,
0.0083,
0,
0... | [
"from zope.interface import implements",
"from zope import schema",
"from zope.component import getUtility",
"from zope.component import getMultiAdapter",
"from zope.formlib.form import Fields",
"from plone.memoize.view import memoize",
"from Products.CMFCore.utils import getToolByName",
"from Product... |
# Poof
| [] | [] |
from zope.interface import implements
from AccessControl import ClassSecurityInfo
from Products.CMFCore.utils import getToolByName
from Products.Archetypes.public import BaseBTreeFolderSchema, Schema, TextField, LinesField
from Products.Archetypes.public import BaseBTreeFolder, registerType
from Products.Archetypes.public import TextAreaWidget, LinesWidget
from Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin
from Products.Ploneboard.config import PROJECTNAME
from Products.Ploneboard.permissions import ViewBoard, SearchBoard, \
AddForum, ManageBoard
from Products.Ploneboard.content.PloneboardForum import PloneboardForum
from Products.Ploneboard.interfaces import IPloneboard
from Products.Ploneboard import utils
schema = BaseBTreeFolderSchema + Schema((
TextField('description',
searchable = 1,
default_content_type = 'text/html',
default_output_type = 'text/plain',
widget = TextAreaWidget(description = "Enter a brief description of the board.",
description_msgid = "help_description_board",
i18n_domain = "ploneboard",
label = "Description",
label_msgid = "label_description_board",
rows = 5)),
LinesField('categories',
widget = LinesWidget(
description = "Enter the categories you want to have available for forums, one category on each line.",
description_msgid = "help_categories_board",
label = "Categories",
label_msgid = "label_categories_board",
i18n_domain = "ploneboard")),
))
utils.finalizeSchema(schema)
class Ploneboard(BrowserDefaultMixin, BaseBTreeFolder):
"""Ploneboard is the outmost board object, what shows up in your site."""
implements(IPloneboard)
__implements__ = (BrowserDefaultMixin.__implements__, BaseBTreeFolder.__implements__,)
meta_type = 'Ploneboard'
schema = schema
_at_rename_after_creation = True
security = ClassSecurityInfo()
def getCatalog(self):
return getToolByName(self, 'portal_catalog')
security.declareProtected(ManageBoard, 'edit')
def edit(self, **kwargs):
"""Alias for update()
"""
self.update(**kwargs)
security.declareProtected(AddForum, 'addForum')
def addForum( self
, id
, title
, description ):
"""Add a forum to the board.
XXX: Should be possible to parameterise the exact type that is being
added.
"""
kwargs = {'title' : title, 'description' : description}
forum = PloneboardForum(id)
self._setObject(id, forum)
forum = getattr(self, id)
forum.initializeArchetype(**kwargs)
forum._setPortalTypeName('PloneboardForum')
forum.notifyWorkflowCreated()
# Enable topic syndication by default
syn_tool = getToolByName(self, 'portal_syndication', None)
if syn_tool is not None:
if (syn_tool.isSiteSyndicationAllowed() and not syn_tool.isSyndicationAllowed(forum)):
syn_tool.enableSyndication(forum)
#forum.setDescription(description)
return forum
security.declareProtected(ViewBoard, 'getForums')
def getForums(self, sitewide=False):
"""Return all the forums in this board."""
query = {'object_provides':'Products.Ploneboard.interfaces.IForum'}
if not sitewide:
query['path'] = '/'.join(self.getPhysicalPath())
return [f.getObject() for f in self.getCatalog()(query)]
security.declareProtected(ViewBoard, 'getForumIds')
def getForumIds(self):
"""Return all the forums in this board."""
return [f.getId for f in self.getCatalog()(
object_provides='Products.Ploneboard.interfaces.IForum')]
security.declareProtected(ManageBoard, 'removeForum')
def removeForum(self, forum_id):
"""Remove a forum from this board."""
self._delObject(forum_id)
security.declareProtected(SearchBoard, 'searchComments')
def searchComments(self, query):
"""This method searches through all forums, conversations and comments."""
return self.getCatalog()(**query)
security.declarePublic('getForum')
def getForum(self, forum_id):
"""Returns forum with specified forum id."""
#return getattr(self, forum_id, None)
forums = self.getCatalog()(
object_provides='Products.Ploneboard.interfaces.IForum',
getId=forum_id)
if forums:
return forums[0].getObject()
else:
return None
def __nonzero__(self):
return 1
registerType(Ploneboard, PROJECTNAME)
| [
[
1,
0,
0.0076,
0.0076,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0229,
0.0076,
0,
0.66,
0.0667,
227,
0,
1,
0,
0,
227,
0,
0
],
[
1,
0,
0.0305,
0.0076,
0,
... | [
"from zope.interface import implements",
"from AccessControl import ClassSecurityInfo",
"from Products.CMFCore.utils import getToolByName",
"from Products.Archetypes.public import BaseBTreeFolderSchema, Schema, TextField, LinesField",
"from Products.Archetypes.public import BaseBTreeFolder, registerType",
... |
from zope.interface import implements
from AccessControl import ClassSecurityInfo
from Acquisition import aq_chain, aq_inner
from OFS.CopySupport import CopyContainer
from OFS.Image import File
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType, log_deprecated
from Products.Archetypes.public import BaseBTreeFolderSchema, Schema
from Products.Archetypes.public import TextField, LinesField, IntegerField
from Products.Archetypes.public import BaseBTreeFolder, registerType
from Products.Archetypes.public import TextAreaWidget, MultiSelectionWidget, IntegerWidget, SelectionWidget
from Products.Archetypes.public import DisplayList
from Products.Ploneboard.config import PROJECTNAME, HAS_SIMPLEATTACHMENT
from Products.Ploneboard.permissions import ViewBoard, ManageForum, AddConversation, MoveConversation
from Products.Ploneboard.interfaces import IPloneboard, IForum
from Products.Ploneboard.interfaces import IConversation, IComment
from Products.Ploneboard import utils
from Products.CMFPlone.interfaces.NonStructuralFolder \
import INonStructuralFolder as ZopeTwoINonStructuralFolder
from Products.CMFPlone.interfaces.structure import INonStructuralFolder
from Products.Archetypes.event import ObjectInitializedEvent
from zope import event
schema = BaseBTreeFolderSchema + Schema((
TextField('description',
searchable = 1,
default_content_type = 'text/html',
default_output_type = 'text/plain',
widget = TextAreaWidget(
description = "Brief description of the forum topic.",
description_msgid = "help_description_forum",
label = "Description",
label_msgid = "label_description_forum",
i18n_domain = "ploneboard",
rows = 5)),
LinesField('category',
write_permission = ManageForum,
vocabulary = 'getCategories',
widget = MultiSelectionWidget(
description = "Select which category the forum should be listed under. A forum can exist in multiple categories, although using only one category is recommended.",
description_msgid = "help_category",
condition="object/getCategories",
label = "Category",
label_msgid = "label_category",
i18n_domain = "ploneboard",
)),
IntegerField('maxAttachments',
write_permission = ManageForum,
default = 1,
widget = IntegerWidget(
description = "Select the maximum number of attachments per comment.",
description_msgid = "help_maxattachments",
label = "Maximum number of attachments",
label_msgid = "label_maxattachments",
i18n_domain = "ploneboard",
)),
IntegerField('maxAttachmentSize',
write_permission = ManageForum,
vocabulary = 'getAttachmentSizes',
default = 100,
widget = SelectionWidget(
description = "Select the maximum size for attachments.",
description_msgid = "help_maxattachmentsize",
label = "Maximum attachment size",
label_msgid = "label_maxattachmentsize",
i18n_domain = "ploneboard",
)),
))
utils.finalizeSchema(schema)
if not HAS_SIMPLEATTACHMENT:
schema['maxAttachments'].mode="r"
schema['maxAttachments'].default=0
schema['maxAttachments'].widget.visible={'edit' : 'invisible', 'view' : 'invisible' }
schema['maxAttachmentSize'].widget.visible={'edit' : 'invisible', 'view' : 'invisible' }
class PloneboardForum(BaseBTreeFolder):
"""A Forum contains conversations."""
implements(IForum, INonStructuralFolder)
__implements__ = (BaseBTreeFolder.__implements__, ZopeTwoINonStructuralFolder)
meta_type = 'PloneboardForum'
schema = schema
_at_rename_after_creation = True
security = ClassSecurityInfo()
def getCatalog(self):
return getToolByName(self, 'portal_catalog')
security.declareProtected(ManageForum, 'edit')
def edit(self, **kwargs):
"""Alias for update()
"""
self.update(**kwargs)
security.declarePublic('synContentValues')
def synContentValues(self):
return (self.getConversations())
security.declareProtected(ViewBoard, 'getBoard')
def getBoard(self):
"""Returns containing or nearest board."""
# Try containment
stoptypes = ['Plone Site']
for obj in aq_chain(aq_inner(self)):
if hasattr(obj, 'portal_type') and obj.portal_type not in stoptypes:
if IPloneboard.providedBy(obj):
return obj
return None
security.declareProtected(AddConversation, 'addConversation')
def addConversation(self, title, text=None, creator=None, files=None, **kwargs):
"""Adds a new conversation to the forum.
XXX should be possible to parameterise the exact type that is being
added.
"""
id = self.generateId(prefix='')
conv = _createObjectByType('PloneboardConversation', self, id)
event.notify(ObjectInitializedEvent(conv))
# XXX: There is some permission problem with AT write_permission
# and using **kwargs in the _createObjectByType statement.
conv.setTitle(title)
if creator is not None:
conv.setCreators([creator])
if text is not None or files:
m = _createObjectByType('PloneboardComment', conv, conv.generateId(prefix=''))
event.notify(ObjectInitializedEvent(m))
# XXX: There is some permission problem with AT write_permission
# and using **kwargs in the _createObjectByType statement.
m.setTitle(title)
if text is not None:
m.setText(text)
if creator is not None:
m.setCreators([creator])
# Create files in message
if files:
for file in files:
# Get raw filedata, not persistent object with reference to tempstorage
attachment = File(file.getId(), file.title_or_id(), str(file.data), file.getContentType())
m.addAttachment(attachment)
m.reindexObject()
conv.reindexObject()
return conv
security.declareProtected(ViewBoard, 'getConversation')
def getConversation(self, conversation_id, default=None):
"""Returns the conversation with the given conversation id."""
#return self._getOb(conversation_id, default)
catalog = self.getCatalog()
conversations = catalog(
object_provides=IConversation.__identifier__,
getId=conversation_id,
path='/'.join(self.getPhysicalPath()))
if conversations:
return conversations[0].getObject()
else:
return None
security.declareProtected(ManageForum, 'removeConversation')
def removeConversation(self, conversation_id):
"""Removes a conversation with the given conversation id from the forum."""
self._delObject(conversation_id)
security.declareProtected(ViewBoard, 'getConversations')
def getConversations(self, limit=20, offset=0):
"""Returns conversations."""
log_deprecated("Products.Ploneboard.content.PloneboardForum.PloneboardForum.getConversations is deprecated in favor of Products.Ploneboard.browser.forum.ForumView.getConversations")
catalog = self.getCatalog()
return [f.getObject() for f in \
catalog(object_provides=IConversation.__identifier__,
sort_on='modified',
sort_order='reverse',
sort_limit=(offset+limit),
path='/'.join(self.getPhysicalPath()))[offset:offset+limit]]
security.declareProtected(ViewBoard, 'getNumberOfConversations')
def getNumberOfConversations(self):
"""Returns the number of conversations in this forum."""
log_deprecated("Products.Ploneboard.content.PloneboardForum.PloneboardForum.getNumberOfConversations is deprecated in favor of Products.Ploneboard.browser.forum.ForumView.getNumberOfConversations")
return len(self.getCatalog()(
object_provides=IConversation.__identifier__,
path='/'.join(self.getPhysicalPath())))
security.declareProtected(ViewBoard, 'getNumberOfComments')
def getNumberOfComments(self):
"""Returns the number of comments to this forum."""
log_deprecated("Products.Ploneboard.content.PloneboardForum.PloneboardForum.getNumberOfComments is deprecated in favor of Products.Ploneboard.browser.forum.ForumView.getNumberOfComments")
return len(self.getCatalog()(
object_provides='Products.Ploneboard.interfaces.IComment',
path='/'.join(self.getPhysicalPath())))
security.declareProtected(ViewBoard, 'getLastConversation')
def getLastConversation(self):
"""
Returns the last conversation.
"""
# XXX Is Created or Modified the most interesting part?
res = self.getCatalog()(
object_provides=IConversation.__identifier__,
sort_on='created', sort_order='reverse', sort_limit=1,
path='/'.join(self.getPhysicalPath()))
if res:
return res[0].getObject()
else:
return None
security.declareProtected(ViewBoard, 'getLastCommentDate')
def getLastCommentDate(self):
"""
Returns a DateTime corresponding to the timestamp of the last comment
for the forum.
"""
res = self.getCatalog()(
object_provides='Products.Ploneboard.interfaces.IComment',
sort_on='created', sort_order='reverse', sort_limit=1,
path='/'.join(self.getPhysicalPath()))
if res:
return res[0].created
else:
return None
security.declareProtected(ViewBoard, 'getLastCommentAuthor')
def getLastCommentAuthor(self):
"""
Returns the name of the author of the last comment.
"""
res = self.getCatalog()(
object_provides='Products.Ploneboard.interfaces.IComment',
sort_on='created', sort_order='reverse', sort_limit=1,
path='/'.join(self.getPhysicalPath()))
if res:
return res[0].Creator
else:
return None
# Vocabularies
security.declareProtected(ViewBoard, 'getCategories')
def getCategories(self):
value = []
board = self.getBoard()
if board is not None and hasattr(board, 'getCategories'):
categories = board.getCategories()
if categories is not None:
value = [(c,c) for c in categories]
value.sort()
return DisplayList(value)
security.declareProtected(ViewBoard, 'getAttachmentSizes')
def getAttachmentSizes(self):
voc = DisplayList()
voc.add(10, '10 kilobyte')
voc.add(100, '100 kilobyte')
voc.add(1000, '1 megabyte')
voc.add(10000, '10 megabyte')
voc.add(-1, 'unlimited')
return voc
security.declarePublic('getConversationBatchSize')
def getConversationBatchSize(self):
pb_tool = getToolByName(self, 'portal_ploneboard')
prop_name = "%s_ConversationBatchSize" % self.getId()
if pb_tool.hasProperty(prop_name):
return pb_tool.getProperty(prop_name)
prop_name = "ConversationBatchSize"
if pb_tool.hasProperty(prop_name):
return pb_tool.getProperty(prop_name)
return 30
############################################################################
# Folder methods, indexes and such
security.declareProtected(MoveConversation, 'manage_pasteObjects')
def manage_pasteObjects(self, cp):
""" move another conversation """
CopyContainer.manage_pasteObjects(self, cp)
def __nonzero__(self):
return 1
registerType(PloneboardForum, PROJECTNAME)
| [
[
1,
0,
0.0033,
0.0033,
0,
0.66,
0,
443,
0,
1,
0,
0,
443,
0,
0
],
[
1,
0,
0.0098,
0.0033,
0,
0.66,
0.04,
227,
0,
1,
0,
0,
227,
0,
0
],
[
1,
0,
0.013,
0.0033,
0,
0.6... | [
"from zope.interface import implements",
"from AccessControl import ClassSecurityInfo",
"from Acquisition import aq_chain, aq_inner",
"from OFS.CopySupport import CopyContainer",
"from OFS.Image import File",
"from Products.CMFCore.utils import getToolByName",
"from Products.CMFPlone.utils import _creat... |
import Ploneboard
import PloneboardForum
import PloneboardConversation
import PloneboardComment
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
534,
0,
1,
0,
0,
534,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.3333,
371,
0,
1,
0,
0,
371,
0,
0
],
[
1,
0,
0.75,
0.25,
0,
0.66,
0.6... | [
"import Ploneboard",
"import PloneboardForum",
"import PloneboardConversation",
"import PloneboardComment"
] |
try:
from lipsum import markupgenerator
except ImportError:
class markupgenerator(object):
def __init__(self,sample,dictionary):pass
def generate_sentence(self):return 'subject'
def generate_paragraph(self):return 'Please install lorem-ipsum-generator.'
import transaction
from time import time
from random import betavariate
from Products.CMFCore.utils import getToolByName
from Products.Ploneboard.config import EMOTICON_TRANSFORM_MODULE
from Products.Ploneboard.config import URL_TRANSFORM_MODULE
from Products.Ploneboard.config import SAFE_HTML_TRANSFORM_MODULE
def setupVarious(context):
if not context.readDataFile('ploneboard_various.txt'):
return
site=context.getSite()
addTransforms(site)
setupCommentLocalRoles(site)
addPlacefulPolicy(site)
def addTransforms(site):
pb_tool = getToolByName(site, 'portal_ploneboard')
pb_tool.registerTransform('text_to_emoticons', EMOTICON_TRANSFORM_MODULE, 'Graphical smilies')
pb_tool.registerTransform('url_to_hyperlink', URL_TRANSFORM_MODULE, 'Clickable links')
pb_tool.registerTransform('safe_html', SAFE_HTML_TRANSFORM_MODULE, 'Remove dangerous HTML')
def lotsofposts(context):
debug = True
if not context.readDataFile('ploneboard_lotsofposts.txt'):
return
sample = context.readDataFile('rabbit.txt')
dictionary = context.readDataFile('vocab.txt')
mg = markupgenerator(sample=sample, dictionary=dictionary)
# XXX CREATE 1000 REAL USERS WITH AVATARS FOR POSTING
# For every forum, create random content for a total of a configurable number
totalgoal = 100000
site=context.getSite()
board = site.ploneboard # From the basicboard dependency
forums = board.getForums()
for forum in forums:
count = int(totalgoal * betavariate(1, len(forums)-1))
i = 0
while i < count:
start = time()
conv = forum.addConversation(mg.generate_sentence(), mg.generate_paragraph())
i+=1
if debug:
print "Creating conversation %s of %s in %s in %.5fs" % (i, count, forum.getId(), time()-start)
if i % 1000 == 0:
transaction.get().savepoint(optimistic=True)
if debug:
print "\nSAVEPOINT\n"
# XXX add arbitrary number of comments, which all count towards count
for j in range(0,int(betavariate(1, 5) * max(300,(count/10)))):
if i < count:
start = time()
conv.addComment(mg.generate_sentence(), mg.generate_paragraph())
i+=1
if debug:
print "Creating comment %s of %s in %s in %.5fs" % (i, count, forum.getId(), time()-start)
if i % 1000 == 0:
transaction.get().savepoint(optimistic=True)
if debug:
print "\nSAVEPOINT\n"
else:
continue
def setupCommentLocalRoles(self):
pc=getToolByName(self, 'portal_catalog')
pu=getToolByName(self, 'plone_utils')
comments=pc(object_provides='Products.Ploneboard.interfaces.IComment')
comments=[x.getObject() for x in comments if x.getObject()]
count=0
for c in comments:
# Do not update needlessly. Screws up modified
if not pu.isLocalRoleAcquired(c):
pu.acquireLocalRoles(c, 0)
count += 1
self.plone_log('setupCommentLocalRoles', 'Updated %d of total %d comments' % (count, len(comments)))
def addPlacefulPolicy(self):
pw=getToolByName(self, 'portal_placeful_workflow')
new_id = 'EditableComment'
if new_id not in pw.objectIds():
pw.manage_addWorkflowPolicy(new_id)
ob = pw[new_id]
ob.setChain('PloneboardComment', 'ploneboard_editable_comment_workflow')
| [
[
7,
0,
0.0408,
0.0714,
0,
0.66,
0,
0,
0,
1,
0,
0,
0,
0,
0
],
[
1,
1,
0.0204,
0.0102,
1,
0.44,
0,
758,
0,
1,
0,
0,
758,
0,
0
],
[
3,
1,
0.0561,
0.0408,
1,
0.44,
... | [
"try:\n from lipsum import markupgenerator\nexcept ImportError:\n class markupgenerator(object):\n def __init__(self,sample,dictionary):pass\n def generate_sentence(self):return 'subject'\n def generate_paragraph(self):return 'Please install lorem-ipsum-generator.'",
" from lipsum im... |
"""
$Id: interfaces.py 55766 2007-12-18 11:08:52Z wichert $
"""
# Dependency on Zope 2.8.x (or greater) or Five
from zope.interface import Interface, Attribute
class IPloneboard(Interface):
"""
Ploneboard is the outmost board object, what shows up in your site.
The board contains forums. Board is folderish. The number of items contained
in Board should be limited and steady.
This is an optional type.
"""
def addForum(id, title, description):
"""
The method add_forum takes id, title and description and creates a
forum inside the board.
Should this go away and rather just use the regular Plone content
creation? That would make it easier to switch content types.
"""
def removeForum(forum_id):
"""
The method remove_forum removes the forum with the specified id from
this board.
"""
def getForum(forum_id):
"""
Return the forum for forum_id, or None.
"""
def getForumIds():
"""
Returns the ids of the forums.
If this is the only board in a site, it should return forum ids for
the entire site, not just inside the board.
"""
def getForums():
"""
Return the forums
If this is the only board in a site, it should return forums for the
entire site, not just inside the board.
"""
def searchComments(query):
"""
This method searches through all forums, conversations and comments.
"""
class IForum(Interface):
"""
A Forum contains conversations. Forum is folderish. The number of items contained
in Forum is high and increases, so it is probably a good idea to use BTrees
for indexing.
"""
def getBoard():
"""
Gets the containing board.
Returns None if there are no boards in the site.
"""
def addConversation(subject, body, **kw):
"""
Adds a new conversation to the forum.
Should this go away and rather just use the regular Plone content
creation? That would make it easier to switch content types.
"""
def getConversation(conversation_id):
"""
Returns the conversation with the given conversation id.
"""
def removeConversation(conversation_id):
"""
Removes a conversation with the given conversation id from the forum.
"""
def getConversations(limit=20, offset=0):
"""
Returns a maximum of 'limit' conversations, the last updated conversations first,
starting from 'offset'.
"""
def getNumberOfConversations():
"""
Returns the number of conversations in this forum.
"""
def getNumberOfComments():
"""
Returns the number of comments to this forum.
"""
class IConversation(Interface):
"""
Conversation contains comments. The number of comments contained in
Conversation is high and increases. It is recommended to use BTree for
indexing and to autogenerate ids for contained comments.
"""
def getForum():
"""
Returns the containing forum.
"""
def addComment(comment_subject, comment_body):
"""
Adds a new comment with subject and body.
"""
def getComment(comment_id):
"""
Returns the comment with the specified id.
"""
def getComments(limit=30, offset=0, **kw):
"""
Retrieves the specified number of comments with offset 'offset'.
In addition there are kw args for sorting and retrieval options.
"""
def getNumberOfComments():
"""
Returns the number of comments to this conversation.
"""
def getLastCommentDate():
"""
Returns a DateTime corresponding to the timestamp of the last comment
for the conversation.
"""
def getLastCommentAuthor():
"""
Returns the author of the last comment for the conversation.
"""
def getLastComment():
"""
Returns the last comment as full object (no Brain).
If there is no such one then None is returned
"""
def getRootComments():
"""
Return a list all comments rooted to the board; ie comments which
are not replies to other comments.
"""
def getFirstComment():
"""
Returns the first (aka root) comment in this IConversation.
"""
class IComment(Interface):
"""
A comment contains regular text body and metadata.
"""
def getConversation():
"""
Returns the containing conversation.
"""
def addReply(comment_subject, comment_body):
"""
Add a response to this comment of same type as object itself.
"""
def inReplyTo():
"""
Returns the comment object this comment is a reply to. If it is the
topmost comment (ie: first comment in a conversation), it returns None.
"""
def getReplies():
"""
Returns the comments that were replies to this one.
"""
def getTitle():
"""
Returns the title of the comment.
"""
def getText():
"""
Returns the text of the comment.
"""
def delete():
"""
Delete this comment. Will ensure to clean up any comments
that were replies to this comment.
"""
class IAttachmentSupport(Interface):
"""
Attachment support, typically for comments
"""
def addAttachment(file, title=None):
"""
Add a file attachment.
"""
def hasAttachment():
"""
Return 0 or 1 if this comment has attachments.
"""
def getNumberOfAllowedAttachments():
"""
Return the number of allowed attachments
"""
def getNumberOfAttachments():
"""
Return the number of attachments
"""
def getAttachments():
"""
Return all attachments
"""
class IPloneboardTool(Interface):
"""Services for Ploneboard: Handles text transformation plugins and attached files.
"""
id = Attribute('id', 'Must be set to "portal_ploneboard"')
def registerTransform(name, module, friendlyName=None):
"""Adds a text transformation module to portal_transforms.
Used from the configuration panel
"""
def unregisterTransform(name):
"""Removes the transformation module from portal_transforms
Used from the configuration panel
"""
def enableTransform(name, enabled=True):
"""Globally enables a transform (site wide)
"""
def unregisterAllTransforms():
"""Removes from portal_transforms all transform modules added with Ploneboard
"""
def getTransforms():
"""Returns list of transform names.
"""
def getTransformFriendlyName(name):
"""Returns a friendly name for the given transform.
"""
def getEnabledTransforms():
"""Returns list of names for enabled transforms.
"""
def performCommentTransform(orig, **kwargs):
"""This performs the comment transform - also used for preview.
"""
def getUploadedFiles():
"""Stores files from request in session and returns these files
"""
def clearUploadedFiles():
"""Removes uploaded files from session machinery
"""
| [
[
8,
0,
0.0072,
0.0108,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0181,
0.0036,
0,
0.66,
0.1429,
443,
0,
2,
0,
0,
443,
0,
0
],
[
3,
0,
0.1047,
0.1625,
0,
0.66... | [
"\"\"\"\n$Id: interfaces.py 55766 2007-12-18 11:08:52Z wichert $\n\"\"\"",
"from zope.interface import Interface, Attribute",
"class IPloneboard(Interface):\n \"\"\"\n Ploneboard is the outmost board object, what shows up in your site.\n The board contains forums. Board is folderish. The number of item... |
from Products.Ploneboard.interfaces import IConversation
from plone.indexer.decorator import indexer
@indexer(IConversation)
def num_comments(obj):
return obj.getNumberOfComments()
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
895,
0,
1,
0,
0,
895,
0,
0
],
[
1,
0,
0.5,
0.1667,
0,
0.66,
0.5,
1,
0,
1,
0,
0,
1,
0,
0
],
[
2,
0,
0.9167,
0.3333,
0,
0.66,
... | [
"from Products.Ploneboard.interfaces import IConversation",
"from plone.indexer.decorator import indexer",
"def num_comments(obj):\n return obj.getNumberOfComments()",
" return obj.getNumberOfComments()"
] |
from Testing import ZopeTestCase
# Make the boring stuff load quietly
ZopeTestCase.installProduct('SimpleAttachment')
ZopeTestCase.installProduct('CMFPlacefulWorkflow')
ZopeTestCase.installProduct('Ploneboard')
from Products.PloneTestCase import PloneTestCase
PloneTestCase.setupPloneSite(products=('SimpleAttachment', 'CMFPlacefulWorkflow', 'Ploneboard'))
class PloneboardTestCase(PloneTestCase.PloneTestCase):
class Session(dict):
def set(self, key, value):
self[key] = value
def _setup(self):
PloneTestCase.PloneTestCase._setup(self)
self.app.REQUEST['SESSION'] = self.Session()
class PloneboardFunctionalTestCase(PloneTestCase.FunctionalTestCase):
class Session(dict):
def set(self, key, value):
self[key] = value
def _setup(self):
PloneTestCase.FunctionalTestCase._setup(self)
self.app.REQUEST['SESSION'] = self.Session()
| [
[
1,
0,
0.0323,
0.0323,
0,
0.66,
0,
740,
0,
1,
0,
0,
740,
0,
0
],
[
8,
0,
0.129,
0.0323,
0,
0.66,
0.1429,
602,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.1613,
0.0323,
0,
0.6... | [
"from Testing import ZopeTestCase",
"ZopeTestCase.installProduct('SimpleAttachment')",
"ZopeTestCase.installProduct('CMFPlacefulWorkflow')",
"ZopeTestCase.installProduct('Ploneboard')",
"from Products.PloneTestCase import PloneTestCase",
"PloneTestCase.setupPloneSite(products=('SimpleAttachment', 'CMFPlac... |
import Products.Five
import Products.ATContentTypes
from Products.CMFPlacefulWorkflow.WorkflowPolicyConfig import manage_addWorkflowPolicyConfig
from DateTime import DateTime
def addMember(self, username, fullname="", email="", roles=('Member',), last_login_time=None):
self.portal.portal_membership.addMember(username, 'secret', roles, [])
member = self.portal.portal_membership.getMemberById(username)
member.setMemberProperties({'fullname': fullname, 'email': email,
'last_login_time': DateTime(last_login_time),})
def setUpDefaultMembersBoardAndForum(self):
addMember(self, 'member1', 'Member one', roles=('Member',))
addMember(self, 'member2', 'Member two', roles=('Member',))
addMember(self, 'manager1', 'Manager one', roles=('Manager',))
addMember(self, 'reviewer1', 'Manager one', roles=('Reviewer',))
self.workflow = self.portal.portal_workflow
self.setRoles(('Manager',))
self.portal.invokeFactory('Ploneboard', 'board1')
self.board = self.portal.board1
self.forum = self.board.addForum('forum1', 'Forum 1', 'Forum one')
self.setRoles(('Member',))
def disableScriptValidators(portal):
from Products.CMFFormController.FormController import ANY_CONTEXT, ANY_BUTTON
scripts = ['add_comment_script', 'add_conversation_script', 'add_forum_script']
try:
for v in portal.portal_skins.ploneboard_scripts.objectValues():
if v.id in scripts:
v.manage_doCustomize('custom')
portal.portal_form_controller.addFormValidators(v.id, ANY_CONTEXT, ANY_BUTTON, [])
except:
pass
def logoutThenLoginAs(self, browser, userid):
browser.open('%s/logout' % self.portal.absolute_url())
browser.open('%s/login_form' % self.portal.absolute_url())
browser.getControl(name='came_from').value = self.portal.absolute_url()
browser.getControl(name='__ac_name').value = userid
browser.getControl(name='__ac_password').value = 'secret'
browser.getControl('Log in').click()
return
def setupEditableForum(self, forum):
self.setRoles(('Manager',))
manage_addWorkflowPolicyConfig(forum)
pw_tool = self.portal.portal_placeful_workflow
config = pw_tool.getWorkflowPolicyConfig(forum)
config.setPolicyIn(policy='EditableComment')
config.setPolicyBelow(policy='EditableComment', update_security=True)
self.setRoles(('Member',))
def lockBoard(self, state):
self.setRoles(('Manager',))
self.workflow.doActionFor(self.board, state)
self.setRoles(('Member',))
| [
[
1,
0,
0.0169,
0.0169,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.0339,
0.0169,
0,
0.66,
0.1111,
189,
0,
1,
0,
0,
189,
0,
0
],
[
1,
0,
0.0508,
0.0169,
0,
... | [
"import Products.Five",
"import Products.ATContentTypes",
"from Products.CMFPlacefulWorkflow.WorkflowPolicyConfig import manage_addWorkflowPolicyConfig",
"from DateTime import DateTime",
"def addMember(self, username, fullname=\"\", email=\"\", roles=('Member',), last_login_time=None):\n self.portal.port... |
#
# Conversation tests
#
import transaction
import unittest
from zope.interface.verify import verifyClass, verifyObject
import PloneboardTestCase
from Products.CMFPlone.utils import _createObjectByType
from Products.Ploneboard.interfaces import IConversation
from Products.Ploneboard.content.PloneboardConversation import PloneboardConversation
from Products.Ploneboard.tests.utils import addMember
class TestPloneboardConversation(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
self.conv = self.forum.addConversation('subject', 'body')
self.comment = self.conv.getComments()[0]
def testInterfaceVerification(self):
self.failUnless(verifyClass(IConversation, PloneboardConversation))
def testInterfaceConformance(self):
self.failUnless(IConversation.providedBy(self.conv))
self.failUnless(verifyObject(IConversation, self.conv))
def testGetForum(self):
self.failUnlessEqual(self.forum, self.conv.getForum())
def testAddComment(self):
msg = self.conv.addComment('msg_title', 'msg_text')
self.assertEqual(msg.getTitle(), 'msg_title')
self.assertEqual(msg.getText(), 'msg_text')
def testGetLastComment(self):
msg = self.conv.addComment('last_comment_title', 'last_comment_text')
self.assertEqual(self.conv.getLastComment().getTitle(), msg.getTitle())
msg2 = self.conv.addComment('last_comment_title2', 'last_comment_text')
self.assertEqual(self.conv.getLastComment().getTitle(), msg2.getTitle())
def testGetComment(self):
conv = self.conv
self.failUnlessEqual(self.comment, conv.getComment(self.comment.getId()))
def testGetComments(self):
conv = self.conv
comment2 = conv.addComment('subject2', 'body2')
self.failUnlessEqual(conv.getComments(), [self.comment, comment2])
def testGetCommentsSlicing(self):
conv = self.conv
comment2 = conv.addComment('subject2', 'body2')
self.failUnlessEqual(conv.getComments(limit=1, offset=0), [self.comment])
self.failUnlessEqual(conv.getComments(limit=1, offset=1), [comment2])
def testGetNumberOfComments(self):
conv = self.conv
self.failUnlessEqual(conv.getNumberOfComments(), 1)
conv.addComment('followup', 'text')
self.failUnlessEqual(conv.getNumberOfComments(), 2)
# Check to make sure it doesn't count comments elsewhere
conv2 = self.forum.addConversation('subject', 'body')
self.failUnlessEqual(conv.getNumberOfComments(), 2)
def testGetLastCommentDate(self):
conv = self.conv
self.failUnlessEqual(self.comment.created(), conv.getLastCommentDate())
comment = conv.addComment('followup', 'text')
self.failUnlessEqual(comment.created(), conv.getLastCommentDate())
def testGetRootComments(self):
conv = self.conv
threaded = conv.getRootComments()
self.failUnlessEqual(len(threaded), 1)
conv.addComment("base2", "base two")
threaded = conv.getRootComments()
self.failUnlessEqual(len(threaded), 2)
reply = self.comment.addReply('anotherfollowup', 'moretext')
threaded = conv.getRootComments()
self.failUnlessEqual(len(threaded), 2)
self.failUnlessEqual(len(self.comment.getReplies()), 1)
def testGetFirstComment(self):
conv = self.conv
first = conv.getFirstComment()
self.failUnless(first)
self.failUnlessEqual(first, conv.objectValues()[0])
conv.addComment('followup', 'text')
self.failUnlessEqual(first, conv.getFirstComment())
def testModificationDate(self):
conv = self.conv
modified1 = conv.modified()
from time import sleep
sleep(0.1) # To make sure modified is different
conv.addComment('followup', 'text')
modified2 = conv.modified()
self.failIfEqual(modified1, modified2)
conv.objectValues()[0].addReply('followup', 'text')
sleep(0.1) # To make sure modified is different
modified3 = conv.modified()
self.failIfEqual(modified1, modified3)
self.failIfEqual(modified2, modified3)
def XXXtest_delObject(self):
forum = self.forum
conv = forum.addConversation('subject', 'body')
msg = conv.addComment('msg_title', 'msg_text')
#msg = conv.objectValues()[0]
r = msg.addReply('reply_subject', 'reply_body')
r1 = msg.addReply('reply_subject1', 'reply_body1')
r2 = msg.addReply('reply_subject2', 'reply_body2')
r2.addReply('rs', 'rb').addReply('rs1', 'rb1').addReply('rs2', 'rb2')
self.assertEqual(conv.getNumberOfComments(), 7)
conv._delObject(r2.getId(), recursive=1)
self.assertEqual(conv.getNumberOfComments(), 3)
# check if we delete conversation so we delete root comment
self.assertEqual(forum.getNumberOfConversations(), 1)
conv._delObject(msg.getId(), recursive=1)
self.assertEqual(forum.getNumberOfConversations(), 0)
# check if Comment was uncataloged
self.failIf(r.getId() in [v.id for v in self.catalog(meta_type='PloneboardComment', id=r.getId())])
self.failIf(msg.getId() in [v.id for v in self.catalog(meta_type='PloneboardComment', id=msg.getId())])
# Checking non recursive delete
conv = forum.addConversation('subject', 'body')
msg = conv.objectValues()[0]
r = msg.addReply('reply_subject', 'reply_body')
self.assertEqual(conv.getNumberOfComments(), 2)
self.failUnless(r.getId() in [v.getId for v in self.catalog(meta_type='PloneboardComment', id=r.getId())])
conv._delObject(msg.getId())
self.assertEqual(conv.getNumberOfComments(), 1)
self.failUnless(r.getId() in [v.getId for v in self.catalog(meta_type='PloneboardComment', id=r.getId())])
def testNewConversationIsVisibleToAnonymous(self):
conv = self.forum.addConversation('subject2', 'body2')
conv.addComment("comment", "comment")
id = conv.getId()
self.logout()
convs = self.forum.getConversations()
# self.failUnless(id in [x.getId() for x in convs])
comments = conv.getComments()
self.assertEqual(len(comments), 2)
def testAddCommentAsAnonymousTakesOwnerOfForumAndCreatorAnonymous(self):
conv = self.conv
self.logout()
reply = conv.addComment('reply1', 'body1', creator='Anonymous')
self.assertEqual(conv.getForum().owner_info()['id'], reply.owner_info()['id'])
self.assertEqual(reply.Creator(), 'Anonymous')
def testAddCommentAsNotAnonymousLeavesOwnershipAlone(self):
conv = self.conv
addMember(self, 'member2')
self.login('member2')
self.assertNotEqual(conv.getForum().owner_info()['id'], 'member2')
reply = conv.addComment('reply1', 'body1')
self.assertEqual(reply.owner_info()['id'], 'member2')
def testDuplicateConversations(self):
conv2 = self.forum.addConversation('subject2', 'body2')
comment = conv2.addComment('subject2', 'body2')
transaction.savepoint(optimistic=True)
cp = self.forum.manage_copyObjects(conv2.getId())
self.failUnlessRaises(ValueError, self.conv.manage_pasteObjects, cp)
def testMergeConversations(self):
conv2 = self.forum.addConversation('subject2', 'body2')
comment = conv2.getComments()[0]
transaction.savepoint(optimistic=True)
self.conv.manage_pasteObjects(self.forum.manage_cutObjects(conv2.getId()))
self.failUnless(comment.getId() in self.conv.objectIds())
self.failUnless(len(self.conv.getComments()) == 2)
self.failIf(conv2.getId() in self.forum.objectIds())
def testMoveCommentToConversation(self):
conv2 = self.forum.addConversation('subject2', 'body2')
comment = conv2.addComment('subject2', 'body2')
transaction.savepoint(optimistic=True)
self.conv.manage_pasteObjects(conv2.manage_cutObjects(comment.getId()))
self.failUnless(comment.getId() in self.conv.objectIds())
self.failUnless(len(self.conv.getComments()) == 2)
self.failUnless(conv2.getId() in self.forum.objectIds()) # We only moved the comment
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPloneboardConversation))
return suite
| [
[
1,
0,
0.0256,
0.0051,
0,
0.66,
0,
502,
0,
1,
0,
0,
502,
0,
0
],
[
1,
0,
0.0308,
0.0051,
0,
0.66,
0.1111,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0359,
0.0051,
0,
0.... | [
"import transaction",
"import unittest",
"from zope.interface.verify import verifyClass, verifyObject",
"import PloneboardTestCase",
"from Products.CMFPlone.utils import _createObjectByType",
"from Products.Ploneboard.interfaces import IConversation",
"from Products.Ploneboard.content.PloneboardConversa... |
#
# Ploneboard tests
#
from Products.Ploneboard.tests import PloneboardTestCase
# Catch errors in Install
from Products.Ploneboard.Extensions import Install
from Products.CMFCore.utils import getToolByName
class TestSetup(PloneboardTestCase.PloneboardTestCase):
def testSkins(self):
portal_skins = self.portal.portal_skins.objectIds()
skins = (
'ploneboard_images',
'ploneboard_scripts',
'ploneboard_templates',
)
for skin in skins:
self.failUnless(skin in skins)
def testPortalTypes(self):
portal_types = self.portal.portal_types.objectIds()
content_types = (
'Ploneboard',
'PloneboardForum',
'PloneboardConversation',
'PloneboardComment',
)
for content_type in content_types:
self.failUnless(content_type in portal_types)
def testTools(self):
from Products.Ploneboard.config import PLONEBOARD_TOOL
tool_names = (
PLONEBOARD_TOOL,
)
for tool_name in tool_names:
self.failUnless(tool_name in self.portal.objectIds())
def testTransforms(self):
from Products.Ploneboard.config import PLONEBOARD_TOOL
tool = getToolByName(self.portal, PLONEBOARD_TOOL)
transforms = [t for t in tool.getEnabledTransforms()]
self.failUnless('safe_html' in transforms)
self.failUnless('text_to_emoticons' in transforms)
self.failUnless('url_to_hyperlink' in transforms)
def testCatalogIndex(self):
ct = getToolByName(self.portal, 'portal_catalog')
self.failUnless('object_provides' in ct.indexes())
self.failUnless('num_comments' in ct.indexes())
self.failUnless('num_comments' in ct.schema())
def testPortalFactorySetup(self):
portal_factory = getToolByName(self.portal, 'portal_factory')
factoryTypes = portal_factory.getFactoryTypes().keys()
for t in ['Ploneboard', 'PloneboardComment', 'PloneboardConversation', 'PloneboardForum']:
self.failUnless(t in factoryTypes)
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
suite.addTest(makeSuite(TestSetup))
return suite
| [
[
1,
0,
0.0746,
0.0149,
0,
0.66,
0,
703,
0,
1,
0,
0,
703,
0,
0
],
[
1,
0,
0.1194,
0.0149,
0,
0.66,
0.25,
138,
0,
1,
0,
0,
138,
0,
0
],
[
1,
0,
0.1493,
0.0149,
0,
0.... | [
"from Products.Ploneboard.tests import PloneboardTestCase",
"from Products.Ploneboard.Extensions import Install",
"from Products.CMFCore.utils import getToolByName",
"class TestSetup(PloneboardTestCase.PloneboardTestCase):\n\n def testSkins(self):\n portal_skins = self.portal.portal_skins.objectIds(... |
"""Ploneboard functional doctests. This module collects all *.txt
files in the tests directory and runs them. (stolen from Plone)
"""
import os, sys
import glob
import doctest
import unittest
from Globals import package_home
from Testing.ZopeTestCase import FunctionalDocFileSuite as Suite
from Products.Ploneboard.config import GLOBALS
# Load products
from Products.Ploneboard.tests.PloneboardTestCase import PloneboardFunctionalTestCase
REQUIRE_TESTBROWSER = ['MemberPostingForum.txt', 'MemberOnlyForum.txt',
'MemberEditsComment.txt', 'AdminLocksBoard.txt',
'FreeForAllForum.txt', 'ModeratedForum.txt']
OPTIONFLAGS = (doctest.REPORT_ONLY_FIRST_FAILURE |
doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE)
def list_doctests():
home = package_home(GLOBALS)
return [filename for filename in
glob.glob(os.path.sep.join([home, 'tests', '*.txt']))]
def list_nontestbrowser_tests():
return [filename for filename in list_doctests()
if os.path.basename(filename) not in REQUIRE_TESTBROWSER]
def test_suite():
# BBB: We can obviously remove this when testbrowser is Plone
# mainstream, read: with Five 1.4.
try:
import Products.Five.testbrowser
except ImportError:
print >> sys.stderr, ("WARNING: testbrowser not found - you probably"
"need to add Five 1.4 to the Products folder. "
"testbrowser tests skipped")
filenames = list_nontestbrowser_tests()
else:
filenames = list_doctests()
return unittest.TestSuite(
[Suite(os.path.basename(filename),
optionflags=OPTIONFLAGS,
package='Products.Ploneboard.tests',
test_class=PloneboardFunctionalTestCase)
for filename in filenames]
)
| [
[
8,
0,
0.0364,
0.0545,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0909,
0.0182,
0,
0.66,
0.0769,
688,
0,
2,
0,
0,
688,
0,
0
],
[
1,
0,
0.1273,
0.0182,
0,
0.66... | [
"\"\"\"Ploneboard functional doctests. This module collects all *.txt\nfiles in the tests directory and runs them. (stolen from Plone)\n\"\"\"",
"import os, sys",
"import glob",
"import doctest",
"import unittest",
"from Globals import package_home",
"from Testing.ZopeTestCase import FunctionalDocFileS... |
#
# Comment tests
#
import unittest
from zope.interface.verify import verifyClass
import PloneboardTestCase
from Products.Ploneboard.interfaces import IComment
from Products.Ploneboard.content.PloneboardComment import PloneboardComment
from Products.Ploneboard.config import HAS_SIMPLEATTACHMENT
from OFS.Image import File
from Products.CMFPlone.utils import _createObjectByType
from Products.Ploneboard.tests.utils import addMember
class TestPloneboardComment(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
self.conv = self.forum.addConversation('conv1', 'conv1 body')
self.comment = self.conv.addComment("comment1", "comment1 body")
def testInterfaceVerification(self):
self.failUnless(verifyClass(IComment, PloneboardComment))
def testGetConversation(self):
self.failUnlessEqual(self.comment.getConversation(), self.conv)
def testAddReply(self):
conv = self.conv
reply = self.comment.addReply('reply1', 'body1')
self.failUnless(reply in conv.objectValues())
def testAddReplyAsAnonymousTakesOwnerOfForumAndCreatorAnonymous(self):
conv = self.conv
self.logout()
reply = self.comment.addReply('reply1', 'body1', creator='Anonymous')
self.assertEqual(conv.getForum().owner_info()['id'], reply.owner_info()['id'])
self.assertEqual(reply.Creator(), 'Anonymous')
def testAddReplyAsNotAnonymousLeavesOwnershipAlone(self):
conv = self.conv
addMember(self, 'member2')
self.login('member2')
self.assertNotEqual(conv.getForum().owner_info()['id'], 'member2')
reply = self.comment.addReply('reply1', 'body1')
self.assertEqual(reply.owner_info()['id'], 'member2')
def testAddReplyAddsRe(self):
conv = self.conv
reply = self.comment.addReply('', 'body1')
self.assertEqual(reply.Title(), 'Re: ' + conv.Title())
def testAddReplyAddsReOnlyOnce(self):
conv = self.conv
reply = self.comment.addReply('', 'body1')
reply2 = reply.addReply('', 'body2')
self.assertEqual(reply2.Title(), 'Re: ' + conv.Title())
def testAddReplyOnlyAddsReIfNotSet(self):
conv = self.conv
reply = self.comment.addReply('reply1', 'body1')
self.assertEqual(reply.Title(), 'reply1')
def testInReplyTo(self):
reply = self.comment.addReply('reply1', 'body1')
self.failUnlessEqual(self.comment, reply.inReplyTo())
def testGetReplies(self):
reply = self.comment.addReply('reply1', 'body1')
reply2 = self.comment.addReply('reply2', 'body2')
self.failUnlessEqual(len(self.comment.getReplies()), 2)
self.failUnless(reply in self.comment.getReplies())
self.failUnless(reply2 in self.comment.getReplies())
def testGetTitle(self):
self.failUnlessEqual(self.comment.getTitle(), 'comment1')
def testGetText(self):
self.failUnlessEqual(self.comment.getText(), 'comment1 body')
def testSetInReplyTo(self):
forum = self.forum
conv = forum.addConversation('subject', 'body')
msg = conv.addComment('msg_subject', 'msg_body')
msg1 = conv.addComment('msg_subject1', 'msg_body1')
msg1.setInReplyTo(msg)
self.assertEqual(msg.getId(), msg1.inReplyTo().getId())
def testDeleteReply(self):
conv = self.conv
m = conv.objectValues()[0]
self.assertEqual(conv.getNumberOfComments(), 2)
r = m.addReply('reply1', 'body1')
self.assertEqual(conv.getNumberOfComments(), 3)
m.deleteReply(r)
self.assertEqual(len(m.getReplies()), 0)
def testMakeBranch(self):
forum = self.forum
conv = self.conv
comment = conv.objectValues()[0]
reply = comment.addReply('reply1', 'body1')
reply1 = reply.addReply('reply2', 'body2')
self.assertEqual(conv.getNumberOfComments(), 4)
self.assertEqual(forum.getNumberOfConversations(), 1)
branch = reply.makeBranch()
self.assertEqual(conv.getNumberOfComments(), 2)
self.assertEqual(forum.getNumberOfConversations(), 2)
self.failIfEqual(branch, conv)
self.assertEqual(branch.getNumberOfComments(), 2)
def testChildIds(self):
conv = self.conv
r = self.comment.addReply('reply_subject', 'reply_body')
r1 = self.comment.addReply('reply_subject1', 'reply_body1')
r2 = self.comment.addReply('reply_subject2', 'reply_body2')
r2.addReply('rs', 'rb').addReply('rs1', 'rb1').addReply('rs2', 'rb2')
self.assertEqual(len(self.comment.childIds()), 6)
def testTransforms(self):
conv = self.conv
text = 'Smiley :)'
self.comment.setText(text)
self.failUnless(self.comment.getText())
self.failIfEqual(self.comment.getText(), text)
self.failUnlessEqual(self.portal.portal_ploneboard.performCommentTransform(text), self.comment.getText())
def XXXtestDeleting(self):
pass
def testNewCommentIsVisibleToAnonymous(self):
comment = self.conv.addComment('subject2', 'body2')
id = comment.getId()
self.logout()
comments = self.conv.getComments()
self.failUnless(id in [x.getId() for x in comments])
def testMemberWithNoFullname(self):
addMember(self, 'membernofullname', fullname='')
self.login('membernofullname')
comment = self.conv.addComment('subject3', 'body3')
commentview = comment.restrictedTraverse('@@singlecomment_view')
self.assertEqual(commentview.author(), 'membernofullname')
def testMemberWithFullname(self):
addMember(self, 'memberwithfullname', fullname='MemberName')
self.login('memberwithfullname')
comment = self.conv.addComment('subject4', 'body4')
commentview = comment.restrictedTraverse('@@singlecomment_view')
self.assertEqual(commentview.author(), 'MemberName')
class TestPloneboardCommentAttachmentSupport(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
self.conv = self.forum.addConversation('conv1', 'conv1 body')
self.comment = self.conv.addComment("comment1", "comment1 body")
def testAddAttachment(self):
conv = self.conv
self.assertEqual(self.comment.getNumberOfAttachments(), 0)
file = File('testfile', 'testtitle', 'asdf')
self.comment.addAttachment(file=file, title='comment')
self.assertEqual(self.comment.getNumberOfAttachments(), 1)
self.failUnless(self.comment.getAttachment('testfile'))
def testHasAttachment(self):
pass
def testRemoveAttachment(self):
conv = self.conv
file = File('testfile', 'testtitle', 'asdf')
self.comment.addAttachment(file=file, title='comment')
self.assertEqual(self.comment.getNumberOfAttachments(), 1)
self.comment.removeAttachment('testfile')
self.assertEqual(self.comment.getNumberOfAttachments(), 0)
def testAttachmentRestrictionChanging(self):
conv = self.conv
self.forum.setMaxAttachments(10)
self.failUnlessEqual(self.comment.getNumberOfAllowedAttachments(), 10)
self.forum.setMaxAttachments(1)
self.failUnlessEqual(self.comment.getNumberOfAllowedAttachments(), 1)
def tryAttachmentSizeRestrictions(self, msg):
self.forum.setMaxAttachments(10)
self.forum.setMaxAttachmentSize(1)
file = File('testfile', 'testtitle', 'X')
msg.addAttachment(file=file, title='comment')
msg.removeAttachment('testfile')
file = File('testfile', 'testtitle', 'X'*2048)
try:
msg.addAttachment(file=file, title='comment')
except ValueError:
pass
else:
self.fail("Can add too many attachments")
self.forum.setMaxAttachmentSize(2)
msg.addAttachment(file=file, title='comment')
def testAttachmentSizeRestriction(self):
conv = self.conv
self.tryAttachmentSizeRestrictions(self.comment)
def testAttachmentSizeRestrictionsOnChild(self):
conv = self.conv
reply = self.comment.addReply('reply1', 'body1')
self.tryAttachmentSizeRestrictions(reply)
def testAttachmentNumberRestriction(self):
conv = self.conv
self.forum.setMaxAttachments(1)
file = File('testfile', 'testtitle', 'asdf')
self.comment.addAttachment(file=file, title='comment')
file = File('testfile2', 'testtitle2', 'asdf')
try:
self.comment.addAttachment(file=file, title='another comment')
except ValueError:
pass
else:
self.fail("Can add too many attachments")
def testGetAttachments(self):
conv = self.conv
self.forum.setMaxAttachments(5)
file = File('testfile', 'testtitle', 'asdf')
self.comment.addAttachment(file=file, title='comment')
file1 = File('testfile1', 'testtitle1', 'asdf')
self.comment.addAttachment(file=file1, title='comment1')
self.assertEqual(len(self.comment.getAttachments()), 2)
self.failUnless('comment' in [v.Title() for v in self.comment.getAttachments()])
self.failUnless('comment1' in [v.Title() for v in self.comment.getAttachments()])
def testDeleteing(self):
"""Test deleting a comment.
"""
# Was going to use doctests for this until I realized that
# PloneTestCase has no doctest capability :(
# - Rocky
# Actually - it does!
# see http://plone.org/documentation/tutorial/testing :)
# - Martin
# Now lets start adding some comments:
first_comment = self.conv.getFirstComment()
c1 = first_comment.addReply('foo1', 'bar1')
c2 = first_comment.addReply('foo2', 'bar2')
c21 = c2.addReply('foo3', 'bar3')
# Make sure the first comment has exactly two replies:
self.assert_(first_comment.getReplies(), [c1, c2])
# Now lets try deleting the first reply to the main comment:
c1.delete()
self.assert_(first_comment.getReplies(), [c2])
# Ok, so lets try deleting a comment that has replies to it:
c2.delete()
# Now even though we deleted the last remaining reply to
# first_comment, we should still have another reply because
# deleting a reply that had a child will make that child seem
# as though it is a reply to its parent's parent.
self.assert_(first_comment.getReplies(), [c21])
# lets add a comment to c21
c211 = c21.addReply('foo4', 'bar4')
# Once the only root comment is deleted that means the conversation's
# sole root comment should become c211
c21.delete()
self.assert_(self.conv.getRootComments(), [c211])
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPloneboardComment))
if HAS_SIMPLEATTACHMENT:
suite.addTest(unittest.makeSuite(TestPloneboardCommentAttachmentSupport))
return suite
| [
[
1,
0,
0.016,
0.0032,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0192,
0.0032,
0,
0.66,
0.0909,
767,
0,
1,
0,
0,
767,
0,
0
],
[
1,
0,
0.0256,
0.0032,
0,
0.6... | [
"import unittest",
"from zope.interface.verify import verifyClass",
"import PloneboardTestCase",
"from Products.Ploneboard.interfaces import IComment",
"from Products.Ploneboard.content.PloneboardComment import PloneboardComment",
"from Products.Ploneboard.config import HAS_SIMPLEATTACHMENT",
"from OFS.... |
#
# Comment tests
#
import unittest
from Products.Ploneboard.tests import PloneboardTestCase
from Products.CMFPlone.utils import _createObjectByType
class TestITextContentAdapter(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
from Products.ATContentTypes.interface import ITextContent
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
self.conv = self.forum.addConversation('conv1', 'conv1 body')
self.comment = self.conv.addComment("c1 title", "c1 body")
self.textContent = ITextContent(self.comment)
def testGetText(self):
self.assertEqual(self.comment.getText(),
self.textContent.getText())
def testSetText(self):
s = 'blah'
self.textContent.setText('blah')
self.assertEqual(self.comment.getText(), s)
self.assertEqual(self.textContent.getText(), s)
def testCookedBody(self):
self.assertEqual(self.textContent.CookedBody(),
self.comment.getText())
def testEditableBody(self):
self.assertEqual(self.textContent.CookedBody(),
self.comment.getRawText())
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestITextContentAdapter))
return suite
| [
[
1,
0,
0.1163,
0.0233,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.1395,
0.0233,
0,
0.66,
0.25,
703,
0,
1,
0,
0,
703,
0,
0
],
[
1,
0,
0.1628,
0.0233,
0,
0.66... | [
"import unittest",
"from Products.Ploneboard.tests import PloneboardTestCase",
"from Products.CMFPlone.utils import _createObjectByType",
"class TestITextContentAdapter(PloneboardTestCase.PloneboardTestCase):\n\n def afterSetUp(self):\n from Products.ATContentTypes.interface import ITextContent \n ... |
#
# Ploneboard tests
#
import unittest
from Products.Ploneboard.tests import PloneboardTestCase
from Products.Ploneboard.batch import Batch
from Products.CMFPlone.utils import _createObjectByType
class TestBatch(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
def batch(self, size=5, start=0, orphan=1):
return Batch(self.forum.getConversations,
self.forum.getNumberOfConversations(),
size, start, orphan=orphan)
def sorted(self, b):
items = [x for x in b]
items.sort(lambda x, y: cmp(x.Title(), y.Title()))
return items
def sbatch(self, size=5, start=0, orphan=1):
b = self.batch(size, start, orphan)
return b, self.sorted(b)
def testEmptyBatch(self):
b = self.batch()
self.assertEqual(len(b), 0)
self.assertEqual(b.next, None)
self.assertEqual(b.previous, None)
def testLessThanOnePage(self):
for i in range(3):
self.forum.addConversation('Title %02s' % i)
b, items = self.sbatch()
self.assertEqual(len(b), 3)
for i in range(3):
self.assertEqual(items[i].Title(), 'Title %02s' % i)
self.assertEqual(b.next, None)
self.assertEqual(b.previous, None)
def testExactlyOnePage(self):
for i in range(5):
self.forum.addConversation('Title %02s' % i)
b, items = self.sbatch()
self.assertEqual(len(b), 5)
for i in range(5):
self.assertEqual(items[i].Title(), 'Title %02s' % i)
self.assertEqual(b.next, None)
self.assertEqual(b.previous, None)
def testOnePagePlusOrphan(self):
for i in range(6):
self.forum.addConversation('Title %02s' % i)
b, items = self.sbatch()
self.assertEqual(len(b), 6)
for i in range(6):
self.assertEqual(items[i].Title(), 'Title %02s' % i)
self.assertEqual(b.next, None)
self.assertEqual(b.previous, None)
# note: when testing more than one page, we don't test for the
# exact objects returned, because getConversations returns things
# sorted by modified date, but when we create objects in a loop like
# below, the resolution of the timestamp isn't good enough, and thus order
# is sometimes unpredictable, leading to non-deterministic tests.
def testOnePagePlusOneMoreThanOrphan(self):
for i in range(7):
self.forum.addConversation('Title %02s' % i)
b = self.batch()
self.assertEqual(b.previous, None)
self.assertNotEqual(b.next, None)
self.assertEqual(len(b.next), 2)
def testGetLastPage(self):
for i in range(8):
self.forum.addConversation('Title %02s' % i)
b = self.batch(start=5)
self.assertEqual(len(b), 3)
self.assertEqual(b.next, None)
self.assertNotEqual(b.previous, None)
self.assertEqual(len(b.previous), 5)
def testGetMiddlePage(self):
for i in range(12):
self.forum.addConversation('Title %02s' % i)
b = self.batch(start=5)
self.assertEqual(len(b), 5)
self.assertNotEqual(b.next, None)
self.assertNotEqual(b.previous, None)
self.assertEqual(len(b.next), 2)
self.assertEqual(len(b.previous), 5)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestBatch))
return suite
| [
[
1,
0,
0.0481,
0.0096,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0577,
0.0096,
0,
0.66,
0.2,
703,
0,
1,
0,
0,
703,
0,
0
],
[
1,
0,
0.0769,
0.0096,
0,
0.66,... | [
"import unittest",
"from Products.Ploneboard.tests import PloneboardTestCase",
"from Products.Ploneboard.batch import Batch",
"from Products.CMFPlone.utils import _createObjectByType",
"class TestBatch(PloneboardTestCase.PloneboardTestCase):\n\n def afterSetUp(self):\n self.board = _createObjectBy... |
#
# Tests the default workflow
#
from AccessControl.Permission import Permission
from Products.CMFPlone.tests import PloneTestCase
from Products.CMFCore.utils import _checkPermission as checkPerm
from Products.CMFPlone.utils import _createObjectByType
from Products.Ploneboard.Extensions import WorkflowScripts # Catch errors
from Products.Ploneboard.tests import PloneboardTestCase
from Products.Ploneboard import permissions
default_user = PloneTestCase.default_user
class TestCommentWorkflow(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.workflow = self.portal.portal_workflow
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
self.conv = self.forum.addConversation('conv1', 'conv1 body')
self.comment = self.conv.addComment("title", "body")
self.portal.acl_users._doAddUser('member', 'secret', ['Member'], [])
self.portal.acl_users._doAddUser('member2', 'secret', ['Member'], [])
self.portal.acl_users._doAddUser('reviewer', 'secret', ['Reviewer'], [])
self.portal.acl_users._doAddUser('manager', 'secret', ['Manager'], [])
# Check allowed transitions
def testAutoPublishMemberposting(self):
self.login('member')
self.failUnless(checkPerm(permissions.ApproveComment, self.forum))
self.failUnless(checkPerm(permissions.ApproveComment, self.conv))
self.failUnless(checkPerm(permissions.ApproveComment, self.comment))
self.assertEqual(self.workflow.getInfoFor(self.forum, 'review_state'), 'memberposting')
self.assertEqual(self.workflow.getInfoFor(self.conv, 'review_state'), 'active')
self.assertEqual(self.workflow.getInfoFor(self.comment, 'review_state'), 'published')
# make_moderated disabled until moderation is fixed in general
# def testAutoSubmitModerated(self):
# self.workflow.doActionFor(self.forum, 'make_moderated')
#
# self.login('member')
#
# conv = self.forum.addConversation('conv2', 'conv2 body')
# comment = conv.objectValues()[0]
#
# self.failIf(checkPerm(permissions.ApproveComment, self.forum))
# self.failIf(checkPerm(permissions.ApproveComment, self.conv))
# self.failIf(checkPerm(permissions.ApproveComment, comment))
#
# self.assertEqual(self.workflow.getInfoFor(self.forum, 'review_state'), 'moderated')
# self.assertEqual(self.workflow.getInfoFor(conv, 'review_state'), 'pending')
# self.assertEqual(self.workflow.getInfoFor(comment, 'review_state'), 'pending')
def testCommentEditing(self):
self.login('manager')
conv = self.forum.addConversation('conv2', 'conv2 body')
self.failUnless(checkPerm(permissions.EditComment, self.comment))
self.logout()
self.login('member2')
self.failIf(checkPerm(permissions.EditComment, self.comment))
class TestWorkflowsCreation(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.workflow = self.portal.portal_workflow
def testWorkflowsCreated(self):
workflows = ['ploneboard_workflow', 'ploneboard_forum_workflow',
'ploneboard_conversation_workflow', 'ploneboard_comment_workflow']
for workflow in workflows:
self.failUnless(workflow in self.workflow.objectIds(), "%s missing" % workflow)
def XXXtestPreserveChainsOnReinstall(self):
# Disable this test: GenericSetup profiles will always overwrite the
# workflow chains for the types
boardtypes = ('Ploneboard',
'PloneboardForum',
'PloneboardConversation',
'PloneboardComment')
self.workflow.setChainForPortalTypes(boardtypes, 'plone_workflow')
self.workflow.getChainForPortalType('Ploneboard')
for boardtype in boardtypes:
self.failUnless('plone_workflow' in self.workflow.getChainForPortalType(boardtype),
'Workflow chain for %s not set' % boardtype)
self.portal.portal_quickinstaller.reinstallProducts(['Ploneboard'])
for boardtype in boardtypes:
chain = self.workflow.getChainForPortalType(boardtype)
self.failUnless('plone_workflow' in chain,
'Overwritten workflow chain for %s: %s' % (boardtype, ', '.join(chain)))
def testPermissionsOnPortal(self):
p=Permission('Ploneboard: Add Comment Attachment', (), self.portal)
roles=p.getRoles()
self.failUnless('Member' in roles)
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
suite.addTest(makeSuite(TestCommentWorkflow))
suite.addTest(makeSuite(TestWorkflowsCreation))
return suite
| [
[
1,
0,
0.0427,
0.0085,
0,
0.66,
0,
745,
0,
1,
0,
0,
745,
0,
0
],
[
1,
0,
0.0513,
0.0085,
0,
0.66,
0.1,
656,
0,
1,
0,
0,
656,
0,
0
],
[
1,
0,
0.0684,
0.0085,
0,
0.6... | [
"from AccessControl.Permission import Permission",
"from Products.CMFPlone.tests import PloneTestCase",
"from Products.CMFCore.utils import _checkPermission as checkPerm",
"from Products.CMFPlone.utils import _createObjectByType",
"from Products.Ploneboard.Extensions import WorkflowScripts # Catch errors",
... |
#
# Event notification tests
#
import unittest
import zope.component
from Products.Ploneboard.tests import PloneboardTestCase
from Products.Archetypes.event import ObjectInitializedEvent
from Products.CMFPlone.utils import _createObjectByType
notified = []
@zope.component.adapter(ObjectInitializedEvent)
def dummyEventHandler(event):
notified.append(event.object)
class TestPloneboardEventNotifications(PloneboardTestCase.PloneboardTestCase):
"""Test the events that should be fired when conversations or comments are added"""
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
zope.component.provideHandler(dummyEventHandler)
def testPloneboardEventNotifications(self):
conv = self.forum.addConversation('subject', 'body')
self.failUnless(conv in notified)
comment = conv.addComment('subject', 'body')
self.failUnless(comment in notified)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPloneboardEventNotifications))
return suite
| [
[
1,
0,
0.1579,
0.0263,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.1842,
0.0263,
0,
0.66,
0.125,
353,
0,
1,
0,
0,
353,
0,
0
],
[
1,
0,
0.2105,
0.0263,
0,
0.6... | [
"import unittest",
"import zope.component",
"from Products.Ploneboard.tests import PloneboardTestCase",
"from Products.Archetypes.event import ObjectInitializedEvent",
"from Products.CMFPlone.utils import _createObjectByType",
"notified = []",
"def dummyEventHandler(event):\n notified.append(event.ob... |
#
# Ploneboard transform tests
#
import unittest
from Products.Ploneboard.tests import PloneboardTestCase
from Products.CMFCore.utils import getToolByName
from Products.Ploneboard.config import PLONEBOARD_TOOL
from Products.CMFPlone.utils import _createObjectByType
class TestTransformRegistration(PloneboardTestCase.PloneboardTestCase):
"""Test transform registration """
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
def testDefaultRegistrations(self):
"""Check if the default registrations are present."""
tool = getToolByName(self.portal, PLONEBOARD_TOOL)
self.failUnlessEqual(len(tool.getTransforms()), 3)
self.failUnlessEqual(len(tool.getEnabledTransforms()), 3)
def testDisabling(self):
"""Try registering and unregistering a transform"""
tool = getToolByName(self.portal, PLONEBOARD_TOOL)
tool.enableTransform('safe_html', enabled=False)
self.failIf('safe_html' in tool.getEnabledTransforms())
tool.enableTransform('safe_html')
self.failUnless('safe_html' in tool.getEnabledTransforms())
def testUnregisteringAllRemovesOnlyThoseAdded(self):
tool = getToolByName(self.portal, PLONEBOARD_TOOL)
tool.unregisterAllTransforms()
transforms = getToolByName(self.portal, 'portal_transforms')
self.failIf('url_to_hyperlink' in transforms.objectIds())
self.failIf('text_to_emoticons' in transforms.objectIds())
self.failUnless('safe_html' in transforms.objectIds())
def testUnregisteringIndividualRemovesOnlyThoseAdded(self):
tool = getToolByName(self.portal, PLONEBOARD_TOOL)
transforms = getToolByName(self.portal, 'portal_transforms')
tool.unregisterTransform('url_to_hyperlink')
self.failIf('url_to_hyperlink' in transforms.objectIds())
tool.unregisterTransform('safe_html')
self.failUnless('safe_html' in transforms.objectIds())
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestTransformRegistration))
return suite
| [
[
1,
0,
0.0943,
0.0189,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.1132,
0.0189,
0,
0.66,
0.1667,
703,
0,
1,
0,
0,
703,
0,
0
],
[
1,
0,
0.1321,
0.0189,
0,
0.... | [
"import unittest",
"from Products.Ploneboard.tests import PloneboardTestCase",
"from Products.CMFCore.utils import getToolByName",
"from Products.Ploneboard.config import PLONEBOARD_TOOL",
"from Products.CMFPlone.utils import _createObjectByType",
"class TestTransformRegistration(PloneboardTestCase.Ploneb... |
"""Ploneboard tests package
"""
| [
[
8,
0,
0.75,
1,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
]
] | [
"\"\"\"Ploneboard tests package\n\"\"\""
] |
#
# Forum tests
#
import unittest
from zExceptions import Unauthorized
from zope.interface.verify import verifyClass, verifyObject
import PloneboardTestCase
from Products.Ploneboard.interfaces import IForum
from Products.Ploneboard.content.PloneboardForum import PloneboardForum
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
class TestPloneboardForum(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board')
self.forum = _createObjectByType('PloneboardForum', self.board, 'forum')
def testInterfaceVerification(self):
self.failUnless(verifyClass(IForum, PloneboardForum))
def testInterfaceConformance(self):
self.failUnless(IForum.providedBy(self.forum))
self.failUnless(verifyObject(IForum, self.forum))
def testForumFields(self):
"""
Check the fields on Forum, especially the Description field mimetypes.
"""
forum = self.forum
self.assertEqual(forum.getId(), 'forum')
forum.setTitle('title')
self.assertEqual(forum.Title(), 'title')
forum.setDescription('description')
self.assertEqual(forum.Description(), 'description')
self.assertEqual(forum.Description(mimetype='text/html'), '<p>description</p>')
def testForumCategory(self):
self.failUnlessEqual(len(self.forum.getCategories()), 0)
self.board.setCategories(['Category'])
self.failUnlessEqual(len(self.forum.getCategories()), 1)
# Interface tests
def testGetBoard(self):
self.failUnlessEqual(self.board, self.forum.getBoard())
def testGetBoardOutsideStrictContainment(self):
forum = _createObjectByType('PloneboardForum', self.folder, 'forum')
self.failUnlessEqual(None, forum.getBoard())
def testAddConversation(self):
"""
Create new folder in home directory & check its basic properties and behaviour
"""
forum = self.forum
conv = forum.addConversation('subject', 'body')
conv_id = conv.getId()
self.failUnless(conv_id in forum.objectIds())
self.assertEqual(conv.Title(), 'subject')
def testGetConversation(self):
forum = self.forum
conv = forum.addConversation('subject', 'body')
self.failUnlessEqual(conv, forum.getConversation(conv.getId()))
def testGetConversationOutsideStrictContainment(self):
# Make a folder inside the forum, then a conversation in the folder
pass
def testRemoveConversation(self):
"""
Create new folder in home directory & check its basic properties and behaviour
"""
forum = self.forum
conv = forum.addConversation('subject', 'body')
conv_id = conv.getId()
forum.removeConversation(conv_id)
self.assertEqual(len(forum.objectIds()), 0)
self.failIf(conv_id in forum.objectIds())
def testGetConversations(self):
forum = self.forum
conv = forum.addConversation('subject', 'body')
conv2 = forum.addConversation('subject2', 'body2')
# Notice reverse ordering, last always first
self.failUnlessEqual(forum.getConversations(), [conv2, conv])
# Check to make sure it doesn't get comments elsewhere
forum2 = _createObjectByType('PloneboardForum', self.board, 'forum2')
forum2.addConversation('subject', 'body')
self.failUnlessEqual(forum.getConversations(), [conv2, conv])
def testGetConversationsWithSlicing(self):
forum = self.forum
conv = forum.addConversation('subject', 'body')
conv2 = forum.addConversation('subject2', 'body2')
self.failUnlessEqual(forum.getConversations(limit=1, offset=0), [conv2])
self.failUnlessEqual(forum.getConversations(limit=1, offset=1), [conv])
def testGetConversationsOutsideStrictContainment(self):
# Make a folder inside the forum, then a conversation in the folder
pass
def testGetNumberOfConversations(self):
forum = self.forum
self.failUnlessEqual(forum.getNumberOfConversations(), 0)
conv = forum.addConversation('subject', 'body')
self.failUnlessEqual(forum.getNumberOfConversations(), 1)
conv2 = forum.addConversation('subject2', 'body2')
self.failUnlessEqual(forum.getNumberOfConversations(), 2)
forum.removeConversation(conv.getId())
self.failUnlessEqual(forum.getNumberOfConversations(), 1)
# Check to make sure it doesn't count conversations elsewhere
forum2 = _createObjectByType('PloneboardForum', self.board, 'forum2')
conv = forum2.addConversation('subject', 'body')
self.failUnlessEqual(forum.getNumberOfConversations(), 1)
def testGetNumberOfComments(self):
forum = self.forum
self.failUnlessEqual(forum.getNumberOfComments(), 0)
conv = forum.addConversation('subject', 'body')
self.failUnlessEqual(forum.getNumberOfComments(), 1)
conv2 = forum.addConversation('subject2', 'body2')
self.failUnlessEqual(forum.getNumberOfComments(), 2)
forum.removeConversation(conv.getId())
self.failUnlessEqual(forum.getNumberOfComments(), 1)
conv2.addComment('followup', 'text')
self.failUnlessEqual(forum.getNumberOfComments(), 2)
# Check to make sure it doesn't count comments elsewhere
forum2 = _createObjectByType('PloneboardForum', self.board, 'forum2')
conv = forum2.addConversation('subject', 'body')
conv.addComment("another", "another")
self.failUnlessEqual(forum.getNumberOfComments(), 2)
class TestPloneboardForumRSSFeed(PloneboardTestCase.PloneboardTestCase):
def afterSetUp(self):
self.board = _createObjectByType('Ploneboard', self.folder, 'board',
title='Test Board')
self.forum=self.board.addForum('forum1', 'Title one', 'Description one')
self.syn_tool = getToolByName(self.portal, 'portal_syndication')
self.view = self.forum.restrictedTraverse("@@RSS")
def testDisblingSyndication(self):
self.assertEqual(self.syn_tool.isSyndicationAllowed(self.forum), True)
self.syn_tool.disableSyndication(self.forum)
self.assertEqual(self.syn_tool.isSyndicationAllowed(self.forum), False)
def testViewNotAllowedWithSyndicationDisabled(self):
self.syn_tool.disableSyndication(self.forum)
self.assertRaises(Unauthorized, self.view.__call__)
def testViewUrl(self):
self.assertEqual(self.view.url(), self.forum.absolute_url())
def testViewDate(self):
self.assertEqual(self.view.date(), self.forum.modified().HTML4())
def testViewTitle(self):
self.assertEqual(self.view.title(), 'Title one')
def testHumbleBeginnings(self):
self.view.update()
self.assertEqual(self.view.comments, [])
def testFirstComment(self):
conv=self.forum.addConversation('Conversation one', 'Text one')
conv.addComment("comment title", "comment body")
self.view.update()
self.assertEqual(len(self.view.comments), 2)
def testCommentInfo(self):
conv=self.forum.addConversation('Conversation one', 'Text one')
conv.addComment("comment title", "comment body")
self.view.update()
comment=self.view.comments[0]
self.assertEqual(comment['title'], 'comment title')
self.assertEqual(comment['description'], 'comment body')
self.assertEqual(comment['author'], 'test_user_1_')
self.failUnless('date' in comment)
self.failUnless('url' in comment)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPloneboardForum))
suite.addTest(unittest.makeSuite(TestPloneboardForumRSSFeed))
return suite
| [
[
1,
0,
0.026,
0.0052,
0,
0.66,
0,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0312,
0.0052,
0,
0.66,
0.1,
550,
0,
1,
0,
0,
550,
0,
0
],
[
1,
0,
0.0365,
0.0052,
0,
0.66,
... | [
"import unittest",
"from zExceptions import Unauthorized",
"from zope.interface.verify import verifyClass, verifyObject",
"import PloneboardTestCase",
"from Products.Ploneboard.interfaces import IForum",
"from Products.Ploneboard.content.PloneboardForum import PloneboardForum",
"from Products.CMFCore.ut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.