ERP5ShopOrderConduit.py 39.2 KB
Newer Older
Kevin Deldycke's avatar
Kevin Deldycke committed
1 2 3 4 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Kevin Deldycke <kevin@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

from Products.ERP5SyncML.Conduit.ERP5Conduit import ERP5Conduit
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions
from Products.CMFCore.utils import getToolByName
from Acquisition import aq_base, aq_inner, aq_chain, aq_acquire

from xml.dom import implementation
from xml.dom.ext import PrettyPrint
from xml.dom import Node

import random
from cStringIO import StringIO

from zLOG import LOG



class ERP5ShopOrderConduit(ERP5Conduit):
  """
  This conduit is used in the synchronisation process of Storever and ERP5 to convert
  a Storever Shop Order to a ERP5 Sale Order.
50
  Don't forget to add this base categories in portal_category :
51
      'hd_size', 'memory_size', 'optical_drive', 'keyboard_layout', 'cpu_type'
Kevin Deldycke's avatar
Kevin Deldycke committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  """


#   TODO: tester ce script sur le serveur de backup (qui semble tre different)


  # Declarative security
  security = ClassSecurityInfo()

  # Initialize the random function
  random.seed()



  security.declareProtected(Permissions.ModifyPortalContent, 'constructContent')
  def constructContent(self, object, object_id, docid, portal_type):
    """
    This is a redefinition of the original ERP5Conduit.constructContent function to
    allow the creation of a ERP5 Sale Order instead of a Storever Shop Order.
    """
    portal_types = getToolByName(object, 'portal_types')
    subobject = None
74
    new_object_id = object_id
Kevin Deldycke's avatar
Kevin Deldycke committed
75 76
    if portal_type == 'Shop Order':
      # The random part of the id can be removed. It's only used for the developpement
77
      #new_object_id = 'storever-' + object_id  + '-' + str(random.randint(1000, 9999))
78 79
      subobject = object.newContent( portal_type = 'Sale Order'
                                   , id          = new_object_id)
80 81 82 83
      # And we must set the destination and destination_section to Nexedi
      nexedi = object.getPortalObject().organisation.nexedi
      subobject.setSourceValue(nexedi)
      subobject.setSourceSectionValue(nexedi)
Kevin Deldycke's avatar
Kevin Deldycke committed
84 85 86
    if portal_type == 'Order Line':
      last_line_num = self.getLastOrderLineNumber(object)
      new_object_id = "storever-" + str(last_line_num + 1) + "-" + object_id
