SimulationTool.py 99.4 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
#
# 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.
#
##############################################################################

30
from Products.CMFCore.utils import getToolByName
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32 33 34

from AccessControl import ClassSecurityInfo
from Globals import InitializeClass, DTMLFile
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
from Products.ERP5 import DeliverySolver
from Products.ERP5 import TargetSolver
47
from Products.PythonScripts.Utility import allow_class
Jean-Paul Smets's avatar
Jean-Paul Smets committed
48

49
from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery, QueryMixin
50

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


    Examples of applications:

    -

    -
    ERP5 main purpose:

    -

    -

    """
    id = 'portal_simulation'
    meta_type = 'ERP5 Simulation Tool'
71
    portal_type = 'Simulation Tool'
Jean-Paul Smets's avatar
Jean-Paul Smets committed
72 73 74 75 76 77 78 79 80 81 82 83
    allowed_types = ( 'ERP5 Applied Rule', )

    # Declarative Security
    security = ClassSecurityInfo()

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

    def filtered_meta_types(self, user=None):
84 85 86 87 88 89 90
      # 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
Jean-Paul Smets's avatar
Jean-Paul Smets committed
91

92 93 94
    def tpValues(self) :
      """ show the content in the left pane of the ZMI """
      return self.objectValues()
95

96 97 98
    security.declarePrivate('manage_afterAdd')
    def manage_afterAdd(self, item, container) :
      """Init permissions right after creation.
99

100 101 102 103 104 105 106 107 108 109 110 111
      Permissions in simulation tool are simple:
       o Each member can access and create some content.
       o Only manager can view, because simulation can be seen as
         sensitive information.
      """
      item.manage_permission(Permissions.AddPortalContent,
            ['Member', 'Author', 'Manager'])
      item.manage_permission(Permissions.AccessContentsInformation,
            ['Member', 'Auditor', 'Manager'])
      item.manage_permission(Permissions.View,
            ['Manager',])
      BaseTool.inheritedAttribute('manage_afterAdd')(self, item, container)
112

113
    def solveDelivery(self, delivery, dsolver_name, tsolver_name,
114 115 116 117 118 119
                                     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)
120 121

    def solveMovement(self, movement, dsolver_name, tsolver_name,
122 123 124 125
                                       additional_parameters=None,**kw):
      """
        Solve a movement by calling DeliverySolver and TargetSolver
      """
126
      return self.solveMovementOrDelivery(movement, dsolver_name, tsolver_name,
127
          movement=1,additional_parameters=additional_parameters,**kw)
128 129

    def solveMovementOrDelivery(self, obj, dsolver_name, tsolver_name,
130 131
                                          movement=0,delivery=0,
                                          additional_parameters=None,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
132
      """
133
        Solve a delivery by calling DeliverySolver and TargetSolver
