TransformationRule.py 15.8 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 30 31 32 33 34 35
#
# 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.
#
##############################################################################

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
Romain Courteaud's avatar
Romain Courteaud committed
36 37
from Products.ERP5.Document.TransformationSourcingRule import\
                                            TransformationSourcingRuleMixin
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38 39 40

from zLOG import LOG

41 42
class TransformationRuleError(Exception): pass

Jean-Paul Smets's avatar
Jean-Paul Smets committed
43 44 45 46 47 48 49 50 51 52
class TransformationRule(Rule):
    """
      Order Rule object make sure an Order in the similation
      is consistent with the real order
    """
    # CMF Type Definition
    meta_type = 'ERP5 Transformation Rule'
    portal_type = 'Transformation Rule'
    # Declarative security
    security = ClassSecurityInfo()
53
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
54 55 56 57 58 59
    # Default Properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
                      )
Romain Courteaud's avatar
Romain Courteaud committed
60 61
    # Class variable 
    simulation_movement_portal_type = "Simulation Movement"
Jean-Paul Smets's avatar
Jean-Paul Smets committed
62 63 64 65 66 67 68 69 70

    security.declareProtected(Permissions.AccessContentsInformation, 'test')
    def test(self, movement):
      """
        Tests if the rule (still) applies
      """
      # Test if we must transform
      # The test should actually be based on nodes, paths
      # and capacities, which is not possible now
Romain Courteaud's avatar
Romain Courteaud committed
71
      result = 1
72 73 74
      # Only apply to Order applied rule
      root_applied_rule = movement.getRootAppliedRule()
      root_rule = root_applied_rule.getSpecialiseValue()
Romain Courteaud's avatar
Romain Courteaud committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
      order = root_applied_rule.getCausalityValue()
      root_movement = movement.getRootSimulationMovement()
      # Test movement
      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) or\
         (movement.getResourceValue() != root_movement.getResourceValue()):
         # We only produced what is asked on the Production Order
           result = 0
      else:
        supply_chain = self.getSupplyChain(movement.getParent())
        parent_supply_link = self.getCurrentSupplyLink(movement)
        current_tranfo_link_list = supply_chain.\
                       getPreviousProductionSupplyLinkList(parent_supply_link)
        length = len(current_tranfo_link_list)
        if length == 0:
          result = 0
        elif length > 1:
          result = 0
          # XXX FIXME: implementation needed
97
          raise TransformationRuleError,\
Romain Courteaud's avatar
Romain Courteaud committed
98 99
                "TransformationRule not able to use multiple SupplyLink."
      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
100 101 102

    # Simulation workflow
    security.declareProtected(Permissions.ModifyPortalContent, 'expand')