87 88
      subobject = object.newContent( portal_type = 'Sale Order Line'
                                   , id          = new_object_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
89 90 91
    return subobject


92

Kevin Deldycke's avatar
Kevin Deldycke committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
#   # Not needed yet
#   security.declareProtected(Permissions.ModifyPortalContent, 'addWorkflowNode')
#   def addWorkflowNode(self, object, xml, simulate):
#     """
#     This is a redefinition of the original ERP5Conduit.addWorkflowNode function to
#     allow the translation of a Storever Shop Order workflow to a ERP5 Sale Order one.
#     """
#     conflict_list = []
#     status = self.getStatusFromXml(xml)
# #     if status['action'] == 'ship':
# #       status['time']
#     return conflict_list



  security.declarePrivate('dom2str')
  def dom2str(self, xml_root=None):
    """
    This function transform a DOM tree to string.
    This function is only usefull for debugging.
    """
    xml_str = StringIO()
    PrettyPrint(xml_root, xml_str)
    xml_string = xml_str.getvalue()
    LOG('XML output: ', 0, xml_string)
    return xml_string



  security.declarePrivate('str2id')
  def str2id(self, string=None):
    """
    This function transform a string to a safe id.
    It is also used here to create a safe category id from a string.
    """
    out = ''
    if string == None:
      return None
    string = string.lower()
    # We ignore the discontinued information to allow the use of the same category
    # even if the option is discontinued on the storever side
    string = string.replace('discontinued', '')
    string = string.strip()
#     # TODO: manage accent
    for char in string:
      if char == '_' or char.isalnum():
        pass
      elif char.isspace() or char in ('+', '-'):
        char = '_'
      else:
        char = None
      if char != None:
        out += char
    # LOG('Category name output (using str2id) >>>>>>> ', 0, out)
147
    out = out.strip('_')
Kevin Deldycke's avatar
Kevin Deldycke committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    return out



  security.declarePrivate('countrySearch')
  def countrySearch(self, site_root, category_path=None, country=None):
    """
    This recursive function try to find the region category from the name of a country
    """
    if category_path == None:
      portal_categories = getToolByName(site_root, 'portal_categories')
      categories_path = portal_categories.absolute_url(relative=1)
      category_path = categories_path + '/region'
    region_folder = site_root.restrictedTraverse(category_path)
    for region_id in region_folder.objectIds():
      region_path = category_path + '/' + region_id
      splitted_path = region_path.split("/")
      cat_region = "/".join(splitted_path[3:])
      if region_id.lower() == country.lower():
        return cat_region
      find_path = self.countrySearch(site_root, region_path, country)
      if find_path != None:
        return find_path
    return None



  security.declarePrivate('createOrFindProduct')
  def createOrFindProduct(self, erp5_site, erp5_product_id):
    """
    This function try to find a previous product with the same id,
    and create it if the search is unsuccessful
    """
    erp5_site_path = erp5_site.absolute_url(relative=1)
    product_path = erp5_site_path + '/product'
    product_folder = erp5_site.restrictedTraverse(product_path)
184
    product = None
Kevin Deldycke's avatar
Kevin Deldycke committed
185 186 187
    # Try to find a previous product
    for product_id in product_folder.objectIds():
      if product_id == erp5_product_id:
188
        product = erp5_site.restrictedTraverse(erp5_site_path + '/product/' + erp5_product_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
189
    # We have to create a new product
190 191 192 193 194 195 196
    if product is None:
      product = product_folder.newContent( portal_type = 'Product'
                                         , id          = erp5_product_id)
    if len(product.getProductLineValueList())==0:
      #storever_product_line = erp5_site.portal_categories.product_line.storever
      product.setProductLine('storever')
    return product
Kevin Deldycke's avatar
Kevin Deldycke committed
197 198 199 200 201 202 203 204 205



  security.declarePrivate('setProductWorkflow')
  def setProductWorkflow(self, product_object, product_title):
    """
    This function set the validation workflow to indicate if a product
    is discontinued (workflow state = invalidate) or not (workflow state = validate)
    """
206 207 208
    #!!!!!!!!!!!!!!!!!!!!!!!!!!
#     return
    #!!!!!!!!!!!!!!!!!!!!!!!!!!
Kevin Deldycke's avatar
Kevin Deldycke committed
209 210
    action = None
    if hasattr(product_object, 'workflow_history'):
211
      LOG('Info needed from portal_workflow >>>>>>>>> ', 0, '')
Kevin Deldycke's avatar
Kevin Deldycke committed
212
      workflow_state = product_object.portal_workflow.getInfoFor(product_object, 'validation_state')
213
      LOG('workflow_state is >>>>>>>>> ', 0, repr(workflow_state))
Kevin Deldycke's avatar
Kevin Deldycke committed
214
    if product_title.lower().find('discontinued') != -1:
215 216 217 218 219 220 221 222 223 224 225
      #if workflow_state != 'invalidated':
      #  action = 'invalidate_action'
      if workflow_state == 'draft':
        LOG('workflow_state we will validate ', 0, repr(workflow_state))
        #product_object.portal_workflow.doActionFor( product_object
        #                                          , 'validate_action'
        #                                          , wf_id = 'validation_workflow')
        product_object.validate()
        new_workflow_state = product_object.portal_workflow.getInfoFor(product_object, 'validation_state')
        LOG('workflow_state we will new_workflow_state ', 0, repr(new_workflow_state))
      product_object.invalidate()
Kevin Deldycke's avatar
Kevin Deldycke committed
226
    elif workflow_state in ('draft', 'invalidated'):
227 228
      #action = 'validate_action'
      product_object.validate()
229
    LOG('action is >>>>>>>>> ', 0, repr(action))
230 231 232 233 234 235 236 237 238 239
    LOG('product_object.portal_type is >>>>>>>>> ', 0, product_object.getPortalType())
    LOG('productobject.getPhysicalPath is >>>>>>>>> ', 0, product_object.getPhysicalPath())
    LOG('productobject.title is >>>>>>>>> ', 0, product_object.getTitle())
    LOG('productobject.  product_title is >>>>>>>>> ', 0, product_title)
    #if action != None:
    #  if action ==
    #  product_object.invalidate()
      #product_object.portal_workflow.doActionFor( product_object
      #                                          , action
      #                                          , wf_id = 'validation_workflow')
240
    LOG('end of workflow action >>>>>>>>> ', 0, repr(action))
Kevin Deldycke's avatar
Kevin Deldycke committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264



  security.declarePrivate('niceTitle')
  def niceTitle(self, title):
    """
    This function create a nice title without the discontinued information
    """
    splitted_title = title.strip().split(" ")
    nice_title = ''
    for string in splitted_title:
      if string.lower().find('discontinued') == -1:
        nice_title += string + ' '
    return nice_title.strip()



  security.declarePrivate('getLastOrderLineNumber')
  def getLastOrderLineNumber(self, order_object):
    """
    This function give the number of the last Storever Shop Order Line processed
    """
    # Scan existing order line id to get the last order line number
    maximum_order_num = 0
265 266
    LOG('order_object.objectIds',0,order_object.objectIds())
    LOG('order_object.objectIds',0,[x for x in order_object.objectIds()])
Kevin Deldycke's avatar
Kevin Deldycke committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    for order_line_id in order_object.objectIds():
      splitted_line_id = order_line_id.split("-")
      current_line_num = int(splitted_line_id[1])
      if current_line_num > maximum_order_num:
        maximum_order_num = current_line_num
    LOG('getLastOrderLineNumber return  >>>>>>>> ', 0, repr(maximum_order_num))
    return int(maximum_order_num)



#     # Not needed yet because we prefer using my own owner_account_id property
#   security.declareProtected(Permissions.ModifyPortalContent, 'addLocalRoleNode')
#   def addLocalRoleNode(self, object, xml):
#     """
#     """
#     conflict_list = []
#     LOG('object >>>>>>>> ', 0, object)
#     LOG('xml >>>>>>>> ', 0, self.dom2str(xml))
#     return conflict_list



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 323 324 325
  security.declarePrivate('updateObjProperty')
  def updateObjProperty(self, object, property, kw, key):
    """
    This function update the property of an object with a given value stored in a dictionnary. This function help the Conduit to make decision about the synchronisation of values.

    Example of call : self.updateObjProperty(person_object, 'DefaultAddressStreetAddress', kw, 'address')

    Solution (d'apres seb) :
      * machin = getattr (object, methos)
      * machin()
    """
    if kw.has_key(key):
      new_value = kw[key]
      if new_value != None:
        if type(new_value) is type('s'):
          new_value = new_value.title()

        current_value = eval('object.get' + property + '()')
        LOG("I have to run this >>>>>>>> ", 0, 'object.get' + property + '()')
        LOG("current_value >>>>>>>> ", 0, repr(current_value))

        # The current property value is not consistent
        if current_value == None or len(current_value) == 0:
          # Erase the current value with the new one

          LOG("I have to run this to set the property >>>>>>>> " + 'object.set' + str(property) + '(' + str(new_value) + ')' + str(current_value), 0, '')

        # A previous consistent value exist
        elif current_value.strip().lower() != new_value.strip().lower():
          # TODO : We need to choose if we replace it or not, or mix the current with the new one
          LOG('We have to make the fusion of previous address with the current one  >>>>>>>', 0, '')
          return False
        return True
    return False



Kevin Deldycke's avatar
Kevin Deldycke committed
326 327 328 329 330 331 332 333 334 335
  security.declareProtected(Permissions.ModifyPortalContent, 'editDocument')
  def editDocument(self, object=None, **kw):
    """
    This function use the properties of the object to convert a Storever ShopOrder to an ERP5 SaleOrder.
    """
    if object == None:
      return

    LOG('KW >>>>>>>> ', 0, kw)

336 337 338 339
    # This list contain a list of object to check to know if their workflow need to be mofified
    # We store these objects into a list and we will apply modification at the end to avoid mysql lock problem
    workflow_joblist = []

Kevin Deldycke's avatar
Kevin Deldycke committed
340 341 342 343 344 345 346
    # Get the ERP5 root object
    portal_types = getToolByName(object, 'portal_types')
    erp5_site = portal_types.getPortalObject()
    erp5_site_path = erp5_site.absolute_url(relative=1)

    # The object is a ShopOrder
    if kw.has_key('country'):
Sebastien Robin's avatar
Sebastien Robin committed
347 348
      object.setTargetStartDate(kw['target_start_date'])
      object.setTargetStopDate(kw['target_stop_date'])
Kevin Deldycke's avatar
Kevin Deldycke committed
349 350 351 352
      # Find the organisation and the person folder
      person_path = erp5_site_path + '/person'
      person_folder = erp5_site.restrictedTraverse(person_path)
      organisation_path = erp5_site_path + '/organisation'
353
      org_folder = erp5_site.restrictedTraverse(organisation_path)
Kevin Deldycke's avatar
Kevin Deldycke committed
354 355 356 357 358 359 360 361 362 363 364 365 366
      # Find the service folder
      service_path = erp5_site_path + '/service'
      service_folder = erp5_site.restrictedTraverse(service_path)

#       # TODO : if storever-id exist dans ERP5 --> prendre en charge l'update de la facture

      # Get the id of the owner account in storever
      owner_account_id = kw['owner_account_id']
      # Set the id of the owner in ERP5 (the owner could be an Organisation or a Person)
      owner_id = "storever-" + owner_account_id

      # Try to find the identity created for a previous ShopOrder of the same Storever member account
      person_object = None
367
      org_object = None
Kevin Deldycke's avatar
Kevin Deldycke committed
368 369 370 371 372
      for person_id in person_folder.objectIds():
        if person_id == owner_id:
          person_object = erp5_site.restrictedTraverse(erp5_site_path + '/person/' + person_id)
          LOG("Previous person found ! >>>>>>>>",0,repr(person_object))
          break
373
      for organisation_id in org_folder.objectIds():
Kevin Deldycke's avatar
Kevin Deldycke committed
374
        if organisation_id == owner_id:
375 376
          org_object = erp5_site.restrictedTraverse(erp5_site_path + '/organisation/' + organisation_id)
          LOG("Previous organisation found ! >>>>>>>>",0,repr(org_object))
Kevin Deldycke's avatar
Kevin Deldycke committed
377 378 379 380 381 382
          break

      # Define the previous customer structure
      previous_owner_type = ''
      if person_object != None:
        previous_owner_type += 'p'
383
      if org_object != None:
Kevin Deldycke's avatar
Kevin Deldycke committed
384
        previous_owner_type += 'o'
Sebastien Robin's avatar
Sebastien Robin committed
385 386 387 388
        # This is a particular case where the user put 
        # the name of an organisation in his own name
        if not kw.has_key('organisation'):
          kw['organisation'] = org_object.getId()
Kevin Deldycke's avatar
Kevin Deldycke committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
      if len(previous_owner_type) == 0:
        previous_owner_type = None
      LOG("Previous customer structure >>>>>>>>",0,repr(previous_owner_type))

      # Try to know the type of the current storever customer
      owner_type = ''
      if kw.has_key('name') and kw['name'] not in (None, ''):
        owner_type += 'p'
      if kw.has_key('organisation') and kw['organisation'] not in (None, '', 'none'):
        owner_type += 'o'
      if kw.has_key('eu_vat') and kw['eu_vat'] not in (None, '') and owner_type.find('o') == -1:
        owner_type += 'o'
      if len(owner_type) == 0:
        owner_type = None
      LOG("Current customer structure >>>>>>>>",0,repr(owner_type))

#       # TODO : in this part of the script, add the possibility to find an existing
#       # ERP5 person/organisation according to the name of that person/organisation
      # Compare the current representation of the member account with the previous one
      if previous_owner_type != owner_type:
        # There is difference between the two (previous and current) representation of the customer
        # We have to manage the differences to create a unique customer representation
411
        LOG("There is difference between previous and current >>>>>>>>",0,'')
Kevin Deldycke's avatar
Kevin Deldycke committed
412 413 414
        if previous_owner_type == None:
          # No previous customer found, create one
          if owner_type.find('o') != -1:
415 416 417
            org_object = org_folder.newContent( portal_type = 'Organisation'
                                              , id          = owner_id)
            LOG("new organisation created >>>>>>>>",0,repr(org_object))
Kevin Deldycke's avatar
Kevin Deldycke committed
418
          if owner_type.find('p') != -1:
419 420
            person_object = person_folder.newContent( portal_type = 'Person'
                                                    , id          = owner_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
421 422 423 424 425
            LOG("new person created >>>>>>>>",0,repr(person_object))
        else:
          if owner_type == None:
            # Use the previous Structure
            owner_type = previous_owner_type
426
            LOG("Use the previous Structure >>>>>>>>",0,'')
Kevin Deldycke's avatar
Kevin Deldycke committed
427
          else:
428 429
            LOG("We have to convert the structure >>>>>>>>",0,'')
#         #  XXX Be aware of that problem: the invoice for a sale order must look the same (I mean when we generate the pdf version)
Kevin Deldycke's avatar
Kevin Deldycke committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
#           Case to process :
#           previous current
#           o  -->   p
#           o  -->   op
#           p  -->   o
#           op -->   o
#           op -->   p
#           p  -->   op  - in progress

            # The previous customer was detected as a person only
            if previous_owner_type.find('p') != -1 and previous_owner_type.find('o') == -1:
#             Case to process :
#             previous current
#             p  -->   o
#             p  -->   op  - in progress
              # The customer has now an organisation, we have to create this organisation and link the person to
              if owner_type.find('p') != -1 and owner_type.find('o') != -1:
                # Create a new organisation
#                 # TODO : factorise this code with the same above
449 450
                org_object = org_folder.newContent( portal_type = 'Organisation'
                                                  , id          = owner_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
              else:
#                 # TODO : Transform a person to an organisation ? Is it a good idea ?
                pass
            # The previous customer was detected as an organisation only
            elif previous_owner_type.find('p') == -1 and previous_owner_type.find('o') != -1:
#             Case to process :
#             previous current
#             o  -->   p
#             o  -->   op
              pass
            # The previous customer was detected as a person in an organisation
            else:
#             Case to process :
#             previous current
#             op -->   o
#             op -->   p
              pass
      else:
        if previous_owner_type == None or owner_type == None:
          # There is not enough informations to know if the customer is an organisation or
          # a person and there is no previous record
          # By default, we consider the customer as a person, so we have to force to create one
          owner_type = 'p'
474 475
          person_object = person_folder.newContent( portal_type = 'Person'
                                                  , id          = owner_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
476 477 478 479 480
          LOG("Create a person by default  >>>>>>>>",0,repr(person_object))
        else:
          # The structure is the same
          # We only need to be aware of data fusion between the previous and the current representation
          # So we don't need to do something because the information fusion process take place below
481
          LOG("The structure is the same. don't do anything >>>>>>>>",0,'')
Kevin Deldycke's avatar
Kevin Deldycke committed
482 483 484
          pass

      LOG("Person object >>>>>>>>",0,repr(person_object))
485
      LOG("Organisation object >>>>>>>>",0,repr(org_object))
Kevin Deldycke's avatar
Kevin Deldycke committed
486 487 488 489 490 491 492 493 494 495 496 497

      # Copy informations related to the customer in the ERP5 representation of the customer
      # Be carefull because all informations from the storever ShopOrder are optionnals
      if owner_type.find('p') != -1:
        # Link the customer with the Sale Order
        object.setDestination("person/" + owner_id)
        object.setDestinationDecision("person/" + owner_id)

#         # TODO : do the same things for each single information
#         # TODO : before doing something working well in every case, copy the previou value in the comment field to traceback the modification and let me evaluate the solidity of my algorithm
#         # TODO : perhaps it's possible to factorize the code using a generic function
        # Synchronise the street address
498 499 500 501 502 503 504 505 506 507 508 509 510 511

        # Solution (d'apres seb)
        # machin = getattr (object, methos)
        # method(machin)

        machin = self.updateObjProperty(person_object, 'DefaultAddressStreetAddress', kw, 'address')
        LOG("My new updateObjProperty() return >>>>>>>>",0,repr(machin))

#         if kw.has_key('address') and kw['address'] != None:
#           previous_address = person_object.getDefaultAddressStreetAddress()
#           if len(previous_address) == 0:
#             person_object.setDefaultAddressStreetAddress(kw['address'].title())
#           elif previous_address.strip().lower() != kw['address'].strip().lower():
#             LOG('We have to make the fusion of previous address with the current one  >>>>>>>', 0, '')
Kevin Deldycke's avatar
Kevin Deldycke committed
512

Sebastien Robin's avatar
Sebastien Robin committed
513 514 515 516 517 518
        if kw.has_key('city') and kw['city']!=None:
          person_object.setDefaultAddressCity(kw['city'].title())
        if kw.has_key('address') and kw['address'] != None:
          person_object.setDefaultAddressStreetAddress(kw['address'].title())
        if kw.has_key('zipcode') and kw['zipcode']!=None:
          person_object.setDefaultAddressZipCode(kw['zipcode'])
Kevin Deldycke's avatar
Kevin Deldycke committed
519 520 521 522 523 524 525 526
#         # TODO : set the person products interest (storever, etc)
        # Search the country in the region category
        if kw['country'] != None:
          region_path = self.countrySearch(erp5_site, None, kw['country'])
          if region_path != None:
            person_object.setDefaultAddressRegion(region_path)
#           else:
#             # TODO : Ask the user to select an appropriate region
527 528 529 530
        if kw.has_key('email') and kw['email'] != None:
          person_object.setDefaultEmailText(kw['email'])
        if kw.has_key('phone') and kw['phone'] != None:
          person_object.setDefaultTelephoneText(kw['phone'])
Kevin Deldycke's avatar
Kevin Deldycke committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
#         # TODO : Don't work
#         person_object.setDefaultCareerRole("client")
        # Split the name to give at least a required LastName
        # Then the title will be automaticaly created by the Person object from this data
        if kw.has_key('name') and kw['name'] != None:
          splitted_name = kw['name'].strip().split(" ")
          person_object.setLastName((splitted_name[-1]).title())
          if len(splitted_name) > 1:
            person_object.setFirstName((" ".join(splitted_name[:-1])).title())
        else:
          # We have to find a title to have something to show in the RelationField of the SaleOrderForm
          person_object.setTitle(owner_account_id.title())
        # The Person is subordinated to an Organisation ?
        if owner_type.find('o') != -1:
#           # TODO : fix this
#           person_object.setSubordination("organisation/" + owner_id)
547 548
          if kw.has_key('organisation') and kw['organisation'] != None:
            org_object.setTitle(kw['organisation'].title())
Sebastien Robin's avatar
Sebastien Robin committed
549
            org_object.setCorporateName(kw['organisation'].title())
550 551 552 553 554 555 556
          if kw.has_key('eu_vat') and kw['eu_vat'] != None:
            org_object.setEuVatCode(kw['eu_vat'])
          # Test for debug
          if (not (kw.has_key('organisation')) or (kw.has_key('organisation') and kw['organisation'] != None)) and (not (kw.has_key('eu_vat')) or (kw.has_key('eu_vat') and kw['eu_vat'] != None)):
            LOG("AARRGG ! Big conflict detected : this organisation has no title or eu_vat. These properties are primary key to deduced that the storever member account was an organisation >>>>>>>>>>", 0, '')
          org_object.setRole("client")

Kevin Deldycke's avatar
Kevin Deldycke committed
557 558 559 560 561 562
      # The customer is not a person or a person of an organisation, so the customer is an organisation...
      else:
        # Link the customer with the Sale Order
        object.setDestination("organisation/" + owner_id)
        object.setDestinationDecision("organisation/" + owner_id)
        # All informations describe the organisation
Sebastien Robin's avatar
Sebastien Robin committed
563 564 565
        if kw.has_key('organisation') and kw['organisation'] != None:
          org_object.setTitle(kw['organisation'].title())
          org_object.setCorporateName(kw['organisation'].title())
566
        org_object.setRole("client")
Sebastien Robin's avatar
Sebastien Robin committed
567 568 569 570 571 572
        if kw.has_key('eu_vat') and kw['eu_vat'] != None:
          org_object.setEuVatCode(kw['eu_vat'])
        if kw.has_key('address') and kw['address'] != None:
          org_object.setDefaultAddressStreetAddress(kw['address'].title())
        if kw.has_key('city') and kw['city'] != None:
          org_object.setDefaultAddressCity(kw['city'].title())
573
        org_object.setDefaultAddressZipCode(kw['zipcode'])
Kevin Deldycke's avatar
Kevin Deldycke committed
574 575 576 577
        # Search the country in the region category
        if kw['country'] != None:
          region_path = self.countrySearch(erp5_site, None, kw['country'])
          if region_path != None:
578
            org_object.setDefaultAddressRegion(region_path)
Kevin Deldycke's avatar
Kevin Deldycke committed
579 580
#           else:
#             # TODO : Ask the user to select an appropriate region
Sebastien Robin's avatar
Sebastien Robin committed
581 582 583 584
        if kw.has_key('email') and kw['email'] != None:
          org_object.setDefaultEmailText(kw['email'])
        if kw.has_key('phone') and kw['phone'] != None:
          org_object.setDefaultTelephoneText(kw['phone'])
Kevin Deldycke's avatar
Kevin Deldycke committed
585 586 587 588 589

      # Save the billing address in the description, because there is no dedicated place for it
      if kw.has_key('billing_address') and len(kw['billing_address']) > 0:
        object.setDescription("Send the bill to : " + kw['billing_address'])
      # Set the Title because its required
590
      object.setTitle("Storever Order " + str(kw['order_id']))
Kevin Deldycke's avatar
Kevin Deldycke committed
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638

#       # ONLY for information (will be used in the future)
      object.setDescription(str(object.getDescription()) + "\n\nTotal Price (with transport fees) :" + str(kw['total_price']))

      # Add a new orderLine for the shipment
      stor_ship_title = kw['send_fee_title'].strip()
      erp5_ship_title = stor_ship_title + ' Shipment'
      my_shipment_id = 'storever-' + self.str2id(stor_ship_title)

      # Try to find an existing shipment service using several methods
      shipment_id = None
      for service_id in service_folder.objectIds():
        service_object = erp5_site.restrictedTraverse(erp5_site_path + '/service/' + service_id)
        # First method: compare the id with my standard layout
        if service_id.strip() == my_shipment_id:
          shipment_id = my_shipment_id
          LOG("Service found with method 1 ! >>>>>>>>", 0, repr(shipment_id))
          break
        # Second method: use a standard title layout
        if service_object.getTitle().lower().strip() == erp5_ship_title.lower().strip():
          shipment_id = service_id
          LOG("Service found with method 2 ! >>>>>>>>", 0, repr(shipment_id))
          break
        # Third method: compare words
        erp5_ship_id_word_list = self.str2id(service_id).split("_")
        stor_ship_id_word_list = self.str2id(stor_ship_title).split("_")
        erp5_ship_title_word_list = self.str2id(erp5_ship_title).split("_")
        erp5_ship_id_word_list.sort(lambda x, y: cmp(str(x), str(y)))
        stor_ship_id_word_list.sort(lambda x, y: cmp(str(x), str(y)))
        erp5_ship_title_word_list.sort(lambda x, y: cmp(str(x), str(y)))
        if stor_ship_id_word_list in (erp5_ship_id_word_list, erp5_ship_title_word_list):
          shipment_id = service_id
          LOG("Service found with method 3 ! >>>>>>>>", 0, repr(shipment_id))
          break

      # No previous shipment service found, so create a new one
      if shipment_id == None:
#         TODO : implement the code here to follow the comment in the LOG below
        LOG("We have to create the shipping service with this id >>>>>>>>", 0, repr(my_shipment_id))
        # Create a new shipment service
        shipment_id = my_shipment_id

      # Get the object of the shipment service
#       shipment_path = erp5_site_path + '/service/' + shipment_id
#       shipment_object = erp5_site.restrictedTraverse(shipment_path)

      # Create a new order line in this order to represent the shipment service
      ship_order_line_id = "storever-" + shipment_id
639 640
      ship_order_object = object.newContent( portal_type = 'Sale Order Line'
                                           , id          = ship_order_line_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
641 642
      ship_order_object.setQuantity(1.0)
      ship_order_object.setPrice(kw['send_fee'])
643
      ship_order_object.setQuantityUnit('unit')
Kevin Deldycke's avatar
Kevin Deldycke committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
      ship_order_object.setResource("service/" + shipment_id)










    # The object is an OrderLine
    else:
      # Find the product folder
      product_path = erp5_site_path + '/product'
      product_folder = erp5_site.restrictedTraverse(product_path)

      # Find the parent order object
      parent_order_object = object.aq_parent

      # Get the id of the product in storever
      storever_product_id = kw['product_id']

      # Set the id of the product in ERP5
      erp5_product_id = "storever-" + storever_product_id

      # Try to find a previous product or create a new one
      product_object = self.createOrFindProduct(erp5_site, erp5_product_id)

      # Create a nice title (without discontinued) from the product title
      product_title = self.niceTitle(kw['product_title'])

      # Synchronise every data
      product_object.setDescription(kw['product_description'])
      product_object.setTitle(product_title)
#       # TODO : I don't know where to put this value,
#       #   because there is no "delivery days"-like property for a product
#       product_object.setDeliveryDays(kw['product_delivery_days'])
      if kw['product_expiration_date'] != None:
        product_object.setSourceBasePriceValidity(kw['product_expiration_date'])
      product_object.setBasePrice(kw['product_price'])
685
      product_object.setQuantityUnit('unit')
686 687
      # Save the worflow status for later modification
      workflow_joblist.append((product_object, kw['product_title']))
Kevin Deldycke's avatar
Kevin Deldycke committed
688 689 690 691
      # In storever, every option are set as string in the title of the OrderLine
      # This part of code create a list of all options choosen by the customer for this product
      splitted_title = kw['title'].strip().split(":")
      option_list = (":".join(splitted_title[1:])).split("/")
692
      LOG('Customer option list >>>>>> ', 0, repr(option_list))
Kevin Deldycke's avatar
Kevin Deldycke committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707

      # Now, we will find the price of each option
      option_classes = [ kw['product_disk_price']
                       , kw['product_memory_price']
                       , kw['product_option_price']
                       , kw['product_processor_price']
                       ]
      priced_list = {}
      for option_item in option_list:
        option = option_item.strip()
        for option_class in option_classes:
          for option_key in option_class.keys():
            if option == option_key.strip():
              priced_list[option] = option_class[option_key]
#       # TODO : there is no default options in the final priced_list. Is the option 'default' important ?
708
      LOG('Customer option priced list >>>>>>>>> ', 0, repr(priced_list))
Kevin Deldycke's avatar
Kevin Deldycke committed
709 710 711 712 713

      # In ERP5, we have decided to represent some options as variation of a product
      #   and some options as new order line of product
      # Now we will update or create the variation categories related to the initial product
      # Don't forget to add this base categories in portal_category :
714
      #   'hd_size', 'memory_size', 'optical_drive', 'keyboard_layout', 'cpu_type'
Kevin Deldycke's avatar
Kevin Deldycke committed
715 716 717 718 719 720 721 722 723 724 725
      portal_cat = product_object.portal_categories

      # Get all keyboard related options and all optical drive related options
      keyboard_options = {}
      optical_options = {}
      options_prices = kw['product_option_price']
      for option_key in options_prices.keys():
        if option_key.lower().find("keyboard") != -1:
          keyboard_options[option_key] = options_prices[option_key]
        elif option_key.lower().find("cd") != -1 or option_key.lower().find("dvd") != -1:
          optical_options[option_key] = options_prices[option_key]
726 727
      LOG('Product keyboard layout priced list >>>>>>>>> ', 0, repr(keyboard_options))
      LOG('Product optical drive priced list >>>>>>>>> ', 0, repr(optical_options))
Kevin Deldycke's avatar
Kevin Deldycke committed
728 729 730 731 732 733

      # Create a data structure containing all allowed variations
      variant_category_list = [ ('hd_size',        kw['product_disk_price'])
                              , ('memory_size',    kw['product_memory_price'])
                              , ('cpu_type',       kw['product_processor_price'])
                              , ('optical_drive',  optical_options)
734
                              , ('keyboard_layout', keyboard_options)]
Kevin Deldycke's avatar
Kevin Deldycke committed
735 736 737 738 739 740 741 742 743 744 745 746 747 748
      # Create or update every category representing all variantions
      base_cat_list = []
      cat_list = []
      for (cat_base, cat_data) in variant_category_list:
        if len(cat_data) > 0 and portal_cat.resolveCategory(cat_base) != None:
          base_cat_list.append(cat_base)
          for disk_variant_key in cat_data.keys():
            cat_id = self.str2id(disk_variant_key)
            cat_path = cat_base + '/' + cat_id
            cat_list.append(cat_path)
            if portal_cat.resolveCategory(cat_path) == None:
              cat_base_object = portal_cat._getOb(cat_base)
              cat_base_object.newContent ( portal_type = 'Category'
                                         , id          = cat_id)
749
              LOG("New created category >>>>>>>>>>> ", 0, cat_path)
Kevin Deldycke's avatar
Kevin Deldycke committed
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

      # Set the base variation of the product
      product_object.setVariationBaseCategoryList(base_cat_list)

      # Set the variation range of the product
      product_object.setVariationCategoryList(cat_list)

      LOG("cat_list >>>>>>>>>>", 0, repr(cat_list))

      # Now we seperate options and variations of the initial product ordered by the customer
      customer_product_option_list = {}
      customer_product_variation_list = {}
      customer_product_base_variation_list = []
      for option in priced_list:
        option_is_variant = None
        for (cat_base, cat_data) in variant_category_list:
766
          LOG('editDocument, cat_base',0,cat_base)
Kevin Deldycke's avatar
Kevin Deldycke committed
767 768 769 770 771 772 773 774 775 776 777 778 779 780
          base_cat_object = portal_cat.resolveCategory(cat_base)
          cat_list = base_cat_object.getCategoryChildIdItemList()
          for (category, category_bis) in cat_list:
            if self.str2id(option) == category:
              customer_product_variation_list[category] = cat_base + '/' + category
              if cat_base not in customer_product_base_variation_list:
                customer_product_base_variation_list.append(cat_base)
              option_is_variant = 1
              break
          if option_is_variant == 1:
            break
        if option_is_variant == None:
          customer_product_option_list[option] = priced_list[option]
      if len(customer_product_option_list) + len(customer_product_variation_list) != len(priced_list):
781
        LOG('>>>>>>> Wrong repartition of the customer priced list', 200)
Kevin Deldycke's avatar
Kevin Deldycke committed
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
      LOG('>>>>>> Customer product option priced list: ', 0, repr(customer_product_option_list))
      LOG('>>>>>> Customer product variation priced list: ', 0, repr(customer_product_variation_list))
      LOG('>>>>>> Customer product base variation list: ', 0, repr(customer_product_base_variation_list))

      # This variable repesent the sum of every option prices
      options_price_sum = 0.0

      # We have to create a new product for every option not included in the variation system
      for opt_prod_key in customer_product_option_list.keys():
        opt_prod_price = customer_product_option_list[opt_prod_key]

        # Set the id of the optionnal product
        opt_prod_key = self.str2id(opt_prod_key)
        opt_prod_id = "storever-" + opt_prod_key

        # Create the optionnal product or get it if it already exist
        opt_prod_object = self.createOrFindProduct(erp5_site, opt_prod_id)

        # Remove the "discontinued" string in the title
        opt_prod_title = self.niceTitle(opt_prod_key)
        # Set some properties of the optionnal product
        opt_prod_object.setTitle(opt_prod_title.title())
        opt_prod_object.setBasePrice(opt_prod_price)
805
        opt_prod_object.setQuantityUnit('unit')
806 807
        # Save the workflow state changing for later modification
        workflow_joblist.append((opt_prod_object, opt_prod_key))
Kevin Deldycke's avatar
Kevin Deldycke committed
808 809 810

        # Get the last number of order lines
        # This process is needed to distinguish the same option created for two different product
811
        #   and avoid problem when a new Order line is created for an option product already used
Kevin Deldycke's avatar
Kevin Deldycke committed
812 813 814 815
        #   inside the same Sale Order
        last_line_num = self.getLastOrderLineNumber(parent_order_object)
        opt_prod_line_id = "storever-" + str(last_line_num) + "-" + opt_prod_key
        # Create an order line for the product
816 817
        opt_order_line_object = parent_order_object.newContent( portal_type = 'Sale Order Line'
                                                              , id          = opt_prod_line_id)
Kevin Deldycke's avatar
Kevin Deldycke committed
818
        # Set several properties of the new orderLine
819
        opt_order_line_object.setQuantityUnit('unit')
Kevin Deldycke's avatar
Kevin Deldycke committed
820 821
        opt_order_line_object.setPrice(opt_prod_price)
        # There is the same quantity of the base product
Sebastien Robin's avatar
Sebastien Robin committed
822
        opt_order_line_object.setTargetQuantity(kw['quantity'])
Kevin Deldycke's avatar
Kevin Deldycke committed
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
        # Link the Order Line with the product
        opt_order_line_object.setResource("product/" + opt_prod_id)

        # Calcul the sum of option prices
        options_price_sum += float(opt_prod_price)

#       # TODO: don't forget to manage the VAT values

#      TODO: # Try to find a previous OrderLine to update
#       line_object = None
#       for product_id in product_folder.objectIds():
#         if product_id == erp5_product_id:
#           product_object = erp5_site.restrictedTraverse(erp5_site_path + '/product/' + erp5_product_id)
#           break

      # Migrate the line informations
Sebastien Robin's avatar
Sebastien Robin committed
839
      object.setTargetQuantity(kw['quantity'])
Kevin Deldycke's avatar
Kevin Deldycke committed
840
      object.setDescription(kw['title'])
841
      object.setQuantityUnit('unit')
Kevin Deldycke's avatar
Kevin Deldycke committed
842 843 844 845 846 847 848 849 850 851 852 853

      # Substract to the product price the sum of options prices
      initial_prod_price = float(kw['price']) - options_price_sum
      object.setPrice(initial_prod_price)

      # Link the Order Line with the product
      object.setResource("product/" + erp5_product_id)

      # Set variations of the order line product choosen by the customer
      category_list = []
      for variation_key in customer_product_variation_list.keys():
        category_list.append(customer_product_variation_list[variation_key])
854
      #object.setVariationBaseCategoryList(customer_product_base_variation_list)
Kevin Deldycke's avatar
Kevin Deldycke committed
855
#       # TODO : fix this
856 857 858 859 860
      #object.setVariationCategoryList(category_list)
      previous_category_list = object.getCategoryList()
      LOG('ERP5ShopOrderConduit, previous_category_list',0,previous_category_list)
      category_list = list(previous_category_list) + list(category_list)
      object.setCategoryList(category_list)
Kevin Deldycke's avatar
Kevin Deldycke committed
861

862 863 864
    # Do all workflow change at the end
    LOG("enter workflow loop >>>>>>>>",0,repr(workflow_joblist))
    for (object, object_title) in workflow_joblist:
865
      LOG("Workflow to change :: >>>>>>>>",0,repr((object, object_title)))
866 867 868
      self.setProductWorkflow(object, object_title)

    return