Jean-Paul Smets's avatar
Jean-Paul Smets committed
134
      """
135 136 137 138 139 140 141 142 143
      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)
144
          solver = solver_class(additional_parameters=additional_parameters,**kw)
145

146
          if movement:
147
            return solver.solveMovement(obj)
148
          if delivery:
149
            return solver.solveDelivery(obj)
150

Jean-Paul Smets's avatar
Jean-Paul Smets committed
151 152
    #######################################################
    # Stock Management
153

154
    def _generatePropertyUidList(self, prop, as_text=0):
155 156 157 158 159 160 161
      """
      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
      """
162
      if prop is None :
163 164
        return []
      category_tool = getToolByName(self, 'portal_categories')
165
      property_uid_list = []
166
      if isinstance(prop, str):
167
        if not as_text:
168
          prop_value = category_tool.getCategoryValue(prop)
169
          if prop_value is None:
170
            raise ValueError, 'Category %s does not exists' % prop
171
          property_uid_list.append(prop_value.getUid())
172
        else:
173 174 175
          property_uid_list.append(prop)
      elif isinstance(prop, (list, tuple)):
        for property_item in prop :
176
          if not as_text:
177 178 179 180
            prop_value = category_tool.getCategoryValue(property_item)
            if prop_value is None:
              raise ValueError, 'Category %s does not exists' % property_item
            property_uid_list.append(prop_value.getUid())
181 182
          else:
            property_uid_list.append(property_item)
183
      elif isinstance(prop, dict):
184
        tmp_uid_list = []
185 186 187
        if isinstance(prop['query'], str):
          prop['query'] = [prop['query']]
        for property_item in prop['query'] :
188
          if not as_text:
189 190 191 192
            prop_value = category_tool.getCategoryValue(property_item)
            if prop_value is None:
              raise ValueError, 'Category %s does not exists' % property_item
            tmp_uid_list.append(prop_value.getUid())
193 194
          else:
            tmp_uid_list.append(property_item)
195
        if tmp_uid_list:
196
          property_uid_list = {}
197
          property_uid_list['operator'] = prop['operator']
198 199 200
          property_uid_list['query'] = tmp_uid_list
      return property_uid_list

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    def _getSimulationStateQuery(self, **kw):
      simulation_state_dict = self._getSimulationStateDict(**kw)
      return self._buildSimulationStateQuery(simulation_state_dict)
      
    def _buildSimulationStateQuery(self, simulation_state_dict):
      input_simulation_state = simulation_state_dict.get(
                                 'input_simulation_state')
      output_simulation_state = simulation_state_dict.get(
                                 'output_simulation_state')
      simulation_state = simulation_state_dict.get('simulation_state')
      if simulation_state is not None:
        simulation_query = Query(operator='IN',
                                 **{'stock.simulation_state':
                                    simulation_state})
      elif input_simulation_state is not None:
        input_quantity_query = Query(**{'stock.quantity': '>0'})
        input_simulation_query = Query(operator='IN',
                                       **{'stock.simulation_state':
                                          input_simulation_state})
        simulation_query = ComplexQuery(input_quantity_query,
                                        input_simulation_query,
                                        operator='AND')
        if output_simulation_state is not None:
          output_quantity_query = Query(**{'stock.quantity': '<0'})
          output_simulation_query = Query(operator='IN',
                                          **{'stock.simulation_state':
                                             output_simulation_state})
          output_query = ComplexQuery(output_quantity_query,
                                      output_simulation_query,
                                      operator='AND')
          simulation_query = ComplexQuery(simulation_query, output_query,
                                          operator='OR')
      else:
        simulation_query = '1'
      return simulation_query

    def _getSimulationStateDict(self, simulation_state=None, omit_transit=0,
238 239 240 241 242 243 244 245 246 247 248 249
                                input_simulation_state=None,
                                output_simulation_state=None,
                                transit_simulation_state=None,
                                strict_simulation_state=None):
      """
      This method is used in order to give what should be
      the input_simulation_state or output_simulation_state
      depending on many parameters
      """
      string_or_list = (str, list, tuple)
      # Simulation States
      # If strict_simulation_state is set, we directly put it into the dictionary
250
      simulation_dict = {}
251 252 253
      if strict_simulation_state:
        if isinstance(simulation_state, string_or_list)\
                and simulation_state:
254 255
           simulation_query = Query(
                   **{'stock.simulation_state': simulation_state})
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 297 298 299 300 301 302 303 304 305 306 307 308 309 310
      else:
        # first, we evaluate simulation_state
        sql_kw = {}
        if simulation_state and isinstance(simulation_state, string_or_list):
          if isinstance(simulation_state, str):
            sql_kw['input_simulation_state'] = [simulation_state]
            sql_kw['output_simulation_state'] = [simulation_state]
          else:
            sql_kw['input_simulation_state'] = simulation_state
            sql_kw['output_simulation_state'] = simulation_state
        # then, if omit_transit == 1, we evaluate (simulation_state -
        # transit_simulation_state) for input_simulation_state
        if omit_transit:
          if isinstance(simulation_state, string_or_list)\
                and simulation_state:
            if isinstance(transit_simulation_state, string_or_list)\
                  and transit_simulation_state:
              # when we know both are usable, we try to calculate
              # (simulation_state - transit_simulation_state)
              if isinstance(simulation_state, str):
                simulation_state = [simulation_state]
              if isinstance(transit_simulation_state, str) :
                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)
              sql_kw['input_simulation_state'] = delivered_simulation_state_list

        # alternatively, the user can directly define input_simulation_state
        # and output_simulation_state
        if input_simulation_state and isinstance(input_simulation_state,
                                                  string_or_list):
          if isinstance(input_simulation_state, str):
            input_simulation_state = [input_simulation_state]
          sql_kw['input_simulation_state'] = input_simulation_state
        if output_simulation_state and isinstance(output_simulation_state,
                                                  string_or_list):
          if isinstance(output_simulation_state, str):
            output_simulation_state = [output_simulation_state]
          sql_kw['output_simulation_state'] = output_simulation_state
        # XXX In this case, we must not set sql_kw[input_simumlation_state] before
        input_simulation_state = None
        output_simulation_state = None
        if sql_kw.has_key('input_simulation_state'):
          input_simulation_state = sql_kw.get('input_simulation_state')
        if sql_kw.has_key('output_simulation_state'):
          output_simulation_state = sql_kw.get('output_simulation_state')
        if input_simulation_state is not None \
           or output_simulation_state is not None:
          sql_kw.pop('input_simulation_state',None)
          sql_kw.pop('output_simulation_state',None)
        if input_simulation_state is not None:
          if output_simulation_state is not None:
            if input_simulation_state == output_simulation_state:
311
              simulation_dict['simulation_state'] = input_simulation_state
312
            else:
313 314
              simulation_dict['input_simulation_state'] = input_simulation_state
              simulation_dict['output_simulation_state'] = output_simulation_state
315
          else:
316
            simulation_dict['input_simulation_state'] = input_simulation_state
317
        elif output_simulation_state is not None:
318 319
          simulation_dict['simulation_state'] = output_simulation_state
      return simulation_dict
320 321 322 323 324 325 326 327 328 329

    def _getOmitQuery(self, query_table=None, omit_input=0, omit_output=0, **kw):
      """
      Build a specific query in order to take:
      - negatives quantity values if omit_input
      - postives quantity values if omit_output
      """
      omit_query = None
      if omit_input or omit_output:
        # Make sure to check some conditions
330 331 332 333 334 335 336
        condition_expression = \
          "%(query_table)s.node_uid <> %(query_table)s.mirror_node_uid \
         OR %(query_table)s.section_uid <> %(query_table)s.mirror_section_uid \
         OR %(query_table)s.mirror_node_uid IS NULL \
         OR %(query_table)s.mirror_section_uid IS NULL \
         OR %(query_table)s.payment_uid IS NOT NULL \
           " % {'query_table': query_table}
337
        if omit_input:
338
          quantity_query = Query(**{'%s.quantity' % query_table: '<0'})
339 340 341
          omit_query = ComplexQuery(quantity_query, condition_expression,
                                    operator='AND')
        if omit_output:
342
          quantity_query = Query(**{'%s.quantity' % query_table: '>0'})
343 344 345 346 347 348 349 350 351 352
          if omit_query is None:
            omit_query = ComplexQuery(quantity_query, condition_expression,
                                      operator='AND')
          else:
            output_query = ComplexQuery(quantity_query, condition_expression,
                                        operator='AND')
            omit_query = ComplexQuery(omit_query, output_query, operator='AND')

      return omit_query

353 354 355 356 357
    def _generateSQLKeywordDict(self, table='stock', **kw):
        sql_kw, new_kw = self._generateKeywordDict(table=table, **kw)
        return self._generateSQLKeywordDictFromKeywordDict(table=table, sql_kw=sql_kw, new_kw=new_kw)

    def _generateSQLKeywordDictFromKeywordDict(self, table, sql_kw, new_kw):
358
        # Some columns cannot be found automatically, prepend table name to avoid ambiguities.
359 360 361
        group_by = new_kw.pop('group_by', [])
        if len(group_by):
          new_kw['group_by_expression'] = ', '.join(['%s.%s' % (table, x) for x in group_by])
362 363 364
        column_value_dict = new_kw.pop('column_value_dict', {})
        for key, value in column_value_dict.iteritems():
          new_kw['%s.%s' % (table, key)] = value
365 366 367 368
        sql_kw.update(self.portal_catalog.buildSQLQuery(**new_kw))
        return sql_kw

    def _generateKeywordDict(self, table='stock',
369
        # dates
370
        from_date=None, to_date=None, at_date=None,
371
        omit_mirror_date=1,
372
        # instances
Alexandre Boeglin's avatar
Alexandre Boeglin committed
373
        resource=None, node=None, payment=None,
374 375 376 377
        section=None, mirror_section=None, item=None,
        # used for tracking
        input=0, output=0,
        # categories
Alexandre Boeglin's avatar
Alexandre Boeglin committed
378
        resource_category=None, node_category=None, payment_category=None,
379
        section_category=None, mirror_section_category=None,
380 381 382 383 384 385 386
        # categories with strict membership
        resource_category_strict_membership=None,
        node_category_strict_membership=None,
        payment_category_strict_membership=None,
        section_category_strict_membership=None,
        mirror_section_category_strict_membership=None,
        # simulation_state
387
        strict_simulation_state=0,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
388
        simulation_state=None, transit_simulation_state = None, omit_transit=0,
389
        input_simulation_state=None, output_simulation_state=None,
390
        reserved_kw=None,
391
        # variations
392
        variation_text=None, sub_variation_text=None,
393 394 395
        variation_category=None,
        # uids
        resource_uid=None, node_uid=None, section_uid=None,
396 397 398 399 400 401 402 403 404 405 406 407 408
        # omit input and output
        omit_input=0,
        omit_output=0,
        # group by
        group_by_node=0,
        group_by_mirror_node=0,
        group_by_section=0,
        group_by_mirror_section=0,
        group_by_payment=0,
        group_by_sub_variation=0,
        group_by_variation=0,
        group_by_movement=0,
        group_by_resource=1,
409 410
        # keywords for related keys
        **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
411
      """
412 413 414 415
      Generates keywords and calls buildSQLQuery

      - omit_mirror_date: normally, date's parameters are only based on date
        column. If 0, it also used the mirror_date column.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
