~serpent-consulting-services/openerp-usa/fix-shipping_api_ups_cc

« back to all changes in this revision

Viewing changes to shipping_api_ups/stock_certify.py

  • Committer: npgllc
  • Date: 2012-08-02 17:13:27 UTC
  • Revision ID: npgllc-20120802171327-2xgyyjjb5d1kx26y
Removed all the 6.0 compatible modules

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- coding: utf-8 -*-
2
 
##############################################################################
3
 
#
4
 
#    OpenERP, Open Source Management Solution
5
 
#    Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
6
 
#    Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
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
 
 
24
 
from osv import fields,osv
25
 
from xml.dom.minidom import Document
26
 
from tools.translate import _
27
 
import httplib
28
 
import xml2dic
29
 
import base64
30
 
import time
31
 
import datetime
32
 
from urlparse import urlparse
33
 
import Image
34
 
import tempfile
35
 
import re
36
 
 
37
 
from mako.template import Template
38
 
from mako import exceptions
39
 
import netsvc
40
 
import base64
41
 
import logging
42
 
import tools
43
 
 
44
 
pack_type={'01' : 'UPS Letter',
45
 
'02' : 'Customer Supplied Package',
46
 
'03' : 'Tube',
47
 
'04' : 'PAK',
48
 
'21' : 'UPS ExpressBox',
49
 
'24' : 'UPS 25KG Box',
50
 
'25' : 'UPS 10KG Box',
51
 
'30' : 'Pallet',
52
 
'2a' : 'Small Express Box',
53
 
'2b' : 'Medium Express Box',
54
 
'2c' : 'Large Express Box'}
55
 
 
56
 
 
57
 
 
58
 
class shipping_move(osv.osv):
59
 
    _inherit = "shipping.move"
60
 
    _columns = {
61
 
 
62
 
            'shipment_identific_no': fields.char('ShipmentIdentificationNumber', size=64, ),
63
 
            'logo':fields.binary('Logo'),
64
 
            'tracking_url':fields.char('Tracking URL', size=512, ),
65
 
            'service': fields.many2one('ups.shipping.service.type', 'Shipping Service'),
66
 
 
67
 
             }
68
 
    def print_label(self, cr, uid, ids, context=None):
69
 
        if not ids: return []
70
 
 
71
 
        return {
72
 
            'type': 'ir.actions.report.xml',
73
 
            'report_name':'ship.log.label.print',
74
 
            'datas': {
75
 
                    'model':'shipping.move',
76
 
                    'id': ids and ids[0] or False,
77
 
                    'ids': ids and ids or [],
78
 
                    'report_type': 'pdf'
79
 
                },
80
 
            'nodestroy': True
81
 
            }
82
 
    def getTrackingUrl(self,cr, uid, ids, context=None):
83
 
        ship_log_obj = self.browse(cr, uid, ids[0], context=context)
84
 
        if ship_log_obj.tracking_no:
85
 
            tracking_url = """http://wwwapps.ups.com/WebTracking/processInputRequest?sort_by=status&tracknums_displayed=1&TypeOfInquiryNumber=T&loc=en_US&InquiryNumber1=%s&track.x=0&track.y=0""" % ship_log_obj.tracking_no
86
 
 
87
 
 
88
 
shipping_move()
89
 
 
90
 
 
91
 
 
92
 
class stock_picking(osv.osv):
93
 
 
94
 
    _inherit = "stock.picking"
95
 
    def _get_company_code(self, cr, user, context=None):
96
 
        res =  super(stock_picking, self)._get_company_code(cr, user, context=context)
97
 
        res.append(('ups', 'UPS'))
98
 
        return res
99
 
    _columns={
100
 
            'ups_service': fields.many2one('ups.shipping.service.type','Service',help='The specific shipping service offered'),
101
 
            'shipper': fields.many2one('ups.account.shipping','Shipper',help='The specific user ID and shipper. Setup in the company configuration.'),
102
 
            'shipment_digest': fields.text('ShipmentDigest'),
103
 
            'negotiated_rates': fields.float('NegotiatedRates'),
104
 
            'shipment_identific_no': fields.char('ShipmentIdentificationNumber', size=64, ),
105
 
            'tracking_no': fields.char('TrackingNumber', size=64, ),
106
 
            
107
 
            'trade_mark': fields.related('shipper','trademark',type='char',size=1024,string='Trademark'),
108
 
            'ship_company_code': fields.selection(_get_company_code, 'Ship Company', method=True,  size=64),
109
 
             }
110
 
    
111
 
    def action_process(self, cr, uid, ids, context=None):
112
 
        deliv_order = self.browse(cr, uid, type(ids)==type([]) and ids[0] or ids, context=context)
113
 
        do_transaction = True
114
 
        if deliv_order.sale_id and deliv_order.sale_id.payment_method == 'cc_pre_auth' and not deliv_order.sale_id.invoiced:
115
 
            
116
 
            rel_voucher_id = deliv_order.sale_id.rel_account_voucher_id and deliv_order.sale_id.rel_account_voucher_id.id or False
117
 
            if rel_voucher_id and deliv_order.sale_id.rel_account_voucher_id.state != 'posted' and deliv_order.sale_id.rel_account_voucher_id.cc_auth_code:
118
 
                do_transaction = False
119
 
                self.pool.get('account.voucher').write(cr,uid,[rel_voucher_id],{'cc_p_authorize':False,'cc_charge':True})
120
 
                do_transaction = self.pool.get('account.voucher').authorize(cr, uid, [rel_voucher_id], context=context)
121
 
        if  not do_transaction:
122
 
            self.write(cr,uid,ids,{'ship_state':'hold','ship_message':'Unable to process creditcard payment.'})
123
 
            cr.commit()
124
 
            raise osv.except_osv(_('Final credit card charge cannot be completed!'),_("Please hold shipment and contact customer service..") )
125
 
        return super(stock_picking, self).action_process(cr, uid, ids, context=context)
126
 
    
127
 
    def action_done(self, cr, uid, ids, context=None):
128
 
 
129
 
        res = super(stock_picking, self).action_done(cr, uid, ids, context=context)
130
 
        if ids:
131
 
            for stock_pick_obj in self.pool.get('stock.picking').browse(cr,uid,ids):
132
 
                vals={}
133
 
                if stock_pick_obj.sale_id:
134
 
                    if stock_pick_obj.sale_id.ship_method:
135
 
                        ups_shipping_service_type_ids=self.pool.get('ups.shipping.service.type').search(cr,uid,[('description','like',stock_pick_obj.sale_id.ship_method)])
136
 
                        if ups_shipping_service_type_ids:
137
 
                          vals['ups_service']=ups_shipping_service_type_ids[0]
138
 
                          ups_shipping_service_type_obj=self.pool.get('ups.shipping.service.type').browse(cr,uid,ups_shipping_service_type_ids[0])
139
 
                          if ups_shipping_service_type_obj.ups_account_id:
140
 
                            vals['shipper']=ups_shipping_service_type_obj.ups_account_id.id
141
 
                            if ups_shipping_service_type_obj.ups_account_id.logistic_company_id:
142
 
                                vals['logis_company']=ups_shipping_service_type_obj.ups_account_id.logistic_company_id.id
143
 
                if vals:
144
 
                    self.write(cr,uid,ids,vals)
145
 
        return True
146
 
 
147
 
 
148
 
    def on_change_sale_id(self, cr, uid, ids, sale_id=False, state=False, context=None):
149
 
            vals={}
150
 
            if sale_id:
151
 
                sale_order_obj=self.pool.get('sale.order').browse(cr,uid,sale_id)
152
 
                ups_shipping_service_ids=self.pool.get('ups.shipping.service.type').search(cr,uid,[('description','=',sale_order_obj.ship_method)])
153
 
 
154
 
                if type(ups_shipping_service_ids)==type([]) and len(ups_shipping_service_ids)>0:
155
 
                      vals['ups_service']=ups_shipping_service_ids[0]
156
 
                      ups_shipping_account_ids=self.pool.get('ups.account.shipping').search(cr,uid,[('ups_shipping_service_ids','in',ups_shipping_service_ids[0])])
157
 
 
158
 
                      if type(ups_shipping_account_ids)==type([]) and len(ups_shipping_account_ids)>0:
159
 
                        vals['shipper']=ups_shipping_account_ids[0]
160
 
                        logistic_company_ids=self.pool.get('logistic.company').search(cr,uid,[('ups_shipping_account_ids','in',ups_shipping_account_ids[0])])
161
 
 
162
 
                        if type(logistic_company_ids)==type([]) and len(logistic_company_ids)>0:
163
 
                            vals['logis_company']=logistic_company_ids[0]
164
 
 
165
 
            return {'value':vals}
166
 
 
167
 
 
168
 
    def process_void(self,cr, uid, ids, context=None):
169
 
        
170
 
        error_flag = False
171
 
        if type(ids)==type([]):
172
 
            pick_obj=self.pool.get('stock.picking').browse(cr, uid, ids[0])
173
 
        else:
174
 
            pick_obj=self.pool.get('stock.picking').browse(cr, uid, ids)
175
 
 
176
 
        if pick_obj.ship_company_code != 'ups':
177
 
            return super(stock_picking, self).process_void(cr, uid, ids, context=context)
178
 
 
179
 
###create the acces req xml first
180
 
        data_for_Access_Request={
181
 
                                    'AccessLicenseNumber':pick_obj.shipper.id and pick_obj.shipper.accesslicensenumber or '',
182
 
                                    'UserId':pick_obj.shipper.id and pick_obj.shipper.userid or '',
183
 
                                    'Password':pick_obj.shipper.id and pick_obj.shipper.password or ''
184
 
                                }
185
 
        response = ''
186
 
        for pack in pick_obj.packages_ids:
187
 
 
188
 
            data_for_void_shipment={'VoidShipmentRequest':{'Request':{
189
 
                                                        'RequestAction':"1",
190
 
                                                      'TransactionReference':{'CustomerContext':"",},
191
 
                                                      },
192
 
                                            'ShipmentIdentificationNumber':pick_obj.logis_company.test_mode and '1Z2220060294314162' or pack.shipment_identific_no or '',
193
 
 
194
 
                                                'ExpandedVoidShipment':{
195
 
                                                                        'ShipmentIdentificationNumber':pick_obj.logis_company.test_mode and  '1Z2220060294314162' or pack.shipment_identific_no or '',
196
 
                                                                        'TrackingNumber':pick_obj.logis_company.test_mode and '1Z2220060291994175' or pack.tracking_no or ''
197
 
                                                                        }
198
 
                                                            }
199
 
                                            }
200
 
 
201
 
 
202
 
            doc2=Document()
203
 
            VoidShipmentRequest = doc2.createElement("VoidShipmentRequest")
204
 
            doc2.appendChild(VoidShipmentRequest)
205
 
 
206
 
            Request = doc2.createElement("Request")
207
 
            VoidShipmentRequest.appendChild(Request)
208
 
 
209
 
 
210
 
            RequestAction = doc2.createElement("RequestAction")
211
 
            ptext = doc2.createTextNode(data_for_void_shipment["VoidShipmentRequest"]['Request']['RequestAction'])
212
 
            RequestAction.appendChild(ptext)
213
 
            Request.appendChild(RequestAction)
214
 
 
215
 
            TransactionReference = doc2.createElement("TransactionReference")
216
 
            Request.appendChild(TransactionReference)
217
 
 
218
 
            CustomerContext = doc2.createElement("CustomerContext")
219
 
            ptext = doc2.createTextNode(data_for_void_shipment["VoidShipmentRequest"]['Request']['TransactionReference']['CustomerContext'])
220
 
            CustomerContext.appendChild(ptext)
221
 
            TransactionReference.appendChild(CustomerContext)
222
 
 
223
 
            ExpandedVoidShipment = doc2.createElement("ExpandedVoidShipment")
224
 
            VoidShipmentRequest.appendChild(ExpandedVoidShipment)
225
 
 
226
 
            ShipmentIdentificationNumber = doc2.createElement("ShipmentIdentificationNumber")
227
 
            ptext = doc2.createTextNode(data_for_void_shipment["VoidShipmentRequest"]['ExpandedVoidShipment']['ShipmentIdentificationNumber'])
