TransformationSourcingRule.py 11.2 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
Romain Courteaud's avatar
Romain Courteaud committed
3
# Copyright (c) 2002, 2005 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Romain Courteaud's avatar
Romain Courteaud committed
5
#                    Romain Courteaud <romain@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#
# 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.
#
##############################################################################

Romain Courteaud's avatar
Romain Courteaud committed
30 31
import ExtensionClass

Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33 34 35 36 37 38 39 40
from AccessControl import ClassSecurityInfo
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
from Products.CMFCore.utils import getToolByName

from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5.Document.Rule import Rule

from zLOG import LOG

41 42 43
class ProductionOrderError(Exception): pass
class TransformationSourcingRuleError(Exception): pass

Romain Courteaud's avatar
Romain Courteaud committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
class TransformationSourcingRuleMixin(ExtensionClass.Base):
  """
    Mixin class used by TransformationSourcingRule and TransformationRule
  """
  # Declarative security
  security = ClassSecurityInfo()

  security.declareProtected(Permissions.View,
                            'getSupplyChain')
  def getSupplyChain(self, applied_rule):
    """
      Get the SupplyChain.
    """
    # Get the SupplyChain to use
    supply_chain_portal_type = "Supply Chain"
    order = applied_rule.getRootAppliedRule().getCausalityValue()
    supply_chain = order.getSpecialiseValue(
                               portal_type=supply_chain_portal_type)
    if supply_chain is None:
63
      raise ProductionOrderError,\
Romain Courteaud's avatar
Romain Courteaud committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
            "No SupplyChain defined on %s" % str(order)
    else:
      return supply_chain

  def getCurrentSupplyLink(self, movement):
    """
      Get the current SupplyLink
    """
    # Get the current supply link
    supply_link_portal_type = "Supply Link"
    current_supply_link = movement.getCausalityValue(
                                  portal_type=supply_link_portal_type)
    return current_supply_link

  security.declareProtected(Permissions.ModifyPortalContent, 
                            '_buildMovementList')
80
  def _buildMovementList(self, applied_rule, movement_dict,activate_kw=None,**kw):
Romain Courteaud's avatar
Romain Courteaud committed
81 82 83 84 85 86 87 88 89 90 91 92
    """
      For each movement in the dictionnary, test if the movement already
      exists.
      If not, create it.
      Then, update the movement attributes.
    """
    for movement_id in movement_dict.keys():
      movement = applied_rule.get(movement_id)
      # Create the movement if it does not exist
      if movement is None:
        movement = applied_rule.newContent(
                        portal_type=self.simulation_movement_portal_type,
93 94
                        id=movement_id,
                        activate_kw=activate_kw
Romain Courteaud's avatar
Romain Courteaud committed
95 96 97 98
        )
      # Update movement properties
      movement.edit(**(movement_dict[movement_id]))

99
  security.declareProtected(Permissions.View, 'getTransformation')
100
  def getTransformation(self, movement):
101 102 103
    """
    Get transformation related to used by the applied rule.
    """
104
    production_order_movement = movement.getRootSimulationMovement().\
105 106
                                                   getOrderValue()
    # XXX Acquisition can be use instead
107
    parent_uid = production_order_movement.getParentUid()
108 109 110 111
    explanation_uid = production_order_movement.getExplanationUid()
    if parent_uid == explanation_uid:
      production_order_line = production_order_movement
    else:
112
      production_order_line = production_order_movement.getParentValue()
Romain Courteaud's avatar
Romain Courteaud committed
113
    script = production_order_line._getTypeBasedMethod('_getTransformation') 
114 115
    if script is not None:
      transformation = script()
116
    else:
117 118 119 120 121 122 123
      line_transformation = production_order_line.objectValues(
                portal_type=self.getPortalTransformationTypeList())
      if len(line_transformation)==1:
        transformation = line_transformation[0]
      else:
        transformation = production_order_line.getSpecialiseValue(
                           portal_type=self.getPortalTransformationTypeList())
124 125
    return transformation

Jean-Paul Smets's avatar
Jean-Paul Smets committed
126 127 128 129 130 131 132 133 134 135
class TransformationSourcingRule(Rule):
    """
      Transformation Sourcing Rule object make sure
      items required in a Transformation are sourced
    """
    # CMF Type Definition
    meta_type = 'ERP5 Transformation Sourcing Rule'
    portal_type = 'Transformation Sourcing Rule'
    # Declarative security
    security = ClassSecurityInfo()
136
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jérome Perrin's avatar
Jérome Perrin committed
137 138
    __implements__ = ( Interface.Predicate,
                       Interface.Rule )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
139 140 141 142 143 144
    # Default Properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
                      )
Romain Courteaud's avatar
Romain Courteaud committed
145 146
    # Class variable 
    simulation_movement_portal_type = "Simulation Movement"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
147

148
    def _test(self, movement):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
149 150 151
      """
        Tests if the rule (still) applies
      """
Romain Courteaud's avatar
Romain Courteaud committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
      # Test if we must transform
      # The test should actually be based on nodes, paths
      # and capacities, which is not possible now
      result = 1
      # Only apply to Order applied rule
      root_applied_rule = movement.getRootAppliedRule()
      root_rule = root_applied_rule.getSpecialiseValue()
      order = root_applied_rule.getCausalityValue()
      # Test some properties to see if we are really 
      # in a 'production' expand.
      if (root_rule is None) or\
         (root_rule.getPortalType() != "Production Order Rule") or\
         (order is None) or\
         (movement.getResourceValue() is None) or\
         (movement.getSourceValue() is None):
           result = 0
      else:
