SimulationTool.py 74.1 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3
# Copyright (c) 2002, 2005 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
5
#                    Romain Courteaud <romain@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#
# 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
34
from Products.ERP5Type.Document.Folder import Folder
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35
from Products.ERP5Type import Permissions
36
from Products.ERP5Type.Tool.BaseTool import BaseTool
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38 39 40 41 42 43

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
44
from DateTime import DateTime
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45

46 47
from Products.ERP5 import DeliverySolver
from Products.ERP5 import TargetSolver
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

49
class SimulationTool (BaseTool):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    """
    The SimulationTool implements the ERP5
    simulation algorithmics.


    Examples of applications:

    -

    -
    ERP5 main purpose:

    -

    -

    """
    id = 'portal_simulation'
    meta_type = 'ERP5 Simulation Tool'
69
    portal_type = 'Simulation Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    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))
90 91
    #def __init__(self):
    #    return Folder.__init__(self, SimulationTool.id)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
92 93 94 95 96 97 98 99 100 101 102

    # 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

103 104 105 106
    def tpValues(self) :
      """ show the content in the left pane of the ZMI """
      return self.objectValues()

107 108 109 110 111 112 113 114 115 116 117 118 119
    def solveDelivery(self, delivery, dsolver_name, tsolver_name, 
                                     additional_parameters=None,**kw):
      """
        Solve a delivery by calling DeliverySolver and TargetSolver
      """
      self.solveMovementOrDelivery(delivery, dsolver_name, tsolver_name,
          delivery=1,additional_parameters=additional_parameters,**kw)
      
    def solveMovement(self, movement, dsolver_name, tsolver_name, 
                                       additional_parameters=None,**kw):
      """
        Solve a movement by calling DeliverySolver and TargetSolver
      """
120
      return self.solveMovementOrDelivery(movement, dsolver_name, tsolver_name,
121 122 123 124 125
          movement=1,additional_parameters=additional_parameters,**kw)
      
    def solveMovementOrDelivery(self, obj, dsolver_name, tsolver_name, 
                                          movement=0,delivery=0,
                                          additional_parameters=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
126
      """
127
        Solve a delivery by calling DeliverySolver and TargetSolver
Jean-Paul Smets's avatar
Jean-Paul Smets committed
128
      """
129 130 131 132 133 134 135 136 137
      for solver_name, solver_module in [(dsolver_name, DeliverySolver),\
                                         (tsolver_name, TargetSolver)]:

        if solver_name is not None:
          solver_file_path = "%s.%s" % (solver_module.__name__,
                                        solver_name)
          __import__(solver_file_path)
          solver_file = getattr(solver_module, solver_name)
          solver_class = getattr(solver_file, solver_name)
138
          solver = solver_class(additional_parameters=additional_parameters,**kw)
139

140
          if movement:
141
            return solver.solveMovement(obj)
142
          if delivery:
143
            return solver.solveDelivery(obj)
144
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
145 146
    #######################################################
    # Stock Management
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
    def _generatePropertyUidList(self, property, as_text=0):
      """
      converts relative_url or text (single element or list or dict)
        to an object usable by buildSQLQuery

      as_text == 0: tries to lookup an uid from the relative_url
      as_text == 1: directly passes the argument as text
      """
      property_uid_list = []
      if type(property) is type('') :
        if as_text == 0:
          property_uid_list.append(self.portal_categories.getCategoryValue(property).getUid())
        else:
          property_uid_list.append(property)
      elif type(property) is type([]) or type(property) is type(()) :
        for property_item in property :
          if as_text == 0:
            property_uid_list.append(self.portal_categories.getCategoryValue(property_item).getUid())
          else:
            property_uid_list.append(property_item)
      elif type(property) is type({}) :
        tmp_uid_list = []
        if type(property['query']) is type('') :
          property['query'] = [property['query']]
        for property_item in property['query'] :
          if as_text == 0:
            tmp_uid_list.append(self.portal_categories.getCategoryValue(property_item).getUid())
          else:
            tmp_uid_list.append(property_item)
        if len(tmp_uid_list) :
          property_uid_list = {}
          property_uid_list['operator'] = property['operator']
          property_uid_list['query'] = tmp_uid_list
      return property_uid_list

183 184
    def _generateSQLKeywordDict(self, table='stock',
        from_date=None, to_date=None, at_date=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
185
        resource=None, node=None, payment=None,
186
        section=None, mirror_section=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
187
        resource_category=None, node_category=None, payment_category=None,
188
        section_category=None, mirror_section_category=None,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
189
        simulation_state=None, transit_simulation_state = None, omit_transit=0,
190
        input_simulation_state = None, output_simulation_state=None,
191
        variation_text=None, sub_variation_text=None,
192
        variation_category=None,is_accountable=None,
193
        **kw) :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
194
      """
195
      generates keywork and calls buildSqlQuery
Alexandre Boeglin's avatar
Alexandre Boeglin committed
196 197 198 199 200 201 202 203 204 205 206 207
      """
      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'
208 209 210
        elif at_date :
          date_dict['query'].append(at_date)
          date_dict['range'] = 'minngt'
Alexandre Boeglin's avatar
Alexandre Boeglin committed
211 212 213 214 215 216 217
      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) :
