Merge lp:~red15/magentoerpconnect/fix-magentoerp-logging into lp:magentoerpconnect/oerp6.1-oldstable

Proposed by Niels Huylebroeck
Status: Merged
Merge reported by: Guewen Baconnier @ Camptocamp
Merged at revision: not available
Proposed branch: lp:~red15/magentoerpconnect/fix-magentoerp-logging
Merge into: lp:magentoerpconnect/oerp6.1-oldstable
Diff against target: 965 lines (+135/-137)
6 files modified
magentoerpconnect/magerp_core.py (+4/-5)
magentoerpconnect/magerp_osv.py (+30/-30)
magentoerpconnect/product.py (+53/-55)
magentoerpconnect/product_images.py (+14/-14)
magentoerpconnect/sale.py (+25/-24)
magentoerpconnect/stock.py (+9/-9)
To merge this branch: bzr merge lp:~red15/magentoerpconnect/fix-magentoerp-logging
Reviewer Review Type Date Requested Status
Guewen Baconnier @ Camptocamp Approve
Review via email: mp+107348@code.launchpad.net

Description of the change

Replaced all logging calls for modules contained in the magentoerp branch, there are more modules that need fixing but they would have to be pulled into this branch first I suppose?

To post a comment you must log in.
Revision history for this message
Guewen Baconnier @ Camptocamp (gbaconnier-c2c) wrote :

Thanks for your contribution !
It's merged

review: Approve
634. By Niels Huylebroeck

[MRG] Replaced all netsvc.Logger() calls with the appropriate logging.getLogger() and also adjusted the logging calls themselves.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'magentoerpconnect/magerp_core.py'
--- magentoerpconnect/magerp_core.py 2012-05-15 11:49:38 +0000
+++ magentoerpconnect/magerp_core.py 2012-05-25 09:04:23 +0000
@@ -25,7 +25,7 @@
25from osv import osv, fields25from osv import osv, fields
26import magerp_osv26import magerp_osv
27import pooler27import pooler
28import netsvc28import logging
29import base64, urllib29import base64, urllib
30from magerp_osv import Connection30from magerp_osv import Connection
31import tools31import tools
@@ -67,7 +67,7 @@
67 'magento_referential': fields.function(_is_magento_referential, type="boolean", method=True, string="Magento Referential"),67 'magento_referential': fields.function(_is_magento_referential, type="boolean", method=True, string="Magento Referential"),
68 'last_imported_product_id': fields.integer('Last Imported Product Id', help="Product are imported one by one. This is the magento id of the last product imported. If you clear it all product will be imported"),68 'last_imported_product_id': fields.integer('Last Imported Product Id', help="Product are imported one by one. This is the magento id of the last product imported. If you clear it all product will be imported"),
69 'last_imported_partner_id': fields.integer('Last Imported Partner Id', help="Partners are imported one by one. This is the magento id of the last partner imported. If you clear it all partners will be imported"),69 'last_imported_partner_id': fields.integer('Last Imported Partner Id', help="Partners are imported one by one. This is the magento id of the last partner imported. If you clear it all partners will be imported"),
70 'import_all_attributs': fields.boolean('Import all attributs', help="If the option is uncheck only the attributs that doesn't exist in OpenERP will be imported"), 70 'import_all_attributs': fields.boolean('Import all attributs', help="If the option is uncheck only the attributs that doesn't exist in OpenERP will be imported"),
71 'import_image_with_product': fields.boolean('With image', help="If the option is check the product's image and the product will be imported at the same time and so the step '7-import images' is not needed"),71 'import_image_with_product': fields.boolean('With image', help="If the option is check the product's image and the product will be imported at the same time and so the step '7-import images' is not needed"),
72 'import_links_with_product': fields.boolean('With links', help="If the option is check the product's links (Up-Sell, Cross-Sell, Related) and the product will be imported at the same time and so the step '8-import links' is not needed"),72 'import_links_with_product': fields.boolean('With links', help="If the option is check the product's links (Up-Sell, Cross-Sell, Related) and the product will be imported at the same time and so the step '8-import links' is not needed"),
73 }73 }
@@ -123,7 +123,7 @@
123 def sync_attribs(self, cr, uid, ids, context=None):123 def sync_attribs(self, cr, uid, ids, context=None):
124 attr_obj = self.pool.get('magerp.product_attributes')124 attr_obj = self.pool.get('magerp.product_attributes')
125 attr_set_obj = self.pool.get('magerp.product_attribute_set')125 attr_set_obj = self.pool.get('magerp.product_attribute_set')
126 logger = netsvc.Logger()126 logger = logging.getLogger('ext synchro')
127 for referential in self.browse(cr, uid, ids, context=context):127 for referential in self.browse(cr, uid, ids, context=context):
128 attr_conn = referential.external_connection(DEBUG, context=context)128 attr_conn = referential.external_connection(DEBUG, context=context)
129 attrib_set_ids = attr_set_obj.search(cr, uid, [('referential_id', '=', referential.id)])129 attrib_set_ids = attr_set_obj.search(cr, uid, [('referential_id', '=', referential.id)])
@@ -146,7 +146,7 @@
146 attributes_imported.append(ext_id)146 attributes_imported.append(ext_id)
147 attr_obj.ext_import(import_cr, uid, [attribut], referential.id, defaults={'referential_id':referential.id}, context={'referential_id':referential.id})147 attr_obj.ext_import(import_cr, uid, [attribut], referential.id, defaults={'referential_id':referential.id}, context={'referential_id':referential.id})
148 import_cr.commit()148 import_cr.commit()
149 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "All attributs for the attributs set id %s was succesfully imported" %(attr_set_id))149 logger.info("All attributs for the attributs set id %s was succesfully imported", attr_set_id)
150 #Relate attribute sets & attributes150 #Relate attribute sets & attributes
151 mage_inp = {}151 mage_inp = {}
152 #Pass in {attribute_set_id:{attributes},attribute_set_id2:{attributes}}152 #Pass in {attribute_set_id:{attributes},attribute_set_id2:{attributes}}
@@ -263,7 +263,6 @@
263 return conn.call('catalog_product_link.types')263 return conn.call('catalog_product_link.types')
264264
265 def sync_images(self, cr, uid, ids, context=None):265 def sync_images(self, cr, uid, ids, context=None):
266 logger = netsvc.Logger()
267 product_obj = self.pool.get('product.product')266 product_obj = self.pool.get('product.product')
268 image_obj = self.pool.get('product.images')267 image_obj = self.pool.get('product.images')
269 import_cr = pooler.get_db(cr.dbname).cursor()268 import_cr = pooler.get_db(cr.dbname).cursor()
270269
=== modified file 'magentoerpconnect/magerp_osv.py'
--- magentoerpconnect/magerp_osv.py 2012-05-24 06:57:34 +0000
+++ magentoerpconnect/magerp_osv.py 2012-05-25 09:04:23 +0000
@@ -24,7 +24,7 @@
24import time24import time
25import datetime25import datetime
26import xmlrpclib26import xmlrpclib
27import netsvc27import logging
28import urllib228import urllib2
29import base6429import base64
30import pooler30import pooler
@@ -39,7 +39,7 @@
39 def __init__(self, location, username, password, debug=False):39 def __init__(self, location, username, password, debug=False):
40 #Append / if not there40 #Append / if not there
41 if not location[-1] == '/':41 if not location[-1] == '/':
42 location += '/' 42 location += '/'
43 self.corelocation = location43 self.corelocation = location
44 #Please do not remove the str indeed xmlrpc lib require a string for the location44 #Please do not remove the str indeed xmlrpc lib require a string for the location
45 #if an unicode is send it will raise you an error45 #if an unicode is send it will raise you an error
@@ -48,33 +48,33 @@
48 self.password = password48 self.password = password
49 self.debug = False49 self.debug = False
50 self.result = {}50 self.result = {}
51 self.logger = netsvc.Logger()51 self.logger = logging.getLogger('Connection(%s)' % self.location)
5252
53 53
54 def connect(self):54 def connect(self):
55 if not self.location[-1] == '/':55 if not self.location[-1] == '/':
56 self.location += '/'56 self.location += '/'
57 if self.debug:57 if self.debug:
58 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Attempting connection with Settings:%s,%s,%s") % (self.location, self.username, self.password))58 self.logger.info(_("Attempting connection with Settings:%s,%s,%s"), self.location, self.username, self.password)
59 self.ser = xmlrpclib.ServerProxy(self.location)59 self.ser = xmlrpclib.ServerProxy(self.location)
60 for sleep_time in [1, 3, 6]:60 for sleep_time in [1, 3, 6]:
61 try:61 try:
62 self.session = self.ser.login(self.username, self.password)62 self.session = self.ser.login(self.username, self.password)
63 if self.debug:63 if self.debug:
64 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Login Successful"))64 self.logger.info(_("Login Successful"))
65 return True65 return True
66 except IOError, e:66 except IOError, e:
67 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Error in connecting:%s") % (e))67 self.logger.error(_("Error in connecting:%s"), e, exc_info=True)
68 self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_WARNING, _("Webservice Failure, sleeping %s second before next attempt") % (sleep_time))68 self.logger.warn(_("Webservice Failure, sleeping %s second before next attempt"), sleep_time)
69 time.sleep(sleep_time)69 time.sleep(sleep_time)
70 except Exception,e:70 except Exception,e:
71 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Error in connecting:%s") % (e))71 self.logger.error(_("Error in connecting:%s"), e, exc_info=True)
72 self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_WARNING, _("Webservice Failure, sleeping %s second before next attempt") % (sleep_time))72 self.logger.warn(_("Webservice Failure, sleeping %s second before next attempt"), sleep_time)
73 time.sleep(sleep_time) 73 time.sleep(sleep_time)
74 raise osv.except_osv(_('User Error'), _('Error when try to connect to magento, are your sure that your login is right? Did openerp can access to your magento?'))74 raise osv.except_osv(_('User Error'), _('Error connecting to magento, are your sure that your login is right? Did you configure API user in magento?'))
7575
76 76
77 def call(self, method, *arguments): 77 def call(self, method, *arguments):
78 if arguments:78 if arguments:
79 arguments = list(arguments)[0]79 arguments = list(arguments)[0]
80 else:80 else:
@@ -82,18 +82,18 @@
82 for sleep_time in [1, 3, 6]:82 for sleep_time in [1, 3, 6]:
83 try:83 try:
84 if self.debug:84 if self.debug:
85 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Calling Method:%s,Arguments:%s") % (method, arguments))85 self.logger.info(_("Calling Method:%s,Arguments:%s"), method, arguments)
86 res = self.ser.call(self.session, method, arguments)86 res = self.ser.call(self.session, method, arguments)
87 if self.debug:87 if self.debug:
88 if method=='catalog_product.list':88 if method=='catalog_product.list':
89 # the response of the method catalog_product.list can be very very long so it's better to see it only if debug log is activate89 # the response of the method catalog_product.list can be very very long so it's better to see it only if debug log is activate
90 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_DEBUG, _("Query Returned:%s") % (res))90 self.logger.debug(_("Query Returned:%s"), res)
91 else:91 else:
92 self.logger.notifyChannel(_("Magento Connection"), netsvc.LOG_INFO, _("Query Returned:%s") % (res))92 self.logger.info(_("Query Returned:%s"), res)
93 return res93 return res
94 except IOError, e:94 except IOError, e:
95 self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_ERROR, _("Method: %s\nArguments:%s\nError:%s") % (method, arguments, e))95 self.logger.error(_("Method: %s\nArguments:%s\nError:%s"), method, arguments, e, exc_info=True)
96 self.logger.notifyChannel(_("Magento Call"), netsvc.LOG_WARNING, _("Webservice Failure, sleeping %s second before next attempt") % (sleep_time))96 self.logger.warn(_("Webservice Failure, sleeping %s second before next attempt"), sleep_time)
97 time.sleep(sleep_time)97 time.sleep(sleep_time)
98 raise98 raise
9999
@@ -118,7 +118,7 @@
118 _DELETE_METHOD = False118 _DELETE_METHOD = False
119 _mapping = {}119 _mapping = {}
120 DEBUG = False120 DEBUG = False
121 121
122 #TODO deprecated, remove use122 #TODO deprecated, remove use
123 def mage_to_oe(self, cr, uid, mageid, instance, *arguments):123 def mage_to_oe(self, cr, uid, mageid, instance, *arguments):
124 """given a record id in the Magento referential, returns a tuple (id, name) with the id in the OpenERP referential; Magento instance wise"""124 """given a record id in the Magento referential, returns a tuple (id, name) with the id in the OpenERP referential; Magento instance wise"""
@@ -143,7 +143,7 @@
143 read = self.read(cr, uid, oeid, [self._rec_name])143 read = self.read(cr, uid, oeid, [self._rec_name])
144 return (read[0]['id'], read[0][self._rec_name])144 return (read[0]['id'], read[0][self._rec_name])
145 return False145 return False
146 146
147 #TODO deprecated, remove use147 #TODO deprecated, remove use
148 def sync_import(self, cr, uid, magento_records, instance, debug=False, defaults=None, *attrs):148 def sync_import(self, cr, uid, magento_records, instance, debug=False, defaults=None, *attrs):
149149
@@ -178,7 +178,7 @@
178 'temp_vars':{},178 'temp_vars':{},
179 'mage2oe_filters':mage2oe_filters179 'mage2oe_filters':mage2oe_filters
180 }180 }
181 181
182 #now properly mapp known Magento attributes to OpenERP entity columns:182 #now properly mapp known Magento attributes to OpenERP entity columns:
183 for each_valid_key in self._mapping:183 for each_valid_key in self._mapping:
184 if each_valid_key in magento_record.keys():184 if each_valid_key in magento_record.keys():
@@ -216,7 +216,7 @@
216 self.record_save(cr, uid, rec_id, vals, defaults)216 self.record_save(cr, uid, rec_id, vals, defaults)
217 else:217 else:
218 self.record_save(cr, uid, rec_id, vals, defaults)218 self.record_save(cr, uid, rec_id, vals, defaults)
219 219
220 def record_save(self, cr, uid, rec_id, vals, defaults):220 def record_save(self, cr, uid, rec_id, vals, defaults):
221 if defaults:221 if defaults:
222 for key in defaults.keys():222 for key in defaults.keys():
@@ -227,7 +227,7 @@
227 else:227 else:
228 #Record is not there, create it228 #Record is not there, create it
229 self.create(cr, uid, vals,)229 self.create(cr, uid, vals,)
230 230
231 def cast_string(self, subject):231 def cast_string(self, subject):
232 """This function will convert string objects to the data type required. Example "0"/"1" to boolean conversion"""232 """This function will convert string objects to the data type required. Example "0"/"1" to boolean conversion"""
233 for key in subject.keys():233 for key in subject.keys():
@@ -237,7 +237,7 @@
237 else:237 else:
238 subject[key] = True238 subject[key] = True
239 return subject239 return subject
240 240
241 def mage_import_base(self,cr,uid,conn, external_referential_id, defaults=None, context=None):241 def mage_import_base(self,cr,uid,conn, external_referential_id, defaults=None, context=None):
242 if context is None:242 if context is None:
243 context = {}243 context = {}
@@ -259,7 +259,7 @@
259 list_method = self.pool.get('external.mapping').read(cr,uid,mapping_id[0],['external_list_method']).get('external_list_method',False)259 list_method = self.pool.get('external.mapping').read(cr,uid,mapping_id[0],['external_list_method']).get('external_list_method',False)
260 if list_method:260 if list_method:
261 data = conn.call(list_method, context['ids_or_filter'])261 data = conn.call(list_method, context['ids_or_filter'])
262 262
263 #it may happen that list method doesn't provide enough information, forcing us to use get_method on each record (case for sale orders)263 #it may happen that list method doesn't provide enough information, forcing us to use get_method on each record (case for sale orders)
264 if context.get('one_by_one', False):264 if context.get('one_by_one', False):
265 self.mage_import_one_by_one(cr, uid, conn, external_referential_id, mapping_id[0], data, defaults, context)265 self.mage_import_one_by_one(cr, uid, conn, external_referential_id, mapping_id[0], data, defaults, context)
@@ -337,7 +337,7 @@
337 self.sync_import(cr, uid, magento_records, instance, debug, defaults)337 self.sync_import(cr, uid, magento_records, instance, debug, defaults)
338 else:338 else:
339 raise osv.except_osv(_('Undefined List method !'), _("list method is undefined for this object!"))339 raise osv.except_osv(_('Undefined List method !'), _("list method is undefined for this object!"))
340 340
341 #TODO deprecated, remove use341 #TODO deprecated, remove use
342 def get_all_mage_ids(self, cr, uid, ids, instance=False):342 def get_all_mage_ids(self, cr, uid, ids, instance=False):
343 search_param = []343 search_param = []
@@ -350,4 +350,4 @@
350 for each in reads:350 for each in reads:
351 mageids.append(each[self._MAGE_FIELD])351 mageids.append(each[self._MAGE_FIELD])
352 return mageids352 return mageids
353 353
354354
=== modified file 'magentoerpconnect/product.py'
--- magentoerpconnect/product.py 2012-05-16 14:02:43 +0000
+++ magentoerpconnect/product.py 2012-05-25 09:04:23 +0000
@@ -28,7 +28,7 @@
28import pooler28import pooler
29import magerp_osv29import magerp_osv
30from tools.translate import _30from tools.translate import _
31import netsvc31import logging
32import unicodedata32import unicodedata
33import base64, urllib33import base64, urllib
34import os34import os
@@ -293,7 +293,7 @@
293293
294 def init(self, cr):294 def init(self, cr):
295 """ Replace product_product by product.product295 """ Replace product_product by product.product
296 and product_template by product.template for 296 and product_template by product.template for
297 consistency with model names"""297 consistency with model names"""
298 cr.execute("UPDATE magerp_product_attributes SET based_on = REPLACE(based_on, '_', '.')")298 cr.execute("UPDATE magerp_product_attributes SET based_on = REPLACE(based_on, '_', '.')")
299 cr.execute("UPDATE magerp_product_attributes SET based_on = 'product.template' WHERE based_on IS NULL")299 cr.execute("UPDATE magerp_product_attributes SET based_on = 'product.template' WHERE based_on IS NULL")
@@ -561,12 +561,11 @@
561 " result = [('%(attribute_code)s', [option.value for option in options])]") % \561 " result = [('%(attribute_code)s', [option.value for option in options])]") % \
562 ({'field_name': field_name, 'attribute_code': attribute.attribute_code})562 ({'field_name': field_name, 'attribute_code': attribute.attribute_code})
563 elif ttype in ['binary']:563 elif ttype in ['binary']:
564 logger = netsvc.Logger()564 logger = logging.getLogger('ext synchro mapping')
565 warning_text = "Binary mapping is actually not supported (attribute: %s)" % (attribute.attribute_code,)565 logger.warn("Binary mapping is actually not supported (attribute: %s)", attribute.attribute_code)
566 logger.notifyChannel('ext synchro mapping', netsvc.LOG_WARNING, warning_text)566 warning_msg = ("import logging\n"
567 warning_msg = ("import netsvc\n"567 "logger = logging.getLogger('ext synchro mapping')\n"
568 "logger = netsvc.Logger()\n"568 "logger.warn('Binary mapping is actually not supported (attribute: %%s)', %s)") % (attribute.attribute_code)
569 "logger.notifyChannel('ext synchro mapping', netsvc.LOG_WARNING, '%s')") % (warning_text,)
570 in_function = out_function = warning_msg569 in_function = out_function = warning_msg
571 return in_function, out_function570 return in_function, out_function
572571
@@ -682,7 +681,7 @@
682 _name = "magerp.product_attribute_set"681 _name = "magerp.product_attribute_set"
683 _description = "Attribute sets in products"682 _description = "Attribute sets in products"
684 _rec_name = 'attribute_set_name'683 _rec_name = 'attribute_set_name'
685 684
686 _columns = {685 _columns = {
687 'sort_order':fields.integer('Sort Order'),686 'sort_order':fields.integer('Sort Order'),
688 'attribute_set_name':fields.char('Set Name', size=100),687 'attribute_set_name':fields.char('Set Name', size=100),
@@ -731,7 +730,7 @@
731 cr.execute(query)730 cr.execute(query)
732731
733 return True732 return True
734 733
735magerp_product_attribute_set()734magerp_product_attribute_set()
736735
737class magerp_product_attribute_groups(magerp_osv.magerp_osv):736class magerp_product_attribute_groups(magerp_osv.magerp_osv):
@@ -744,7 +743,7 @@
744 for attribute_group in self.browse(cr, uid, ids, context):743 for attribute_group in self.browse(cr, uid, ids, context):
745 res[attribute_group.id] = self.pool.get('magerp.product_attribute_set').extid_to_oeid(cr, uid, attribute_group.attribute_set_id, attribute_group.referential_id.id)744 res[attribute_group.id] = self.pool.get('magerp.product_attribute_set').extid_to_oeid(cr, uid, attribute_group.attribute_set_id, attribute_group.referential_id.id)
746 return res745 return res
747 746
748 _columns = {747 _columns = {
749 'attribute_set_id':fields.integer('Attribute Set ID'),748 'attribute_set_id':fields.integer('Attribute Set ID'),
750 'attribute_set':fields.function(_get_set, type="many2one", relation="magerp.product_attribute_set", method=True, string="Attribute Set"),749 'attribute_set':fields.function(_get_set, type="many2one", relation="magerp.product_attribute_set", method=True, string="Attribute Set"),
@@ -758,7 +757,7 @@
758class product_tierprice(osv.osv):757class product_tierprice(osv.osv):
759 _name = "product.tierprice"758 _name = "product.tierprice"
760 _description = "Implements magento tier pricing"759 _description = "Implements magento tier pricing"
761 760
762 _columns = {761 _columns = {
763 'web_scope':fields.selection([762 'web_scope':fields.selection([
764 ('all', 'All Websites'),763 ('all', 'All Websites'),
@@ -799,7 +798,7 @@
799798
800class product_mag_osv(magerp_osv.magerp_osv):799class product_mag_osv(magerp_osv.magerp_osv):
801 _register = False # Set to false if the model shouldn't be automatically discovered.800 _register = False # Set to false if the model shouldn't be automatically discovered.
802 801
803 #remember one thing in life: Magento lies: it tells attributes are required while they are awkward to fill802 #remember one thing in life: Magento lies: it tells attributes are required while they are awkward to fill
804 #and will have a nice default vaule anyway, that's why we avoid making them mandatory in the product view803 #and will have a nice default vaule anyway, that's why we avoid making them mandatory in the product view
805 _magento_fake_mandatory_attrs = ['created_at', 'updated_at', 'has_options', 'required_options', 'model']804 _magento_fake_mandatory_attrs = ['created_at', 'updated_at', 'has_options', 'required_options', 'model']
@@ -880,7 +879,7 @@
880 cr, uid, oerp_group_id,879 cr, uid, oerp_group_id,
881 ['attribute_group_name'],880 ['attribute_group_name'],
882 context=context)['attribute_group_name']881 context=context)['attribute_group_name']
883 882
884 # Create a page for each attribute group883 # Create a page for each attribute group
885 attr_group_fields_rel.setdefault(group_name, [])884 attr_group_fields_rel.setdefault(group_name, [])
886 while True:885 while True:
@@ -954,7 +953,7 @@
954 wf, fields_get['websites_ids'], context=context)953 wf, fields_get['websites_ids'], context=context)
955954
956 return notebook955 return notebook
957 956
958 def _filter_fields_to_return(self, cr, uid, field_names, context=None):957 def _filter_fields_to_return(self, cr, uid, field_names, context=None):
959 '''This function is a hook in order to filter the fields that appears on the view'''958 '''This function is a hook in order to filter the fields that appears on the view'''
960 return field_names959 return field_names
@@ -1067,13 +1066,13 @@
1067 #TODO base the import on the mapping and the function ext_import1066 #TODO base the import on the mapping and the function ext_import
1068 def import_product_image(self, cr, uid, id, referential_id, conn, ext_id=None, context=None):1067 def import_product_image(self, cr, uid, id, referential_id, conn, ext_id=None, context=None):
1069 image_obj = self.pool.get('product.images')1068 image_obj = self.pool.get('product.images')
1070 logger = netsvc.Logger()1069 logger = logging.getLogger('ext synchro')
1071 if not ext_id:1070 if not ext_id:
1072 ext_id = self.oeid_to_extid(cr, uid, id, referential_id, context=None)1071 ext_id = self.oeid_to_extid(cr, uid, id, referential_id, context=None)
1073 # TODO everythere will should pass the params 'id' for magento api in order to force 1072 # TODO everythere will should pass the params 'id' for magento api in order to force
1074 # to use the id as external key instead of mixed id/sku1073 # to use the id as external key instead of mixed id/sku
1075 img_list = conn.call('catalog_product_attribute_media.list', [ext_id, False, 'id'])1074 img_list = conn.call('catalog_product_attribute_media.list', [ext_id, False, 'id'])
1076 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Magento image for product ext_id %s: %s" %(ext_id, img_list))1075 logger.info("Magento image for product ext_id %s: %s", ext_id, img_list)
1077 images_name = []1076 images_name = []
1078 for image in img_list:1077 for image in img_list:
1079 img=False1078 img=False
@@ -1083,13 +1082,13 @@
1083 data = f.read()1082 data = f.read()
1084 f.close()1083 f.close()
1085 if "DOCTYPE html PUBLIC" in data:1084 if "DOCTYPE html PUBLIC" in data:
1086 logger.notifyChannel('ext synchro', netsvc.LOG_WARNING, "failed to open the image %s from Magento" % (image['url'],))1085 logger.warn("Failed to open the image %s from Magento", image['url'])
1087 continue1086 continue
1088 else:1087 else:
1089 img = base64.encodestring(data)1088 img = base64.encodestring(data)
1090 except Exception, e:1089 except Exception, e:
1091 #TODO raise correctly the error1090 #TODO raise correctly the error
1092 logger.notifyChannel('ext synchro', netsvc.LOG_WARNING, "failed to open the image %s from Magento, error : %s" % (image['url'],e))1091 logger.error("Failed to open the image %s from Magento, error : %s", image['url'], e, exc_info=True)
1093 continue1092 continue
1094 mag_filename, extention = os.path.splitext(os.path.basename(image['file']))1093 mag_filename, extention = os.path.splitext(os.path.basename(image['file']))
1095 data = {'name': image['label'] and not image['label'] in images_name and image['label'] or mag_filename,1094 data = {'name': image['label'] and not image['label'] in images_name and image['label'] or mag_filename,
@@ -1115,7 +1114,7 @@
1115 new_image_id = image_obj.create(cr, uid, data, context=context)1114 new_image_id = image_obj.create(cr, uid, data, context=context)
1116 image_obj.create_external_id_vals(cr, uid, new_image_id, image['file'], referential_id, context=context)1115 image_obj.create_external_id_vals(cr, uid, new_image_id, image['file'], referential_id, context=context)
1117 return True1116 return True
1118 1117
1119 def extid_to_existing_oeid(self, cr, uid, id, external_referential_id, context=None):1118 def extid_to_existing_oeid(self, cr, uid, id, external_referential_id, context=None):
1120 """Returns the OpenERP id of a resource by its external id.1119 """Returns the OpenERP id of a resource by its external id.
1121 Returns False if the resource does not exist."""1120 Returns False if the resource does not exist."""
@@ -1180,7 +1179,7 @@
1180 else:1179 else:
1181 return False1180 return False
1182 tier_price = False1181 tier_price = False
1183 if 'x_magerp_tier_price' in vals.keys(): 1182 if 'x_magerp_tier_price' in vals.keys():
1184 tier_price = vals.pop('x_magerp_tier_price')1183 tier_price = vals.pop('x_magerp_tier_price')
1185 tp_obj = self.pool.get('product.tierprice')1184 tp_obj = self.pool.get('product.tierprice')
1186 #Delete existing tier prices1185 #Delete existing tier prices
@@ -1193,7 +1192,7 @@
1193 stat = super(product_product, self).write(cr, uid, ids, vals, context)1192 stat = super(product_product, self).write(cr, uid, ids, vals, context)
1194 #Perform other operation1193 #Perform other operation
1195 return stat1194 return stat
1196 1195
1197 def create_tier_price(self, cr, uid, tier_price, instance, product_id):1196 def create_tier_price(self, cr, uid, tier_price, instance, product_id):
1198 tp_obj = self.pool.get('product.tierprice')1197 tp_obj = self.pool.get('product.tierprice')
1199 for each in eval(tier_price):1198 for each in eval(tier_price):
@@ -1215,13 +1214,13 @@
1215 tier_vals['web_scope'] = 'specific'1214 tier_vals['web_scope'] = 'specific'
1216 tier_vals['website_id'] = self.pool.get('external.shop.group').mage_to_oe(cr, uid, int(each['website_id']), instance)1215 tier_vals['website_id'] = self.pool.get('external.shop.group').mage_to_oe(cr, uid, int(each['website_id']), instance)
1217 tp_obj.create(cr, uid, tier_vals)1216 tp_obj.create(cr, uid, tier_vals)
1218 1217
1219 def create(self, cr, uid, vals, context=None):1218 def create(self, cr, uid, vals, context=None):
1220 tier_price = False1219 tier_price = False
1221 if vals.get('referential_id', False):1220 if vals.get('referential_id', False):
1222 instance = vals['referential_id']1221 instance = vals['referential_id']
1223 #Filter keys to be changed1222 #Filter keys to be changed
1224 if 'x_magerp_tier_price' in vals.keys(): 1223 if 'x_magerp_tier_price' in vals.keys():
1225 tier_price = vals.pop('x_magerp_tier_price')1224 tier_price = vals.pop('x_magerp_tier_price')
12261225
1227 crid = super(product_product, self).create(cr, uid, vals, context)1226 crid = super(product_product, self).create(cr, uid, vals, context)
@@ -1262,7 +1261,7 @@
1262 raise osv.except_osv(_('Warning!'), _('This product is related to Magento. It can not be deleted!\nYou can change it Magento status to "Disabled" and uncheck the active box to hide it from OpenERP.'))1261 raise osv.except_osv(_('Warning!'), _('This product is related to Magento. It can not be deleted!\nYou can change it Magento status to "Disabled" and uncheck the active box to hide it from OpenERP.'))
1263 else:1262 else:
1264 return super(product_product, self).unlink(cr, uid, ids, context)1263 return super(product_product, self).unlink(cr, uid, ids, context)
1265 1264
1266 #TODO move part of this to declarative mapping CSV template1265 #TODO move part of this to declarative mapping CSV template
1267 def extdata_from_oevals(self, cr, uid, external_referential_id, data_record, mapping_lines, defaults, context=None):1266 def extdata_from_oevals(self, cr, uid, external_referential_id, data_record, mapping_lines, defaults, context=None):
1268 product_data = super(product_product, self).extdata_from_oevals(cr, uid, external_referential_id, data_record, mapping_lines, defaults, context) #Aapply custom/attributes mappings1267 product_data = super(product_product, self).extdata_from_oevals(cr, uid, external_referential_id, data_record, mapping_lines, defaults, context) #Aapply custom/attributes mappings
@@ -1275,10 +1274,10 @@
1275 if isinstance(pl_default_id, int):1274 if isinstance(pl_default_id, int):
1276 pl_default_id = [pl_default_id]1275 pl_default_id = [pl_default_id]
1277 product_data.update({'price': self.pool.get('product.pricelist').price_get(cr, uid, pl_default_id, product.id, 1.0)[pl_default_id[0]]})1276 product_data.update({'price': self.pool.get('product.pricelist').price_get(cr, uid, pl_default_id, product.id, 1.0)[pl_default_id[0]]})
1278 1277
1279 if not product_data.get('tax_class_id', False):1278 if not product_data.get('tax_class_id', False):
1280 product_data.update({'tax_class_id': 2}) #FIXME hugly!1279 product_data.update({'tax_class_id': 2}) #FIXME hugly!
1281 1280
1282 if not product_data.get('status', False):1281 if not product_data.get('status', False):
1283 product_data.update({'status': product.active and 1 or 0})1282 product_data.update({'status': product.active and 1 or 0})
12841283
@@ -1292,7 +1291,7 @@
1292 product_data.update({'meta_keyword': product.name})1291 product_data.update({'meta_keyword': product.name})
1293 if not product_data.get('meta_description', False):1292 if not product_data.get('meta_description', False):
1294 product_data.update({'meta_description': product.description_sale and product.description_sale[:255]})1293 product_data.update({'meta_description': product.description_sale and product.description_sale[:255]})
1295 1294
1296 return product_data1295 return product_data
12971296
1298 def oevals_from_extdata(self, cr, uid, external_referential_id, data_record, mapping_lines, key_for_external_id=None, parent_data=None, previous_lines=None, defaults=None, context=None):1297 def oevals_from_extdata(self, cr, uid, external_referential_id, data_record, mapping_lines, key_for_external_id=None, parent_data=None, previous_lines=None, defaults=None, context=None):
@@ -1350,7 +1349,7 @@
1350 return ext_id1349 return ext_id
13511350
1352 def action_before_exporting_grouped_product(self, cr, uid, id, external_referential_ids=None, defaults=None, context=None):1351 def action_before_exporting_grouped_product(self, cr, uid, id, external_referential_ids=None, defaults=None, context=None):
1353 logger = netsvc.Logger()1352 logger = logging.getLogger('ext synchro')
1354 if context.get('mrp_is_installed', False):1353 if context.get('mrp_is_installed', False):
1355 bom_ids = self.read(cr, uid, id, ['bom_ids'])['bom_ids']1354 bom_ids = self.read(cr, uid, id, ['bom_ids'])['bom_ids']
1356 if len(bom_ids): # it has or is part of a BoM1355 if len(bom_ids): # it has or is part of a BoM
@@ -1361,18 +1360,18 @@
1361 for row in results:1360 for row in results:
1362 child_ids.append(row['product_id'])1361 child_ids.append(row['product_id'])
1363 quantities.update({row['product_id']: row['product_qty']})1362 quantities.update({row['product_id']: row['product_qty']})
1364 if child_ids: #it is an assembly and it contains the products child_ids: 1363 if child_ids: #it is an assembly and it contains the products child_ids:
1365 self.ext_export(cr, uid, child_ids, external_referential_ids, defaults, context) #so we export them1364 self.ext_export(cr, uid, child_ids, external_referential_ids, defaults, context) #so we export them
1366 else:1365 else:
1367 return False1366 return False
1368 else:1367 else:
1369 logger.notifyChannel('ext synchro', netsvc.LOG_ERROR, "OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")1368 logger.error("OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")
1370 return quantities, child_ids1369 return quantities, child_ids
13711370
1372 def action_before_exporting(self, cr, uid, id, product_type, external_referential_ids=None, defaults=None, context=None):1371 def action_before_exporting(self, cr, uid, id, product_type, external_referential_ids=None, defaults=None, context=None):
1373 '''Hook to allow your external module to execute some code before exporting a product'''1372 '''Hook to allow your external module to execute some code before exporting a product'''
1374 return True1373 return True
1375 1374
1376 #todo move this code to a generic module1375 #todo move this code to a generic module
1377 def get_last_update_date(self, cr, uid, product_read, context=None):1376 def get_last_update_date(self, cr, uid, product_read, context=None):
1378 """if a product have a depends on other object like bom for grouped product, or other product for configurable1377 """if a product have a depends on other object like bom for grouped product, or other product for configurable
@@ -1389,10 +1388,10 @@
1389 if last_updated_bom_date > last_updated_date:1388 if last_updated_bom_date > last_updated_date:
1390 last_updated_date=last_updated_bom_date1389 last_updated_date=last_updated_bom_date
1391 else:1390 else:
1392 conn.logger.notifyChannel('ext synchro', netsvc.LOG_ERROR, "OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed") 1391 conn.logger.error("OpenERP 'grouped' products will export to Magento as 'grouped products' only if they have a BOM and if the 'mrp' BOM module is installed")
1393 return last_updated_date1392 return last_updated_date
1394 1393
1395 1394
1396 def get_ordered_ids(self, cr, uid, ids, external_referential_ids=None, defaults=None, context=None):1395 def get_ordered_ids(self, cr, uid, ids, external_referential_ids=None, defaults=None, context=None):
1397 #TODO pass the shop better than the referentials1396 #TODO pass the shop better than the referentials
1398 dates_2_ids = []1397 dates_2_ids = []
@@ -1408,7 +1407,7 @@
1408 read = cr.dictfetchall()1407 read = cr.dictfetchall()
1409 ids = []1408 ids = []
1410 context['force']=True1409 context['force']=True
1411 1410
1412 for product_read in read:1411 for product_read in read:
1413 last_updated_date = self.get_last_update_date(cr, uid, product_read, context=context)1412 last_updated_date = self.get_last_update_date(cr, uid, product_read, context=context)
1414 if last_exported_date and last_updated_date < last_exported_date:1413 if last_exported_date and last_updated_date < last_exported_date:
@@ -1474,7 +1473,7 @@
1474 context['default_set_id'] = default_set_id1473 context['default_set_id'] = default_set_id
14751474
1476 context_dic = [context.copy()]1475 context_dic = [context.copy()]
1477 context_dic[0]['export_url'] = True # for the magento version 1.3.2.4, only one url is autorized by product, so we only export with the MAPPING TEMPLATE the url of the default language 1476 context_dic[0]['export_url'] = True # for the magento version 1.3.2.4, only one url is autorized by product, so we only export with the MAPPING TEMPLATE the url of the default language
1478 context_dic[0]['lang'] = shop.referential_id.default_lang_id.code1477 context_dic[0]['lang'] = shop.referential_id.default_lang_id.code
14791478
1480 for storeview in shop.storeview_ids:1479 for storeview in shop.storeview_ids:
@@ -1499,14 +1498,14 @@
1499 result['create_ids'] += temp_result['create_ids']1498 result['create_ids'] += temp_result['create_ids']
1500 result['write_ids'] += temp_result['write_ids']1499 result['write_ids'] += temp_result['write_ids']
1501 return result1500 return result
1502 1501
1503 def try_ext_update(self, cr, uid, data, conn, method, oe_id, external_id, ir_model_data_id, create_method, context=None):1502 def try_ext_update(self, cr, uid, data, conn, method, oe_id, external_id, ir_model_data_id, create_method, context=None):
1504 if context is None: context = {}1503 if context is None: context = {}
1505 if context.get('storeview_code', False):1504 if context.get('storeview_code', False):
1506 return conn.call(method, [external_id, data, context.get('storeview_code', False)])1505 return conn.call(method, [external_id, data, context.get('storeview_code', False)])
1507 else:1506 else:
1508 return conn.call(method, [external_id, data])1507 return conn.call(method, [external_id, data])
1509 1508
1510 def ext_update(self, cr, uid, data, conn, method, oe_id, external_id, ir_model_data_id, create_method, context=None):1509 def ext_update(self, cr, uid, data, conn, method, oe_id, external_id, ir_model_data_id, create_method, context=None):
1511 product = self.browse(cr, uid, oe_id)1510 product = self.browse(cr, uid, oe_id)
1512 sku = self.product_to_sku(cr, uid, product)1511 sku = self.product_to_sku(cr, uid, product)
@@ -1544,7 +1543,7 @@
1544 :return: True1543 :return: True
1545 """1544 """
1546 if context is None: context = {}1545 if context is None: context = {}
1547 logger = netsvc.Logger()1546 logger = logging.getLogger('ext synchro')
15481547
1549 shop = self.pool.get('sale.shop').browse(1548 shop = self.pool.get('sale.shop').browse(
1550 cr, uid, shop_id, context=context)1549 cr, uid, shop_id, context=context)
@@ -1577,14 +1576,13 @@
1577 connection.call('product_stock.update',1576 connection.call('product_stock.update',
1578 [mag_product_id, inventory_vals])1577 [mag_product_id, inventory_vals])
15791578
1580 logger.notifyChannel(1579 logger.info(
1581 'ext synchro',1580 "Successfully updated stock level at %s for product with SKU %s",
1582 netsvc.LOG_INFO,1581 inventory_vals.get('qty', 'N/A'),
1583 "Successfully updated stock level at %s for "1582 product.magento_sku
1584 "product with SKU %s " %1583 )
1585 (inventory_vals.get('qty', 'N/A'), product.magento_sku))
1586 return True1584 return True
1587 1585
1588 def ext_assign_links(self, cr, uid, ids, external_referential_ids=None, defaults=None, context=None):1586 def ext_assign_links(self, cr, uid, ids, external_referential_ids=None, defaults=None, context=None):
1589 """ Assign links of type up-sell, cross-sell, related """1587 """ Assign links of type up-sell, cross-sell, related """
1590 if isinstance(ids, (int, long)):1588 if isinstance(ids, (int, long)):
@@ -1607,7 +1605,7 @@
1607 position = position or {}1605 position = position or {}
1608 quantities = quantities or {}1606 quantities = quantities or {}
1609 external_referential_ids = external_referential_ids or []1607 external_referential_ids = external_referential_ids or []
1610 logger = netsvc.Logger()1608 logger = logging.getLogger('ext assign')
1611 conn = context.get('conn_obj', False)1609 conn = context.get('conn_obj', False)
16121610
1613 for ref_id in external_referential_ids:1611 for ref_id in external_referential_ids:
@@ -1662,7 +1660,7 @@
1662 for c_ext_id in ext_id_to_remove:1660 for c_ext_id in ext_id_to_remove:
1663 # remove the product links that are no more setup on openerp1661 # remove the product links that are no more setup on openerp
1664 conn.call('product_link.remove', magento_args + [c_ext_id])1662 conn.call('product_link.remove', magento_args + [c_ext_id])
1665 logger.notifyChannel('ext assign', netsvc.LOG_INFO, "Successfully removed assignment of type %s for product %s to product %s" % (type, skus[parent_id], c_ext_id))1663 logger.info("Successfully removed assignment of type %s for product %s to product %s", type, skus[parent_id], c_ext_id)
1666 for child_ext_id in ext_id_to_assign:1664 for child_ext_id in ext_id_to_assign:
1667 # assign new product links1665 # assign new product links
1668 product_id = new_child_ext_ids[child_ext_id]1666 product_id = new_child_ext_ids[child_ext_id]
@@ -1671,7 +1669,7 @@
1671 [child_ext_id,1669 [child_ext_id,
1672 {'position': position.get(product_id, 0),1670 {'position': position.get(product_id, 0),
1673 'qty': quantities.get(product_id, 1)}])1671 'qty': quantities.get(product_id, 1)}])
1674 logger.notifyChannel('ext assign', netsvc.LOG_INFO, "Successfully assigned product %s to product %s with type %s" %(skus[parent_id], skus[product_id], type))1672 logger.info("Successfully assigned product %s to product %s with type %s", skus[parent_id], skus[product_id], type)
1675 for child_ext_id in ext_id_to_update:1673 for child_ext_id in ext_id_to_update:
1676 # update products links already assigned1674 # update products links already assigned
1677 product_id = new_child_ext_ids[child_ext_id]1675 product_id = new_child_ext_ids[child_ext_id]
@@ -1680,7 +1678,7 @@
1680 [child_ext_id,1678 [child_ext_id,
1681 {'position': position.get(product_id, 0),1679 {'position': position.get(product_id, 0),
1682 'qty': quantities.get(product_id, 1)}])1680 'qty': quantities.get(product_id, 1)}])
1683 logger.notifyChannel('ext assign', netsvc.LOG_INFO, "Successfully updated assignment of type %s of product %s to product %s" %(type, skus[parent_id], skus[product_id]))1681 logger.info("Successfully updated assignment of type %s of product %s to product %s", type, skus[parent_id], skus[product_id])
1684 return True1682 return True
16851683
1686 #TODO move this code (get exportable image) and also some code in product_image.py and sale.py in base_sale_multichannel or in a new module in order to be more generic1684 #TODO move this code (get exportable image) and also some code in product_image.py and sale.py in base_sale_multichannel or in a new module in order to be more generic
@@ -1696,7 +1694,7 @@
16961694
1697 def _mag_import_product_links_type(self, cr, uid, product, link_type, external_referential_id, conn, context=None):1695 def _mag_import_product_links_type(self, cr, uid, product, link_type, external_referential_id, conn, context=None):
1698 if context is None: context = {}1696 if context is None: context = {}
1699 logger = netsvc.Logger()1697 logger = logging.getLogger('ext synchro')
1700 product_link_obj = self.pool.get('product.link')1698 product_link_obj = self.pool.get('product.link')
1701 selection_link_types = product_link_obj._columns['type'].selection(cr, uid, context)1699 selection_link_types = product_link_obj._columns['type'].selection(cr, uid, context)
1702 # This method could be completed to import grouped products too, you know, for Magento a product link is as1700 # This method could be completed to import grouped products too, you know, for Magento a product link is as
@@ -1707,7 +1705,7 @@
1707 product_links = conn.call('product_link.list', [link_type, product.magento_sku])1705 product_links = conn.call('product_link.list', [link_type, product.magento_sku])
1708 except Exception, e:1706 except Exception, e:
1709 self.log(cr, uid, product.id, "Error when retrieving the list of links in Magento for product with sku %s and product id %s !" % (product.magento_sku, product.id,))1707 self.log(cr, uid, product.id, "Error when retrieving the list of links in Magento for product with sku %s and product id %s !" % (product.magento_sku, product.id,))
1710 logger.notifyChannel('ext synchro', netsvc.LOG_DEBUG, "Error when retrieving the list of links in Magento for product with sku %s and product id %s !" % (product.magento_sku, product.id,))1708 logger.debug("Error when retrieving the list of links in Magento for product with sku %s and product id %s !", product.magento_sku, product.id)
17111709
1712 for product_link in product_links:1710 for product_link in product_links:
1713 ctx = context.copy()1711 ctx = context.copy()
@@ -1729,7 +1727,7 @@
1729 product_link_obj.write(cr, uid, existing_link, link_data, context=context)1727 product_link_obj.write(cr, uid, existing_link, link_data, context=context)
1730 else:1728 else:
1731 product_link_obj.create(cr, uid, link_data, context=context)1729 product_link_obj.create(cr, uid, link_data, context=context)
1732 logger.notifyChannel('Import Product Links', netsvc.LOG_INFO, "Successfully imported product link of type %s on product %s to product %s" %(link_type, product.id, linked_product_id))1730 logger.info("Successfully imported product link of type %s on product %s to product %s", link_type, product.id, linked_product_id)
1733 return True1731 return True
17341732
1735 def mag_import_product_links_types(self, cr, uid, ids, link_types, external_referential_id, conn, context=None):1733 def mag_import_product_links_types(self, cr, uid, ids, link_types, external_referential_id, conn, context=None):
17361734
=== modified file 'magentoerpconnect/product_images.py'
--- magentoerpconnect/product_images.py 2011-11-27 15:12:39 +0000
+++ magentoerpconnect/product_images.py 2012-05-25 09:04:23 +0000
@@ -23,7 +23,7 @@
23from osv import osv, fields23from osv import osv, fields
24import magerp_osv24import magerp_osv
25import mimetypes25import mimetypes
26import netsvc26import logging
27from tools.translate import _27from tools.translate import _
2828
29#TODO the option small_image, thumbnail, exclude, base_image, should be store diferently indeed this is not compatible with mutli instance (maybe serialized will be a good solution)29#TODO the option small_image, thumbnail, exclude, base_image, should be store diferently indeed this is not compatible with mutli instance (maybe serialized will be a good solution)
@@ -48,12 +48,12 @@
48 'thumbnail':lambda * a:True,48 'thumbnail':lambda * a:True,
49 'exclude':lambda * a:False49 'exclude':lambda * a:False
50 }50 }
51 51
52 def get_changed_ids(self, cr, uid, start_date=False):52 def get_changed_ids(self, cr, uid, start_date=False):
53 proxy = self.pool.get('product.images')53 proxy = self.pool.get('product.images')
54 domain = start_date and ['|', ('create_date', '>', start_date), ('write_date', '>', start_date)] or []54 domain = start_date and ['|', ('create_date', '>', start_date), ('write_date', '>', start_date)] or []
55 return proxy.search(cr, uid, domain)55 return proxy.search(cr, uid, domain)
56 56
57 def del_image_name(self, cr, uid, id, context=None):57 def del_image_name(self, cr, uid, id, context=None):
58 if context is None: context = {}58 if context is None: context = {}
59 image_ext_name_obj = self.pool.get('product.images.external.name')59 image_ext_name_obj = self.pool.get('product.images.external.name')
@@ -65,7 +65,7 @@
65 def update_remote_images(self, cr, uid, ids, context=None):65 def update_remote_images(self, cr, uid, ids, context=None):
66 if context is None:66 if context is None:
67 context = {}67 context = {}
68 logger = netsvc.Logger()68 logger = logging.getLogger('ext synchro')
69 conn = context.get('conn_obj', False)69 conn = context.get('conn_obj', False)
70 if not conn:70 if not conn:
71 return False71 return False
@@ -112,7 +112,7 @@
112 image_2_date[image['id']] = image['write_date'] or image['create_date']112 image_2_date[image['id']] = image['write_date'] or image['create_date']
113 list_date = date_2_image.keys()113 list_date = date_2_image.keys()
114 list_date.sort()114 list_date.sort()
115 115
116 ids = [date_2_image[date] for date in list_date]116 ids = [date_2_image[date] for date in list_date]
117117
118 while ids:118 while ids:
@@ -122,24 +122,24 @@
122 ext_file_name = each.oeid_to_extid(context['external_referential_id'])122 ext_file_name = each.oeid_to_extid(context['external_referential_id'])
123 if ext_file_name: #If update123 if ext_file_name: #If update
124 try:124 try:
125 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Updating %s's image: %s" %(each.product_id.magento_sku, each.name))125 logger.info("Updating %s's image: %s", each.product_id.magento_sku, each.name)
126 result = update_image(ext_file_name, each)126 result = update_image(ext_file_name, each)
127 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "%s's image updated with sucess: %s" %(each.product_id.magento_sku, each.name))127 logger.info("%s's image updated with sucess: %s", each.product_id.magento_sku, each.name)
128 need_to_be_created = False128 need_to_be_created = False
129 except Exception, e:129 except Exception, e:
130 logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Error in connecting:%s") % (e))130 logger.error(_("Error in connecting:%s"), e, exc_info=True)
131 if not "Fault 103" in str(e):131 if not "Fault 103" in str(e):
132 logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("Unknow error stop export"))132 logger.error(_("Unknow error stop export"))
133 raise133 raise
134 else:134 else:
135 #If the image was deleded in magento, the external name is automatically deleded before trying to re-create the image in magento135 #If the image was deleded in magento, the external name is automatically deleded before trying to re-create the image in magento
136 model_data_ids = ir_model_data_obj.search(cr, uid, [('model', '=', self._name), ('res_id', '=', each.id), ('external_referential_id', '=', context['external_referential_id'])])136 model_data_ids = ir_model_data_obj.search(cr, uid, [('model', '=', self._name), ('res_id', '=', each.id), ('external_referential_id', '=', context['external_referential_id'])])
137 if model_data_ids and len(model_data_ids) > 0:137 if model_data_ids and len(model_data_ids) > 0:
138 ir_model_data_obj.unlink(cr, uid, model_data_ids, context=context)138 ir_model_data_obj.unlink(cr, uid, model_data_ids, context=context)
139 logger.notifyChannel(_("Magento Connection"), netsvc.LOG_ERROR, _("The image don't exist in magento, try to create it"))139 logger.error(_("The image don't exist in magento, try to create it"))
140 if need_to_be_created:140 if need_to_be_created:
141 if each.product_id.magento_sku:141 if each.product_id.magento_sku:
142 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Sending %s's image: %s" %(each.product_id.magento_sku, each.name))142 logger.info("Sending %s's image: %s", each.product_id.magento_sku, each.name)
143 result = conn.call('catalog_product_attribute_media.create',143 result = conn.call('catalog_product_attribute_media.create',
144 [each.product_id.magento_sku,144 [each.product_id.magento_sku,
145 {'file':{145 {'file':{
@@ -151,12 +151,12 @@
151 ])151 ])
152 self.create_external_id_vals(cr, uid, each.id, result, context['external_referential_id'], context=context)152 self.create_external_id_vals(cr, uid, each.id, result, context['external_referential_id'], context=context)
153 result = update_image(result, each)153 result = update_image(result, each)
154 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "%s's image send with sucess: %s" %(each.product_id.magento_sku, each.name))154 logger.info("%s's image send with sucess: %s", each.product_id.magento_sku, each.name)
155 if image_2_date[each.id] > context['last_images_export_date']: #indeed if a product was created a long time ago and checked as exportable recently, the write date of the image can be far away in the past155 if image_2_date[each.id] > context['last_images_export_date']: #indeed if a product was created a long time ago and checked as exportable recently, the write date of the image can be far away in the past
156 self.pool.get('sale.shop').write(cr,uid,context['shop_id'],{'last_images_export_date':image_2_date[each.id]})156 self.pool.get('sale.shop').write(cr,uid,context['shop_id'],{'last_images_export_date':image_2_date[each.id]})
157 cr.commit()157 cr.commit()
158 ids = ids[1000:]158 ids = ids[1000:]
159 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "still %s image to export" %len(ids))159 logger.info("still %s image to export", len(ids))
160 return True160 return True
161 161
162product_images()162product_images()
163163
=== modified file 'magentoerpconnect/sale.py'
--- magentoerpconnect/sale.py 2012-05-24 19:33:15 +0000
+++ magentoerpconnect/sale.py 2012-05-25 09:04:23 +0000
@@ -26,6 +26,7 @@
26import pooler26import pooler
27import magerp_osv27import magerp_osv
28import netsvc28import netsvc
29import logging
29from tools.translate import _30from tools.translate import _
30import string31import string
31#from datetime import datetime32#from datetime import datetime
@@ -50,7 +51,7 @@
5051
51class sale_shop(magerp_osv.magerp_osv):52class sale_shop(magerp_osv.magerp_osv):
52 _inherit = "sale.shop"53 _inherit = "sale.shop"
53 54
54 def _get_exportable_product_ids(self, cr, uid, ids, name, args, context=None):55 def _get_exportable_product_ids(self, cr, uid, ids, name, args, context=None):
55 res = super(sale_shop, self)._get_exportable_product_ids(cr, uid, ids, name, args, context=None)56 res = super(sale_shop, self)._get_exportable_product_ids(cr, uid, ids, name, args, context=None)
56 for shop_id in res:57 for shop_id in res:
@@ -70,10 +71,10 @@
70 else:71 else:
71 res[shop.id] = False72 res[shop.id] = False
72 return res73 return res
73 74
74 def export_images(self, cr, uid, ids, context=None):75 def export_images(self, cr, uid, ids, context=None):
75 if context is None: context = {}76 if context is None: context = {}
76 logger = netsvc.Logger()77 logger = logging.getLogger('ext synchro')
77 start_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)78 start_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
78 image_obj = self.pool.get('product.images')79 image_obj = self.pool.get('product.images')
79 for shop in self.browse(cr, uid, ids):80 for shop in self.browse(cr, uid, ids):
@@ -84,13 +85,13 @@
84 exportable_product_ids = self.read(cr, uid, shop.id, ['exportable_product_ids'], context=context)['exportable_product_ids']85 exportable_product_ids = self.read(cr, uid, shop.id, ['exportable_product_ids'], context=context)['exportable_product_ids']
85 res = self.pool.get('product.product').get_exportable_images(cr, uid, exportable_product_ids, context=context)86 res = self.pool.get('product.product').get_exportable_images(cr, uid, exportable_product_ids, context=context)
86 if res:87 if res:
87 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Creating %s images" %(len(res['to_create'])))88 logger.info("Creating %s images", len(res['to_create']))
88 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Updating %s images" %(len(res['to_update'])))89 logger.info("Updating %s images", len(res['to_update']))
89 image_obj.update_remote_images(cr, uid, res['to_update']+res['to_create'], context)90 image_obj.update_remote_images(cr, uid, res['to_update']+res['to_create'], context)
90 self.write(cr,uid,context['shop_id'],{'last_images_export_date': start_date})91 self.write(cr,uid,context['shop_id'],{'last_images_export_date': start_date})
91 return True92 return True
92 93
93 94
94 def _get_rootcategory(self, cr, uid, ids, prop, unknow_none, context=None):95 def _get_rootcategory(self, cr, uid, ids, prop, unknow_none, context=None):
95 res = {}96 res = {}
96 for shop in self.browse(cr, uid, ids, context):97 for shop in self.browse(cr, uid, ids, context):
@@ -131,7 +132,7 @@
131 'magento_shop': fields.boolean('Magento Shop', readonly=True),132 'magento_shop': fields.boolean('Magento Shop', readonly=True),
132 'allow_magento_order_status_push': fields.boolean('Allow Magento Order Status push', help='Allow to send back order status to Magento if order status changed in OpenERP first?'),133 'allow_magento_order_status_push': fields.boolean('Allow Magento Order Status push', help='Allow to send back order status to Magento if order status changed in OpenERP first?'),
133 'allow_magento_notification': fields.boolean('Allow Magento Notification', help='Allow Magento to notify customer with an e-mail when OpenERP change an order status, create an invoice or a delivery order on Magento.'),134 'allow_magento_notification': fields.boolean('Allow Magento Notification', help='Allow Magento to notify customer with an e-mail when OpenERP change an order status, create an invoice or a delivery order on Magento.'),
134 } 135 }
135136
136 _defaults = {137 _defaults = {
137 'allow_magento_order_status_push': lambda * a: False,138 'allow_magento_order_status_push': lambda * a: False,
@@ -174,7 +175,7 @@
174 conn = shop.referential_id.external_connection()175 conn = shop.referential_id.external_connection()
175 # Update the state of orders in OERP that are in "need_to_update":True176 # Update the state of orders in OERP that are in "need_to_update":True
176 # from the Magento's corresponding orders177 # from the Magento's corresponding orders
177 178
178 # Get all need_to_update orders in OERP179 # Get all need_to_update orders in OERP
179 orders_to_update = so_obj.search(180 orders_to_update = so_obj.search(
180 cr, uid,181 cr, uid,
@@ -239,7 +240,7 @@
239240
240 def run_update_images_scheduler(self, cr, uid, context=None):241 def run_update_images_scheduler(self, cr, uid, context=None):
241 self._sale_shop(cr, uid, self.export_images, context=context)242 self._sale_shop(cr, uid, self.export_images, context=context)
242 243
243 def run_export_shipping_scheduler(self, cr, uid, context=None):244 def run_export_shipping_scheduler(self, cr, uid, context=None):
244 self._sale_shop(cr, uid, self.export_shipping, context=context)245 self._sale_shop(cr, uid, self.export_shipping, context=context)
245246
@@ -248,7 +249,7 @@
248249
249class sale_order(magerp_osv.magerp_osv):250class sale_order(magerp_osv.magerp_osv):
250 _inherit = "sale.order"251 _inherit = "sale.order"
251 252
252 _columns = {253 _columns = {
253 'magento_incrementid': fields.char('Magento Increment ID', size=32),254 'magento_incrementid': fields.char('Magento Increment ID', size=32),
254 'magento_storeview_id': fields.many2one('magerp.storeviews', 'Magento Store View'),255 'magento_storeview_id': fields.many2one('magerp.storeviews', 'Magento Store View'),
@@ -257,14 +258,14 @@
257 type='boolean',258 type='boolean',
258 string='Is a Magento Sale Order')259 string='Is a Magento Sale Order')
259 }260 }
260 261
261 def _auto_init(self, cr, context=None):262 def _auto_init(self, cr, context=None):
262 tools.drop_view_if_exists(cr, 'sale_report')263 tools.drop_view_if_exists(cr, 'sale_report')
263 cr.execute("ALTER TABLE sale_order_line ALTER COLUMN discount TYPE numeric(16,6);")264 cr.execute("ALTER TABLE sale_order_line ALTER COLUMN discount TYPE numeric(16,6);")
264 cr.execute("ALTER TABLE account_invoice_line ALTER COLUMN discount TYPE numeric(16,6);")265 cr.execute("ALTER TABLE account_invoice_line ALTER COLUMN discount TYPE numeric(16,6);")
265 self.pool.get('sale.report').init(cr)266 self.pool.get('sale.report').init(cr)
266 super(sale_order, self)._auto_init(cr, context)267 super(sale_order, self)._auto_init(cr, context)
267 268
268 def get_order_addresses(self, cr, uid, referential_id, data_record, context=None):269 def get_order_addresses(self, cr, uid, referential_id, data_record, context=None):
269 partner_obj = self.pool.get('res.partner')270 partner_obj = self.pool.get('res.partner')
270 partner_address_obj = self.pool.get('res.partner.address')271 partner_address_obj = self.pool.get('res.partner.address')
@@ -436,7 +437,7 @@
436 name = product.name437 name = product.name
437 if ext_code_field and data_record.get(ext_code_field, False):438 if ext_code_field and data_record.get(ext_code_field, False):
438 name = "%s [%s]" % (name, data_record[ext_code_field])439 name = "%s [%s]" % (name, data_record[ext_code_field])
439 440
440 if is_tax_included:441 if is_tax_included:
441 price_unit = float(amount) + float(data_record[ext_tax_field])442 price_unit = float(amount) + float(data_record[ext_tax_field])
442 else:443 else:
@@ -464,7 +465,7 @@
464 res['order_line'].append((0, 0, extra_line))465 res['order_line'].append((0, 0, extra_line))
465466
466 return res467 return res
467 468
468 def add_order_shipping(self, cr, uid, res, external_referential_id, data_record, defaults, context=None):469 def add_order_shipping(self, cr, uid, res, external_referential_id, data_record, defaults, context=None):
469 if context is None: context = {}470 if context is None: context = {}
470 if data_record.get('shipping_amount', False) and float(data_record.get('shipping_amount', False)) > 0:471 if data_record.get('shipping_amount', False) and float(data_record.get('shipping_amount', False)) > 0:
@@ -509,7 +510,7 @@
509 product_ref = ('magentoerpconnect', 'product_product_cash_on_delivery')510 product_ref = ('magentoerpconnect', 'product_product_cash_on_delivery')
510 res = self.add_order_extra_line(cr, uid, res, data_record, 'cod_fee', product_ref, defaults, ctx)511 res = self.add_order_extra_line(cr, uid, res, data_record, 'cod_fee', product_ref, defaults, ctx)
511 return res512 return res
512 513
513 def convert_extdata_into_oedata(self, cr, uid, external_data, external_referential_id, parent_data=None, defaults=None, context=None):514 def convert_extdata_into_oedata(self, cr, uid, external_data, external_referential_id, parent_data=None, defaults=None, context=None):
514 res = super(sale_order, self).convert_extdata_into_oedata(cr, uid, external_data, external_referential_id, parent_data=parent_data, defaults=defaults, context=context)515 res = super(sale_order, self).convert_extdata_into_oedata(cr, uid, external_data, external_referential_id, parent_data=parent_data, defaults=defaults, context=context)
515 res=res[0]516 res=res[0]
@@ -566,7 +567,7 @@
566 all_items.extend(item_modified)567 all_items.extend(item_modified)
567 else:568 else:
568 all_items.append(top_item)569 all_items.append(top_item)
569 570
570 data_record['items'] = all_items571 data_record['items'] = all_items
571 return data_record572 return data_record
572573
@@ -593,7 +594,7 @@
593 res = super(magerp_osv.magerp_osv, self).oevals_from_extdata(cr, uid, external_referential_id, data_record, key_field, mapping_lines, parent_data, previous_lines, defaults, context)594 res = super(magerp_osv.magerp_osv, self).oevals_from_extdata(cr, uid, external_referential_id, data_record, key_field, mapping_lines, parent_data, previous_lines, defaults, context)
594595
595 #Move me in a mapping596 #Move me in a mapping
596 if not context.get('one_by_one', False): 597 if not context.get('one_by_one', False):
597 if data_record.get('status_history', False) and len(data_record['status_history']) > 0:598 if data_record.get('status_history', False) and len(data_record['status_history']) > 0:
598 res['date_order'] = data_record['status_history'][len(data_record['status_history'])-1]['created_at']599 res['date_order'] = data_record['status_history'][len(data_record['status_history'])-1]['created_at']
599 return res600 return res
@@ -653,7 +654,7 @@
653 """654 """
654 if context is None:655 if context is None:
655 context = {}656 context = {}
656 logger = netsvc.Logger()657 logger = logging.getLogger('ext synchro')
657 conn = context.get('conn_obj', False)658 conn = context.get('conn_obj', False)
658 parent_list = []659 parent_list = []
659 # get all parents orders (to cancel) of the sale orders660 # get all parents orders (to cancel) of the sale orders
@@ -669,7 +670,7 @@
669 try:670 try:
670 wf_service.trg_validate(uid, 'sale.order', canceled_order_id, 'cancel', cr)671 wf_service.trg_validate(uid, 'sale.order', canceled_order_id, 'cancel', cr)
671 self.log(cr, uid, canceled_order_id, "order %s canceled when updated from external system" % (canceled_order_id,))672 self.log(cr, uid, canceled_order_id, "order %s canceled when updated from external system" % (canceled_order_id,))
672 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Order %s canceled when updated from external system because it has been replaced by a new one" % (canceled_order_id,))673 logger.info("Order %s canceled when updated from external system because it has been replaced by a new one", canceled_order_id)
673 except osv.except_osv, e:674 except osv.except_osv, e:
674 #TODO: generic reporting of errors in magentoerpconnect675 #TODO: generic reporting of errors in magentoerpconnect
675 # except if the sale order has been confirmed for example, we cannot cancel the order676 # except if the sale order has been confirmed for example, we cannot cancel the order
@@ -744,10 +745,10 @@
744 def ext_set_order_imported(self, cr, uid, external_id, external_referential_id, context=None):745 def ext_set_order_imported(self, cr, uid, external_id, external_referential_id, context=None):
745 if context is None:746 if context is None:
746 context = {}747 context = {}
747 logger = netsvc.Logger()748 logger = logging.getLogger('ext synchro')
748 conn = context.get('conn_obj', False)749 conn = context.get('conn_obj', False)
749 conn.call('sales_order.done', [external_id])750 conn.call('sales_order.done', [external_id])
750 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Successfully set the imported flag on Magento on sale order %s" % external_id)751 logger.info("Successfully set the imported flag on Magento on sale order %s", external_id)
751 return True752 return True
752753
753 def mage_import_base(self, cr, uid, conn, external_referential_id, defaults=None, context=None):754 def mage_import_base(self, cr, uid, conn, external_referential_id, defaults=None, context=None):
@@ -774,7 +775,7 @@
774 if context is None:775 if context is None:
775 context = {}776 context = {}
776777
777 logger = netsvc.Logger()778 logger = logging.getLogger('ext synchro')
778 mapping_id = self.pool.get('external.mapping').search(779 mapping_id = self.pool.get('external.mapping').search(
779 cr, uid,780 cr, uid,
780 [('model', '=', self._name),781 [('model', '=', self._name),
@@ -792,7 +793,7 @@
792 existing_id = self.extid_to_existing_oeid(cr, uid, ext_order_id, referential_id, context=context)793 existing_id = self.extid_to_existing_oeid(cr, uid, ext_order_id, referential_id, context=context)
793 if existing_id:794 if existing_id:
794 unchanged_ids.append(existing_id)795 unchanged_ids.append(existing_id)
795 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "the order %s already exist in OpenERP" % (ext_order_id,))796 logger.info("the order %s already exist in OpenERP", ext_order_id)
796 self.ext_set_order_imported(cr, uid, ext_order_id, referential_id, context=context)797 self.ext_set_order_imported(cr, uid, ext_order_id, referential_id, context=context)
797 else:798 else:
798 order_ids_filtred.append({'increment_id' : ext_order_id})799 order_ids_filtred.append({'increment_id' : ext_order_id})
799800
=== modified file 'magentoerpconnect/stock.py'
--- magentoerpconnect/stock.py 2012-05-14 13:22:22 +0000
+++ magentoerpconnect/stock.py 2012-05-25 09:04:23 +0000
@@ -20,7 +20,7 @@
20#########################################################################20#########################################################################
2121
22import xmlrpclib22import xmlrpclib
23import netsvc23import logging
2424
25from osv import fields,osv25from osv import fields,osv
26from tools.translate import _26from tools.translate import _
@@ -38,14 +38,14 @@
38 conn = context.get('conn_obj', False)38 conn = context.get('conn_obj', False)
39 ext_shipping_id = conn.call('sales_order_shipment.create', [magento_incrementid, {}, _("Shipping Created"), mail_notification, True])39 ext_shipping_id = conn.call('sales_order_shipment.create', [magento_incrementid, {}, _("Shipping Created"), mail_notification, True])
40 return ext_shipping_id40 return ext_shipping_id
41 41
42 def add_picking_line(self, cr, uid, lines, picking_line, context=None):42 def add_picking_line(self, cr, uid, lines, picking_line, context=None):
43 """ A line to add in the shipping is a dict with : product_id and product_qty keys."""43 """ A line to add in the shipping is a dict with : product_id and product_qty keys."""
44 line_info = {'product_id': picking_line.product_id.id,44 line_info = {'product_id': picking_line.product_id.id,
45 'product_qty': picking_line.product_qty,45 'product_qty': picking_line.product_qty,
46 }46 }
47 lines.append(line_info)47 lines.append(line_info)
48 return lines 48 return lines
4949
50 def create_ext_partial_shipping(self, cr, uid, id, external_referential_id, magento_incrementid, mail_notification=True, context=None):50 def create_ext_partial_shipping(self, cr, uid, id, external_referential_id, magento_incrementid, mail_notification=True, context=None):
51 if context is None: context = {}51 if context is None: context = {}
@@ -57,7 +57,7 @@
57 product_2_item.update({self.pool.get('product.product').extid_to_oeid(cr, uid, item['product_id'], external_referential_id, context={}): item['item_id']})57 product_2_item.update({self.pool.get('product.product').extid_to_oeid(cr, uid, item['product_id'], external_referential_id, context={}): item['item_id']})
58 picking = self.pool.get('stock.picking').browse(cr, uid, id, context)58 picking = self.pool.get('stock.picking').browse(cr, uid, id, context)
59 item_qty = {}59 item_qty = {}
60 60
61 lines = []61 lines = []
62 # get product and quantities to ship from the picking62 # get product and quantities to ship from the picking
63 for line in picking.move_lines:63 for line in picking.move_lines:
@@ -70,7 +70,7 @@
70 item_qty.update({product_2_item[line['product_id']]: line['product_qty']})70 item_qty.update({product_2_item[line['product_id']]: line['product_qty']})
7171
72 ext_shipping_id = conn.call('sales_order_shipment.create', [magento_incrementid, item_qty, _("Shipping Created"), mail_notification, True])72 ext_shipping_id = conn.call('sales_order_shipment.create', [magento_incrementid, item_qty, _("Shipping Created"), mail_notification, True])
73 return ext_shipping_id 73 return ext_shipping_id
7474
75 def create_ext_shipping(self, cr, uid, id, picking_type, external_referential_id, context=None):75 def create_ext_shipping(self, cr, uid, id, picking_type, external_referential_id, context=None):
76 """76 """
@@ -112,18 +112,18 @@
112112
113 def add_ext_tracking_reference(self, cr, uid, id, carrier_id, ext_shipping_id, context=None):113 def add_ext_tracking_reference(self, cr, uid, id, carrier_id, ext_shipping_id, context=None):
114 if context is None: context = {}114 if context is None: context = {}
115 logger = netsvc.Logger()115 logger = logging.getLogger('ext synchro')
116 conn = context.get('conn_obj', False)116 conn = context.get('conn_obj', False)
117 carrier = self.pool.get('delivery.carrier').read(cr, uid, carrier_id, ['magento_carrier_code', 'magento_tracking_title'], context)117 carrier = self.pool.get('delivery.carrier').read(cr, uid, carrier_id, ['magento_carrier_code', 'magento_tracking_title'], context)
118 118
119 if self.pool.get('ir.model.fields').search(cr, uid, [('name', '=', 'carrier_tracking_ref'), ('model', '=', 'stock.picking')]): #OpenERP v6 have the field carrier_tracking_ref on the stock_picking but v5 doesn't have it119 if self.pool.get('ir.model.fields').search(cr, uid, [('name', '=', 'carrier_tracking_ref'), ('model', '=', 'stock.picking')]): #OpenERP v6 have the field carrier_tracking_ref on the stock_picking but v5 doesn't have it
120 carrier_tracking_ref = self.read(cr, uid, id, ['carrier_tracking_ref'], context)['carrier_tracking_ref']120 carrier_tracking_ref = self.read(cr, uid, id, ['carrier_tracking_ref'], context)['carrier_tracking_ref']
121 else:121 else:
122 carrier_tracking_ref = ''122 carrier_tracking_ref = ''
123 123
124 res = conn.call('sales_order_shipment.addTrack', [ext_shipping_id, carrier['magento_carrier_code'], carrier['magento_tracking_title'] or '', carrier_tracking_ref or ''])124 res = conn.call('sales_order_shipment.addTrack', [ext_shipping_id, carrier['magento_carrier_code'], carrier['magento_tracking_title'] or '', carrier_tracking_ref or ''])
125 if res:125 if res:
126 logger.notifyChannel('ext synchro', netsvc.LOG_INFO, "Successfully adding a tracking reference to the shipping with OpenERP id %s and ext id %s in external sale system" % (id, ext_shipping_id))126 logger.info("Successfully adding a tracking reference to the shipping with OpenERP id %s and ext id %s in external sale system", id, ext_shipping_id)
127 return True127 return True
128128
129stock_picking()129stock_picking()