169
        supply_chain = self.getSupplyChain(movement.getParentValue())
Romain Courteaud's avatar
Romain Courteaud committed
170 171 172 173
        parent_supply_link = self.getCurrentSupplyLink(movement)
        if not supply_chain.test(parent_supply_link, movement):
          result = 0
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
174 175

    security.declareProtected(Permissions.ModifyPortalContent, 'expand')
176
    def expand(self, applied_rule, activate_kw=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
177 178 179 180 181 182
      """
        Expands the current movement downward.
        -> new status -> expanded
        An applied rule can be expanded only if its parent movement
        is expanded.
      """
183
      parent_movement = applied_rule.getParentValue()
Romain Courteaud's avatar
Romain Courteaud committed
184
      # Calculate the previous supply link
185
      supply_chain = self.getSupplyChain(parent_movement.getParentValue())
Romain Courteaud's avatar
Romain Courteaud committed
186 187 188 189 190 191
      parent_supply_link = self.getCurrentSupplyLink(parent_movement)
      previous_supply_link_list = supply_chain.\
                     getPreviousPackingListSupplyLinkList(
                                                    parent_supply_link,
                                                    movement=parent_movement)
      if len(previous_supply_link_list) == 0:
192
        raise TransformationSourcingRuleError,\
Romain Courteaud's avatar
Romain Courteaud committed
193 194 195 196 197 198 199 200 201 202
              "Expand must not be called on %r" %\
                  applied_rule.getRelativeUrl()
      else:
        movement_dict = {}
        for previous_supply_link in previous_supply_link_list:
          # Calculate the source
          source_value = None
          source_node = previous_supply_link.getSourceValue()
          if source_node is not None:
            source_value = source_node.getDestinationValue()
203
          source_section_value = previous_supply_link.getSourceSectionValue()
Romain Courteaud's avatar
Romain Courteaud committed
204
          # Generate the dict
205
          stop_date = parent_movement.getStartDate()
Romain Courteaud's avatar
Romain Courteaud committed
206 207 208
          movement_dict.update({
            "ts": {
              'source_value': source_value,
209
              'source_section_value': source_section_value,
Romain Courteaud's avatar
Romain Courteaud committed
210
              'destination_value': parent_movement.getSourceValue(),
211 212
              'destination_section_value': \
                  parent_movement.getSourceSectionValue(),
Romain Courteaud's avatar
Romain Courteaud committed
213 214 215
              'resource_value': parent_movement.getResourceValue(),
              'variation_category_list': parent_movement.\
                                            getVariationCategoryList(),
216 217
              "variation_property_dict": \
                            parent_movement.getVariationPropertyDict(),
Romain Courteaud's avatar
Romain Courteaud committed
218
              'quantity': parent_movement.getQuantity(),
219
              'price': parent_movement.getPrice(),
Romain Courteaud's avatar
Romain Courteaud committed
220
              'quantity_unit': parent_movement.getQuantityUnit(),
221
              'start_date': previous_supply_link.calculateStartDate(stop_date),
222
              'stop_date': stop_date,
Romain Courteaud's avatar
Romain Courteaud committed
223 224 225 226 227 228
              'deliverable': 1,
              # Save the value of the current supply link
              'causality_value': previous_supply_link,
            }
          })
        # Build the movement
229 230
        self._buildMovementList(applied_rule, movement_dict,
                                activate_kw=activate_kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
231
      # Create one submovement which sources the transformation
232
      Rule.expand(self, applied_rule, activate_kw=activate_kw, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
233 234 235 236

    security.declareProtected(Permissions.ModifyPortalContent, 'solve')
    def solve(self, applied_rule, solution_list):
      """
237
        Solve inconsistency according to a certain number of solutions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
238 239 240 241 242 243 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
        templates. This updates the

        -> new status -> solved

        This applies a solution to an applied rule. Once
        the solution is applied, the parent movement is checked.
        If it does not diverge, the rule is reexpanded. If not,
        diverge is called on the parent movement.
      """

    security.declareProtected(Permissions.ModifyPortalContent, 'diverge')
    def diverge(self, applied_rule):
      """
        -> new status -> diverged

        This basically sets the rule to "diverged"
        and blocks expansion process
      """

    # Solvers
    security.declareProtected(Permissions.View, 'isDivergent')
    def isDivergent(self, applied_rule):
      """
        Returns 1 if divergent rule
      """

    security.declareProtected(Permissions.View, 'getDivergenceList')
    def getDivergenceList(self, applied_rule):
      """
        Returns a list Divergence descriptors
      """

    security.declareProtected(Permissions.View, 'getSolverList')
    def getSolverList(self, applied_rule):
      """
        Returns a list Divergence solvers
      """
275 276 277 278 279 280 281 282 283

    def isDeliverable(self, m):
      resource = m.getResource()
      if m.getResource() is None:
        return 0
      if resource.find('operation/') >= 0:
        return 0
      else:
        return 1
Romain Courteaud's avatar
Romain Courteaud committed
284 285 286 287 288 289

    def isOrderable(self, m):
      return 0

from Products.ERP5Type.Utils import monkeyPatch
monkeyPatch(TransformationSourcingRuleMixin, TransformationSourcingRule)