~romaindeheele/openobject-addons/extra-trunk

« back to all changes in this revision

Viewing changes to product_icecat/wizard/wizard_product_icecat.py

  • Committer: Jordi Esteve
  • Date: 2010-12-20 08:34:37 UTC
  • Revision ID: jesteve@zikzakmedia.com-20101220083437-b7motey64o4p8h07
[ADD] Product Icecat: Import XML from icecat.biz to products

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- encoding: utf-8 -*-
 
2
############################################################################################
 
3
#
 
4
#    OpenERP, Open Source Management Solution   
 
5
#    Copyright (C) 2010 Zikzakmedia S.L. (<http://www.zikzakmedia.com>). All Rights Reserved
 
6
#    $Id$
 
7
#
 
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.
 
12
#
 
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.
 
17
#
 
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/>.
 
20
#
 
21
############################################################################################
 
22
 
 
23
from osv import fields,osv
 
24
from tools.translate import _
 
25
 
 
26
import os
 
27
import re
 
28
import cgi
 
29
import libxml2
 
30
import urllib
 
31
import urllib2
 
32
from urllib2 import Request, urlopen, URLError, HTTPError
 
33
from ftplib import FTP
 
34
 
 
35
class product_icecat_wizard(osv.osv_memory):
 
36
    _name = 'product.icecat.wizard'
 
37
 
 
38
    _columns = {
 
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([
 
48
            ('first','First'),
 
49
            ('done','Done'),
 
50
        ],'State'),
 
51
    }
 
52
 
 
53
    _defaults = {
 
54
        'state': lambda *a: 'first',
 
55
        'name': lambda *a: 1,
 
56
        'description': lambda *a: 1,
 
57
        'description_sale': lambda *a: 1,
 
58
        'html': lambda *a: 1,
 
59
    }
 
60
 
 
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)
 
68
        f = open( path, 'w' )
 
69
        try:
 
70
            f.write(value)
 
71
        finally:
 
72
            f.close()
 
73
        return path
 
74
 
 
75
    # ==========================================
 
76
    # Convert HTML to text
 
77
    # ==========================================
 
78
    def StripTags(self, text): 
 
79
         finished = 0 
 
80
         while not finished: 
 
81
             finished = 1 
 
82
             start = text.find("<") 
 
83
             if start >= 0: 
 
84
                 stop = text[start:].find(">") 
 
85
                 if stop >= 0: 
 
86
                     text = text[:start] + text[start+stop+1:] 
 
87
                     finished = 0 
 
88
         return text
 
89
 
 
90
    # ==========================================
 
91
    # Convert icecat values to OpenERP mapline
 
92
    # ==========================================
 
93
    def icecat2oerp(self, cr, uid, form, product, icecat, pathxml, language, data, context):
 
94
 
 
95
        if form.language_id.code:
 
96
            language = form.language_id.code
 
97
 
 
98
        doc = libxml2.parseFile(pathxml)
 
99
 
 
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
 
104
                    exit
 
105
 
 
106
        # product info
 
107
        short_summary = doc.xpathEval('//SummaryDescription//ShortSummaryDescription')
 
108
        long_summary = doc.xpathEval('//SummaryDescription//LongSummaryDescription')
 
109
 
 
110
        short_description = short_summary[0].content
 
111
        description = long_summary[0].content
 
112
        name = description.split('.')[0]
 
113
 
 
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
 
119
 
 
120
        # product details category
 
121
        categoryId  = []
 
122
        categoryName  = []
 
123
        for cat in doc.xpathEval('//CategoryFeatureGroup'):
 
124
            categoryId.append(cat.xpathEval('@ID')[0].content)
 
125
 
 
126
        for cat in doc.xpathEval('//CategoryFeatureGroup//FeatureGroup//Name'):
 
127
            categoryName.append(cat.xpathEval('@Value')[0].content)
 
128
 
 
129
        # join categorys lists
 
130
        category = zip(categoryId,categoryName)
 
131
 
 
132
        # product details feature
 
133
        prodFeatureId  = []
 
134
        prodFeatureName = []
 
135
        values = {}
 
136
        for prod in doc.xpathEval('//ProductFeature'):
 
137
            prodFeatureId.append(prod.xpathEval('@CategoryFeatureGroup_ID')[0].content+"#"+prod.xpathEval('@Presentation_Value')[0].content)
 
138
 
 
139
        for prod in doc.xpathEval('//ProductFeature//Feature//Name'):
 
140
            prodFeatureName.append(prod.xpathEval('@Value')[0].content)
 
141
 
 
142
        # ordered id, name & description Product Feature
 
143
        prodFeature = {}
 
144
        i = 0
 
145
        for feature in prodFeatureId:
 
146
            if not prodFeatureName[i] == 'Source data-sheet':
 
147
                values = feature.split('#')
 
148
                if values[1] == "Y":
 
149
                    value = _("Yes")
 
150
                elif values[1] == "N":
 
151
                    value = _("No")
 
152
                else:
 
153
                    value = values[1]
 
154
                if values[0] not in prodFeature:
 
155
                    prodFeature[values[0]] = []
 
156
                prodFeature[values[0]].append('<strong>'+prodFeatureName[i]+':</strong>'+' '+value)
 
157
            i += 1
 
158
 
 
159
        mapline_ids = self.pool.get('product.icecat.mapline').search(cr, uid, [('icecat_id', '=', icecat.id)])
 
160
        mapline_fields = []
 
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})
 