218
        new_kw[table + '.date'] = date_dict
Alexandre Boeglin's avatar
Alexandre Boeglin committed
219

220
      resource_uid_list = self._generatePropertyUidList(resource)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
221
      if len(resource_uid_list) :
222
        new_kw[table + '.resource_uid'] = resource_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
223

224 225 226
      if is_accountable is not None:
        new_kw[table + '.is_accountable'] = is_accountable

227
      node_uid_list = self._generatePropertyUidList(node)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
228
      if len(node_uid_list) :
229
        new_kw[table + '.node_uid'] = node_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
230

231
      payment_uid_list = self._generatePropertyUidList(payment)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
232
      if len(payment_uid_list) :
233
        new_kw[table + '.payment_uid'] = payment_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
234

235
      section_uid_list = self._generatePropertyUidList(section)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
236
      if len(section_uid_list) :
237
        new_kw[table + '.section_uid'] = section_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
238

239
      mirror_section_uid_list = self._generatePropertyUidList(mirror_section)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
240
      if len(mirror_section_uid_list) :
241
        new_kw[table + '.mirror_section_uid'] = mirror_section_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
242

243
      variation_text_list = self._generatePropertyUidList(variation_text, as_text=1)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
244
      if len(variation_text_list) :
245
        new_kw[table + '.variation_text'] = variation_text_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
246

247 248 249 250
      sub_variation_text_list = self._generatePropertyUidList(sub_variation_text, as_text=1)
      if len(sub_variation_text_list) :
        new_kw[table + '.sub_variation_text'] = sub_variation_text_list

251
      resource_category_uid_list = self._generatePropertyUidList(resource_category)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
252
      if len(resource_category_uid_list) :
253
        new_kw[table + '_resourceCategory'] = resource_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
254

255
      node_category_uid_list = self._generatePropertyUidList(node_category)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
256
      if len(node_category_uid_list) :
257
        new_kw[table + '_nodeCategory'] = node_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
258

259
      payment_category_uid_list = self._generatePropertyUidList(payment_category)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
260
      if len(payment_category_uid_list) :
261
        new_kw[table + '_paymentCategory'] = payment_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
262

263
      section_category_uid_list = self._generatePropertyUidList(section_category)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
264
      if len(section_category_uid_list) :
265
        new_kw[table + '_sectionCategory'] = section_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
266

267
      mirror_section_category_uid_list = self._generatePropertyUidList(mirror_section_category)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
268
      if len(mirror_section_category_uid_list) :
269
        new_kw[table + '_mirrorSectionCategory'] = mirror_section_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
270

271 272 273
      #variation_category_uid_list = self._generatePropertyUidList(variation_category)
      #if len(variation_category_uid_list) :
      #  new_kw['variationCategory'] = variation_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
274 275 276 277 278

      # 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) :
279 280
          sql_kw['input_simulation_state'] = simulation_state
          sql_kw['output_simulation_state'] = simulation_state
Alexandre Boeglin's avatar
Alexandre Boeglin committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
      # 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)
296
                sql_kw['input_simulation_state'] = delivered_simulation_state_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
297 298 299
      # 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) :
300
          sql_kw['input_simulation_state'] = input_simulation_state
Alexandre Boeglin's avatar
Alexandre Boeglin committed
301 302
      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) :
