Inventory.py 14.6 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
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from AccessControl import ClassSecurityInfo
30
from Products.ERP5Type import Permissions, PropertySheet
31
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
32
from Products.ERP5.Document.NoIndexStockInventory import NoIndexStockInventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
33

34
class Inventory(NoIndexStockInventory):
Romain Courteaud's avatar
Romain Courteaud committed
35 36 37 38 39 40
  """
  Inventory
  """
  # CMF Type Definition
  meta_type = 'ERP5 Inventory'
  portal_type = 'Inventory'
41

Romain Courteaud's avatar
Romain Courteaud committed
42 43 44 45 46
  def immediateReindexObject(self, temp_constructor=None, **kw):
    """
    Rewrite reindexObject so that we can insert lines in stock table
    which will be equal to the difference between stock values for
    resource in the inventory and the one before the date of this inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
47

Romain Courteaud's avatar
Romain Courteaud committed
48 49 50 51
    temp_constructor is used in some particular cases where we want
    to have our own temp object constructor, this is usefull if we
    want to use some classes with some particular methods
    """
52
    portal = self.getPortalObject()
53 54 55
    sql_catalog_id = kw.pop("sql_catalog_id", None)
    disable_archive = kw.pop("disable_archive", 0)

56
    state = self.getSimulationState()
57
    # we need reindex when cancelling inventories
58 59
    if (state in portal.getPortalDraftOrderStateList() and
        state != 'cancelled'):
60 61 62
      # this prevent from trying to calculate stock
      # with not all properties defined and thus making
      # request with no condition in mysql
63
      immediate_reindex_archive = sql_catalog_id is not None
64 65 66 67
      portal.portal_catalog.catalogObjectList([self],
        sql_catalog_id = sql_catalog_id,
        disable_archive=disable_archive,
        immediate_reindex_archive=immediate_reindex_archive)
68
      return
69

Romain Courteaud's avatar
Romain Courteaud committed
70 71
    connection_id = None
    if sql_catalog_id is not None:
72
      # try to get connection used in the catalog
73
      catalog = portal.portal_catalog[sql_catalog_id]
74
      connection_id = catalog.getConnectionId()
75

76 77
    default_inventory_calculation_list = ({ "inventory_params" : {"section": self.getDestinationSection(),
                                                                  "node" : self.getDestination(),
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
                                                                          "group_by_sub_variation" : 1,
                                                                          "group_by_variation" : 1,
                                                                          "group_by_resource" : 1,
                                                                          },
                                            "list_method" : "getMovementList",
                                            "first_level" : ({'key' : 'resource_relative_url',
                                                             'getter' : 'getResource',
                                                              'setter' : ("appendToCategoryList", "resource")},
                                                             {'key' : 'variation_text',
                                                              'getter' : 'getVariationText',
                                                              'setter' : "splitAndExtendToCategoryList"},
                                                             ),
                                            "second_level" : ({'key' : 'sub_variation_text',
                                                               'getter' : 'getSubVariationText',
                                                               'setter' : "splitAndExtendToCategoryList"},
                                                              ),
                                            },
                                          )

97
    method = self._getTypeBasedMethod('getDefaultInventoryCalculationList')
98 99
    if method is not None:
      default_inventory_calculation_list = method()
100

101

Romain Courteaud's avatar
Romain Courteaud committed
102
    if temp_constructor is None:
103
      from Products.ERP5Type.Document import newTempMovement as temp_constructor
104 105 106 107
    stop_date = self.getStopDate()

    stock_object_list = []
    stock_append = stock_object_list.append
108 109
    to_delete_stock_uid_set = set()
    to_delete_stock_uid_add = to_delete_stock_uid_set.add
110 111 112

    for inventory_calculation_dict in default_inventory_calculation_list:

113
      # build a dict containing all inventory for this node
114 115
      # group by resource/variation and then subvariation
      current_inventory_list = \
116
          portal.portal_simulation.getCurrentInventoryList(
117 118 119 120 121 122 123
                  to_date=stop_date,
                  connection_id=connection_id,
                  **inventory_calculation_dict['inventory_params']
          )
      current_inventory_dict = {}
      current_inventory_key_id_list = [x["key"] for x in inventory_calculation_dict['first_level']]
      for line in current_inventory_list:
Aurel's avatar
Aurel committed
124 125 126 127
        current_inventory_key = [line[x] for x in current_inventory_key_id_list]
        for x in xrange(len(current_inventory_key)):
          if current_inventory_key[x] is None:
            current_inventory_key[x] = ""
128
        current_inventory_key = tuple(current_inventory_key)
129 130 131 132 133 134 135 136 137 138 139 140

        if inventory_calculation_dict.has_key("second_level"):
          # two level of variation
          try:
            current_inventory_by_sub_variation = \
                current_inventory_dict[current_inventory_key]
          except KeyError:
            current_inventory_by_sub_variation = \
                current_inventory_dict[current_inventory_key] = {}
          second_level_key_id_list = [x['key'] for x in inventory_calculation_dict['second_level']]
          second_level_key = tuple([line[x] for x in second_level_key_id_list])
          current_inventory_by_sub_variation[second_level_key] = line['total_quantity']
Romain Courteaud's avatar
Romain Courteaud committed
141
        else:
142 143 144 145
          # only one level of variation
          current_inventory_dict[current_inventory_key] = line['total_quantity']

      # Browse all movements on inventory and create diff line when necessary
146 147 148 149
      if self.isFullInventory():
        not_used_inventory_dict = current_inventory_dict
      else:
        not_used_inventory_dict = {}
150
      inventory_id = self.getId()
151 152
      list_method = inventory_calculation_dict['list_method']
      method = getattr(self, list_method)
153 154 155 156 157 158 159

      __order_id_counter_list = [0]
      def getOrderIdCounter():
        value = __order_id_counter_list[0]
        __order_id_counter_list[0] = value + 1
        return value

160
      for movement in method():
161 162
        # Make sure we remove any any value
        to_delete_stock_uid_add(movement.getUid())
163
        if movement.getResourceValue() is not None and \
164
            movement.getInventoriatedQuantity() not in (None, ''):
165

166
          movement_quantity = movement.getInventoriatedQuantity()
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
          # construct key to retrieve inventory into dict
          getter_list = [x['getter'] for x in inventory_calculation_dict['first_level']]
          key_list = []
          for getter in getter_list:
            method = getattr(movement, getter, None)
            if method is not None:
              key_list.append(method())
          inventory_value = current_inventory_dict.get(tuple(key_list), 0)
          second_key_list = []
          if inventory_calculation_dict.has_key('second_level'):
            if inventory_value == 0:
              inventory_value = {}
            # two level
            second_getter_list = [x['getter'] for x in inventory_calculation_dict['second_level']]
            for getter in second_getter_list:
              method = getattr(movement, getter, None)
              if method is not None:
                second_key_list.append(method())
              second_key_list = tuple(second_key_list)
              if inventory_value.has_key(second_key_list):
                total_quantity = inventory_value.pop(second_key_list)
188
                # Put remaining subvariation in a dict to know which one
189 190 191 192 193 194
                # to removed at end
                not_used_inventory_dict[tuple(key_list)] = inventory_value
                diff_quantity = movement_quantity - total_quantity
              else:
                # Inventory for new resource/variation/sub_variation
                diff_quantity = movement_quantity
195
                # Put remaining subvariation in a dict to know which one
196 197
                # to removed at end
                not_used_inventory_dict[tuple(key_list)] = inventory_value
198
          else:
199 200
            # we got the quantity from first level key
            diff_quantity = movement_quantity - inventory_value
201

202 203
          # Create tmp movement
          kwd = {'uid': movement.getUid(),
204 205 206 207
                 'start_date': stop_date,
                 'order_id': getOrderIdCounter(),
                 'mirror_order_id':getOrderIdCounter()
                 }
208 209
          temp_delivery_line = temp_constructor(self,
                                                inventory_id)
210

211 212 213 214 215
          # set category on it only if quantity not null
          # thus line with same uid will be deleted but we
          # don't insert line with null quantity as we test
          # some categories like resource/destination/source
          # before insert but not before delete
