1
# -*- encoding: utf-8 -*-
2
############################################################################################
4
# OpenERP, Open Source Management Solution
5
# Copyright (C) 2010 Zikzakmedia S.L. (<http://www.zikzakmedia.com>). All Rights Reserved
8
# This program is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 3 of the License, or
11
# (at your option) any later version.
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with this program. If not, see <http://www.gnu.org/licenses/>.
21
############################################################################################
23
from osv import fields,osv
24
from tools.translate import _
32
from urllib2 import Request, urlopen, URLError, HTTPError
33
from ftplib import FTP
35
class product_icecat_wizard(osv.osv_memory):
36
_name = 'product.icecat.wizard'
39
'name':fields.boolean('Name'),
40
'description':fields.boolean('Description'),
41
'description_sale':fields.boolean('Description Śale'),
42
'language_id': fields.many2one('res.lang','Language'),
43
'image':fields.boolean('Image'),
44
'html':fields.boolean('HTML Code'),
45
'result': fields.text('Result', readonly=True),
46
'resimg': fields.text('Image', readonly=True),
47
'state':fields.selection([
54
'state': lambda *a: 'first',
56
'description': lambda *a: 1,
57
'description_sale': lambda *a: 1,
61
# ==========================================
62
# save XML file into product_icecat/xml dir
63
# ==========================================
64
def save_file(self, name, value):
65
path = os.path.abspath( os.path.dirname(__file__) )
66
path += '/icecat/%s' % name
67
path = re.sub('wizard/', '', path)
75
# ==========================================
76
# Convert HTML to text
77
# ==========================================
78
def StripTags(self, text):
82
start = text.find("<")
84
stop = text[start:].find(">")
86
text = text[:start] + text[start+stop+1:]
90
# ==========================================
91
# Convert icecat values to OpenERP mapline
92
# ==========================================
93
def icecat2oerp(self, cr, uid, form, product, icecat, pathxml, language, data, context):
95
if form.language_id.code:
96
language = form.language_id.code
98
doc = libxml2.parseFile(pathxml)
100
for prod in doc.xpathEval('//Product'):
101
if prod.xpathEval('@ErrorMessage'):
102
if prod.xpathEval('@ErrorMessage')[0].content:
103
return prod.xpathEval('@ErrorMessage')[0].content
107
short_summary = doc.xpathEval('//SummaryDescription//ShortSummaryDescription')
108
long_summary = doc.xpathEval('//SummaryDescription//LongSummaryDescription')
110
short_description = short_summary[0].content
111
description = long_summary[0].content
112
name = description.split('.')[0]
114
for prod in doc.xpathEval('//ProductDescription'):
115
if prod.xpathEval('@ShortDesc'):
116
short_description = prod.xpathEval('@ShortDesc')[0].content
117
if prod.xpathEval('@LongDesc'):
118
description = prod.xpathEval('@LongDesc')[0].content
120
# product details category
123
for cat in doc.xpathEval('//CategoryFeatureGroup'):
124
categoryId.append(cat.xpathEval('@ID')[0].content)
126
for cat in doc.xpathEval('//CategoryFeatureGroup//FeatureGroup//Name'):
127
categoryName.append(cat.xpathEval('@Value')[0].content)
129
# join categorys lists
130
category = zip(categoryId,categoryName)
132
# product details feature
136
for prod in doc.xpathEval('//ProductFeature'):
137
prodFeatureId.append(prod.xpathEval('@CategoryFeatureGroup_ID')[0].content+"#"+prod.xpathEval('@Presentation_Value')[0].content)
139
for prod in doc.xpathEval('//ProductFeature//Feature//Name'):
140
prodFeatureName.append(prod.xpathEval('@Value')[0].content)
142
# ordered id, name & description Product Feature
145
for feature in prodFeatureId:
146
if not prodFeatureName[i] == 'Source data-sheet':
147
values = feature.split('#')
150
elif values[1] == "N":
154
if values[0] not in prodFeature:
155
prodFeature[values[0]] = []
156
prodFeature[values[0]].append('<strong>'+prodFeatureName[i]+':</strong>'+' '+value)
159
mapline_ids = self.pool.get('product.icecat.mapline').search(cr, uid, [('icecat_id', '=', icecat.id)])
161
for mapline_id in mapline_ids:
162
mapline = self.pool.get('product.icecat.mapline').browse(cr, uid, mapline_id)
163
mapline_fields.append({'icecat':mapline.name,'oerp':mapline.field_id.name})
165
#show details product
166
#TODO: HTML template use Mako template for not hardcode HTML tags
171
if catID in prodFeature and len(prodFeature[catID]):
172
for mapline_field in mapline_fields:
173
if mapline_field['icecat'] == catID:
174
source = '<h3>%s</h3>' % catName
176
for feature in prodFeature[catID]:
179
source += '<li>%s</li>' % feature
183
source = self.StripTags(source)
184
mapline_values.append({'field':mapline_field['oerp'],'source':source})
185
# This is not hardcode. Short description is avaible in antother fields, for example meta_description website fields (magento, djnago,...)
186
if mapline_field['icecat'] == 'ShortSummaryDescription':
187
mapline_values.append({'field':mapline_field['oerp'],'source':short_description})
189
# update icecat values at product
190
# default values. It is not hardcode ;)
194
trans_name_id = self.pool.get('ir.translation').search(cr, uid, [('lang', '=', language),('name','=','product.template,name'),('res_id','=',product.id)])
196
self.pool.get('ir.translation').write(cr, uid, trans_name_id, {'value': name}, context)
198
values['name'] = name
200
if form.description_sale:
201
trans_descsale_id = self.pool.get('ir.translation').search(cr, uid, [('lang', '=', language),('name','=','product.template,description_sale'),('res_id','=',product.id)])
202
if trans_descsale_id:
203
self.pool.get('ir.translation').write(cr, uid, trans_descsale_id, {'value': short_description}, context)
205
values['description_sale'] = short_description
209
description = self.StripTags(description)
210
trans_description_id = self.pool.get('ir.translation').search(cr, uid, [('lang', '=', language),('name','=','product.template,description'),('res_id','=',product.id)])
211
if trans_description_id:
212
self.pool.get('ir.translation').write(cr, uid, trans_description_id, {'value': description}, context)
214
values['description'] = description
216
# add mapline values calculated
217
for mapline_value in mapline_values:
218
values[mapline_value['field']] = mapline_value['source']
220
self.pool.get('product.product').write(cr, uid, [product.id], values, context)
222
result = _("Product %s XML Import successfully") % name
226
# ==========================================
227
# Convert icecat values to OpenERP mapline
228
# ==========================================
229
def iceimg2oerpimg(self, cr, uid, form, product, icecat, pathxml, data, context):
230
doc = libxml2.parseFile(pathxml)
233
for prod in doc.xpathEval('//Product'):
234
if prod.xpathEval('@HighPic'):
235
image = prod.xpathEval('@HighPic')[0].content
238
fname = image.split('/')
239
fname = fname[len(fname)-1]
241
path = os.path.abspath( os.path.dirname(__file__) )
242
path += '/icecat/%s' % fname
243
path = re.sub('wizard/', '', path)
246
urllib.urlretrieve(image, path)
249
ftp = FTP(icecat.ftpip)
250
ftp.login(icecat.ftpusername, icecat.ftppassword)
251
ftp.cwd(icecat.ftpdirectory)
253
ftp.storbinary('STOR '+os.path.basename(path),f)
256
# add values into product_image
258
long_summary = doc.xpathEval('//SummaryDescription//LongSummaryDescription')
259
description = long_summary[0].content
260
name = description.split('.')[0]
265
'filename': icecat.ftpurl+fname,
266
'product_id': product.id,
268
self.pool.get('product.images').create(cr, uid, values, context)
269
return icecat.ftpurl+fname
271
return _("Not exist %s image") % fname
273
# ==========================================
275
# =========================================
276
def import_xml(self, cr, uid, ids, data, context={}):
277
icecat_id = self.pool.get('product.icecat').search(cr, uid, [('active', '=', 1)])[0]
278
icecat = self.pool.get('product.icecat').browse(cr, uid, icecat_id)
280
form = self.browse(cr, uid, ids[0])
282
if not form.language_id:
283
language = self.pool.get('res.users').browse(cr, uid, uid).context_lang
284
lang = language.split('_')[0]
286
language = form.language_id.code
287
lang = language.split('_')[0]
291
for prod in data['active_ids']:
292
product = self.pool.get('product.product').browse(cr, uid, prod)
296
url = 'http://data.icecat.biz/xml_s3/xml_server3.cgi?ean_upc=%s;lang=%s;output=productxml' % (ean, lang)
297
fileName = '%s.xml' % ean
299
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
300
# this creates a password manager
301
passman.add_password(None, url, icecat.username, icecat.password)
303
authhandler = urllib2.HTTPBasicAuthHandler(passman)
304
# create the AuthHandler
306
openerp = urllib2.build_opener(authhandler)
308
urllib2.install_opener(openerp)
309
# All calls to urllib2.urlopen will now use our handler
312
pagehandle = urllib2.urlopen(url)
313
req = urllib2.Request(url)
314
handle = urllib2.urlopen(req)
315
content = handle.read()
317
pathxml = self.save_file( fileName, content )
318
#import values icecat2oerp
319
result = self.icecat2oerp(cr, uid, form, product, icecat, pathxml, language, data, context)
320
#import image icecat2oerp
321
if icecat.ftp and form.image:
322
resimg += self.iceimg2oerpimg(cr, uid, form, product, icecat, pathxml, data, context)
325
resimg += _("Import image not avaible")
330
result = _("EAN not avaible")
338
self.write(cr, uid, ids, values)
342
product_icecat_wizard()