416 417 418 419 420
      """
      new_kw = {}
      new_kw.update(kw)
      sql_kw = {}

421 422 423 424
      # input and output are used by getTrackingList
      sql_kw['input'] = input
      sql_kw['output'] = output

425 426 427 428 429 430 431 432 433 434 435 436 437 438
      query_list = []

      if omit_mirror_date:
        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 at_date :
            date_dict['query'].append(at_date)
            date_dict['range'] = 'minngt'
        elif to_date :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
439
          date_dict['query'].append(to_date)
440
          date_dict['range'] = 'max'
441 442
        elif at_date :
          date_dict['query'].append(at_date)
443 444 445 446 447 448 449 450 451 452 453
          date_dict['range'] = 'ngt'
        if len(date_dict) :
          new_kw[table + '.date'] = date_dict
      else:
        date_query_list = []
        query_list.append(ComplexQuery(
          Query(range='ngt', 
                **{'%s.date' % table: [to_date]}),
          Query(range='nlt', 
                **{'%s.mirror_date' % table: [from_date]}),
          operator='AND'))
454

455
      column_value_dict = {}
456
      if resource_uid is not None :
457
        column_value_dict['resource_uid'] = resource_uid
458
      if section_uid is not None :
459
        column_value_dict['section_uid'] = section_uid
460
        sql_kw['section_filtered'] = 1
461
      if node_uid is not None :
462
        column_value_dict['node_uid'] = node_uid
463

464
      resource_uid_list = self._generatePropertyUidList(resource)
465
      if resource_uid_list:
466
        column_value_dict['resource_uid'] = resource_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
467

468
      item_uid_list = self._generatePropertyUidList(item)
469
      if item_uid_list:
470
        column_value_dict['aggregate_uid'] = item_uid_list
471

472
      node_uid_list = self._generatePropertyUidList(node)
473
      if node_uid_list:
474
        column_value_dict['node_uid'] = node_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
475

476
      payment_uid_list = self._generatePropertyUidList(payment)
477
      if payment_uid_list:
478
        column_value_dict['payment_uid'] = payment_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
479

480
      section_uid_list = self._generatePropertyUidList(section)
481
      if section_uid_list:
482
        column_value_dict['section_uid'] = section_uid_list
483
        sql_kw['section_filtered'] = 1
Alexandre Boeglin's avatar
Alexandre Boeglin committed
484

485
      mirror_section_uid_list = self._generatePropertyUidList(mirror_section)
486
      if mirror_section_uid_list:
487
        column_value_dict['mirror_section_uid'] = mirror_section_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
488

489 490
      variation_text_list = self._generatePropertyUidList(variation_text,
                                                          as_text=1)
491
      if variation_text_list:
492
        column_value_dict['variation_text'] = variation_text_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
493

494 495
      sub_variation_text_list = self._generatePropertyUidList(
                                              sub_variation_text, as_text=1)
496
      if sub_variation_text_list:
497 498 499
        column_value_dict['sub_variation_text'] = sub_variation_text_list

      new_kw['column_value_dict'] = column_value_dict
500

501 502 503
      # category membership
      resource_category_uid_list = self._generatePropertyUidList(
                                              resource_category)
504
      if resource_category_uid_list:
505
        new_kw[table + '_resource_category_uid'] = resource_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
506

507
      node_category_uid_list = self._generatePropertyUidList(node_category)
508
      if node_category_uid_list:
509
        new_kw[table + '_node_category_uid'] = node_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
510

511
      payment_category_uid_list = self._generatePropertyUidList(payment_category)
512
      if payment_category_uid_list:
513
        new_kw[table + '_payment_category_uid'] = payment_category_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
514

515
      section_category_uid_list = self._generatePropertyUidList(section_category)
516
      if section_category_uid_list:
517
        new_kw[table + '_section_category_uid'] = section_category_uid_list
518
        sql_kw['section_filtered'] = 1
Alexandre Boeglin's avatar
Alexandre Boeglin committed
519

520 521
      mirror_section_category_uid_list = self._generatePropertyUidList(
                                              mirror_section_category)
522
      if mirror_section_category_uid_list:
523 524 525 526 527 528
        new_kw[table + '_mirror_section_category_uid'] =\
                                              mirror_section_category_uid_list

      # category strict membership
      resource_category_strict_membership_uid_list =\
            self._generatePropertyUidList(resource_category_strict_membership)
529
      if resource_category_strict_membership_uid_list:
530 531 532 533 534
        new_kw[table + '_resource_category_strict_membership_uid'] =\
            resource_category_strict_membership_uid_list

      node_category_strict_membership_uid_list =\
            self._generatePropertyUidList(node_category_strict_membership)
535
      if node_category_strict_membership_uid_list:
536 537 538 539 540
        new_kw[table + '_node_category_strict_membership_uid'] =\
            node_category_strict_membership_uid_list

      payment_category_strict_membership_uid_list =\
            self._generatePropertyUidList(payment_category_strict_membership)
541
      if payment_category_strict_membership_uid_list:
542 543 544 545 546
        new_kw[table + '_payment_category_strict_membership_uid'] =\
            payment_category_strict_membership_uid_list

      section_category_strict_membership_uid_list =\
            self._generatePropertyUidList(section_category_strict_membership)
547
      if section_category_strict_membership_uid_list:
548 549
        new_kw[table + '_section_category_strict_membership_uid'] =\
            section_category_strict_membership_uid_list
550
        sql_kw['section_filtered'] = 1
551 552 553 554

      mirror_section_category_strict_membership_uid_list =\
            self._generatePropertyUidList(
                                  mirror_section_category_strict_membership)
555
      if mirror_section_category_strict_membership_uid_list:
556 557
        new_kw[table + '_mirror_section_category_strict_membership_uid'] =\
            mirror_section_category_strict_membership_uid_list
Alexandre Boeglin's avatar
Alexandre Boeglin committed
558

559 560 561
      #variation_category_uid_list = self._generatePropertyUidList(variation_category)
      #if len(variation_category_uid_list) :
      #  new_kw['variationCategory'] = variation_category_uid_list
562
      
563 564
      simulation_query =  self._getSimulationStateQuery(
                                simulation_state=simulation_state, 
565 566 567 568 569 570 571 572 573 574 575 576 577 578
                                omit_transit=omit_transit,
                                input_simulation_state=input_simulation_state,
                                output_simulation_state=output_simulation_state,
                                transit_simulation_state=transit_simulation_state,
                                strict_simulation_state=strict_simulation_state)
      if omit_input or omit_output:
        omit_query = self._getOmitQuery(omit_input=omit_input,
                                        omit_output=omit_output,
                                        query_table=table)
        if simulation_query is not None:
          simulation_query = ComplexQuery(simulation_query, omit_query, operator='AND')
        else:
          simulation_query = omit_query
      if reserved_kw is not None:
579
        if not isinstance(reserved_kw, dict):
580 581 582
          # Not a dict when taken from URL, so, cast is needed 
          # to make pop method available
          reserved_kw = dict(reserved_kw)
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        reserved_omit_input = reserved_kw.pop('omit_input',0)
        reserved_omit_output = reserved_kw.pop('omit_output',0)
        reserved_omit_query = self._getOmitQuery(query_table=table,
                                                 omit_input=reserved_omit_input,
                                                 omit_output=reserved_omit_output)
        reserved_query = self._getSimulationStateQuery(**reserved_kw)
        if reserved_omit_query is not None:
          reserved_query = ComplexQuery(reserved_omit_query,reserved_query,
                                        operator='AND')
        if simulation_query is not None:
          simulation_query = ComplexQuery(simulation_query, reserved_query,
                                          operator='OR')
        else:
          simulation_query = reserved_query
      if simulation_query is not None:
598
        query_list.append(simulation_query)
599

600 601
      if query_list:
        new_kw['query'] = ComplexQuery(*query_list)
602

Alexandre Boeglin's avatar
Alexandre Boeglin committed
603

604 605 606 607 608 609 610
      # 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 = {}
611
      if variation_category is not None and variation_category:
612 613
        where_expression = self.getPortalObject().portal_categories\
          .buildSQLSelector(
614 615 616 617 618 619 620 621 622 623
            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)
624 625
          new_kw['where_expression'] = '( %s )' % ' OR '.join(
                      ['catalog.uid=%s' % uid for uid in uid_list])
Alexandre Boeglin's avatar
Alexandre Boeglin committed
626

Sebastien Robin's avatar
Sebastien Robin committed
627 628
      # build the group by expression
      group_by_expression_list = []
629
      if group_by_node:
630
        group_by_expression_list.append('node_uid')
631
      if group_by_mirror_node:
632
        group_by_expression_list.append('mirror_node_uid')
633
      if group_by_section:
634
        group_by_expression_list.append('section_uid')
635
      if group_by_mirror_section:
636
        group_by_expression_list.append('mirror_section_uid')
637
      if group_by_payment:
638
        group_by_expression_list.append('payment_uid')
639
      if group_by_sub_variation:
640
        group_by_expression_list.append('sub_variation_text')
641
      if group_by_variation:
642
        group_by_expression_list.append('variation_text')
643
      if group_by_movement:
644
        group_by_expression_list.append('uid')
645 646
      if group_by_expression_list:
        # by default, we group by resource
647
        if group_by_resource:
648 649 650
          group_by_expression_list.append('resource_uid')
        new_kw['group_by'] = group_by_expression_list
      return sql_kw, new_kw 
651

Jean-Paul Smets's avatar
Jean-Paul Smets committed
652
    #######################################################
653 654
    # Inventory management
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
655
                              'getInventory')
656
    def getInventory(self, src__=0, simulation_period='', **kw):
657
      """
