code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
PROJECTNAME = "PloneboardNotify" | Python |
from setuptools import setup, find_packages
import os
version = '0.3.0'
setup(name='Products.PloneboardNotify',
version=version,
description="A configurable product that rely on Zope 3 events, for sending emails when new message is added on Ploneboard forum",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Framework :: Plone",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='ploneboard forum event notify',
author='keul',
author_email='luca.fabbri@redturtle.net',
url='http://svn.plone.org/svn/collective/Products.PloneboardNotify',
license='GPL',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['Products'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
#'Products.Ploneboard',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
[distutils.setup_keywords]
paster_plugins = setuptools.dist:assert_string_list
[egg_info.writers]
paster_plugins.txt = setuptools.command.egg_info:write_arg
""",
paster_plugins = ["ZopeSkel"],
)
| Python |
# 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__)
| Python |
from Acquisition import Explicit
from DateTime import DateTime
from Products.CMFCore.utils import getToolByName
from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.interface import implements
from zope.viewlet.interfaces import IViewlet
from zope import component
from zope.i18n import translate
from plonehrm.contracts.content.contract import ContractHourSpread
from plonehrm.contracts import ContractsMessageFactory as _
def compare_dates(a, b):
return cmp(a.getStartdate(), b.getStartdate())
def sort_contracts(contracts):
"""Sort Contracts and Letters.
This is a helper method that is easier to test (and write).
Wanted:
- future contract
- current contract
- second change to current contract
- first change to current contract
- previous contract
- only change to previous contract
Well, the indentation will be done with css or something, but the
above order should be there.
Make mock classes:
>>> class MockContract(object):
... portal_type = 'Contract'
... def __init__(self, date):
... self.date = date
... def getStartdate(self):
... return self.date
... def __repr__(self):
... return '%s from %r' % (self.portal_type, str(self.date))
>>> class MockLetter(MockContract):
... portal_type = 'Letter'
Make sample objects. Most in the past and one in the future:
>>> contract_0 = MockContract(DateTime(1999, 1, 1))
>>> letter_0 = MockLetter(DateTime(1999, 5, 16))
>>> contract_1 = MockContract(DateTime(2001, 1, 1))
>>> letter_1 = MockLetter(DateTime(2001, 5, 16))
>>> contract_2 = MockContract(DateTime(2001, 7, 1))
>>> letter_2a = MockLetter(DateTime(2001, 8, 16))
>>> letter_2b = MockLetter(DateTime(2001, 10, 16))
>>> contract_3 = MockContract(DateTime(2100, 1, 1))
Now some easy tests:
>>> sort_contracts([])
[]
>>> sort_contracts([contract_1])
[Contract from '2001/01/01']
>>> sort_contracts([letter_1])
[Letter from '2001/05/16']
Contracts should be listed newest first.
>>> sort_contracts([contract_3, contract_1, contract_2]) == [contract_3, contract_2, contract_1]
True
Same for letters:
>>> sort_contracts([letter_2a, letter_1, letter_2b]) == [letter_2b, letter_2a, letter_1]
True
A change letter should be listed *after* its contract.
>>> sort_contracts([letter_1, contract_1])
[Contract from '2001/01/01', Letter from '2001/05/16']
>>> sort_contracts([letter_2a, contract_2, letter_2b])
[Contract from '2001/07/01', Letter from '2001/10/16', Letter from '2001/08/16']
Now the middle ones.
>>> contracts = [contract_1, contract_2, letter_1, letter_2a, letter_2b]
>>> sort_contracts(contracts)
[Contract from '2001/07/01', Letter from '2001/10/16', Letter from '2001/08/16', Contract from '2001/01/01', Letter from '2001/05/16']
Add the last one.
>>> contracts.append(contract_3)
>>> sort_contracts(contracts)
[Contract from '2100/01/01', Contract from '2001/07/01', Letter from '2001/10/16', Letter from '2001/08/16', Contract from '2001/01/01', Letter from '2001/05/16']
See if adding Contract zero is for some reason difficult.
>>> sort_contracts(contracts + [contract_0])
[Contract from '2100/01/01', Contract from '2001/07/01', Letter from '2001/10/16', Letter from '2001/08/16', Contract from '2001/01/01', Letter from '2001/05/16', Contract from '1999/01/01']
Check if starting with a Letter adds difficulties (thought doing
so would be strange.
>>> sort_contracts(contracts + [letter_0])
[Contract from '2100/01/01', Contract from '2001/07/01', Letter from '2001/10/16', Letter from '2001/08/16', Contract from '2001/01/01', Letter from '2001/05/16', Letter from '1999/05/16']
"""
contracts.sort(cmp=compare_dates, reverse=True)
sorted = []
changes = []
for con in contracts:
if con.portal_type == 'Contract':
# First add the contract,
sorted.append(con)
# then add the temporary list of change letters,
sorted += changes
# then empty that listit
changes = []
else:
changes.append(con)
# For safety (and testing)
sorted += changes
return sorted
class ContractView(BrowserView):
def first_contract(self):
today = DateTime()
filter = dict(portal_type='Contract')
contracts = self.context.contentValues(filter=filter)
if len(contracts) == 0:
return None
contracts.sort(cmp=compare_dates)
return contracts[0]
def start_employment(self):
contract = self.first_contract()
if contract is not None:
start = contract.getStartdate()
return start
return None
def sum_worktime(self):
start_date = self.context.workStartDate
if start_date is not None:
worktime = start_date
else:
worktime = self.start_employment()
if worktime is not None:
today = DateTime()
expire = self.expires()
if expire is not None and expire < today:
date_to_compare = expire
else:
date_to_compare = today
worktime_year = date_to_compare.year() - worktime.year()
worktime_month = date_to_compare.month() - worktime.month()
if worktime_month < 0:
worktime_month = worktime_month+12
worktime_year = worktime_year-1
return {'year': worktime_year,
'month': worktime_month}
return None
def current_contract(self, includeChangeLetters=True):
"""Return a link to the contract"""
today = DateTime()
# Get a list of contracts with start dates before today.
if includeChangeLetters:
filter=dict(portal_type=('Contract', 'Letter'))
else:
filter=dict(portal_type='Contract')
contracts = self.context.contentValues(filter=filter)
candidates = [(c.getStartdate(), c) for c in contracts
if today > c.getStartdate() > 0]
if len(candidates) > 0:
# sort by date
candidates.sort()
dummy, contract = candidates[-1]
return contract
return None
def expires(self):
"""Return the expiration date of the last contract/letter of
the employee.
"""
contract = self.context.get_last_contract()
if contract is not None:
return contract.expiry_date()
return None
def default_start_date(self):
""" Takes the current contract expiry data and adds one day.
"""
last_contract_expire = self.expires()
if not last_contract_expire:
return
return last_contract_expire + 1
def trial_period_end(self):
"""Return the expiration date of the current contract.
ChangeLetters can have no duration as they cannot change the
duration of the Contract they are changing. So ignore those.
XXX If the current contract almost expires and there already
is a new contract, then we should probably take that date as
expiry date.
"""
contract = self.current_contract(includeChangeLetters=False)
if contract is not None:
start = contract.getStartdate()
trialPeriod = contract.getTrialPeriod()
if start is None or trialPeriod == 0:
return None
year, month, day = start.year(), start.month(), start.day()
year = year + (month + trialPeriod - 1) / 12
month = 1 + (month + trialPeriod - 1) % 12
# Try not to return e.g. 31 February ...
first_of_month = DateTime(year, month, 1)
return first_of_month + day - 1
return None
class ContractViewlet(Explicit, ContractView):
implements(IViewlet)
render = ViewPageTemplateFile('contract.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
# Attribute used to know which kind of view is displayed.
# It can have four values: list, add_contract
# add_letter, settings and endEmployment.
self.view_mode = "list"
def update(self):
pass
def number(self):
"""Return the number of contracts.
"""
cat = getToolByName(self.context, 'portal_catalog')
path = '/'.join(self.context.getPhysicalPath())
brains = cat.searchResults({'portal_type': 'Contract', 'path': path})
if brains:
return len(brains)
def wage(self):
""" Return the wage
"""
if self.current_contract():
return self.current_contract().getWage()
def get_function(self):
""" Return function
"""
if self.current_contract():
return self.current_contract().getFunction()
def add_url(self):
""" Add new contract
"""
# check Add permission on employee
# return None if we don't have permission
mtool = getToolByName(self.context, 'portal_membership')
if mtool.checkPermission('plonehrm: Add contract', self.context):
url = self.context.absolute_url() + '/createObject?type_name=Contract'
return url
def contract_list(self):
return self.context.contentValues(
filter=dict(portal_type=('Contract', 'Letter')))
def sorted_contracts(self):
"""Sort contracts and letters
"""
candidates = sort_contracts(self.contract_list())
results = []
if len(candidates) > 0:
for contract in candidates:
type = contract.portal_type.lower()
if type == 'contract':
title = _(u'contract: ')
else:
title = _(u'letter: ')
title = translate(title,
context=self.request)
title += contract.title
con = dict(contract=contract,
typ=type,
title=title)
results.append(con)
return results
def start_date(self):
""" Returns the date when the employee started working.
"""
return self.context.getWorkStartDate()
def can_create_contract(self):
""" This function checks if templates, functions and employment
types have already been set. It does not check security.
"""
return bool(self.get_templates()) and \
bool(self.get_functions()) and \
bool(self.get_employment_types())
def get_templates(self, type='contract'):
""" Returns the list of available templates.
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
return tool.listTemplates(type)
def get_functions(self):
"""Vocabulary for the functions field
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
return tool.getFunctions()
def get_employment_types(self):
"""Vocabulary for the employmentType field
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
return tool.getEmploymentTypes()
def base_contract(self):
"""Get the current contract of the parent Employee.
"""
view = component.getMultiAdapter((self.context, self.request),
name=u'contracts')
return view.current_contract()
def default_wage(self):
"""Get the wage of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return '0.00'
return base.getWage()
def default_function(self):
"""Get the function of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return ''
return base.getFunction()
def default_hours(self):
"""Get the hours of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return ''
return base.getHours()
def default_employment_type(self):
"""Get the employment type of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return ''
return base.getEmploymentType()
def default_days_per_week(self):
"""Get the days per week of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return 0
return base.getDaysPerWeek()
def default_hour_spread(self):
""" Returns the ContractHourSpread object linked to the contract.
"""
base = self.base_contract()
if base is None or base == self:
return ContractHourSpread()
return base.hour_spread
def is_arbo_manager(self):
""" Checks if the user has arbo manager rights.
"""
membership = getToolByName(self.context, 'portal_membership')
return membership.checkPermission('plonehrm: manage Arbo content',
self.context)
| Python |
from Acquisition import aq_inner
from DateTime import DateTime
from kss.core import kssaction, KSSView
from zope.event import notify
from Products.Archetypes.event import ObjectInitializedEvent
from Products.CMFCore.utils import getToolByName
from zope.i18n import translate
from plonehrm.contracts import ContractsMessageFactory as _
class ContractKssView(KSSView):
""" Class managing KSS actions for the contract viewlet.
"""
def replace_viewlet(self, mode = 'list'):
""" This method refreshes the content of the
contract viewlet.
The 'mode' parameter is used to know which type of view is
used.
"""
# We check that the mode used is a correct one.
if not mode in ['list', 'add_contract', 'add_letter',
'settings', 'endEmployment']:
mode = 'list'
# First, we get the viewlet manager.
view = self.context.restrictedTraverse('@@plonehrm.contracts')
# We configure it.
view.view_mode = mode
# 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('plonehrmContractViewlet')
core.replaceHTML(selector, rendered)
@property
def lang(self):
props = getToolByName(self.context, 'portal_properties')
return props.site_properties.getProperty('default_language')
@kssaction
def show_list(self, hide_status=True):
""" Shows the contract list in the viewlet.
"""
#Hides the previous status message.
if hide_status:
self.getCommandSet('plone').issuePortalMessage('')
self.replace_viewlet('list')
@kssaction
def show_add_letter(self):
""" Shows the add letter form in the viewlet.
"""
self.replace_viewlet('add_letter')
@kssaction
def show_add_contract(self):
""" Shows the add letter form in the viewlet.
"""
self.replace_viewlet('add_contract')
@kssaction
def show_settings(self):
""" Shows the settings form in the viewlet.
"""
self.replace_viewlet('settings')
@kssaction
def show_end_employment(self):
""" Shows the form to end employment.
"""
self.replace_viewlet('endEmployment')
@kssaction
def save_settings(self):
""" Saves the settings for the employee.
The form is not passed as a parameter, we use
kssSubmitForm to send the data.
"""
form = self.request.form
core = self.getCommandSet('core')
field_base = 'contract_settings_start_date'
if form.get(field_base + '_year', '0000') != '0000':
year = int(self.request.get(field_base + '_year'))
month = int(self.request.get(field_base + '_month'))
day = int(self.request.get(field_base + '_day'))
try:
date = DateTime(year, month, day)
except:
selector = core.getHtmlIdSelector(
'contract_viewlet_settings_baddate_error')
core.setAttribute(selector, 'class', 'errormessage')
# Show error status message
message = translate(_(u'msg_error_saving_settings',
u'Errors have been found when saving settings'),
target_language=self.lang)
self.getCommandSet('plone').issuePortalMessage(message,
msgtype='Error')
return
if date and not date.isPast():
# Displays an error message
selector = core.getHtmlIdSelector(
'contract_viewlet_settings_pastdate_error')
core.setAttribute(selector, 'class', 'errormessage')
message = translate(_(u'msg_error_saving_settings',
u'Errors have been found when saving settings'),
target_language=self.lang)
self.getCommandSet('plone').issuePortalMessage(message,
msgtype='Error')
return
else:
date = None
# Save the date and display the contract list again.
self.context.setWorkStartDate(date)
if date is None:
message = ''
else:
message = translate(_(u'msg_settings_savec',
u'Settings have been saved'),
target_language=self.lang)
self.getCommandSet('plone').issuePortalMessage(message)
self.show_list(hide_status=False)
@kssaction
def end_employment(self):
""" Sets date and reason for employment end.
"""
form = self.request.form
core = self.getCommandSet('core')
employee = aq_inner(self.context)
fields = ['end_employment_reason',
'contract_end_employment_date_day',
'contract_end_employment_date_month',
'contract_end_employment_date_year']
for field in fields:
if not field in form:
# Should not happen.
return
# Hide previous errors.
errors = ['contract_viewlet_end_date_invalid_error',
'contract_viewlet_end_date_empty_error']
for error in errors:
selector = core.getHtmlIdSelector(error)
core.setAttribute(selector, 'class', 'dont-show')
# Potential error message.
message = translate(_(u'msg_employee_errors',
u'Errors have been found while terminating employment.'),
target_language=self.lang)
# Check that a date has been set.
if form['contract_end_employment_date_day'] == '00':
selector = core.getHtmlIdSelector(
'contract_viewlet_end_date_empty_error')
core.setAttribute(selector, 'class', 'errormessage')
self.getCommandSet('plone').issuePortalMessage(message,
msgtype='Error')
return
# Check that the date is correct.
try:
date = DateTime(int(form['contract_end_employment_date_year']),
int(form['contract_end_employment_date_month']),
int(form['contract_end_employment_date_day']))
except:
selector = core.getHtmlIdSelector(
'contract_viewlet_end_date_invalid_error')
core.setAttribute(selector, 'class', 'errormessage')
self.getCommandSet('plone').issuePortalMessage(message,
msgtype='Error')
return
# Set end date/reason
employee.setEndEmploymentDate(date)
employee.setEndEmploymentReason(form['end_employment_reason'])
# Change employee workflow.
try:
workflowTool = getToolByName(employee, "portal_workflow")
workflowTool.doActionFor(employee, "deactivate")
except:
# The employment was already terminated.
pass
# Show the success message.
message = translate(_(u'msg_employee_ended',
u'Employment has been terminated.'),
target_language=self.lang)
self.getCommandSet('plone').issuePortalMessage(message)
# Refresh the viewlet.
self.show_list(hide_status=False)
# Refresh the checklist viewlet.
view = self.context.restrictedTraverse('@@plonehrm.checklist')
# We configure it.
view.view_mode = 'list'
view.editedItem = None
# 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('checklist')
core.replaceHTML(selector, rendered)
def _validate_field(self, value, errormsg, type='int', errors = []):
""" This method tries to cast value into the asked type.
If casting is not possible, the error message is appended into
the errors list.
"""
if value:
try:
if type == 'int':
int(value)
elif type == 'float':
tmp = '.'.join(value.split(','))
float(tmp)
except ValueError:
errors.append(errormsg)
@kssaction
def add_contract(self):
""" Method called when a new contract is added.
"""
self.add_contract_or_letter()
@kssaction
def add_letter(self):
""" Method called when a new letter is added.
"""
self.add_contract_or_letter(False)
def add_contract_or_letter(self, is_contract = True):
""" Action called when a contract/letter is saved.
"""
form = self.request.form
core = self.getCommandSet('core')
field_base = 'contract_form_'
title = form.get(field_base + 'title')
template = form.get(field_base + 'template')
wage = form.get(field_base + 'wage')
year = form.get(field_base + 'startdate_year')
month = form.get(field_base + 'startdate_month')
day = form.get(field_base + 'startdate_day')
function = form.get(field_base + 'function')
duration = form.get(field_base + 'duration')
trial_period = form.get(field_base + 'trial_period')
employment_type = form.get(field_base + 'employment_type')
number_hours = form.get(field_base + 'number_hours')
workdays = form.get(field_base + 'workdays')
# Before displaying any error, we clean the previous ones.
for errorMsg in ['contract_viewlet_no_template',
'contract_viewlet_wage_no_float',
'contract_viewlet_invalid_date',
'contract_viewlet_duration_no_integer',
'contract_viewlet_hours_no_integer',
'contract_viewlet_workdays_no_integer',
'contract_viewlet_incorrect_workdays',
'contract_viewlet_spread_to_high',
'contract_viewlet_more_than_24',
'contract_viewlet_invalid_hour_spread']:
selector = core.getHtmlIdSelector(errorMsg)
core.setAttribute(selector, 'class', 'dont-show')
errors = []
if template == '':
errors.append('contract_viewlet_no_template')
self._validate_field(wage, 'contract_viewlet_wage_no_float',
'float', errors)
if form.get(field_base + 'startdate_year', '0000') != '0000':
try:
date = DateTime(int(year), int(month), int(day))
except:
errors.append('contract_viewlet_invalid_date')
date = None
else:
date = None
self._validate_field(
duration, 'contract_viewlet_duration_no_integer',
'int', errors)
if is_contract:
# This field is not present in
# the letter form.
# We do not raise any error as this case should not append,
# the only values possible for this field are 0, 1 or 2.
self._validate_field(trial_period, '', 'int', errors)
self._validate_field(number_hours, 'contract_viewlet_hours_no_integer',
'int', errors)
if not number_hours:
number_hours = 0
try:
tmp = int(workdays)
if tmp < 1 or tmp > 7:
errors.append('contract_viewlet_incorrect_workdays')
except:
if workdays:
errors.append('contract_viewlet_workdays_no_integer')
# We check that number of hours specified is correct.
if 'contract_form_working_schedule' in form:
total = 0
if form['contract_form_working_schedule'] == 'manual':
rows = ['odd']
elif form['contract_form_working_schedule'] == 'manual_oddeven':
rows = ['odd', 'even']
else:
rows = []
for row in rows:
for day in range(0, 7):
field = 'schedule_' + row + '_' + str(day)
if field in form:
try:
field_value = float(form[field])
except ValueError:
errors.append(
'contract_viewlet_invalid_hour_spread')
total += field_value
if field_value > 24:
errors.append('contract_viewlet_more_than_24')
if rows:
total = total / len(rows)
if total > int(number_hours):
errors.append('contract_viewlet_spread_to_high')
# We display the error messages.
for errorMsg in errors:
selector = core.getHtmlIdSelector(errorMsg)
core.setAttribute(selector, 'class', 'errormessage')
if len(errors) > 0:
if is_contract:
message = translate(_(u'msg_error_contract',
u'Errors were found while creating the contract'),
target_language=self.lang)
else:
message = translate(_(u'msg_error_letter',
u'Errors were found while creating the letter'),
target_language=self.lang)
self.getCommandSet('plone').issuePortalMessage(message,
msgtype='Error')
return
# If no error has been found, we create the contract and display
# the contract list.
if is_contract:
new_id = self.context.generateUniqueId('Contract')
self.context.invokeFactory("Contract", id=new_id,
title='contract_tmp')
else:
new_id = self.context.generateUniqueId('Letter')
self.context.invokeFactory("Letter", id=new_id,
title='letter_tmp')
contract = getattr(self.context, new_id)
contract.setTitle(title)
contract.setTemplate(template)
contract.setWage(wage)
contract.setFunction(function)
contract.setEmploymentType(employment_type)
contract.setHours(number_hours)
contract.setDaysPerWeek(workdays)
contract.setStartdate(date)
contract.setDuration(duration)
if is_contract:
contract.setTrialPeriod(trial_period)
contract.unmarkCreationFlag()
contract._renameAfterCreation()
notify(ObjectInitializedEvent(contract))
# Adds informations for hours spread.
if 'contract_form_working_schedule' in form:
contract.hour_spread.update_from_form(form)
# Shows status message
if is_contract:
message = translate(_(u'msg_contract_added',
u'Contract added'),
target_language=self.lang)
else:
message = translate(_(u'msg_letter_added',
u'Letter added'),
target_language=self.lang)
self.getCommandSet('plone').issuePortalMessage(message)
self.show_list(hide_status=False)
@kssaction
def change_schedule_table(self, value):
""" Show or hide the schedule table.
"""
if value == 'auto':
css = 'dont-show'
elif value in ['manual', 'manual_oddeven']:
css = 'listing'
else:
return
core = self.getCommandSet('core')
selector = core.getHtmlIdSelector('contract_viewlet_manual_schedule')
core.setAttribute(selector, 'class', css)
if not value == 'auto':
if value == 'manual':
css = 'dont-show'
first_row = _(u'label_normal', u'normal')
else:
css = ''
first_row = _(u'label_odd', u'odd')
# We hide the second row which is useless.
selector = core.getHtmlIdSelector(
'contract_viewlet_manual_schedule_even')
core.setAttribute(selector, 'class', css)
selector = core.getHtmlIdSelector(
'contract_viewlet_manual_schedule_odd_first_row')
core.replaceInnerHTML(selector,
translate(first_row,
target_language=self.lang))
| Python |
from zope.interface import Interface
class IContractView(Interface):
"""Provide a view for an Employee specifically for Contracts.
"""
def current_contract():
"""Return a link to the contract"""
def expires():
"""Return the expiration date of the current contract."""
def trial_period_end():
"""Return the end of the trial period of the current contract."""
class IContractViewlet(Interface):
def current_contract():
"""Return a link to the contract"""
def expires():
"""Return the expiration date of the current contract."""
def number():
"""Return the number of contracts.
"""
def wage():
""" Return the wage
"""
def get_function():
""" Return function
"""
def add_url():
""" Add new contract
"""
def contract_list():
"""Return a list of contracts"""
def sorted_contracts():
"""Return a sorted list of contracts and letters"""
| Python |
# python package
| Python |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from AccessControl import ClassSecurityInfo
from Acquisition import aq_chain, aq_inner
from DateTime import DateTime
from Products.Archetypes.utils import IntDisplayList
from Products.Archetypes.interfaces import IBaseContent
from Products.Archetypes.atapi import BaseContent
from Products.Archetypes.atapi import BaseSchema
from Products.Archetypes.atapi import CalendarWidget
from Products.Archetypes.atapi import DateTimeField
from Products.Archetypes.atapi import DecimalWidget
from Products.Archetypes.atapi import IntegerWidget
from Products.Archetypes.atapi import DisplayList
from Products.Archetypes.atapi import FixedPointField
from Products.Archetypes.atapi import IntegerField
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import SelectionWidget
from Products.Archetypes.atapi import StringField
from Products.Archetypes.atapi import TextField
from Products.Archetypes.atapi import RichWidget
from Products.Archetypes.atapi import registerType
from Products.CMFCore.utils import getToolByName
from Products.plonehrm.interfaces import IEmployee
from zope import component
from zope.interface import implements
from zope.annotation.interfaces import IAnnotations
from persistent.list import PersistentList
from persistent.dict import PersistentDict
from persistent import Persistent
from plonehrm.contracts import config
from plonehrm.contracts.interfaces import IContract
from plonehrm.contracts import ContractsMessageFactory as _
schema = Schema((
StringField(name='template',
required=1,
vocabulary='_templates',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
widget=SelectionWidget(
format='select',
condition='not:object/template_chosen',
label=_(u'contract_label_template', default=u'Template'),
),
),
FixedPointField(
name='wage',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
validators = ('isCurrency', ),
default_method='default_wage',
widget=DecimalWidget(
condition='not:object/template_chosen',
label=_(u'contract_label_wage', default=u'Wage'),
)
),
StringField(
name='function',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
default_method='default_function',
widget=SelectionWidget(
format='select',
condition='not:object/template_chosen',
label=_(u'contract_label_function', default=u'Function'),
),
vocabulary='_available_functions'
),
DateTimeField(
name='startdate',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
widget=CalendarWidget(
condition='not:object/template_chosen',
show_hm=0,
label=_(u'contract_label_startdate', default=u'Start date'),
)
),
IntegerField(
name='duration',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
widget=IntegerWidget(
condition='not:object/template_chosen',
label=_(u'contract_label_duration', default=u'Duration (months)'),
)
),
IntegerField(
name='trialPeriod',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
default=0,
widget=SelectionWidget(
format='select',
condition='not:object/template_chosen',
label=_(u'contract_label_trial_period',
default=u'Trial period (months)'),
),
vocabulary='_trial_period_vocabulary',
),
StringField(
name='employmentType',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
default_method='default_employment_type',
widget=SelectionWidget(
condition='not:object/template_chosen',
format='select',
label=_(u'contract_label_employmentType',
default=u'Type of employment'),
),
vocabulary='_available_employment_types'
),
IntegerField(
name='hours',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
default_method='default_hours',
widget=IntegerWidget(
condition='not:object/template_chosen',
label=_(u'contract_label_hours', default=u'Number of hours'),
)
),
IntegerField(
name='daysPerWeek',
read_permission='plonehrm: View hrm content',
write_permission='plonehrm: Modify contract',
default_method='default_days_per_week',
validators = ('maxDaysPerWeek', ),
widget=IntegerWidget(
condition='not:object/template_chosen',
label=_(u'contract_label_days_per_week',
default=u'Number of workdays per week'),
)
),
TextField(name='text',
required=False,
seachable=False,
primary=True,
default_output_type = 'text/x-html-safe',
widget = RichWidget(
description = '',
label = _(u'label_body_text', default=u'Body Text'),
rows = 25,
visible = {'view': 'visible', 'edit': 'invisible'},
condition='object/template_chosen',
),
)
),
)
Contract_schema = BaseSchema.copy() + schema.copy()
# We take the title of the chosen template usually, but this can be
# overridden by specifically filling in a title. But at least the
# title is now not required:
Contract_schema['title'].required = False
Contract_schema['title'].widget.visible = {'view': 'visible',
'edit': 'invisible'}
class ContractHourSpread(Persistent):
def __init__(self):
# Mode can be manual, manual_oddeven or auto.
self.mode = 'auto'
# Number of hours worked by week.
self.total_hours = 0
# Stores the number of hours per day.
# Each cell is referenced as week_type + '_' + day number.
# For example, 'even_0' defines number of hours worked on
# monday of even weeks. 'odd_3' defines number of jours
# worked on thurday for odd weeks.
self.hours = {}
for week in ['odd', 'even']:
for day in range(0, 7):
self.hours[week + '_' + str(day)] = 0
def update_from_form(self, form):
""" Takes the form submitted with the contract viewlet and
updates data.
This method does not raise any error has the form should have been
checked previously by the KSS action called when submitting
the form.
If problems are found, this method dies silently.
"""
def quarter_round(f):
""" Takes a float and returns it rounded to the quarter
x.0, x.25, x.50, x.75
"""
int_part = int(f)
float_part = f - int_part
for i in range(0, 5):
if float_part > (0.25 * (i - 1)) and float_part < (0.25 * i):
float_part = i and 0.25 * (i - 1) or 0.0
break
return int_part + float_part
# First, we check that all necessary fields are here.
fields = ['contract_form_workdays',
'contract_form_number_hours',
'contract_form_working_schedule']
for week in ['odd', 'even']:
for day in range(0, 7):
fields. append('schedule_' + week + '_' + str(day))
for field in fields:
if not field in form:
# Should not happen.
return
if not form[field]:
form[field] = 0
self.mode = form['contract_form_working_schedule']
try:
hours = float(form['contract_form_number_hours'])
workdays = int(form['contract_form_workdays'])
except:
# Should not happen.
return
if self.mode == 'auto':
for week in ['odd', 'even']:
for day in range(0, workdays):
self.hours[week + '_' + str(day)] = \
quarter_round(hours / workdays)
elif self.mode == 'manual':
for day in range(0, 7):
self.hours['odd_' + str(day)] = float(form['schedule_odd_' + \
str(day)])
self.hours['even_' + str(day)] = float(form['schedule_odd_' + \
str(day)])
elif self.mode == 'manual_oddeven':
for day in range(0, 7):
self.hours['odd_' + str(day)] = float(form['schedule_odd_' + \
str(day)])
self.hours['even_' + str(day)] = float(form['schedule_even_' + \
str(day)])
def get_value_from_field(self, field):
key = field.split('schedule_')[-1]
if key in self.hours:
return self.hours[key]
class Contract(BaseContent):
"""
"""
security = ClassSecurityInfo()
__implements__ = (BaseContent.__implements__, )
implements(IBaseContent, IContract)
_at_rename_after_creation = True
schema = Contract_schema
def getWage(self):
"""Override the default getting to return a comma in some cases.
We just look at the default language and check if it is in a
list of languages that we know use commas in their currencies.
"""
wage = self.getField('wage').get(self)
language_tool = getToolByName(self, 'portal_languages')
if language_tool:
language = language_tool.getDefaultLanguage()
else:
language = 'en'
if language in ('nl', 'de', 'fr'):
wage = wage.replace('.', ',')
return wage
security.declarePrivate('_templates')
def _templates(self):
"""Vocabulary for the template field
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
items = [(item.id, item.Title()) for item
in tool.listTemplates('contract')]
return DisplayList(items)
security.declarePublic('template_chosen')
def template_chosen(self):
"""Determine if the template (a string) has been chosen yet.
"""
return len(self.getTemplate()) > 0
security.declarePrivate('_available_functions')
def _available_functions(self):
"""Vocabulary for the functions field
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
return tool.getFunctions()
security.declarePrivate('_available_employment_types')
def _available_employment_types(self):
"""Vocabulary for the employmentType field
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
return tool.getEmploymentTypes()
security.declarePrivate('_trial_period_vocabulary')
def _trial_period_vocabulary(self):
"""Vocabulary for the trialPeriod field
"""
return IntDisplayList([(0, '0'), (1, '1'), (2, '2')])
def get_employee(self):
"""Get the employee that this contract 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.
"""
for parent in aq_chain(aq_inner(self)):
if IEmployee.providedBy(parent):
return parent
def base_contract(self):
"""Get the current contract of the parent Employee.
"""
parent = self.get_employee()
if parent is None:
return
# XXX: Remove view lookup
# A content class should not need to be aware of the request in
# order to preserve separation of concerns. The subsitution
# mechanism here should be replaced with a component that doesn't
# know or care about the request - Rocky
view = component.getMultiAdapter((parent, self.REQUEST),
name=u'contracts')
return view.current_contract()
def default_wage(self):
"""Get the wage of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return '0.00'
return base.getWage()
def default_function(self):
"""Get the function of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return ''
return base.getFunction()
def default_hours(self):
"""Get the hours of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return ''
return base.getHours()
def default_employment_type(self):
"""Get the employment type of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return ''
return base.getEmploymentType()
def default_days_per_week(self):
"""Get the days per week of the parent Employee.
"""
base = self.base_contract()
if base is None or base == self:
return 0
return base.getDaysPerWeek()
def expiry_date(self):
"""Expiry date of this contract.
Basically start date + duration. But e.g. a contract of one
month starting at 31 January should end at 28 (or 29) February.
Will return None if start date or duration is not known.
"""
start = self.getStartdate()
duration = self.getDuration()
if start is None or duration is None:
return None
year, month, day = start.year(), start.month(), start.day()
year = year + (month + duration - 1) / 12
month = 1 + (month + duration - 1) % 12
first_of_month = DateTime(year, month, 1)
date = first_of_month + day - 1
# 31 January + 31 days is 3 March, so count backwards in that
# case. Watch out for infinite loops here...
safety_count = 5
while date.month() != month and safety_count > 0:
safety_count -= 1
date -= 1
if not safety_count:
return None
return date - 1
security.declarePublic('hour_spread')
@property
def hour_spread(self):
""" Returns the object ContractHourSpread linked to the contract.
If the object do not exist yet, then it is created.
"""
annotations = IAnnotations(self)
ANNO_KEY = 'plonehrm.contract'
metadata = annotations.get(ANNO_KEY, None)
if metadata is None:
annotations[ANNO_KEY] = PersistentDict()
metadata = annotations[ANNO_KEY]
if not 'hour_spread' in metadata:
metadata['hour_spread'] = ContractHourSpread()
return metadata['hour_spread']
def getHoursPerWeek(self):
""" Returns the number of hours worked each week.
"""
# Check if the user has Arbo rights.
membership = getToolByName(self, 'portal_membership')
is_arbo = membership.checkPermission('plonehrm: manage Arbo content',
self)
if not is_arbo:
return self.getHours()
odd_weeks = 0
even_weeks = 0
for hour in self.hour_spread.hours:
if hour.startswith('odd'):
odd_weeks += float(self.hour_spread.hours[hour])
else:
even_weeks += float(self.hour_spread.hours[hour])
if odd_weeks == even_weeks:
return str(int(odd_weeks))
else:
return str(int(odd_weeks)) + '/' + str(int(even_weeks))
def is_contract(self):
return True
registerType(Contract, config.PROJECTNAME)
| Python |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from Acquisition import aq_parent, aq_chain
from Products.Archetypes.atapi import registerType
from zope import component
from zope.interface import implements
from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import DisplayList
from Products.CMFCore.utils import getToolByName
from plonehrm.contracts import config
from plonehrm.contracts.content.contract import Contract
from plonehrm.contracts.content.contract import Contract_schema
from plonehrm.contracts.interfaces import ILetter
Letter_schema = Contract_schema.copy()
Letter_schema['trialPeriod'].widget.visible={'view':'visible', 'edit':'invisible'}
class Letter(Contract):
"""Letter for change of contract
"""
security = ClassSecurityInfo()
__implements__ = (getattr(Contract,'__implements__',()),)
implements(ILetter)
_at_rename_after_creation = True
schema = Letter_schema
security.declarePrivate('_templates')
def _templates(self):
"""Vocabulary for the template field
"""
tool = getToolByName(self, 'portal_contracts', None)
if tool is None:
return []
else:
items = [(item.id, item.Title()) for item
in tool.listTemplates('letter')]
return DisplayList(items)
def is_contract(self):
return False
registerType(Letter, config.PROJECTNAME)
| Python |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
# # Classes
import contract
import letter
| Python |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
from AccessControl import ClassSecurityInfo
from Acquisition import aq_inner, aq_parent
from Products.Archetypes.atapi import BaseFolder
from Products.Archetypes.atapi import BaseFolderSchema
from Products.Archetypes.atapi import LinesField
from Products.Archetypes.atapi import Schema
from Products.Archetypes.atapi import registerType
from Products.CMFCore.utils import ImmutableId
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.permissions import ModifyPortalContent
from zope.i18n import translate
from zope.interface import implements
from plonehrm.contracts import config
from plonehrm.contracts.interfaces import IContractTool
from plonehrm.contracts import ContractsMessageFactory as _
schema = Schema((
LinesField(
name='functions',
widget=LinesField._properties['widget'](
label=_(u'contract_label_functions', default=u'Positions'),
)
),
LinesField(
name='employmentTypes',
widget=LinesField._properties['widget'](
label=_(u'contract_label_employmentTypes',
default=u'Types of employment'),
)
),
),
)
ContractTool_schema = BaseFolderSchema.copy() + schema.copy()
class ContractTool(ImmutableId, BaseFolder):
"""Contract tool.
>>> from plonehrm.contracts.content.tool import ContractTool
>>> tool = ContractTool()
>>> tool.Title()
'Contract templates'
>>> tool.at_post_edit_script()
"""
id = 'portal_contracts'
security = ClassSecurityInfo()
__implements__ = (BaseFolder.__implements__, )
implements(IContractTool)
typeDescription = "ContractTool"
typeDescMsgId = 'description_edit_contracttool'
schema = ContractTool_schema
def __init__(self, *args, **kwargs):
self.setTitle(translate(_(u'title_portal_contracts',
default=u'Contract templates')))
def listTemplates(self, type=None):
"""List the templates in this tool.
Optionally list the templates from a higher level
portal_contracts tool as well. This is done by trying to call
getUseHigherLevelTemplates on the current tool. This method
is not available by default, but can be implemented by third
party products. Default is False. If you always want this to
be True, add a python script getUseHigherLevelTool in the
portal_skins/custom folder that just returns True.
We return full objects; returning just ids will fail as we
then have no way of knowing in which portal_contracts that
template id is.
When specifying the parameter 'type' we return only templates
of that type (presumably 'contract' or 'letter'), otherwise we
return all.
"""
templates = self.contentValues()
try:
recursive = self.getUseHigherLevelTool()
except AttributeError:
recursive = False
if recursive:
# Get our grand parent and ask him for a portal_contracts
# tool. Note that if we ask our parent, then a
# getToolByName will return ourselves, which is not what
# we want.
grand_parent = aq_parent(aq_parent(aq_inner(self)))
higher_tool = getToolByName(grand_parent, self.id, None)
if higher_tool is not None:
templates += higher_tool.listTemplates()
# We filter the templates to keep only contract/letter templates.
filtered = []
for template in templates:
try:
template_type = template.getType()
except:
# An old template stays in the contract tool.
continue
if type is None or template_type == type:
filtered.append(template)
return filtered
security.declareProtected(ModifyPortalContent, 'indexObject')
def indexObject(self):
pass
security.declareProtected(ModifyPortalContent, 'reindexObject')
def reindexObject(self, idxs=[]):
pass
security.declareProtected(ModifyPortalContent, 'reindexObjectSecurity')
def reindexObjectSecurity(self, skip_self=False):
pass
registerType(ContractTool, config.PROJECTNAME)
| Python |
from Products.CMFCore.utils import getToolByName
def setup(context):
# This is the main method that gets called by genericsetup.
if context.readDataFile('plonehrm.contracts.txt') is None:
return
site = context.getSite()
logger = context.getLogger('plonehrm')
add_currency_property(site, logger)
def add_currency_property(site, logger):
"""Add a currency property to portal_properties.plonehrm_properties.
We do that in python code instead of in propertiestool.xml to
avoid overwriting changes by the user.
Plus: there was a problem importing a string property with
'€' as value:
ExpatError: /test/portal_properties: undefined entity: line 7, column 42
"""
portal_props = getToolByName(site, 'portal_properties')
props = portal_props.plonehrm_properties
propname = 'currency'
if not props.hasProperty(propname):
value = '€'
props._setProperty(propname, value, 'string')
logger.info('Added property %r with default value %r',
propname, value)
| Python |
from zope.interface import Interface
class IContract(Interface):
def getId():
""" """
def setId():
""" """
def Title():
""" """
def Description():
""" """
def setDescription():
""" """
def getWage():
"""return the current wage"""
def setWage():
"""set the current wage"""
def getFunction():
"""Returns the function"""
def setFunction():
"""Set the function"""
def getDuration():
""" """
def setDuration():
""" """
def getEmploymentType():
""" """
def setEmploymentType():
""" """
def getHoures():
""" """
def setHours():
""" """
def getDaysPerWeek():
""" """
def setDaysPerWeek():
""" """
def getTemplate():
""" """
def setTemplate():
""" """
class ILetter(IContract):
"""An official letter"""
class IContractTool(Interface):
"""Tool to manage templates, positions, and contract types."""
| Python |
import logging
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Acquisition import aq_parent
from Products.plonehrm import utils
from Products.plonehrm.controlpanel import IHRMNotificationsPanelSchema
from plonehrm.contracts import ContractsMessageFactory as _
from plonehrm.contracts.notifications.events import ContractEndingEvent
from plonehrm.contracts.notifications.events import TrialPeriodEndingEvent
from plonehrm.notifications.emailer import HRMEmailer
from plonehrm.notifications.interfaces import INotified
from plonehrm.notifications.utils import get_employees_for_checking
from zope.event import notify
logger = logging.getLogger("plonehrm.contracts:")
EXPIRY_NOTIFICATION = u"plonehrm.contracts: Expiry notification"
TRIAL_PERIOD_ENDING_NOTIFICATION = u"plonehrm.contracts: Trial period ending"
def contract_ending_checker(object, event):
"""Check if the last contract of employees is almost ending.
object is likely the portal, but try not to depend on that.
"""
portal = getToolByName(object, 'portal_url').getPortalObject()
panel = IHRMNotificationsPanelSchema(object)
if not panel.contract_expiry_notification:
logger.info("Contract ending notification is switched off.")
return
days_warning = panel.contract_expiry_notification_period
employees = get_employees_for_checking(object)
for brain in employees:
try:
employee = brain.getObject()
except (AttributeError, KeyError):
logger.warn("Error getting object at %s", brain.getURL())
continue
last_contract = employee.get_last_contract()
info = dict(employee_name = employee.officialName(),
employee_url = employee.absolute_url())
if last_contract is None:
#email = HRMEmailer(employee)
#email.template = ZopeTwoPageTemplateFile('no_current_contract.pt')
#email.send()
#notify(NoContractEvent(employee))
continue
expires = last_contract.expiry_date()
if expires is None:
continue
now = DateTime()
if now + days_warning >= expires:
# Check if we have already warned about this.
notified = INotified(last_contract)
if notified.has_notification(EXPIRY_NOTIFICATION):
continue
info['days'] = days_warning
options = dict(days=days_warning)
worklocation = aq_parent(employee)
if worklocation.getCreateLetterWhenExpiry():
options['new_type'] = 'Letter'
else:
options['new_type'] = 'Contract'
template = ZopeTwoPageTemplateFile('contract_nears_ending.pt')
addresses = utils.email_adresses_of_local_managers(employee)
recipients = (addresses['worklocation_managers'] +
addresses['hrm_managers'])
email = HRMEmailer(employee,
template=template,
options=options,
recipients=recipients,
subject=_(u'A contract nears ending'))
email.send()
notify(ContractEndingEvent(employee))
notified.add_notification(EXPIRY_NOTIFICATION)
def trial_period_ending_checker(object, event):
"""Check if the trial period of employees is almost ending.
object is likely the portal, but try not to depend on that.
"""
portal = getToolByName(object, 'portal_url').getPortalObject()
panel = IHRMNotificationsPanelSchema(object)
if not panel.trial_ending_notification:
logger.info("Trial period ending notification is switched off.")
return
days_warning = panel.trial_ending_notification_period
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
contracts = employee.restrictedTraverse('@@contracts')
current_contract = contracts.current_contract()
info = dict(employee_name = employee.officialName(),
employee_url = employee.absolute_url())
if current_contract is None:
continue
trial_period_end = contracts.trial_period_end()
if trial_period_end is None:
# for example when there is no trial period...
continue
now = DateTime()
if now + days_warning >= trial_period_end:
# Check if we have already warned about this.
notified = INotified(current_contract)
if notified.has_notification(TRIAL_PERIOD_ENDING_NOTIFICATION):
continue
notify(TrialPeriodEndingEvent(employee))
notified.add_notification(TRIAL_PERIOD_ENDING_NOTIFICATION)
| Python |
from plonehrm.notifications.interfaces import IHRMModuleEvent
from plonehrm.notifications.interfaces import IHRMEmailer
class IContractEvent(IHRMModuleEvent):
pass
class IContractEmailer(IHRMEmailer):
pass
| Python |
try:
import zope.annotation
except ImportError:
# BBB for Zope 2.9
import zope.app.annotation
import zope.app.annotation.interfaces
import sys
sys.modules['zope.annotation'] = zope.app.annotation
sys.modules['zope.annotation.interfaces'] = zope.app.annotation.interfaces
| Python |
from zope.i18n import translate
from zope.interface import implements
from zope.component.interfaces import ObjectEvent
from Acquisition import aq_parent
from Products.CMFCore.utils import getToolByName
from plonehrm.contracts import ContractsMessageFactory as _
from plonehrm.contracts.notifications.interfaces import IContractEvent
class NoContractEvent(ObjectEvent):
implements(IContractEvent)
class ContractEndingEvent(ObjectEvent):
"""Contract is almost ending.
"""
implements(IContractEvent)
# This needs to be handled by a (HRM) Manager, e.g. a checklist
# item specifically for managers needs to be created.
for_manager = True
def __init__(self, *args, **kwargs):
super(ContractEndingEvent, self).__init__(*args, **kwargs)
# We get the settings of the worklocaton to see
# if a new letter or a new contract shall be created.
worklocation = aq_parent(self.object)
if worklocation.getCreateLetterWhenExpiry():
new_type = 'Letter'
text = _('msg_make_new_letter', u"Make new letter")
else:
new_type = 'Contract'
text = _('msg_make_new_contract', u"Make new contract")
create_url = self.object.absolute_url() + \
'/createObject?type_name=' + new_type
# Get the expiry date.
last_contract = self.object.get_last_contract()
if not last_contract:
# Should not happen.
expires = None
else:
expires = last_contract.expiry_date()
# Add a message to make a new contract, with the correct link.
props = getToolByName(self.object, 'portal_properties')
lang = props.site_properties.getProperty('default_language')
text = translate(text, target_language=lang)
self.message = text
self.link_url = create_url
self.date = expires
class TrialPeriodEndingEvent(ObjectEvent):
"""Trial period is almost ending.
"""
implements(IContractEvent)
# This needs to be handled by a (HRM) Manager, e.g. a checklist
# item specifically for managers needs to be created.
for_manager = True
def __init__(self, *args, **kwargs):
super(TrialPeriodEndingEvent, self).__init__(*args, **kwargs)
contracts = self.object.restrictedTraverse('@@contracts')
trial_period_end = contracts.trial_period_end()
# Add a warning message.
toLocalizedTime = self.object.restrictedTraverse(
'@@plone').toLocalizedTime
trial_period_end = toLocalizedTime(trial_period_end)
text = _(u"Trial period ends at ${date}.",
mapping=dict(date=trial_period_end))
props = getToolByName(self.object, 'portal_properties')
lang = props.site_properties.getProperty('default_language')
self.message = translate(text, target_language=lang)
| Python |
from Products.PloneTestCase import PloneTestCase as ptc
from Products.plonehrm.tests.base import PlonehrmLayer
ptc.setupPloneSite()
class BaseTestCase(ptc.PloneTestCase):
layer = PlonehrmLayer
| Python |
# -*- coding: utf-8 -*-
#
# File: tests.py
#
# Copyright (c) 2007 by []
# Generator: ArchGenXML Version 1.6.0-beta-svn
# http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
__author__ = """unknown <unknown>"""
__docformat__ = 'plaintext'
| Python |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
import logging
from zope.i18nmessageid import MessageFactory
from Products.Archetypes import listTypes
from Products.Archetypes.atapi import process_types
from Products.CMFCore import utils as cmfutils
from Products.validation.exceptions import AlreadyRegisteredValidatorError
from plonehrm.contracts import config
from Products.validation import validation
from validators import MaxDaysPerWeek
validation.register(MaxDaysPerWeek('maxDaysPerWeek'))
logger = logging.getLogger('plonehrm.contracts')
logger.debug('Installing Product')
ContractsMessageFactory = MessageFactory(u'contract')
try:
from plonehrm.contracts import validators
except AlreadyRegisteredValidatorError:
pass
def initialize(context):
import content
from content import tool
content_types, constructors, ftis = process_types(
listTypes(config.PROJECTNAME),
config.PROJECTNAME)
cmfutils.ContentInit(
config.PROJECTNAME + ' Content',
content_types = content_types,
permission = 'plonehrm: Add contract',
extra_constructors = constructors,
fti = ftis,
).initialize(context)
| Python |
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)
| Python |
__author__ = """Jean-Paul Ladage <j.ladage@zestsoftware.nl>"""
__docformat__ = 'plaintext'
PROJECTNAME = "plonehrm.contracts"
product_globals = globals()
| Python |
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()
| Python |
import logging
from AccessControl import Unauthorized
from DateTime import DateTime
from zope.component import queryMultiAdapter
from Products.CMFCore.utils import getToolByName
from zExceptions import BadRequest
logger = logging.getLogger("plonehrm")
class HRMConfigException(Exception):
pass
def updateEmployee(object, event=None):
"""Add missing employee modules to the employee.
This method can be used as event handler; but event is ignored: we
only need the object. The function signature needs to accept
events though, otherwise you get TypeErrors.
"""
employee = object
available_ids = employee.objectIds()
needed_objects = []
portal_props = getToolByName(employee,
'portal_properties', None)
if portal_props is not None:
#hrm_props = getattr(portal_props, 'plonehrm_properties', None)
hrm_props = portal_props.get('plonehrm_properties', None)
if hrm_props is not None:
needed_objects = hrm_props.getProperty(
'portal_types_to_create', [])
type_id_mapping = {}
for item in needed_objects:
parts = item.split(',')
if len(parts) != 2:
raise HRMConfigException, \
"Bad item found in portal_types_to_create: %s" % item
parts = [p.strip() for p in parts]
portal_type = parts[0]
id_ = parts[1]
type_id_mapping[id_] = portal_type
needed_ids = type_id_mapping.keys()
to_create = [t for t in needed_ids
if t not in available_ids]
pt = getToolByName(employee, 'portal_types')
for id_ in to_create:
portal_type = type_id_mapping[id_]
try:
#_createObjectByType(portal_type, employee, id_)
pt.constructContent(portal_type, employee, id_)
obj = employee[id_]
obj.setTitle(id_)
except BadRequest:
# Already added, even though we checked this so why is
# this getting called then. Lunacy!
pass
except ValueError, exc:
# Probably: content type does not exist.
logger.warn(exc)
def email_adresses_of_local_managers(context):
"""Return email adresses of the local managers."""
# Partially copied from plone's computeRoleMap.py.
pu = context.plone_utils
acquired_roles = pu.getInheritedLocalRoles(context)
local_roles = context.acl_users.getLocalRolesForDisplay(context)
mtool = context.portal_membership
worklocation_managers = []
hrm_managers = []
worklocation_role = 'WorklocationManager'
hrm_role = 'HrmManager'
def process_member(name, roles, type, id):
if not id.startswith('group_'):
member = mtool.getMemberById(name)
if (member is not None
and not member.getProperty('email', '') == ''
and not member.getProperty('fullname', '') == ''):
name = member.getProperty('fullname')
email = member.getProperty('email')
full_email = '%s <%s>' % (name, email)
if worklocation_role in roles:
worklocation_managers.append(full_email)
if hrm_role in roles:
hrm_managers.append(full_email)
# first process acquired roles
for name, roles, type, id in acquired_roles:
process_member(name, roles, type, id)
# second process local roles
for name, roles, type, id in local_roles:
process_member(name, roles, type, id)
return {'worklocation_managers': worklocation_managers,
'hrm_managers': hrm_managers,
# Later, employees might be added. That's why I'm not
# returning a tuple.
}
def set_plonehrm_workflow_policy(context):
"""Give the context the plonehrm placeful workflow policy."""
pw = getToolByName(context, 'portal_placeful_workflow')
try:
config = pw.getWorkflowPolicyConfig(context)
except Unauthorized:
logger.warn("User is not allowed to get/set the workflow policy "
"in his work location. Using the default.")
return
if not config:
# Add the config.
adder = context.manage_addProduct['CMFPlacefulWorkflow']
adder.manage_addWorkflowPolicyConfig()
config = pw.getWorkflowPolicyConfig(context)
# Set the config.
config.setPolicyIn(policy='plonehrm')
getToolByName(context, 'portal_workflow').updateRoleMappings()
def next_anniversary(employee, now=None):
"""Helper function to get the next anniversary of the employee
If the employee has his anniversary today, then next_anniversary
will also return today.
The 'now' parameter is only there to ease testing.
We test the next_anniversary and age functions here . We create
some easier dummy classes:
>>> class DummyEmployee(object):
... def __init__(self, birthdate=None):
... self.birthDate = birthdate
... def getBirthDate(self):
... return self.birthDate
>>> emp = DummyEmployee()
>>> next_anniversary(emp) is None
True
Let's take a normal birthday:
>>> emp.birthdate = DateTime('1976/01/27')
>>> next_anniversary(emp, now=DateTime('1999/01/12'))
DateTime('1999/01/27')
>>> age(emp, now=DateTime('1999/01/12'))
22
>>> next_anniversary(emp, now=DateTime('1999/01/27'))
DateTime('1999/01/27')
>>> age(emp, now=DateTime('1999/01/27'))
23
>>> next_anniversary(emp, now=DateTime('1999/02/12'))
DateTime('2000/01/27')
>>> age(emp, now=DateTime('1999/02/12'))
23
Having a birthday at leap day (29 February) should work too). We
cheat by setting the anniversay to the 28th of February then.
>>> emp.birthdate = DateTime('1984/02/29')
>>> next_anniversary(emp, now=DateTime('1999/02/12'))
DateTime('1999/02/28')
>>> age(emp, now=DateTime('1999/02/12'))
14
Of course when this year *is* a leap year, then 29 February is
fine.
>>> next_anniversary(emp, now=DateTime('2004/02/12'))
DateTime('2004/02/29')
>>> age(emp, now=DateTime('2004/02/12'))
19
>>> next_anniversary(emp, now=DateTime('2004/02/28'))
DateTime('2004/02/29')
>>> age(emp, now=DateTime('2004/02/28'))
19
>>> next_anniversary(emp, now=DateTime('2004/02/29'))
DateTime('2004/02/29')
>>> age(emp, now=DateTime('2004/02/29'))
20
>>> next_anniversary(emp, now=DateTime('2004/03/12'))
DateTime('2005/02/28')
>>> age(emp, now=DateTime('2004/03/12'))
20
>>> next_anniversary(emp, now=DateTime('2005/02/12'))
DateTime('2005/02/28')
>>> age(emp, now=DateTime('2005/02/12'))
20
>>> next_anniversary(emp, now=DateTime('2005/02/28'))
DateTime('2005/02/28')
>>> age(emp, now=DateTime('2005/02/28'))
20
>>> next_anniversary(emp, now=DateTime('2005/03/12'))
DateTime('2006/02/28')
>>> age(emp, now=DateTime('2005/03/12'))
21
"""
birth_date = employee.getBirthDate()
if birth_date is None:
return None
# When testing we want to make sure that the tests keep passing,
# also next year, and in the next leap year. So we allow passing
# a parameter 'now'.
if not now:
now = DateTime().earliestTime()
birth_month = birth_date.month()
birth_day = birth_date.day()
if not now.isLeapYear() and birth_month == 2 and birth_day == 29:
# This is a leap day, but it is not a leap year.
birth_day = 28
anniversary = DateTime(now.year(), birth_month, birth_day)
if now > anniversary:
birth_day = birth_date.day()
next_year = DateTime(now.year()+1, 1, 1)
if not next_year.isLeapYear() and birth_month == 2 and birth_day == 29:
# This is a leap day, but it is not a leap year.
birth_day = 28
anniversary = DateTime(next_year.year(), birth_month, birth_day)
return anniversary
def age(employee, now=None):
"""Helper function to get the age of the employee.
The 'now' parameter is only there to ease testing.
For tests, see the next_anniversary function above.
"""
# When testing we want to make sure that the tests keep passing,
# also next year, and in the next leap year. So we allow passing
# a parameter 'now'.
if not now:
now = DateTime().earliestTime()
birth_date = employee.getBirthDate()
if birth_date is None:
return None
birth_year = birth_date.year()
birth_month = birth_date.month()
birth_day = birth_date.day()
birth_date_this_year = (now.year(), birth_month, birth_day)
this_date = (now.year(), now.month(), now.day())
age = now.year() - birth_year
if birth_date_this_year == this_date:
return age
if this_date < birth_date_this_year:
age -= 1
return age
return age
def apply_template_of_tool(object, tool_name):
"""After initializing this object, set the text based on template.
object is likely a job performance interview or absence evaluation
interview. For contracts there are some special rules, but that
is done in plonehrm.contracts.
This funcion is no event handler, but can be used in event
handlers.
"""
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, tool_name, None)
if tool is None:
logger.error("%s cannot be found.", tool_name)
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)
| Python |
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")
| Python |
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.')
| Python |
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())
| Python |
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())
| Python |
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)
| Python |
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)
| Python |
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.")
| Python |
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)
| Python |
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.
"""
| Python |
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()
| Python |
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()
| Python |
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
| Python |
# make me a python package | Python |
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()
| Python |
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())
| Python |
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'
| Python |
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'])
| Python |
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)
| Python |
# -*- coding: utf-8 -*-
import worklocation
import employee
import template
| Python |
__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)
| Python |
__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)
| Python |
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'])
| Python |
__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 """
| Python |
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)
| Python |
from plonehrm.notifications.interfaces import IHRMModuleEvent
from plonehrm.notifications.interfaces import IHRMEmailer
class IPersonalDataEvent(IHRMModuleEvent):
pass
class IPersonalDataEmailer(IHRMEmailer):
pass
| Python |
# | Python |
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)
| Python |
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, ))
| Python |
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
| Python |
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, ))
| Python |
__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, ))
| Python |
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, ))
| Python |
#
| Python |
__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)
| Python |
# | Python |
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')
| Python |
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)
| Python |
# 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__)
| Python |
#
| Python |
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"),
)
#
| Python |
# -*- extra stuff goes here -*-
from contact import Icontact
from organization import Iorganization
| Python |
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"),
)
#
| Python |
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}
| Python |
#
| Python |
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}
| Python |
"""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)
| Python |
#
| Python |
"""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)
| Python |
"""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, [])
| Python |
#
| Python |
"""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)
| Python |
"""Common configuration constants
"""
PROJECTNAME = 'Products.plonecrm'
ADD_PERMISSIONS = {
# -*- extra stuff goes here -*-
'contact': 'Products.plonecrm: Add contact',
'organization': 'Products.plonecrm: Add organization',
}
| Python |
# 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__)
| Python |
# -*- 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"],
)
| Python |
# 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__)
| Python |
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'})]
| Python |
"""
$Id: utils.py 53403 2007-11-08 09:54:35Z wichert $
"""
from ZODB.PersistentMapping import PersistentMapping
from AccessControl import ClassSecurityInfo, ModuleSecurityInfo
from Acquisition import Implicit, aq_inner, aq_parent
import Globals
from zope.i18nmessageid import MessageFactory
from Products.CMFCore.utils import getToolByName
import config
def importModuleFromName(module_name):
""" import and return a module by its name """
__traceback_info__ = (module_name, )
m = __import__(module_name)
try:
for sub in module_name.split('.')[1:]:
m = getattr(m, sub)
except AttributeError, e:
raise ImportError(str(e))
return m
def changeOwnershipOf(object, userid, recursive=0):
"""Changes the ownership of an object. Stolen from Plone and CMFCore, but
be less restrictive about where the owner is found.
"""
membership = getToolByName(object, 'portal_membership')
user = None
uf = object.acl_users
while uf is not None:
user = uf.getUserById(userid)
if user is not None:
break
container = aq_parent(aq_inner(uf))
parent = aq_parent(aq_inner(container))
uf = getattr(parent, 'acl_users', None)
if user is None:
raise KeyError, "User %s cannot be found." % userid
object.changeOwnership(user, recursive)
def fixOwnerRole(object, user_id):
# Get rid of all other owners
owners = object.users_with_local_role('Owner')
for o in owners:
roles = list(object.get_local_roles_for_userid(o))
roles.remove('Owner')
if roles:
object.manage_setLocalRoles(o, roles)
else:
object.manage_delLocalRoles([o])
# Fix for 1750
roles = list(object.get_local_roles_for_userid(user_id))
roles.append('Owner')
object.manage_setLocalRoles(user_id, roles)
fixOwnerRole(object, user.getId())
catalog_tool = getToolByName(object, 'portal_catalog')
catalog_tool.reindexObject(object)
if recursive:
purl = getToolByName(object, 'portal_url')
_path = purl.getRelativeContentURL(object)
subobjects = [b.getObject() for b in \
catalog_tool(path={'query':_path,'level':1})]
for obj in subobjects:
fixOwnerRole(obj, user.getId())
catalog_tool.reindexObject(obj)
class TransformDataProvider(Implicit):
""" Base class for data providers """
security = ClassSecurityInfo()
security.declareObjectPublic()
def __init__(self):
self.config = PersistentMapping()
self.config_metadata = PersistentMapping()
self.config.update({'inputs' : {} })
self.config_metadata.update({
'inputs' : {
'key_label' : '',
'value_label' : '',
'description' : ''}
})
security.declarePublic('setElement')
def setElement(self, inputs):
""" inputs - dictionary, but may be extended to new data types"""
self.config['inputs'].update(inputs)
def delElement(self, el):
""" el - dictionary key"""
del self.config['inputs'][el]
security.declarePublic('getElements')
def getElements(self):
""" Returns mapping """
return self.config['inputs']
security.declarePublic('getConfigMetadata')
def getConfigMetadata(self):
""" Returns config metadata """
return self.config_metadata['inputs']
Globals.InitializeClass(TransformDataProvider)
def finalizeSchema(schema):
# Categorization
if schema.has_key('subject'):
schema.changeSchemataForField('subject', 'categorization')
if schema.has_key('relatedItems'):
schema.changeSchemataForField('relatedItems', 'categorization')
if schema.has_key('location'):
schema.changeSchemataForField('location', 'categorization')
if schema.has_key('language'):
schema.changeSchemataForField('language', 'categorization')
# Dates
if schema.has_key('effectiveDate'):
schema.changeSchemataForField('effectiveDate', 'dates')
if schema.has_key('expirationDate'):
schema.changeSchemataForField('expirationDate', 'dates')
if schema.has_key('creation_date'):
schema.changeSchemataForField('creation_date', 'dates')
if schema.has_key('modification_date'):
schema.changeSchemataForField('modification_date', 'dates')
# Ownership
if schema.has_key('creators'):
schema.changeSchemataForField('creators', 'ownership')
if schema.has_key('contributors'):
schema.changeSchemataForField('contributors', 'ownership')
if schema.has_key('rights'):
schema.changeSchemataForField('rights', 'ownership')
# Settings
if schema.has_key('allowDiscussion'):
schema.changeSchemataForField('allowDiscussion', 'settings')
if schema.has_key('excludeFromNav'):
schema.changeSchemataForField('excludeFromNav', 'settings')
if schema.has_key('nextPreviousEnabled'):
schema.changeSchemataForField('nextPreviousEnabled', 'settings')
# Use PloneboardMessageFactory for translations in Python
PloneboardMessageFactory = MessageFactory(config.I18N_DOMAIN)
ModuleSecurityInfo('Products.Ploneboard.utils').declarePublic('PloneboardMessageFactory')
| Python |
## 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)
| Python |
## 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))
| Python |
## 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 | Python |
## 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) | Python |
## 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
| Python |
## 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)
| Python |
## 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 | Python |
from ExtensionClass import Base
from Products.CMFPlone.PloneBatch import Batch as PloneBatch, \
calculate_pagenumber, \
calculate_pagerange, \
calculate_leapback, \
calculate_leapforward
class LazyPrevBatch(Base):
def __of__(self, parent):
start = parent.first - parent._size + parent.overlap
if start < 0 or start >= parent.sequence_length:
return None
return Batch(parent._method, parent.sequence_length, parent._size,
start, 0, parent.orphan, parent.overlap)
class LazyNextBatch(Base):
def __of__(self, parent):
start = parent.end - parent.overlap
if start < 0 or start >= parent.sequence_length:
return None
return Batch(parent._method, parent.sequence_length, parent._size,
start, 0, parent.orphan, parent.overlap)
class Batch(PloneBatch):
"""A custom batch implementation to enable batching over forums and
conversations. This is identical to PloneBatch's implementation except:
- The sequence length is explicitly given to the constructor
- Instead of operating on a sequence, the batch is given a method to call.
This method needs to have a signature
def getItems(self, limit, offset)
limit is the number of items to return (the batch size) and offset is
the number of items to skip at the beginning of the sequence.
"""
__allow_access_to_unprotected_subobjects__ = 1
# Needs first, length,
previous = LazyPrevBatch()
next = LazyNextBatch()
sequence_length = None
size = first= start = end = orphan = overlap = navlist = None
numpages = pagenumber = pagerange = pagerangeend = pagerangestart = pagenumber = quantumleap = None
def __init__( self, method, sequence_length, size, start=0, end=0, orphan=0, overlap=0, pagerange=7, quantumleap=0, b_start_str='b_start'):
""" Encapsulate sequence in batches of size
method - the method to call to get the correct part of the batch
sequence_length - the total number of items in the sequence
size - the number of items in each batch. This will be computed if left out.
start - the first element of sequence to include in batch (0-index)
end - the last element of sequence to include in batch (0-index, optional)
orphan - the next page will be combined with the current page if it does not contain more than orphan elements
overlap - the number of overlapping elements in each batch
pagerange - the number of pages to display in the navigation
quantumleap - 0 or 1 to indicate if bigger increments should be used in the navigation list for big results.
b_start_str - the request variable used for start, default 'b_start'
"""
start = start + 1
self.sequence_length = sequence_length
self._method = method
start,end,sz = opt(start,end,size,orphan,sequence_length)
self.size = sz
self._size = size
self.start = start
self.end = end
self.orphan = orphan
self.overlap = overlap
self.first = max(start - 1, 0)
self.length = self.end - self.first
self.b_start_str = b_start_str
self.last = sequence_length - size
# Set up next and previous
if self.first == 0:
self.previous = None
# Set up the total number of pages
self.numpages = calculate_pagenumber(self.sequence_length - self.orphan, self.size, self.overlap)
# Set up the current page number
self.pagenumber = calculate_pagenumber(self.start, self.size, self.overlap)
# Set up pagerange for the navigation quick links
self.pagerange, self.pagerangestart, self.pagerangeend = calculate_pagerange(self.pagenumber,self.numpages,pagerange)
# Set up the lists for the navigation: 4 5 [6] 7 8
# navlist is the complete list, including pagenumber
# prevlist is the 4 5 in the example above
# nextlist is 7 8 in the example above
self.navlist = self.prevlist = self.nextlist = []
if self.pagerange and self.numpages >= 1:
self.navlist = range(self.pagerangestart, self.pagerangeend)
self.prevlist = range(self.pagerangestart, self.pagenumber)
self.nextlist = range(self.pagenumber + 1, self.pagerangeend)
# QuantumLeap - faster navigation for big result sets
self.quantumleap = quantumleap
self.leapback = self.leapforward = []
if self.quantumleap:
self.leapback = calculate_leapback(self.pagenumber, self.numpages, self.pagerange)
self.leapforward = calculate_leapforward(self.pagenumber, self.numpages, self.pagerange)
def __getitem__(self, index):
""" Pull an item out of the partial sequence that is this batch """
if (index < 0 and index + self.end < self.first) or index >= self.length:
raise IndexError, index
sequence = getattr(self, '_partial_sequence', None)
if sequence is None:
self._partial_sequence = sequence = self._method(self.length, self.start-1)
return sequence[index]
def __len__(self):
""" Get the length of the partial sequence that is this batch """
return self.length
def opt(start, end, size, orphan, sequence_length):
"""Calculate start, end and batch size"""
length = sequence_length
if size < 1:
if start > 0 and end > 0 and end >= start:
size = end + 1 - start
else: size = 25
if start > 0:
if start>length:
start = length
if end > 0:
if end < start: end = start
else:
end = start + size - 1
if (end+orphan)>=length:
end = length
elif end > 0:
if (end)>length:
end = length
start = end + 1 - size
if start - 1 < orphan: start = 1
else:
start = 1
end = start + size - 1
if (end+orphan)>=length:
end = length
return start,end,size
| Python |
### Register Transforms
### This is interesting because we don't expect all transforms to be
### available on all platforms. To do this we allow things to fail at
### two levels
### 1) Imports
### If the import fails the module is removed from the list and
### will not be processed/registered
### 2) Registration
### A second phase happens when the loaded modules register method
### is called and this produces an instance that will used to
### implement the transform, if register needs to fail for now it
### should raise an ImportError as well (dumb, I know)
from Products.PortalTransforms.libtransforms.utils import MissingBinary
modules = [
'text_to_emoticons',
'url_to_hyperlink',
]
g = globals()
transforms = []
for m in modules:
try:
ns = __import__(m, g, g, None)
transforms.append(ns.register())
except ImportError, e:
print "Problem importing module %s : %s" % (m, e)
except MissingBinary, e:
print e
except:
import traceback
traceback.print_exc()
def initialize(engine):
for transform in transforms:
engine.registerTransform(transform)
| Python |
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()
| Python |
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" ]
| Python |
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)
| Python |
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()
| Python |
# this file is here to make Install.py importable.
# we need to make it non-zero size to make winzip cooperate
| Python |
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())))
| Python |
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")
| Python |
from Acquisition import aq_inner
from zExceptions import Unauthorized
from zope.component import getMultiAdapter
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile
class RSSView(BrowserView):
template = ZopeTwoPageTemplateFile("rss.pt")
def __init__(self, context, request):
super(RSSView, self).__init__(context, request)
self.response=request.response
self.context_state=getMultiAdapter((context, request),
name="plone_context_state")
sp=getToolByName(context, "portal_properties").site_properties
plone_view=getMultiAdapter((context, request), name="plone")
def crop(text):
return plone_view.cropText(text,
sp.search_results_description_length, sp.ellipsis)
self.crop=crop
self.formatTime=plone_view.toLocalizedTime
self.syndication=getToolByName(context, "portal_syndication")
def updatePeriod(self):
return self.syndication.getUpdatePeriod(aq_inner(self.context))
def updateFrequency(self):
return self.syndication.getUpdateFrequency(aq_inner(self.context))
def updateBase(self):
return self.syndication.getHTML4UpdateBase(aq_inner(self.context))
def title(self):
return self.context_state.object_title()
def description(self):
return self.context.Description()
def url(self):
return self.context_state.view_url()
def date(self):
return self.context.modified().HTML4()
def _morph(self, brain):
obj=brain.getObject()
text=obj.Schema()["text"].get(obj, mimetype="text/plain").strip()
return dict(
title = brain.Title,
url = brain.getURL()+"/view",
description = self.crop(text),
date = brain.created.HTML4(),
author = brain.Creator,
)
def update(self):
catalog=getToolByName(self.context, "portal_catalog")
query=dict(
path="/".join(aq_inner(self.context).getPhysicalPath()),
object_provides="Products.Ploneboard.interfaces.IComment",
sort_on="created",
sort_order="reverse",
sort_limit=20)
brains=catalog(query)
self.comments=[self._morph(brain) for brain in brains]
def __call__(self):
if not self.syndication.isSyndicationAllowed(aq_inner(self.context)):
raise Unauthorized, "Syndication is not enabled"
self.update()
self.response.setHeader("Content-Type", "text/xml;charset=utf-8")
return self.template()
| Python |
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_)
| Python |
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()
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.