303 304 305 306 307
          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
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
      # It is necessary to use here another SQL query (or at least a subquery)
      # to get _DISTINCT_ uid from predicate_category table.
      # Otherwise, by using a where_expression, cells which fit conditions
      # more than one time are counted more than one time, and the resulting
      # inventory is false
      # XXX Perhaps is there a better solution
      add_kw = {}
      if variation_category is not None and len(variation_category)>0:
        where_expression = self.portal_categories.buildSQLSelector(
            category_list = variation_category,
            query_table = 'predicate_category')
        if where_expression != '':
          add_kw['where_expression'] = where_expression
          add_kw['predicate_category.uid'] = '!=NULL'
          add_kw['group_by_expression'] = 'uid'
          add_query = self.portal_catalog(**add_kw)
          uid_list = []
          for line in add_query:
            uid_list.append(line.uid)
          new_kw['where_expression'] = '( %s )' % ' OR '.join(['catalog.uid=%s' % uid for uid in uid_list])
Alexandre Boeglin's avatar
Alexandre Boeglin committed
329

Sebastien Robin's avatar
Sebastien Robin committed
330 331 332 333
      # build the group by expression
      group_by_expression_list = []
      if kw.get('group_by_node',0):
        group_by_expression_list.append('stock.node_uid')
334 335
      if kw.get('group_by_sub_variation',0):
        group_by_expression_list.append('stock.sub_variation_text')
Sebastien Robin's avatar
Sebastien Robin committed
336 337 338 339 340 341
      if kw.get('group_by_variation',0):
        group_by_expression_list.append('stock.variation_text')
      if len(group_by_expression_list):
        group_by_expression_list.append('stock.resource_uid') # Always group by resource
        sql_kw['group_by_expression'] = ', '.join(group_by_expression_list)

342
      sql_kw.update(self.portal_catalog.buildSQLQuery(**new_kw))
343 344
      return sql_kw

Jean-Paul Smets's avatar
Jean-Paul Smets committed
345 346
    #######################################################
    # Inventory management                  
