SimulationTool.py 101 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
#
# 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 Products.CMFCore.utils import UniqueObject

from AccessControl import ClassSecurityInfo
from Globals import InitializeClass, DTMLFile
33
from Products.ERP5Type.Document.Folder import Folder
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34
from Products.ERP5Type import Permissions
35
from Products.ERP5Type.Tool.BaseTool import BaseTool
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37 38 39 40 41 42

from Products.ERP5 import _dtmldir

from zLOG import LOG

from Products.ERP5.Capacity.GLPK import solve
from Numeric import zeros, resize
Alexandre Boeglin's avatar
Alexandre Boeglin committed
43
from DateTime import DateTime
Jean-Paul Smets's avatar
Jean-Paul Smets committed
44 45 46 47 48 49 50 51

# Solver Registration
is_initialized = 0
delivery_solver_dict = {}
delivery_solver_list = []

def registerDeliverySolver(solver):
    global delivery_solver_list, delivery_solver_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
52
    #LOG('Register Solver', 0, str(solver.__name__))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
53 54 55 56 57 58 59 60
    delivery_solver_list.append(solver)
    delivery_solver_dict[solver.__name__] = solver

target_solver_dict = {}
target_solver_list = []

def registerTargetSolver(solver):
    global target_solver_list, target_solver_dict
Jean-Paul Smets's avatar
Jean-Paul Smets committed
61
    #LOG('Register Solver', 0, str(solver.__name__))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
62 63 64 65 66 67 68 69 70 71 72
    target_solver_list.append(solver)
    target_solver_dict[solver.__name__] = solver

class Target:

  def __init__(self, **kw):
    """
      Defines a target (target_quantity, start_date, stop_date)
    """
    self.__dict__.update(kw)

73
class SimulationTool (BaseTool):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    """
    The SimulationTool implements the ERP5
    simulation algorithmics.


    Examples of applications:

    -

    -
    ERP5 main purpose:

    -

    -

    """
    id = 'portal_simulation'
    meta_type = 'ERP5 Simulation Tool'
93
    portal_type = 'Simulation Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    allowed_types = ( 'ERP5 Applied Rule', )

    # Declarative Security
    security = ClassSecurityInfo()

    #
    #   ZMI methods
    #
    manage_options = ( ( { 'label'      : 'Overview'
                         , 'action'     : 'manage_overview'
                         }
                        ,
                        )
                     + Folder.manage_options
                     )

    security.declareProtected( Permissions.ManagePortal, 'manage_overview' )
    manage_overview = DTMLFile( 'explainSimulationTool', _dtmldir )

    # Filter content (ZMI))
114 115
    #def __init__(self):
    #    return Folder.__init__(self, SimulationTool.id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

    # Filter content (ZMI))
    def filtered_meta_types(self, user=None):
        # Filters the list of available meta types.
        all = SimulationTool.inheritedAttribute('filtered_meta_types')(self)
        meta_types = []
        for meta_type in self.all_meta_types():
            if meta_type['name'] in self.allowed_types:
                meta_types.append(meta_type)
        return meta_types

    def initialize(self):
      """
        Update values of simulation movements based on delivery
        target values and solver
      """
132
      from Products.ERP5.TargetSolver import Reduce, Defer, SplitAndDefer, CopyToTarget, Redirect
Jean-Paul Smets's avatar
Jean-Paul Smets committed
133 134 135 136 137 138 139 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
      from Products.ERP5.DeliverySolver import Distribute, Copy

    def isInitialized(self):
      global is_initialized
      return is_initialized

    def newDeliverySolver(self, solver_id, *args, **kw):
      """
        Returns a solver instance
      """
      if not self.isInitialized(): self.initialize()
      solver = delivery_solver_dict[solver_id](self, *args, **kw)
      return solver

    def applyDeliverySolver(self, movement, solver):
      """
        Update values of simulation movements based on delivery
        target values and solver.

        movement  --  a delivery line or cell

        solver    --  a delivery solver
      """
      if not self.isInitialized(): self.initialize()
      solver.solve(movement)

    def newTargetSolver(self, solver_id, *args, **kw):
      """
        Returns a solver instance
      """
      if not self.isInitialized(): self.initialize()
      solver = target_solver_dict[solver_id](self, *args, **kw)
      return solver

    def applyTargetSolver(self, movement, solver, new_target=None):
      """
        Update upper targets based on new targets

        movement  --  a simulation movement

        solver    --  a target solver

        new_target--  new target values for that movement
      """
      if new_target is None:
        # Default behaviour is to solve target based on
        # target defined by Delivery
        # it must be overriden in recursive upward update
        # to make sure
        new_target = Target(target_quantity = movement.getQuantity(),
                            target_start_date = movement.getStartDate(),
184 185 186 187 188 189
                            target_stop_date = movement.getStopDate(),
                            target_destination = movement.getDestination(),
                            target_destination_section = movement.getDestinationSection(),
                            target_source = movement.getSource(),
                            target_source_section = movement.getSourceSection())

Jean-Paul Smets's avatar
Jean-Paul Smets committed
190 191 192 193 194 195 196
      if not self.isInitialized(): self.initialize()
      solver.solve(movement, new_target)

    def closeTargetSolver(self, solver):
      return solver.close()

    def showTargetSolver(self, solver):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
197
      #LOG("SimulationTool",0,"in showTargetSolver")
Jean-Paul Smets's avatar
Jean-Paul Smets committed
198 199 200 201 202
      return str(solver.__dict__)


    #######################################################
    # Stock Management
203 204

    def _generateSQLKeywordDict(self, from_date=None, to_date=None, at_date=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
205
        resource=None, node=None, payment=None,
206
        section=None, mirror_section=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
207
        resource_category=None, node_category=None, payment_category=None,
208
        section_category=None, mirror_section_category=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
209
        simulation_state=None, transit_simulation_state = None, omit_transit=0,
210
        input_simulation_state = None, output_simulation_state=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
211
        variation_text=None, variation_category=None,
212
        **kw) :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
213
      """
214
      generates keywork and calls buildSqlQuery
Alexandre Boeglin's avatar
Alexandre Boeglin committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
      """
      new_kw = {}
      new_kw.update(kw)
      sql_kw = {}

      date_dict = {'query':[], 'operator':'and'}
      if from_date :
        date_dict['query'].append(from_date)
        date_dict['range'] = 'min'
        if to_date :
          date_dict['query'].append(to_date)
          date_dict['range'] = 'minmax'
      elif to_date :
        date_dict['query'].append(to_date)
        date_dict['range'] = 'max'
      elif at_date :
        date_dict['query'].append(at_date)
        date_dict['range'] = 'ngt'
      if len(date_dict) :
        new_kw['stock.date'] = date_dict

      resource_uid_list = []
      if type(resource) is type('') :
        resource_uid_list.append(self.portal_categories.restrictedTraverse(resource).getUid())
      elif type(resource) is type([]) or type(resource) is type(()) :
        for resource_item in resource :
          resource_uid_list.append(self.portal_categories.restrictedTraverse(resource_item).getUid())
      if len(resource_uid_list) :
        new_kw['stock.resource_uid'] = resource_uid_list

      node_uid_list = []
      if type(node) is type('') :
        node_uid_list.append(self.portal_categories.restrictedTraverse(node).getUid())
      elif type(node) is type([]) or type(node) is type(()) :
        for node_item in node :
          node_uid_list.append(self.portal_categories.restrictedTraverse(node_item).getUid())
      if len(node_uid_list) :
        new_kw['stock.node_uid'] = node_uid_list

      payment_uid_list = []
      if type(payment) is type('') :
        payment_uid_list.append(self.portal_categories.restrictedTraverse(payment).getUid())
      elif type(payment) is type([]) or type(payment) is type(()) :
        for payment_item in payment :
          payment_uid_list.append(self.portal_categories.restrictedTraverse(payment_item).getUid())
      if len(payment_uid_list) :
        new_kw['stock.payment_uid'] = payment_uid_list

      section_uid_list = []
      if type(section) is type('') :
        section_uid_list.append(self.portal_categories.restrictedTraverse(section).getUid())
      elif type(section) is type([]) or type(section) is type(()) :
        for section_item in section :
          section_uid_list.append(self.portal_categories.restrictedTraverse(section_item).getUid())
      if len(section_uid_list) :
        new_kw['stock.section_uid'] = section_uid_list

      mirror_section_uid_list = []
      if type(mirror_section) is type('') :
        mirror_section_uid_list.append(self.portal_categories.restrictedTraverse(mirror_section).getUid())
      elif type(mirror_section) is type([]) or type(mirror_section) is type(()) :
        for mirror_section_item in mirror_section :
          mirror_section_uid_list.append(self.portal_categories.restrictedTraverse(mirror_section_item).getUid())
      if len(mirror_section_uid_list) :
        new_kw['stock.mirror_section_uid'] = mirror_section_uid_list

      variation_text_list = []
      if type(variation_text) is type('') :
        variation_text_list.append(variation_text)
      elif type(variation_text) is type([]) or type(variation_text) is type(()) :
        for variation_text_item in variation_text :
          variation_text_list.append(variation_text_item)
      if len(variation_text_list) :
        new_kw['stock.variation_text'] = variation_text_list

      resource_category_uid_list = []
      if type(resource_category) is type('') :
        resource_category_uid_list.append(self.portal_categories.restrictedTraverse(resource_category).getUid())
      elif type(resource_category) is type([]) or type(resource_category) is type(()) :
        for resource_category_item in resource_category :
          resource_category_uid_list.append(self.portal_categories.restrictedTraverse(resource_category_item).getUid())
      if len(resource_category_uid_list) :
297
        new_kw['stock_resourceCategory'] = resource_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
