BusinessConfiguration.py 19.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
##############################################################################
#
# Copyright (c) 2006 Nexedi SARL and Contributors. All Rights Reserved.
#                    Romain Courteaud <romain@nexedi.com>
#                    Ivan Tyagov <ivan@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import time
from AccessControl import ClassSecurityInfo
from Globals import PersistentMapping
from Acquisition import aq_base
from Products.ERP5Type import Permissions, PropertySheet
from zLOG import LOG, INFO
from cStringIO import StringIO

from Products.ERP5Configurator.Tool.ConfiguratorTool import _validateFormToRequest
from Products.ERP5.Document.Item import Item

## Workflow states definitions
INITIAL_STATE_TITLE = 'Start'
DOWNLOAD_STATE_TITLE = 'Download'
END_STATE_TITLE = 'End'

46
class BusinessConfiguration(Item):
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
  """
    BusinessConfiguration store the values enter by the wizard. 
  """

  meta_type = 'ERP5 Business Configuration'
  portal_type = 'Business Configuration'
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Item
                    , PropertySheet.Arrow
                    , PropertySheet.BusinessConfiguration
                    , PropertySheet.Comment
                    , PropertySheet.Version
                    )

  security.declareProtected(Permissions.View, 'isInitialConfigurationState')
  def isInitialConfigurationState(self):
    """ Check if the Business Configuration is on initial workflow state
    """
77
    workflow = self.getResourceValue()
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    if workflow is not None:
      return self.getCurrentState() == workflow.getSource()
    return None

  security.declareProtected(Permissions.View, 'isDownloadConfigurationState')
  def isDownloadConfigurationState(self):
    """ Check if the Business Configuration is on Download State
    """
    return self.getCurrentStateTitle() == DOWNLOAD_STATE_TITLE 

  security.declareProtected(Permissions.View, 'isEndConfigurationState')
  def isEndConfigurationState(self):
    """ Check if the Business Configuration is on End State
    """
    return self.getCurrentStateTitle() == END_STATE_TITLE

  security.declareProtected(Permissions.View, 'getNextTransition')
  def getNextTransition(self):
    """ Return next transition. """
    current_state = self.getCurrentStateValue()
    if current_state is None:
      return None
    transition_list = current_state.getAvailableTransitionList(self)
    transition_number = len(transition_list)
    if transition_number > 1:
      raise TypeError, "More than one transition is available."
    elif transition_number == 0:
      return None
106

107 108 109 110 111 112 113 114 115 116 117 118 119 120
    return transition_list[0]

  security.declarePrivate('_executeTransition')
  def _executeTransition(self, \
                        form_kw=None,
                        request_kw=None):
    """ Execute the transition. """
    if form_kw is None:
      form_kw = {}
    current_state = self.getCurrentStateValue()
    transition = self.getNextTransition()
    next_state = self.unrestrictedTraverse(transition.getDestination())
    ## it's possible that we have already saved a configuration save object 
    ## in workflow_history for this state so we use it
121 122
    configuration_save = self._getConfSaveForStateFromWorkflowHistory()
    if configuration_save is None:
123
      ## we haven't saved any configuration save for this state so create new one
124
      configuration_save = self.newContent(portal_type='Configuration Save')
125 126 127
    else:
      ## we have already created configuration save for this state
      ## so remove from it already existing configuration items
128
      if configuration_save != self:  # don't delete ourselves
129
        existing_conf_items = configuration_save.objectIds()
130
        existing_conf_items = map(None, existing_conf_items)
131 132 133 134 135 136 137
        configuration_save.manage_delObjects(existing_conf_items)

    modified_form_kw = {}
    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) 
138
    ## Add some variables so we can get use them in workflow after scripts
139
    form_kw['configuration_save_url'] = configuration_save.getRelativeUrl()
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    form_kw['transition'] = transition.getRelativeUrl()
    current_state.executeTransition(transition, self, form_kw=form_kw)

  security.declarePrivate('_displayNextForm')
  def _displayNextForm(self, \
                       validation_errors=None, \
                       context=None, \
                       transition=None):
    """ Render next form. """
    if transition is None:
      transition = self.getNextTransition()
    while transition is not None:
      form_id = transition.getTransitionFormId()
      current_state = self.getCurrentStateValue()
      if self.isDownloadConfigurationState():
        ## exec next transition for this business configuration 
        self._executeTransition()
        transition = self.getNextTransition()
        return None, None, None, None, None
      if form_id is None:
        ## go on until you find a form
        self._executeTransition()
        transition = self.getNextTransition()
      else:
        if context is None:
          ## examine workflow_history for already saved 
          ## 'Configuration Save' objects for this state
          context = self._getConfSaveForStateFromWorkflowHistory()
        ## get form object in a proper context
        form_html, form_title = self._renderFormInContext(form_id, context, validation_errors)
        ## check if we've can shown 'Previous' button
        previous = None
        translate = self.Base_translateString
        if self._isAlreadyConfSaveInWorkflowHistory(transition):
          previous = translate("Previous")
        return previous, form_html, form_title, \
               translate(transition.getTitle()), self.getServerBuffer()

  security.declarePrivate('_renderFormInContext')
  def _renderFormInContext(self, form_id, context, validation_errors):
    html = ""
    html_forms = []
    isMultiEntryTransition = self._isMultiEntryTransition()
    forms_number = isMultiEntryTransition
    if context is None:
      form = getattr(self, form_id)
      if not isMultiEntryTransition:
        if validation_errors is not None:
          self.REQUEST.set('field_errors', form.ErrorFields(validation_errors))
        html = form()
      else:
        template_html = form()
        for form_counter in range(0, forms_number):
          form_html = self.Base_mainConfiguratorFormTemplate(
194 195 196 197
                                  current_form_number=form_counter + 1,
                                  max_form_numbers=forms_number,
                                  form_title=form.title,                               
                                  form_html=template_html)
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
          html_forms.append(form_html)
    else:
      if not isMultiEntryTransition:
        ## only one form saved under this context
        form = getattr(context, form_id)
        if validation_errors is not None:
          self.REQUEST.set('field_errors', form.ErrorFields(validation_errors))
        html = form()
      else:
        ## we have many forms saved under this context
        form = getattr(self, form_id)
        field_ids = form.get_fields()
        for form_counter in range(0, forms_number):
          ## fill REQUEST with data as it will be used to render form
          for field in field_ids:
213
            field_value = getattr(context, "field_%s" % field.id, None)
214 215 216 217 218 219
            if field_value is not None and len(field_value) > form_counter:
              field_value = field_value[form_counter]
              self.REQUEST.set(field.id, field_value)
            else:
              self.REQUEST.set(field.id, '')
          form_html = self.Base_mainConfiguratorFormTemplate( \
220
                             current_form_number=form_counter + 1,\
Rafael Monnerat's avatar
Rafael Monnerat committed
221 222
                             max_form_numbers=forms_number,\
                             form_html=getattr(context, form_id)())
223
          html_forms.append(form_html)
224
    if html_forms != []:
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      html = "\n".join(html_forms)
    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()   
    for wh in workflow_history:
      ## go one step back
      current_state = self.getCurrentStateValue()
      current_state.undoTransition(self)
      transition = self.unrestrictedTraverse(wh['transition'])
      conf_save = self.unrestrictedTraverse(wh['configuration_save_url'])
      ## check if this transition can be shown to user ...
      if transition._checkPermission(self) and \
           transition.getTransitionFormId() is not None:
        return  self._displayNextForm(context=conf_save, transition=transition)