228
 
            ShipmentIdentificationNumber.appendChild(ptext)
229
 
            ExpandedVoidShipment.appendChild(ShipmentIdentificationNumber)
230
 
 
231
 
            TrackingNumber = doc2.createElement("TrackingNumber")
232
 
            ptext = doc2.createTextNode(data_for_void_shipment["VoidShipmentRequest"]['ExpandedVoidShipment']['TrackingNumber'])
233
 
            TrackingNumber.appendChild(ptext)
234
 
            ExpandedVoidShipment.appendChild(TrackingNumber)
235
 
 
236
 
            Request_string2=doc2.toprettyxml()
237
 
 
238
 
 
239
 
            doc1 = Document()
240
 
            AccessRequest = doc1.createElement("AccessRequest")
241
 
            AccessRequest.setAttribute("xml:lang", "en-US")
242
 
            doc1.appendChild(AccessRequest)
243
 
 
244
 
            AccessLicenseNumber = doc1.createElement("AccessLicenseNumber")
245
 
            ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"])
246
 
            AccessLicenseNumber.appendChild(ptext)
247
 
            AccessRequest.appendChild(AccessLicenseNumber)
248
 
 
249
 
            UserId = doc1.createElement("UserId")
250
 
            ptext = doc1.createTextNode(data_for_Access_Request["UserId"])
251
 
            UserId.appendChild(ptext)
252
 
            AccessRequest.appendChild(UserId)
253
 
 
254
 
            Password = doc1.createElement("Password")
255
 
            ptext = doc1.createTextNode(data_for_Access_Request["Password"])
256
 
            Password.appendChild(ptext)
257
 
            AccessRequest.appendChild(Password)
258
 
 
259
 
            Request_string1=doc1.toprettyxml()
260
 
 
261
 
            Request_string=Request_string1+Request_string2
262
 
 
263
 
            
264
 
            if pick_obj.logis_company.test_mode:
265
 
                void_web = pick_obj.logis_company.ship_void_test_web or ''
266
 
                void_port = pick_obj.logis_company.ship_void_test_port
267
 
            else:
268
 
                void_web = pick_obj.logis_company.ship_void_web or ''
269
 
                void_port = pick_obj.logis_company.ship_void_port
270
 
            if void_web:
271
 
                parse_url = urlparse(void_web)
272
 
                serv = parse_url.netloc
273
 
                serv_path = parse_url.path
274
 
            else:
275
 
                raise osv.except_osv(_('Unable to find Shipping URL!'),_("Please configure the shipping company with websites.") )
276
 
            
277
 
            conn=httplib.HTTPSConnection(serv,void_port)
278
 
            filename="/tmp/void_request_" + pick_obj.name.replace('/','') + '.xml'
279
 
            f = open(filename, 'w')
280
 
            f.write(Request_string)
281
 
            f.close
282
 
            res=conn.request("POST",serv_path,Request_string)
283
 
            res=conn.getresponse()
284
 
            result = res.read()
285
 
            filename="/tmp/void_response_" + pick_obj.name.replace('/','') + '.xml'
286
 
            f = open(filename, 'w')
287
 
            f.write(result)
288
 
            f.close
289
 
 
290
 
            response_dic=xml2dic.main(result)
291
 
            response = ''
292
 
            error_flag=False
293
 
            for elm in response_dic['VoidShipmentResponse'][0]['Response']:
294
 
                if 'ResponseStatusCode' in elm.keys():
295
 
                    response += 'ResponseStatusCode:'+str(elm['ResponseStatusCode'])+'\n'
296
 
                if 'ResponseStatusDescription' in elm.keys():
297
 
                    response += 'ResponseStatusDescription:'+str(elm['ResponseStatusDescription'])+'\n'
298
 
                if 'Error' in elm.keys():
299
 
                    error_flag = True
300
 
                    response += 'Error:'+str(elm['Error'])+'\n'
301
 
 
302
 
 
303
 
            response = 'Void:\n'+response
304
 
            self.pool.get('stock.packages').write(cr,uid,pack.id,{'ship_message':str(response)})
305
 
 
306
 
        if not error_flag:
307
 
            clear_vals={
308
 
                            'ship_message': '',
309
 
                            'negotiated_rates' : 0.00,
310
 
                            'shipment_identific_no' :'',
311
 
                            'tracking_no': '',
312
 
                            'tracking_url': '',
313
 
                            'logo' : '',
314
 
                            'control_log_receipt':''
315
 
                        }
316
 
            for package in pick_obj.packages_ids:
317
 
                self.pool.get('stock.packages').write(cr, uid, package.id, clear_vals, context=context)
318
 
            self.pool.get('stock.picking').write(cr, uid, ids,{'ship_state':'draft','ship_message':'Shipment has been cancelled.'})
319
 
        else:
320
 
            self.pool.get('stock.picking').write(cr, uid, ids,{'ship_message':response})
321
 
        return True
322
 
 
323
 
 
324
 
    def get_package(self,pack_obj):
325
 
        if not pack_obj:
326
 
            return []
327
 
        else:
328
 
            ret = []
329
 
            ret.append({
330
 
                'Description':"",'PackagingType':{'Code':pack_obj.package_type or "",'Description':pack_type.get(pack_obj.package_type , "")},#PackagingType
331
 
                        'Dimensions':{'UnitOfMeasurement':{'Code':"IN",'Description':"Inches"},'Length':str(pack_obj.length or "0"),'Width':str(pack_obj.width or "0"),'Height':str(pack_obj.height or "0")},#Dimensions
332
 
                        'PackageWeight':{'UnitOfMeasurement':{'Code':"LBS",'Description':"Pounds"},'Weight':str(pack_obj.weight or "0")},
333
 
                        'ReferenceNumber':{'BarCodeIndicator':"",'Code':pack_obj.ref1 or "",'Value':""},
334
 
                            'PackageServiceOptions':{#'DeliveryConfirmation':{'DCISType':"",'DCISNumber':""},#DeliveryConfirmation
335
 
                                        'InsuredValue':{#'Type':"",'Code':"",'Description':"",
336
 
                                                'MonetaryValue':str(pack_obj.decl_val),
337
 
                                                
338
 
                                         },#InsuredValue
339
 
                        }#PackageServiceOptions
340
 
                })
341
 
            return ret
342
 
 
343
 
    def fill_addr(self,addr_id):
344
 
        ret = {'AddressLine1':addr_id and addr_id.street or '',
345
 
             'AddressLine2':addr_id and addr_id.street2 or '',
346
 
             'AddressLine3':"",
347
 
            'City':addr_id and addr_id.city or '',
348
 
            'StateProvinceCode':addr_id and addr_id.state_id.id and addr_id.state_id.code or '',
349
 
            'PostalCode':addr_id and addr_id.zip or '',
350
 
            'CountryCode':addr_id and addr_id.country_id.id and addr_id.country_id.code or '',
351
 
            }
352
 
        if addr_id and addr_id.classification=='2':
353
 
            ret.update({'ResidentialAddress': ""})
354
 
 
355
 
        if addr_id and ('zip_id' in addr_id._columns.keys()):
356
 
            ret['PostalCode'] = addr_id.zip_id.id and str(addr_id.zip_id.zipcode) or ''
357
 
        return ret
358
 
 
359
 
    def create_ship_accept_request(self,cr, uid, ids,package_id):
360
 
        package_obj=self.pool.get('stock.packages').browse(cr, uid, package_id)
361
 
 
362
 
###create the acces req xml first
363
 
        data_for_Access_Request={
364
 
                                    'AccessLicenseNumber':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.accesslicensenumber or '',
365
 
                                    'UserId':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.userid or '',
366
 
                                    'Password':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.password or ''
367
 
                                }
368
 
 
369
 
        doc1 = Document()
370
 
        AccessRequest = doc1.createElement("AccessRequest")
371
 
        AccessRequest.setAttribute("xml:lang", "en-US")
372
 
        doc1.appendChild(AccessRequest)
373
 
 
374
 
        AccessLicenseNumber = doc1.createElement("AccessLicenseNumber")
375
 
        ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"])
376
 
        AccessLicenseNumber.appendChild(ptext)
377
 
        AccessRequest.appendChild(AccessLicenseNumber)
378
 
 
379
 
        UserId = doc1.createElement("UserId")
380
 
        ptext = doc1.createTextNode(data_for_Access_Request["UserId"])
381
 
        UserId.appendChild(ptext)
382
 
        AccessRequest.appendChild(UserId)
383
 
 
384
 
        Password = doc1.createElement("Password")
385
 
        ptext = doc1.createTextNode(data_for_Access_Request["Password"])
386
 
        Password.appendChild(ptext)
387
 
        AccessRequest.appendChild(Password)
388
 
 
389
 
        Request_string1=doc1.toprettyxml()
390
 
 
391
 
        data_for_Ship_Accept = {'ShipmentAcceptRequest':{
392
 
                                                        'Request':{
393
 
                                                                  'RequestAction':'ShipAccept',
394
 
                                                                  'TransactionReference':{'CustomerContext':''}
395
 
                                                                  },
396
 
                                                        'ShipmentDigest':package_obj.shipment_digest
397
 
                                                        }
398
 
                                    }
399
 
 
400
 
 
401
 
        doc2 = Document()
402
 
        ShipmentAcceptRequest = doc2.createElement("ShipmentAcceptRequest")
403
 
        ShipmentAcceptRequest.setAttribute("xml:lang", "en-US")
404
 
        doc2.appendChild(ShipmentAcceptRequest)
405
 
 
406
 
        Request = doc2.createElement("Request")
407
 
        ShipmentAcceptRequest.appendChild(Request)
408
 
 
409
 
        RequestAction = doc2.createElement("RequestAction")
410
 
        ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["Request"]['RequestAction'])
411
 
        RequestAction.appendChild(ptext)
412
 
        Request.appendChild(RequestAction)
413
 
 
414
 
        TransactionReference = doc2.createElement("TransactionReference")
415
 
        Request.appendChild(TransactionReference)
416
 
 
417
 
        CustomerContext = doc2.createElement("CustomerContext")
418
 
        ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["Request"]['TransactionReference']['CustomerContext'])
419
 
        CustomerContext.appendChild(ptext)
420
 
        TransactionReference.appendChild(CustomerContext)
421
 
 
422
 
        ShipmentDigest = doc2.createElement("ShipmentDigest")
423
 
        ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["ShipmentDigest"])
424
 
        ShipmentDigest.appendChild(ptext)
425
 
        ShipmentAcceptRequest.appendChild(ShipmentDigest)
426
 
 
427
 
        Request_string2=doc2.toprettyxml()
428
 
        request_string=Request_string1+Request_string2
429
 
 
430
 
        return request_string
431
 
 
432
 
    def process_ship_accept(self,cr, uid, ids,ship_move_ids,pack_obj,context=None):
433
 
 
434
 
 
435
 
        shipment_accept_request_xml=self.create_ship_accept_request(cr, uid, ids,pack_obj.id)
436
 
 
437
 
        if pack_obj.pick_id.logis_company.test_mode:
438
 
            acce_web = pack_obj.pick_id.logis_company.ship_accpt_test_web or ''
439
 
            acce_port = pack_obj.pick_id.logis_company.ship_accpt_test_port
440
 
        else:
441
 
            acce_web = pack_obj.pick_id.logis_company.ship_accpt_web or ''
442
 
            acce_port = pack_obj.pick_id.logis_company.ship_accpt_port
443
 
        if acce_web:
444
 
            parse_url = urlparse(acce_web)
445
 
            serv = parse_url.netloc
446
 
            serv_path = parse_url.path
447
 
        else:
448
 
            raise osv.except_osv(_('Unable to find Shipping URL!'),_("Please configure the shipping company with websites.") )
449
 
 
450
 
 
451
 
 
452
 
        conn=httplib.HTTPSConnection(serv,acce_port)
453
 
        filename="/tmp/ship_accept_request_" + pack_obj.pick_id.name.replace('/','') + '.xml'
454
 
        f = open(filename, 'w')
455
 
        f.write(shipment_accept_request_xml)
456
 
        f.close
457
 
        res=conn.request("POST",serv_path,shipment_accept_request_xml)
