~technofluid-team/openobject-addons/technofluid_multiple_installations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import base64
import dateutil.parser

from xml.etree.ElementTree import ElementTree,Element, SubElement
from datetime import datetime
from StringIO import *
from osv import fields, osv
from ftplib import FTP
from tools.translate import _
import traceback
import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

class exports_landefeld(osv.osv):
    _name = "elneo_landefeld.exports_landefeld"
    _description = "Export history of Landefeld"
    _order = 'name desc'
    _columns = {
                'name': fields.char('Export Reference', size=64, required=True, select=True),
                'type': fields.char('Type', size=64, required=True, select=True),
                'start_date' : fields.datetime('Start Date'),
                'end_date' : fields.datetime('End Date'),
                'status' : fields.selection([('draft', 'Draft'), ('sent', 'Sent'), ('warning', 'Warning'), ('error', 'Error')], string='Status', required=True),
                'log' : fields.text('Log'), 
                'origin':fields.char("Origin", size=255, select=True)
    }
    
    _defaults = {
         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'elneo_landefeld.exports'),        
    }
    
    
    def export_xml_order(self, cr, uid, purchase_order_ids, automatic_landefeld_sale = False, context=None):
        export_landefelds_ids = []
        for purchase_order_id in purchase_order_ids:
            
            status = 'draft'
            origin = ''
            
            #create export_landefelds
            export_landefelds_id = self.create(cr, uid, 
                                               {'type':'ORDER',
                                                'status':status, 
                                                'start_date':datetime.today()
                                                         }, context)
            export_landefelds_ids.append(export_landefelds_id)
            
            
            log = 'Start export at :'+ datetime.today().strftime("%Y-%m-%d %H:%M")+'\n'
            
            try:
            
                #Get Order
                
                purchase_order = self.pool.get('purchase.order').browse(cr, uid, [purchase_order_id], context=context)[0]
                sale_order_id = self.pool.get("sale.order").find_by_purchase_order(cr, uid, purchase_order.id, context)
                if sale_order_id:
                    sale_order = self.pool.get("sale.order").browse(cr, uid, sale_order_id, context)
                else:
                    sale_order = False
                    
                origin = purchase_order.name
                
                if len(purchase_order_ids) == 0:
                    log = log+'Error when loading purchase_order - purchase order does not exist \n'
                else:
                    #fill xml-data
                    #Order
                    order = Element('ORDER')
                    order.attrib["version"] = "2.1"
                    order.attrib["type"] = "express" #Choose the type of delivery : standard, express, release, consignment
                    order.attrib["xmlns:bmecat"] = "http://www.bmecat.org/bmecat/2005"
                    
                    ##Header
                    order_header = SubElement(order, 'ORDER_HEADER')
                    ###Control Info
                    control_info = SubElement(order_header, 'CONTROL_INFO')
                    generation_date = SubElement(control_info, 'GENERATION_DATE')
                    generation_date.text = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+01:00")
                    ###Header info
                    order_info = SubElement(order_header, 'ORDER_INFO')
                    ####ORDER_ID ??
                    order_id = SubElement(order_info, 'ORDER_ID')
                    if sale_order and sale_order.client_order_ref:
                        order_id.text = purchase_order.name+'//'+sale_order.client_order_ref
                    else:
                        order_id.text = purchase_order.name
                    
                    ####ORDER_DATE
                    order_date = SubElement(order_info, 'ORDER_DATE')
                    order_date.text = datetime.strptime(purchase_order.date_order, '%Y-%m-%d').strftime("%Y-%m-%dT%H:%M:%S+01:00")
                    ####PARTIES
                    parties = SubElement(order_info, 'PARTIES')
                    
                    
                    #########Supplier (Landefeld)
                    partner = purchase_order.partner_id
                    addresses = partner.address
                    for address in addresses:
                        if address.type == "default":
                            supplier_idref_value = address.landefeld_ref
                            party = SubElement(parties, 'PARTY')
                            party_id = SubElement(party, 'bmecat:PARTY_ID')
                            party_id.attrib["type"] = "buyer_specific"
                            party_id.text =supplier_idref_value
                            party_role = SubElement(party, 'PARTY_ROLE')
                            party_role.text = "supplier"
                            
                            party_address = SubElement(party, 'ADDRESS')
                            party_address_name = SubElement(party_address, 'bmecat:NAME')
                            party_address_name.text = address.name
                            party_address_street = SubElement(party_address, 'bmecat:STREET')
                            
                            if address.street2:
                                party_address_name2 = SubElement(party_address, 'bmecat:NAME2')
                                party_address_name2.text = address.street
                                party_address_street.text = address.street2
                            else:
                                party_address_street.text = address.street
                                
                            party_address_zip = SubElement(party_address, 'bmecat:ZIP')
                            party_address_zip.text = address.zip
                            party_address_city = SubElement(party_address, 'bmecat:CITY')
                            party_address_city.text = address.city
                            party_address_country = SubElement(party_address, 'bmecat:COUNTRY')
                            party_address_country.text = address.country_id.name
                            party_address_country_coded = SubElement(party_address, 'bmecat:COUNTRY_CODED')
                            party_address_country_coded.text = address.country_id.code
                            break
                    
                    #########Buyer (Elneo)
                    addresses = self.pool.get("res.users").browse(cr, uid, uid, context).company_id.partner_id.address
                    buyer_address = None       
                    buyer_address_invoice = None
                    buyer_address_default = None
                    
                    for address in addresses:
                        if address.type == "invoice":
                            buyer_address_invoice = address
                        if address.type == "default":
                            buyer_address_default = address
                            buyer_idref_value = address.landefeld_ref
                    if buyer_address_invoice:
                        buyer_address = buyer_address_invoice
                    else:
                        buyer_address = buyer_address_default
                                
                                
                    party = SubElement(parties, 'PARTY')
                    party_id = SubElement(party, 'bmecat:PARTY_ID')
                    party_id.attrib["type"] = "supplier_specific"
                    party_id.text =buyer_idref_value
                    party_role = SubElement(party, 'PARTY_ROLE')
                    party_role.text = "buyer"
                    party_address = SubElement(party, 'ADDRESS')
                    party_address_name = SubElement(party_address, 'bmecat:NAME')
                    party_address_name.text = buyer_address.name
                    party_address_street = SubElement(party_address, 'bmecat:STREET')
                    party_address_street.text = buyer_address.street
                    if buyer_address.street2:
                        party_address_street.text = party_address_street.text + buyer_address.street2
                    party_address_zip = SubElement(party_address, 'bmecat:ZIP')
                    party_address_zip.text = buyer_address.zip
                    party_address_city = SubElement(party_address, 'bmecat:CITY')
                    party_address_city.text = buyer_address.city
                    party_address_country = SubElement(party_address, 'bmecat:COUNTRY')
                    party_address_country.text = buyer_address.country_id.name
                    party_address_country_coded = SubElement(party_address, 'bmecat:COUNTRY_CODED')
                    party_address_country_coded.text = buyer_address.country_id.code
                    
                    
                    #########Delivery (Customer)
                    #find elneo delivery address
                    elneo_delivery_address = purchase_order.warehouse_id.lot_stock_id.address_id
                                        
                    if sale_order:
                        if sale_order.landefeld_automatic_sale:
                            origin = origin + ' ' + sale_order.name
                            delivery_address = sale_order.partner_shipping_id
                        else:
                            delivery_address = elneo_delivery_address
                    else:
                        delivery_address = elneo_delivery_address
                        
                    if not delivery_address:
                        raise osv.except_osv(_('OpenTrans ERROR'), _('Can\'t find delivery address.'))
                    
                    party = SubElement(parties, 'PARTY')
                    party_id = SubElement(party, 'bmecat:PARTY_ID')
                    party_id.attrib["type"] = "supplier_specific"
                    if sale_order:
                        party_id.text = delivery_address.landefeld_ref
                    else:
                        party_id.text = ''
                    party_role = SubElement(party, 'PARTY_ROLE')
                    party_role.text = "delivery"
                    
                    party_address = SubElement(party, 'ADDRESS')
                    party_address_name = SubElement(party_address, 'bmecat:NAME')
                    
                    if delivery_address.name:
                        party_address_name.text = delivery_address.name
                    else:
                        party_address_name.text = delivery_address.partner_id.name
                        
                    party_address_street = SubElement(party_address, 'bmecat:STREET')
                    if delivery_address.street2:
                        party_address_name2 = SubElement(party_address, 'bmecat:NAME2')
                        party_address_name2.text = delivery_address.street
                        party_address_street.text = delivery_address.street2
                    else:
                        party_address_street.text = delivery_address.street
                    party_address_zip = SubElement(party_address, 'bmecat:ZIP')
                    party_address_zip.text = delivery_address.zip
                    party_address_city = SubElement(party_address, 'bmecat:CITY')
                    party_address_city.text = delivery_address.city
                    party_address_country = SubElement(party_address, 'bmecat:COUNTRY')
                    party_address_country.text = delivery_address.country_id.name
                    party_address_country_coded = SubElement(party_address, 'bmecat:COUNTRY_CODED')
                    party_address_country_coded.text = delivery_address.country_id.code
                    
                    ####ORDER_PARTIES_REFERENCE
                    order_parties_reference = SubElement(order_info, 'ORDER_PARTIES_REFERENCE')
                    buyer_idref= SubElement(order_parties_reference, 'bmecat:BUYER_IDREF')
                    buyer_idref.text =buyer_idref_value
                    supplier_idref= SubElement(order_parties_reference, 'bmecat:SUPPLIER_IDREF')
                    supplier_idref.text = supplier_idref_value
                    
                    #HEADER_UDX
                    #set neutral if direct delivery to Customer
                    if sale_order and sale_order.landefeld_automatic_sale:
                        header_udx = SubElement(order_info, 'HEADER_UDX')
                        udx_shipment_neutral = SubElement(header_udx, 'UDX_SHIPMENT_NEUTRAL')
                        udx_shipment_neutral.text = 'Standard'
                    
                    ##Items List
                    order_item_list = SubElement(order, 'ORDER_ITEM_LIST')
                    total_item_number_value = 0
                    total_amount_value = 0
                    for purchase_order_line in purchase_order.order_line:
                        total_item_number_value = total_item_number_value+ purchase_order_line.product_qty
                        total_amount_value = total_amount_value+(purchase_order_line.price_unit * purchase_order_line.product_qty)
                        ###Item 
                        order_item = SubElement(order_item_list, 'ORDER_ITEM')
                        ###LINE Item 
                        line_item_id = SubElement(order_item, 'LINE_ITEM_ID')
                        line_item_id.text = str(purchase_order_line.id)
                        ###product 
                        product_id = SubElement(order_item, 'PRODUCT_ID')
                        supplier_pid = SubElement(product_id, 'bmecat:SUPPLIER_PID')
                        supplier_pid.attrib["type"] = "supplier_specific"
                        for supplier in purchase_order_line.product_id.seller_ids:
                            if partner.id == supplier.name.id:
                                supplier_pid.text =  supplier.product_code
                        description_short = SubElement(product_id, 'bmecat:DESCRIPTION_SHORT')
                        description_short.text = purchase_order_line.name
                        ###quantity
                        quantity = SubElement(order_item, 'QUANTITY')
                        quantity.text = str(purchase_order_line.product_qty)
                        ###order_unit
                        order_unit = SubElement(order_item, 'bmecat:ORDER_UNIT')
                        order_unit.text = purchase_order_line.product_uom.name='PCE' and 'pc.' or purchase_order_line.product_uom.name
                        ###price line amount
                        price_line_amount = SubElement(order_item, 'PRICE_LINE_AMOUNT')
                        price_line_amount.text = str(purchase_order_line.price_unit * purchase_order_line.product_qty)
                        
        
                    
                    ##Summary
                    order_summary = SubElement(order, 'ORDER_SUMMARY')    
                    total_item_num = SubElement(order_summary, 'TOTAL_ITEM_NUM')
                    total_item_num.text = str(total_item_number_value)
                    total_amount = SubElement(order_summary, 'TOTAL_AMOUNT')
                    total_amount.text = str(total_amount_value)
                    
                    #write xml-file 
                    filename = '%s-%s-%s.xml' % (
                            purchase_order.name, 
                            datetime.today().strftime("%Y%m%d"),
                            str(export_landefelds_id).zfill(7)[-7:],
                        )
                    
                    file_buffer =  StringIO()
                    ElementTree(order).write(file_buffer, xml_declaration=True,  encoding="utf-8")
                    
                     
                    #create attachment 
                    att_id = self.pool.get('ir.attachment').create(cr, uid, {
                        'res_id': export_landefelds_id,
                        'res_model': self._name,
                        'name': filename,
                        'datas_fname':filename, 
                        'datas': base64.encodestring(file_buffer.getvalue()),
                    }, context=context)
             
                
                #update log for export_landefelds
                if status != 'error':
                    status = 'draft'
                self.write(cr, uid,export_landefelds_id, 
                                                   {'log' : 'File generated at ' + datetime.today().strftime("%Y-%m-%d %H:%M"),
                                                    'status':status, 
                                                    'end_date':datetime.today(), 
                                                    'origin':origin
                                                             }, context)
                
            except osv.except_osv, e:
                #update log for import_landefelds
                log = log + '\n Error when creating OpenTrans file : '+str(e)+'\n'+traceback.format_exc()    
                status = "error"
                self.write(cr, uid,export_landefelds_id, 
                                                   {'log' : log+'\n '+unicode(e.value),
                                                    'status':'error',
                                                    'origin':origin 
                                                    }, context)
                   
        self.send_export_landefeld(cr, uid, export_landefelds_ids, context) 
            
                
        return export_landefelds_ids
    
    
    def send_export_landefeld(self, cr, uid, ids, context=None):
        # Create an instance of the FTP object  
        isPassive = False
        port = 21
        dirname = '/ftp62360/in'               # remote directory to fetch from
        host = 'fw.landefeld.de'                # adresse du serveur FTP
        user = 'ftp62360'                       # votre identifiant
        password = 'HB579@int6'                    # votre mot de passe


        for export_landefeld in self.browse(cr, uid, ids, context):
            log = export_landefeld.log
            if not log:
                log = ''
            status = export_landefeld.status
            
            try:                                    
                #find attachment
                attachment_ids = self.pool.get('ir.attachment').search(cr, uid, [('res_id','=',export_landefeld.id),('res_model','=',self._name)])
                attach_to_send = []
                for attachment in self.pool.get('ir.attachment').browse(cr, uid, attachment_ids, context=context):
                    if attachment.datas:
                        attach_to_send.append((attachment.datas_fname, StringIO(base64.decodestring(attachment.datas))))
                        
                #send by email
                '''
                email_pool = self.pool.get("email_template.mailbox")
                mail_id = email_pool.create(cr, uid, {
                    'email_from':'info@elneo.com', 
                    'email_to':'edi@landefeld.de', 
                    'email_cc':'cth@elneo.com', 
                    'subject':'OpenTrans order', 
                    'body_text':'',
                    'account_id':1,
                    'attachments_ids':[(4,att_id) for att_id in attachment_ids] 
                }, context=context)
                email_pool.send_this_mail(cr, uid, [mail_id], context)
                '''
                
                #send by FTP
                connection=FTP()                    
                connection.set_pasv(isPassive)
                connection.connect(host,port,3)
                connection.login(user,password)
                
                connection.cwd(dirname)                
                
                for attach in attach_to_send:
                    connection.storlines("STOR " + attach[0], attach[1])
                
                connection.quit()
            
                
                #update log for export_landefelds
                if status != 'error':
                    status = 'sent'
                self.write(cr, uid,export_landefeld.id, 
                                                   {'log' : 'File sent at ' + datetime.today().strftime("%Y-%m-%d %H:%M"),
                                                    'status':status, 
                                                    'end_date':datetime.today()
                                                             }, context)
                
            except Exception, e:
                #update log for import_landefelds
                log = log + '\n Error when sending OpenTrans file to FTP : '
                if str(e):
                    log = log + str(e)
                if traceback.format_exc():
                    log = log + '\n'+traceback.format_exc()    
                status = "error"
                self.write(cr, uid,export_landefeld.id, 
                                                   {'log' : log+'\n '+str(e),
                                                    'status':'error', 
                                                    }, context)   
            
    
    
exports_landefeld()