Commit c615bc62 authored by Gabriel Monnerat's avatar Gabriel Monnerat

[ERP5 Configurator] Rename _build to _checkConsistency to follow Constraint API

The logic of all Configuration Items was not changed, but now the
changes are applied only if fixit is True and the constraints are
filtered by constraint type equal configuration.

Cosmetic: Trailing whitespaces were removed in the same commit
parent 91ef6772
......@@ -56,42 +56,53 @@ class AccountConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.DublinCore
, PropertySheet.Account )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
account_module = self.getPortalObject().account_module
account = None
account_id = getattr(self, 'account_id', None)
error_list = []
error_list_append = lambda msg: error_list.append(
self._createConstraintMessage(msg))
extra_kw = {}
if account_id:
extra_kw['id'] = account_id
account = getattr(account_module, account_id, None)
if account is None:
account = account_module.newContent(
portal_type='Account',
title=self.getTitle(),
account_type=self.getAccountType(),
gap=self.getGap(),
financial_section=self.getFinancialSection(),
credit_account=self.isCreditAccount(),
description=self.getDescription(),
**extra_kw)
error_list_append("Account %s should be created" % self.getTitle())
if fixit:
account = account_module.newContent(
portal_type='Account',
title=self.getTitle(),
account_type=self.getAccountType(),
gap=self.getGap(),
financial_section=self.getFinancialSection(),
credit_account=self.isCreditAccount(),
description=self.getDescription(),
**extra_kw)
else:
# Update existing account
if (self.getAccountType() != account.getAccountType()) and \
(self.getFinancialSection() != account.getFinancialSection()):
raise ValueError("The Configurator is trying to overwrite previous configuration information (%s)" % account.getRelativeUrl())
error_list_append("Account %s should be updated" % account.getRelativeUrl())
if fixit:
# Update existing account
if (self.getAccountType() != account.getAccountType()) and \
(self.getFinancialSection() != account.getFinancialSection()):
raise ValueError("The Configurator is trying to overwrite previous configuration information (%s)" % account.getRelativeUrl())
account.edit(title=self.getTitle(), description=self.getDescription())
gap_list = account.getGapList()
# Only include only the additional gap that do not collide.
if self.getGap() not in gap_list:
gap_list.append(self.getGap())
account.setGapList(gap_list)
account.setCreditAccount(self.isCreditAccount())
account.edit(title=self.getTitle(), description=self.getDescription())
gap_list = account.getGapList()
# Only include only the additional gap that do not collide.
if self.getGap() not in gap_list:
gap_list.append(self.getGap())
account.setGapList(gap_list)
account.setCreditAccount(self.isCreditAccount())
if self.portal_workflow.isTransitionPossible(account, 'validate'):
account.validate(comment=translateString("Validated by Configurator"))
if account and fixit:
if self.portal_workflow.isTransitionPossible(account, 'validate'):
account.validate(comment=translateString("Validated by Configurator"))
## add to customer template
self.install(account, business_configuration)
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(account, business_configuration)
return error_list
......@@ -55,20 +55,23 @@ class AccountingPeriodConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.DublinCore
, PropertySheet.Task )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal = self.getPortalObject()
business_configuration = self.getBusinessConfigurationValue()
organisation_id = business_configuration.\
getGlobalConfigurationAttr('organisation_id')
organisation = portal.organisation_module._getOb(organisation_id)
period = organisation.newContent(
portal_type='Accounting Period',
start_date=self.getStartDate(),
stop_date=self.getStopDate(),
short_title=self.getShortTitle(),
title=self.getTitle())
if fixit:
period = organisation.newContent(
portal_type='Accounting Period',
start_date=self.getStartDate(),
stop_date=self.getStopDate(),
short_title=self.getShortTitle(),
title=self.getTitle())
if self.portal_workflow.isTransitionPossible(period, 'start'):
period.start(comment="Started by Configurator")
if self.portal_workflow.isTransitionPossible(period, 'start'):
period.start(comment="Started by Configurator")
# no need to 'install' in the business template, because it's contain as
# subobject of an organisation we already added.
return ['Accounting Period %s should be created' % self.getTitle()]
......@@ -58,8 +58,9 @@ class AlarmConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.Periodicity
)
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal_alarms = self.getPortalObject().portal_alarms
error_list = []
property_dict = {
"active_sense_method_id" : self.getActiveSenseMethodId(),
"periodicity_hour_list" : self.getPeriodicityHourList(),
......@@ -72,14 +73,22 @@ class AlarmConfiguratorItem(ConfiguratorItemMixin, XMLObject):
"periodicity_week_list": self.getPeriodicityWeekList(),
}
alarm = getattr(portal_alarms, self.getId(), None)
alarm_id = self.getId()
alarm = getattr(portal_alarms, alarm_id, None)
if alarm is None:
alarm = portal_alarms.newContent(id=self.getId(),
title=self.getTitle())
alarm.edit(**property_dict)
error_list.append(self._createConstraintMessage(
"Alarm %s should be created" % alarm_id))
if fixit:
alarm = portal_alarms.newContent(id=alarm_id,
title=self.getTitle())
alarm.edit(**property_dict)
# Always enabled
alarm.setEnabled(True)
# Always enabled
alarm.setEnabled(True)
## add to customer template
self.install(alarm, business_configuration)
if alarm and fixit:
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(alarm, business_configuration)
return error_list
......@@ -42,7 +42,7 @@ END_STATE_TITLE = 'End'
class BusinessConfiguration(Item):
"""
BusinessConfiguration store the values enter by the wizard.
BusinessConfiguration store the values enter by the wizard.
"""
meta_type = 'ERP5 Business Configuration'
......@@ -79,7 +79,7 @@ class BusinessConfiguration(Item):
def isDownloadConfigurationState(self):
""" Check if the Business Configuration is on Download State
"""
return self.getCurrentStateTitle() == DOWNLOAD_STATE_TITLE
return self.getCurrentStateTitle() == DOWNLOAD_STATE_TITLE
security.declareProtected(Permissions.View, 'isEndConfigurationState')
def isEndConfigurationState(self):
......@@ -126,12 +126,12 @@ class BusinessConfiguration(Item):
form_kw = {}
current_state = self.getCurrentStateValue()
transition = self.getNextTransition()
## it's possible that we have already saved a configuration save object
## it's possible that we have already saved a configuration save object
## in workflow_history for this state so we use it
configuration_save = self._getConfSaveForStateFromWorkflowHistory()
if configuration_save is None:
## we haven't saved any configuration save for this state so create new one
configuration_save = self.newContent(portal_type='Configuration Save',
configuration_save = self.newContent(portal_type='Configuration Save',
title=current_state.getTitle())
else:
## we have already created configuration save for this state
......@@ -145,7 +145,7 @@ class BusinessConfiguration(Item):
for k in form_kw.keys():
if form_kw[k].__class__.__name__ != 'FileUpload':
modified_form_kw[k] = form_kw[k]
configuration_save.edit(**modified_form_kw)
configuration_save.edit(**modified_form_kw)
## Add some variables so we can get use them in workflow after scripts
form_kw['configuration_save_url'] = configuration_save.getRelativeUrl()
form_kw['transition'] = transition.getRelativeUrl()
......@@ -162,7 +162,7 @@ class BusinessConfiguration(Item):
while transition is not None:
form_id = transition.getTransitionFormId()
if self.isDownloadConfigurationState():
## exec next transition for this business configuration
## exec next transition for this business configuration
self._executeTransition()
transition = self.getNextTransition()
return None, None, None, None
......@@ -172,7 +172,7 @@ class BusinessConfiguration(Item):
transition = self.getNextTransition()
else:
if context is None:
## examine workflow_history for already saved
## examine workflow_history for already saved
## 'Configuration Save' objects for this state
context = self._getConfSaveForStateFromWorkflowHistory()
## get form object in a proper context
......@@ -203,7 +203,7 @@ class BusinessConfiguration(Item):
form_html = self.Base_mainConfiguratorFormTemplate(
current_form_number=form_counter + 1,
max_form_numbers=forms_number,
form_title=form.title,
form_title=form.title,
form_html=template_html)
html_forms.append(form_html)
else:
......@@ -233,14 +233,14 @@ class BusinessConfiguration(Item):
html_forms.append(form_html)
if html_forms != []:
html = "\n".join(html_forms)
title = form.title
title = form.title
return html, title
security.declarePrivate('_displayPreviousForm')
def _displayPreviousForm(self):
""" Render previous form using workflow history. """
workflow_history = self.getCurrentStateValue().getWorkflowHistory(self, remove_undo=1)
workflow_history.reverse()
workflow_history.reverse()
for wh in workflow_history:
## go one step back
current_state = self.getCurrentStateValue()
......@@ -303,7 +303,7 @@ class BusinessConfiguration(Item):
security.declareProtected(Permissions.ModifyPortalContent, 'setMultiEntryTransition')
def setMultiEntryTransition(self, transition_url, max_entry_number):
""" Set a transition as multiple - i.e max_entry_number of forms
""" Set a transition as multiple - i.e max_entry_number of forms
which will be rendered. This method is called in after scripts
and usually this number is set by user in a web form. """
if getattr(aq_base(self), '_multi_entry_transitions', None) is None:
......@@ -327,13 +327,13 @@ class BusinessConfiguration(Item):
############# Instance and Business Configuration ########################
security.declareProtected(Permissions.ModifyPortalContent, 'buildConfiguration')
def buildConfiguration(self):
"""
Build list of business templates according to already saved
"""
Build list of business templates according to already saved
Configuration Saves (i.e. user input).
This is the actual implementation which can be used from workflow
This is the actual implementation which can be used from workflow
actions and Configurator requets
"""
kw = dict(tag="start_configuration_%s" % self.getId(),
kw = dict(tag="start_configuration_%s" % self.getId(),
after_method_id=["updateBusinessTemplateFromUrl",
"recursiveImmediateReindexObject",
"immediateReindexObject"])
......@@ -346,13 +346,14 @@ class BusinessConfiguration(Item):
configuration_item_list = configuration_save.contentValues()
configuration_item_list.sort(lambda x, y: cmp(x.getIntId(), y.getIntId()))
for configurator_item in configuration_item_list:
configurator_item.activate(**kw).build(self.getRelativeUrl())
configurator_item.activate(**kw).fixConsistency(
filter={"constraint_type":"configuration"})
kw["after_tag"] = kw["tag"]
kw["tag"] = "configurator_item_%s_%s" % (configurator_item.getId(),
configurator_item.getUid())
kw["tag"] = "final_configuration_step_%s" % self.getId()
kw["after_method_id"] = ["build", 'immediateReindexObject', \
kw["after_method_id"] = ["fixConsistency", 'immediateReindexObject', \
"recursiveImmediateReindexObject"]
self.activate(**kw).ERP5Site_afterConfigurationSetup()
......
......@@ -58,57 +58,61 @@ class BusinessProcessConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.Reference
)
def _build(self, business_configuration):
portal = self.getPortalObject()
business_process = portal.business_process_module.newContent(
portal_type="Business Process",
reference=self.getReference(),
title=self.getTitle())
business_configuration.setGlobalConfigurationAttr(\
business_process_id=business_process.getId())
business_process_dict = self._getBusinessProcessDict()
int_index = 0
for path_dict in business_process_dict["Trade Model Path"]:
int_index += 1
path_dict.setdefault("int_index", int_index)
title = path_dict.pop('title')
trade_phase = path_dict.pop('trade_phase')
trade_date = path_dict.pop('trade_date')
for key in path_dict:
if path_dict[key] is None:
path_dict.pop(key)
self._addTradeModelPath(business_process=business_process,
def _checkConsistency(self, fixit=False, filter=None, **kw):
error_list = ["Business Process %s should be created" % self.getReference(),]
if fixit:
portal = self.getPortalObject()
business_process = portal.business_process_module.newContent(
portal_type="Business Process",
reference=self.getReference(),
title=self.getTitle())
business_configuration = self.getBusinessConfigurationValue()
business_configuration.setGlobalConfigurationAttr(\
business_process_id=business_process.getId())
business_process_dict = self._getBusinessProcessDict()
int_index = 0
for path_dict in business_process_dict["Trade Model Path"]:
int_index += 1
path_dict.setdefault("int_index", int_index)
title = path_dict.pop('title')
trade_phase = path_dict.pop('trade_phase')
trade_date = path_dict.pop('trade_date')
for key in path_dict:
if path_dict[key] is None:
path_dict.pop(key)
self._addTradeModelPath(business_process=business_process,
title=title,
trade_phase=trade_phase,
trade_date=trade_date,
**path_dict)
int_index = 0
for link_dict in business_process_dict["Business Link"]:
int_index += 1
link_dict.setdefault("int_index", int_index)
title = link_dict.pop('title')
trade_phase = link_dict.pop('trade_phase')
delivery_builder = link_dict.pop('delivery_builder', None)
predecessor = link_dict.pop('predecessor', None)
successor = link_dict.pop('successor', None)
for key in path_dict:
if path_dict[key] is None:
path_dict.pop(key)
self._addBusinessLink(business_process=business_process,
title=title,
trade_phase=trade_phase,
trade_date=trade_date,
**path_dict)
int_index = 0
for link_dict in business_process_dict["Business Link"]:
int_index += 1
link_dict.setdefault("int_index", int_index)
title = link_dict.pop('title')
trade_phase = link_dict.pop('trade_phase')
delivery_builder = link_dict.pop('delivery_builder', None)
predecessor = link_dict.pop('predecessor', None)
successor = link_dict.pop('successor', None)
for key in path_dict:
if path_dict[key] is None:
path_dict.pop(key)
self._addBusinessLink(business_process=business_process,
title=title,
trade_phase = trade_phase,
predecessor = predecessor,
successor = successor,
delivery_builder = delivery_builder,
**link_dict)
business_process.validate(comment=translateString('Validated by configurator'))
self.install(business_process, business_configuration)
trade_phase = trade_phase,
predecessor = predecessor,
successor = successor,
delivery_builder = delivery_builder,
**link_dict)
business_process.validate(comment=translateString('Validated by configurator'))
self.install(business_process, business_configuration)
return error_list
def _getBusinessProcessDict(self):
""" Read the spreadsheet and return the configuration for
......
......@@ -55,15 +55,21 @@ class CatalogKeywordKeyConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
error_list = []
portal = self.getPortalObject()
catalog = portal.portal_catalog.getSQLCatalog()
key_list = list(catalog.getProperty('sql_catalog_keyword_search_keys', ()))
for k in self.key_list:
if k not in key_list:
error_list.append(self._createConstraintMessage(
"%s should be in sql_catalog_keyword_search_keys" % k))
key_list.append(k)
key_list = tuple(key_list)
catalog._setPropValue('sql_catalog_keyword_search_keys', key_list)
bt = business_configuration.getSpecialiseValue()
bt.edit(template_catalog_keyword_key_list=key_list)
if fixit:
catalog._setPropValue('sql_catalog_keyword_search_keys', key_list)
business_configuration = self.getBusinessConfigurationValue()
bt = business_configuration.getSpecialiseValue()
bt.edit(template_catalog_keyword_key_list=key_list)
return error_list
......@@ -64,37 +64,49 @@ class CategoriesSpreadsheetConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.ConfiguratorItem
)
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal = self.getPortalObject()
ctool = portal.portal_categories
self._readSpreadSheet()
cache = self._category_cache
object_id_list = ctool.objectIds()
error_list = []
for bc_id, category_list in cache.items():
if bc_id in ctool.objectIds():
if bc_id in object_id_list:
bc = ctool._getOb(bc_id)
else:
# TODO: test bc creation
# the bc should be added as base category in bt5 ?
bc = ctool.newContent(id=bc_id)
for category_info in category_list:
path = bc
for cat in category_info['path'].split("/")[1:]:
if not cat in path.objectIds():
path = path.newContent(
portal_type='Category',
id=cat,)
else:
path = path[cat]
edit_dict = category_info.copy()
edit_dict.pop('path')
if 'id' in edit_dict.keys():
edit_dict.pop('id')
path.edit(**edit_dict)
## add to customer template
self.install(path, business_configuration)
error_list.append(self._createConstraintMessage(
"Base Category %s should be created" % bc_id))
if fixit:
bc = ctool.newContent(id=bc_id)
if fixit:
for category_info in category_list:
path = bc
for cat in category_info['path'].split("/")[1:]:
if not cat in path.objectIds():
path = path.newContent(
portal_type='Category',
id=cat,)
else:
path = path[cat]
edit_dict = category_info.copy()
edit_dict.pop('path')
if 'id' in edit_dict.keys():
edit_dict.pop('id')
path.edit(**edit_dict)
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(path, business_configuration)
else:
error_list.extend(["%s should be created" % category['path'] \
for category in category_list])
return error_list
def _readSpreadSheet(self):
"""Read the spreadsheet and prepare internal category cache.
......
......@@ -54,14 +54,17 @@ class CategoryConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore)
def _build(self, business_configuration):
portal = self.getPortalObject()
category_root = portal.portal_categories[self.category_root]
object_id = self.object_id
if object_id in category_root.objectIds():
category_root.manage_delObjects(object_id)
category = category_root.newContent(portal_type='Category',
id = object_id,
title = self.getTitle())
## add to customer template
self.install(category, business_configuration)
def _checkConsistency(self, fixit=False, filter=None, **kw):
if fixit:
portal = self.getPortalObject()
category_root = portal.portal_categories[self.category_root]
object_id = self.object_id
if object_id in category_root.objectIds():
category_root.manage_delObjects(object_id)
category = category_root.newContent(portal_type='Category',
id = object_id,
title = self.getTitle())
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(category, business_configuration)
return ['Category %s should be created' % self.getTitle(),]
......@@ -58,22 +58,29 @@ class CurrencyConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.Resource
, PropertySheet.Reference )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
currency_module = self.getPortalObject().currency_module
error_list = []
title = self.getTitle()
reference = self.getReference()
base_unit_quantity = self.getBaseUnitQuantity()
# XXX FIXME This is not exactly desired behaviour
currency = self.portal_catalog.getResultValue(id=reference,
portal_type="Currency")
if currency is None:
currency = currency_module.newContent(portal_type = "Currency",
id = reference,
title = title,
reference = reference,
base_unit_quantity = base_unit_quantity)
currency.validate(comment=translateString("Validated by Configurator"))
business_configuration.setGlobalConfigurationAttr(currency_id=currency.getId())
## add to customer template
self.install(currency, business_configuration)
error_list.append(self._createConstraintMessage(
"Currency %s should be created" % reference))
if fixit:
currency = currency_module.newContent(portal_type = "Currency",
id = reference,
title = title,
reference = reference,
base_unit_quantity=self.getBaseUnitQuantity())
currency.validate(comment=translateString("Validated by Configurator"))
if currency:
business_configuration = self.getBusinessConfigurationValue()
business_configuration.setGlobalConfigurationAttr(currency_id=currency.getId())
## add to customer template
self.install(currency, business_configuration)
return error_list
......@@ -57,9 +57,17 @@ class CustomerBT5ConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
bt5 = self.getPortalObject().portal_templates.newContent(
portal_type="Business Template", title=self.bt5_title)
def _checkConsistency(self, fixit=False, filter=None, **kw):
template_tool = self.getPortalObject().portal_templates
error_list = []
if self.bt5_title not in template_tool.getBuiltBusinessTemplateList():
error_list.append(self._createConstraintMessage(
'%s should be created' % self.bt5_title))
## ..and set it as current
business_configuration.setSpecialise(bt5.getRelativeUrl())
if fixit:
bt5 = template_tool.newContent(portal_type="Business Template",
title=self.bt5_title)
business_configuration = self.getBusinessConfigurationValue()
business_configuration.setSpecialise(bt5.getRelativeUrl())
return error_list
......@@ -56,30 +56,33 @@ class OrganisationConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.DublinCore
, PropertySheet.Organisation )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
""" Setup organisation. """
portal = self.getPortalObject()
organisation = portal.organisation_module.newContent(portal_type="Organisation")
if fixit:
portal = self.getPortalObject()
organisation = portal.organisation_module.newContent(portal_type="Organisation")
org_dict = {'price_currency': 'currency_module/%s' % self.getPriceCurrency(),
'group': self.getGroup(),
'title': self.getTitle(),
'corporate_name': self.getCorporateName(),
'default_address_city': self.getDefaultAddressCity(),
'default_email_text': self.getDefaultEmailText(),
'default_telephone_text': self.getDefaultTelephoneText(),
'default_address_zip_code': self.getDefaultAddressZipCode(),
'default_address_region': self.getDefaultAddressRegion(),
'default_address_street_address': self.getDefaultAddressStreetAddress(),
'site':'main', # First customer's organisation is always main site.
}
organisation.edit(**org_dict)
# store globally organization_id
business_configuration.setGlobalConfigurationAttr(organisation_id=organisation.getId())
org_dict = {'price_currency': 'currency_module/%s' % self.getPriceCurrency(),
'group': self.getGroup(),
'title': self.getTitle(),
'corporate_name': self.getCorporateName(),
'default_address_city': self.getDefaultAddressCity(),
'default_email_text': self.getDefaultEmailText(),
'default_telephone_text': self.getDefaultTelephoneText(),
'default_address_zip_code': self.getDefaultAddressZipCode(),
'default_address_region': self.getDefaultAddressRegion(),
'default_address_street_address': self.getDefaultAddressStreetAddress(),
'site':'main', # First customer's organisation is always main site.
}
organisation.edit(**org_dict)
if self.portal_workflow.isTransitionPossible(organisation, 'validate'):
organisation.validate(comment=translateString("Validated by Configurator"))
business_configuration = self.getBusinessConfigurationValue()
# store globally organization_id
business_configuration.setGlobalConfigurationAttr(organisation_id=organisation.getId())
## add to customer template
self.install(organisation, business_configuration)
if self.portal_workflow.isTransitionPossible(organisation, 'validate'):
organisation.validate(comment=translateString("Validated by Configurator"))
## add to customer template
self.install(organisation, business_configuration)
return ['Organisation should be created',]
......@@ -54,9 +54,11 @@ class PermissionConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
template_module_id_list = []
error_list = []
module_permissions_map = {}
business_configuration = self.getBusinessConfigurationValue()
sheets_dict = business_configuration.ConfigurationTemplate_readOOCalcFile(\
self.filename)
for module_id, permissions in sheets_dict.items():
......@@ -79,9 +81,14 @@ class PermissionConfiguratorItem(ConfiguratorItemMixin, XMLObject):
for permission_name, roles in permissions_map.items():
# we must alway include additionally 'Manager' and 'Owner'
roles.extend(['Manager', 'Owner'])
module.manage_permission(permission_name, tuple(roles), 0)
if fixit:
module.manage_permission(permission_name, tuple(roles), 0)
error_list.append(self._createConstraintMessage(
'%s should be set to %s' % (','.join(roles), module.getId())))
# add customized module to customer's bt5
if len(template_module_id_list):
if len(template_module_id_list) and fixit:
bt5_obj = business_configuration.getSpecialiseValue()
bt5_obj.setTemplateModuleIdList(template_module_id_list)
return error_list
......@@ -57,44 +57,49 @@ class PersonConfiguratorItem(XMLObject, ConfiguratorItemMixin):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore
, PropertySheet.Reference
, PropertySheet.Person
, PropertySheet.Person
, PropertySheet.Login)
def _build(self, business_configuration):
portal = self.getPortalObject()
person = portal.person_module.newContent(portal_type="Person")
group_id = getattr(aq_base(self), 'group_id', None)
site_id = getattr(aq_base(self), 'site_id', None)
def _checkConsistency(self, fixit=False, filter=None, **kw):
error_list = ["Person %s should be created" % self.getReference(),]
if fixit:
person_module = self.getPortalObject().person_module
person = person_module.newContent(portal_type="Person")
group_id = getattr(aq_base(self), 'group_id', None)
site_id = getattr(aq_base(self), 'site_id', None)
if getattr(aq_base(self), 'organisation_id', None) is not None:
person.setCareerSubordination('organisation_module/%s' % \
self.organisation_id)
if getattr(aq_base(self), 'organisation_id', None) is not None:
person.setCareerSubordination('organisation_module/%s' % \
self.organisation_id)
# save
person.edit(**{'default_email_text': self.getDefaultEmailText(),
'default_telephone_text': self.getDefaultTelephoneText(),
'first_name': self.getFirstName(),
'career_function': self.getFunction(),
'last_name': self.getLastName(),
'reference': self.getReference(),
'password': self.getPassword(),
})
# save
person.edit(**{'default_email_text': self.getDefaultEmailText(),
'default_telephone_text': self.getDefaultTelephoneText(),
'first_name': self.getFirstName(),
'career_function': self.getFunction(),
'last_name': self.getLastName(),
'reference': self.getReference(),
'password': self.getPassword(),
})
assignment = person.newContent(portal_type="Assignment",
function = self.getFunction(),
group = group_id,
site = site_id)
assignment = person.newContent(portal_type="Assignment",
function = self.getFunction(),
group = group_id,
site = site_id)
# Set dates are required to create valid assigments.
now = DateTime()
assignment.setStartDate(now)
# XXX Is it required to set stop date?
# Define valid for 10 years.
assignment.setStopDate(now + (365*10))
# Set dates are required to create valid assigments.
now = DateTime()
assignment.setStartDate(now)
# XXX Is it required to set stop date?
# Define valid for 10 years.
assignment.setStopDate(now + (365*10))
# Validate the Person and Assigment
person.validate(comment=translateString("Validated by Configurator"))
assignment.open(comment=translateString("Open by Configuration"))
## add to customer template
self.install(person, business_configuration)
# Validate the Person and Assigment
person.validate(comment=translateString("Validated by Configurator"))
assignment.open(comment=translateString("Open by Configuration"))
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(person, business_configuration)
return error_list
......@@ -54,7 +54,7 @@ class PortalTypeConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal = self.getPortalObject()
# Support adding new property sheet to portal type information.
......@@ -67,17 +67,21 @@ class PortalTypeConfiguratorItem(ConfiguratorItemMixin, XMLObject):
new_property_sheet_list = list(type_information.property_sheet_list)
new_property_sheet_list.append(name)
type_information.property_sheet_list = tuple(new_property_sheet_list)
business_configuration = self.getBusinessConfigurationValue()
bt5_obj = business_configuration.getSpecialiseValue()
old_property_sheet_list = bt5_obj.getTemplatePortalTypePropertySheetList()
new_property_sheet_list = (list(old_property_sheet_list) +
['%s | %s' % (self.target_portal_type, name)
['%s | %s' % (self.target_portal_type, name)
for name in self.add_propertysheet_list]
)
bt5_obj.edit(
template_portal_type_property_sheet_list=new_property_sheet_list)
)
if fixit:
bt5_obj.edit(
template_portal_type_property_sheet_list=new_property_sheet_list)
#
# TODO:This class must support many other features we can use in ZMI.
#
return ['Property Sheets configuration should be added in %s' % \
bt5_obj.getTitle(),]
......@@ -59,16 +59,16 @@ class PortalTypeRolesSpreadsheetConfiguratorItem(ConfiguratorItemMixin, XMLObjec
, PropertySheet.DublinCore
, PropertySheet.ConfiguratorItem
)
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal = self.getPortalObject()
portal_type_role_dict = self._getPortalTypeRoleDict()
error_list = []
for type_name, role_list in portal_type_role_dict.items():
portal_type = portal.portal_types.getTypeInfo(type_name)
if portal_type is None:
LOG("CONFIGURATOR", INFO, "Fail to define Roles for %s" % portal_type)
continue
for role in role_list:
# rebuild a category from Group / Site & Function
category_list = []
......@@ -76,21 +76,29 @@ class PortalTypeRolesSpreadsheetConfiguratorItem(ConfiguratorItemMixin, XMLObjec
if role.get(bc):
category_list.append(role[bc])
#category = '\n'.join(category_list)
role_dict = {
'title': role.get('Name', 'Default'),
'description': role.get('Description', 'Configured by ERP5 Configurator'),
'role_name_list': [x.strip() for x in role.get('Role', '').split(';')],
'role_category_list': category_list,
'role_base_category_list': role.get('Base_Category', ''),
'role_base_category_script_id': role.get('Base_Category_Script',
role.get('Script', ''))}
portal_type.newContent(portal_type='Role Information', \
**role_dict)
## Update BT5
bt5_obj = business_configuration.getSpecialiseValue()
if bt5_obj is not None:
bt5_obj.edit(template_portal_type_role_list=portal_type_role_dict.keys())
role_name_list = [x.strip() for x in role.get('Role', '').split(';')]
error_list.append(self._createConstraintMessage(
"Add roles(%s) to %s are required" % (role_name_list, portal_type)))
if fixit:
role_dict = {
'title': role.get('Name', 'Default'),
'description': role.get('Description', 'Configured by ERP5 Configurator'),
'role_name_list': role_name_list,
'role_category_list': category_list,
'role_base_category_list': role.get('Base_Category', ''),
'role_base_category_script_id': role.get('Base_Category_Script',
role.get('Script', ''))}
portal_type.newContent(portal_type='Role Information', \
**role_dict)
if fixit:
## Update BT5
business_configuration = self.getBusinessConfigurationValue()
bt5_obj = business_configuration.getSpecialiseValue()
if bt5_obj is not None:
bt5_obj.edit(template_portal_type_role_list=portal_type_role_dict.keys())
return error_list
def checkSpreadSheetConsistency(self):
"""Check that the spread sheet is consistent with categories spreadsheet.
......
......@@ -71,16 +71,22 @@ class PreferenceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
property_id_list.append('%s%s' % (prop.getReference(), list_prefix))
return property_id_list
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
error_list = []
portal = self.getPortalObject()
preference = portal.portal_preferences._getOb(self.object_id, None)
if preference is None:
preference = portal.portal_preferences.newContent(
portal_type = 'Preference',
id = self.object_id,
title = self.title,
description = self.description,
priority = 1)
error_list.append(self._createConstraintMessage(
"Preference %s should be created" % self.object_id))
if fixit:
preference = portal.portal_preferences.newContent(
portal_type = 'Preference',
id = self.object_id,
title = self.title,
description = self.description,
priority = 1)
else:
return error_list
preference_dict = {}
......@@ -94,6 +100,7 @@ class PreferenceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
if self.portal_workflow.isTransitionPossible(preference, 'enable'):
preference.enable()
business_configuration = self.getBusinessConfigurationValue()
organisation_id = business_configuration.\
getGlobalConfigurationAttr('organisation_id')
organisation_path = 'organisation_module/%s' % organisation_id
......@@ -107,3 +114,4 @@ class PreferenceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
current_template_preference_list.append(preference.getId())
bt5_obj.edit(template_preference_list=current_template_preference_list,)
return error_list
......@@ -58,29 +58,34 @@ class PurchaseTradeConditionConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.Reference
)
def _build(self, business_configuration):
portal = self.getPortalObject()
business_process_id = \
business_configuration.getGlobalConfigurationAttr('business_process_id')
def _checkConsistency(self, fixit=False, filter=None, **kw):
if fixit:
portal = self.getPortalObject()
business_configuration = self.getBusinessConfigurationValue()
business_process_id = \
business_configuration.getGlobalConfigurationAttr('business_process_id')
organisation_id = \
business_configuration.getGlobalConfigurationAttr('organisation_id')
organisation_id = \
business_configuration.getGlobalConfigurationAttr('organisation_id')
currency_id = \
business_configuration.getGlobalConfigurationAttr('currency_id')
currency_id = \
business_configuration.getGlobalConfigurationAttr('currency_id')
trade_condition = portal.purchase_trade_condition_module.newContent(
portal_type="Purchase Trade Condition",
reference=self.getReference(),
title=self.getTitle(), )
trade_condition = portal.purchase_trade_condition_module.newContent(
portal_type="Purchase Trade Condition",
reference=self.getReference(),
title=self.getTitle(), )
trade_condition.setSpecialise("business_process_module/%s" %\
business_process_id)
trade_condition.setSpecialise("business_process_module/%s" %\
business_process_id)
trade_condition.setDestination("organisation_module/%s" % organisation_id)
trade_condition.setDestinationSection("organisation_module/%s" % organisation_id)
trade_condition.setPriceCurrency("currency_module/%s" % currency_id)
trade_condition.setDestination("organisation_module/%s" % organisation_id)
trade_condition.setDestinationSection("organisation_module/%s" % organisation_id)
trade_condition.setPriceCurrency("currency_module/%s" % currency_id)
trade_condition.validate(comment=translateString("Validated by Configurator"))
trade_condition.validate(comment=translateString("Validated by Configurator"))
self.install(trade_condition, business_configuration)
self.install(trade_condition, business_configuration)
return ['Purchase Trade Condition with reference %s should be created' % \
self.getReference(),]
......@@ -56,49 +56,55 @@ class RoleConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
object_list = business_configuration.ConfigurationTemplate_readOOCalcFile(self.filename)
portal = self.getPortalObject()
def _checkConsistency(self, fixit=False, filter=None, **kw):
error_list = ['Roles should imported and created',]
if fixit:
business_configuration = self.getBusinessConfigurationValue()
object_list = business_configuration.ConfigurationTemplate_readOOCalcFile(self.filename)
portal = self.getPortalObject()
portal_type_dict = {}
# we may pass some override dynamic values from outside
# Example:we post 'group_id' and in column we have it then
# it will be replaced with value if not configuration file matters
dynamic_values = dict(group_id = getattr(aq_base(self), 'group_id', None),
function_id = getattr(aq_base(self), 'function_id', None),
site_id = getattr(aq_base(self), 'site_id', None),)
for oo_module_dict in object_list:
mod_conf_list = []
portal_type = oo_module_dict.pop('portal_type')
for category, role_list_string in oo_module_dict.items():
# passed from outside (it has higher priority than configuration file)
category = dynamic_values.get(category, category)
title = category.replace('/', '_')
role_name_list = [x.strip() for x in role_list_string.split(';')]
role_category_list = [category]
conf_dict = {'title': title,
'description': 'Configured by ERP5 Configurator',
'role_name_list': role_name_list,
'role_category_list': role_category_list}
portal_type_dict = {}
# we may pass some override dynamic values from outside
# Example:we post 'group_id' and in column we have it then
# it will be replaced with value if not configuration file matters
dynamic_values = dict(group_id = getattr(aq_base(self), 'group_id', None),
function_id = getattr(aq_base(self), 'function_id', None),
site_id = getattr(aq_base(self), 'site_id', None),)
for oo_module_dict in object_list:
mod_conf_list = []
portal_type = oo_module_dict.pop('portal_type')
for category, role_list_string in oo_module_dict.items():
# passed from outside (it has higher priority than configuration file)
category = dynamic_values.get(category, category)
title = category.replace('/', '_')
role_name_list = [x.strip() for x in role_list_string.split(';')]
role_category_list = [category]
conf_dict = {'title': title,
'description': 'Configured by ERP5 Configurator',
'role_name_list': role_name_list,
'role_category_list': role_category_list}
mod_conf_list.append(conf_dict)
portal_type_dict[portal_type] = mod_conf_list
## Update fake site
# XXX rafael: improve this, the ignore list is quite ugly.
ignore_list = []
portal_type_id_list = portal.portal_types.objectIds()
for portal_type, role_list in portal_type_dict.items():
for role_dict in role_list:
if portal_type in portal_type_id_list:
portal.portal_types[portal_type].newContent(portal_type='Role Information', \
**role_dict)
else:
ignore_list.append(portal_type)
LOG("CONFIGURATOR", INFO, "Fail to define Roles for %s" % portal_type)
mod_conf_list.append(conf_dict)
portal_type_dict[portal_type] = mod_conf_list
## Update fake site
# XXX rafael: improve this, the ignore list is quite ugly.
ignore_list = []
portal_type_id_list = portal.portal_types.objectIds()
for portal_type, role_list in portal_type_dict.items():
for role_dict in role_list:
if portal_type in portal_type_id_list:
portal.portal_types[portal_type].newContent(portal_type='Role Information', \
**role_dict)
else:
ignore_list.append(portal_type)
LOG("CONFIGURATOR", INFO, "Fail to define Roles for %s" % portal_type)
## Update BT5
bt5_obj = business_configuration.getSpecialiseValue()
# keep existing roles definition (from previous configuration saves)
for existing_type in bt5_obj.getTemplatePortalTypeRoleList():
portal_type_dict[existing_type] = 1
bt5_obj.edit(template_portal_type_role_list=[i for i in portal_type_dict.keys() if i not in ignore_list])
## Update BT5
bt5_obj = business_configuration.getSpecialiseValue()
# keep existing roles definition (from previous configuration saves)
for existing_type in bt5_obj.getTemplatePortalTypeRoleList():
portal_type_dict[existing_type] = 1
bt5_obj.edit(template_portal_type_role_list=[i for i in portal_type_dict.keys() if i not in ignore_list])
return error_list
......@@ -56,21 +56,24 @@ class RuleConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.DublinCore
, PropertySheet.Reference )
def _build(self, business_configuration):
portal = self.getPortalObject()
template_id = self.getId()
def _checkConsistency(self, fixit=False, filter=None, **kw):
if fixit:
portal = self.getPortalObject()
template_id = self.getId()
if getattr(portal.portal_rules, template_id, None) is not None:
cb_data = portal.portal_rules.manage_copyObjects([template_id])
copied, = portal.portal_rules.manage_pasteObjects(cb_data)
rule = portal.portal_rules[copied["new_id"]]
if self.getReference() is not None:
rule.edit(reference=self.getReference())
rule.setVersion(str(int(rule.getVersion(0)) + 1))
if len(self.getTradePhaseList()) > 0:
rule.setTradePhaseList(self.getTradePhaseList())
rule.validate()
else:
raise ValueError("Unable to find rule template with id %s" % template_id)
if getattr(portal.portal_rules, template_id, None) is not None:
cb_data = portal.portal_rules.manage_copyObjects([template_id])
copied, = portal.portal_rules.manage_pasteObjects(cb_data)
rule = portal.portal_rules[copied["new_id"]]
if self.getReference() is not None:
rule.edit(reference=self.getReference())
rule.setVersion(str(int(rule.getVersion(0)) + 1))
if len(self.getTradePhaseList()) > 0:
rule.setTradePhaseList(self.getTradePhaseList())
rule.validate()
else:
raise ValueError("Unable to find rule template with id %s" % template_id)
self.install(rule, business_configuration)
business_configuration = self.getBusinessConfigurationValue()
self.install(rule, business_configuration)
return ['Rule should be defined',]
......@@ -58,29 +58,35 @@ class SaleTradeConditionConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.Reference
)
def _build(self, business_configuration):
portal = self.getPortalObject()
business_process_id = \
business_configuration.getGlobalConfigurationAttr('business_process_id')
def _checkConsistency(self, fixit=False, filter=None, **kw):
if fixit:
portal = self.getPortalObject()
organisation_id = \
business_configuration.getGlobalConfigurationAttr('organisation_id')
business_configuration = self.getBusinessConfigurationValue()
business_process_id = \
business_configuration.getGlobalConfigurationAttr('business_process_id')
currency_id = \
business_configuration.getGlobalConfigurationAttr('currency_id')
organisation_id = \
business_configuration.getGlobalConfigurationAttr('organisation_id')
trade_condition = portal.sale_trade_condition_module.newContent(
portal_type="Sale Trade Condition",
reference=self.getReference(),
title=self.getTitle())
currency_id = \
business_configuration.getGlobalConfigurationAttr('currency_id')
trade_condition.setSpecialise("business_process_module/%s" %\
business_process_id)
trade_condition = portal.sale_trade_condition_module.newContent(
portal_type="Sale Trade Condition",
reference=self.getReference(),
title=self.getTitle())
trade_condition.setSource("organisation_module/%s" % organisation_id)
trade_condition.setSourceSection("organisation_module/%s" % organisation_id)
trade_condition.setPriceCurrency("currency_module/%s" % currency_id)
trade_condition.setSpecialise("business_process_module/%s" %\
business_process_id)
trade_condition.validate(comment=translateString("Validated by Configurator"))
trade_condition.setSource("organisation_module/%s" % organisation_id)
trade_condition.setSourceSection("organisation_module/%s" % organisation_id)
trade_condition.setPriceCurrency("currency_module/%s" % currency_id)
self.install(trade_condition, business_configuration)
trade_condition.validate(comment=translateString("Validated by Configurator"))
self.install(trade_condition, business_configuration)
return ['Sale Trade Condition with reference %s should be created' % \
self.getReference(),]
......@@ -57,21 +57,26 @@ class SecurityCategoryMappingConfiguratorItem(SkinConfiguratorItemMixin,
, PropertySheet.CategoryCore
, PropertySheet.DublinCore
)
def _checkConsistency(self, fixit=False, filter=None, **kw):
script_id = 'ERP5Type_getSecurityCategoryMapping'
error_list = ['%s should be created' % script_id,]
if fixit:
portal_alarms = self.getPortalObject().portal_alarms
script_content = """return (
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['function']),
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['follow_up']),
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['function', 'follow_up']),
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['group']),
('ERP5Type_getSecurityCategoryRoot', ['group']),
)"""
def _build(self, business_configuration):
portal_alarms = self.getPortalObject().portal_alarms
script_content = """return (
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['function']),
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['follow_up']),
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['function', 'follow_up']),
('ERP5Type_getSecurityCategoryFromAssignmentStrict', ['group']),
('ERP5Type_getSecurityCategoryRoot', ['group']),
)"""
folder = self._createSkinFolder()
self._createZODBPythonScript(folder,
script_id,
'', script_content)
folder = self._createSkinFolder()
self._createZODBPythonScript(folder,
'ERP5Type_getSecurityCategoryMapping',
'', script_content)
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(folder, business_configuration)
## add to customer template
self.install(folder, business_configuration)
return error_list
......@@ -57,8 +57,9 @@ class ServiceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.DublinCore
, PropertySheet.ConfiguratorItem )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal = self.getPortalObject()
error_list = []
for service_id, service_dict in iter(self.getConfigurationListList()):
if isinstance(service_dict, basestring):
warn(DeprecationWarning,
......@@ -67,9 +68,16 @@ class ServiceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
document = getattr(portal.service_module, service_id, None)
if document is None:
document = portal.service_module.newContent(portal_type='Service',
id=service_id, **service_dict)
document.validate(comment=translateString("Validated by Configurator"))
error_list.append(self._createConstraintMessage(
"Service %s should be created"))
if fixit:
document = portal.service_module.newContent(portal_type='Service',
id=service_id, **service_dict)
document.validate(comment=translateString("Validated by Configurator"))
## add to customer template
self.install(document, business_configuration)
if document:
## add to customer template
business_configuration = self.getBusinessConfigurationValue()
self.install(document, business_configuration)
return error_list
......@@ -55,14 +55,19 @@ class SitePropertyConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.DublinCore
, PropertySheet.ConfiguratorItem )
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
portal = self.getPortalObject()
id_list = []
for id, value, prop_type in self.getConfigurationList():
if portal.hasProperty(id):
portal._delProperty(id)
portal._setProperty(id, value, type=prop_type)
if fixit:
if portal.hasProperty(id):
portal._delProperty(id)
portal._setProperty(id, value, type=prop_type)
id_list.append(id)
bt = business_configuration.getSpecialiseValue()
bt.edit(template_site_property_id_list=id_list)
if fixit:
business_configuration = self.getBusinessConfigurationValue()
bt = business_configuration.getSpecialiseValue()
bt.edit(template_site_property_id_list=id_list)
return ["The property %s should set on portal" % id for id in id_list]
......@@ -54,28 +54,32 @@ class SolverConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
portal = self.getPortalObject()
def _checkConsistency(self, fixit=False, filter=None, **kw):
if fixit:
portal = self.getPortalObject()
business_configuration = self.getBusinessConfigurationValue()
solver = getattr(portal.portal_solvers, self.getId(), None)
if solver is None:
solver_property_dict = \
business_configuration.BusinessConfiguration_getSolverPropertyDict()
property_dict = solver_property_dict.get(self.getId())
argument_dict = {}
solver = getattr(portal.portal_solvers, self.getId(), None)
if solver is None:
solver_property_dict = \
business_configuration.BusinessConfiguration_getSolverPropertyDict()
property_dict = solver_property_dict.get(self.getId())
argument_dict = {}
for k, v in property_dict.iteritems():
if k not in ("content_list",) and k in self.showDict():
argument_dict[k] = v
solver = portal.portal_solvers.newContent(portal_type="Solver Type",
id=argument_dict.pop('id'))
solver.edit(**argument_dict)
for k, v in property_dict.iteritems():
if k not in ("content_list",) and k in self.showDict():
argument_dict[k] = v
for information_dict in self.content_list:
portal_type = information_dict.pop('portal_type')
id = information_dict.pop('id')
action = solver.newContent(portal_type=portal_type, id=id)
action.edit(**information_dict)
solver = portal.portal_solvers.newContent(portal_type="Solver Type",
id=argument_dict.pop('id'))
solver.edit(**argument_dict)
self.install(solver, business_configuration)
for information_dict in self.content_list:
portal_type = information_dict.pop('portal_type')
id = information_dict.pop('id')
action = solver.newContent(portal_type=portal_type, id=id)
action.edit(**information_dict)
self.install(solver, business_configuration)
return ['Solvers should be created',]
......@@ -59,14 +59,14 @@ class StandardBT5ConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.StandardBT5ConfiguratorItem
)
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
template_tool = self.getPortalObject().portal_templates
bt5_id = self.getBt5Id().split('.')[0]
if bt5_id in template_tool.getInstalledBusinessTemplateTitleList():
LOG("StandardBT5ConfiguratorItem", INFO,
"Business Template already Installed: %s for %s" % (bt5_id, self.getRelativeUrl()))
return
return []
def _getRepositoryBusinessTemplateTitleList():
return [bt.getTitle() for bt in \
......@@ -77,15 +77,13 @@ class StandardBT5ConfiguratorItem(ConfiguratorItemMixin, XMLObject):
cache_factory='erp5_content_long')()
if bt5_id in repository_bt_title_list:
template_tool.installBusinessTemplateListFromRepository([bt5_id],
update_catalog=self.getUpdateCatalog(0),
install_dependency=self.getInstallDependency(1),
activate=True)
if fixit:
template_tool.installBusinessTemplateListFromRepository([bt5_id],
update_catalog=self.getUpdateCatalog(0),
install_dependency=self.getInstallDependency(1),
activate=True)
LOG("StandardBT5ConfiguratorItem", INFO,
"Install %s for %s" % (bt5_id, self.getRelativeUrl()))
return
return [self._createConstraintMessage('%s should be installed' % bt5_id),]
raise ValueError("The business template %s was not found on available \
sources." % bt5_id)
......@@ -72,16 +72,22 @@ class SystemPreferenceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
property_id_list.append('%s%s' % (prop.getReference(), list_prefix))
return property_id_list
def _build(self, business_configuration):
def _checkConsistency(self, fixit=False, filter=None, **kw):
error_list = []
portal = self.getPortalObject()
preference = portal.portal_preferences._getOb(self.object_id, None)
if preference is None:
preference = portal.portal_preferences.newContent(
portal_type = 'System Preference',
id = self.object_id,
title = self.title,
description = self.description,
priority = 1)
error_list.append(self._createConstraintMessage(
"System Preference %s should be created" % self.object_id))
if fixit:
preference = portal.portal_preferences.newContent(
portal_type = 'System Preference',
id = self.object_id,
title = self.title,
description = self.description,
priority = 1)
else:
return error_list
preference_dict = {}
......@@ -96,9 +102,11 @@ class SystemPreferenceConfiguratorItem(ConfiguratorItemMixin, XMLObject):
preference.enable()
preference.edit(**preference_dict)
business_configuration = self.getBusinessConfigurationValue()
bt5_obj = business_configuration.getSpecialiseValue()
current_template_preference_list = list(bt5_obj.getTemplatePreferenceList())
if preference.getId() not in current_template_preference_list:
current_template_preference_list.append(preference.getId())
bt5_obj.edit(template_preference_list=current_template_preference_list,)
return error_list
......@@ -54,74 +54,76 @@ class WorkflowSecurityConfiguratorItem(ConfiguratorItemMixin, XMLObject):
, PropertySheet.CategoryCore
, PropertySheet.DublinCore )
def _build(self, business_configuration):
## NOT TESTED
return
table_dict = business_configuration.ConfigurationTemplate_readOOCalcFile(self.filename)
portal = self.getPortalObject()
suffix = '_security'
suffix_len = len(suffix)
if self.filename[-suffix_len:] == suffix:
workflow_id = self.filename[:-suffix_len]
else:
raise "NoValidName"
def _checkConsistency(self, fixit=False, filter=None, **kw):
return []
if fixit:
## NOT TESTED
business_configuration = self.getBusinessConfigurationValue()
table_dict = business_configuration.ConfigurationTemplate_readOOCalcFile(self.filename)
portal = self.getPortalObject()
suffix = '_security'
suffix_len = len(suffix)
if self.filename[-suffix_len:] == suffix:
workflow_id = self.filename[:-suffix_len]
else:
raise "NoValidName"
# Configure state permission
view_permission_list = ['View']
access_permission_list = ['Access contents information']
modify_permission_list = ['Modify portal content']
add_content_permission_list = ['Add portal content']
# Configure list of variable on the workflow
permission_list = view_permission_list + \
access_permission_list + \
modify_permission_list + \
add_content_permission_list
# Remove permission list
workflow = portal.portal_workflow[workflow_id]
workflow.delManagedPermissions(workflow.permissions)
# Add new permission list
for permission in permission_list:
workflow.addManagedPermission(permission)
# Configure state permission matrix
state_list = table_dict['state']
for state_config in state_list:
state_id = state_config.pop('state')
state = workflow.states[state_id]
# Clean the state matrix
# Configure state permission
view_permission_list = ['View']
access_permission_list = ['Access contents information']
modify_permission_list = ['Modify portal content']
add_content_permission_list = ['Add portal content']
# Configure list of variable on the workflow
permission_list = view_permission_list + \
access_permission_list + \
modify_permission_list + \
add_content_permission_list
# Remove permission list
workflow = portal.portal_workflow[workflow_id]
workflow.delManagedPermissions(workflow.permissions)
# Add new permission list
for permission in permission_list:
state.setPermission(permission, 0, [])
# Update state matrix
permission_dict = dict([(x, []) for x in permission_list])
for role, perm_symbol in state_config.items():
managed_permission_list = []
if 'A' in perm_symbol:
managed_permission_list.extend(access_permission_list)
if 'V' in perm_symbol:
managed_permission_list.extend(view_permission_list)
if 'C' in perm_symbol:
managed_permission_list.extend(add_content_permission_list)
if 'M' in perm_symbol:
managed_permission_list.extend(modify_permission_list)
for permission in managed_permission_list:
permission_dict[permission].append(role.capitalize())
for permission, roles in permission_dict.items():
state.setPermission(permission, 0, roles)
# XXX To be deleted
# for permission in permission_list:
# module.manage_permission(permission, ['Manager'], 0)
workflow.addManagedPermission(permission)
# Configure state permission matrix
state_list = table_dict['state']
for state_config in state_list:
state_id = state_config.pop('state')
state = workflow.states[state_id]
# Clean the state matrix
for permission in permission_list:
state.setPermission(permission, 0, [])
# Update state matrix
permission_dict = dict([(x, []) for x in permission_list])
for role, perm_symbol in state_config.items():
managed_permission_list = []
if 'A' in perm_symbol:
managed_permission_list.extend(access_permission_list)
if 'V' in perm_symbol:
managed_permission_list.extend(view_permission_list)
if 'C' in perm_symbol:
managed_permission_list.extend(add_content_permission_list)
if 'M' in perm_symbol:
managed_permission_list.extend(modify_permission_list)
for permission in managed_permission_list:
permission_dict[permission].append(role.capitalize())
for permission, roles in permission_dict.items():
state.setPermission(permission, 0, roles)
# XXX To be deleted
# for permission in permission_list:
# module.manage_permission(permission, ['Manager'], 0)
# Configure transition guard
transition_list = table_dict['transition']
for transition_conf in transition_list:
transition_id = transition_conf.pop('transition')
transition = workflow.transitions[transition_id]
guard = transition.getGuard()
role_list = [x.capitalize() for x in transition_conf.keys()]
role_string = ';'.join(role_list)
guard.changeFromProperties({'guard_roles': role_string})
# Update business template
bt5_obj = business_configuration.getSpecialiseValue()
template_workflow_id_list = list(bt5_obj.getTemplateWorkflowIdList())
if workflow_id not in template_workflow_id_list:
template_workflow_id_list.append(workflow_id)
bt5_obj.edit(template_workflow_id_list=template_workflow_id_list,)
# Configure transition guard
transition_list = table_dict['transition']
for transition_conf in transition_list:
transition_id = transition_conf.pop('transition')
transition = workflow.transitions[transition_id]
guard = transition.getGuard()
role_list = [x.capitalize() for x in transition_conf.keys()]
role_string = ';'.join(role_list)
guard.changeFromProperties({'guard_roles': role_string})
# Update business template
bt5_obj = business_configuration.getSpecialiseValue()
template_workflow_id_list = list(bt5_obj.getTemplateWorkflowIdList())
if workflow_id not in template_workflow_id_list:
template_workflow_id_list.append(workflow_id)
bt5_obj.edit(template_workflow_id_list=template_workflow_id_list,)
......@@ -28,12 +28,25 @@
#
##############################################################################
from Products.ERP5Type.ConsistencyMessage import ConsistencyMessage
from Products.ERP5Type.Base import Base
from zLOG import LOG, INFO
import time
class ConfiguratorItemMixin:
""" This is the base class for all configurator item. """
def getBusinessConfigurationValue(self):
item = self
while item.getPortalType() != 'Business Configuration':
item = item.getParentValue()
return item
def _createConstraintMessage(self, message):
return ConsistencyMessage(self,
object_relative_url=self.getRelativeUrl(),
message=message)
def install(self, document, business_configuration, prefix=''):
""" Add object to customer customization template. """
bt5_obj = business_configuration.getSpecialiseValue()
......@@ -52,25 +65,6 @@ class ConfiguratorItemMixin:
current_template_path_list.extend(template_path_list)
bt5_obj.edit(template_path_list=current_template_path_list)
def addToCustomerBT5ByRelativeUrl(self, business_configuration,
relative_url_list):
""" Add object to customer customization template object by
its relative url. """
bt5_obj = business_configuration.getSpecialiseValue()
current_template_path_list = list(bt5_obj.getTemplatePathList())
current_template_path_list.extend(relative_url_list)
bt5_obj.edit(template_path_list=current_template_path_list)
def build(self, business_configuration_relative_url):
""" Invoke build process """
business_configuration = self.getPortalObject().restrictedTraverse(\
business_configuration_relative_url)
LOG('CONFIGURATOR', INFO, 'Building --> %s' % self)
start_build = time.time()
result = self._build(business_configuration)
LOG('CONFIGURATOR', INFO, 'Built --> %s (%.02fs)' % (self,
time.time()-start_build))
return result
class SkinConfiguratorItemMixin(ConfiguratorItemMixin):
""" Mixin which allows to create python scripts and/or skin
......
......@@ -89,7 +89,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
group=group_id, site='main', **kw)
self.tic()
item._build(configuration_save.getParentValue())
item.fixConsistency()
self.tic()
organisation = self.portal.portal_catalog.getResultValue(
......@@ -139,7 +139,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
title="title_%s" % category_id_1)
self.tic()
item0._build(bc)
item0.fixConsistency()
self.tic()
category_0 = getattr(self.portal.portal_categories.group, category_id_0, None)
......@@ -149,7 +149,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
category_1 = getattr(self.portal.portal_categories.group, category_id_1, None)
self.assertEqual(category_1, None)
item1._build(bc)
item1.fixConsistency()
self.tic()
category_1 = getattr(self.portal.portal_categories.group, category_id_1, None)
......@@ -164,7 +164,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
object_id=category_id_1,
title="new_title_%s" % category_id_1)
item2._build(bc)
item2.fixConsistency()
self.tic()
category_1 = getattr(self.portal.portal_categories.group,
......@@ -195,7 +195,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
self.tic()
item_eur._build(bc)
item_eur.fixConsistency()
self.tic()
eur = getattr(self.portal.currency_module, eur_currency_id , None)
......@@ -205,7 +205,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
brl = getattr(self.portal.currency_module, brl_currency_id , None)
self.assertEqual(brl, None)
item_brl._build(bc)
item_brl.fixConsistency()
self.tic()
brl = getattr(self.portal.currency_module, brl_currency_id , None)
......@@ -214,9 +214,9 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
# Build several times to not break portal.
item_brl._build(bc)
item_brl.fixConsistency()
self.tic()
item_brl._build(bc)
item_brl.fixConsistency()
self.tic()
def testSecurityCategoryMappingConfiguratorItem(self):
......@@ -240,7 +240,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
"Security Category Mapping Configurator Item")
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
# XXX Skin folder should be part of configuration and not always custom
......@@ -267,7 +267,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
"Account Configurator Item", **account_dict)
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
account = getattr(account_module, account_dict['account_id'], None)
......@@ -289,7 +289,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
"Account Configurator Item", **account_dict)
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
same_account = getattr(account_module, account_dict['account_id'], None)
......@@ -327,7 +327,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
property_map["active_sense_method_id"],
"", "context.setEnabled(0)")
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
alarm = getattr(self.portal.portal_alarms, "my_test_alarm", None)
......@@ -394,7 +394,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
person_module_type.manage_delObjects([i.id for i in role_list])
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
role_list = [i for i in person_type.objectValues(
......@@ -449,7 +449,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
configuration_spreadsheet_data = data)
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
base_category_list = ["group", "site", "business_application",
......@@ -499,7 +499,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
id = "rule_do_not_exist")
self.tic()
self.assertRaises(ValueError, item._build, bc)
self.assertRaises(ValueError, item.fixConsistency)
rule_reference = "testing_configurator_rule_%s" % self.newUniqueUID()
item = configuration_save.addConfigurationItem(
......@@ -509,7 +509,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
trade_phase_list = ['testing/order'])
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
template_id = item.getId()
......@@ -541,7 +541,7 @@ class TestConfiguratorItem(TestLiveConfiguratorWorkflowMixin):
reference = reference)
self.tic()
item._build(bc)
item.fixConsistency()
self.tic()
business_process = self.portal.portal_catalog.getResultValue(
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment