forked from OCA/delivery-carrier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock.py
More file actions
343 lines (309 loc) · 13.6 KB
/
stock.py
File metadata and controls
343 lines (309 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) All Rights Reserved 2014 Akretion
# @author David BEAL <david.beal@akretion.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from openerp.osv import orm
from openerp.tools.translate import _
from .report.label import GLSLabel, InvalidDataForMako
from .report.exception_helper import (InvalidAccountNumber)
from .report.label_helper import (
InvalidValueNotInList,
InvalidMissingField,
InvalidType,)
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from datetime import datetime
import pycountry
from operator import attrgetter
EXCEPT_TITLE = "GLS Library Exception"
LABEL_TYPE = 'zpl2'
def raise_exception(orm, message):
raise orm.except_orm(EXCEPT_TITLE, map_except_message(message))
def map_except_message(message):
""" Allows to map vocabulary from external library
to Odoo vocabulary in Exception message
"""
model_mapping = {
'shipper_country': 'partner_id.country_id.code',
}
for key, val in model_mapping.items():
message = message.replace(key, val)
return message
class StockPicking(orm.Model):
_inherit = "stock.picking"
def action_done(self, cr, uid, ids, context=None):
"""
:return: see original method
"""
for picking in self.browse(cr, uid, ids, context=context):
if picking.carrier_type == 'gls':
self.generate_labels(
cr, uid, [picking.id], context=context)
return super(StockPicking, self).action_done(
cr, uid, ids, context=context)
def _customize_gls_picking(self, cr, uid, picking, context=None):
"Use this method to override gls picking"
return True
def _prepare_global_gls(self, cr, uid, picking=None, context=None):
res = {}
param_m = self.pool['ir.config_parameter']
gls_keys = ['carrier_gls_warehouse', 'carrier_gls_customer_code']
ids = param_m.search(cr, uid, [('key', 'in', gls_keys)],
context=context)
for elm in param_m.browse(cr, uid, ids, context=context):
res[elm.key] = elm.value
return res
def _prepare_address_name_gls(self, cr, uid, partner, context=None):
consignee = partner.name
contact = partner.name
if partner.parent_id and partner.use_parent_address:
consignee = partner.parent_id.name
return {'consignee_name': consignee, 'contact': contact}
def _prepare_address_gls(self, cr, uid, picking, context=None):
address = {}
res = self.pool['res.partner']._get_split_address(
cr, uid, picking.partner_id, 3, 35, context=context)
address['street'], address['street2'], address['street3'] = res
country_code = (picking.partner_id and
picking.partner_id.country_id.code or 'FR')
iso_3166 = pycountry.countries.get(alpha2=country_code).numeric
address.update({
"zip": picking.partner_id.zip,
"city": picking.partner_id.city,
"consignee_phone": picking.partner_id.phone,
"consignee_mobile": (picking.partner_id.mobile or
picking.partner_id.phone),
"consignee_email": picking.partner_id.email,
"country_code": picking.partner_id.country_id.code or 'FR',
# useful uniship label only
"country_norme3166": int(iso_3166),
})
destination = self._prepare_address_name_gls(
cr, uid, picking.partner_id, context=context)
address['consignee_name'] = destination['consignee_name'][:35]
address['contact'] = destination['contact'][:35]
return address
def _prepare_delivery_gls(
self, cr, uid, picking, number_of_packages, context=None):
shipping_date = picking.min_date or picking.date
shipping_date = datetime.strptime(
shipping_date, DEFAULT_SERVER_DATETIME_FORMAT)
delivery = {}
delivery.update({
'consignee_ref': picking.name[:20],
'additional_ref_1': u'',
'additional_ref_2': picking.name[:20],
'shipping_date': shipping_date.strftime('%Y%m%d'),
'commentary': picking.note,
'parcel_total_number': number_of_packages,
})
return delivery
def _prepare_sender_gls(self, cr, uid, pick, context=None):
partner = self.pool['stock.picking.out']._get_label_sender_address(
cr, uid, pick, context=context)
global_infos = self._prepare_global_gls(cr, uid, context=context)
sender = {'contact_id': pick.company_id.gls_fr_contact_id,
'customer_id': global_infos['carrier_gls_customer_code'],
'contact_id_inter': pick.company_id.gls_inter_contact_id,
'outbound_depot': global_infos['carrier_gls_warehouse']}
if partner.country_id:
sender['country'] = partner.country_id.name
sender.update({
'shipper_street': partner.street,
'shipper_street2': partner.street2,
'shipper_name': partner.name,
'shipper_country': partner.country_id.code,
'shipper_zip': partner.zip,
'shipper_city': partner.city,
})
return sender
def _prepare_pack_gls(
self, cr, uid, tracking, pack_number, weight=None, context=None):
pack = {}
pack.update({
'parcel_number_label': pack_number,
'parcel_number_barcode': pack_number,
'custom_sequence': self._get_sequence(
cr, uid, 'gls', context=context),
})
if weight:
pack.update({
'weight': "{0:05.2f}".format(weight),
})
else:
if tracking.move_ids:
tracking_weight = [move.weight
for move in tracking.move_ids][0]
pack.update({
'weight': "{0:05.2f}".format(tracking_weight),
})
return pack
def _get_tracking_ids_from_moves(self, cr, uid, picking, context=None):
""" get all the trackings of the picking
no tracking_id will return a False (Browse Null), meaning that
we want a label for the picking
"""
return sorted(set(
line.tracking_id for line in picking.move_lines
), key=attrgetter('name'))
def _get_weight_from_moves_without_tracking(
self, cr, uid, picking, context=None):
weights = [line.weight for line in picking.move_lines
if not line.tracking_id]
return sum(weights)
def _generate_gls_labels(
self, cr, uid, picking, service, tracking_ids=None, context=None):
""" Generate labels and write tracking numbers received """
pack_nbr = 0
pick2update = {}
address = self._prepare_address_gls(cr, uid, picking, context=context)
if tracking_ids is None:
trackings = self._get_tracking_ids_from_moves(
cr, uid, picking, context=context)
else:
# restrict on the provided trackings
trackings = self.pool['stock.tracking'].browse(
cr, uid, tracking_ids, context=context)
labels = []
without_track = 0
for track in trackings:
if not track:
without_track += 1
pick2update['number_of_packages'] = len(trackings) - without_track + 1
delivery = self._prepare_delivery_gls(
cr, uid, picking, pick2update['number_of_packages'],
context=context)
# Write tracking_number on serial field
# for move lines with tracking
# and on picking for other moves
for packing in trackings:
pack_nbr += 1
addr = address.copy()
deliv = delivery.copy()
if not packing:
without_track -= 1
if without_track > 0:
continue
# only executed for the last move line with no tracking
weight = self._get_weight_from_moves_without_tracking(
cr, uid, picking, context=context)
pack = self._prepare_pack_gls(
cr, uid, packing, pack_nbr, weight=weight, context=context)
label = self.get_zpl(service, deliv, addr, pack)
pick2update['carrier_tracking_ref'] = label['tracking_number']
else:
pack = self._prepare_pack_gls(
cr, uid, packing, pack_nbr, context=context)
label = self.get_zpl(service, deliv, addr, pack)
packing.write({'serial': label['tracking_number']})
label_info = {
'tracking_id': packing.id if packing else False,
'file': label['content'],
'file_type': LABEL_TYPE,
'name': label['filename']+'.zpl',
}
if label['tracking_number']:
label_info['name'] = '%s%s.zpl' % (label['tracking_number'],
label['filename'])
labels.append(label_info)
# must be on this stock.picking.out to event on connector
# like in modules prestahop or magento
self.pool['stock.picking.out'].write(cr, uid, picking.id, pick2update,
context=context)
picking = self.browse(cr, uid, picking.id, context=context)
self._customize_gls_picking(cr, uid, picking, context=context)
return labels
def get_zpl(self, service, delivery, address, pack):
try:
result = service.get_label(delivery, address, pack)
except (InvalidMissingField,
InvalidDataForMako,
InvalidValueNotInList,
InvalidAccountNumber,
InvalidType) as e:
raise_exception(orm, e.message)
except Exception, e:
raise orm.except_orm(EXCEPT_TITLE, e.message)
return result
def generate_shipping_labels(
self, cr, uid, ids, tracking_ids=None, context=None):
""" Add label generation for GLS """
if isinstance(ids, (long, int)):
ids = [ids]
assert len(ids) == 1
picking = self.browse(cr, uid, ids[0], context=context)
if picking.carrier_id.type == 'gls':
sender = self._prepare_sender_gls(
cr, uid, picking, context=context)
# gls has a rescue label without webservice required
# if webservice is down
# rescue label is also used for international carrier
test = False
if picking.company_id.gls_test:
test = True
try:
service = GLSLabel(
sender, picking.carrier_code, test_plateform=test)
except InvalidMissingField as e:
raise_exception(orm, e.message)
except Exception as e:
raise_exception(orm, e.message)
return self._generate_gls_labels(
cr, uid, picking, service,
tracking_ids=tracking_ids,
context=context)
return super(StockPicking, self).\
generate_shipping_labels(
cr, uid, ids, tracking_ids=tracking_ids, context=context)
def _get_sequence(self, cr, uid, label_name, context=None):
sequence = self.pool['ir.sequence'].next_by_code(
cr, uid, 'stock.picking_' + label_name, context=context)
if not sequence:
raise orm.except_orm(
_("Picking sequence"),
_("There is no sequence defined for the label '%s'")
% label_name)
return sequence
class StockPickingOut(orm.Model):
_inherit = 'stock.picking.out'
def copy(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
default.update({
'carrier_tracking_ref': None,
})
return super(StockPickingOut, self).copy(
cr, uid, id, default, context=context)
def get_shipping_cost(self, cr, uid, ids, context=None):
return 0
class StockPickingIn(orm.Model):
_inherit = 'stock.picking.in'
def action_generate_carrier_label(self, cr, uid, ids, context=None):
raise orm.except_orm(
"Return label",
"Return Label is not implemented for "
"GLS Carrier \n"
"Ask us for service proposal, http://www.akretion.com/contact")
class ShippingLabel(orm.Model):
_inherit = 'shipping.label'
def _get_file_type_selection(self, cr, uid, context=None):
selection = super(ShippingLabel, self)._get_file_type_selection(
cr, uid, context=None)
selection.append(('zpl2', 'ZPL2'))
selection = list(set(selection))
return selection