File: stock.py

package info (click to toggle)
tryton-modules-stock-package-shipping-dpd 5.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 336 kB
  • sloc: python: 409; xml: 80; makefile: 6; sh: 3
file content (238 lines) | stat: -rw-r--r-- 8,466 bytes parent folder | download | duplicates (2)
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
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

import locale
from io import BytesIO
from lxml import etree
from zeep.exceptions import Fault
from PyPDF2 import PdfFileReader, PdfFileWriter

from trytond.pool import Pool, PoolMeta
from trytond.model import fields
from trytond.wizard import Wizard, StateAction, StateTransition
from trytond.transaction import Transaction

from .configuration import get_client, SHIPMENT_SERVICE

__all__ = ['ShipmentOut', 'CreateShipping', 'CreateDPDShipping']


class ShipmentOut(metaclass=PoolMeta):
    __name__ = 'stock.shipment.out'

    @classmethod
    def __setup__(cls):
        super(ShipmentOut, cls).__setup__()
        cls._error_messages.update({
                'warehouse_address_required': ('An address is required for'
                    ' warehouse "%(warehouse)s".'),
                })

    def validate_packing_dpd(self):
        warehouse_address = self.warehouse.address
        if not warehouse_address:
            self.raise_user_error('warehouse_address_required', {
                    'warehouse': self.warehouse.rec_name,
                    })


class CreateShipping(metaclass=PoolMeta):
    __name__ = 'stock.shipment.create_shipping'

    dpd = StateAction(
        'stock_package_shipping_dpd.act_create_shipping_dpd_wizard')

    def transition_start(self):
        pool = Pool()
        ShipmentOut = pool.get('stock.shipment.out')

        shipment = ShipmentOut(Transaction().context['active_id'])
        next_state = super(CreateShipping, self).transition_start()
        if shipment.carrier.shipping_service == 'dpd':
            next_state = 'dpd'
        return next_state

    def do_dpd(self, action):
        ctx = Transaction().context
        return action, {
            'model': ctx['active_model'],
            'id': ctx['active_id'],
            'ids': [ctx['active_id']],
            }


class CreateDPDShipping(Wizard):
    'Create DPD Shipping'
    __name__ = 'stock.shipment.create_shipping.dpd'

    start = StateTransition()

    @classmethod
    def __setup__(cls):
        super(CreateDPDShipping, cls).__setup__()
        cls._error_messages.update({
                'has_reference_number': ('Shipment "%(shipment)s" already has'
                    ' a reference number.'),
                'dpd_webservice_error': ('DPD webservice call failed with the'
                    ' following error message:\n\n%(message)s'),
                })

    def transition_start(self):
        pool = Pool()
        ShipmentOut = pool.get('stock.shipment.out')
        Package = pool.get('stock.package')

        shipment = ShipmentOut(Transaction().context['active_id'])
        if shipment.reference:
            self.raise_user_error('has_reference_number', {
                    'shipment': shipment.rec_name,
                    })

        credential = self.get_credential(shipment)
        if not credential.depot or not credential.token:
            credential.update_token()

        shipping_client = get_client(credential.server, SHIPMENT_SERVICE)
        print_options = self.get_print_options(shipment)
        packages = shipment.root_packages
        shipment_data = self.get_shipment_data(credential, shipment, packages)

        count = 0
        while count < 2:
            lang = (credential.company.party.lang.code
                if credential.company.party.lang else 'en')
            lang = locale.normalize(lang)[:5]
            authentication = {
                'delisId': credential.user_id,
                'authToken': credential.token,
                'messageLanguage': lang,
                }
            try:
                shipment_response = shipping_client.service.storeOrders(
                    print_options, shipment_data, _soapheaders={
                        'authentication': authentication,
                        })
                break
            except Fault as e:
                tag = etree.QName(e.detail[0].tag)
                if tag.localname == 'authenticationFault':
                    count += 1
                    credential.update_token()
                else:
                    raise
        else:
            self.raise_user_error('can_not_login', {
                    'credential': credential.rec_name,
                    })

        response, = shipment_response.shipmentResponses
        if response.faults:
            message = '\n'.join(f.message for f in response.faults)
            self.raise_user_error('dpd_webservice_error', {
                    'message': message,
                    })

        labels = []
        labels_pdf = BytesIO(shipment_response.parcellabelsPDF)
        reader = PdfFileReader(labels_pdf)
        for page_num in range(reader.getNumPages()):
            new_pdf = PdfFileWriter()
            new_label = BytesIO()
            new_pdf.addPage(reader.getPage(page_num))
            new_pdf.write(new_label)
            labels.append(new_label)

        shipment.reference = response.mpsId
        parcels = response.parcelInformation
        for package, label, parcel in zip(packages, labels, parcels):
            package.shipping_label = fields.Binary.cast(label.getvalue())
            package.shipping_reference = parcel.parcelLabelNumber
        Package.save(shipment.root_packages)
        shipment.save()

        return 'end'

    def get_credential_pattern(self, shipment):
        return {
            'company': shipment.company.id,
            }

    def get_credential(self, shipment):
        pool = Pool()
        DPDCredential = pool.get('carrier.credential.dpd')

        credential_pattern = self.get_credential_pattern(shipment)
        for credential in DPDCredential.search([]):
            if credential.match(credential_pattern):
                return credential

    def get_print_options(self, shipment):
        return {
            'printerLanguage': 'PDF',
            'paperFormat': 'A6',
            }

    def shipping_party(self, party, address):
        shipping_party = {
            'name1': address.party_full_name[:50],
            'name2': '',
            'street': ' '.join((address.street or '').splitlines())[:35],
            'country': address.country.code if address.country else '',
            'zipCode': address.zip[:9],
            'city': address.city[:50],
            }
        if party.full_name != address.party_full_name:
            shipping_party['name2'] = party.full_name[:35]

        phone = email = ''
        for mechanism in party.contact_mechanisms:
            if mechanism.type in {'phone', 'mobile'} and not phone:
                phone = mechanism.value
            if mechanism.type == 'email' and not email:
                email = mechanism.value
        if phone:
            shipping_party['phone'] = phone[:30]
        if email:
            shipping_party['email'] = email[:50]

        return shipping_party

    def get_parcel(self, package):
        pool = Pool()
        UoM = pool.get('product.uom')
        ModelData = pool.get('ir.model.data')

        cm = UoM(ModelData.get_id('product', 'uom_centimeter'))

        parcel = {
            'customerReferenceNumber1': package.code,
            'weight': int(package.total_weight * 10) * 10
            }

        length = UoM.compute_qty(
            package.type.length_uom, package.type.length, cm)
        width = UoM.compute_qty(
            package.type.width_uom, package.type.width, cm)
        height = UoM.compute_qty(
            package.type.height_uom, package.type.height, cm)
        if length < 1000 and width < 1000 and height < 1000:
            parcel['volume'] = '%03i%03i%03i' % (length, width, height)

        return parcel

    def get_shipment_data(self, credential, shipment, packages):
        return {
            'generalShipmentData': {
                'identificationNumber': shipment.number,
                'sendingDepot': credential.depot,
                'product': 'CL',
                'sender': self.shipping_party(
                    shipment.company.party, shipment.warehouse.address),
                'recipient': self.shipping_party(
                    shipment.customer, shipment.delivery_address),
                },
            'parcels': [self.get_parcel(p) for p in packages],
            'productAndServiceData': {
                'orderType': 'consignment',
                }
            }