298 299 300 301 302 303 304 305

      node_category_uid_list = []
      if type(node_category) is type('') :
        node_category_uid_list.append(self.portal_categories.restrictedTraverse(node_category).getUid())
      elif type(node_category) is type([]) or type(node_category) is type(()) :
        for node_category_item in node_category :
          node_category_uid_list.append(self.portal_categories.restrictedTraverse(node_category_item).getUid())
      if len(node_category_uid_list) :
306
        new_kw['stock_nodeCategory'] = node_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
307 308 309 310 311 312 313 314

      payment_category_uid_list = []
      if type(payment_category) is type('') :
        payment_category_uid_list.append(self.portal_categories.restrictedTraverse(payment_category).getUid())
      elif type(payment_category) is type([]) or type(payment_category) is type(()) :
        for payment_category_item in payment_category :
          payment_category_uid_list.append(self.portal_categories.restrictedTraverse(payment_category_item).getUid())
      if len(payment_category_uid_list) :
315
        new_kw['stock_paymentCategory'] = payment_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
316 317 318 319 320 321 322 323

      section_category_uid_list = []
      if type(section_category) is type('') :
        section_category_uid_list.append(self.portal_categories.restrictedTraverse(section_category).getUid())
      elif type(section_category) is type([]) or type(section_category) is type(()) :
        for section_category_item in section_category :
          section_category_uid_list.append(self.portal_categories.restrictedTraverse(section_category_item).getUid())
      if len(section_category_uid_list) :
324
        new_kw['stock_sectionCategory'] = section_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
325 326 327 328 329 330 331 332

      mirror_section_category_uid_list = []
      if type(mirror_section_category) is type('') :
        mirror_section_category_uid_list.append(self.portal_categories.restrictedTraverse(mirror_section_category).getUid())
      elif type(mirror_section_category) is type([]) or type(mirror_section_category) is type(()) :
        for mirror_section_category_item in mirror_section_category :
          mirror_section_category_uid_list.append(self.portal_categories.restrictedTraverse(mirror_section_category_item).getUid())
      if len(mirror_section_category_uid_list) :
333
        new_kw['stock_mirrorSectionCategory'] = mirror_section_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347

      variation_category_uid_list = []
      if type(variation_category) is type('') :
        variation_category_uid_list.append(self.portal_categories.restrictedTraverse(variation_category).getUid())
      elif type(variation_category) is type([]) or type(variation_category) is type(()) :
        for variation_category_item in variation_category :
          variation_category_uid_list.append(self.portal_categories.restrictedTraverse(variation_category_item).getUid())
      if len(variation_category_uid_list) :
        new_kw['variationCategory'] = variation_category_uid_list

      # Simulation States
      # first, we evaluate simulation_state
      if (type(simulation_state) is type('')) or (type(simulation_state) is type([])) or (type(simulation_state) is type(())) :
        if len(simulation_state) :
348 349
          sql_kw['input_simulation_state'] = simulation_state
          sql_kw['output_simulation_state'] = simulation_state
Alexandre Boeglin's avatar
Alexandre Boeglin committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
      # then, if omit_transit == 1, we evaluate (simulation_state - transit_simulation_state) for input_simulation_state
      if omit_transit == 1 :
        if (type(simulation_state) is type('')) or (type(simulation_state) is type([])) or (type(simulation_state) is type(())) :
          if len(simulation_state) :
            if (type(transit_simulation_state) is type('')) or (type(transit_simulation_state) is type([])) or (type(transit_simulation_state) is type(())) :
              if len(transit_simulation_state) :
                # when we know both are usable, we try to calculate (simulation_state - transit_simulation_state)
                if type(simulation_state) is type('') :
                  simulation_state = [simulation_state]
                if type(transit_simulation_state) is type('') :
                  transit_simulation_state = [transit_simulation_state]
                delivered_simulation_state_list = []
                for state in simulation_state :
                  if state not in transit_simulation_state :
                    delivered_simulation_state_list.append(state)
365
                sql_kw['input_simulation_state'] = delivered_simulation_state_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
366 367 368
      # alternatively, the user can directly define input_simulation_state and output_simulation_state
      if (type(input_simulation_state) is type('')) or (type(input_simulation_state) is type([])) or (type(input_simulation_state) is type(())) :
        if len(input_simulation_state) :
369
          sql_kw['input_simulation_state'] = input_simulation_state
Alexandre Boeglin's avatar
Alexandre Boeglin committed
370 371
      if (type(output_simulation_state) is type('')) or (type(output_simulation_state) is type([])) or (type(output_simulation_state) is type(())) :
        if len(output_simulation_state) :
372 373 374 375 376
          sql_kw['output_simulation_state'] = output_simulation_state
      if type(sql_kw.get('input_simulation_state')) is type('') :
        sql_kw['input_simulation_state'] = [sql_kw['input_simulation_state']]
      if type(sql_kw.get('output_simulation_state')) is type('') :
        sql_kw['output_simulation_state'] = [sql_kw['output_simulation_state']]
Alexandre Boeglin's avatar
Alexandre Boeglin committed
377 378 379

      sql_kw.update(self.portal_catalog.buildSQLQuery(**new_kw))

380 381
      return sql_kw

Jean-Paul Smets's avatar
Jean-Paul Smets committed
382 383
    #######################################################
    # Inventory management                  
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    security.declareProtected(Permissions.AccessContentsInformation, 'getInventory')
    def getInventory(self, src__=0,
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
        selection_domain=None, selection_report=None, **kw) :
      """
      from_date (>=) -

      to_date   (<)  -

      at_date   (<=) - only take rows which date is <= at_date

      resource (only in generic API in simulation)

      node        -  only take rows in stock table which node_uid is equivalent to node

      payment        -  only take rows in stock table which payment_uid is equivalent to payment

      section        -  only take rows in stock table which section_uid is equivalent to section

      mirror_section

      resource_category        -  only take rows in stock table which resource_uid is in resource_category

      node_category        -  only take rows in stock table which node_uid is in section_category

      payment_category        -  only take rows in stock table which payment_uid is in section_category

      section_category        -  only take rows in stock table which section_uid is in section_category

      mirror_section_category

      variation_text - only take rows in stock table with specified variation_text
                       this needs to be extended with some kind of variation_category ?
                       XXX this way of implementing variation selection is far from perfect

      variation_category - variation or list of possible variations

      simulation_state - only take rows with specified simulation_state

      transit_simulation_state - take rows with specified transit_simulation_state and quantity < 0

      omit_transit - do not evaluate transit_simulation_state

      input_simulation_state - only take rows with specified input_simulation_state and quantity > 0

      output_simulation_state - only take rows with specified output_simulation_state and quantity < 0

      ignore_variation - do not take into account variation in inventory calculation

      standardise - provide a standard quantity rather than an SKU

      omit_simulation

      omit_input

      omit_output

      selection_domain, selection_report - see ListBox

      **kw  - if we want extended selection with more keywords (but bad performance)
              check what we can do with buildSqlQuery
      """
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
448
      if src__ :
449 450
        return self.Resource_zGetInventory(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
451 452 453
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

454 455
      result = self.Resource_zGetInventory(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
456 457
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
458 459 460 461
      if len(result) > 0:
        return result[0].inventory
      return 0.0

Alexandre Boeglin's avatar
Alexandre Boeglin committed
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventory')
    def getCurrentInventory(self, **kw):
      """
      Returns current inventory
      """
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
      return self.getInventory(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getAvailableInventory')
    def getAvailableInventory(self, **kw):
      """
      Returns available inventory
      (current inventory - deliverable)
      """
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
      return self.getInventory(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventory')
    def getFutureInventory(self, **kw):
      """
      Returns future inventory
      """
484 485
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
486 487 488
      return self.getInventory(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryList')
489
    def getInventoryList(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
490
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
491
        selection_domain=None, selection_report=None, **kw) :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
492 493 494
      """
      Returns list of inventory grouped by section or site
      """
495 496 497 498 499 500 501 502 503 504 505 506
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_zGetInventoryList(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_zGetInventoryList(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
507 508 509 510 511 512

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryList')
    def getCurrentInventoryList(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
513
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
514 515 516 517 518 519 520
      return self.getInventoryList(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryList')
    def getFutureInventoryList(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
521 522
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
523 524 525
      return self.getInventoryList(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryStat')
526
    def getInventoryStat(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
527
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
528
        selection_domain=None, selection_report=None, **kw) :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
529 530 531
      """
      Returns statistics of inventory grouped by section or site
      """
532 533 534 535 536 537 538 539 540 541 542 543
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_zGetInventory(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_zGetInventory(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
544 545 546 547 548 549

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryStat')
    def getCurrentInventoryStat(self, **kw):
      """
      Returns statistics of current inventory grouped by section or site
      """
550
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
551 552 553 554 555 556 557
      return self.getInventoryStat(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryStat')
    def getFutureInventoryStat(self, **kw):
      """
      Returns statistics of future inventory grouped by section or site
      """
558 559
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
560 561 562
      return self.getInventoryStat(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryChart')
563
    def getInventoryChart(self, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
564 565 566
      """
      Returns list of inventory grouped by section or site
      """
567 568 569 570 571
      if src__ :
        return self.getInventoryList(src__=1, **kw)

      result = self.getInventoryList(**kw)
      return map(lambda r: (r.node_title, r.inventory), result)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
572 573 574 575 576 577

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryChart')
    def getCurrentInventoryChart(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
578
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
579 580 581 582 583 584 585
      return self.getInventoryChart(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryChart')
    def getFutureInventoryChart(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
586 587
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
588 589 590
      return self.getInventoryChart(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryAssetPrice')
591
    def getInventoryAssetPrice(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
592
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
593
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
594 595 596
      """
      Returns list of inventory grouped by section or site
      """
597 598 599 600 601 602 603 604 605 606 607 608
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_zGetInventoryAssetPrice(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_zGetInventoryAssetPrice(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
609 610 611 612 613 614

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryAssetPrice')
    def getCurrentInventoryAssetPrice(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
615
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
616 617 618 619 620 621 622 623
      return self.getInventoryAssetPrice(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getAvailableInventoryAssetPrice')
    def getAvailableInventoryAssetPrice(self, **kw):
      """
      Returns list of available inventory grouped by section or site
      (current inventory - deliverable)
      """
624
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
625 626 627 628 629 630 631
      return self.getInventoryAssetPrice(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryAssetPrice')
    def getFutureInventoryAssetPrice(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
632 633
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
634 635 636
      return self.getInventoryAssetPrice(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryHistoryList')
637
    def getInventoryHistoryList(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
638
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
639
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
640 641 642
      """
      Returns list of inventory grouped by section or site
      """
643 644 645 646 647 648 649 650 651 652 653 654
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_getInventoryHistoryList(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_getInventoryHistoryList(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
655 656

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryHistoryChart')
657
    def getInventoryHistoryChart(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
658
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
659
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
660 661 662
      """
      Returns list of inventory grouped by section or site
      """
663 664 665 666 667 668 669 670 671 672 673 674
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_getInventoryHistoryChart(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_getInventoryHistoryChart(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
675 676

    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementHistoryList')
677
    def getMovementHistoryList(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
678
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
679
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
680 681 682
      """
      Returns list of inventory grouped by section or site
      """
683 684 685 686 687 688 689 690 691 692 693 694
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_zGetMovementHistoryList(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_zGetMovementHistoryList(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
695 696

    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementHistoryStat')
697
    def getMovementHistoryStat(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
698
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
699
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
700 701 702
      """
      Returns statistics of inventory grouped by section or site
      """
703 704 705 706 707 708 709 710 711 712 713 714
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_zGetInventory(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_zGetInventory(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
715 716

    security.declareProtected(Permissions.AccessContentsInformation, 'getNextNegativeInventoryDate')
717
    def getNextNegativeInventoryDate(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
718
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
719
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
720 721 722
      """
      Returns statistics of inventory grouped by section or site
      """
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_getInventoryHistoryList(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      result = self.Resource_getInventoryHistoryList(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      for inventory in result:
        if inventory['inventory'] < 0:
          return inventory['stop_date']

      return None
Alexandre Boeglin's avatar
Alexandre Boeglin committed
741

Jean-Paul Smets's avatar
Jean-Paul Smets committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
    
    #######################################################
    # Traceability management                  
    security.declareProtected(Permissions.AccessContentsInformation, 'getTrackingList')
    def getTrackingList(self, src__=0,
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
        selection_domain=None, selection_report=None, **kw) :
      """
      Returns the history of an item
      
        uid (of item)
        date
        node_uid
        section_uid
        resource_uid
        variation_text
        
      This method is only suitable for singleton items (an item which can 
      only be at a single place at a given time). Such items include
      containers, serial numbers (ex. for engine), rolls with subrolls,
      
      This method is not suitable for batches (ex. a coloring batch). 
      For such items, standard getInventoryList method is appropriate
      
      Parameters are the same as for getInventory.
      
      Default sort orders is based on dates, reverse.     
      """
      sql_kw = self._generateSQLKeywordDict(**kw)

      if src__ :
        return self.Resource_zGetTrackingList(src__=1,
            ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
            omit_input=omit_input, omit_output=omit_output,
            selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

      return self.Resource_zGetTrackingList(
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
          omit_input=omit_input, omit_output=omit_output,
          selection_domain=selection_domain, selection_report=selection_report, **sql_kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentTrackingList')
    def getCurrentTrackingList(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
      return self.getTrackingList(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureTrackingList')
    def getFutureTrackingList(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
      return self.getTrackingList(**kw)

          
Jean-Paul Smets's avatar
Jean-Paul Smets committed
801 802
    #######################################################
    # Movement Group Collection / Delivery Creation
803
    def collectMovement(self, movement_list,class_list=None,**kw):
804 805
      """
      group movements in the way we want. Thanks to this method, we are able to retrieve
806
      movement classed by order, resource, criterion,....
807 808 809 810 811 812 813 814 815 816

      movement_list : the list of movement wich we want to group

      check_list : the list of classes used to group movements. The order
                   of the list is important and determines by what we will
                   group movement first
                   Typically, check_list is :
                   [DateMovementGroup,PathMovementGroup,...]
      """
      s_tool = self.portal_simulation
817 818 819 820
      from Products.ERP5.MovementGroup import OrderMovementGroup, PathMovementGroup
      from Products.ERP5.MovementGroup import DateMovementGroup, ResourceMovementGroup
      from Products.ERP5.MovementGroup import VariantMovementGroup, RootMovementGroup
      if class_list is None:
821
        # For compatibility reasons, by default we keep the previous order
822 823 824
        class_list = [OrderMovementGroup,PathMovementGroup,DateMovementGroup,
                      ResourceMovementGroup,VariantMovementGroup]
      my_root_group = RootMovementGroup(class_list=class_list)
825
      for movement in movement_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
826
        if not movement in my_root_group.movement_list :
827
          my_root_group.append(movement,class_list=class_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
828 829

      return my_root_group
830

Jean-Paul Smets's avatar
Jean-Paul Smets committed
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    def buildOrderList(self, movement_group):
      # Build orders from a list of movements (attached to orders)
      order_list = []

      if movement_group is not None:
        for order_group in movement_group.group_list:
          if order_group.order is None:
            # Only build if there is not order yet
            for path_group in order_group.group_list :
              if path_group.destination.find('site/Stock_PF') >=0 :
                # Build a Production Order
                delivery_module = self.ordre_fabrication
                delivery_type = 'Production Order'
                delivery_line_type = delivery_type + ' Line'
                delivery_cell_type = 'Delivery Cell'
              else:
                # Build a Purchase Order
                delivery_module = self.commande_achat
                delivery_type = 'Purchase Order'
                delivery_line_type = delivery_type + ' Line'
                delivery_cell_type = 'Delivery Cell'
              # we create a new delivery for each DateGroup
              for date_group in path_group.group_list :

                for resource_group in date_group.group_list :

                  # Create a new production Order for each resource (Modele)
                  modele_url_items = resource_group.resource.split('/')
                  modele_id = modele_url_items[len(modele_url_items)-1]
                  try :
                    modele_object = self.getPortalObject().modele[modele_id]
                  except :
                    modele_object = None
                  if modele_object is not None :
                    of_description = modele_id + ' ' + modele_object.getDefaultDestinationTitle('')
                  else :
                    of_description = modele_id

                  new_delivery_id = str(delivery_module.generateNewId())
                  self.portal_types.constructContent(type_name = delivery_type,
                                                      container = delivery_module,
                                                      id = new_delivery_id,
                                                      start_date = date_group.start_date,
                                                      stop_date = date_group.stop_date,
                                                      source = path_group.source,
                                                      destination = path_group.destination,
                                                      source_section = path_group.source_section,
                                                      destination_section = path_group.destination_section,
                                                      description = of_description,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
880
                                                      title = new_delivery_id
Jean-Paul Smets's avatar
Jean-Paul Smets committed
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
                                                    )
                  delivery = delivery_module[new_delivery_id]
                  # the new delivery is added to the order_list
                  order_list.append(delivery)

                  # Create each delivery_line in the new delivery

                  new_delivery_line_id = str(delivery.generateNewId())
                  self.portal_types.constructContent(type_name = delivery_line_type,
                  container = delivery,
                  id = new_delivery_line_id,
                  resource = resource_group.resource,
                  )
                  delivery_line = delivery[new_delivery_line_id]

                  line_variation_category_list = []
                  line_variation_base_category_dict = {}

                  # compute line_variation_base_category_list and
                  # line_variation_category_list for new delivery_line
                  for variant_group in resource_group.group_list :
                    for variation_item in variant_group.category_list :
                      if not variation_item in line_variation_category_list :
                        line_variation_category_list.append(variation_item)
                        variation_base_category_items = variation_item.split('/')
                        if len(variation_base_category_items) > 0 :
                          line_variation_base_category_dict[variation_base_category_items[0]] = 1

                  # update variation_base_category_list and line_variation_category_list for delivery_line
                  line_variation_base_category_list = line_variation_base_category_dict.keys()
                  delivery_line.setVariationBaseCategoryList(line_variation_base_category_list)
                  delivery_line.setVariationCategoryList(line_variation_category_list)

                  # IMPORTANT : delivery cells are automatically created during setVariationCategoryList

916
                  # update quantity for each delivery_cell
Jean-Paul Smets's avatar
Jean-Paul Smets committed
917
                  for variant_group in resource_group.group_list :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
918
                    #LOG('Variant_group examin',0,str(variant_group.category_list))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
919 920 921 922 923 924 925
                    object_to_update = None
                    # if there is no variation of the resource, update delivery_line with quantities and price
                    if len(variant_group.category_list) == 0 :
                      object_to_update = delivery_line
                    # else find which delivery_cell is represented by variant_group
                    else :
                      categories_identity = 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
926 927
                      #LOG('Before Check cell',0,str(delivery_cell_type))
                      #LOG('Before Check cell',0,str(delivery_line.contentValues()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
928
                      for delivery_cell in delivery_line.contentValues(filter={'portal_type':'Delivery Cell'}) :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
929 930 931
                        #LOG('Check cell',0,str(delivery_cell))
                        #LOG('Check cell',0,str(variant_group.category_list))
                        #LOG('Check cell',0,str(delivery_cell.getVariationCategoryList()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
932
                        if len(variant_group.category_list) == len(delivery_cell.getVariationCategoryList()) :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
933
                          #LOG('Parse category',0,str(delivery_cell.getVariationCategoryList()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
934 935
                          for category in delivery_cell.getVariationCategoryList() :
                            if not category in variant_group.category_list :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
936
                              #LOG('Not found category',0,str(category))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
937 938 939 940 941 942 943 944
                              break
                          else :
                            categories_identity = 1

                        if categories_identity :
                          object_to_update = delivery_cell
                          break

945
                    # compute quantity and price for delivery_cell or delivery_line and
Jean-Paul Smets's avatar
Jean-Paul Smets committed
946 947
                    # build relation between simulation_movement and delivery_cell or delivery_line
                    if object_to_update is not None :
948
                      cell_quantity = 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
949
                      for movement in variant_group.movement_list :
950
                        cell_quantity += movement.getConvertedQuantity()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
951 952
                      # We do not create a relation or modifu anything
                      # since planification of this movement will create new applied rule
953
                      object_to_update.edit(quantity = cell_quantity,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
954
                                            force_update = 1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
955 956 957

      return order_list

958 959 960 961




Jean-Paul Smets's avatar
Jean-Paul Smets committed
962 963
    def buildDeliveryList(self, movement_group):
      # Build deliveries from a list of movements
964 965 966 967 968
      LOG('buildDeliveryList root_group',0,movement_group)
      LOG('buildDeliveryList root_group.__dict__',0,movement_group.__dict__)
      for group in movement_group.group_list:
        LOG('buildDeliveryList group.__dict__',0,group.__dict__)
      LOG('buildDeliveryList nested_class.__dict__',0,movement_group.nested_class.__dict__)
969 970


971
      def orderGroupProcessing(order_group, delivery_list, reindexable_movement_list, **kw):
972

973 974 975 976 977 978 979 980 981 982
        # Order should never be None
        LOG("buildDeliveryList", 0, str(order_group.__dict__))
        if order_group.order is not None:
          order = self.portal_categories.resolveCategory(order_group.order)
          if order is not None:
            # define some variables
            LOG("order", 0, str(order.__dict__))
            if order.getPortalType() == 'Purchase Order' :
              delivery_module = order.getPortalObject().livraison_achat
              delivery_type = 'Purchase Packing List'
983 984
              delivery_line_type = delivery_type + ' Line'
              delivery_cell_type = 'Delivery Cell'
985 986 987 988 989
            elif order.getPortalType() == 'Sale Order' :
              delivery_module = order.getPortalObject().sale_packing_list
              delivery_type = 'Sale Packing List'
              delivery_line_type = delivery_type + ' Line'
              delivery_cell_type = 'Delivery Cell'
990 991 992
            else :
              delivery_module = order.getPortalObject().livraison_vente
              delivery_type = 'Sales Packing List'
993 994
              delivery_line_type = delivery_type + ' Line'
              delivery_cell_type = 'Delivery Cell'
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
          else : # should never be none
            LOG("order is None", 0, str(order.__dict__))
            return -1
        else: # order is None
          order = None
          # possible when we build deliveries for tranfer of property
          delivery_module = self.getPortalObject().livraison_vente
          delivery_type = 'Sales Packing List'
          delivery_line_type = delivery_type + ' Line'
          delivery_cell_type = 'Delivery Cell'

        for path_group in order_group.group_list:
          pathGroupProcessing(path_group=path_group,
                              delivery_module=delivery_module,
                              delivery_type=delivery_type,
                              delivery_line_type=delivery_line_type,
                              delivery_cell_type=delivery_cell_type,
                              order=order,
                              delivery_list=delivery_list,
                              reindexable_movement_list=reindexable_movement_list, **kw)
1015

1016
        return 0
1017 1018


1019 1020 1021
      def pathGroupProcessing(path_group, delivery_module, delivery_type, delivery_line_type, delivery_cell_type, order, delivery_list, reindexable_movement_list, default_rule_id=None, **kw):
        # we create a new delivery for each DateGroup

1022

1023 1024 1025 1026 1027
        if default_rule_id is 'default_amortisation_rule':
          pass
        else:
          # if path is internal ???
          # JPS NEW
1028
          if path_group.source is None or path_group.destination is None:
1029
            # Production Path
1030 1031
            LOG("Builder",0, "Strange Path %s " % path_group.source)
            LOG("Builder",0, "Strange Path %s " % path_group.destination)
1032
          LOG("Builder path_group in pathGroupProcessing",0, path_group.__dict__)
1033

Alexandre Boeglin's avatar
Alexandre Boeglin committed
1034

1035
          if path_group.source is None or path_group.destination is None:
1036 1037 1038 1039 1040
            pass
            #delivery_module = self.rapport_fabrication
            #delivery_type = 'Production Report'
            #delivery_line_type = 'Production Report Line'
            #delivery_cell_type = 'Production Report Cell'
1041 1042
          elif path_group.destination.find('site/Stock_PF') >= 0 and \
              path_group.source.find('site/Piquage') >= 0:
1043 1044 1045 1046
            delivery_module = self.livraison_fabrication
            delivery_type = 'Production Packing List'
            delivery_line_type = delivery_type + ' Line'
            delivery_cell_type = 'Delivery Cell'
1047 1048
          elif path_group.source.find('site/Stock_MP') >= 0 and \
              path_group.destination.find('site/Piquage') >= 0:
1049 1050 1051 1052
            delivery_module = self.livraison_fabrication
            delivery_type = 'Production Packing List'
            delivery_line_type = delivery_type + ' Line'
            delivery_cell_type = 'Delivery Cell'
1053

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
          for date_group in path_group.group_list :
            dateGroupProcessing(date_group=date_group,
                                path_group=path_group,
                                delivery_module=delivery_module,
                                delivery_type=delivery_type,
                                delivery_line_type=delivery_line_type,
                                delivery_cell_type=delivery_cell_type,
                                order=order,
                                delivery_list=delivery_list,
                                reindexable_movement_list=reindexable_movement_list,
                                default_rule_id=default_rule_id, **kw)
1065 1066


1067
      def dateGroupProcessing(date_group, path_group, delivery_module, delivery_type, delivery_line_type, delivery_cell_type, order, delivery_list, reindexable_movement_list, default_rule_id=None, resource=None, **kw):
1068

1069 1070
        if default_rule_id == 'default_amortisation_rule':
          accounting_transaction_data_list = {}
1071

1072 1073 1074 1075 1076
          for path_group in date_group.group_list:
            source_section = path_group.source_section
            destination_section = path_group.destination_section
            source = path_group.source
            destination = path_group.destination
1077

1078 1079 1080 1081 1082 1083
            accounting_transaction_data = accounting_transaction_data_list.get( (source_section, destination_section), None)
            if accounting_transaction_data is None:
              accounting_transaction_data_list[ (source_section, destination_section) ] = {}
              accounting_transaction_data = accounting_transaction_data_list.get( (source_section, destination_section), None)
            quantity = 0
            source_movement_list = []
1084

1085 1086 1087 1088 1089 1090 1091
            for movement in path_group.movement_list:
              if movement.getDeliveryValue() is None:
                quantity += movement.getQuantity()
                source_movement_list.append(movement)
            accounting_transaction_data[ (source, destination) ] = (quantity, source_movement_list)
            if len(source_movement_list) == 0:
              del accounting_transaction_data[ (source, destination) ]
1092

1093 1094
          for (source_section, destination_section), accounting_transaction_data in accounting_transaction_data_list.items():
            if len(accounting_transaction_data.items()) > 0:
1095
              new_delivery_id = str(delivery_module.generateNewId())
Guillaume Michon's avatar
Guillaume Michon committed
1096
              accounting_transaction = delivery_module.newContent(portal_type = delivery_type,
1097 1098 1099 1100 1101 1102 1103 1104 1105
                                                id = new_delivery_id,
                                                start_date = date_group.start_date,
                                                stop_date = date_group.stop_date,
                                                source_section = source_section,
                                                destination_section = destination_section
                                                )
              accounting_transaction.setResource(resource)
              for (source, destination), (quantity, source_movement_list) in accounting_transaction_data.items():
                new_transaction_line_id = str(accounting_transaction.generateNewId())
1106
                accounting_transaction_line = accounting_transaction.newContent(type_name = delivery_line_type,
1107 1108 1109 1110 1111 1112 1113 1114 1115
                                                  id = new_transaction_line_id,
                                                  source = source,
                                                  destination = destination)
                accounting_transaction_line = accounting_transaction[new_transaction_line_id]
                accounting_transaction_line.setQuantity(quantity)
                accounting_transaction_line.setResource(resource)
                for movement in source_movement_list:
                  movement.setDeliveryValue(accounting_transaction_line)
                  movement.recursiveImmediateReindexObject()
1116

1117 1118 1119
        else:
          # Create a new packing list
          new_delivery_id = str(delivery_module.generateNewId())
1120
          delivery = delivery_module.newContent(type_name = delivery_type,
1121 1122 1123 1124 1125 1126
                                    id = new_delivery_id,
                                    start_date = date_group.start_date,
                                    stop_date = date_group.stop_date,
                                    source = path_group.source,
                                    destination = path_group.destination,
                                    source_section = path_group.source_section,
1127
                                    destination_section = path_group.destination_section,
1128 1129 1130 1131 1132 1133 1134 1135 1136
                                    )
          if order is not None :
            delivery.edit(title = order.getTitle(),
                          causality_value = order,
                          incoterm = order.getIncoterm(),
                          delivery_mode = order.getDeliveryMode()
                          )
          # the new delivery is added to the delivery_list
          delivery_list.append(delivery)
1137
  #        LOG('Livraison cre',0,str(delivery.getId()))
1138

1139
          # Create each delivery_line in the new delivery
1140

1141 1142 1143 1144 1145 1146 1147 1148
          for resource_group in date_group.group_list :
            resourceGroupProcessing(resource_group=resource_group,
                                    delivery=delivery,
                                    delivery_type=delivery_type,
                                    delivery_line_type=delivery_line_type,
                                    delivery_cell_type=delivery_cell_type,
                                    delivery_list=delivery_list,
                                    reindexable_movement_list=reindexable_movement_list, **kw)
1149 1150


1151
      def resourceGroupProcessing(resource_group, delivery, delivery_type, delivery_line_type, delivery_cell_type, delivery_list, reindexable_movement_list, delivery_module=None, default_rule_id=None, **kw):
1152

1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        if default_rule_id == 'default_amortisation_rule':
          resource = resource_group.resource
          for date_group in resource_group.group_list:
            dateGroupProcessing(date_group=date_group,
                                path_group=None,
                                delivery_module=delivery_module,
                                delivery_type=delivery_type,
                                delivery_line_type=delivery_line_type,
                                delivery_cell_type=delivery_cell_type,
                                order=None,
                                delivery_list=delivery_list,
                                reindexable_movement_list=reindexable_movement_list,
                                default_rule_id=default_rule_id,
                                resource=resource)
        else:
1168

1169 1170 1171 1172 1173
          if delivery_type == 'Production Report':
            if resource_group.resource.find('operation') == 0:
              delivery_line_type = 'Production Report Operation'
            else:
              delivery_line_type = 'Production Report Component'
1174

1175 1176 1177
          #new_delivery_line_id = str(delivery.generateNewId())
          delivery_line = delivery.newContent(type_name = delivery_line_type,
                                              resource = resource_group.resource,
1178
                                            )
1179

1180 1181
          line_variation_category_list = []
          line_variation_base_category_dict = {}
1182

1183 1184 1185 1186 1187 1188 1189 1190 1191
          # compute line_variation_base_category_list and
          # line_variation_category_list for new delivery_line
          for variant_group in resource_group.group_list :
            for variation_item in variant_group.category_list :
              if not variation_item in line_variation_category_list :
                line_variation_category_list.append(variation_item)
                variation_base_category_items = variation_item.split('/')
                if len(variation_base_category_items) > 0 :
                  line_variation_base_category_dict[variation_base_category_items[0]] = 1
1192

1193 1194 1195
          # update variation_base_category_list and line_variation_category_list for delivery_line
          line_variation_base_category_list = line_variation_base_category_dict.keys()
          delivery_line._setVariationBaseCategoryList(line_variation_base_category_list)
1196
          delivery_line.setVariationCategoryList(line_variation_category_list)
1197

1198
          # IMPORTANT : delivery cells are automatically created during setVariationCategoryList
1199

1200
          # update quantity for each delivery_cell
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
          for variant_group in resource_group.group_list:
            #LOG('Variant_group examin?,0,str(variant_group.category_list))
            object_to_update = None
            # if there is no variation of the resource, update delivery_line with quantities and price
            if len(variant_group.category_list) == 0 :
              object_to_update = delivery_line
            # else find which delivery_cell is represented by variant_group
            else :
              categories_identity = 0
              #LOG('Before Check cell',0,str(delivery_cell_type))
              #LOG('Before Check cell',0,str(delivery_line.contentValues()))
              for delivery_cell in delivery_line.contentValues(
                                                    filter={'portal_type':delivery_cell_type}) :
                #LOG('Check cell',0,str(delivery_cell))
                if len(variant_group.category_list) == len(delivery_cell.getVariationCategoryList()) :
                  #LOG('Parse category',0,str(delivery_cell.getVariationCategoryList()))
                  for category in delivery_cell.getVariationCategoryList() :
                    if not category in variant_group.category_list :
                      #LOG('Not found category',0,str(category))
                      break
                  else :
                    categories_identity = 1

                if categories_identity :
                  object_to_update = delivery_cell
                  break

1228
            # compute quantity, quantity and price for delivery_cell or delivery_line and
1229 1230
            # build relation between simulation_movement and delivery_cell or delivery_line
            if object_to_update is not None :
1231
              cell_quantity = 0
1232 1233 1234 1235
              cell_total_price = 0
              for movement in variant_group.movement_list :
                LOG('SimulationTool, movement.getPhysicalPath',0,movement.getPhysicalPath())
                LOG('SimulationTool, movement.showDict',0,movement.showDict())
1236
                cell_quantity += movement.getNetConvertedQuantity()
1237
                try:
1238
                  cell_total_price += movement.getNetConvertedQuantity()*movement.getPrice() # XXX WARNING - ADD PRICED QUANTITY
1239 1240 1241 1242 1243 1244 1245
                except:
                  cell_total_price = None

                if movement.getPortalType() == 'Simulation Movement' :
                  # update every simulation_movement
                  # we set delivery_value and target dates and quantity
                  movement._setDeliveryValue(object_to_update)
1246 1247 1248 1249 1250 1251 1252 1253
                  movement._setQuantity(movement.getQuantity())
                  movement._setEfficiency(movement.getEfficiency())
                  movement._setStartDate(movement.getStartDate())
                  movement._setStopDate(movement.getStopDate())
                  movement._setSource(movement.getSource())
                  movement._setDestination(movement.getDestination())
                  movement._setSourceSection(movement.getSourceSection())
                  movement._setDestinationSection(movement.getDestinationSection())
1254 1255 1256 1257

                  # We will reindex later
                  reindexable_movement_list.append(movement)

1258 1259
              if cell_quantity <> 0 and cell_total_price is not None:
                average_price = cell_total_price/cell_quantity
1260
              else :
1261 1262
                average_price = 0
              #LOG('object mis  jour',0,str(object_to_update.getRelativeUrl()))
1263 1264 1265
              object_to_update._edit(quantity = cell_quantity,
                                     price = average_price,
                                     force_update = 1,
1266
                                    )
1267

1268 1269


1270 1271
      delivery_list = []
      reindexable_movement_list = []
1272

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1273

1274 1275 1276 1277 1278 1279 1280 1281
      if movement_group is not None:
        # Verify the rule used to build the movements
        default_rule_id = None
        if len(movement_group.movement_list) > 0:
          f = getattr(movement_group.movement_list[0], 'getRootAppliedRule', None)
          if f is not None:
            applied_rule = f()
            default_rule_id = applied_rule.getSpecialiseId()
1282 1283


1284 1285 1286 1287 1288
        if default_rule_id == 'default_amortisation_rule':
          delivery_module = self.getPortalObject().accounting
          delivery_type = 'Amortisation Transaction'
          delivery_line_type = delivery_type + ' Line'
          delivery_cell_type = None
1289

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
          for resource_group in movement_group.group_list:
            resourceGroupProcessing(resource_group=resource_group,
                                    delivery=None,
                                    delivery_module=delivery_module,
                                    delivery_type=delivery_type,
                                    delivery_line_type=delivery_line_type,
                                    delivery_cell_type=delivery_cell_type,
                                    delivery_list=delivery_list,
                                    reindexable_movement_list=reindexable_movement_list,
                                    default_rule_id=default_rule_id)
          for movement in movement_group.movement_list:
            movement.immediateReindexObject()
1302 1303


1304 1305 1306 1307 1308 1309
        else:
          for order_group in movement_group.group_list:
            if orderGroupProcessing(order_group=order_group,
                                    delivery_list=delivery_list,
                                    reindexable_movement_list=reindexable_movement_list) == -1:
              return delivery_list
1310 1311


Jean-Paul Smets's avatar
Jean-Paul Smets committed
1312 1313 1314 1315 1316 1317 1318
      # If we reach this point, it means we could
      # create deliveries
      # get_transaction().commit()
      # DO NOT USE COMMIT BECAUSE OF WORKFLOW

      # Now, let us index what must be indexed
      # Since we comitted changes, there should be no risk of conflict
1319
      LOG('reindexable_movement_list',0,reindexable_movement_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1320
      for movement in reindexable_movement_list:
1321
        LOG('will reindex this object: ',0,movement)
1322 1323
        # We have to use 'immediate' to bypass the activity tool,
        # because we will depend on these objects when we try to call buildInvoiceList
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1324

1325
        # movement.reindexObject() # we do it now because we need to
1326
        movement.immediateReindexObject() # we do it now because we need to
1327
                                 # update category relation
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358

      # Now return deliveries which were created
      return delivery_list

    #######################################################
    # Capacity Management
    security.declareProtected( Permissions.ModifyPortalContent, 'updateCapacity' )
    def updateCapacity(self, node):
      capacity_item_list = []
      for o in node.contentValues():
        if o.isCapacity():
          # Do whatever is needed
          capacity_item_list += o.asCapacityItemList()
          pass
      # Do whatever with capacity_item_list
      # and store the resulting new capacity in node
      node._capacity_item_list = capacity_item_list

    security.declareProtected( Permissions.ModifyPortalContent, 'isMovementInsideCapacity' )
    def isMovementInsideCapacity(self, movement):
      """
        Purpose: provide answer to customer for the question "can you do it ?"

        movement:
          date
          source destination (2 nodes)
          source_section ...
      """
      # Get nodes and dat
      source_node = movement.getSourceValue()
      destination_node = movement.getDestinationValue()
1359 1360
      start_date = movement.getStartDate()
      stop_date = movement.getStopDate()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
      # Return result
      return self.isNodeInsideCapacity(source_node, start_date, additional_movement=movement, sign=1) and self.isNodeInsideCapacity(destination_node, stop_date, additional_movement=movement, sign=-1)

    security.declareProtected( Permissions.ModifyPortalContent, 'isNodeInsideCapacity' )
    def isNodeInsideCapacity(self, node, date, simulation_state=None, additional_movement=None, sign=1):
      """
        Purpose: decide if a node is consistent with its capacity definitions
        at a certain date (ie. considreing the stock / production history
      """
      # First get the current inventory situation for this node
      inventory_list = node.getInventoryList(XXXXX)
      # Add additional movement
      if additional_movement:
          inventory_list = inventory_list + sign * additional_movement # needs to be implemented
      # Return answer
      return self.isAmountListInsideCapacity(node, inventory_list)

    security.declareProtected( Permissions.ModifyPortalContent, 'isAmountListInsideCapacity' )
    def isAmountListInsideCapacity(self, node, amount_list,
         resource_aggregation_base_category=None, resource_aggregation_depth=None):
      """
        Purpose: decide if a list of amounts is consistent with the capacity of a node

        If any resource in amount_list is missing in the capacity of the node, resource
        aggregation is performed, based on resource_aggregation_base_category. If the
        base category is not specified, it is an error (should guess instead?). The resource
        aggregation is done at the level of resource_aggregation_depth in the tree
        of categories. If resource_aggregation_depth is not specified, it's an error.

        Assumptions: amount_list is an association list, like ((R1 V1) (R2 V2)).
                     node has an attribute '_capacity_item_list' which is a list of association lists.
                     resource_aggregation_base_category is a Base Category object or a list of Base
                     Category objects or None.
                     resource_aggregation_depth is a strictly positive integer or None.
      """
      # Make a copy of the attribute _capacity_item_list, because it may be necessary
      # to modify it for resource aggregation.
      capacity_item_list = node._capacity_item_list[:]

      # Make a mapping between resources and its indices.
      resource_map = {}
      index = 0
      for alist in capacity_item_list:
        for pair in alist:
          resource = pair[0]
#          LOG('isAmountListInsideCapacity', 0,
#              "resource is %s" % repr(resource))
          if resource not in resource_map:
            resource_map[resource] = index
            index += 1

      # Build a point from the amount list.
      point = zeros(index, 'd') # Fill up zeros for safety.
      mask_map = {}     # This is used to skip items in amount_list.
      for amount in amount_list:
        if amount[0] in mask_map:
          continue
        # This will fail, if amount_list has any different resource from the capacity.
        # If it has any different point, then we should ......
        #
        # There would be two possible different solutions:
        # 1) If a missing resource is a meta-resource of resources supported by the capacity,
        #    it is possible to add the resource into the capacity by aggregation.
        # 2) If a missing resource has a meta-resource as a parent and the capacity supports
        #    the meta-resource directly or indirectly (`indirectly' means `by aggregation'),
        #    it is possible to convert the missing resource into the meta-resource.
        #
        # However, another way has been implemented here. This does the following, if the resource
        # is not present in the capacity:
        # 1) If the value is zero, just ignore the resource, because zero is always acceptable.
        # 2) Attempt to aggregate resources both of the capacity and of the amount list. This aggregation
        #    is performed at the depth of 'resource_aggregation_depth' under the base category
        #    'resource_aggregation_base_category'.
        #
        resource = amount[0]
        if resource in resource_map:
          point[resource_map[amount[0]]] = amount[1]
        else:
          if amount[1] == 0:
            # If the value is zero, no need to consider.
            pass
          elif resource_aggregation_base_category is None or resource_aggregation_depth is None:
            # XXX use an appropriate error class
            # XXX should guess a base category instead of emitting an exception
            raise RuntimeError, "The resource '%s' is not found in the capacity, and the argument 'resource_aggregation_base_category' or the argument 'resource_aggregation_depth' is not specified" % resource
          else:
            # It is necessary to aggregate resources, to guess the capacity of this resource.

            def getAggregationResourceUrl(url, depth):
              # Return a partial url of the argument 'url'.
              # If 'url' is '/foo/bar/baz' and 'depth' is 2, return '/foo/bar'.
              pos = 0
              for i in range(resource_aggregation_depth):
                pos = url.find('/', pos+1)
                if pos < 0:
                  break
              if pos < 0:
                return None
              pos = url.find('/', pos+1)
              if pos < 0:
                pos = len(url)
              return url[:pos]

            def getAggregatedResourceList(aggregation_url, category, resource_list):
              # Return a list of resources which should be aggregated. 'aggregation_url' is used
              # for a top url of those resources. 'category' is a base category for the aggregation.
              aggregated_resource_list = []
              for resource in resource_list:
                for url in resource.getCategoryMembershipList(category, base=1):
                  if url.startswith(aggregation_url):
                    aggregated_resource_list.append(resource)
              return aggregated_resource_list

            def getAggregatedItemList(item_list, resource_list, aggregation_resource):
              # Return a list of association lists, which is a result of an aggregation.
              # 'resource_list' is a list of resources which should be aggregated.
              # 'aggregation_resource' is a category object which is a new resource created by
              # this aggregation.
              # 'item_list' is a list of association lists.
              new_item_list = []
              for alist in item_list:
                new_val = 0
                new_alist = []
                # If a resource is not a aggregated, then add it to the new alist as it is.
                # Otherwise, aggregate it to a single value.
                for pair in alist:
                  if pair[0] in resource_list:
                    new_val += pair[1]
                  else:
                    new_alist.append(pair)
                # If it is zero, ignore this alist, as it is nonsense.
                if new_val != 0:
                  new_alist.append([aggregation_resource, new_val])
                  new_item_list.append(new_alist)
              return new_item_list

            # Convert this to a string if necessary, for convenience.
            if type(resource_aggregation_base_category) not in (type([]), type(())):
              resource_aggregation_base_category = (resource_aggregation_base_category,)

            done = 0
#            LOG('isAmountListInsideCapacity', 0,
#                "resource_aggregation_base_category is %s" % repr(resource_aggregation_base_category))
            for category in resource_aggregation_base_category:
              for resource_url in resource.getCategoryMembershipList(category, base=1):
                aggregation_url = getAggregationResourceUrl(resource_url,
                                                            resource_aggregation_depth)
                if aggregation_url is None:
                  continue
                aggregated_resource_list = getAggregatedResourceList (aggregation_url,
                                                                      category,
                                                                      resource_map.keys())
                # If any, do the aggregation.
                if len(aggregated_resource_list) > 0:
                  aggregation_resource = self.portal_categories.resolveCategory(aggregation_url)
                  # Add the resource to the mapping.
 #                 LOG('aggregation_resource', 0, str(aggregation_resource))
                  resource_map[aggregation_resource] = index
                  index += 1
                  # Add the resource to the point.
                  point = resize(point, (index,))
                  val = 0
                  for aggregated_amount in amount_list:
                    for url in aggregated_amount[0].getCategoryMembershipList(category, base=1):
                      if url.startswith(aggregation_url):
                        val += aggregated_amount[1]
                        mask_map[aggregated_amount[0]] = None
                        break
                  point[index-1] = val
                  # Add capacity definitions of the resource into the capacity.
                  capacity_item_list += getAggregatedItemList(capacity_item_list,
                                                              aggregated_resource_list,
                                                              aggregation_resource)
                  done = 1
                  break
              if done:
                break
            if not done:
              raise RuntimeError, "Aggregation failed"

      # Build a matrix from the capacity item list.
#      LOG('resource_map', 0, str(resource_map))
      matrix = zeros((len(capacity_item_list)+1, index), 'd')
      for index in range(len(capacity_item_list)):
        for pair in capacity_item_list[index]:
          matrix[index,resource_map[pair[0]]] = pair[1]

#      LOG('isAmountListInsideCapacity', 0,
#          "matrix = %s, point = %s, capacity_item_list = %s" % (str(matrix), str(point), str(capacity_item_list)))
      return solve(matrix, point)


Jean-Paul Smets's avatar
Jean-Paul Smets committed
1553 1554
    # Asset Price Calculation
    def updateAssetPrice(self, resource, variation_text, section_category, node_category,
1555 1556 1557
                         strict_membership=0, simulation_state=None):
      if simulation_state is None:
        simulation_state = self.getPortalCurrentInventoryStateList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1558 1559 1560 1561 1562 1563
      section_value = self.portal_categories.resolveCategory(section_category)
      node_value = self.portal_categories.resolveCategory(node_category)
      # Initialize price
      current_asset_price = 0.0 # Missing: initial inventory price !!!
      current_inventory = 0.0
      # Parse each movement
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1564
      brain_list = self.Resource_zGetMovementHistoryList(resource=[resource],
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1565 1566 1567 1568
                             variation_text=variation_text,
                             section_category=section_category,
                             node_category=node_category,
                             strict_membership=strict_membership,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1569 1570 1571 1572
                             simulation_state=simulation_state) # strict_membership not taken into account
                             # We select movements related to certain nodes (ex. Stock) and sections (ex.Coramy Group)
      result = []
      for b in brain_list:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1573 1574
        m = b.getObject()
        if m is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
          previous_inventory = current_inventory
          inventory_quantity = b.quantity # We should use the aggregated quantity provided by Resource_zGetMovementHistoryList
          quantity = m.getQuantity() # The movement quantity is important to determine the meaning of source and destination
          # Maybe we should take care of target qty in delired deliveries
          if quantity is None:
            quantity = 0.0
          if m.getSourceValue() is None:
            # This is a production movement or an inventory movement
            # Use Industrial Price
            current_inventory += inventory_quantity # Update inventory
            if m.getPortalType() in ('Inventory Line', 'Inventory Cell'): # XX should be replaced by isInventory ???
              asset_price = m.getPrice()
              if asset_price in (0.0, None):
                asset_price = current_asset_price # Use current price if no price defined
            else: # this is a production
              asset_price = m.getIndustrialPrice()
              if asset_price is None: asset_price = current_asset_price  # Use current price if no price defined
            result.append((m.getRelativeUrl(), m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1593
                          m.getQuantity(), 'Production or Inventory', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1594 1595 1596 1597 1598 1599
                        ))
          elif m.getDestinationValue() is None:
            # This is a consumption movement or an inventory movement
            current_inventory += inventory_quantity # Update inventory
            asset_price = current_asset_price
            result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1600
                          m.getQuantity(), 'Consumption or Inventory', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1601
                        ))
1602
          elif m.getSourceValue().isAcquiredMemberOf(node_category) and m.getDestinationValue().isAcquiredMemberOf(node_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1603 1604 1605 1606
            # This is an internal movement
            current_inventory += inventory_quantity # Update inventory
            asset_price = current_asset_price
            result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1607
                          m.getQuantity(), 'Internal', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1608
                        ))
1609
          elif m.getSourceValue().isAcquiredMemberOf(node_category) and quantity < 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1610 1611 1612 1613
            # This is a physically inbound movement - try to use commercial price
            if m.getSourceSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1614
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1615
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1616
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1617 1618 1619 1620
                          ))
            elif m.getDestinationSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1621
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1622
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1623
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1624
                          ))
1625
            elif m.getDestinationSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1626
              current_inventory += inventory_quantity # Update inventory
1627
              if m.getDestinationValue().isAcquiredMemberOf('site/Piquage'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1628 1629 1630 1631
                # Production
                asset_price = m.getIndustrialPrice()
                if asset_price is None: asset_price = current_asset_price  # Use current price if no price defined
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1632
                              m.getQuantity(), 'Production', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1633
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1634 1635 1636
              else:
                # Inbound from same section
                asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1637
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1638
                              m.getQuantity(), 'Inbound same section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1639
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1640
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1641 1642 1643
              current_inventory += inventory_quantity # Update inventory
              asset_price = m.getPrice()
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1644
                            m.getQuantity(), 'Inbound different section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1645
                          ))
1646
          elif m.getDestinationValue().isAcquiredMemberOf(node_category) and quantity > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1647 1648 1649 1650 1651 1652
            # This is a physically inbound movement - try to use commercial price
            if m.getSourceSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
              asset_price = current_asset_price
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1653
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1654 1655 1656 1657
                          ))
            elif m.getDestinationSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1658
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1659
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1660
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1661
                          ))
1662
            elif m.getSourceSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1663
              current_inventory += inventory_quantity # Update inventory
1664
              if m.getSourceValue().isAcquiredMemberOf('site/Piquage'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1665 1666 1667 1668
                # Production
                asset_price = m.getIndustrialPrice()
                if asset_price is None: asset_price = current_asset_price  # Use current price if no price defined
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1669
                              m.getQuantity(), 'Production', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1670
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1671
              else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1672 1673 1674
                # Inbound from same section
                asset_price = current_asset_price
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1675
                            m.getQuantity(), 'Inbound same section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1676
                          ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1677
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1678 1679 1680
              current_inventory += inventory_quantity # Update inventory
              asset_price = m.getPrice()
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1681
                            m.getQuantity(), 'Inbound different section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1682 1683 1684 1685 1686 1687
                          ))
          else:
            # Outbound movement
            current_inventory += inventory_quantity # Update inventory
            asset_price = current_asset_price
            result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1688
                            m.getQuantity(), 'Outbound', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
                          ))

          # Update asset_price
          if current_inventory > 0:
            if inventory_quantity is not None:
              # Update price with an average of incoming goods and current goods
              current_asset_price = ( current_asset_price * previous_inventory + asset_price * inventory_quantity ) / float(current_inventory)
          else:
            # New price is the price of incoming goods - negative stock has no meaning for asset calculation
            current_asset_price = asset_price

          result.append(('###New Asset Price', current_asset_price, 'New Inventory', current_inventory))

          # Update Asset Price on the right side
1703
          if m.getSourceSectionValue() is not None and m.getSourceSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1704 1705
            # for each movement, source section is member of one and one only accounting category
            # therefore there is only one and one only source asset price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1706 1707 1708 1709 1710 1711 1712
            m._setSourceAssetPrice(current_asset_price)
            #quantity = m.getInventoriatedQuantity()
            #if quantity:
            #  #total_asset_price = - current_asset_price * quantity
            #  #m.Movement_zSetSourceTotalAssetPrice(uid=m.getUid(), total_asset_price = total_asset_price)
            #  m._setSourceAssetPrice(current_asset_price)
          if m.getDestinationSectionValue() is not None and m.getDestinationSectionValue().isMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1713 1714
            # for each movement, destination section is member of one and one only accounting category
            # therefore there is only one and one only destination asset price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1715 1716 1717 1718 1719
            m._setDestinationAssetPrice(current_asset_price)
            #quantity = m.getInventoriatedQuantity()
            #if quantity:
            #  total_asset_price = current_asset_price * quantity
            #  m.Movement_zSetDestinationTotalAssetPrice(uid=m.getUid(), total_asset_price = total_asset_price)
1720 1721 1722
          # Global reindexing required afterwards in any case: so let us do it now
          # Until we get faster methods (->reindexObject())
          #m.immediateReindexObject()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1723
          m.reindexObject()
1724
          #m.activate(priority=7).immediateReindexObject() # Too slow
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1725 1726

      return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1727

1728 1729 1730
    # Used for mergeDeliveryList.
    class MergeDeliveryListError(Exception): pass

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    security.declareProtected( Permissions.ModifyPortalContent, 'mergeDeliveryList' )
    def mergeDeliveryList(self, delivery_list):
      """
        Merge multiple deliveries into one delivery.
        All delivery lines are merged into the first one.
        The first one is therefore called main_delivery here.
        The others are cancelled.
        Return the main delivery.
      """
      # Sanity checks.
      if len(delivery_list) == 0:
1742
        raise self.MergeDeliveryListError, "No delivery is passed"
1743
      elif len(delivery_list) == 1:
1744
        raise self.MergeDeliveryListError, "Only one delivery is passed"
1745 1746 1747 1748

      main_delivery = delivery_list[0]
      delivery_list = delivery_list[1:]

1749
      # Another sanity check. It is necessary for them to be identical in some attributes.
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
      for delivery in delivery_list:
        for attr in ('portal_type', 'simulation_state',
                     'source', 'destination',
                     'source_section', 'destination_section',
                     'source_decision', 'destination_decision',
                     'source_administration', 'destination_administration',
                     'source_payment', 'destination_payment'):
          main_value = main_delivery.getProperty(attr)
          value = delivery.getProperty(attr)
          if  main_value != value:
1760 1761 1762 1763
            raise self.MergeDeliveryListError, \
              "%s is not the same between %s and %s (%s and %s)" % (attr, delivery.getId(), main_delivery.getId(), value, main_value)

      # One more sanity check. Check if discounts are the same, if any.
1764
      main_discount_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()})
1765
      for delivery in delivery_list:
1766
        discount_list = delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()})
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
        if len(main_discount_list) != len(discount_list):
          raise self.MergeDeliveryListError, "Discount is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())
        for discount in discount_list:
          for main_discount in main_discount_list:
            if discount.getDiscount() == main_discount.getDiscount() \
               and discount.getDiscountRatio() == main_discount.getDiscountRatio() \
               and discount.getDiscountType() == main_discount.getDiscountType() \
               and discount.getImmediateDiscount() == main_discount.getImmediateDiscount():
              break
          else:
            raise self.MergeDeliveryListError, "Discount is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())

      # One more sanity check. Check if payment conditions are the same, if any.
1780
      main_payment_condition_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()})
1781
      for delivery in delivery_list:
1782
        payment_condition_list = delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()})
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
        if len(main_payment_condition_list) != len(payment_condition_list):
          raise self.MergeDeliveryListError, "Payment Condition is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())
        for condition in payment_condition_list:
          for main_condition in main_payment_condition_list:
            if condition.getPaymentMode() == main_condition.getPaymentMode() \
               and condition.getPaymentAdditionalTerm() == main_condition.getPaymentAdditionalTerm() \
               and condition.getPaymentAmount() == main_condition.getPaymentAmount() \
               and condition.getPaymentEndOfMonth() == main_condition.getPaymentEndOfMonth() \
               and condition.getPaymentRatio() == main_condition.getPaymentRatio() \
               and condition.getPaymentTerm() == main_condition.getPaymentTerm():
              break
          else:
            raise self.MergeDeliveryListError, "Payment Condition is not the same between %s and %s" % (delivery.getId(), main_delivery.getId())
1796 1797 1798

      # Make sure that all activities are flushed, to get simulation movements from delivery cells.
      for delivery in delivery_list:
1799
        for order in delivery.getCausalityValueList(portal_type = self.getPortalOrderTypeList()):
1800 1801
          for applied_rule in order.getCausalityRelatedValueList(portal_type = 'Applied Rule'):
            applied_rule.flushActivity(invoke = 1)
1802
        for causality_related_delivery in delivery.getCausalityValueList(portal_type = self.getPortalDeliveryTypeList()):
1803 1804
          for applied_rule in causality_related_delivery.getCausalityRelatedValueList(portal_type = 'Applied Rule'):
            applied_rule.flushActivity(invoke = 1)
1805

1806 1807 1808 1809 1810
      # Get a list of simulated movements and invoice movements.
      main_simulated_movement_list = main_delivery.getSimulatedMovementList()
      main_invoice_movement_list = main_delivery.getInvoiceMovementList()
      simulated_movement_list = main_simulated_movement_list[:]
      invoice_movement_list = main_invoice_movement_list[:]
1811
      for delivery in delivery_list:
1812 1813 1814
        simulated_movement_list.extend(delivery.getSimulatedMovementList())
        invoice_movement_list.extend(delivery.getInvoiceMovementList())

1815 1816 1817 1818
      #for movement in simulated_movement_list + invoice_movement_list:
      #  parent = movement.aq_parent
      #  LOG('mergeDeliveryList', 0, 'movement = %s, parent = %s, movement.getPortalType() = %s, parent.getPortalType() = %s' % (repr(movement), repr(parent), repr(movement.getPortalType()), repr(parent.getPortalType())))

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
      LOG('mergeDeliveryList', 0, 'simulated_movement_list = %s, invoice_movement_list = %s' % (str(simulated_movement_list), str(invoice_movement_list)))
      for main_movement_list, movement_list in \
        ((main_simulated_movement_list, simulated_movement_list),
         (main_invoice_movement_list, invoice_movement_list)):
        root_group = self.collectMovement(movement_list,
                                          check_order = 0,
                                          check_path = 0,
                                          check_date = 0,
                                          check_criterion = 1,
                                          check_resource = 1,
                                          check_base_variant = 1,
                                          check_variant = 1)
1831 1832 1833 1834 1835 1836 1837 1838 1839
        for criterion_group in root_group.group_list:
          LOG('mergeDeliveryList dump tree', 0, 'criterion = %s, movement_list = %s, group_list = %s' % (repr(criterion_group.criterion), repr(criterion_group.movement_list), repr(criterion_group.group_list)))
          for resource_group in criterion_group.group_list:
            LOG('mergeDeliveryList dump tree', 0, 'resource = %s, movement_list = %s, group_list = %s' % (repr(resource_group.resource), repr(resource_group.movement_list), repr(resource_group.group_list)))
            for base_variant_group in resource_group.group_list:
              LOG('mergeDeliveryList dump tree', 0, 'base_category_list = %s, movement_list = %s, group_list = %s' % (repr(base_variant_group.base_category_list), repr(base_variant_group.movement_list), repr(base_variant_group.group_list)))
              for variant_group in base_variant_group.group_list:
                LOG('mergeDeliveryList dump tree', 0, 'category_list = %s, movement_list = %s, group_list = %s' % (repr(variant_group.category_list), repr(variant_group.movement_list), repr(variant_group.group_list)))

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
        for criterion_group in root_group.group_list:
          for resource_group in criterion_group.group_list:
            for base_variant_group in resource_group.group_list:
              # Get a list of categories.
              category_dict = {}
              for variant_group in base_variant_group.group_list:
                for category in variant_group.category_list:
                  category_dict[category] = 1
              category_list = category_dict.keys()

              # Try to find a delivery line.
              delivery_line = None
              for movement in base_variant_group.movement_list:
                if movement in main_movement_list:
1854 1855
                  if movement.aq_parent.getPortalType() in self.getPortalSimulatedMovementTypeList() \
                    or movement.aq_parent.getPortalType() in self.getPortalInvoiceMovementTypeList():
1856 1857 1858 1859 1860
                    delivery_line = movement.aq_parent
                  else:
                    delivery_line = movement
                  LOG('mergeDeliveryList', 0, 'delivery_line %s is found: criterion = %s, resource = %s, base_category_list = %s' % (repr(delivery_line), repr(criterion_group.criterion), repr(resource_group.resource), repr(base_variant_group.base_category_list)))
                  break
1861

1862 1863 1864
              if delivery_line is None:
                # Not found. So create a new delivery line.
                movement = base_variant_group.movement_list[0]
1865 1866
                if movement.aq_parent.getPortalType() in self.getPortalSimulatedMovementTypeList() \
                  or movement.aq_parent.getPortalType() in self.getPortalInvoiceMovementTypeList():
1867
                  delivery_line_type = movement.aq_parent.getPortalType()
1868
                else:
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
                  delivery_line_type = movement.getPortalType()
                delivery_line = main_delivery.newContent(portal_type = delivery_line_type,
                                                         resource = resource_group.resource)
                LOG('mergeDeliveryList', 0, 'New delivery_line %s is created: criterion = %s, resource = %s, base_category_list = %s' % (repr(delivery_line), repr(criterion_group.criterion), repr(resource_group.resource), repr(base_variant_group.base_category_list)))

              # Update the base categories and categories.
              #LOG('mergeDeliveryList', 0, 'base_category_list = %s, category_list = %s' % (repr(base_category_list), repr(category_list)))
              delivery_line.setVariationBaseCategoryList(base_variant_group.base_category_list)
              delivery_line.setVariationCategoryList(category_list)

1879
              object_to_update = None
1880 1881 1882 1883 1884 1885
              for variant_group in base_variant_group.group_list:
                if len(variant_group.category_list) == 0:
                  object_to_update = delivery_line
                else:
                  for delivery_cell in delivery_line.contentValues():
                    predicate_value_list = delivery_cell.getPredicateValueList()
1886
                    LOG('mergeDeliveryList', 0, 'delivery_cell = %s, predicate_value_list = %s, variant_group.category_list = %s' % (repr(delivery_cell), repr(predicate_value_list), repr(variant_group.category_list)))
1887 1888 1889 1890 1891 1892 1893
                    if len(predicate_value_list) == len(variant_group.category_list):
                      for category in variant_group.category_list:
                        if category not in predicate_value_list:
                          break
                      else:
                        object_to_update = delivery_cell
                        break
1894

1895
                #LOG('mergeDeliveryList', 0, 'object_to_update = %s' % repr(object_to_update))
1896
                if object_to_update is not None:
1897
                  cell_price = object_to_update.getPrice() or 0.0
1898
                  cell_quantity = object_to_update.getQuantity() or 0.0
1899
                  cell_target_quantity = object_to_update.getNetConvertedTargetQuantity() or 0.0 # XXX What to do ?
1900
                  cell_total_price = cell_target_quantity * cell_price
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
                  cell_category_list = list(object_to_update.getCategoryList())

                  for movement in variant_group.movement_list:
                    if movement in main_movement_list:
                      continue
                    LOG('mergeDeliveryList', 0, 'movement = %s' % repr(movement))
                    cell_quantity += movement.getQuantity()
                    cell_target_quantity += movement.getNetConvertedTargetQuantity()
                    try:
                      # XXX WARNING - ADD PRICED QUANTITY
1911 1912
                      cell_price = movement.getPrice()
                      cell_total_price += movement.getNetConvertedTargetQuantity() * cell_price
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
                    except:
                      cell_total_price = None
                    for category in movement.getCategoryList():
                      if category not in cell_category_list:
                        cell_category_list.append(category)
                    # Make sure that simulation movements point to an appropriate delivery line or
                    # delivery cell.
                    if hasattr(movement, 'getDeliveryRelatedValueList'):
                      for simulation_movement in \
                        movement.getDeliveryRelatedValueList(portal_type = 'Simulation Movement'):
                        simulation_movement.setDeliveryValue(object_to_update)
                        #simulation_movement.reindexObject()
                    if hasattr(movement, 'getOrderRelatedValueList'):
                      for simulation_movement in \
                        movement.getOrderRelatedValueList(portal_type = 'Simulation Movement'):
                        simulation_movement.setOrderValue(object_to_update)
                        #simulation_movement.reindexObject()

                  if cell_target_quantity != 0 and cell_total_price is not None:
                    average_price = cell_total_price / cell_target_quantity
                  else:
                    average_price = 0

1936
                  LOG('mergeDeliveryList', 0, 'object_to_update = %s, cell_category_list = %s, cell_target_quantity = %s, cell_quantity = %s, average_price = %s' % (repr(object_to_update), repr(cell_category_list), repr(cell_target_quantity), repr(cell_quantity), repr(average_price)))
1937
                  object_to_update.setCategoryList(cell_category_list)
1938
                  if object_to_update.getPortalType() in self.getPortalSimulatedMovementTypeList():
1939 1940 1941 1942
                    object_to_update.edit(target_quantity = cell_target_quantity,
                                          quantity = cell_quantity,
                                          price = average_price,
                                          )
1943
                  elif object_to_update.getPortalType() in self.getPortalInvoiceMovementTypeList():
1944 1945 1946 1947 1948 1949 1950
                    # Invoices do not have target quantities, and the price never change.
                    object_to_update.edit(quantity = cell_quantity,
                                          price = cell_price,
                                          )
                  else:
                    raise self.MergeDeliveryListError, "Unknown portal type %s" % str(object_to_update.getPortalType())
                  #object_to_update.immediateReindexObject()
1951 1952 1953 1954 1955
                else:
                  raise self.MergeDeliveryListError, "No object to update"

      # Merge containers. Just copy them from other deliveries into the main.
      for delivery in delivery_list:
1956
        container_id_list = delivery.contentIds(filter = {'portal_type': self.getPortalContainerTypeList()})
1957 1958 1959
        if len(container_id_list) > 0:
          copy_data = delivery.manage_copyObjects(ids = container_id_list)
          new_id_list = main_delivery.manage_pasteObjects(copy_data)
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980

      # Unify the list of causality.
      causality_list = main_delivery.getCausalityValueList()
      for delivery in delivery_list:
        for causality in delivery.getCausalityValueList():
          if causality not in causality_list:
            causality_list.append(causality)
      LOG("mergeDeliveryList", 0, "causality_list = %s" % str(causality_list))
      main_delivery.setCausalityValueList(causality_list)

      # Cancel deliveries.
      for delivery in delivery_list:
        LOG("mergeDeliveryList", 0, "cancelling %s" % repr(delivery))
        delivery.cancel()

      # Reindex the main delivery.
      main_delivery.reindexObject()

      return main_delivery


1981
InitializeClass(SimulationTool)