File: stock.py

package info (click to toggle)
tryton-modules-purchase 5.0.6-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,252 kB
  • sloc: python: 2,723; xml: 1,049; makefile: 6; sh: 3
file content (320 lines) | stat: -rw-r--r-- 11,652 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
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
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from functools import wraps

from sql import Null
from sql.aggregate import Max
from sql.operators import Concat

from trytond.model import Workflow, ModelView, fields
from trytond.pyson import Eval
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction

from trytond.modules.product import price_digits

__all__ = ['ShipmentIn', 'ShipmentInReturn', 'Move', 'Location']


def process_purchase(moves_field):
    def _process_purchase(func):
        @wraps(func)
        def wrapper(cls, shipments):
            pool = Pool()
            Purchase = pool.get('purchase.purchase')
            with Transaction().set_context(_check_access=False):
                purchases = set(m.purchase for s in cls.browse(shipments)
                    for m in getattr(s, moves_field) if m.purchase)
            func(cls, shipments)
            if purchases:
                Purchase.__queue__.process(purchases)
        return wrapper
    return _process_purchase


class ShipmentIn(metaclass=PoolMeta):
    __name__ = 'stock.shipment.in'

    @classmethod
    def __setup__(cls):
        super(ShipmentIn, cls).__setup__()
        add_remove = [
            ('supplier', '=', Eval('supplier')),
            ]
        if not cls.incoming_moves.add_remove:
            cls.incoming_moves.add_remove = add_remove
        else:
            cls.incoming_moves.add_remove = [
                add_remove,
                cls.incoming_moves.add_remove,
                ]
        if 'supplier' not in cls.incoming_moves.depends:
            cls.incoming_moves.depends.append('supplier')

        cls._error_messages.update({
                'reset_move': ('You cannot reset to draft move "%s" because '
                    'it was generated by a purchase.'),
                })

    @classmethod
    @ModelView.button
    @Workflow.transition('draft')
    def draft(cls, shipments):
        PurchaseLine = Pool().get('purchase.line')
        for shipment in shipments:
            for move in shipment.incoming_moves:
                if (move.state == 'cancel'
                        and isinstance(move.origin, PurchaseLine)):
                    cls.raise_user_error('reset_move', (move.rec_name,))

        return super(ShipmentIn, cls).draft(shipments)

    @classmethod
    @ModelView.button
    @Workflow.transition('received')
    @process_purchase('incoming_moves')
    def receive(cls, shipments):
        super(ShipmentIn, cls).receive(shipments)

    @classmethod
    @ModelView.button
    @Workflow.transition('cancel')
    @process_purchase('incoming_moves')
    def cancel(cls, shipments):
        super(ShipmentIn, cls).cancel(shipments)


class ShipmentInReturn(metaclass=PoolMeta):
    __name__ = 'stock.shipment.in.return'

    @classmethod
    def __setup__(cls):
        super(ShipmentInReturn, cls).__setup__()
        cls._error_messages.update({
                'reset_move': ('You cannot reset to draft a move generated '
                    'by a purchase.'),
                })

    @classmethod
    def __register__(cls, module_name):
        pool = Pool()
        Move = pool.get('stock.move')
        PurchaseLine = pool.get('purchase.line')
        Purchase = pool.get('purchase.purchase')
        cursor = Transaction().connection.cursor()
        sql_table = cls.__table__()
        move = Move.__table__()
        line = PurchaseLine.__table__()
        purchase = Purchase.__table__()

        # Migration from 3.8: New supplier field
        cursor.execute(*sql_table.select(sql_table.supplier,
                where=sql_table.supplier == Null, limit=1))
        if cursor.fetchone():
            value = sql_table.join(move, condition=(
                    Concat(cls.__name__ + ',', sql_table.id) == move.shipment)
                ).join(line, condition=(
                        Concat(PurchaseLine.__name__ + ',', line.id)
                        == move.origin)
                ).join(purchase,
                    condition=(purchase.id == line.purchase)
                ).select(Max(purchase.party))
            cursor.execute(*sql_table.update(
                    columns=[sql_table.supplier],
                    values=[value]))
        super(ShipmentInReturn, cls).__register__(module_name)

    @classmethod
    @ModelView.button
    @Workflow.transition('draft')
    def draft(cls, shipments):
        PurchaseLine = Pool().get('purchase.line')
        for shipment in shipments:
            for move in shipment.moves:
                if (move.state == 'cancel'
                        and isinstance(move.origin, PurchaseLine)):
                    cls.raise_user_error('reset_move')

        return super(ShipmentInReturn, cls).draft(shipments)

    @classmethod
    @ModelView.button
    @Workflow.transition('done')
    @process_purchase('moves')
    def done(cls, shipments):
        super(ShipmentInReturn, cls).done(shipments)


def process_purchase_move(func):
    @wraps(func)
    def wrapper(cls, moves):
        pool = Pool()
        Purchase = pool.get('purchase.purchase')
        with Transaction().set_context(_check_access=False):
            purchases = set(
                m.purchase for m in cls.browse(moves) if m.purchase)
        func(cls, moves)
        if purchases:
            Purchase.__queue__.process(purchases)
    return wrapper