458
 
        res=conn.getresponse()
459
 
        
460
 
        result = res.read()
461
 
        filename="/tmp/ship_accept_response_" + pack_obj.pick_id.name.replace('/','') + '.xml'
462
 
        f = open(filename, 'w')        
463
 
        f.write(result)
464
 
        f.close
465
 
 
466
 
        response_dic=xml2dic.main(result)
467
 
        NegotiatedRates=''
468
 
        ShipmentIdentificationNumber=''
469
 
        TrackingNumber=''
470
 
        label_image=''
471
 
        control_log_image=''
472
 
        if response_dic['ShipmentAcceptResponse'][0]['Response'][0]['ResponseStatusCode'] == '1':
473
 
            if len(response_dic['ShipmentAcceptResponse'])>1 and response_dic['ShipmentAcceptResponse'][1].has_key('ShipmentResults'):
474
 
                if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'])>1 and response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1].has_key('NegotiatedRates'):
475
 
                    if  len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'])>0 and response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0].has_key('NetSummaryCharges'):
476
 
                        if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'])>0 and response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'][0].has_key('GrandTotal'):
477
 
                           NegotiatedRates=response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'][0]['GrandTotal'][1]['MonetaryValue']
478
 
 
479
 
                if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'])>0 and response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][3].has_key('ShipmentIdentificationNumber'):
480
 
                    ShipmentIdentificationNumber=response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][3]['ShipmentIdentificationNumber']
481
 
 
482
 
                if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'])>4 and response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4].has_key('PackageResults') :
483
 
                    if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'])>0:
484
 
                        TrackingNumber=response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][0]['TrackingNumber']
485
 
 
486
 
                    if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'])>2 and response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][2].has_key('LabelImage') :
487
 
                        label_image =response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][2]['LabelImage'][1]['GraphicImage']
488
 
                
489
 
                
490
 
                for item in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults']:
491
 
                    if item.has_key('ControlLogReceipt'):
492
 
                        for i in item:
493
 
                            for j in item['ControlLogReceipt']:
494
 
                                if j.get('GraphicImage'):
495
 
                                    control_log_image = j['GraphicImage']
496
 
                
497
 
        if TrackingNumber:
498
 
            tracking_url = pack_obj.pick_id.logis_company.ship_tracking_url
499
 
            if tracking_url:
500
 
                try:
501
 
                    tracking_url = tracking_url%TrackingNumber
502
 
                except Exception, e:
503
 
                    tracking_url = "Invalid tracking url on shipping company"
504
 
        else:
505
 
            tracking_url = ''
506
 
        if label_image:
507
 
            im_in_raw=base64.decodestring(label_image)
508
 
            path=tempfile.mktemp()
509
 
            temp=file(path,'wb')
510
 
            temp.write(im_in_raw)
511
 
            temp.close()
512
 
            new_im=Image.open(path)
513
 
            new_im=new_im.rotate(270)
514
 
            
515
 
            filename="/tmp/label_" + pack_obj.pick_id.name.replace('/','') + '.gif'
516
 
            f = open(filename, 'w')
517
 
            f.close
518
 
            
519
 
            new_im.save(filename,'GIF')
520
 
            
521
 
            label_from_file=open(filename,'rb')
522
 
            label_image=base64.encodestring(label_from_file.read())
523
 
            label_from_file.close()
524
 
 
525
 
        if control_log_image:
526
 
            print "contrlo log image : ", control_log_image
527
 
            im_in_raw=base64.decodestring(control_log_image)
528
 
            
529
 
            path= '/tmp/control_log.html'
530
 
            temp=file(path,'wb')
531
 
            temp.write(im_in_raw)
532
 
            temp.close()
533
 
            
534
 
            label_from_file=open(path,'rb')
535
 
            control_log_image=base64.encodestring(label_from_file.read())
536
 
            label_from_file.close()
537
 
            
538
 
        self.pool.get('stock.packages').write(cr,uid,[pack_obj.id],{'tracking_no':TrackingNumber or "",
539
 
                                                                     'shipment_identific_no':ShipmentIdentificationNumber or "",
540
 
                                                                     'negotiated_rates':NegotiatedRates or '',
541
 
                                                                     'logo':label_image,
542
 
                                                                     'control_log_receipt' : control_log_image,
543
 
                                                                     'ship_state':'in_process',
544
 
                                                                     'tracking_url':tracking_url})
545
 
 
546
 
        if ship_move_ids.get(pack_obj.id):
547
 
            if TrackingNumber:
548
 
                tracking_url = pack_obj.pick_id.logis_company.ship_tracking_url
549
 
                if tracking_url:
550
 
                    try:
551
 
                        tracking_url = tracking_url%TrackingNumber
552
 
                    except Exception, e:
553
 
                        tracking_url = "Invalid tracking url on shipping company"
554
 
            else:
555
 
                tracking_url = ''
556
 
            self.pool.get('shipping.move').write(cr, uid, [ship_move_ids.get(pack_obj.id)], {'tracking_no':TrackingNumber or "",
557
 
                                                                     'shipment_identific_no':ShipmentIdentificationNumber or "",
558
 
                                                                     'ship_cost':NegotiatedRates or '',
559
 
                                                                     'logo':label_image,
560
 
                                                                     'state':'ready_pick',
561
 
                                                                     'tracking_url':tracking_url})
562
 
        return True
563
 
 
564
 
    def add_product(self, cr, uid, package_obj):
565
 
        prods = []
566
 
        tot_weight = 0
567
 
        for pkg in package_obj.pick_id.packages_ids:
568
 
            tot_weight += pkg.weight
569
 
        for move_lines in package_obj.pick_id.move_lines:
570
 
            product_id = move_lines.product_id
571
 
            if move_lines.product_id.supply_method == 'produce':
572
 
                produce = "Yes"
573
 
            else:
574
 
                produce = "NO[1]" 
575
 
            product={'Description':move_lines.product_id.description or " ",
576
 
                     'Unit':{'Number':str(int(move_lines.product_qty) or 0),
577
 
                             'Value':str((move_lines.product_id.list_price * move_lines.product_qty) or 0),
578
 
                             'UnitOfMeasurement':{'Code':"LBS",'Description':"Pounds"}
579
 
                            },
580
 
             'CommodityCode':package_obj.pick_id.comm_code or "",
581
 
             'PartNumber':"",
582
 
             'OriginCountryCode':package_obj.pick_id.address_id and package_obj.pick_id.address_id.country_id and package_obj.pick_id.address_id.country_id.code or "",
583
 
             'JointProductionIndicator':"",
584
 
             'NetCostCode':"NO",
585
 
             'PreferenceCriteria':"B",
586
 
             'ProducerInfo':produce,
587
 
             'MarksAndNumbers':"",
588
 
             'NumberOfPackagesPerCommodity':str(len(package_obj.pick_id.packages_ids)),
589
 
             'ProductWeight':{'UnitOfMeasurement':{'Code':"LBS",'Description':"Pounds"},
590
 
                               'Weight':"%.1f"%(tot_weight or '0')},
591
 
             'VehicleID':"",
592
 
                }
593
 
            prods.append(product)
594
 
        return prods
595
 
 
596
 
    def create_comm_inv(self, cr, uid, package_obj):
597
 
        invoice_id = False
598
 
        if package_obj.pick_id.sale_id:
599
 
            if package_obj.pick_id.sale_id.invoice_ids:
600
 
                invoice_id = package_obj.pick_id.sale_id.invoice_ids[0]
601
 
        user = self.pool.get('res.users').browse(cr, uid, uid)
602
 
        comm_inv={    'FormType':"01",
603
 
            'Product':[],#Placed out of this dictionary for common use
604
 
            'InvoiceNumber':"",
605
 
            'InvoiceDate':"",
606
 
            'PurchaseOrderNumber':"",
607
 
            'TermsOfShipment':"",
608
 
            'ReasonForExport':"SALE",
609
 
            'Comments':"",
610
 
            'DeclarationStatement':"I hereby certify that the good covered by this shipment qualifies as an originating good for purposes of preferential tariff treatment under the NAFTA.",
611
 
            'CurrencyCode':user.company_id.currency_id.name or "",
612
 
        }
613
 
        if invoice_id:
614
 
            comm_inv['InvoiceNumber'] = invoice_id.number or '/'
615
 
            if invoice_id.date_invoice:
616
 
                d=invoice_id.date_invoice
617
 
                comm_inv['InvoiceDate'] = d[:4]+d[5:7]+d[8:10]
618
 
        if not comm_inv['InvoiceDate']:
619
 
            comm_inv['InvoiceDate'] = time.strftime("%Y%m%d")
620
 
        
621
 
        return comm_inv
622
 
 
623
 
    def create_cer_orig(self, cr, uid, package_obj):
624
 
        cer_orig={    
625
 
            'FormType':"03",
626
 
#            'AdditionalDocumentIndicator':"",                            Not Required
627
 
#            'FormGroupIdName':"",                                        Not Required
628
 
            'Product':[],#Placed out of this dictionary for common use
629
 
            'ExportDate':time.strftime("%Y%m%d"),
630
 
            'ExportingCarrier':package_obj.pick_id.exp_carrier or "",
631
 
        }
632
 
        return cer_orig
633
 
 
634
 
    def create_nafta_cer_orig(self, cr, uid, package_obj):
635
 
        addr = {}
636
 
        if package_obj.pick_id.prod_address_id:
637
 
            addr_id = package_obj.pick_id.prod_address_id
638
 
            
639
 
            addr = {'AddressLine1':addr_id.street or "",
640
 
                                  'AddressLine2':addr_id.street2 or "",
641
 
                                  'City':addr_id.city or "",
642
 
                                  'StateProvinceCode':addr_id.state_id and addr_id.state_id.code or "",
643
 
                                  'PostalCode':addr_id.zip or "",
644
 
                                  'CountryCode':addr_id.country_id and addr_id.country_id.code or "",
645
 
                                  }
646
 
        beg_date=" "
647
 
        end_date=" "
648
 
        if package_obj.pick_id.blanket_begin_date:
649
 
            beg_date = package_obj.pick_id.blanket_begin_date
650
 
            beg_date = beg_date[:4]+beg_date[5:7]+beg_date[8:10]
651
 
        if package_obj.pick_id.blanket_end_date:
652
 
            end_date = package_obj.pick_id.blanket_end_date
653
 
            end_date = end_date[:4]+end_date[5:7]+end_date[8:10]
654
 
        nafta_cer_orig={    'FormType':"04",
655
 
             'Contacts':{
656
 
 
657
 
                            'Producer':{'Option':package_obj.pick_id.prod_option or "",
658
 
                                        'CompanyName':package_obj.pick_id.prod_company or "",
659
 
                                        'TaxIdentificationNumber':package_obj.pick_id.prod_tax_id_no or "",
660
 
                                        'Address':addr,#Address
661
 
                                        },#Producer
662
 
                         },#Contacts
663
 
             'BlanketPeriod':{
664
 
                              'BeginDate':beg_date,
665
 
                              'EndDate':end_date,
666
 
 
667
 
                              },
668
 
             'Product':[],#Placed out of this dictionary for common use
669
 
        }
670
 
        return nafta_cer_orig
671
 
    
672
 
    def create_forms(self, cr, uid, package_obj):
673
 
        comm_inv = {}
674
 
        cer_orig = {}
675
 
        nafta_cer_orig = {}
676
 
        sed = {}
677
 
        if package_obj.pick_id.comm_inv:
678
 
            comm_inv = self.create_comm_inv(cr, uid, package_obj)
679
 
        if package_obj.pick_id.cer_orig:
680
 
            cer_orig = self.create_cer_orig(cr, uid, package_obj)
681
 
        if package_obj.pick_id.nafta_cer_orig:
682
 
            nafta_cer_orig = self.create_nafta_cer_orig(cr, uid, package_obj)
683
 
        prod = self.add_product(cr, uid, package_obj)
684
 
        ret = {'comm_inv':comm_inv,'cer_orig':cer_orig,'nafta_cer_orig':nafta_cer_orig,'sed':sed,'prod':prod}
685
 
        return ret
686
 
    def create_ship_confirm_request(self,cr, uid,package_id):