347 348 349 350 351
    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) :
      """
352 353 354
      Returns an inventory of a single or multiple resources on a single or multiple
      nodes as a single float value
      
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
      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

385 386
      sub_variation_text - only take rows in stock table with specified variation_text

387
      variation_category - variation or list of possible variations (it is not a cross-search ; SQL query uses OR)
388 389 390

      simulation_state - only take rows with specified simulation_state

391
      transit_simulation_state - specifies which states are transit states
392 393 394 395 396 397 398

      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

399 400
      ignore_variation - do not take into account variation in inventory calculation (useless on getInventory,
                         but useful on getInventoryList)
401

402
      standardise - provide a standard quantity rather than an SKU (XXX not implemented yet)
403 404 405 406 407 408 409

      omit_simulation

      omit_input

      omit_output

410 411
      is_accountable - 0 or 1. Select only movement from deliveries, not orders

412 413
      selection_domain, selection_report - see ListBox

414
      group_by_variation (useless on getInventory, but useful on getInventoryList)
Sebastien Robin's avatar
Sebastien Robin committed
415

416
      group_by_node (useless on getInventory, but useful on getInventoryList)
Sebastien Robin's avatar
Sebastien Robin committed
417

418 419
      group_by_sub_variation (useless on getInventory, but useful on getInventoryList)

420 421
      **kw  - if we want extended selection with more keywords (but bad performance)
              check what we can do with buildSqlQuery
422 423 424
      
      NOTE: we may want to define a parameter so that we can select the kind of inventory
      statistics we want to display (ex. sum, average, cost, etc.)      
425 426 427
      """
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
428
      result = self.Resource_zGetInventory(src__=src__,
429
          ignore_variation=ignore_variation, standardise=standardise, omit_simulation=omit_simulation,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
430 431
          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
432 433 434
      if src__ :
        return result

435 436 437 438 439 440 441
      total_result = 0.0
      if len(result) > 0:
        for result_line in result:
          if result_line.inventory is not None:
            total_result += result_line.inventory

      return total_result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
442

Alexandre Boeglin's avatar
Alexandre Boeglin committed
443 444 445 446 447 448 449 450 451 452 453 454
    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
455
      (current inventory - reserved)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
456
      """
457 458
      kw['simulation_state'] = tuple(list(self.getPortalReservedInventoryStateList())
                                  +  list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
459 460 461 462 463 464 465
      return self.getInventory(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventory')
    def getFutureInventory(self, **kw):
      """
      Returns future inventory
      """
466
      kw['simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
467 468
                                   + list(self.getPortalReservedInventoryStateList())
                                   + list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
469 470
      return self.getInventory(**kw)

Romain Courteaud's avatar
Romain Courteaud committed
471 472 473 474 475
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventoryList')
    def getInventoryList(self, src__=0, ignore_variation=0, standardise=0, 
                         omit_simulation=0, omit_input=0, omit_output=0,
                         selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
476
      """
Romain Courteaud's avatar
Romain Courteaud committed
477 478 479 480 481 482 483
        Returns a list of inventories for a single or multiple 
        resources on a single or multiple nodes, grouped by resource, 
        node, section, etc. Every line defines an inventory value for 
        a given group of resource, node, section.
        NOTE: we may want to define a parameter so that we can select 
        the kind of inventory statistics we want to display (ex. sum, 
        average, cost, etc.)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
484
      """
485
      sql_kw = self._generateSQLKeywordDict(**kw)
Romain Courteaud's avatar
Romain Courteaud committed
486 487 488 489 490 491 492 493 494
      return self.Resource_zGetInventoryList(
                    src__=src__, 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, 
                              'getCurrentInventoryList')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
495 496
    def getCurrentInventoryList(self, **kw):
      """
Romain Courteaud's avatar
Romain Courteaud committed
497
        Returns list of current inventory grouped by section or site
Alexandre Boeglin's avatar
Alexandre Boeglin committed
498
      """
499
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
500 501
      return self.getInventoryList(**kw)

Romain Courteaud's avatar
Romain Courteaud committed
502 503
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getFutureInventoryList')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
504 505
    def getFutureInventoryList(self, **kw):
      """
Romain Courteaud's avatar
Romain Courteaud committed
506
        Returns list of future inventory grouped by section or site
Alexandre Boeglin's avatar
Alexandre Boeglin committed
507
      """
Romain Courteaud's avatar
Romain Courteaud committed
508 509 510 511
      kw['simulation_state'] = tuple(
                 list(self.getPortalFutureInventoryStateList()) +\
                 list(self.getPortalReservedInventoryStateList()) +\
                 list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
512 513 514
      return self.getInventoryList(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryStat')
515
    def getInventoryStat(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
516
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
517
        selection_domain=None, selection_report=None, **kw) :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
518
      """
519 520 521
      getInventoryStat is the pending to getInventoryList in order to provide
      statistics on getInventoryList lines in ListBox such as: total of inventories,
      number of variations, number of different nodes, etc.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
522
      """
523 524
      sql_kw = self._generateSQLKeywordDict(**kw)

525
      result = self.Resource_zGetInventory(src__=src__,
526 527 528
          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)
529 530 531
      if src__ :
        return result
      
532 533 534 535 536
      total_result = 0
      for row in result :
        total_result += row.stock_uid
      return total_result
      
Alexandre Boeglin's avatar
Alexandre Boeglin committed
537 538 539 540 541
    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryStat')
    def getCurrentInventoryStat(self, **kw):
      """
      Returns statistics of current inventory grouped by section or site
      """
542
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
543 544 545 546 547 548 549
      return self.getInventoryStat(**kw)

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

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryChart')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
555
    def getInventoryChart(self, src__=0, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
556
      """
557 558 559 560 561
      Returns a list of couples derived from getInventoryList in order
      to feed a chart renderer. Each couple consist of a label
      (node, section, payment, combination of node & section, etc.) and an inventory value.
      
      Mostly useful for charts in ERP5 forms.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
562
      """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
563
      result = self.getInventoryList(src__=src__, **kw)
564
      if src__ :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
565
        return result
566 567

      return map(lambda r: (r.node_title, r.inventory), result)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
568 569 570 571 572 573

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

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

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryAssetPrice')
587
    def getInventoryAssetPrice(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
588
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
589
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
590
      """
591 592 593 594
      Same thing as getInventory but returns an asset 
      price rather than an inventory.
      
      NOTE: implementation could be merged with getInventory
Alexandre Boeglin's avatar
Alexandre Boeglin committed
595
      """
596 597
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
598
      return self.Resource_zGetInventoryAssetPrice(src__=src__,
599 600 601
          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
602 603 604 605 606 607

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryAssetPrice')
    def getCurrentInventoryAssetPrice(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
608
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
609 610 611 612 613 614 615 616
      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)
      """
617
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
618 619 620 621 622 623 624
      return self.getInventoryAssetPrice(**kw)

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

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryHistoryList')
630
    def getInventoryHistoryList(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
631
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
632
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
633
      """
634 635 636
      Returns a time based serie of inventory values
      for a single or a group of resource, node, section, etc. This is useful
      to list the evolution with time of inventory values (quantity, asset price).
Alexandre Boeglin's avatar
Alexandre Boeglin committed
637
      """
638 639
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
640
      return self.Resource_getInventoryHistoryList(src__=src__,
641 642 643
          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
644 645

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryHistoryChart')
646
    def getInventoryHistoryChart(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
647
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
648
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
649
      """
650 651 652 653 654
      getInventoryHistoryChart is the pensing to getInventoryHistoryList
      to ease the rendering of time based graphs which show the evolution
      of one ore more inventories. Each item in the serie consists of
      time, value and "colour" (multiple graphs can be drawn for example
      for each variation of a resource)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
655
      """
656 657
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
658
      return self.Resource_getInventoryHistoryChart(src__=src__,
659 660 661
          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
662 663

    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementHistoryList')
664
    def getMovementHistoryList(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
665
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
666
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
667
      """
668 669
      Returns a list of movements which modify the inventory
      for a single or a group of resource, node, section, etc.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
670
      """
671 672
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
673
      return self.Resource_zGetMovementHistoryList(src__=src__,
674 675 676
          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
677 678

    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementHistoryStat')
679
    def getMovementHistoryStat(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
680
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
681
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
682
      """
683
      getMovementHistoryStat is the pending to getMovementHistoryList for ListBox stat
Alexandre Boeglin's avatar
Alexandre Boeglin committed
684
      """
685 686
      sql_kw = self._generateSQLKeywordDict(**kw)

Alexandre Boeglin's avatar
Alexandre Boeglin committed
687
      return self.Resource_zGetInventory(src__=src__,
688 689 690
          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
691 692

    security.declareProtected(Permissions.AccessContentsInformation, 'getNextNegativeInventoryDate')
693
    def getNextNegativeInventoryDate(self, src__=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
694
        ignore_variation=0, standardise=0, omit_simulation=0, omit_input=0, omit_output=0,
695
        selection_domain=None, selection_report=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
696 697 698
      """
      Returns statistics of inventory grouped by section or site
      """
699 700 701
      sql_kw = self._generateSQLKeywordDict(order_by_expression='stock.date', **kw)
      sql_kw['group_by_expression'] = 'stock.uid'
      sql_kw['order_by_expression'] = 'stock.date'
702

703
      result = self.Resource_zGetInventory(src__=src__,
704 705 706
          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
707 708
      if src__ :
        return result
709

710
      total_inventory = 0.
711
      for inventory in result:
712 713 714 715 716
        if inventory['inventory'] is not None:
          total_inventory += inventory['inventory']
          if total_inventory < 0:
            return inventory['date']

717
      return None
Alexandre Boeglin's avatar
Alexandre Boeglin committed
718

Jean-Paul Smets's avatar
Jean-Paul Smets committed
719 720 721 722 723 724
    #######################################################
    # Traceability management                  
    security.declareProtected(Permissions.AccessContentsInformation, 'getTrackingList')
    def getTrackingList(self, src__=0,
        selection_domain=None, selection_report=None, **kw) :
      """
725
      Returns a list of items in the form
Jean-Paul Smets's avatar
Jean-Paul Smets committed
726 727 728 729 730 731 732
      
        uid (of item)
        date
        node_uid
        section_uid
        resource_uid
        variation_text
733 734 735 736 737 738 739 740 741 742
      
      If at_date is provided, returns the a list which answers
      to the question "where are those items at this date" or
      "which are those items which are there a this date"

      If at_date is not provided, returns a history of positions
      which answers the question "where have those items been
      between this time and this time". This will be handled by
      something like getTrackingHistoryList
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
743 744 745 746 747 748 749 750 751
      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.
      
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
      Default sort orders is based on dates, reverse.


      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

      section        -  only take rows in stock table which section_uid is equivalent to 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

      section_category        -  only take rows in stock table which section_uid is in 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

      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
      
Jean-Paul Smets's avatar
Jean-Paul Smets committed
794
      """
795 796 797 798 799 800 801 802 803 804
      new_kw = {}
      new_kw['at_date'] = kw.get('at_date')
      new_kw['node_uid'] = self.portal_categories.getCategoryUid(kw.get('node'))

      section_uid_list = self._generatePropertyUidList(kw.get('section'))
      if len(section_uid_list) :
        new_kw['section_uid_list'] = section_uid_list

      for property_name in ('portal_type', 'variation_text', 'simulation_state'):
        property_list = self._generatePropertyUidList(kw.get(property_name), as_text=1)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
805 806
        if len(property_list) :
          new_kw['%s_list' % property_name] = property_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
807

808
      return self.Resource_zGetTrackingList(src__=src__, **new_kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826

    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
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
    #######################################################
    # 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()
854 855
      start_date = movement.getStartDate()
      stop_date = movement.getStopDate()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 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 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
      # 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
1048 1049
    # Asset Price Calculation
    def updateAssetPrice(self, resource, variation_text, section_category, node_category,
1050 1051 1052
                         strict_membership=0, simulation_state=None):
      if simulation_state is None:
        simulation_state = self.getPortalCurrentInventoryStateList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1053 1054 1055 1056 1057 1058
      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
1059
      brain_list = self.Resource_zGetMovementHistoryList(resource=[resource],
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1060 1061 1062 1063
                             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
1064 1065 1066 1067
                             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
1068 1069
        m = b.getObject()
        if m is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
          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(),
1088
                          m.getQuantity(), 'Production or Inventory', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1089 1090 1091 1092 1093 1094
                        ))
          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(),
1095
                          m.getQuantity(), 'Consumption or Inventory', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1096
                        ))
1097
          elif m.getSourceValue().isAcquiredMemberOf(node_category) and m.getDestinationValue().isAcquiredMemberOf(node_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1098 1099 1100 1101
            # 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(),
1102
                          m.getQuantity(), 'Internal', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1103
                        ))
1104
          elif m.getSourceValue().isAcquiredMemberOf(node_category) and quantity < 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1105 1106 1107 1108
            # 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
1109
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1110
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1111
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1112 1113 1114 1115
                          ))
            elif m.getDestinationSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1116
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1117
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1118
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1119
                          ))
1120
            elif m.getDestinationSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1121
              current_inventory += inventory_quantity # Update inventory
1122
              if m.getDestinationValue().isAcquiredMemberOf('site/Piquage'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1123 1124 1125 1126
                # 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(),
1127
                              m.getQuantity(), 'Production', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1128
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1129 1130 1131
              else:
                # Inbound from same section
                asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1132
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1133
                              m.getQuantity(), 'Inbound same section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1134
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1135
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1136 1137 1138
              current_inventory += inventory_quantity # Update inventory
              asset_price = m.getPrice()
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1139
                            m.getQuantity(), 'Inbound different section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1140
                          ))
1141
          elif m.getDestinationValue().isAcquiredMemberOf(node_category) and quantity > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1142 1143 1144 1145 1146 1147
            # 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(),
1148
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1149 1150 1151 1152
                          ))
            elif m.getDestinationSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1153
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1154
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1155
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1156
                          ))