658 659
      Returns an inventory of a single or multiple resources on a single or
      multiple nodes as a single float value
660

661
      from_date (>=) - only take rows which date is >= from_date
662

663
      to_date   (<)  - only take rows which date is < to_date
664 665 666 667 668

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

      resource (only in generic API in simulation)

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

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

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

678 679
      mirror_section -  only take rows in stock table which mirror_section_uid is
                        mirror_section
680

681 682
      resource_category  -  only take rows in stock table which
                        resource_uid is member of resource_category
683

684 685
      node_category   - only take rows in stock table which node_uid is
                        member of section_category
686

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

690
      section_category -  only take rows in stock table which section_uid is
691 692 693 694 695 696 697 698 699 700 701
                          member of section_category

      mirror_section_category - only take rows in stock table which 
                                mirror_section_uid is member of
				mirror_section_category

      node_filter     - only take rows in stock table which node_uid
                        matches node_filter

      payment_filter  - only take rows in stock table which payment_uid
                        matches payment_filter
702

703 704 705
      section_filter  - only take rows in stock table which section_uid
                        matches section_filter

706 707
      mirror_section_filter - only take rows in stock table which
                              mirror_section_uid matches mirror_section_filter
708

709 710 711 712 713 714
      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
715

716 717
      sub_variation_text - only take rows in stock table with specified
                        variation_text
718

719 720
      variation_category - variation or list of possible variations (it is not
                        a cross-search ; SQL query uses OR)
721 722 723

      simulation_state - only take rows with specified simulation_state

724
      transit_simulation_state - specifies which states are transit states
725

726
      omit_transit   -  do not evaluate transit_simulation_state
727

728 729
      input_simulation_state - only take rows with specified simulation_state
                        and quantity > 0
730

731 732
      output_simulation_state - only take rows with specified simulation_state
                        and quantity < 0
733

734 735 736
      ignore_variation -  do not take into account variation in inventory
                        calculation (useless on getInventory, but useful on
                        getInventoryList)
737

738 739
      standardise    -  provide a standard quantity rather than an SKU (XXX
                        not implemented yet)
740

741 742
      omit_simulation - doesn't take into account simulation movements

743
      omit_input     -  doesn't take into account movement with quantity < 0
744

745
      omit_output    -  doesn't take into account movement with quantity > 0
746 747 748

      selection_domain, selection_report - see ListBox

749 750
      group_by_variation - (useless on getInventory, but useful on
                        getInventoryList)
Sebastien Robin's avatar
Sebastien Robin committed
751

752 753
      group_by_node  -  (useless on getInventory, but useful on
                        getInventoryList)
Sebastien Robin's avatar
Sebastien Robin committed
754

755 756
      group_by_mirror_node - (useless on getInventory, but useful on
                        getInventoryList)
Sebastien Robin's avatar
Sebastien Robin committed
757

758 759
      group_by_sub_variation - (useless on getInventory, but useful on
                        getInventoryList)
760

761 762 763
      group_by_movement - (useless on getInventory, but useful on
                        getInventoryList)

764 765
      precision - the precision used to round quantities and prices.

766 767
      **kw           -  if we want extended selection with more keywords (but
                        bad performance) check what we can do with
768
                        buildSQLQuery
769

770 771
      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.)
772
      """
773 774 775 776 777 778 779 780
      # JPS: this is a hint for implementation of xxx_filter arguments
      # node_uid_count = portal_catalog.countResults(**node_filter)
      # if node_uid_count not too big:
      #   node_uid_list = cache(portal_catalog(**node_filter))
      #   pass this list to ZSQL method
      # else:
      #   build a table in MySQL
      #   and join that table with the stock table
781 782
      method = getattr(self,'get%sInventoryList' % simulation_period)
      result = method(inventory_list=0, ignore_group_by=1, src__=src__, **kw)
783
      if src__:
Alexandre Boeglin's avatar
Alexandre Boeglin committed
784 785
        return result

786 787
      total_result = 0.0
      if len(result) > 0:
788 789
        if len(result) != 1:
          raise ValueError, 'Sorry we must have only one'
790
        inventory = result[0].total_quantity
791 792
        if inventory is not None:
          total_result = inventory
793 794

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

796
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
797
                              'getCurrentInventory')
798
    def getCurrentInventory(self, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
799 800 801
      """
      Returns current inventory
      """
802
      return self.getInventory(simulation_period='Current', **kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
803

804
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
805
                              'getAvailableInventory')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
806 807 808
    def getAvailableInventory(self, **kw):
      """
      Returns available inventory
809
      (current inventory - reserved_inventory)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
810
      """
811
      return self.getInventory(simulation_period='Available', **kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
812

813
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
814
                              'getFutureInventory')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
815 816 817 818
    def getFutureInventory(self, **kw):
      """
      Returns future inventory
      """
819
      return self.getInventory(simulation_period='Future', **kw)
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    
    def _getDefaultGroupByParameters(self, ignore_group_by=0, **kw):
      """
      Set defaults group_by parameters
      """
      if not (ignore_group_by \
         or kw.get('group_by_node', 0) or kw.get('group_by_mirror_node', 0) \
         or kw.get('group_by_section', 0) or kw.get('group_by_mirror_section', 0) \
         or kw.get('group_by_payment', 0) or kw.get('group_by_sub_variation', 0) \
         or kw.get('group_by_variation', 0) or kw.get('group_by_movement', 0) \
         or kw.get('group_by_resource', 0)):
        kw['group_by_movement'] = 1
        kw['group_by_node'] = 1
        kw['group_by_resource'] = 1
      return kw
Alexandre Boeglin's avatar
Alexandre Boeglin committed
835

836
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
837
                              'getInventoryList')
838
    def getInventoryList(self, src__=0, ignore_variation=0, standardise=0,
839
                         omit_simulation=0, 
840
                         selection_domain=None, selection_report=None,
841
                         statistic=0, inventory_list=1, 
842
                         precision=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
843
      """
844 845 846
        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
Romain Courteaud's avatar
Romain Courteaud committed
847
        a given group of resource, node, section.
848 849
        NOTE: we may want to define a parameter so that we can select
        the kind of inventory statistics we want to display (ex. sum,
Romain Courteaud's avatar
Romain Courteaud committed
850
        average, cost, etc.)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
851
      """
852
      kw = self._getDefaultGroupByParameters(**kw)
853
      # If no group at all, give a default sort group by
854
      sql_kw = self._generateSQLKeywordDict(**kw)
Romain Courteaud's avatar
Romain Courteaud committed
855
      return self.Resource_zGetInventoryList(
856
                    src__=src__, ignore_variation=ignore_variation,
857
                    standardise=standardise, omit_simulation=omit_simulation,
858
                    selection_domain=selection_domain,
859
                    selection_report=selection_report, precision=precision,
860 861
                    inventory_list=inventory_list, 
                    statistic=statistic, **sql_kw)
Romain Courteaud's avatar
Romain Courteaud committed
862

863
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
864
                              'getCurrentInventoryList')
865 866
    def getCurrentInventoryList(self, omit_transit=1, 
                                transit_simulation_state=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
867
      """
Romain Courteaud's avatar
Romain Courteaud committed
868
        Returns list of current inventory grouped by section or site
Alexandre Boeglin's avatar
Alexandre Boeglin committed
869
      """
870 871 872 873 874 875 876 877 878
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList() + \
                               self.getPortalTransitInventoryStateList()
      if transit_simulation_state is None:
        transit_simulation_state = self.getPortalTransitInventoryStateList()

      return self.getInventoryList(
                            omit_transit=omit_transit,
                            transit_simulation_state=transit_simulation_state,
                            **kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
879

880
    security.declareProtected(Permissions.AccessContentsInformation,
881
                              'getAvailableInventoryList')
882
    def getAvailableInventoryList(self, omit_transit=1, transit_simulation_state=None, **kw):
883 884 885
      """
        Returns list of current inventory grouped by section or site
      """
886 887 888 889 890 891 892 893 894
      if transit_simulation_state is None:
        transit_simulation_state = self.getPortalTransitInventoryStateList()
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList() + \
                               self.getPortalTransitInventoryStateList()
      reserved_kw = {'simulation_state': self.getPortalReservedInventoryStateList(),
                     'transit_simulation_state': transit_simulation_state,
                     'omit_input': 1}
      return self.getInventoryList(reserved_kw=reserved_kw, omit_transit=omit_transit,
                     transit_simulation_state=transit_simulation_state, **kw)
895 896

    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
897
                              'getFutureInventoryList')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
898 899
    def getFutureInventoryList(self, **kw):
      """
Romain Courteaud's avatar
Romain Courteaud committed
900
        Returns list of future inventory grouped by section or site
Alexandre Boeglin's avatar
Alexandre Boeglin committed
901
      """
Romain Courteaud's avatar
Romain Courteaud committed
902
      kw['simulation_state'] = tuple(
Romain Courteaud's avatar
Romain Courteaud committed
903
                 list(self.getPortalFutureInventoryStateList()) + \
904
                 list(self.getPortalTransitInventoryStateList()) + \
Romain Courteaud's avatar
Romain Courteaud committed
905
                 list(self.getPortalReservedInventoryStateList()) + \
Romain Courteaud's avatar
Romain Courteaud committed
906
                 list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
907 908
      return self.getInventoryList(**kw)

909
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
910
                              'getInventoryStat')
911
    def getInventoryStat(self, simulation_period='', **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
912
      """
913
      getInventoryStat is the pending to getInventoryList in order to
Romain Courteaud's avatar
Romain Courteaud committed
914
      provide statistics on getInventoryList lines in ListBox such as:
915
      total of inventories, number of variations, number of different
Romain Courteaud's avatar
Romain Courteaud committed
916
      nodes, etc.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
917
      """
Romain Courteaud's avatar
Romain Courteaud committed
918
      kw['group_by_variation'] = 0
919
      method = getattr(self,'get%sInventoryList' % simulation_period)
920
      return method(statistic=1, inventory_list=0, 
921
                                   ignore_group_by=1, **kw)
922 923

    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
924
                              'getCurrentInventoryStat')
925
    def getCurrentInventoryStat(self, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
926 927 928
      """
      Returns statistics of current inventory grouped by section or site
      """
929
      return self.getInventoryStat(simulation_period='Current', **kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
930

931
    security.declareProtected(Permissions.AccessContentsInformation,
932 933 934 935 936
                              'getAvailableInventoryStat')
    def getAvailableInventoryStat(self, **kw):
      """
      Returns statistics of current inventory grouped by section or site
      """
937
      return self.getInventoryStat(simulation_period='Available', **kw)
938 939

    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
940
                              'getFutureInventoryStat')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
941 942 943 944
    def getFutureInventoryStat(self, **kw):
      """
      Returns statistics of future inventory grouped by section or site
      """
945
      return self.getInventoryStat(simulation_period='Future', **kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
946

947
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
948
                              'getInventoryChart')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
949
    def getInventoryChart(self, src__=0, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
950
      """
951 952
      Returns a list of couples derived from getInventoryList in order
      to feed a chart renderer. Each couple consist of a label
953
      (node, section, payment, combination of node & section, etc.)
Romain Courteaud's avatar
Romain Courteaud committed
954
      and an inventory value.
955

956
      Mostly useful for charts in ERP5 forms.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
957
      """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
958
      result = self.getInventoryList(src__=src__, **kw)
959
      if src__ :
Alexandre Boeglin's avatar
Alexandre Boeglin committed
960
        return result
961

962
      return map(lambda r: (r.node_title, r.total_quantity), result)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
963

964
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
965
                              'getCurrentInventoryChart')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
966 967 968 969
    def getCurrentInventoryChart(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
970
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
971 972
      return self.getInventoryChart(**kw)

973
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
974
                              'getFutureInventoryChart')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
975 976 977 978
    def getFutureInventoryChart(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
Romain Courteaud's avatar
Romain Courteaud committed
979 980 981 982
      kw['simulation_state'] = tuple(
                      list(self.getPortalFutureInventoryStateList()) + \
                      list(self.getPortalReservedInventoryStateList()) + \
                      list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
983 984
      return self.getInventoryChart(**kw)

985
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
986
                              'getInventoryAssetPrice')
987 988
    def getInventoryAssetPrice(self, src__=0, 
                               simulation_period='', **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
989
      """
990
      Same thing as getInventory but returns an asset
991
      price rather than an inventory.
Alexandre Boeglin's avatar
Alexandre Boeglin committed
992
      """
993 994
      method = getattr(self,'get%sInventoryList' % simulation_period)
      result = method( src__=src__, inventory_list=0, ignore_group_by=1, **kw)
995 996
      if src__ :
        return result
997

998 999 1000
      total_result = 0.0
      if len(result) > 0:
        for result_line in result:
1001
          if result_line.total_price is not None:
1002
            total_result += result_line.total_price
1003

1004
      return total_result
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1005

1006
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1007
                              'getCurrentInventoryAssetPrice')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1008 1009 1010 1011
    def getCurrentInventoryAssetPrice(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
1012
      kw['simulation_state'] = self.getPortalCurrentInventoryStateList()
1013
      return self.getInventoryAssetPrice(simulation_period='Current',**kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1014

1015
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1016
                              'getAvailableInventoryAssetPrice')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1017 1018 1019 1020 1021
    def getAvailableInventoryAssetPrice(self, **kw):
      """
      Returns list of available inventory grouped by section or site
      (current inventory - deliverable)
      """
1022 1023 1024
      kw['simulation_state'] = tuple(
                    list(self.getPortalReservedInventoryStateList()) + \
                    list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1025 1026
      return self.getInventoryAssetPrice(**kw)

1027
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1028
                              'getFutureInventoryAssetPrice')
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1029 1030 1031 1032
    def getFutureInventoryAssetPrice(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
Romain Courteaud's avatar
Romain Courteaud committed
1033 1034 1035 1036
      kw['simulation_state'] = tuple(
               list(self.getPortalFutureInventoryStateList()) + \
               list(self.getPortalReservedInventoryStateList()) + \
               list(self.getPortalCurrentInventoryStateList()))
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1037 1038
      return self.getInventoryAssetPrice(**kw)

1039
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1040
                              'getInventoryHistoryList')
1041
    def getInventoryHistoryList(self, src__=0, ignore_variation=0,
1042
                                standardise=0, omit_simulation=0, omit_input=0,
1043
                                omit_output=0, selection_domain=None,
1044
                                selection_report=None, precision=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1045
      """
1046 1047 1048
      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).
1049 1050 1051 1052

      TODO:
        - make sure getInventoryHistoryList can return
	  cumulative values calculated by SQL (JPS)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1053
      """
1054
      sql_kw = self._generateSQLKeywordDict(**kw)
Romain Courteaud's avatar
Romain Courteaud committed
1055
      return self.Resource_getInventoryHistoryList(
1056
                      src__=src__, ignore_variation=ignore_variation,
1057
                      standardise=standardise, omit_simulation=omit_simulation,
Romain Courteaud's avatar
Romain Courteaud committed
1058
                      omit_input=omit_input, omit_output=omit_output,
1059
                      selection_domain=selection_domain,
1060 1061
                      selection_report=selection_report, precision=precision,
                      **sql_kw)
1062

1063
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1064
                              'getInventoryHistoryChart')
1065
    def getInventoryHistoryChart(self, src__=0, ignore_variation=0,
1066
                                 standardise=0, omit_simulation=0,
Romain Courteaud's avatar
Romain Courteaud committed
1067
                                 omit_input=0, omit_output=0,
1068
                                 selection_domain=None,
1069
                                 selection_report=None, precision=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1070
      """
1071 1072 1073 1074 1075
      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
1076
      """
1077 1078
      sql_kw = self._generateSQLKeywordDict(**kw)

Romain Courteaud's avatar
Romain Courteaud committed
1079
      return self.Resource_getInventoryHistoryChart(
1080
                    src__=src__, ignore_variation=ignore_variation,
1081
                    standardise=standardise, omit_simulation=omit_simulation,
Romain Courteaud's avatar
Romain Courteaud committed
1082
                    omit_input=omit_input, omit_output=omit_output,
1083
                    selection_domain=selection_domain,
1084 1085
                    selection_report=selection_report, precision=precision,
                    **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1086

1087
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1088
                              'getMovementHistoryList')
1089
    def getMovementHistoryList(self, src__=0, ignore_variation=0,
1090
                               standardise=0, omit_simulation=0,
1091 1092
                               omit_input=0, omit_output=0,
                               selection_domain=None, selection_report=None,
1093
                               initial_running_total_quantity=0,
1094
                               initial_running_total_price=0, precision=None,
Romain Courteaud's avatar
Romain Courteaud committed
1095
                               **kw):
1096
      """Returns a list of movements which modify the inventory
1097
      for a single or a group of resource, node, section, etc.
1098 1099 1100
      A running total quantity and a running total price are available on
      brains. The initial values can be passed, in case you want to have an
      "initial summary line".
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1101
      """
1102
      sql_kw = self._generateSQLKeywordDict(**kw)
Romain Courteaud's avatar
Romain Courteaud committed
1103
      return self.Resource_zGetMovementHistoryList(
1104 1105
                         src__=src__, ignore_variation=ignore_variation,
                         standardise=standardise,
1106
                         omit_simulation=omit_simulation,
Romain Courteaud's avatar
Romain Courteaud committed
1107
                         omit_input=omit_input, omit_output=omit_output,
1108
                         selection_domain=selection_domain,
1109 1110 1111 1112 1113
                         selection_report=selection_report,
                         initial_running_total_quantity=
                                  initial_running_total_quantity,
                         initial_running_total_price=
                                  initial_running_total_price,
1114
                         precision=precision, **sql_kw)
1115

1116
    security.declareProtected(Permissions.AccessContentsInformation,
Romain Courteaud's avatar
Romain Courteaud committed
1117
                              'getMovementHistoryStat')
1118
    def getMovementHistoryStat(self, src__=0, ignore_variation=0,
1119
                               standardise=0, omit_simulation=0, omit_input=0,
1120
                               omit_output=0, selection_domain=None,
1121
                               selection_report=None, precision=None, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1122
      """
Romain Courteaud's avatar
Romain Courteaud committed
1123 1124
      getMovementHistoryStat is the pending to getMovementHistoryList
      for ListBox stat
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1125
      """
1126
      sql_kw = self._generateSQLKeywordDict(**kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1127
      return self.Resource_zGetInventory(src__=src__,
1128
          ignore_variation=ignore_variation, standardise=standardise,
1129
          omit_simulation=omit_simulation, omit_input=omit_input,
1130
          omit_output=omit_output, selection_domain=selection_domain,
1131
          selection_report=selection_report, precision=precision, **sql_kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1132

1133 1134
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getNextNegativeInventoryDate')
1135
    def getNextNegativeInventoryDate(self, src__=0, **kw):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1136 1137 1138
      """
      Returns statistics of inventory grouped by section or site
      """
1139 1140 1141
      #sql_kw = self._generateSQLKeywordDict(order_by_expression='stock.date', **kw)
      #sql_kw['group_by_expression'] = 'stock.uid'
      #sql_kw['order_by_expression'] = 'stock.date'
1142

1143
      result = self.getInventoryList(src__=src__,
1144
          sort_on = (('stock.date', 'ascending'),), group_by_movement=1, **kw)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1145 1146
      if src__ :
        return result
1147

1148
      total_inventory = 0.
1149
      for inventory in result:
1150 1151 1152 1153 1154
        if inventory['inventory'] is not None:
          total_inventory += inventory['inventory']
          if total_inventory < 0:
            return inventory['date']

1155
      return None
Alexandre Boeglin's avatar
Alexandre Boeglin committed
1156

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1157
    #######################################################
1158
    # Traceability management
1159
    security.declareProtected(Permissions.AccessContentsInformation, 'getTrackingList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1160
    def getTrackingList(self, src__=0,
1161 1162
        selection_domain=None, selection_report=None,
        strict_simulation_state=1, **kw) :
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1163
      """
1164
      Returns a list of items in the form
1165

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1166 1167 1168 1169 1170 1171
        uid (of item)
        date
        node_uid
        section_uid
        resource_uid
        variation_text
1172
        delivery_uid
1173

1174 1175 1176 1177 1178 1179 1180 1181
      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
1182 1183

      This method is only suitable for singleton items (an item which can
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1184 1185
      only be at a single place at a given time). Such items include
      containers, serial numbers (ex. for engine), rolls with subrolls,
1186 1187

      This method is not suitable for batches (ex. a coloring batch).
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1188
      For such items, standard getInventoryList method is appropriate
1189

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1190
      Parameters are the same as for getInventory.
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
      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

      selection_domain, selection_report - see ListBox

      **kw  - if we want extended selection with more keywords (but bad performance)
1224
              check what we can do with buildSQLQuery
1225 1226 1227 1228

      Extra parameters for getTrackingList :

      item
1229

1230 1231 1232 1233 1234
      input - if set, answers to the question "which are those items which have been
              delivered for the first time after from_date". Cannot be used with output

      output - if set, answers to the question "which are those items which have been
               delivered for the last time before at_date or to_date". Cannot be used with input
1235

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1236
      """
1237
      new_kw = self._generateSQLKeywordDict(table='item',strict_simulation_state=strict_simulation_state,**kw)
1238 1239 1240 1241
      at_date = kw.get('at_date',None)
      if at_date is not None:
        query_mixin = QueryMixin()
        at_date = query_mixin._quoteSQLString(at_date)
1242
        at_date = at_date.strip("'")
1243 1244 1245
      # Do not remove at_date in new_kw, it is required in 
      # order to do a "select item left join item on date"
      new_kw['at_date'] = at_date
1246

1247 1248 1249 1250
      # Extra parameters for the SQL Method
      new_kw['join_on_item'] = new_kw.get('at_date') or \
                               new_kw.get('input') or \
                               new_kw.get('output')
1251
      new_kw['date_condition_in_join'] = not (new_kw.get('input') or new_kw.get('output'))
1252

1253 1254 1255 1256 1257
      # Pass simulation state to request
      if kw.has_key('item.simulation_state'):
          new_kw['simulation_state_list'] = kw['item.simulation_state']
      else:
          new_kw['simulation_state_list'] =  None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1258

1259
      return self.Resource_zGetTrackingList(src__=src__,
1260 1261 1262
                                            selection_domain=selection_domain,
                                            selection_report=selection_report,
                                            **new_kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1263 1264 1265 1266 1267 1268

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentTrackingList')
    def getCurrentTrackingList(self, **kw):
      """
      Returns list of current inventory grouped by section or site
      """
1269
      kw['item.simulation_state'] = self.getPortalCurrentInventoryStateList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1270 1271 1272 1273 1274 1275 1276
      return self.getTrackingList(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureTrackingList')
    def getFutureTrackingList(self, **kw):
      """
      Returns list of future inventory grouped by section or site
      """
1277
      kw['item.simulation_state'] = tuple(list(self.getPortalFutureInventoryStateList())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1278 1279 1280
          + list(self.getPortalReservedInventoryStateList()) + list(self.getPortalCurrentInventoryStateList()))
      return self.getTrackingList(**kw)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    #######################################################
    # 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()
1308 1309
      start_date = movement.getStartDate()
      stop_date = movement.getStopDate()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 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 1359 1360 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
      # 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.
1447
            if not isinstance(resource_aggregation_base_category, (tuple, list)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
              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
1502 1503
    # Asset Price Calculation
    def updateAssetPrice(self, resource, variation_text, section_category, node_category,
1504 1505 1506
                         strict_membership=0, simulation_state=None):
      if simulation_state is None:
        simulation_state = self.getPortalCurrentInventoryStateList()
1507 1508 1509
      category_tool = getToolByName(self, 'portal_categories')
      section_value = category_tool.resolveCategory(section_category)
      node_value = category_tool.resolveCategory(node_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1510 1511 1512 1513
      # 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
1514
      brain_list = self.Resource_zGetMovementHistoryList(resource=[resource],
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1515 1516 1517 1518
                             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
1519 1520 1521 1522
                             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
1523 1524
        m = b.getObject()
        if m is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
          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(),
1543
                          m.getQuantity(), 'Production or Inventory', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1544 1545 1546 1547 1548 1549
                        ))
          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(),
1550
                          m.getQuantity(), 'Consumption or Inventory', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1551
                        ))
1552
          elif m.getSourceValue().isAcquiredMemberOf(node_category) and m.getDestinationValue().isAcquiredMemberOf(node_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1553 1554 1555 1556
            # 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(),
1557
                          m.getQuantity(), 'Internal', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1558
                        ))
1559
          elif m.getSourceValue().isAcquiredMemberOf(node_category) and quantity < 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1560 1561 1562 1563
            # 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
1564
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1565
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1566
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1567 1568 1569 1570
                          ))
            elif m.getDestinationSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1571
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1572
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1573
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1574
                          ))
1575
            elif m.getDestinationSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1576
              current_inventory += inventory_quantity # Update inventory
1577
              if m.getDestinationValue().isAcquiredMemberOf('site/Piquage'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1578 1579 1580 1581
                # 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(),
1582
                              m.getQuantity(), 'Production', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1583
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1584 1585 1586
              else:
                # Inbound from same section
                asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1587
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1588
                              m.getQuantity(), 'Inbound same section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1589
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1590
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1591 1592 1593
              current_inventory += inventory_quantity # Update inventory
              asset_price = m.getPrice()
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1594
                            m.getQuantity(), 'Inbound different section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1595
                          ))
1596
          elif m.getDestinationValue().isAcquiredMemberOf(node_category) and quantity > 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1597 1598 1599 1600 1601 1602
            # 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(),
1603
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1604 1605 1606 1607
                          ))
            elif m.getDestinationSectionValue() is None:
              # No meaning
              current_inventory += inventory_quantity # Update inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1608
              asset_price = current_asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1609
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1610
                            m.getQuantity(), 'Error', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1611
                          ))
1612
            elif m.getSourceSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1613
              current_inventory += inventory_quantity # Update inventory
1614
              if m.getSourceValue().isAcquiredMemberOf('site/Piquage'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1615 1616 1617 1618
                # 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(),
1619
                              m.getQuantity(), 'Production', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1620
                            ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1621
              else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1622 1623 1624
                # Inbound from same section
                asset_price = current_asset_price
                result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1625
                            m.getQuantity(), 'Inbound same section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1626
                          ))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1627
            else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1628 1629 1630
              current_inventory += inventory_quantity # Update inventory
              asset_price = m.getPrice()
              result.append((m.getRelativeUrl(),m.getStartDate(), m.getSource(), m.getSourceSection(), m.getDestination(), m.getDestinationSection(),
1631
                            m.getQuantity(), 'Inbound different section', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1632 1633 1634 1635 1636 1637
                          ))
          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(),
1638
                            m.getQuantity(), 'Outbound', 'Price: %s' % asset_price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
                          ))

          # 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
1653
          if m.getSourceSectionValue() is not None and m.getSourceSectionValue().isAcquiredMemberOf(section_category):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1654 1655
            # 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
1656 1657 1658 1659 1660 1661 1662
            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
1663 1664
            # 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
1665 1666 1667 1668 1669
            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)
1670 1671 1672
          # 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
1673
          m.reindexObject()
1674
          #m.activate(priority=7).immediateReindexObject() # Too slow
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1675 1676

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

1678 1679 1680
    # Used for mergeDeliveryList.
    class MergeDeliveryListError(Exception): pass

1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
    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:
1692
        raise self.MergeDeliveryListError, "No delivery is passed"
1693
      elif len(delivery_list) == 1:
1694
        raise self.MergeDeliveryListError, "Only one delivery is passed"
1695 1696 1697 1698

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

1699
      # Another sanity check. It is necessary for them to be identical in some attributes.
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
      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:
1710 1711 1712 1713
            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.
1714
      main_discount_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()})
1715
      for delivery in delivery_list:
1716
        discount_list = delivery.contentValues(filter = {'portal_type': self.getPortalDiscountTypeList()})
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
        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.
1730
      main_payment_condition_list = main_delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()})
1731
      for delivery in delivery_list:
1732
        payment_condition_list = delivery.contentValues(filter = {'portal_type': self.getPortalPaymentConditionTypeList()})
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
        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())
1746 1747 1748

      # Make sure that all activities are flushed, to get simulation movements from delivery cells.
      for delivery in delivery_list:
1749
        for order in delivery.getCausalityValueList(portal_type = self.getPortalOrderTypeList()):
1750 1751
          for applied_rule in order.getCausalityRelatedValueList(portal_type = 'Applied Rule'):
            applied_rule.flushActivity(invoke = 1)
1752
        for causality_related_delivery in delivery.getCausalityValueList(portal_type = self.getPortalDeliveryTypeList()):
1753 1754
          for applied_rule in causality_related_delivery.getCausalityRelatedValueList(portal_type = 'Applied Rule'):
            applied_rule.flushActivity(invoke = 1)
1755

1756 1757 1758 1759 1760
      # 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[:]
1761
      for delivery in delivery_list:
1762 1763 1764
        simulated_movement_list.extend(delivery.getSimulatedMovementList())
        invoice_movement_list.extend(delivery.getInvoiceMovementList())

1765 1766 1767 1768
      #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())))

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
      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)
1781 1782 1783 1784 1785 1786 1787 1788 1789
        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)))

1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
        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:
1804 1805
                  if movement.aq_parent.getPortalType() in self.getPortalSimulatedMovementTypeList() \
                    or movement.aq_parent.getPortalType() in self.getPortalInvoiceMovementTypeList():
1806 1807 1808 1809 1810
                    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
1811

1812 1813 1814
              if delivery_line is None:
                # Not found. So create a new delivery line.
                movement = base_variant_group.movement_list[0]
1815 1816
                if movement.aq_parent.getPortalType() in self.getPortalSimulatedMovementTypeList() \
                  or movement.aq_parent.getPortalType() in self.getPortalInvoiceMovementTypeList():
1817
                  delivery_line_type = movement.aq_parent.getPortalType()
1818
                else:
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
                  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)

1829
              object_to_update = None
1830 1831 1832 1833 1834 1835
              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()
1836
                    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)))
1837 1838 1839 1840 1841 1842 1843
                    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
1844

1845
                #LOG('mergeDeliveryList', 0, 'object_to_update = %s' % repr(object_to_update))
1846
                if object_to_update is not None:
1847
                  cell_price = object_to_update.getPrice() or 0.0
1848
                  cell_quantity = object_to_update.getQuantity() or 0.0
1849
                  cell_target_quantity = object_to_update.getNetConvertedTargetQuantity() or 0.0 # XXX What to do ?
1850
                  cell_total_price = cell_target_quantity * cell_price
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
                  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
1861 1862
                      cell_price = movement.getPrice()
                      cell_total_price += movement.getNetConvertedTargetQuantity() * cell_price
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1863
                    except TypeError:
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
                      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

1886
                  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)))
1887
                  object_to_update.setCategoryList(cell_category_list)
1888
                  if object_to_update.getPortalType() in self.getPortalSimulatedMovementTypeList():
1889 1890 1891 1892
                    object_to_update.edit(target_quantity = cell_target_quantity,
                                          quantity = cell_quantity,
                                          price = average_price,
                                          )
1893
                  elif object_to_update.getPortalType() in self.getPortalInvoiceMovementTypeList():
1894 1895 1896 1897 1898 1899 1900
                    # 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()
1901 1902 1903 1904 1905
                else:
                  raise self.MergeDeliveryListError, "No object to update"

      # Merge containers. Just copy them from other deliveries into the main.
      for delivery in delivery_list:
1906
        container_id_list = delivery.contentIds(filter = {'portal_type': self.getPortalContainerTypeList()})
1907 1908 1909
        if len(container_id_list) > 0:
          copy_data = delivery.manage_copyObjects(ids = container_id_list)
          new_id_list = main_delivery.manage_pasteObjects(copy_data)
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929

      # 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

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    #######################################################
    # Sequence
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getSequence')
    def getSequence(self, **kw):
      """
      getSequence is take the same parameters as Sequence constructor,
      and return a Sequence.
      """
      return Sequence(**kw)

    #######################################################
    # Time Management
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getAvailableTime')
    def getAvailableTime(self, from_date=None, to_date=None, 
1946 1947
                         portal_type=[], node=[], 
                         resource=[], src__=0, **kw):
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
      """
      Calculate available time for a node
      Returns an inventory of a single or multiple resources on a single
      node as a single float value

      from_date (>=) - only take rows which mirror_date is >= from_date

      to_date   (<)  - only take rows which date is < to_date

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

1960 1961 1962
      resource       - only take rows in stock table which resource_uid is
                       equivalent to resource

1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
      portal_type    - only take rows in stock table which portal_type
                       is in portal_type parameter
      """
      # XXX For now, consider that from_date and to_date are required
      if (from_date is None) or (to_date is None):
        raise NotImplementedError, \
              "getAvailableTime does not managed yet None values"
      # Calculate portal_type
      if portal_type == []:
        portal_type = self.getPortalCalendarPeriodTypeList()

1974 1975 1976 1977
      simulation_state = self.getPortalCurrentInventoryStateList() + \
                         self.getPortalTransitInventoryStateList() + \
                         self.getPortalReservedInventoryStateList()

1978
      sql_result = self.Person_zGetAvailableTime(
1979 1980 1981 1982
                          from_date=from_date,
                          to_date=to_date,
                          portal_type=portal_type,
                          node=node,
1983
                          resource=resource,
1984
                          simulation_state=simulation_state,
1985 1986
                          src__=src__, **kw)
      if not src__:
1987
        result = 0
1988 1989 1990 1991
        if len(sql_result) == 1:
          result = sql_result[0].total_quantity
      else:
        result = sql_result
1992 1993 1994 1995 1996 1997
      return result

    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getAvailableTimeSequence')
    def getAvailableTimeSequence(self, from_date, to_date,  
                                 portal_type=[], node=[],
1998
                                 resource=[], 
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
                                 src__=0,
                                 **kw):
      """
      Calculate available time for a node in multiple period of time.
      Each row is the available time for a specific period

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

      portal_type    - only take rows in stock table which portal_type
                       is in portal_type parameter

2011 2012 2013
      resource       - only take rows in stock table which resource_uid is
                       equivalent to resource

2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
      from_date (>=) - return period which start >= from_date

      to_date   (<)  - return period which start < to_date

      second, minute,
      hour, day,
      month, year   - duration of each time period (cumulative)
      """
      # Calculate portal_type
      if portal_type == []:
        portal_type = self.getPortalCalendarPeriodTypeList()

2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
      sequence = Sequence(from_date, to_date, **kw)
      for sequence_item in sequence:
        setattr(sequence_item, 'total_quantity',
                self.getAvailableTime(
                          from_date=sequence_item.from_date,
                          to_date=sequence_item.to_date,
                          portal_type=portal_type,
                          node=node,
                          resource=resource,
                          src__=src__))
      return sequence
2037 2038

from Products.ERP5Type.DateUtils import addToDate
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048

class SequenceItem:
  """
  SequenceItem define a time period.
  period.
  """
  def __init__(self, from_date, to_date):
    self.from_date = from_date
    self.to_date = to_date

2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
class Sequence:
  """
  Sequence is a iterable object, which calculate a range of time
  period.
  """
  def __init__(self, from_date, to_date, 
               second=None, minute=None, hour=None,
               day=None, month=None, year=None):
    """
    Calculate a list of time period.
    Time period is a 2-tuple of 2 DateTime, which represent the from date
    and to date of the period.

    The start date of a period is calculated with the rule
        start_date of the previous + period duration

    from_date (>=) - return period which start >= from_date

    to_date   (<)  - return period which start < to_date

    second, minute,
    hour, day,
    month, year   - duration of each time period (cumulative)

    """
    self.item_list = []
    # Calculate all time period
    current_from_date = from_date
    while current_from_date < to_date:
      current_to_date = addToDate(current_from_date, 
                                  second=second,
                                  minute=minute,
                                  hour=hour,
                                  day=day,
                                  month=month,
                                  year=year)
2085 2086
      self.item_list.append(SequenceItem(current_from_date, 
                                         current_to_date))
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
      current_from_date = current_to_date

  def __len__(self):
    return len(self.item_list)

  def __getitem__(self, key):
    return self.item_list[key]

  def __contains__(self, value):
    return (value in self.item_list)

  def __iter__(self):
    for x in self.item_list:
      yield x

InitializeClass(Sequence)
allow_class(Sequence)
2104 2105
InitializeClass(SequenceItem)
allow_class(SequenceItem)
2106

2107
InitializeClass(SimulationTool)