687
 
            package_obj=self.pool.get('stock.packages').browse(cr, uid, package_id)
688
 
 
689
 
###create the acces req xml first
690
 
            data_for_Access_Request={
691
 
                                        'AccessLicenseNumber':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.accesslicensenumber or '',
692
 
                                        'UserId':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.userid or '',
693
 
                                        'Password':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.password or ''
694
 
                                    }
695
 
 
696
 
            doc1 = Document()
697
 
            AccessRequest = doc1.createElement("AccessRequest")
698
 
            AccessRequest.setAttribute("xml:lang", "en-US")
699
 
            doc1.appendChild(AccessRequest)
700
 
 
701
 
            AccessLicenseNumber = doc1.createElement("AccessLicenseNumber")
702
 
            ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"])
703
 
            AccessLicenseNumber.appendChild(ptext)
704
 
            AccessRequest.appendChild(AccessLicenseNumber)
705
 
 
706
 
            UserId = doc1.createElement("UserId")
707
 
            ptext = doc1.createTextNode(data_for_Access_Request["UserId"])
708
 
            UserId.appendChild(ptext)
709
 
            AccessRequest.appendChild(UserId)
710
 
 
711
 
            Password = doc1.createElement("Password")
712
 
            ptext = doc1.createTextNode(data_for_Access_Request["Password"])
713
 
            Password.appendChild(ptext)
714
 
            AccessRequest.appendChild(Password)
715
 
 
716
 
            Request_string1=doc1.toprettyxml()
717
 
 
718
 
###create the shipment acces req xml
719
 
            data_for_confirm_request={'ShipmentConfirmRequest':{
720
 
 
721
 
                                  'Request':{'RequestAction':"ShipConfirm",#-----must be ShipConfirm
722
 
                                            'RequestOption':package_obj.pick_id.address_validate or "nonvalidate",#----------adress validation
723
 
                                            'TransactionReference':{'CustomerContext':"",},#---------optional data
724
 
                                            },#Request
725
 
 
726
 
                                  'Shipment':{'Description':package_obj.description or "Shipping",
727
 
                                              'ReturnService':{'Code':"8", 'DocumentsOnly':"" },
728
 
                                              'Shipper':{ 'Name':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.name or "",
729
 
                                                          'AttentionName':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.atten_name or "",
730
 
                                                          'ShipperNumber':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.acc_no or "",
731
 
                                                          'TaxIdentificationNumber':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.tax_id_no or "",
732
 
                                                          'PhoneNumber':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.address and package_obj.pick_id.shipper.address.phone or "",
733
 
                                                          'FaxNumber':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.address and package_obj.pick_id.shipper.address.fax or "",
734
 
                                                          'EMailAddress':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.address and package_obj.pick_id.shipper.address.email or "",
735
 
                                                          'Address':self.fill_addr(package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.address or '')
736
 
                                                         },#Shipper
737
 
 
738
 
                                              'ShipTo': {'CompanyName':package_obj.pick_id.address_id.partner_id and package_obj.pick_id.address_id.partner_id.name or '',
739
 
                                                        'AttentionName':package_obj.pick_id.inv_att_name or "",
740
 
                                                        'TaxIdentificationNumber':"",
741
 
                                                        'PhoneNumber':package_obj.pick_id.address_id.id and package_obj.pick_id.address_id.phone or '',
742
 
                                                        'FaxNumber':package_obj.pick_id.address_id.id and package_obj.pick_id.address_id.fax or '',
743
 
                                                        'EMailAddress':package_obj.pick_id.address_id.id and package_obj.pick_id.address_id.email or '',
744
 
                                                        'Address':self.fill_addr(package_obj.pick_id.address_id.id and package_obj.pick_id.address_id),
745
 
                                                        'LocationID':"",
746
 
                                                         },#ShipTo
747
 
 
748
 
 
749
 
 
750
 
                                              'ShipFrom':{'CompanyName':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.name or "",
751
 
                                                          'AttentionName':package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.atten_name or "",
752
 
                                                          'TaxIdentificationNumber':package_obj.pick_id.ship_from_tax_id_no or '',
753
 
                                                          'PhoneNumber':package_obj.pick_id.address_id.id and package_obj.pick_id.ship_from_address.phone or '',
754
 
                                                          'FaxNumber':package_obj.pick_id.address_id.id and package_obj.pick_id.ship_from_address.fax or '',
755
 
                                                          'Address':self.fill_addr(package_obj.pick_id.ship_from_address.id and package_obj.pick_id.ship_from_address),
756
 
                                                          },
757
 
 
758
 
                                              'SoldTo':{'Option':package_obj.pick_id.inv_option or " ",
759
 
                                                        'CompanyName':package_obj.pick_id.inv_company or "",
760
 
                                                        'AttentionName':package_obj.pick_id.inv_att_name or "",
761
 
                                                        'TaxIdentificationNumber':package_obj.pick_id.inv_tax_id_no or "",
762
 
                                                        'PhoneNumber':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.phone or "",
763
 
                                                        'Address':{'AddressLine1':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.street or "",
764
 
                                                                   'AddressLine2':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.street2 or "",
765
 
                                                                   'City':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.city or "",
766
 
                                                                   'StateProvinceCode':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.state_id and package_obj.pick_id.inv_address_id.state_id.code or "",
767
 
                                                                   'PostalCode':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.zip or "",
768
 
                                                                   'CountryCode':package_obj.pick_id.inv_address_id and package_obj.pick_id.inv_address_id.country_id and package_obj.pick_id.inv_address_id.country_id.code or "",}
769
 
                                                      },#SoldTo,
770
 
 
771
 
                                              'PaymentInformation':{'Prepaid':{
772
 
                                                                            'BillShipper':{'AccountNumber':package_obj.pick_id.shipper and package_obj.pick_id.shipper.acc_no or "",
773
 
                                                                                            },#BillShipper
774
 
                                                                                },#Prepaid
775
 
                                                                  },#PaymentInformation,
776
 
 
777
 
 
778
 
                                 'GoodsNotInFreeCirculationIndicator':"",
779
 
                                 'RateInformation':{'NegotiatedRatesIndicator':""},#RateInformation
780
 
                                 'Service':{'Code':package_obj.pick_id.ups_service.id and str(package_obj.pick_id.ups_service.shipping_service_code) or "",
781
 
                                            'Description':package_obj.pick_id.ups_service.id and package_obj.pick_id.ups_service.description or ""},#Service
782
 
                                 'InvoiceLineTotal':{'CurrencyCode':"",'MonetaryValue':str(int(package_obj.pick_id.sale_id.amount_total or 0.00)) or ""},#InvoiceLineTotal
783
 
                                 'ShipmentServiceOptions':{'SaturdayDelivery':"",
784
 
                                                           'Notification':[],
785
 
                                                           'LabelDelivery':{'LabelLinkIndicator':"",
786
 
                                                                            'EMailMessage':{'EMailAddress':"mail@mail.com",
787
 
                                                                                           'UndeliverableEMailAddress':"",
788
 
                                                                                           'FromEMailAddress':"mail@mail.com",
789
 
                                                                                           'FromName':"",
790
 
                                                                                           'Memo':"",
791
 
                                                                                           'Subject':"",
792
 
                                                                                           'SubjectCode':""}#EMailMessage
793
 
                                                                            },#LabelDelivery
794
 
 
795
 
                                                           'InternationalForms':self.create_forms(cr, uid, package_obj),#InternationalForms
796
 
                                                         },#ShipmentServiceOptions,
797
 
                                 'Package':self.get_package(package_obj)## this is done in different file
798
 
                                                },#Shipment
799
 
                'LabelSpecification':{'LabelPrintMethod':{'Code':"GIF", 'Description':"GIF",},
800
 
                                      'HTTPUserAgent':"",
801
 
                                      'LabelStockSize':{'Height':"6",'Width':"6"},
802
 
                                      'LabelImageFormat':{'Code':"GIF",'Description':"GIF"},
803
 
                                    },#LabelSpecification
804
 
 
805
 
            },#ShipmentConfirmRequest
806
 
        }
807
 
 
808
 
 
809
 
 
810
 
            print "DATA FOR CONFIR R : \n", data_for_confirm_request
811
 
            comm_inv = data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["InternationalForms"]['comm_inv']
812
 
            cer_orig = data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["InternationalForms"]['cer_orig']
813
 
            nafta_cer_orig = data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["InternationalForms"]['nafta_cer_orig']
814
 
            sed = False #data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["InternationalForms"]['sed']
815
 
            prod = data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["InternationalForms"]['prod']
816
 
            
817
 
 
818
 
            doc2 = Document()
819
 
            ShipmentConfirmRequest = doc2.createElement("ShipmentConfirmRequest")
820
 
            doc2.appendChild(ShipmentConfirmRequest)
821
 
 
822
 
            Request = doc2.createElement("Request")
823
 
            ShipmentConfirmRequest.appendChild(Request)
824
 
 
825
 
            RequestAction = doc2.createElement("RequestAction")
826
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["RequestAction"])
827
 
            RequestAction.appendChild(ptext)
828
 
            Request.appendChild(RequestAction)
829
 
 
830
 
            RequestOption = doc2.createElement("RequestOption")
831
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["RequestOption"])
832
 
            RequestOption.appendChild(ptext)
833
 
            Request.appendChild(RequestOption)
834
 
 
835
 
            TransactionReference = doc2.createElement("TransactionReference")
836
 
            Request.appendChild(TransactionReference)
837
 
 
838
 
            CustomerContext = doc2.createElement("CustomerContext")
839
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["TransactionReference"]['CustomerContext'])
840
 
            CustomerContext.appendChild(ptext)
841
 
            TransactionReference.appendChild(CustomerContext)
842
 
 
843
 
            Shipment = doc2.createElement("Shipment")
844
 
            ShipmentConfirmRequest.appendChild(Shipment)
845
 
 
846
 
            Description = doc2.createElement("Description")
847
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Description"])
848
 
            Description.appendChild(ptext)
849
 
            Shipment.appendChild(Description)
850
 
            if package_obj.pick_id.with_ret_service:
851
 
                ReturnService = doc2.createElement("ReturnService")
852
 
                Shipment.appendChild(ReturnService)
853
 
 
854
 
 
855
 
                Code = doc2.createElement("Code")
856
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ReturnService"]["Code"])
857
 
                Code.appendChild(ptext)
858
 
                ReturnService.appendChild(Code)
859
 
 
860
 
            Shipper = doc2.createElement("Shipper")
861
 
            Shipment.appendChild(Shipper)
862
 
 
863
 
            Name = doc2.createElement("Name")
864
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Name"])
865
 
            Name.appendChild(ptext)
866
 
            Shipper.appendChild(Name)
867
 
 
868
 
            AttentionName = doc2.createElement("AttentionName")
869
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["AttentionName"])
870
 
            AttentionName.appendChild(ptext)
871
 
            Shipper.appendChild(AttentionName)
872
 
 
873
 
            ShipperNumber = doc2.createElement("ShipperNumber")
874
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["ShipperNumber"])
875
 
            ShipperNumber.appendChild(ptext)
876
 
            Shipper.appendChild(ShipperNumber)
877
 
 
878
 
            TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber")
879
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["TaxIdentificationNumber"])
880
 
            TaxIdentificationNumber.appendChild(ptext)
881
 
            Shipper.appendChild(TaxIdentificationNumber)
882
 
            PhoneNumber = doc2.createElement("PhoneNumber")
883
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["PhoneNumber"])
884
 
            PhoneNumber.appendChild(ptext)
885
 
            Shipper.appendChild(PhoneNumber)
886
 
 
887
 
            FaxNumber = doc2.createElement("FaxNumber")
888
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["FaxNumber"])
889
 
            FaxNumber.appendChild(ptext)
890
 
            Shipper.appendChild(FaxNumber)
891
 
 
892
 
            EMailAddress = doc2.createElement("EMailAddress")
893
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["EMailAddress"])
894
 
            EMailAddress.appendChild(ptext)
895
 
            Shipper.appendChild(EMailAddress)
896
 
 
897
 
            #################address
898
 
            Address = doc2.createElement("Address")
899
 
            Shipper.appendChild(Address)
900
 
 
901
 
            AddressLine1 = doc2.createElement("AddressLine1")
902
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine1"])
903
 
            AddressLine1.appendChild(ptext)
904
 
            Address.appendChild(AddressLine1)
905
 
 
906
 
            AddressLine2 = doc2.createElement("AddressLine2")
907
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine2"])
908
 
            AddressLine2.appendChild(ptext)
909
 
            Address.appendChild(AddressLine2)
910
 
 
911
 
            AddressLine3 = doc2.createElement("AddressLine3")
912
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine3"])
913
 
            AddressLine3.appendChild(ptext)
914
 
            Address.appendChild(AddressLine3)
915
 
 
916
 
            City = doc2.createElement("City")
917
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["City"])
918
 
            City.appendChild(ptext)
919
 
            Address.appendChild(City)
920
 
 
921
 
            StateProvinceCode = doc2.createElement("StateProvinceCode")
922
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["StateProvinceCode"])
923
 
            StateProvinceCode.appendChild(ptext)
924
 
            Address.appendChild(StateProvinceCode)
925
 
 
926
 
            PostalCode = doc2.createElement("PostalCode")
927
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["PostalCode"])
928
 
            PostalCode.appendChild(ptext)
929
 
            Address.appendChild(PostalCode)
930
 
            CountryCode = doc2.createElement("CountryCode")
931
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["CountryCode"])
932
 
            CountryCode.appendChild(ptext)
933
 
            Address.appendChild(CountryCode)
934
 
 
935
 
            ShipTo = doc2.createElement("ShipTo")
936
 
            Shipment.appendChild(ShipTo)
937
 
            CompanyName = doc2.createElement("CompanyName")
938
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["CompanyName"])
939
 
            CompanyName.appendChild(ptext)
940
 
            ShipTo.appendChild(CompanyName)
941
 
 
942
 
            AttentionName = doc2.createElement("AttentionName")
943
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["AttentionName"])
944
 
            AttentionName.appendChild(ptext)
945
 
            ShipTo.appendChild(AttentionName)
946
 
 
947
 
            TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber")
948
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["TaxIdentificationNumber"])
949
 
            TaxIdentificationNumber.appendChild(ptext)
950
 
            ShipTo.appendChild(TaxIdentificationNumber)
951
 
 
952
 
            PhoneNumber = doc2.createElement("PhoneNumber")
953
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["PhoneNumber"])
954
 
            PhoneNumber.appendChild(ptext)
955
 
            ShipTo.appendChild(PhoneNumber)
956
 
 
957
 
            FaxNumber = doc2.createElement("FaxNumber")
958
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["FaxNumber"])
959
 
            FaxNumber.appendChild(ptext)
960
 
            ShipTo.appendChild(FaxNumber)
961
 
 
962
 
            EMailAddress = doc2.createElement("EMailAddress")
963
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["EMailAddress"])
964
 
            EMailAddress.appendChild(ptext)
965
 
            ShipTo.appendChild(EMailAddress)
966
 
 
967
 
            LocationID = doc2.createElement("LocationID")
968
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["LocationID"])
969
 
            LocationID.appendChild(ptext)
970
 
            ShipTo.appendChild(LocationID)
971
 
 
972
 
            Address = doc2.createElement("Address")
973
 
            ShipTo.appendChild(Address)
974
 
            AddressLine1 = doc2.createElement("AddressLine1")
975
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine1"])
976
 
            AddressLine1.appendChild(ptext)
977
 
            Address.appendChild(AddressLine1)
978
 
 
979
 
            AddressLine2 = doc2.createElement("AddressLine2")
980
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine2"])
981
 
            AddressLine2.appendChild(ptext)
982
 
            Address.appendChild(AddressLine2)
983
 
 
984
 
            AddressLine2 = doc2.createElement("AddressLine3")
985
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine3"])
986
 
            AddressLine3.appendChild(ptext)
987
 
            Address.appendChild(AddressLine3)
988
 
 
989
 
            City = doc2.createElement("City")
990
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["City"])
991
 
            City.appendChild(ptext)
992
 
            Address.appendChild(City)
993
 
 
994
 
            StateProvinceCode = doc2.createElement("StateProvinceCode")
995
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["StateProvinceCode"])
996
 
            StateProvinceCode.appendChild(ptext)
997
 
            Address.appendChild(StateProvinceCode)
998
 
 
999
 
            PostalCode = doc2.createElement("PostalCode")
1000
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["PostalCode"])
1001
 
            PostalCode.appendChild(ptext)
1002
 
            Address.appendChild(PostalCode)
1003
 
 
1004
 
            CountryCode = doc2.createElement("CountryCode")
1005
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["CountryCode"])
1006
 
            CountryCode.appendChild(ptext)
1007
 
            Address.appendChild(CountryCode)
1008
 
            if package_obj.pick_id.ship_from:
1009
 
                ShipFrom = doc2.createElement("ShipFrom")
1010
 
                Shipment.appendChild(ShipFrom)
1011
 
                CompanyName = doc2.createElement("CompanyName")
1012
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["CompanyName"])
1013
 
                CompanyName.appendChild(ptext)
1014
 
                ShipFrom.appendChild(CompanyName)
1015
 
 
1016
 
                AttentionName = doc2.createElement("AttentionName")
1017
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["AttentionName"])
1018
 
                AttentionName.appendChild(ptext)
1019
 
                ShipFrom.appendChild(AttentionName)
1020
 
 
1021
 
                TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber")
1022
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["TaxIdentificationNumber"])
1023
 
                TaxIdentificationNumber.appendChild(ptext)
1024
 
                ShipFrom.appendChild(TaxIdentificationNumber)
1025
 
 
1026
 
                PhoneNumber = doc2.createElement("PhoneNumber")
1027
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["PhoneNumber"])
1028
 
                PhoneNumber.appendChild(ptext)
1029
 
                ShipFrom.appendChild(PhoneNumber)
1030
 
 
1031
 
                FaxNumber = doc2.createElement("FaxNumber")
1032
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["FaxNumber"])
1033
 
                FaxNumber.appendChild(ptext)
1034
 
                ShipFrom.appendChild(FaxNumber)
1035
 
 
1036
 
                Address = doc2.createElement("Address")
1037
 
                ShipFrom.appendChild(Address)
1038
 
                AddressLine1 = doc2.createElement("AddressLine1")
1039
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine1"])
1040
 
                AddressLine1.appendChild(ptext)
1041
 
                Address.appendChild(AddressLine1)
1042
 
 
1043
 
                AddressLine2 = doc2.createElement("AddressLine2")
1044
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine2"])
1045
 
                AddressLine2.appendChild(ptext)
1046
 
                Address.appendChild(AddressLine2)
1047
 
 
1048
 
                AddressLine3 = doc2.createElement("AddressLine3")
1049
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine3"])
1050
 
                AddressLine3.appendChild(ptext)
1051
 
                Address.appendChild(AddressLine3)
1052
 
 
1053
 
                City = doc2.createElement("City")
1054
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["City"])
1055
 
                City.appendChild(ptext)
1056
 
                Address.appendChild(City)
1057
 
 
1058
 
                StateProvinceCode = doc2.createElement("StateProvinceCode")
1059
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["StateProvinceCode"])
1060
 
                StateProvinceCode.appendChild(ptext)
1061
 
                Address.appendChild(StateProvinceCode)
1062
 
 
1063
 
                CountryCode = doc2.createElement("CountryCode")
1064
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["CountryCode"])
1065
 
                CountryCode.appendChild(ptext)
1066
 
                Address.appendChild(CountryCode)
1067
 
 
1068
 
 
1069
 
            if comm_inv or nafta_cer_orig:
1070
 
                SoldTo = doc2.createElement("SoldTo")
1071
 
                Shipment.appendChild(SoldTo)
1072
 
                Option = doc2.createElement("Option")
1073
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Option"])
1074
 
                Option.appendChild(ptext)
1075
 
                SoldTo.appendChild(Option)
1076
 
                
1077
 
                CompanyName = doc2.createElement("CompanyName")
1078
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["CompanyName"])
1079
 
                CompanyName.appendChild(ptext)
1080
 
                SoldTo.appendChild(CompanyName)
1081
 
#                else:  
1082
 
                CompanyName = doc2.createElement("CompanyName")
1083
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["CompanyName"])
1084
 
                CompanyName.appendChild(ptext)
1085
 
                SoldTo.appendChild(CompanyName)
1086
 
    
1087
 
                AttentionName = doc2.createElement("AttentionName")
1088
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["AttentionName"])
1089
 
                AttentionName.appendChild(ptext)
1090
 
                SoldTo.appendChild(AttentionName)
1091
 
    
1092
 
                TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber")
1093
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["TaxIdentificationNumber"])
1094
 
                TaxIdentificationNumber.appendChild(ptext)
1095
 
                SoldTo.appendChild(TaxIdentificationNumber)
1096
 
    
1097
 
                PhoneNumber = doc2.createElement("PhoneNumber")
1098
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["PhoneNumber"])
1099
 
                PhoneNumber.appendChild(ptext)
1100
 
                SoldTo.appendChild(PhoneNumber)
1101
 
    
1102
 
    
1103
 
                Address = doc2.createElement("Address")
1104
 
                SoldTo.appendChild(Address)
1105
 
                AddressLine1 = doc2.createElement("AddressLine1")
1106
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Address"]["AddressLine1"])
1107
 
                AddressLine1.appendChild(ptext)
1108
 
                Address.appendChild(AddressLine1)
1109
 
    
1110
 
                AddressLine2 = doc2.createElement("AddressLine2")
1111
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Address"]["AddressLine2"])
1112
 
                AddressLine2.appendChild(ptext)
1113
 
                Address.appendChild(AddressLine2)
1114
 
    
1115
 
    
1116
 
                City = doc2.createElement("City")
1117
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Address"]["City"])
1118
 
                City.appendChild(ptext)
1119
 
                Address.appendChild(City)
1120
 
    
1121
 
                StateProvinceCode = doc2.createElement("StateProvinceCode")
1122
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Address"]["StateProvinceCode"])
1123
 
                StateProvinceCode.appendChild(ptext)
1124
 
                Address.appendChild(StateProvinceCode)
1125
 
    
1126
 
                PostalCode = doc2.createElement("PostalCode")
1127
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Address"]["PostalCode"])
1128
 
                PostalCode.appendChild(ptext)
1129
 
                Address.appendChild(PostalCode)
1130
 
    
1131
 
                CountryCode = doc2.createElement("CountryCode")
1132
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["SoldTo"]["Address"]["CountryCode"])
1133
 
                CountryCode.appendChild(ptext)
1134
 
                Address.appendChild(CountryCode)
1135
 
 
1136
 
            PaymentInformation = doc2.createElement("PaymentInformation")
1137
 
            Shipment.appendChild(PaymentInformation)
1138
 
            Prepaid = doc2.createElement("Prepaid")
1139
 
            PaymentInformation.appendChild(Prepaid)
1140
 
 
1141
 
            BillShipper = doc2.createElement("BillShipper")
1142
 
            Prepaid.appendChild(BillShipper)
1143
 
 
1144
 
            AccountNumber = doc2.createElement("AccountNumber")
1145
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["PaymentInformation"]["Prepaid"]["BillShipper"]["AccountNumber"])
1146
 
            AccountNumber.appendChild(ptext)
1147
 
            BillShipper.appendChild(AccountNumber)
1148
 
 
1149
 
 
1150
 
            GoodsNotInFreeCirculationIndicator = doc2.createElement("GoodsNotInFreeCirculationIndicator")
1151
 
            Shipment.appendChild(GoodsNotInFreeCirculationIndicator)
1152
 
 
1153
 
            RateInformation = doc2.createElement("RateInformation")
1154
 
            Shipment.appendChild(RateInformation)
1155
 
            NegotiatedRatesIndicator = doc2.createElement("NegotiatedRatesIndicator")
1156
 
            RateInformation.appendChild(NegotiatedRatesIndicator)
1157
 
 
1158
 
            Service = doc2.createElement("Service")
1159
 
            Shipment.appendChild(Service)
1160
 
            Code = doc2.createElement("Code")
1161
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Service"]["Code"])
1162
 
            Code.appendChild(ptext)
1163
 
            Service.appendChild(Code)
1164
 
            Description = doc2.createElement("Description")
1165
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Service"]["Description"])
1166
 
            Description.appendChild(ptext)
1167
 
            Service.appendChild(Description)
1168
 
 
1169
 
            if (package_obj.pick_id.ship_from and package_obj.pick_id.ship_from_address.id and package_obj.pick_id.ship_from_address.country_id.code == 'US' or package_obj.pick_id.shipper.id and package_obj.pick_id.shipper.address.id and package_obj.pick_id.shipper.address.country_id.id and package_obj.pick_id.shipper.address.country_id.code == 'US') and  package_obj.pick_id.address_id.id and package_obj.pick_id.address_id.country_id.code in ('PR','CA'):
1170
 
                InvoiceLineTotal = doc2.createElement("InvoiceLineTotal")
1171
 
                Shipment.appendChild(InvoiceLineTotal)
1172
 
 
1173
 
                MonetaryValue = doc2.createElement("MonetaryValue")
1174
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["InvoiceLineTotal"]["MonetaryValue"])
1175
 
                MonetaryValue.appendChild(ptext)
1176
 
                InvoiceLineTotal.appendChild(MonetaryValue)
1177
 
 
1178
 
            if package_obj.pick_id.sat_delivery:
1179
 
                SaturdayDelivery = doc2.createElement("SaturdayDelivery")
1180
 
                ShipmentServiceOptions.appendChild(SaturdayDelivery)
1181
 
 
1182
 
            Notification_count = len(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"])
1183
 
            for i in range (0,Notification_count):
1184
 
                Notification = doc2.createElement("Notification")
1185
 
                ShipmentServiceOptions.appendChild(Notification)
1186
 
                NotificationCode = doc2.createElement("NotificationCode")
1187
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["NotificationCode"])
1188
 
                NotificationCode.appendChild(ptext)
1189
 
                Notification.appendChild(NotificationCode)
1190
 
                EMailMessage = doc2.createElement("EMailMessage")
1191
 
                Notification.appendChild(EMailMessage)
1192
 
                UndeliverableEMailAddress = doc2.createElement("UndeliverableEMailAddress")
1193
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["UndeliverableEMailAddress"])
1194
 
                UndeliverableEMailAddress.appendChild(ptext)
1195
 
                EMailMessage.appendChild(UndeliverableEMailAddress)
1196
 
 
1197
 
                EMailAddress = doc2.createElement("EMailAddress")
1198
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["EMailAddress"])
1199
 
                EMailAddress.appendChild(ptext)
1200
 
                EMailMessage.appendChild(EMailAddress)
1201
 
 
1202
 
                FromEMailAddress = doc2.createElement("FromEMailAddress")
1203
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["FromEMailAddress"])
1204
 
                FromEMailAddress.appendChild(ptext)
1205
 
                EMailMessage.appendChild(FromEMailAddress)
1206
 
 
1207
 
                FromName = doc2.createElement("FromName")
1208
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["FromName"])
1209
 
                FromName.appendChild(ptext)
1210
 
                EMailMessage.appendChild(FromName)
1211
 
 
1212
 
                Memo = doc2.createElement("Memo")
1213
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["Memo"])
1214
 
                Memo.appendChild(ptext)
1215
 
                EMailMessage.appendChild(Memo)
1216
 
 
1217
 
                Subject = doc2.createElement("Subject")
1218
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["Subject"])
1219
 
                Subject.appendChild(ptext)
1220
 
                EMailMessage.appendChild(Subject)
1221
 
 
1222
 
                SubjectCode = doc2.createElement("SubjectCode")
1223
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipmentServiceOptions"]["Notification"][i]["EMailMessage"]["SubjectCode"])
1224
 
                SubjectCode.appendChild(ptext)
1225
 
                EMailMessage.appendChild(SubjectCode)
1226
 
            ##//////////////////////end for loop in code
1227
 
            if package_obj.pick_id.with_ret_service:
1228
 
                LabelDelivery = doc2.createElement("LabelDelivery")
1229
 
                ShipmentServiceOptions.appendChild(LabelDelivery)
1230
 
                LabelLinkIndicator = doc2.createElement("LabelLinkIndicator")
1231
 
                LabelDelivery.appendChild(LabelLinkIndicator)
1232
 
            
1233
 
            if comm_inv or cer_orig or nafta_cer_orig or sed:
1234
 
                InternationalForms = doc2.createElement("InternationalForms")
1235
 
                ShipmentServiceOptions.appendChild(InternationalForms)
1236
 
                
1237
 
            if comm_inv:
1238
 
                FormType = doc2.createElement("FormType")
1239
 
                ptext = doc1.createTextNode(comm_inv['FormType'])
1240
 
                FormType.appendChild(ptext)
1241
 
                InternationalForms.appendChild(FormType)
1242
 
            if cer_orig:
1243
 
                FormType = doc2.createElement("FormType")
1244
 
                ptext = doc1.createTextNode(cer_orig['FormType'])
1245
 
                FormType.appendChild(ptext)
1246
 
                InternationalForms.appendChild(FormType)
1247
 
            if nafta_cer_orig:
1248
 
                FormType = doc2.createElement("FormType")
1249
 
                ptext = doc1.createTextNode(nafta_cer_orig['FormType'])
1250
 
                FormType.appendChild(ptext)
1251
 
                InternationalForms.appendChild(FormType)
1252
 
                
1253
 
            if sed or nafta_cer_orig:
1254
 
                Contacts = doc2.createElement("Contacts")
1255
 
                InternationalForms.appendChild(Contacts)
1256
 
                if nafta_cer_orig and nafta_cer_orig["Contacts"].get("Producer"):
1257
 
                    Producer = doc2.createElement("Producer")
1258
 
                    Contacts.appendChild(Producer)
1259
 
                    if nafta_cer_orig["Contacts"]['Producer'].get('Option') != ' ':
1260
 
                        Option = doc2.createElement("Option")
1261
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Option'])
1262
 
                        Option.appendChild(ptext)
1263
 
                        Producer.appendChild(Option)
1264
 
                    else:
1265
 
                        CompanyName = doc2.createElement("CompanyName")
1266
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['CompanyName'])
1267
 
                        CompanyName.appendChild(ptext)
1268
 
                        Producer.appendChild(CompanyName)
1269
 
                
1270
 
                        TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber")
1271
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['TaxIdentificationNumber'])
1272
 
                        TaxIdentificationNumber.appendChild(ptext)
1273
 
                        Producer.appendChild(TaxIdentificationNumber)
1274
 
                
1275
 
                        Address = doc2.createElement("Address")
1276
 
                        Producer.appendChild(Address)
1277
 
                
1278
 
                        AddressLine1 = doc2.createElement("AddressLine1")
1279
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Address']['AddressLine1'])
1280
 
                        AddressLine1.appendChild(ptext)
1281
 
                        Address.appendChild(AddressLine1)
1282
 
                
1283
 
                        AddressLine2 = doc2.createElement("AddressLine2")
1284
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Address']['AddressLine2'])
1285
 
                        AddressLine2.appendChild(ptext)
1286
 
                        Address.appendChild(AddressLine2)
1287
 
                
1288
 
                        City = doc2.createElement("City")
1289
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Address']['City'])
1290
 
                        City.appendChild(ptext)
1291
 
                        Address.appendChild(City)
1292
 
                
1293
 
                        StateProvinceCode = doc2.createElement("StateProvinceCode")
1294
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Address']['StateProvinceCode'])
1295
 
                        StateProvinceCode.appendChild(ptext)
1296
 
                        Address.appendChild(StateProvinceCode)
1297
 
                
1298
 
                        PostalCode = doc2.createElement("PostalCode")
1299
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Address']['PostalCode'])
1300
 
                        PostalCode.appendChild(ptext)
1301
 
                        Address.appendChild(PostalCode)
1302
 
                
1303
 
                        CountryCode = doc2.createElement("CountryCode")
1304
 
                        ptext = doc1.createTextNode(nafta_cer_orig["Contacts"]['Producer']['Address']['CountryCode'])
1305
 
                        CountryCode.appendChild(ptext)
1306
 
                        Address.appendChild(CountryCode)
1307
 
            
1308
 
            Product_count = len(prod) > 50 and 50 or len(prod)
1309
 
            if comm_inv or cer_orig or nafta_cer_orig or sed:
1310
 
                for i in range (0,Product_count):
1311
 
       
1312
 
                    Product = doc2.createElement("Product")
1313
 
                    InternationalForms.appendChild(Product)
1314
 
        
1315
 
                    Description = doc2.createElement("Description")
1316
 
                    ptext = doc1.createTextNode(prod[i]['Description'])
1317
 
                    Description.appendChild(ptext)
1318
 
                    Product.appendChild(Description)
1319
 
                    if comm_inv:
1320
 
                        Unit = doc2.createElement("Unit")
1321
 
                        Product.appendChild(Unit)
1322
 
                        Number = doc2.createElement("Number")
1323
 
                        ptext = doc1.createTextNode(prod[i]['Unit']['Number'])
1324
 
                        Number.appendChild(ptext)
1325
 
                        Unit.appendChild(Number)
1326
 
            
1327
 
                        Value = doc2.createElement("Value")
1328
 
                        ptext = doc1.createTextNode(prod[i]['Unit']['Value'])
1329
 
                        Value.appendChild(ptext)
1330
 
                        Unit.appendChild(Value)
1331
 
        
1332
 
                        UnitOfMeasurement = doc2.createElement("UnitOfMeasurement")
1333
 
                        Unit.appendChild(UnitOfMeasurement)
1334
 
                        Code = doc2.createElement("Code")
1335
 
                        ptext = doc1.createTextNode(prod[i]['Unit']['UnitOfMeasurement']['Code'])
1336
 
                        Code.appendChild(ptext)
1337
 
                        UnitOfMeasurement.appendChild(Code)
1338
 
        
1339
 
                        Description = doc2.createElement("Description")
1340
 
                        ptext = doc1.createTextNode(prod[i]['Unit']['UnitOfMeasurement']['Description'])
1341
 
                        Description.appendChild(ptext)
1342
 
                        UnitOfMeasurement.appendChild(Description)
1343
 
                    if nafta_cer_orig or comm_inv:
1344
 
                        CommodityCode = doc2.createElement("CommodityCode")
1345
 
                        ptext = doc1.createTextNode(prod[i]['CommodityCode'])
1346
 
                        CommodityCode.appendChild(ptext)
1347
 
                        Product.appendChild(CommodityCode)
1348
 
                    if nafta_cer_orig or comm_inv or cer_orig:
1349
 
                        OriginCountryCode = doc2.createElement("OriginCountryCode")
1350
 
                        ptext = doc1.createTextNode(prod[i]['OriginCountryCode'])
1351
 
                        OriginCountryCode.appendChild(ptext)
1352
 
                        Product.appendChild(OriginCountryCode)
1353
 
                    if nafta_cer_orig:
1354
 
            
1355
 
                        NetCostCode = doc2.createElement("NetCostCode")
1356
 
                        ptext = doc1.createTextNode(prod[i]['NetCostCode'])
1357
 
                        NetCostCode.appendChild(ptext)
1358
 
                        Product.appendChild(NetCostCode)
1359
 
            
1360
 
            
1361
 
                        PreferenceCriteria = doc2.createElement("PreferenceCriteria")
1362
 
                        ptext = doc1.createTextNode(prod[i]['PreferenceCriteria'])
1363
 
                        PreferenceCriteria.appendChild(ptext)
1364
 
                        Product.appendChild(PreferenceCriteria)
1365
 
 
1366
 
                        
1367
 
                        ProducerInfo = doc2.createElement("ProducerInfo")
1368
 
                        ptext = doc1.createTextNode(prod[i]['ProducerInfo'])
1369
 
                        ProducerInfo.appendChild(ptext)
1370
 
                        Product.appendChild(ProducerInfo)
1371
 
                    if cer_orig:
1372
 
        
1373
 
                        NumberOfPackagesPerCommodity = doc2.createElement("NumberOfPackagesPerCommodity")
1374
 
                        ptext = doc1.createTextNode(prod[i]['NumberOfPackagesPerCommodity'])