1157
            elif m.getSourceSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1158
              current_inventory += inventory_quantity # Update inventory
1159
              if m.getSourceValue().isAcquiredMemberOf('site/Piquage'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1160 1161 1162 1163
                # 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(),
1164
                              m.getQuantity(), 'Production', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1165
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1166
              else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1167 1168 1169
                # Inbound from same section
                asset_price = current_asset_price
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1170
                            m.getQuantity(), 'Inbound same section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1171
                          ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1172
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1173 1174 1175
              current_inventory += inventory_quantity # Update inventory
              asset_price = m.getPrice()
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1176
                            m.getQuantity(), 'Inbound different section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1177 1178 1179 1180 1181 1182
                          ))
          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(),
1183
                            m.getQuantity(), 'Outbound', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
                          ))

          # 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
1198
          if m.getSourceSectionValue() is not None and m.getSourceSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1199 1200
            # 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
1201 1202 1203 1204 1205 1206 1207
            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
1208 1209
            # 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
1210 1211 1212 1213 1214
            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)
1215 1216 1217
          # 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
1218
          m.reindexObject()
1219
          #m.activate(priority=7).immediateReindexObject() # Too slow
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1220 1221

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

1223 1224 1225
    # Used for mergeDeliveryList.
    class MergeDeliveryListError(Exception): pass

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    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:
1237
        raise self.MergeDeliveryListError, "No delivery is passed"
1238
      elif len(delivery_list) == 1:
1239
        raise self.MergeDeliveryListError, "Only one delivery is passed"
1240 1241 1242 1243

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

1244
      # Another sanity check. It is necessary for them to be identical in some attributes.
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
      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:
1255 1256 1257 1258
            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.
1259
      main_discount_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()})
1260
      for delivery in delivery_list:
1261
        discount_list = delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()})
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
        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.
1275
      main_payment_condition_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()})
1276
      for delivery in delivery_list:
1277
        payment_condition_list = delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()})
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
        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())
1291 1292 1293

      # Make sure that all activities are flushed, to get simulation movements from delivery cells.
      for delivery in delivery_list:
1294
        for order in delivery.getCausalityValueList(portal_type = self.getPortalOrderTypeList()):
1295 1296
          for applied_rule in order.getCausalityRelatedValueList(portal_type = 'Applied Rule'):
            applied_rule.flushActivity(invoke = 1)
1297
        for causality_related_delivery in delivery.getCausalityValueList(portal_type = self.getPortalDeliveryTypeList()):
1298 1299
          for applied_rule in causality_related_delivery.getCausalityRelatedValueList(portal_type = 'Applied Rule'):
            applied_rule.flushActivity(invoke = 1)
1300

1301 1302 1303 1304 1305
      # 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[:]