Rafael Monnerat's avatar
Rafael Monnerat committed
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
  security.declarePrivate('_validateNextForm')
  def _validateNextForm(self, **kw):
    """ Validate the form displayed to the user. """
    REQUEST = self.REQUEST
    form = getattr(self, self.getNextTransition().getTransitionFormId())
    return _validateFormToRequest(form, REQUEST, **kw)

  #############
  ## misc    ##
  #############
  security.declarePrivate('_getConfigurationStack')
  def _getConfigurationStack(self):
    """ Return list of created by client configuration save objects 
        sort on id which is an integer. """
    result = self.objectValues('ERP5 Configuration Save')
    result = map(None, result)
    result.sort(lambda x, y: cmp(x.getIntIndex(x.getIntId()),
                                 y.getIntIndex(y.getIntId())))
    return result

  security.declarePrivate('_getConfSaveForStateFromWorkflowHistory')
  def _getConfSaveForStateFromWorkflowHistory(self):
    """ Get from workflow history configuration save for this state """
    configuration_save = None
    current_state = self.getCurrentStateValue()
    transition = self.getNextTransition()
    next_state = self.unrestrictedTraverse(transition.getDestination())
    workflow_history = current_state.getWorkflowHistory(self)
    for wh in workflow_history:
      wh_state = self.unrestrictedTraverse(wh['current_state'])
      if wh_state == next_state:
        configuration_save = self.unrestrictedTraverse(wh['configuration_save_url'])
    return configuration_save

  security.declarePrivate('_isAlreadyConfSaveInWorkflowHistory')
  def _isAlreadyConfSaveInWorkflowHistory(self, transition):
    """ check if we have an entry in worklow history for this state """
    workflow_history = self.getCurrentStateValue().getWorkflowHistory(self, remove_undo=1)
    workflow_history.reverse()
    for wh in workflow_history:
      wh_state = self.unrestrictedTraverse(wh['current_state'])
      for wh_transition in wh_state.getAvailableTransitionList(self):
287 288
        if wh_transition.getTransitionFormId() is not None and \
           wh_transition != transition:
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
          return True
    return False

  security.declarePrivate('_isMultiEntryTransition')
  def _isMultiEntryTransition(self):
    """ Return number of multiple forms to show for a transition. """
    next_transition = self.getNextTransition()
    if next_transition is not None:
      if getattr(aq_base(self), '_multi_entry_transitions', None) is not None:
        multi_forms = self._multi_entry_transitions.get(next_transition.getRelativeUrl(), 0)
        if multi_forms == 1:
          # we have set '1' which means show one form which is not multiple forms
          multi_forms = 0
        return multi_forms
      else:
        return 0
    else:
      ## no transitions available
      return 0

  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 
        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:
      self._multi_entry_transitions = PersistentMapping()
    self._multi_entry_transitions[transition_url] = max_entry_number

  security.declareProtected(Permissions.ModifyPortalContent, 'setServerBuffer')
  def setServerBuffer(self, **kw):
    """ Set what we should return to client. """
    if getattr(aq_base(self), '_server_buffer', None) is None:
      self._server_buffer = {}
    for item, value in kw.items():
      self._server_buffer[item] = value
    self._p_changed = 1

  security.declareProtected(Permissions.View, 'getServerBuffer')
  def getServerBuffer(self):
    """ Get return buffer which will be sent to client and 
    afterwards deleted. """
    server_buffer = getattr(aq_base(self), '_server_buffer', {})
    self._server_buffer = {}
    return server_buffer

  security.declareProtected(Permissions.ModifyPortalContent, 'setGlobalConfigurationAttr')
  def setGlobalConfigurationAttr(self, **kw):
    """ Set global business configuration attribute. """
    if getattr(aq_base(self),
               '_global_configuration_attributes', None) is None:
      self._global_configuration_attributes = PersistentMapping()
    for key, value in kw.items():
      self._global_configuration_attributes[key] = value

  security.declareProtected(Permissions.View, 'getGlobalConfigurationAttr')
Rafael Monnerat's avatar
Rafael Monnerat committed
345
  def getGlobalConfigurationAttr(self, key, default=None):
346 347 348 349 350 351 352 353 354 355 356
    """ Get global business configuration attribute. """
    global_configuration_attributes = getattr(self, '_global_configuration_attributes', {})
    return global_configuration_attributes.get(key, default)

  security.declareProtected(Permissions.View, 'getBuiltBusinessConfigurationBT5List')
  def getBuiltBusinessConfigurationBT5List(self):
    """
      Get list of built business templates in a Wizard format.
    """
    bt5_file_list = []
    for bt_link in self.contentValues(portal_type="Link"):
Rafael Monnerat's avatar
Rafael Monnerat committed
357 358
      bt5_item = dict(bt5_id=bt_link.getUrlString(), 
                      bt5_filedata="")
359 360 361
      bt5_file_list.append(bt5_item)

    for bt_file in self.contentValues(portal_type="File"):
Rafael Monnerat's avatar
Rafael Monnerat committed
362 363
      bt5_item = dict(bt5_id=bt_file.getId(),
                      bt5_filedata=bt_file.getData())