1375
 
                        NumberOfPackagesPerCommodity.appendChild(ptext)
1376
 
                        Product.appendChild(NumberOfPackagesPerCommodity)
1377
 
        
1378
 
        
1379
 
                        ProductWeight = doc2.createElement("ProductWeight")
1380
 
                        Product.appendChild(ProductWeight)
1381
 
                        UnitOfMeasurement = doc2.createElement("UnitOfMeasurement")
1382
 
                        ProductWeight.appendChild(UnitOfMeasurement)
1383
 
                        Code = doc2.createElement("Code")
1384
 
                        ptext = doc1.createTextNode(prod[i]['ProductWeight']['UnitOfMeasurement']['Code'])
1385
 
                        Code.appendChild(ptext)
1386
 
                        UnitOfMeasurement.appendChild(Code)
1387
 
            
1388
 
                        Description = doc2.createElement("Description")
1389
 
                        ptext = doc1.createTextNode(prod[i]['ProductWeight']['UnitOfMeasurement']['Description'])
1390
 
                        Description.appendChild(ptext)
1391
 
                        UnitOfMeasurement.appendChild(Description)
1392
 
            
1393
 
                        Weight = doc2.createElement("Weight")
1394
 
                        ptext = doc1.createTextNode(prod[i]['ProductWeight']['Weight'])
1395
 
                        Weight.appendChild(ptext)
1396
 
                        ProductWeight.appendChild(Weight)
1397
 
                #/////////end loop in code
1398
 
        
1399
 
        
1400
 
                if comm_inv:
1401
 
                    if comm_inv.get("InvoiceDate"):
1402
 
                        InvoiceDate = doc2.createElement("InvoiceDate")
1403
 
                        ptext = doc1.createTextNode(comm_inv["InvoiceDate"])
1404
 
                        InvoiceDate.appendChild(ptext)
1405
 
                        InternationalForms.appendChild(InvoiceDate)
1406
 
                    ReasonForExport = doc2.createElement("ReasonForExport")
1407
 
                    ptext = doc1.createTextNode(comm_inv["ReasonForExport"])
1408
 
                    ReasonForExport.appendChild(ptext)
1409
 
                    InternationalForms.appendChild(ReasonForExport)
1410
 
 
1411
 
                    DeclarationStatement = doc2.createElement("DeclarationStatement")
1412
 
                    ptext = doc1.createTextNode(comm_inv["DeclarationStatement"])
1413
 
                    DeclarationStatement.appendChild(ptext)
1414
 
                    InternationalForms.appendChild(DeclarationStatement)
1415
 
       
1416
 
                    CurrencyCode = doc2.createElement("CurrencyCode")
1417
 
                    ptext = doc1.createTextNode(comm_inv["CurrencyCode"])
1418
 
                    CurrencyCode.appendChild(ptext)
1419
 
                    InternationalForms.appendChild(CurrencyCode)
1420
 
                if nafta_cer_orig and nafta_cer_orig.get('BlanketPeriod'):
1421
 
                    BlanketPeriod = doc2.createElement("BlanketPeriod")
1422
 
                    InternationalForms.appendChild(BlanketPeriod)
1423
 
                    
1424
 
                    BeginDate = doc2.createElement("BeginDate")
1425
 
                    ptext = doc1.createTextNode(nafta_cer_orig['BlanketPeriod']["BeginDate"])
1426
 
                    BeginDate.appendChild(ptext)
1427
 
                    BlanketPeriod.appendChild(BeginDate)
1428
 
            
1429
 
                    EndDate = doc2.createElement("EndDate")
1430
 
                    ptext = doc1.createTextNode(nafta_cer_orig['BlanketPeriod']["EndDate"])
1431
 
                    EndDate.appendChild(ptext)
1432
 
                    BlanketPeriod.appendChild(EndDate)
1433
 
                if cer_orig or sed:
1434
 
                    ExportDate = doc2.createElement("ExportDate")
1435
 
                    ptext = doc1.createTextNode(cer_orig['ExportDate'])
1436
 
                    ExportDate.appendChild(ptext)
1437
 
                    InternationalForms.appendChild(ExportDate)
1438
 
            
1439
 
                    ExportingCarrier = doc2.createElement("ExportingCarrier")
1440
 
                    ptext = doc1.createTextNode(cer_orig['ExportingCarrier'])
1441
 
                    ExportingCarrier.appendChild(ptext)
1442
 
                    InternationalForms.appendChild(ExportingCarrier)
1443
 
 
1444
 
            Package_count = len(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"])
1445
 
            for i in range(0,Package_count):
1446
 
                Package = doc2.createElement("Package")
1447
 
                Shipment.appendChild(Package)
1448
 
 
1449
 
                Description = doc2.createElement("Description")
1450
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Description"])
1451
 
                Description.appendChild(ptext)
1452
 
                Package.appendChild(Description)
1453
 
                PackagingType = doc2.createElement("PackagingType")
1454
 
                Package.appendChild(PackagingType)
1455
 
 
1456
 
                Code = doc2.createElement("Code")
1457
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackagingType"]['Code'])
1458
 
                Code.appendChild(ptext)
1459
 
                PackagingType.appendChild(Code)
1460
 
                Description = doc2.createElement("Description")
1461
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackagingType"]['Description'])
1462
 
                Description.appendChild(ptext)
1463
 
                PackagingType.appendChild(Description)
1464
 
 
1465
 
                Dimensions = doc2.createElement("Dimensions")
1466
 
                Package.appendChild(Dimensions)
1467
 
 
1468
 
                Length = doc2.createElement("Length")
1469
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Length"])
1470
 
                Length.appendChild(ptext)
1471
 
                Dimensions.appendChild(Length)
1472
 
                Width = doc2.createElement("Width")
1473
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Width"])
1474
 
                Width.appendChild(ptext)
1475
 
                Dimensions.appendChild(Width)
1476
 
                Height = doc2.createElement("Height")
1477
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Height"])
1478
 
                Height.appendChild(ptext)
1479
 
                Dimensions.appendChild(Height)
1480
 
                UnitOfMeasurement = doc2.createElement("UnitOfMeasurement")
1481
 
                Dimensions.appendChild(UnitOfMeasurement)
1482
 
 
1483
 
                Code = doc2.createElement("Code")
1484
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]['UnitOfMeasurement']["Code"])
1485
 
                Code.appendChild(ptext)
1486
 
                UnitOfMeasurement.appendChild(Code)
1487
 
                Description = doc2.createElement("Description")
1488
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]['UnitOfMeasurement']["Description"])
1489
 
                Description.appendChild(ptext)
1490
 
                UnitOfMeasurement.appendChild(Description)
1491
 
 
1492
 
 
1493
 
                PackageWeight = doc2.createElement("PackageWeight")
1494
 
                Package.appendChild(PackageWeight)
1495
 
 
1496
 
                UnitOfMeasurement = doc2.createElement("UnitOfMeasurement")
1497
 
                PackageWeight.appendChild(UnitOfMeasurement)
1498
 
                Code = doc2.createElement("Code")
1499
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']['UnitOfMeasurement']["Code"])
1500
 
                Code.appendChild(ptext)
1501
 
                UnitOfMeasurement.appendChild(Code)
1502
 
 
1503
 
                Description = doc2.createElement("Description")
1504
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']['UnitOfMeasurement']["Description"])
1505
 
                Description.appendChild(ptext)
1506
 
                UnitOfMeasurement.appendChild(Description)
1507
 
 
1508
 
                Weight = doc2.createElement("Weight")
1509
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']["Weight"])
1510
 
                Weight.appendChild(ptext)
1511
 
                PackageWeight.appendChild(Weight)
1512
 
                
1513
 
                """     <PackageServiceOptions>
1514
 
                            <InsuredValue>
1515
 
                                <CurrencyCode>USD</CurrencyCode>
1516
 
                                <MonetaryValue>1000</MonetaryValue>
1517
 
                            </InsuredValue>
1518
 
                       </PackageServiceOptions>
1519
 
                       
1520
 
                    """
1521
 
                PackageServiceOptions = doc2.createElement("PackageServiceOptions")
1522
 
                
1523
 
                
1524
 
                InsuredValue = doc2.createElement("InsuredValue")
1525
 
                
1526
 
                CurrencyCode = doc2.createElement("CurrencyCode")
1527
 
                ptext = doc1.createTextNode('USD')
1528
 
                CurrencyCode.appendChild(ptext)
1529
 
                
1530
 
                MonetaryValue = doc2.createElement("MonetaryValue")
1531
 
                ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackageServiceOptions"]['InsuredValue']['MonetaryValue'])
1532
 
                MonetaryValue.appendChild(ptext)
1533
 
                
1534
 
                
1535
 
                InsuredValue.appendChild(CurrencyCode)
1536
 
                InsuredValue.appendChild(MonetaryValue)
1537
 
                
1538
 
                PackageServiceOptions.appendChild(InsuredValue)
1539
 
                
1540
 
                Package.appendChild(PackageServiceOptions)
1541
 
               
1542
 
                #/////////end loop in code
1543
 
 
1544
 
            LabelSpecification = doc2.createElement("LabelSpecification")
1545
 
            ShipmentConfirmRequest.appendChild(LabelSpecification)
1546
 
 
1547
 
            LabelPrintMethod = doc2.createElement("LabelPrintMethod")
1548
 
            LabelSpecification.appendChild(LabelPrintMethod)
1549
 
            Code = doc2.createElement("Code")
1550
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelPrintMethod"]["Code"])
1551
 
            Code.appendChild(ptext)
1552
 
            LabelPrintMethod.appendChild(Code)
1553
 
 
1554
 
            Description = doc2.createElement("Description")
1555
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelPrintMethod"]["Description"])
1556
 
            Description.appendChild(ptext)
1557
 
            LabelPrintMethod.appendChild(Description)
1558
 
 
1559
 
            LabelStockSize = doc2.createElement("LabelStockSize")
1560
 
            LabelSpecification.appendChild(LabelStockSize)
1561
 
            Height = doc2.createElement("Height")
1562
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelStockSize"]["Height"])
1563
 
            Height.appendChild(ptext)
1564
 
            LabelStockSize.appendChild(Height)
1565
 
            Width = doc2.createElement("Width")
1566
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelStockSize"]["Width"])
1567
 
            Width.appendChild(ptext)
1568
 
            LabelStockSize.appendChild(Width)
1569
 
 
1570
 
            LabelImageFormat = doc2.createElement("LabelImageFormat")
1571
 
            LabelSpecification.appendChild(LabelImageFormat)
1572
 
 
1573
 
            Code = doc2.createElement("Code")
1574
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelImageFormat"]["Code"])
1575
 
            Code.appendChild(ptext)
1576
 
            LabelImageFormat.appendChild(Code)
1577
 
 
1578
 
            Description = doc2.createElement("Description")
1579
 
            ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelImageFormat"]["Description"])
1580
 
            Description.appendChild(ptext)
1581
 
            LabelImageFormat.appendChild(Description)
1582
 
 
1583
 
            request_string2=doc2.toprettyxml()
1584
 
 
1585
 
            request_string=Request_string1+request_string2
1586
 
 
1587
 
            return request_string
1588
 
 
1589
 
 
1590
 
    def get_value(self, cr, uid, object, message=None, context=None):
1591
 
 
1592
 
        if message is None:
1593
 
            message = {}
1594
 
        #Returns the computed expression
1595
 
        if message:
1596
 
            try:
1597
 
                from mako.template import Template as MakoTemplate
1598
 
                message = tools.ustr(message)
1599
 
               
1600
 
                env = {
1601
 
                    'user':self.pool.get('res.users').browse(cr, uid, uid, context=context),
1602
 
                    'db':cr.dbname
1603
 
                       }
1604
 
                templ = MakoTemplate(message, input_encoding='utf-8')
1605
 
                reply = MakoTemplate(message).render_unicode( object=object,
1606
 
                                                             peobject=object,
1607
 
                                                             env=env,
1608
 
                                                             format_exceptions=True)
1609
 
                
1610
 
                return reply or False
1611
 
            except Exception:
1612
 
                logging.exception("Can't render %r", message)