164
 
 
165
        #show details product
 
166
        #TODO: HTML template use Mako template for not hardcode HTML tags
 
167
        mapline_values = []
 
168
        for cat in category:
 
169
            catID = cat[0]
 
170
            catName = cat[1]
 
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
 
175
                        i = True
 
176
                        for feature in prodFeature[catID]:
 
177
                            if i == True:
 
178
                                source += '<ul>'
 
179
                            source += '<li>%s</li>' % feature
 
180
                            i = False
 
181
                        source += '</ul>'
 
182
                        if not form.html:
 
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})
 
188
 
 
189
        # update icecat values at product
 
190
        # default values. It is not hardcode ;)
 
191
        values = {}
 
192
 
 
193
        if form.name:
 
194
            trans_name_id = self.pool.get('ir.translation').search(cr, uid, [('lang', '=', language),('name','=','product.template,name'),('res_id','=',product.id)])
 
195
            if trans_name_id:
 
196
                self.pool.get('ir.translation').write(cr, uid, trans_name_id, {'value': name}, context)
 
197
            else:
 
198
                values['name'] = name
 
199
 
 
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)
 
204
            else:
 
205
                values['description_sale'] = short_description
 
206
 
 
207
        if form.description:
 
208
            if not form.html:
 
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)
 
213
            else:
 
214
                values['description'] = description
 
215
 
 
216
        # add mapline values calculated
 
217
        for mapline_value in mapline_values:
 
218
            values[mapline_value['field']] = mapline_value['source']
 
219
        
 
220
        self.pool.get('product.product').write(cr, uid, [product.id], values, context)
 
221
 
 
222
        result = _("Product %s XML Import successfully") % name
 
223
 
 
224
        return result
 
225
 
 
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)
 
231
 
 
232
        #product image
 
233
        for prod in doc.xpathEval('//Product'):
 
234
            if prod.xpathEval('@HighPic'):
 
235
                image = prod.xpathEval('@HighPic')[0].content
 
236
 
 
237
        if image:
 
238
            fname = image.split('/')
 
239
            fname = fname[len(fname)-1]
 
240
 
 
241
            path = os.path.abspath( os.path.dirname(__file__) )
 
242
            path += '/icecat/%s' % fname
 
243
            path = re.sub('wizard/', '', path)
 
244
 
 
245
            #download image
 
246
            urllib.urlretrieve(image, path)
 
247
 
 
248
            #send ftp server
 
249
            ftp = FTP(icecat.ftpip)
 
250
            ftp.login(icecat.ftpusername, icecat.ftppassword)
 
251
            ftp.cwd(icecat.ftpdirectory)
 
252
            f=file(path,'rb')
 
253
            ftp.storbinary('STOR '+os.path.basename(path),f)
 
254
            ftp.quit()
 
255
 
 
256
            # add values into product_image
 
257
            # product info
 
258
            long_summary = doc.xpathEval('//SummaryDescription//LongSummaryDescription')
 
259
            description = long_summary[0].content
 
260
            name = description.split('.')[0]
 
261
 
 
262
            values = {
 
263
                'name': name,
 
264
                'link': 1,
 
265
                'filename': icecat.ftpurl+fname,
 
266
                'product_id': product.id,
 
267
            }
 
268
            self.pool.get('product.images').create(cr, uid, values, context)
 
269
            return icecat.ftpurl+fname
 
270
        else:
 
271
            return _("Not exist %s image") % fname
 
272
 
 
273
    # ==========================================
 
274
    # wizard
 
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)
 
279
 
 
280
        form = self.browse(cr, uid, ids[0])
 
281
 
 
282
        if not form.language_id:
 
283
            language =  self.pool.get('res.users').browse(cr, uid, uid).context_lang
 
284
            lang = language.split('_')[0]
 
285
        else:
 
286
            language = form.language_id.code
 
287
            lang = language.split('_')[0]
 
288
 
 
289
        resimg = ''
 
290
 
 
291
        for prod in data['active_ids']:
 
292
            product = self.pool.get('product.product').browse(cr, uid, prod)
 
293
            ean = product.ean13
 
294
 
 
295
            if ean:
 
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
 
298
 
 
299
                passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
 
300
                # this creates a password manager
 
301
                passman.add_password(None, url, icecat.username, icecat.password)
 
302
 
 
303
                authhandler = urllib2.HTTPBasicAuthHandler(passman)
 
304
                # create the AuthHandler
 
305
 
 
306
                openerp = urllib2.build_opener(authhandler)
 
307
 
 
308
                urllib2.install_opener(openerp)
 
309
                # All calls to urllib2.urlopen will now use our handler
 
310
 
 
311
                try:
 
312
                    pagehandle = urllib2.urlopen(url)
 
313
                    req = urllib2.Request(url)
 
314
                    handle = urllib2.urlopen(req)
 
315
                    content = handle.read()
 
316
                    #save file
 
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)
 
323
                        resimg += "\n"
 
324
                    else:
 
325
                        resimg += _("Import image not avaible")
 
326
                        resimg += "\n"
 
327
                except URLError, e:
 
328
                    result = e.code
 
329
            else:
 
330
                result = _("EAN not avaible")
 
331
                resimg = False
 
332
 
 
333
        values = {
 
334
            'state':'done',
 
335
            'result':result,
 
336
            'resimg':resimg,
 
337
        }
 
338
        self.write(cr, uid, ids, values)
 
339
 
 
340
        return True
 
341
 
 
342
product_icecat_wizard()