103
    def expand(self, applied_rule, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
104 105 106 107 108 109
      """
        Expands the current movement downward.
        -> new status -> expanded
        An applied rule can be expanded only if its parent movement
        is expanded.
      """
Romain Courteaud's avatar
Romain Courteaud committed
110 111 112 113 114 115 116 117 118 119 120 121 122
      parent_movement = applied_rule.getParent()
      # Get production node and production section
      production = parent_movement.getSource()
      production_section = parent_movement.getSourceSection()
      # Get the current supply link used to calculate consumed resource
      # The current supply link is calculated from the parent AppliedRule.
      supply_chain = self.getSupplyChain(parent_movement.getParent())
      parent_supply_link = self.getCurrentSupplyLink(parent_movement)
      current_supply_link_list = supply_chain.\
                     getPreviousProductionSupplyLinkList(parent_supply_link)
      if len(current_supply_link_list) != 1:
        # We shall no pass here.
        # The test method returned a wrong value !
123
        raise TransformationRuleError,\
Romain Courteaud's avatar
Romain Courteaud committed
124 125
              "Expand must not be called on %r" %\
                  applied_rule.getRelativeUrl()
126
      else:
Romain Courteaud's avatar
Romain Courteaud committed
127 128 129 130 131 132 133 134 135 136 137 138 139
        current_supply_link = current_supply_link_list[0]
        # Generate produced movement
        movement_dict = self._expandProducedResource(applied_rule, 
                                                     production,
                                                     production_section,
                                                     current_supply_link)
        # Generate consumed movement
        consumed_mvt_dict = self._expandConsumedResource(applied_rule, 
                                                         production,
                                                         production_section,
                                                         current_supply_link)
        movement_dict.update(consumed_mvt_dict)
        # Finally, build movement
140
        self._buildMovementList(applied_rule, movement_dict,**kw)
Romain Courteaud's avatar
Romain Courteaud committed
141 142
      # Expand each movement created
      Rule.expand(self, applied_rule, **kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
143

Romain Courteaud's avatar
Romain Courteaud committed
144 145 146 147 148 149 150 151
    def _expandProducedResource(self, applied_rule, production,
                                production_section, current_supply_link):
      """
        Produced resource.
        Create a movement for the resource produced by the transformation.
        Only one produced movement can be created.
      """
      parent_movement = applied_rule.getParent()
152
      stop_date = parent_movement.getStartDate()
Romain Courteaud's avatar
Romain Courteaud committed
153 154 155 156 157 158 159 160
      produced_movement_dict = {
        'pr': {
          "resource": parent_movement.getResource(),
          # XXX what is lost quantity ?
          "quantity": parent_movement.getQuantity(),# + lost_quantity,
          "quantity_unit": parent_movement.getQuantityUnit(),
          "variation_category_list":\
                        parent_movement.getVariationCategoryList(),
161 162
          "variation_property_dict": \
                        parent_movement.getVariationPropertyDict(),
Romain Courteaud's avatar
Romain Courteaud committed
163 164 165 166 167
          "source_list": (),
          "source_section_list": (),
          "destination": production,
          "destination_section": production_section,
          "deliverable": 1,
168
          'start_date': current_supply_link.calculateStartDate(stop_date),
169
          'stop_date': stop_date,
Romain Courteaud's avatar
Romain Courteaud committed
170 171 172 173
          'causality_value': current_supply_link,
        }
      }
      return produced_movement_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
174

Romain Courteaud's avatar
Romain Courteaud committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    def _expandConsumedResource(self, applied_rule, production,
                                production_section, current_supply_link):
      """
        Consumed resource.
        Create a movement for each resource consumed by the transformation,
        and for the previous variation of the produced resource.
      """
      # Calculate all consumed resource
      # Store each value in a dictionnary before created them.
      # { movement_id: {property_name: property_value,} ,}
      consumed_movement_dict = {}
      parent_movement = applied_rule.getParent()
      supply_chain = self.getSupplyChain(parent_movement.getParent())
      # Consumed previous variation
      previous_variation_dict = self._expandConsumedPreviousVariation(
                                                        applied_rule, 
                                                        production, 
                                                        production_section,
                                                        supply_chain,
                                                        current_supply_link)
      consumed_movement_dict.update(previous_variation_dict)
      # Consumed raw materials
      raw_material_dict = self._expandConsumedRawMaterials(
                                                        applied_rule, 
                                                        production, 
                                                        production_section,
                                                        supply_chain,
                                                        current_supply_link)
      consumed_movement_dict.update(raw_material_dict)
      return consumed_movement_dict

    def _expandConsumedPreviousVariation(self, applied_rule, production,
                                         production_section, supply_chain,
                                         current_supply_link):
      """
        Create a movement for the previous variation of the produced resource.
      """
212
      id_count = 1
Romain Courteaud's avatar
Romain Courteaud committed
213 214
      consumed_movement_dict = {}
      parent_movement = applied_rule.getParent()
Romain Courteaud's avatar
Romain Courteaud committed
215 216 217 218 219 220 221
      # Calculate the variation category list of parent movement
      base_category_list = parent_movement.getVariationBaseCategoryList()
      if "industrial_phase" in base_category_list:
        # We do not want to get the industrial phase variation
        base_category_list.remove("industrial_phase")
      category_list = parent_movement.getVariationCategoryList(
                                  base_category_list=base_category_list)
222 223 224 225 226 227 228
      # Calculate the previous variation
      for previous_supply_link in supply_chain.\
            getPreviousSupplyLinkList(current_supply_link):
        previous_ind_phase_list = supply_chain.\
            getPreviousProductionIndustrialPhaseList(previous_supply_link,
                                                     all=1)
        if previous_ind_phase_list != []:
Romain Courteaud's avatar
Romain Courteaud committed
229 230
          # Industrial phase is a category
          ind_phase_list = [x.getCategoryRelativeUrl() for x in \
231 232 233 234 235
                            previous_ind_phase_list]
          consumed_mvt_id = "%s_%s" % ("mr", id_count)
          id_count += 1
          stop_date = parent_movement.getStartDate()
          consumed_movement_dict[consumed_mvt_id] = {
236
            'start_date': current_supply_link.calculateStartDate(stop_date),
237 238 239 240 241 242 243 244 245 246
            'stop_date': stop_date,
            "resource": parent_movement.getResource(),
            # XXX Is the quantity value correct ?
            "quantity": parent_movement.getQuantity(),
            "quantity_unit": parent_movement.getQuantityUnit(),
            "destination_list": (),
            "destination_section_list": (),
            "source": production,
            "source_section": production_section,
            "deliverable": 1,
Romain Courteaud's avatar
Romain Courteaud committed
247
            "variation_category_list": category_list,
248 249
            "variation_property_dict": \
                        parent_movement.getVariationPropertyDict(),
250 251
            'causality_value': current_supply_link,
            "industrial_phase_list": ind_phase_list}
Romain Courteaud's avatar
Romain Courteaud committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
      return consumed_movement_dict

    def _expandConsumedRawMaterials(self, applied_rule, production,
                                    production_section, supply_chain,
                                    current_supply_link):
      """
        Create a movement for each resource consumed by the transformation,
      """
      parent_movement = applied_rule.getParent()
      # Calculate the context for getAggregatedAmountList
      base_category_list = parent_movement.getVariationBaseCategoryList()
      if "industrial_phase" in base_category_list:
        # We do not want to get the industrial phase variation
        base_category_list.remove("industrial_phase")
      category_list = parent_movement.getVariationCategoryList(
                                  base_category_list=base_category_list)
      # Get the transformation to use
269
      transformation = self.getTransformation(applied_rule)
Romain Courteaud's avatar
Romain Courteaud committed
270 271 272 273 274 275 276 277 278
      # Generate the fake context 
      tmp_context = parent_movement.asContext(
                   context=parent_movement, 
                   REQUEST={'categories':category_list})
      # Calculate the industrial phase list
      previous_ind_phase_list = supply_chain.\
          getPreviousPackingListIndustrialPhaseList(current_supply_link)
      ind_phase_id_list = [x.getId() for x in previous_ind_phase_list]
      # Call getAggregatedAmountList
279 280
      # XXX expand failed if transformation is not defined.
      # Do we need to catch the exception ?
Romain Courteaud's avatar
Romain Courteaud committed
281 282 283 284 285 286 287
      amount_list = transformation.getAggregatedAmountList(
                   tmp_context,
                   ind_phase_id_list=ind_phase_id_list)
      # Add entries in the consumed_movement_dict
      consumed_movement_dict = {}
      for amount in amount_list:
        consumed_mvt_id = "%s_%s" % ("cr", amount.getId())
288
        stop_date = parent_movement.getStartDate()
Sebastien Robin's avatar
Sebastien Robin committed
289 290 291 292
        resource_price = amount.getResourcePrice()
        price = None
        if resource_price is not None:
          price = amount.getQuantity() * resource_price
Romain Courteaud's avatar
Romain Courteaud committed
293
        consumed_movement_dict[consumed_mvt_id] = {
294
          'start_date': current_supply_link.calculateStartDate(stop_date),
295
          'stop_date': stop_date,
Romain Courteaud's avatar
Romain Courteaud committed
296 297 298
          "resource": amount.getResource(),
          "variation_category_list":\
                        amount.getVariationCategoryList(),
299 300
          "variation_property_dict": \
                        amount.getVariationPropertyDict(),
Romain Courteaud's avatar
Romain Courteaud committed
301
          "quantity": amount.getQuantity() * parent_movement.getQuantity(),
Sebastien Robin's avatar
Sebastien Robin committed
302
          "price": price,
Romain Courteaud's avatar
Romain Courteaud committed
303 304 305 306 307 308 309 310 311
          "quantity_unit": amount.getQuantityUnit(),
          "destination_list": (),
          "destination_section_list": (),
          "source": production,
          "source_section": production_section,
          "deliverable": 1,
          'causality_value': current_supply_link,
        }
      return consumed_movement_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 345 346 347 348 349 350 351 352

    security.declareProtected(Permissions.ModifyPortalContent, 'solve')
    def solve(self, applied_rule, solution_list):
      """
        Solve inconsitency according to a certain number of solutions
        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
Jean-Paul Smets's avatar
Jean-Paul Smets committed
353
      """
354 355 356
    # Deliverability / orderability
    def isDeliverable(self, m):
      return 1
Romain Courteaud's avatar
Romain Courteaud committed
357 358 359 360 361
    def isOrderable(self, m):
      return 0

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