364 365 366 367 368 369 370 371 372 373 374 375
      bt5_file_list.append(bt5_item)
    return bt5_file_list

  ############# Instance and Business Configuration ########################
  security.declareProtected(Permissions.ModifyPortalContent, 'buildConfiguration')
  def buildConfiguration(self):
    """ 
      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 
      actions and Configurator requets
    """
376
    kw = dict(tag="start")
377 378 379 380
    start = time.time()
    LOG("CONFIGURATOR", INFO, 
        'Build process started for %s' % self.getRelativeUrl())
    # build
381
    for configuration_save in self._getConfigurationStack():
382
      # XXX: check which items are configure-able
383
      configuration_item_list = [x for x in configuration_save.contentValues()]
Rafael Monnerat's avatar
Rafael Monnerat committed
384
      configuration_item_list.sort(lambda x, y: cmp(x.getIntId(), y.getIntId()))
385 386 387 388 389
      for configurator_item in configuration_item_list:
        configurator_item.activate(**kw).buildItem(self.getRelativeUrl())
        kw["after_tag"] = kw["tag"]
        kw["tag"] = "configurator_item_%s_%s" % (configurator_item.getId(),
                                                 configurator_item.getUid())
Rafael Monnerat's avatar
Rafael Monnerat committed
390

391
    LOG('CONFIGURATOR', INFO, 
392 393
        'Build process started for %s ended after %.02fs' % (self.getRelativeUrl(),
                                                             time.time() - start))
394 395 396 397 398 399 400 401

  security.declareProtected(Permissions.ModifyPortalContent, 'resetBusinessConfiguration')
  def resetBusinessConfiguration(self):
    """ 
      Reset Business Confiration at server side.
      Remove all traces from user input (i.e. Configuration Saves, workflow history).
    """
    object_ids = []
Rafael Monnerat's avatar
Rafael Monnerat committed
402
    for obj in self.contentValues(filter={'portal_type': ['Configuration Save', 'File', 'Link']}):
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
      object_ids.append(obj.getId())
    self.manage_delObjects(object_ids)
    del self.workflow_history
    # ERP5 Workflow initialization
    erp5_workflow = self.getResourceValue()
    erp5_workflow.initializeDocument(self)

  def isStandardBT5(self, bt5_id):
    """Is bt5_id standard gzipped bt5 id?
       Use ERP5 site portal_templates to get list of bt5_ids from configured
       repository. This relies on the fact that the host site have a
       configured repository.
    """
    # XXX This should be one API from portal_templates
    bt5_title_list = []
    bt5_title = bt5_id.split('.')[0]
    for bt5 in self.getPortalObject().portal_templates\
        .getRepositoryBusinessTemplateList():
      bt5_title_list.append(bt5.getTitle())
    return bt5_title in bt5_title_list

  security.declareProtected(Permissions.ModifyPortalContent, 'installConfiguration')
Rafael Monnerat's avatar
Rafael Monnerat committed
425
  def installConfiguration(self, execute_after_setup_script=1):
426 427 428 429
    """ 
      Install in remote instance already built list of business templates 
      which are saved in the Business Configuration.
    """
430
    kw = dict(tag="install_start")
431 432
    portal = self.getPortalObject()
    for bt_file in self.contentValues(portal_type="File"):
433 434 435
      # Only install business templates which are not the one created by 
      # Configuration.
      if bt_file.getTitle("").replace(".bt5", "") != self.getSpecialiseTitle():
436 437
        bt5_io = StringIO(str(bt_file.getData()))
        LOG("Business Configuration", INFO, 
438
            "Import of bt5 file (%s - %s)" % \
439 440 441 442 443 444 445 446 447
                                      (bt_file.getId(), bt_file.getTitle()))

        bc = portal.portal_templates.importFile(import_file=bt5_io,
                                         batch_mode=1)
        bc.activate(**kw).install()
        kw["after_tag"] = kw["tag"]
        kw["tag"] = bt_file.getTitle()

    if execute_after_setup_script:
448
      kw["after_method_id"] = ["buildItem", 'recursiveReindexObject']
449
      self.activate(**kw).ERP5Site_afterConfigurationSetup()
450 451 452 453
      LOG("Business Configuration", INFO,
          "After setup script called (force) for %s : %s" %
                    (self.getRelativeUrl(), self.getSpecialise()))