class Move(metaclass=PoolMeta):
    __name__ = 'stock.move'
    purchase = fields.Function(fields.Many2One('purchase.purchase', 'Purchase',
            states={
                'invisible': ~Eval('purchase_visible', False),
                },
            depends=['purchase_visible']), 'get_purchase',
        searcher='search_purchase')
    purchase_quantity = fields.Function(fields.Float('Purchase Quantity',
            digits=(16, Eval('unit_digits', 2)),
            states={
                'invisible': ~Eval('purchase_visible', False),
                },
            depends=['purchase_visible', 'unit_digits']),
        'get_purchase_fields')
    purchase_unit = fields.Function(fields.Many2One('product.uom',
            'Purchase Unit', states={
                'invisible': ~Eval('purchase_visible', False),
                }, depends=['purchase_visible']), 'get_purchase_fields')
    purchase_unit_digits = fields.Function(fields.Integer(
        'Purchase Unit Digits'), 'get_purchase_fields')
    purchase_unit_price = fields.Function(fields.Numeric('Purchase Unit Price',
            digits=price_digits, states={
                'invisible': ~Eval('purchase_visible', False),
                }, depends=['purchase_visible']), 'get_purchase_fields')
    purchase_currency = fields.Function(fields.Many2One('currency.currency',
            'Purchase Currency', states={
                'invisible': ~Eval('purchase_visible', False),
                }, depends=['purchase_visible']), 'get_purchase_fields')
    purchase_visible = fields.Function(fields.Boolean('Purchase Visible'),
        'on_change_with_purchase_visible')
    supplier = fields.Function(fields.Many2One('party.party', 'Supplier'),
        'get_supplier', searcher='search_supplier')
    purchase_exception_state = fields.Function(fields.Selection([
        ('', ''),
        ('ignored', 'Ignored'),
        ('recreated', 'Recreated'),
        ], 'Exception State'), 'get_purchase_exception_state')

    @classmethod
    def _get_origin(cls):
        models = super(Move, cls)._get_origin()
        models.append('purchase.line')
        return models

    @classmethod
    def check_origin_types(cls):
        types = super(Move, cls).check_origin_types()
        types.add('supplier')
        return types

    def get_purchase(self, name):
        PurchaseLine = Pool().get('purchase.line')
        if isinstance(self.origin, PurchaseLine):
            return self.origin.purchase.id

    @classmethod
    def search_purchase(cls, name, clause):
        return [('origin.' + clause[0],) + tuple(clause[1:3])
            + ('purchase.line',) + tuple(clause[3:])]

    def get_purchase_exception_state(self, name):
        PurchaseLine = Pool().get('purchase.line')
        if not isinstance(self.origin, PurchaseLine):
            return ''
        if self in self.origin.moves_recreated:
            return 'recreated'
        if self in self.origin.moves_ignored:
            return 'ignored'

    def get_purchase_fields(self, name):
        PurchaseLine = Pool().get('purchase.line')
        if isinstance(self.origin, PurchaseLine):
            if name[9:] == 'currency':
                return self.origin.purchase.currency.id
            elif name[9:] in ('quantity', 'unit_digits', 'unit_price'):
                return getattr(self.origin, name[9:])
            else:
                return getattr(self.origin, name[9:]).id
        else:
            if name[9:] == 'quantity':
                return 0.0
            elif name[9:] == 'unit_digits':
                return 2

    @fields.depends('from_location', 'to_location')
    def on_change_with_purchase_visible(self, name=None):
        if self.from_location:
            if self.from_location.type == 'supplier':
                if self.to_location and self.to_location == 'supplier':
                    return False
                return True
        elif self.to_location:
            if self.to_location.type == 'supplier':
                return True
        return False

    def get_supplier(self, name):
        PurchaseLine = Pool().get('purchase.line')
        if isinstance(self.origin, PurchaseLine):
            return self.origin.purchase.party.id

    @fields.depends('origin')
    def on_change_with_product_uom_category(self, name=None):
        pool = Pool()
        PurchaseLine = pool.get('purchase.line')
        category = super(Move, self).on_change_with_product_uom_category(
            name=name)
        # Enforce the same unit category as they are used to compute the
        # remaining quantity to receive and the quantity to invoice.
        # Use getattr as reference field can have negative id
        if (isinstance(self.origin, PurchaseLine)
                and getattr(self.origin, 'unit', None)):
            category = self.origin.unit.category.id
        return category

    @property
    def origin_name(self):
        pool = Pool()
        PurchaseLine = pool.get('purchase.line')
        name = super(Move, self).origin_name
        if isinstance(self.origin, PurchaseLine):
            name = (self.origin.purchase.reference
                or self.origin.purchase.rec_name)
        return name

    @classmethod
    def search_supplier(cls, name, clause):
        return [('origin.purchase.party' + clause[0].lstrip(name),)
            + tuple(clause[1:3]) + ('purchase.line',) + tuple(clause[3:])]

    @classmethod
    @ModelView.button
    @Workflow.transition('cancel')
    @process_purchase_move
    def cancel(cls, moves):
        super(Move, cls).cancel(moves)

    @classmethod
    @process_purchase_move
    def delete(cls, moves):
        super(Move, cls).delete(moves)


class Location(metaclass=PoolMeta):
    __name__ = 'stock.location'

    supplier_return_location = fields.Many2One(
        'stock.location', 'Supplier Return',
        states={
            'invisible': Eval('type') != 'warehouse',
            'readonly': ~Eval('active'),
            },
        domain=[
            ('type', '=', 'storage'),
            ('parent', 'child_of', [Eval('id', -1)]),
            ],
        depends=['type', 'active', 'id'],
        help='If empty the Storage location is used')