216 217
          if diff_quantity != 0:
            kwd['quantity'] = diff_quantity
218
            category_list = self.getCategoryList()
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

            setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']]
            if inventory_calculation_dict.has_key("second_level"):
              setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']])
            value_list = list(key_list) + list(second_key_list)
            for x in xrange(len(setter_list)):
              value = value_list[x]
              setter = setter_list[x]
              base_category = ""
              if isinstance(setter, (tuple, list)):
                base_category = setter[1]
                setter = setter[0]
              method = getattr(self, setter, None)
              if method is not None:
                method(category_list, value, base_category)

            kwd['category_list'] = category_list
236 237
          temp_delivery_line.edit(**kwd)
          stock_append(temp_delivery_line)
238

239
      # Now create line to remove some subvariation text not present
240 241 242 243 244 245
      # in new inventory
      if len(not_used_inventory_dict):
        inventory_uid = self.getUid()
        for first_level_key in not_used_inventory_dict.keys():
          inventory_value = \
              not_used_inventory_dict[tuple(first_level_key)]
246
          # XXX-Aurel : this code does not work with only one level of variation
247 248 249 250
          for second_level_key in inventory_value.keys():
            diff_quantity = - inventory_value[tuple(second_level_key)]

            kwd = {'uid': inventory_uid,
251 252 253 254
                   'start_date': stop_date,
                   'order_id': getOrderIdCounter(),
                   'mirror_order_id':getOrderIdCounter()
                   }
255 256 257 258 259

            # create the tmp line and set category on it
            temp_delivery_line = temp_constructor(self,
                                                  inventory_id)
            kwd['quantity'] = diff_quantity
260
            category_list = self.getCategoryList()
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

            setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']]
            if inventory_calculation_dict.has_key("second_level"):
              setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']])
            value_list = list(first_level_key) + list(second_level_key)
            for x in xrange(len(setter_list)):
              value = value_list[x]
              setter = setter_list[x]
              base_category = ""
              if isinstance(setter, (tuple, list)):
                base_category = setter[1]
                setter = setter[0]
              method = getattr(self, setter, None)
              if method is not None:
                method(category_list, value, base_category)

            kwd['category_list'] = category_list
            temp_delivery_line.edit(**kwd)
            stock_append(temp_delivery_line)
280

Romain Courteaud's avatar
Romain Courteaud committed
281
    # Reindex objects
282
    immediate_reindex_archive = sql_catalog_id is not None
283 284 285 286
    portal.portal_catalog.catalogObjectList([self],
      sql_catalog_id = sql_catalog_id,
      disable_archive=disable_archive,
      immediate_reindex_archive=immediate_reindex_archive)
287

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    # Do deletion for everything first, even if there is no need to apply correction,
    # in case we need to remove previous corrections
    to_delete_stock_uid_add(self.getUid())
    to_delete_list = []
    to_delete_list_append = to_delete_list.append
    for uid in to_delete_stock_uid_set:
      temp_line = temp_constructor(self, inventory_id)
      temp_line.setUid(uid)
      to_delete_list_append(temp_line)
    catalog_kw = dict(sql_catalog_id=sql_catalog_id,
         disable_cache=1, check_uid=0, disable_archive=disable_archive,
         immediate_reindex_archive=immediate_reindex_archive)
    method_id_list = ['z0_uncatalog_stock']
    if portal.portal_catalog.getSQLCatalog(sql_catalog_id) \
       .hasObject('SQLCatalog_trimInventoryCacheOnCatalog'):
      method_id_list.append('SQLCatalog_trimInventoryCacheOnCatalog')
    # Delete existing stock records and old inventory_cache first.
    portal.portal_catalog.catalogObjectList(
         to_delete_list[:], method_id_list=method_id_list, **catalog_kw)
307
    if stock_object_list:
308
      # Then insert new records without delete.
309
      portal.portal_catalog.catalogObjectList(
310 311
           stock_object_list[:], method_id_list=('z_catalog_stock_list_without_delete_for_inventory_virtual_movement', ),
           **catalog_kw)