1613
 
                return u""
1614
 
        else:
1615
 
            return message
1616
 
            
1617
 
 
1618
 
 
1619
 
    def process_ship(self,cr, uid, ids, context=None):
1620
 
        deliv_order = self.browse(cr, uid, type(ids)==type([]) and ids[0] or ids, context=context)
1621
 
        if deliv_order.ship_company_code != 'ups':
1622
 
            return super(stock_picking, self).process_ship(cr, uid, ids, context=context)
1623
 
        error_flag=False
1624
 
        ship_move_ids={}
1625
 
        do_transaction = True
1626
 
        response_dic = {}
1627
 
        if not (deliv_order.logis_company or deliv_order.shipper or deliv_order.ups_service):
1628
 
            raise osv.except_osv("Warning", "Please select Logistics Company, Shipper and Shipping Service")
1629
 
        if not deliv_order.packages_ids:
1630
 
            raise osv.except_osv("Warning", "Please add shipping packages before doing Process Shipping.")
1631
 
        if not deliv_order.invoiced and deliv_order.sale_id and deliv_order.sale_id.order_policy == 'credit_card' :
1632
 
            if not deliv_order.sale_id.cc_pre_auth:
1633
 
                raise osv.except_osv("Warning", "The sales order is not paid")
1634
 
            else:
1635
 
                do_transaction = False
1636
 
                rel_voucher_id = deliv_order.sale_id.rel_account_voucher_id
1637
 
                if rel_voucher_id and rel_voucher_id.state != 'posted' and deliv_order.sale_id.cc_pre_auth:
1638
 
                    self.pool.get('account.voucher').write(cr,uid,[rel_voucher_id.id],{'cc_p_authorize':False,'cc_charge':True}, context=context)
1639
 
                    do_transaction = self.pool.get('account.voucher').authorize(cr, uid, [rel_voucher_id.id], context=context)
1640
 
            if  not do_transaction:
1641
 
                self.write(cr,uid,ids,{'ship_state':'hold','ship_message':'Unable to process creditcard payment.'})
1642
 
                cr.commit()
1643
 
                raise osv.except_osv(_('Final credit card charge cannot be completed!'),_("Please hold shipment and contact customer service..") )
1644
 
        warning_error = False
1645
 
        for pack_obj in deliv_order.packages_ids:
1646
 
            ship_confirm_request_xml=self.create_ship_confirm_request(cr, uid,pack_obj.id)
1647
 
            
1648
 
            ship_confirm_web=''
1649
 
            ship_confirm_port=''
1650
 
 
1651
 
            if deliv_order.logis_company:
1652
 
                if deliv_order.logis_company.test_mode:
1653
 
                    ship_confirm_web=deliv_order.logis_company.ship_req_test_web
1654
 
                    ship_confirm_port=deliv_order.logis_company.ship_req_test_port
1655
 
 
1656
 
                else:
1657
 
                    ship_confirm_web=deliv_order.logis_company.ship_req_web
1658
 
                    ship_confirm_port=deliv_order.logis_company.ship_req_port
1659
 
 
1660
 
                if ship_confirm_web:
1661
 
                    parse_url = urlparse(ship_confirm_web)
1662
 
                    serv = parse_url.netloc
1663
 
                    serv_path = parse_url.path
1664
 
                else:
1665
 
                    raise osv.except_osv(_('Unable to find Shipping URL!'),_("Please configure the shipping company with websites."))
1666
 
 
1667
 
                conn=httplib.HTTPSConnection(serv,ship_confirm_port)
1668
 
                filename="/tmp/ship_confirm_request_" + deliv_order.name.replace('/','') + '.xml'
1669
 
                f = open(filename, 'w')
1670
 
                f.write(ship_confirm_request_xml)
1671
 
                f.close
1672
 
                res=conn.request("POST",serv_path,ship_confirm_request_xml)
1673
 
                """1.make and call function to send request/ 2.make function to process the response and write it """
1674
 
 
1675
 
 
1676
 
                res=conn.getresponse()
1677
 
                result = res.read()
1678
 
                filename= "/tmp/ship_confirm_response_" + deliv_order.name.replace('/','') + '.xml'
1679
 
                
1680
 
                f = open(filename, 'w')
1681
 
                f.write(result)
1682
 
                f.close
1683
 
                response_dic=xml2dic.main(result)
1684
 
 
1685
 
                response = ''
1686
 
                
1687
 
            if not response_dic:
1688
 
                continue
1689
 
            for res_elm in  response_dic['ShipmentConfirmResponse'][0]['Response']:
1690
 
                if res_elm.get('ResponseStatusCode'):
1691
 
                    response = '\nResponse Status Code: '+str(res_elm['ResponseStatusCode'])
1692
 
                if res_elm.get('ResponseStatusDescription'):
1693
 
                    response += '\nResponse Description: '+str(res_elm['ResponseStatusDescription'])
1694
 
                if res_elm.get('Error'):
1695
 
                    
1696
 
                    error_flag =True
1697
 
                    for err_elm in res_elm.get('Error'):
1698
 
                        if err_elm.get('ErrorSeverity',False):
1699
 
                            response += '\nErrorSeverity: '+str(err_elm['ErrorSeverity'])
1700
 
                            if str(err_elm['ErrorSeverity']) == 'Warning':
1701
 
                                warning_error = True
1702
 
                                error_flag = False
1703
 
                        if err_elm.get('ErrorCode',False):
1704
 
                            response += '\nErrorCode: '+str(err_elm['ErrorCode'])
1705
 
                        if err_elm.get('ErrorDescription',False):
1706
 
                            response += '\nErrorDescription: '+str(err_elm['ErrorDescription'])
1707
 
                        if err_elm.get('ErrorLocation',False):
1708
 
                            response += '\nErrorLocation: '+str(err_elm['ErrorLocation'])
1709
 
                    self.write(cr,uid,ids,{'ship_message':'Ship Processing:'+str(response)})
1710
 
                    if not warning_error:
1711
 
                        break
1712
 
            temp=""
1713
 
            if len(response_dic['ShipmentConfirmResponse'])>5 and response_dic['ShipmentConfirmResponse'][5].has_key('ShipmentDigest') :
1714
 
                temp +=str(response_dic['ShipmentConfirmResponse'][5]['ShipmentDigest'])
1715
 
            self.pool.get('stock.packages').write(cr,uid,[pack_obj.id],{'ship_message':str(response),'shipment_digest':str(temp)})
1716
 
 
1717
 
 
1718
 
            if int(time.strftime("%w")) in range(1,6) or (time.strftime("%w") == '6' and deliv_order.sat_delivery):
1719
 
                next_pic_date = time.strftime("%Y-%m-%d")
1720
 
            else:
1721
 
                timedelta = datetime.timedelta(7-int(time.strftime("%w")))
1722
 
                next_pic_date = (datetime.datetime.today()+timedelta).strftime("%Y-%m-%d")
1723
 
 
1724
 
            value_dic={'pick_id':deliv_order.id ,
1725
 
                       'package_weight':pack_obj.weight,
1726
 
                       'state':deliv_order.ship_state,
1727
 
                       'partner_id':deliv_order.address_id.id and deliv_order.address_id.partner_id.id,
1728
 
                       'service':deliv_order.ups_service.id,
1729
 
                       'ship_to':deliv_order.address_id.id,
1730
 
                       'ship_from':deliv_order.ship_from and deliv_order.ship_from_address.id  or deliv_order.shipper.id and deliv_order.shipper.address.id,
1731
 
                       'package':pack_obj.description and str(pack_obj.description)[:126],
1732
 
                       'pic_date':next_pic_date,
1733
 
                       'sale_id':deliv_order.sale_id.id and deliv_order.sale_id.id or False,
1734
 
                       }
1735
 
            if not error_flag:
1736
 
                ship_move_ids[pack_obj.id] = self.pool.get('shipping.move').create(cr, uid, value_dic)
1737
 
                self.process_ship_accept(cr, uid, ids,ship_move_ids,pack_obj,context=context)
1738
 
        if not error_flag:
1739
 
            if warning_error:
1740
 
                ship_msg = 'Shipping success with warning. Please see the individual package details.'
1741
 
            else:
1742
 
                ship_msg = 'Success'
1743
 
            self.write(cr,uid,ids,{'ship_state':'ready_pick','ship_message':ship_msg})
1744
 
            try:
1745
 
                self.send_conf_mail(cr,uid,ids,context=context)
1746
 
            except Exception,e:
1747
 
                pass
1748
 
            if ship_move_ids:
1749
 
                self.pool.get('shipping.move').write(cr, uid, ship_move_ids.values(),{'state':'ready_pick'})
1750
 
            return {
1751
 
                    'type': 'ir.actions.report.xml',
1752
 
                    'report_name':'multiple.label.print',
1753
 
                    'datas': {
1754
 
                            'model':'stock.picking',
1755
 
                            'id': ids and ids[0] or False,
1756
 
                            'ids': ids and ids or [],
1757
 
                            'report_type': 'pdf'
1758
 
                        },
1759
 
                    'nodestroy': True
1760
 
                    }
1761
 
        return True
1762
 
 
1763
 
    def _get_journal_id(self, cr, uid, ids, context={}):
1764
 
        journal_obj = self.pool.get('account.journal')
1765
 
        vals = []
1766
 
        browse_picking = self.browse(cr, uid, ids, context=context)
1767
 
 
1768
 
        for pick in browse_picking:
1769
 
            src_usage = pick.move_lines[0].location_id.usage
1770
 
            dest_usage = pick.move_lines[0].location_dest_id.usage
1771
 
            type = pick.type
1772
 
            if type == 'out' and dest_usage == 'supplier':
1773
 
                journal_type = 'purchase_refund'
1774
 
            elif type == 'out' and dest_usage == 'customer':
1775
 
                journal_type = 'sale'
1776
 
            elif type == 'in' and src_usage == 'supplier':
1777
 
                journal_type = 'purchase'
1778
 
            elif type == 'in' and src_usage == 'customer':
1779
 
                journal_type = 'sale_refund'
1780
 
            else:
1781
 
                journal_type = 'sale'
1782
 
 
1783
 
            value = journal_obj.search(cr, uid, [('type', '=',journal_type )])
1784
 
            for jr_type in journal_obj.browse(cr, uid, value, context=context):
1785
 
                t1 = jr_type.id,jr_type.name
1786
 
                if t1 not in vals:
1787
 
                    vals.append(t1)
1788
 
        return vals
1789
 
 
1790
 
 
1791
 
    def do_partial(self, cr, uid, ids, partial_datas, context=None):
1792
 
        res = self._get_journal_id(cr, uid, ids, context=context)
1793
 
        result_partial = super(stock_picking, self).do_partial(cr, uid, ids, partial_datas, context=context)
1794
 
        if res and res[0]:
1795
 
            journal_id = res[0][0]
1796
 
            result = result_partial
1797
 
            stock_picking_objs = self.browse(cr, uid, ids, context=context)
1798
 
            for stock_picking_obj in stock_picking_objs:
1799
 
                if stock_picking_obj.sale_id and stock_picking_obj.sale_id.order_policy == 'picking':
1800
 
                    pick_id = result_partial[stock_picking_obj.id]['delivered_picking']
1801
 
                    result = self.action_invoice_create(cr, uid, [pick_id], journal_id, type=None, context=context)       
1802
 
                    if len(stock_picking_obj.sale_id.invoice_ids)<=1 and result:
1803
 
                        self.pool.get('account.invoice').write(cr, uid, result.values(),{'ship_method':stock_picking_obj.sale_id.ship_method,
1804
 
                                                                                         'shipcharge':stock_picking_obj.sale_id.shipcharge,
1805
 
                                                                                         'sale_account_id' : stock_picking_obj.sale_id.ship_method_id.account_id.id,
1806
 
                                                                                         'ship_method_id':stock_picking_obj.sale_id.ship_method_id and stock_picking_obj.sale_id.ship_method_id.id,})
1807
 
                        self.pool.get('account.invoice').button_reset_taxes(cr, uid, result.values(), context=context)
1808
 
                        
1809
 
                            
1810
 
        
1811
 
        return result_partial
1812
 
stock_picking()
1813
 
 
1814
 
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: