Delivery.py 52.2 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from Globals import InitializeClass, PersistentMapping
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.WorkflowCore import WorkflowMethod
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5Type.XMLMatrix import TempXMLMatrix
36
from Products.ERP5Type.Base import Base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38 39
from Products.ERP5.Document.DeliveryCell import DeliveryCell
from Acquisition import Explicit, Implicit
from Products.PythonScripts.Utility import allow_class
40
from DateTime import DateTime
41
#from Products.ERP5.ERP5Globals import movement_type_list, draft_order_state, planned_order_state
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42

43 44 45 46
from Products.ERP5.MovementGroup import OrderMovementGroup, PathMovementGroup
from Products.ERP5.MovementGroup import DateMovementGroup, ResourceMovementGroup
from Products.ERP5.MovementGroup import VariantMovementGroup, RootMovementGroup

Jean-Paul Smets's avatar
Jean-Paul Smets committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
from zLOG import LOG

class TempDeliveryCell(DeliveryCell):

  def getPrice(self):
    return self.price

  def _setPrice(self, value):
    self.price = value

  def getQuantity(self):
    return self.quantity

  def _setQuantity(self, value):
    self.quantity = value

  def reindexObject(self, *args, **kw):
    pass

  def activate(self):
    return self

class XMLMatrix(TempXMLMatrix):

71
  def newCellContent(self, id,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    """
          This method can be overriden
    """
    new_temp_object = TempDeliveryCell(id)
    self._setObject(id, new_temp_object)
    return self.get(id)

class Group(Implicit):
  """
    Hold movements which have the same resource and the same variation.
  """
  # Declarative security
  security = ClassSecurityInfo()
  #security.declareObjectProtected(Permissions.View)
  security.declareObjectPublic()

  # These get methods are workarounds for the Zope security model.
  security.declareProtected(Permissions.AccessContentsInformation, 'getMovementList')
  def getMovementList(self):
    return self.movement_list

  security.declareProtected(Permissions.AccessContentsInformation, 'getResourceId')
  def getResourceId(self):
    return self.resource_id

  security.declareProtected(Permissions.AccessContentsInformation, 'getResourceTitle')
  def getResourceTitle(self):
    return self.resource_title

  security.declareProtected(Permissions.AccessContentsInformation, 'getVariationBaseCategoryList')
  def getVariationBaseCategoryList(self):
103
    return list(self.variation_base_category_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

  security.declareProtected(Permissions.AccessContentsInformation, 'getTotalPrice')
  def getTotalPrice(self):
    return self.total_price

  security.declareProtected(Permissions.AccessContentsInformation, 'getTotalQuantity')
  def getTotalQuantity(self):
    return self.total_quantity

  security.declareProtected(Permissions.AccessContentsInformation, 'getMatrix')
  def getMatrix(self):
    return self.matrix

  def __init__(self, movement):
    self.movement_list = []
119 120 121 122 123 124
    #self.quantity_unit = movement.getQuantityUnit() # This is likely an error JPSforYO
    resource_value = movement.getResourceValue()
    if resource_value is not None:
      self.quantity_unit = resource_value.getDefaultQuantityUnit()
    else:
      self.quantity_unit = movement.getQuantityUnit() # Meaningless XXX ?
Jean-Paul Smets's avatar
Jean-Paul Smets committed
125 126 127 128
    self.resource = movement.getResource()
    self.resource_id = movement.getResourceId()
    self.resource_title = movement.getResourceTitle()
    self.variation_base_category_list = movement.getVariationBaseCategoryList()
129
    self.variation_category_list = []
130 131 132 133
    # self.total_price = movement.getTotalPrice() # This is likely an error JPSforYO
    # self.total_quantity = movement.getTotalQuantity() # This is likely an error JPSforYO
    self.total_price = 0.0 # No need to add twice since we add it in append
    self.total_quantity = 0.0 # No need to add twice since we add it in append
Jean-Paul Smets's avatar
Jean-Paul Smets committed
134 135 136 137
    self.matrix = XMLMatrix(None)
    self.append(movement)

  def test(self, movement):
138 139
    # Use resource rather than resource_id JPSforYO
    if movement.getResource() == self.resource and \
Jean-Paul Smets's avatar
Jean-Paul Smets committed
140 141 142 143 144 145 146 147
      movement.getVariationBaseCategoryList() == self.variation_base_category_list:
      return 1
    else:
      return 0

  def append(self, movement):
    if not movement in self.movement_list:
      self.movement_list.append(movement)
148 149 150
      price = movement.getTotalPrice()
      if price is not None:
        self.total_price += price # XXX Something should be done wrt to currency
151 152 153 154 155 156
      # If one order has beed negociated in USD and anotehr in EUR, then there is no
      # way to merge invoices. Multiple invoices must be produced
      # This may require serious extensions to this code
      # ie. N deliveries result in M invoices (1 invoice per currency)
      #self.total_quantity += movement.getTotalQuantity() # This is likely an error JPSforYO
      self.total_quantity += movement.getInventoriatedQuantity()
157 158 159
      for category in movement.getVariationCategoryList():
        if category not in self.variation_category_list:
          self.variation_category_list.append(category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

  def finish(self):
    # Make up a list of cell ranges for setCellRange.
    cell_range_list = []
    for base_category in self.variation_base_category_list:
      cell_range = []
      for movement in self.movement_list:
        for category in movement.getCategoryMembershipList(base_category, base=1):
          if not category in cell_range:
            cell_range.append(category)
      cell_range_list.append(cell_range)

    kw_list = {'base_id' : 'movement'}
    apply(self.matrix._setCellRange, cell_range_list, kw_list)

    # Add every movement into the matrix.
    for movement in self.movement_list:
      # Make sure that the order of the category lists is preserved.
      point = []
      for base_category in self.variation_base_category_list:
        point += movement.getCategoryMembershipList(base_category, base=1)
      cell = apply(self.matrix.getCell, point, kw_list)
      if cell is None:
        cell = apply(self.matrix.newCell, point, kw_list)
        cell.setMappedValuePropertyList(['price', 'quantity'])
        cell._setPrice(movement.getPrice())
        cell._setQuantity(movement.getQuantity())
      else:
        quantity = movement.getQuantity()
        if quantity:
          cell._setPrice(movement.getPrice() * quantity + cell.getPrice()) # Accumulate total price
          cell._setQuantity(quantity + cell.getQuantity())  # Accumulate quantity

    # Normalize price to compute unit price
    for cell in self.matrix.getCellValueList():
      quantity =  cell.getQuantity()
      if quantity:
        cell._setPrice(cell.getPrice() / float(quantity))
      else:
        cell._setPrice(0.0) # if quantity is zero, price is et to 0.0 as a convention
200 201 202 203 204 205 206
    # Normalize self price also JPSforYO
    quantity = self.total_quantity
    if quantity:
      self.price = self.total_price / float(quantity)
    else:
      self.price = 0.0
    LOG('Group', 0, repr(self.total_price), repr(self.total_quantity))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
207 208 209 210 211

InitializeClass(Group)
#allow_class(Group)

class Delivery(XMLObject):
212 213 214 215
    """
        Each time delivery is modified, it MUST launch a reindexing of
        inventories which are related to the resources contained in the Delivery
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
216 217 218 219 220
    # CMF Type Definition
    meta_type = 'ERP5 Delivery'
    portal_type = 'Delivery'
    isPortalContent = 1
    isRADContent = 1
221
    isDelivery = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

    # Declarative security
    security = ClassSecurityInfo()
    security.declareObjectProtected(Permissions.View)

    # Default Properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
                      , PropertySheet.Task
                      , PropertySheet.Arrow
                      , PropertySheet.Movement
                      , PropertySheet.Delivery
                      , PropertySheet.Reference
                      )

239
    security.declareProtected(Permissions.ModifyPortalContent, 'expand')
240
    def expand(self, applied_rule_id,force=0,**kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
241 242 243 244
      """
        Reexpand applied rule
      """
      my_applied_rule = self.portal_simulation.get(applied_rule_id, None)
245 246 247
      LOG('Delivery.expand, force',0,force)
      LOG('Delivery.expand, my_applied_rule',0,my_applied_rule)
      LOG('Delivery.expand, my_applied_rule.expand',0,my_applied_rule.expand)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
248
      if my_applied_rule is not None:
249
        my_applied_rule.expand(force=force,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
250 251
        my_applied_rule.immediateReindexObject()
      else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
252
        LOG("ERP5 Error:", 100, "Could not expand applied rule %s for delivery %s" % (applied_rule_id, self.getId()))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

    security.declareProtected(Permissions.AccessContentsInformation, 'isAccountable')
    def isAccountable(self):
      """
        Returns 1 if this needs to be accounted
        Only account movements which are not associated to a delivery
        Whenever delivery is there, delivery has priority
      """
      return 1

    security.declareProtected(Permissions.ModifyPortalContent, 'plan')
    def plan(self):
      """
        Sets the delivery to planned
      """
      # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
      # self.applyToDeliveryRelatedMovement(method_id = 'expand')

    plan = WorkflowMethod(plan)

    security.declareProtected(Permissions.ModifyPortalContent, 'confirm')
    def confirm(self):
      """
        Sets the order to confirmed
      """
      # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
      # self.applyToDeliveryRelatedMovement(method_id = 'expand')

    confirm = WorkflowMethod(confirm)

    security.declareProtected(Permissions.ModifyPortalContent, 'start')
    def start(self):
      """
        Starts the delivery
      """
      # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
      # self.applyToDeliveryRelatedMovement(method_id = 'expand')

    start = WorkflowMethod(start)

    security.declareProtected(Permissions.ModifyPortalContent, 'stop')
    def stop(self):
      """
        Stops the delivery
      """
      # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
      # self.applyToDeliveryRelatedMovement(method_id = 'expand')

    stop = WorkflowMethod(stop)

    security.declareProtected(Permissions.ModifyPortalContent, 'deliver')
    def deliver(self):
      """
        Deliver the delivery
      """
      # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
      # self.applyToDeliveryRelatedMovement(method_id = 'expand')

    deliver = WorkflowMethod(deliver)

    security.declareProtected(Permissions.ModifyPortalContent, 'cancel')
    def cancel(self):
      """
        Deliver the delivery
      """
      # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
      # self.applyToDeliveryRelatedMovement(method_id = 'expand')

    cancel = WorkflowMethod(cancel)

323 324
    security.declareProtected(Permissions.ModifyPortalContent, '_invoice')
    def _invoice(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
325 326 327
      """
        This method is called whenever a packing list is being invoiced
      """
328 329
      # We will make sure that everything is well generated into  the
      # simulation, then we will be able to buid the invoice list.
330
      # we create an invoice for this delivery
331
      self.activate(priority=4).buildInvoiceList()
332

333
    invoice = WorkflowMethod(_invoice, 'invoice')
334

335 336
    security.declareProtected(Permissions.ModifyPortalContent, 'buildInvoiceList')
    def buildInvoiceList(self):
337
      """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
338
        Retrieve all invoices lines into the simulation
339
      """
Alexandre Boeglin's avatar
Alexandre Boeglin committed
340
      reindexable_movement_list = []
341 342 343 344 345

      parent_simulation_line_list = []
      for o in self.objectValues():
        parent_simulation_line_list += [x for x in o.getDeliveryRelatedValueList() \
                                        if x.getPortalType()=='Simulation Movement']
Alexandre Boeglin's avatar
Alexandre Boeglin committed
346 347
      invoice_rule_list = []
      simulation_invoice_line_list = []
348 349
      for o in parent_simulation_line_list:
        for rule in o.objectValues():
Alexandre Boeglin's avatar
Alexandre Boeglin committed
350 351
          invoice_rule_list.append(rule)
          simulation_invoice_line_list += rule.objectValues()
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
      LOG('buildInvoiceList simulation_invoice_line_list',0,simulation_invoice_line_list)
      from Products.ERP5.MovementGroup import OrderMovementGroup
      from Products.ERP5.MovementGroup import PathMovementGroup
      from Products.ERP5.MovementGroup import DateMovementGroup
      from Products.ERP5.MovementGroup import ResourceMovementGroup
      from Products.ERP5.MovementGroup import VariantMovementGroup
      #class_list = [OrderMovementGroup,PathMovementGroup,DateMovementGroup,ResourceMovementGroup,VariantMovementGroup]
      class_list = [OrderMovementGroup,PathMovementGroup,DateMovementGroup,ResourceMovementGroup]
      root_group = self.portal_simulation.collectMovement(simulation_invoice_line_list,class_list=class_list)
      invoice_list = []

      LOG('buildInvoiceList root_group',0,root_group)
      if root_group is not None:
        LOG('buildInvoiceList root_group.group_list',0,root_group.group_list)
        for order_group in root_group.group_list:
          LOG('buildInvoiceList order_group.order',0,order_group.order)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
368
          if order_group.order is not None:
369 370 371 372 373 374 375 376 377 378
            # Only build if there is not order yet
            LOG('buildInvoiceList order_group.group_list',0,order_group.group_list)
            for path_group in order_group.group_list :
              invoice_module = self.accounting
              invoice_type = 'Sale Invoice Transaction'
              invoice_line_type = 'Invoice Line'

              LOG('buildInvoiceList path_group.group_list',0,path_group.group_list)
              for date_group in path_group.group_list :

Alexandre Boeglin's avatar
Alexandre Boeglin committed
379
                invoice = invoice_module.newContent(portal_type = invoice_type,
380 381 382 383 384 385
                              start_date = date_group.start_date,
                              stop_date = date_group.stop_date,
                              source = path_group.source,
                              destination = path_group.destination,
                              source_section = path_group.source_section,
                              destination_section = path_group.destination_section,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
386 387 388 389
                              causality_value = self,
                              title = self.getTitle(),
                              description = 'Invoice related to the Delivery %s' % self.getTitle())
                # the new invoice is added to the invoice_list
390
                invoice_list.append(invoice)
Alexandre Boeglin's avatar
Alexandre Boeglin committed
391
                #for rule in invoice_rule_list : rule.setDeliveryValue(invoice) # This looks strange. Is it okay to do this ?
392 393 394

                for resource_group in date_group.group_list :

Alexandre Boeglin's avatar
Alexandre Boeglin committed
395
                  LOG('buildInvoiceList resource_group.group_list',0,resource_group.group_list)
396
                  # Create a new Sale Invoice Transaction Line for each resource
397 398
                  invoice_line = invoice.newContent(
                        portal_type=invoice_line_type
Alexandre Boeglin's avatar
Alexandre Boeglin committed
399 400 401 402
                      , resource=resource_group.resource)

#                  line_variation_category_list = []
#                  line_variation_base_category_dict = {}
403 404 405 406 407 408 409 410 411 412 413 414

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

                  # update variation_base_category_list and line_variation_category_list for delivery_line
Alexandre Boeglin's avatar
Alexandre Boeglin committed
415 416 417 418 419 420 421 422
#                  line_variation_base_category_list = line_variation_base_category_dict.keys()
#                  invoice_line.setVariationBaseCategoryList(line_variation_base_category_list)
#                  invoice_line.setVariationCategoryList(line_variation_category_list)

                  # IMPORTANT : invoice cells are automatically created during setVariationCategoryList

                  #XXX for now, we quickly need this working, without the need of variant_group
                  object_to_update = invoice_line
423
                  # compute quantity and price for invoice_cell or invoice_line and
Alexandre Boeglin's avatar
Alexandre Boeglin committed
424 425
                  # build relation between simulation_movement and invoice_cell or invoice_line
                  if object_to_update is not None :
426
                    quantity = 0
Alexandre Boeglin's avatar
Alexandre Boeglin committed
427 428
                    total_price = 0
                    for movement in resource_group.movement_list :
429
                      quantity += movement.getConvertedQuantity()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
430
                      try :
431
                        total_price += movement.getNetConvertedQuantity() * movement.getPrice() # XXX WARNING - ADD PRICED QUANTITY
Alexandre Boeglin's avatar
Alexandre Boeglin committed
432 433 434 435 436 437 438
                      except :
                        total_price = None
                      # What do we really need to update in the simulation movement ?
                      if movement.getPortalType() == 'Simulation Movement' :
                        movement._setDeliveryValue(object_to_update)
                        reindexable_movement_list.append(movement)

439 440
                    if quantity <> 0 and total_price is not None:
                      average_price = total_price/quantity
Alexandre Boeglin's avatar
Alexandre Boeglin committed
441 442 443
                    else :
                      average_price = 0

444 445
                    LOG('buildInvoiceList edit', 0, repr(( object_to_update, quantity, average_price, )))
                    object_to_update.edit(quantity = quantity,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
446 447
                                          price = average_price)

448
                  # update quantity and price for each invoice_cell
Alexandre Boeglin's avatar
Alexandre Boeglin committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
                  #XXX for variant_group in resource_group.group_list :
                  if 0 :
                    LOG('Variant_group examin',0,str(variant_group.category_list))
                    object_to_update = None
                    # if there is no variation of the resource, update invoice_line with quantities and price
                    if len(variant_group.category_list) == 0 :
                      object_to_update = invoice_line
                    # else find which invoice_cell is represented by variant_group
                    else :
                      categories_identity = 0
                      #LOG('Before Check cell',0,str(invoice_cell_type))
                      #LOG('Before Check cell',0,str(invoice_line.contentValues()))
                      for invoice_cell in invoice_line.contentValues(filter={'portal_type':'Invoice Cell'}) :
                        #LOG('Check cell',0,str(invoice_cell))
                        #LOG('Check cell',0,str(variant_group.category_list))
                        if len(variant_group.category_list) == len(invoice_cell.getVariationCategoryList()) :
                          #LOG('Parse category',0,str(invoice_cell.getVariationCategoryList()))
                          for category in invoice_cell.getVariationCategoryList() :
                            if not category in variant_group.category_list :
                              #LOG('Not found category',0,str(category))
                              break
                          else :
                            categories_identity = 1

                        if categories_identity :
                          object_to_update = invoice_cell
                          break

477
                    # compute quantity and price for invoice_cell or invoice_line and
Alexandre Boeglin's avatar
Alexandre Boeglin committed
478 479
                    # build relation between simulation_movement and invoice_cell or invoice_line
                    if object_to_update is not None :
480
                      cell_quantity = 0
Alexandre Boeglin's avatar
Alexandre Boeglin committed
481 482
                      cell_total_price = 0
                      for movement in variant_group.movement_list :
483
                        cell_quantity += movement.getConvertedQuantity()
Alexandre Boeglin's avatar
Alexandre Boeglin committed
484
                        try :
485
                          cell_total_price += movement.getNetConvertedQuantity() * movement.getPrice() # XXX WARNING - ADD PRICED QUANTITY
Alexandre Boeglin's avatar
Alexandre Boeglin committed
486 487 488 489 490 491 492
                        except :
                          cell_total_price = None
                        # What do we really need to update in the simulation movement ?
                        if movement.getPortalType() == 'Simulation Movement' :
                          movement._setDeliveryValue(object_to_update)
                          reindexable_movement_list.append(movement)

493 494
                      if cell_quantity <> 0 and cell_total_price is not None:
                        average_price = cell_total_price/cell_quantity
Alexandre Boeglin's avatar
Alexandre Boeglin committed
495 496 497
                      else :
                        average_price = 0

498 499
                      LOG('buildInvoiceList edit', 0, repr(( object_to_update, cell_quantity, average_price, )))
                      object_to_update.edit(quantity = cell_quantity,
Alexandre Boeglin's avatar
Alexandre Boeglin committed
500
                                            price = average_price)
501
                                            
Alexandre Boeglin's avatar
Alexandre Boeglin committed
502 503 504
      # we now reindex the movements we modified
      for movement in reindexable_movement_list :
        movement.immediateReindexObject()
505 506
      return invoice_list

Jean-Paul Smets's avatar
Jean-Paul Smets committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524

    # Pricing methods
    def _getTotalPrice(self, context):
      return 2.0

    def _getDefaultTotalPrice(self, context):
      return 3.0

    def _getSourceTotalPrice(self, context):
      return 4.0

    def _getDestinationTotalPrice(self, context):
      return 5.0

    security.declareProtected(Permissions.AccessContentsInformation, 'getTotalPrice')
    def getTotalPrice(self):
      """
      """
525
      result = self.z_total_price(explanation_uid = self.getUid())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
526 527 528 529 530 531 532 533
      return result[0][0]

#     security.declareProtected(Permissions.AccessContentsInformation, 'getTotalPrice')
#     def getTotalPrice(self, context=None, REQUEST=None, **kw):
#       """
#       """
#       return self._getTotalPrice(self.asContext(context=context, REQUEST=REQUEST, **kw))

Yoshinori Okuji's avatar
Yoshinori Okuji committed
534
    security.declareProtected(Permissions.AccessContentsInformation, 'getDefaultTotalPrice')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    def getDefaultTotalPrice(self, context=None, REQUEST=None, **kw):
      """
      """
      return self._getDefaultTotalPrice(self.asContext(context=context, REQUEST=REQUEST, **kw))

    security.declareProtected(Permissions.AccessContentsInformation, 'getSourceTotalPrice')
    def getSourceTotalPrice(self, context=None, REQUEST=None, **kw):
      """
      """
      return self._getSourceTotalPrice(self.asContext(context=context, REQUEST=REQUEST, **kw))

    security.declareProtected(Permissions.AccessContentsInformation, 'getDestinationTotalPrice')
    def getDestinationTotalPrice(self, context=None, REQUEST=None, **kw):
      """
      """
      return self._getDestinationTotalPrice(self.asContext(context=context, REQUEST=REQUEST, **kw))

    # Pricing
Jean-Paul Smets's avatar
Jean-Paul Smets committed
553 554 555 556 557 558
    security.declareProtected( Permissions.ModifyPortalContent, 'updatePrice' )
    def updatePrice(self):
      for c in self.objectValues():
        if hasattr(aq_base(c), 'updatePrice'):
          c.updatePrice()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
559
    security.declareProtected(Permissions.AccessContentsInformation, 'getTotalPrice')
560
    def getTotalPrice(self,  src__=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
561 562 563
      """
        Returns the total price for this order
      """
564
      kw['explanation_uid'] = self.getUid()
565 566
      kw.update(self.portal_catalog.buildSQLQuery(**kw))
      if src__:
567 568
        return self.Delivery_zGetTotal(src__=1, **kw)
      aggregate = self.Delivery_zGetTotal(**kw)[0]
569
      return aggregate.total_price or 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
570 571

    security.declareProtected(Permissions.AccessContentsInformation, 'getTotalQuantity')
572
    def getTotalQuantity(self, src__=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
573 574
      """
        Returns the quantity if no cell or the total quantity if cells
575
      """      
576
      kw['explanation_uid'] = self.getUid()
577 578
      kw.update(self.portal_catalog.buildSQLQuery(**kw))
      if src__:
579 580
        return self.Delivery_zGetTotal(src__=1, **kw)
      aggregate = self.Delivery_zGetTotal(**kw)[0]
581
      return aggregate.total_quantity or 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
582 583 584 585 586 587 588

    security.declareProtected(Permissions.AccessContentsInformation, 'getDeliveryUid')
    def getDeliveryUid(self):
      return self.getUid()

    security.declareProtected(Permissions.AccessContentsInformation, 'getDeliveryValue')
    def getDeliveryValue(self):
589 590 591 592 593 594 595 596 597 598 599
      """
      Deprecated, we should use getRootDeliveryValue instead
      """
      return self

    security.declareProtected(Permissions.AccessContentsInformation, 'getRootDeliveryValue')
    def getRootDeliveryValue(self):
      """
      This method returns the delivery, it is usefull to retrieve the delivery
      from a line or a cell
      """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
600 601
      return self

602 603 604 605
    security.declareProtected(Permissions.AccessContentsInformation, 'getDelivery')
    def getDelivery(self):
      return self.getRelativeUrl()

606
    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementList')
607
    def getMovementList(self, portal_type=None):
608 609 610
      """
        Return a list of movements.
      """
611 612
      if portal_type is None:
        portal_type = self.getPortalMovementTypeList()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
613
      movement_list = []
614
      for m in self.contentValues(filter={'portal_type': portal_type}):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
615
        if m.hasCellContent():
616
          for c in m.contentValues(filter={'portal_type': portal_type}):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
617 618 619 620 621
            movement_list.append(c)
        else:
          movement_list.append(m)
      return movement_list

622 623 624 625 626 627
    security.declareProtected(Permissions.AccessContentsInformation, 'getSimulatedMovementList')
    def getSimulatedMovementList(self):
      """
        Return a list of simulated movements.
        This does not contain Container Line or Container Cell.
      """
628
      return self.getMovementList(portal_type=self.getPortalSimulatedMovementTypeList())
629 630 631 632 633 634 635

    security.declareProtected(Permissions.AccessContentsInformation, 'getInvoiceMovementList')
    def getInvoiceMovementList(self):
      """
        Return a list of simulated movements.
        This does not contain Container Line or Container Cell.
      """
636
      return self.getMovementList(portal_type=self.getPortalInvoiceMovementTypeList())
637 638 639 640 641 642 643 644

    security.declareProtected(Permissions.AccessContentsInformation, 'getContainerList')
    def getContainerList(self):
      """
        Return a list of root containers.
        This does not contain sub-containers.
      """
      container_list = []
645
      for m in self.contentValues(filter={'portal_type': self.getPortalContainerTypeList()}):
646 647 648
        container_list.append(m)
      return container_list

Jean-Paul Smets's avatar
Jean-Paul Smets committed
649 650 651 652 653
    def applyToDeliveryRelatedMovement(self, portal_type='Simulation Movement', method_id = 'expand'):
      for my_simulation_movement in self.getDeliveryRelatedValueList(
                                                portal_type = 'Simulation Movement'):
          # And apply
          getattr(my_simulation_movement.getObject(), method_id)()
654
      for m in self.contentValues(filter={'portal_type': self.getPortalMovementTypeList()}):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        # Find related in simulation
        for my_simulation_movement in m.getDeliveryRelatedValueList(
                                                portal_type = 'Simulation Movement'):
          # And apply
          getattr(my_simulation_movement.getObject(), method_id)()
        for c in m.contentValues(filter={'portal_type': 'Delivery Cell'}):
          for my_simulation_movement in c.getDeliveryRelatedValueList(
                                                portal_type = 'Simulation Movement'):
            # And apply
            getattr(my_simulation_movement.getObject(), method_id)()


    #######################################################
    # Causality computation
    security.declareProtected(Permissions.View, 'isConvergent')
    def isConvergent(self):
      """
        Returns 0 if the target is not met
      """
      return not self.isDivergent()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
676 677
    security.declareProtected(Permissions.View, 'isSimulated')
    def isSimulated(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
678 679 680 681
      """
        Returns 1 if all movements have a delivery or order counterpart
        in the simulation
      """
682
      LOG('Delivery.isSimulated getMovementList',0,self.getMovementList())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
683
      for m in self.getMovementList():
684 685
        LOG('Delivery.isSimulated m',0,m.getPhysicalPath())
        LOG('Delivery.isSimulated m.isSimulated',0,m.isSimulated())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
686
        if not m.isSimulated():
687
          LOG('Delivery.isSimulated m.getQuantity',0,m.getQuantity())
688 689
          LOG('Delivery.isSimulated m.getSimulationQuantity',0,m.getSimulationQuantity())
          if m.getQuantity() != 0.0 or m.getSimulationQuantity() != 0:
690 691
            return 0
          # else Do we need to create a simulation movement ? XXX probably not
Jean-Paul Smets's avatar
Jean-Paul Smets committed
692 693
      return 1

694 695 696 697 698 699
    security.declareProtected(Permissions.View, 'isDivergent')
    def isDivergent(self):
      """
        Returns 1 if the target is not met according to the current information
        After and edit, the isOutOfTarget will be checked. If it is 1,
        a message is emitted
Jean-Paul Smets's avatar
Jean-Paul Smets committed
700

701 702
        emit targetUnreachable !
      """
703 704 705 706 707 708 709 710 711 712
      if len(self.Delivery_zIsDivergent(uid=self.getUid())) > 0:
        return 1
      # Check if the total quantity equals the total of each simulation movement quantity
      for movement in self.getMovementList():
        d_quantity = movement.getQuantity()
        simulation_quantity = 0.
        for simulation_movement in movement.getDeliveryRelatedValueList():
          simulation_quantity += float(simulation_movement.getCorrectedQuantity())
        if d_quantity != simulation_quantity:
          return 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
      return 0

    security.declareProtected(Permissions.ModifyPortalContent, 'solve')
    def solve(self, dsolver, tsolver):
      """
        Solves a delivery with a Solver
        Only delivery level matter should be modified (not movements)
      """
      dsolver.solveDelivery(self)
      tsolver.solveDelivery(self)

    #######################################################
    # Defer indexing process
    def reindexObject(self, *k, **kw):
      """
        Reindex children and simulation
      """
      if self.isIndexable:
        # Reindex children
        self.activate().recursiveImmediateReindexObject()
        # NEW: we never rexpand simulation - This is a task for DSolver / TSolver
        # Make sure expanded simulation is still OK (expand and reindex)
        # self.activate().applyToDeliveryRelatedMovement(method_id = 'expand')

    #######################################################
    # Stock Management
    def _getMovementResourceList(self):
      resource_dict = {}
741
      for m in self.contentValues(filter={'portal_type': self.getPortalMovementTypeList()}):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
742 743 744 745 746 747
        r = m.getResource()
        if r is not None:
          resource_dict[r] = 1
      return resource_dict.keys()

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventory')
748 749 750 751 752 753
    def getInventory(self, **kw):
      """
      Returns inventory
      """
      kw['resource'] = self._getMovementResourceList()
      return self.portal_simulation.getInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
754 755

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventory')
756
    def getCurrentInventory(self, **kw):
757 758 759 760 761
      """
      Returns current inventory
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getCurrentInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
762 763

    security.declareProtected(Permissions.AccessContentsInformation, 'getAvailableInventory')
764
    def getAvailableInventory(self, **kw):
765 766 767 768 769 770 771 772
      """
      Returns available inventory
      (current inventory - deliverable)
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getAvailableInventory(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventory')
773
    def getFutureInventory(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
774
      """
775
      Returns inventory at infinite
Jean-Paul Smets's avatar
Jean-Paul Smets committed
776
      """
777 778
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getFutureInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
779 780

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryList')
781
    def getInventoryList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
782
      """
783
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
784
      """
785 786
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getInventoryList(**kw)
787

788
    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryList')
789
    def getCurrentInventoryList(self, **kw):
790 791 792 793 794
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getCurrentInventoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
795 796

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryList')
797
    def getFutureInventoryList(self, **kw):
798 799 800 801 802
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getFutureInventoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
803 804

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryStat')
805
    def getInventoryStat(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
806
      """
807
      Returns statistics of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
808
      """
809 810
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getInventoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
811

812
    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryStat')
813
    def getCurrentInventoryStat(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
814
      """
815
      Returns statistics of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
816
      """
817 818
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getCurrentInventoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
819

820
    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryStat')
821
    def getFutureInventoryStat(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
822
      """
823
      Returns statistics of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
824
      """
825 826
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getFutureInventoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
827 828

    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryChart')
829 830 831 832 833 834 835 836
    def getInventoryChart(self, **kw):
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getInventoryChart(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 'getCurrentInventoryChart')
837
    def getCurrentInventoryChart(self, **kw):
838 839 840 841 842
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getCurrentInventoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
843 844

    security.declareProtected(Permissions.AccessContentsInformation, 'getFutureInventoryChart')
845
    def getFutureInventoryChart(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
846
      """
847
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
848
      """
849 850
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getFutureInventoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
851

852
    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryHistoryList')
853
    def getInventoryHistoryList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
854
      """
855
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
856
      """
857 858
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getInventoryHistoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
859

860
    security.declareProtected(Permissions.AccessContentsInformation, 'getInventoryHistoryChart')
861
    def getInventoryHistoryChart(self, **kw):
862 863 864 865 866
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getInventoryHistoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
867 868

    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementHistoryList')
869
    def getMovementHistoryList(self, **kw):
870 871 872 873 874
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getMovementHistoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
875 876

    security.declareProtected(Permissions.AccessContentsInformation, 'getMovementHistoryStat')
877
    def getMovementHistoryStat(self, **kw):
878 879 880 881 882
      """
      Returns list of inventory grouped by section or site
      """
      kw['category'] = self._getMovementResourceList()
      return self.portal_simulation.getMovementHistoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919


    security.declareProtected(Permissions.AccessContentsInformation, 'collectMovement')
    def collectMovement(self, movement_list):
      """
        Collect all movements into a list of group objects.
      """
      from Globals import InitializeClass

      # Collect each delivery cell into a delivery line.
      group_list = []
      for movement in movement_list:
        movement_in_group = 0
        for group in group_list:
          if group.test(movement):
            group.append(movement)
            movement_in_group = 1
            break
        if not movement_in_group:
          group_list.append(Group(movement).__of__(self))

      # This is required to build a matrix.
      for group in group_list:
        group.finish()

      return group_list

    # XXX this should be moved to Invoice
    security.declareProtected(Permissions.AccessContentsInformation, 'buildInvoiceLineList')
    def buildInvoiceLineList(self, movement_group):
      """
        Build invoice lines from a list of movements.
      """
      invoice_line_list = []

      if movement_group is not None:
        for group in movement_group:
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
          # Create each invoice_line in the new invoice
          # but only if quantity > 0
          if group.total_quantity > 0 :
            invoice_line = self.newContent(portal_type = 'Invoice Line',
                                          resource = group.resource,
                                          quantity_unit = group.quantity_unit) # FIXME: more args
            invoice_line_list.append(invoice_line)

            # Make sure that the order is always preserved.
            variation_base_category_list = list(group.variation_base_category_list)
            variation_base_category_list.sort()
            invoice_line.setVariationBaseCategoryList(variation_base_category_list)
            #LOG('buildInvoiceLineList', 0, "group.variation_base_category_list = %s" % str(group.variation_base_category_list))
            variation_category_list = []
            for cell_key in group.matrix.getCellKeyList(base_id='movement'):
              for variation_category in cell_key:
                if variation_category not in variation_category_list:
                  variation_category_list.append(variation_category)
            invoice_line.setVariationCategoryList(variation_category_list)
            # IMPORTANT : delivery cells are automatically created during setVariationCategoryList

            #LOG('buildInvoiceLineList', 0, "invoice_line.contentValues() = %s" % str(invoice_line.contentValues()))
            if len(variation_category_list) > 0:
              for invoice_cell in invoice_line.contentValues(filter={'portal_type':'Invoice Cell'}):
                category_list = invoice_cell.getVariationCategoryList()
                # XXX getVariationCategoryList does not return the same order as setVariationBaseCategoryList
                point = []
                for base_category in group.variation_base_category_list:
                  for category in category_list:
                    if category.startswith(base_category + '/'):
                      point.append(category)
                      break
                kw_list = {'base_id' : 'movement'}
                cell = apply(group.matrix.getCell, point, kw_list)
954
                #LOG('buildInvoiceLineList', 0,
955 956 957 958 959 960 961 962 963 964 965 966
                #    "point = %s, cell = %s" % (str(point), str(cell)))
                if cell is not None:
                  #LOG('buildInvoiceLineList', 0,
                  #    "quentity = %s, price = %s" % (str(cell.getQuantity()), str(cell.getPrice())))
                  invoice_cell.edit(quantity = cell.getQuantity(),
                                    price = cell.getPrice(),
                                    force_update = 1)
            else:
              # There is no variation category.
              invoice_line.edit(quantity = group.total_quantity,
                                price = group.price,
                                force_update = 1) # Use unit price JPSforYO
Jean-Paul Smets's avatar
Jean-Paul Smets committed
967 968

      return invoice_line_list
969 970 971 972 973

    # Simulation consistency propagation
    security.declareProtected(Permissions.ModifyPortalContent, 'updateFromSimulation')
    def updateFromSimulation(self, update_target = 0):
      """
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
      Update all lines of this transaction based on movements in the simulation
      related to this transaction.
      """
      # XXX update_target no more used
      transaction_type = self.getPortalType()
      line_type = transaction_type + " Line"
      to_aggregate_movement_list = []
      to_reindex_list = []
      source_section = self.getSourceSection()
      destination_section = self.getDestinationSection()
      resource = self.getResource()
      start_date = self.getStartDate()
      
      def updateLineOrCell(c):
        quantity = 0
        source = c.getSource()
        destination = c.getDestination()
        for m in c.getDeliveryRelatedValueList():
          m_source_section = m.getSourceSection()
          m_destination_section = m.getDestinationSection()
          m_resource = m.getResource()
          m_start_date = m.getStartDate()
          m_source = m.getSource()
          m_destination = m.getDestination()
          m_quantity = m.getCorrectedQuantity()
          if m_source_section == source_section and m_destination_section == destination_section \
              and m_resource == resource and m_start_date == start_date:
            if m_source == source and m_destination == destination:
              # The path is the same, only the quantity may have changed
              if m_quantity:
                quantity += m_quantity
            else:
              # Source and/or destination have changed. The Simulation Movement has
              # to be linked to a new TransactionLine
              m.setDelivery('')
              to_aggregate_movement_list.append(m)
            to_reindex_list.append(m)
          else:
            # Source_section and/or destination_section and/or date and/or resource differ
            # The Simulation Movement has to be linked to a new Transaction (or an existing one)
            m.setDelivery('')
            to_aggregate_movement_list.append(m)
            to_reindex_list.append(m)
        # Recalculate delivery ratios for the remaining movements in this line
        c.setQuantity(quantity)
        c.updateSimulationDeliveryProperties()
      
      # Update the transaction from simulation
1022
      for l in self.contentValues(filter={'portal_type':self.getPortalDeliveryMovementTypeList()}):
1023
        if l.hasCellContent():
1024
          for c in l.contentValues(filter={'portal_type':self.getPortalDeliveryMovementTypeList()}):
1025
            updateLineOrCell(c)
1026
        else:
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
          updateLineOrCell(l)
          
      # Re-aggregate the disconnected movements
      # XXX Dirty ; it should use DeliveryBuilder when it will be available
      if len(to_aggregate_movement_list) > 0:
        applied_rule_type = to_aggregate_movement_list[0].getRootAppliedRule().getSpecialiseId()
        if applied_rule_type == "default_amortisation_rule":
          self.portal_simulation.buildDeliveryList( self.portal_simulation.collectMovement(to_aggregate_movement_list,
                                                        [ResourceMovementGroup, DateMovementGroup, PathMovementGroup] ) )
        
      # Touch the Transaction to make an automatic converge
      self.edit() 

1040 1041 1042
    security.declareProtected(Permissions.ModifyPortalContent, 'propagateResourceToSimulation')
    def propagateResourceToSimulation(self):
      """
1043
        Propagates any changes on resources or variations to the simulation
1044 1045 1046
        by disconnecting simulation movements refering to another resource/variation,
        creating DeliveryRules for new resources and setting target_quantity to 0 for resources
        which are no longer delivered
1047 1048 1049

        propagateResourceToSimulation has priority (ie. must be executed before) over updateFromSimulation
      """
1050 1051
      if self.getPortalType() == 'Amortisation Transaction':
        return
1052 1053
      unmatched_simulation_movement = []
      unmatched_delivery_movement = []
1054
      LOG('propagateResourceToSimulation, ',0,'starting')
1055
      for l in self.contentValues(filter={'portal_type':self.getPortalDeliveryMovementTypeList()}):
1056 1057 1058 1059
        LOG('propagateResourceToSimulation, l.getPhysicalPath()',0,l.getPhysicalPath())
        LOG('propagateResourceToSimulation, l.objectValues()',0,l.objectValues())
        LOG('propagateResourceToSimulation, l.hasCellContent()',0,l.hasCellContent())
        LOG('propagateResourceToSimulation, l.showDict()',0,l.showDict())
1060
        if l.hasCellContent():
1061
          for c in l.contentValues(filter={'portal_type':self.getPortalDeliveryMovementTypeList()}):
1062
            LOG('propagateResourceToSimulation, c.getPhysicalPath()',0,c.getPhysicalPath())
1063
            for s in c.getDeliveryRelatedValueList():
1064 1065 1066
              LOG('propagateResourceToSimulation, s.getPhysicalPath()',0,s.getPhysicalPath())
              LOG('propagateResourceToSimulation, c.getResource()',0,c.getResource())
              LOG('propagateResourceToSimulation, s.getResource()',0,s.getResource())
1067 1068 1069 1070
              if s.getResource() != c.getResource() or s.getVariationText() != c.getVariationText(): # We should use here some day getVariationValue and __cmp__
                unmatched_delivery_movement.append(c)
                unmatched_simulation_movement.append(s)
                s.setDelivery(None) # Disconnect
1071
                l._setQuantity(0.0)
1072 1073 1074 1075 1076 1077
        else:
          for s in l.getDeliveryRelatedValueList():
            if s.getResource() != l.getResource() or s.getVariationText() != l.getVariationText():
              unmatched_delivery_movement.append(l)
              unmatched_simulation_movement.append(s)
              s.setDelivery(None) # Disconnect
1078
              l._setQuantity(0.0)
1079
      LOG('propagateResourceToSimulation, unmatched_simulation_movement',0,unmatched_simulation_movement)
1080
      # Build delivery list with unmatched_simulation_movement
1081
      root_group = self.portal_simulation.collectMovement(unmatched_simulation_movement)
1082
      new_delivery_list = self.portal_simulation.buildDeliveryList(root_group)
1083 1084 1085 1086 1087 1088
      simulation_state = self.getSimulationState()
      if simulation_state == 'confirmed':
        for new_delivery in new_delivery_list:
          new_delivery.confirm()

      LOG('propagateResourceToSimulation, new_delivery_list',0,new_delivery_list)
1089
      # And merge into us
1090 1091 1092 1093 1094 1095
      if len(new_delivery_list)>0:
        list_to_merge = [self]
        list_to_merge.extend(new_delivery_list)
        LOG('propagateResourceToSimulation, list_to_merge:',0,list_to_merge)
        self.portal_simulation.mergeDeliveryList(list_to_merge)

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    security.declareProtected(Permissions.ModifyPortalContent, 'propagateArrowToSimulation')
    def propagateArrowToSimulation(self):
      """
        Propagates any changes on arrow to the simulation 
        
        propagateArrowToSimulation has priority (ie. must be executed before) over updateFromSimulation        
      """
      LOG('propagateArrowToSimulation, ',0,'starting')
      for l in self.contentValues(filter={'portal_type':delivery_movement_type_list}):
        LOG('propagateArrowToSimulation, l.getPhysicalPath()',0,l.getPhysicalPath())
        LOG('propagateArrowToSimulation, l.objectValues()',0,l.objectValues())
        LOG('propagateArrowToSimulation, l.hasCellContent()',0,l.hasCellContent())
        LOG('propagateArrowToSimulation, l.showDict()',0,l.showDict())
        if l.hasCellContent():
          for c in l.contentValues(filter={'portal_type':delivery_movement_type_list}):
            LOG('propagateArrowToSimulation, c.getPhysicalPath()',0,c.getPhysicalPath())
            for s in c.getDeliveryRelatedValueList():
              LOG('propagateArrowToSimulation, s.getPhysicalPath()',0,s.getPhysicalPath())
              LOG('propagateArrowToSimulation, c.getDestination()',0,c.getDestination())
              LOG('propagateArrowToSimulation, s.getDestination()',0,s.getDestination())
              if c.getTargetSource() != s.getSource() \
                or c.getTargetDestination() != s.getDestination() \
                or c.getTargetSourceSection() != s.getSourceSection() \
                or c.getTargetDestinationSection() != s.getDestinationSection():
                  s.setSource(c.getTargetSource())
                  s.setDestination(c.getTargetDestination())
                  s.setSourceSection(c.getTargetSourceSection())
                  s.setDestinationSection(c.getTargetDestinationSection())
                  s.activate().expand()
        else:
          for s in l.getDeliveryRelatedValueList():
            if l.getTargetSource() != s.getSource() \
              or l.getTargetDestination() != s.getDestination() \
              or l.getTargetSourceSection() != s.getSourceSection() \
              or l.getTargetDestinationSection() != s.getDestinationSection():
                s.setSource(l.getTargetSource())
                s.setDestination(l.getTargetDestination())
                s.setSourceSection(l.getTargetSourceSection())
                s.setDestinationSection(l.getTargetDestinationSection())
                s.activate().expand()

    security.declarePrivate( '_edit' )
    def _edit(self, REQUEST=None, force_update = 0, **kw):
      """
      call propagateArrowToSimulation
      """
      XMLObject._edit(self,REQUEST=REQUEST,force_update=force_update,**kw)
      #self.propagateArrowToSimulation()
      # We must expand our applied rule only if not confirmed
      #if self.getSimulationState() in planned_order_state:
      #  self.updateAppliedRule() # This should be implemented with the interaction tool rather than with this hard coding

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    security.declareProtected(Permissions.ModifyPortalContent, 'notifySimulationChange')
    def notifySimulationChange(self):
      """
        WorkflowMethod used to notify the causality workflow that the simulation
        has changed, so we have to check if the delivery is divergent or not
      """
      pass
    notifySimulationChange = WorkflowMethod(notifySimulationChange)

    def updateSimulationDeliveryProperties(self, movement_list = None, delivery = None):
      """
      Set properties delivery_ratio and delivery_error for each simulation movement
      in movement_list (all movements by default), according to this delivery calculated quantity
      """
      if movement_list is None:
        movement_list = delivery.getDeliveryRelatedValueList()
      # First find the calculated quantity
      delivery_quantity = 0
      for m in delivery.getDeliveryRelatedValueList():
        m_quantity = m.getCorrectedQuantity()
        if m_quantity is not None:
          delivery_quantity += m_quantity
      # Then set the properties
      if delivery_quantity != 0:
        for m in movement_list:
          m.setDeliveryRatio(m.getCorrectedQuantity() / delivery_quantity)
          m.setDeliveryError(delivery_quantity * m.getDeliveryRatio() - m.getCorrectedQuantity())
      else:
        for m in movement_list:
          m.setDeliveryError(m.getCorrectedQuantity())
          m.setProfitQuantity(m.getQuantity())
      # Finally, reindex the movements to update their divergence property
      for m in delivery.getDeliveryRelatedValueList():
        m.immediateReindexObject()