1306
      for delivery in delivery_list:
1307 1308 1309
        simulated_movement_list.extend(delivery.getSimulatedMovementList())
        invoice_movement_list.extend(delivery.getInvoiceMovementList())

1310 1311 1312 1313
      #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())))

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
      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)
1326 1327 1328 1329 1330 1331 1332 1333 1334
        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)))

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
        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:
1349 1350
                  if movement.aq_parent.getPortalType() in self.getPortalSimulatedMovementTypeList() \
                    or movement.aq_parent.getPortalType() in self.getPortalInvoiceMovementTypeList():
1351 1352 1353 1354 1355
                    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
1356

1357 1358 1359
              if delivery_line is None:
                # Not found. So create a new delivery line.
                movement = base_variant_group.movement_list[0]
1360 1361
                if movement.aq_parent.getPortalType() in self.getPortalSimulatedMovementTypeList() \
                  or movement.aq_parent.getPortalType() in self.getPortalInvoiceMovementTypeList():
1362
                  delivery_line_type = movement.aq_parent.getPortalType()
1363
                else:
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
                  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)

1374
              object_to_update = None
1375 1376 1377 1378 1379 1380
              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()
1381
                    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)))
1382 1383 1384 1385 1386 1387 1388
                    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
1389

1390
                #LOG('mergeDeliveryList', 0, 'object_to_update = %s' % repr(object_to_update))
1391
                if object_to_update is not None:
1392
                  cell_price = object_to_update.getPrice() or 0.0
1393
                  cell_quantity = object_to_update.getQuantity() or 0.0
1394
                  cell_target_quantity = object_to_update.getNetConvertedTargetQuantity() or 0.0 # XXX What to do ?
1395
                  cell_total_price = cell_target_quantity * cell_price
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
                  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
1406 1407
                      cell_price = movement.getPrice()
                      cell_total_price += movement.getNetConvertedTargetQuantity() * cell_price
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1408
                    except TypeError:
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
                      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

1431
                  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)))
1432
                  object_to_update.setCategoryList(cell_category_list)
1433
                  if object_to_update.getPortalType() in self.getPortalSimulatedMovementTypeList():
1434 1435 1436 1437
                    object_to_update.edit(target_quantity = cell_target_quantity,
                                          quantity = cell_quantity,
                                          price = average_price,
                                          )
1438
                  elif object_to_update.getPortalType() in self.getPortalInvoiceMovementTypeList():
1439 1440 1441 1442 1443 1444 1445
                    # 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()
1446 1447 1448 1449 1450
                else:
                  raise self.MergeDeliveryListError, "No object to update"

      # Merge containers. Just copy them from other deliveries into the main.
      for delivery in delivery_list:
1451
        container_id_list = delivery.contentIds(filter = {'portal_type': self.getPortalContainerTypeList()})
1452 1453 1454
        if len(container_id_list) > 0:
          copy_data = delivery.manage_copyObjects(ids = container_id_list)
          new_id_list = main_delivery.manage_pasteObjects(copy_data)
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475

      # 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


1476
InitializeClass(SimulationTool)