File: inventory.py

package info (click to toggle)
tryton-modules-stock 2.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,044 kB
  • sloc: python: 4,468; xml: 2,520; makefile: 7
file content (359 lines) | stat: -rw-r--r-- 12,239 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#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 trytond.model import ModelWorkflow, ModelView, ModelSQL, fields
from trytond.wizard import Wizard
from trytond.pyson import Not, Equal, Eval, Or, Bool
from trytond.backend import TableHandler
from trytond.transaction import Transaction
from trytond.pool import Pool

STATES = {
    'readonly': Not(Equal(Eval('state'), 'draft')),
}
DEPENDS = ['state']


class Inventory(ModelWorkflow, ModelSQL, ModelView):
    'Stock Inventory'
    _name = 'stock.inventory'
    _description = __doc__
    _rec_name = 'location'

    location = fields.Many2One(
        'stock.location', 'Location', required=True,
        domain=[('type', '=', 'storage')], states={
            'readonly': Or(Not(Equal(Eval('state'), 'draft')),
                Bool(Eval('lines'))),
            },
        depends=['state', 'lines'])
    date = fields.Date('Date', required=True, states={
            'readonly': Or(Not(Equal(Eval('state'), 'draft')),
                Bool(Eval('lines'))),
            },
        depends=['state', 'lines'])
    lost_found = fields.Many2One(
        'stock.location', 'Lost and Found', required=True,
        domain=[('type', '=', 'lost_found')], states=STATES, depends=DEPENDS)
    lines = fields.One2Many(
        'stock.inventory.line', 'inventory', 'Lines', states=STATES,
        depends=DEPENDS)
    company = fields.Many2One('company.company', 'Company', required=True,
        states={
            'readonly': Or(Not(Equal(Eval('state'), 'draft')),
                Bool(Eval('lines'))),
            },
        depends=['state', 'lines'])
    state = fields.Selection([
        ('draft', 'Draft'),
        ('done', 'Done'),
        ('cancel', 'Canceled'),
        ], 'State', readonly=True, select=1)

    def __init__(self):
        super(Inventory, self).__init__()
        self._order.insert(0, ('date', 'DESC'))

    def init(self, module_name):
        super(Inventory, self).init(module_name)
        cursor = Transaction().cursor

        # Add index on create_date
        table = TableHandler(cursor, self, module_name)
        table.index_action('create_date', action='add')

    def default_state(self):
        return 'draft'

    def default_date(self):
        date_obj = Pool().get('ir.date')
        return date_obj.today()

    def default_company(self):
        return Transaction().context.get('company') or False

    def default_lost_found(self):
        location_obj = Pool().get('stock.location')
        location_ids = location_obj.search(self.lost_found.domain)
        if len(location_ids) == 1:
            return location_ids[0]
        return False

    def wkf_draft(self, inventory):
        self.write(inventory.id, {
            'state': 'draft',
            })

    def wkf_cancel(self, inventory):
        line_obj = Pool().get("stock.inventory.line")
        line_obj.cancel_move(inventory.lines)
        self.write(inventory.id, {
            'state': 'cancel',
            })

    def wkf_done(self, inventory):
        date_obj = Pool().get('ir.date')
        line_obj = Pool().get('stock.inventory.line')

        for line in inventory.lines:
            line_obj.create_move(line)
        self.write(inventory.id, {
            'state': 'done',
            })

    def copy(self, ids, default=None):
        date_obj = Pool().get('ir.date')
        line_obj = Pool().get('stock.inventory.line')

        int_id = False
        if isinstance(ids, (int, long)):
            int_id = True
            ids = [ids]

        if default is None:
            default = {}
        default = default.copy()
        default['date'] = date_obj.today()
        default['lines'] = False

        new_ids = []
        for inventory in self.browse(ids):
            new_id = super(Inventory, self).copy(inventory.id, default=default)
            line_obj.copy([x.id for x in inventory.lines],
                    default={
                        'inventory': new_id,
                        'move': False,
                        })
            self.complete_lines(new_id)
            new_ids.append(new_id)

        if int_id:
            return new_ids[0]
        return new_ids

    def complete_lines(self, ids):
        '''
        Complete or update the inventories

        :param ids: the ids of stock.inventory
        :param context: the context
        '''
        pool = Pool()
        line_obj = pool.get('stock.inventory.line')
        product_obj = pool.get('product.product')
        uom_obj = pool.get('product.uom')

        if isinstance(ids, (int, long)):
            ids = [ids]

        inventories = self.browse(ids)

        for inventory in inventories:
            # Compute product quantities
            with Transaction().set_context(stock_date_end=inventory.date):
                pbl = product_obj.products_by_location(
                        [inventory.location.id])

            # Index some data
            product2uom = {}
            product2type = {}
            for product in product_obj.browse([line[1] for line in pbl]):
                product2uom[product.id] = product.default_uom.id
                product2type[product.id] = product.type

            product_qty = {}
            for (location, product), quantity in pbl.iteritems():
                product_qty[product] = (quantity, product2uom[product])

            # Update existing lines
            for line in inventory.lines:
                if not (line.product.active and
                        line.product.type == 'stockable'):
                    line_obj.delete(line.id)
                    continue
                if line.product.id in product_qty:
                    quantity, uom_id = product_qty.pop(line.product.id)
                elif line.product.id in product2uom:
                    quantity, uom_id = 0.0, product2uom[line.product.id]
                else:
                    quantity, uom_id = 0.0, line.product.default_uom.id
                values = line_obj.update_values4complete(line, quantity, uom_id)
                if values:
                    line_obj.write(line.id, values)

            # Create lines if needed
            for product_id in product_qty:
                if product2type[product_id] != 'stockable':
                    continue
                quantity, uom_id = product_qty[product_id]
                values = line_obj.create_values4complete(product_id, inventory,
                        quantity, uom_id)
                line_obj.create(values)

Inventory()


class InventoryLine(ModelSQL, ModelView):
    'Stock Inventory Line'
    _name = 'stock.inventory.line'
    _description = __doc__
    _rec_name = 'product'

    product = fields.Many2One('product.product', 'Product', required=True,
            domain=[('type', '=', 'stockable')], on_change=['product'])
    uom = fields.Function(fields.Many2One('product.uom', 'UOM'), 'get_uom')
    unit_digits = fields.Function(fields.Integer('Unit Digits'),
            'get_unit_digits')
    expected_quantity = fields.Float('Expected Quantity',
            digits=(16, Eval('unit_digits', 2)), readonly=True,
            depends=['unit_digits'])
    quantity = fields.Float('Quantity', digits=(16, Eval('unit_digits', 2)),
            depends=['unit_digits'])
    move = fields.Many2One('stock.move', 'Move', readonly=True)
    inventory = fields.Many2One('stock.inventory', 'Inventory', required=True,
            ondelete='CASCADE')

    def __init__(self):
        super(InventoryLine, self).__init__()
        self._sql_constraints += [
            ('check_line_qty_pos',
                'CHECK(quantity >= 0.0)', 'Line quantity must be positive!'),
            ('inventory_product_uniq', 'UNIQUE(inventory, product)',
                'Product must be unique by inventory!'),
        ]
        self._order.insert(0, ('product', 'ASC'))

    def default_unit_digits(self):
        return 2

    def on_change_product(self, vals):
        product_obj = Pool().get('product.product')
        uom_obj = Pool().get('product.uom')
        res = {}
        res['unit_digits'] = 2
        if vals.get('product'):
            product = product_obj.browse(vals['product'])
            res['uom'] = product.default_uom.id
            res['uom.rec_name'] = product.default_uom.rec_name
            res['unit_digits'] = product.default_uom.digits
        return res

    def get_uom(self, ids, name):
        res = {}
        for line in self.browse(ids):
            res[line.id] = line.product.default_uom.id
        return res

    def get_unit_digits(self, ids, name):
        res = {}
        for line in self.browse(ids):
            res[line.id] = line.product.default_uom.digits
        return res

    def cancel_move(self, lines):
        move_obj = Pool().get('stock.move')
        move_obj.write( [l.move.id for l in lines if l.move], {
            'state': 'cancel',
            })
        move_obj.delete([l.move.id for l in lines if l.move])
        self.write([l.id for l in lines if l.move], {
            'move': False,
            })

    def create_move(self, line):
        '''
        Create move for an inventory line

        :param line: a BrowseRecord of inventory.line
        :return: the stock.move id or None
        '''
        move_obj = Pool().get('stock.move')
        uom_obj = Pool().get('product.uom')

        delta_qty = uom_obj.compute_qty(line.uom,
            line.expected_quantity - line.quantity,
            line.uom)
        if delta_qty == 0.0:
            return
        from_location = line.inventory.location.id
        to_location = line.inventory.lost_found.id
        if delta_qty < 0:
            (from_location, to_location, delta_qty) = \
                (to_location, from_location, -delta_qty)

        move_id = move_obj.create({
            'from_location': from_location,
            'to_location': to_location,
            'quantity': delta_qty,
            'product': line.product.id,
            'uom': line.uom.id,
            'company': line.inventory.company.id,
            'state': 'done',
            'effective_date': line.inventory.date,
            })
        self.write(line.id, {
            'move': move_id,
            })
        return move_id

    def update_values4complete(self, line, quantity, uom_id):
        '''
        Return update values to complete inventory

        :param line: a BrowseRecord of inventory.line
        :param quantity: the actual product quantity for the inventory location
        :param uom_id: the UoM id of the product line
        :return: a dictionary
        '''
        res = {}
        # if nothing changed, no update
        if line.quantity == line.expected_quantity == quantity \
                and line.uom.id == uom_id:
            return {}
        res['expected_quantity'] = quantity
        res['uom'] = uom_id
        # update also quantity field if not edited
        if line.quantity == line.expected_quantity:
            res['quantity'] = max(quantity, 0.0)
        return res

    def create_values4complete(self, product_id, inventory, quantity, uom_id):
        '''
        Return create values to complete inventory

        :param product_id: the product.product id
        :param inventory: a BrowseRecord of inventory.inventory
        :param quantity: the actual product quantity for the inventory location
        :param uom_id: the UoM id of the product_id
        :return: a dictionary
        '''
        return {
            'inventory': inventory.id,
            'product': product_id,
            'expected_quantity': quantity,
            'quantity': max(quantity, 0.0),
            'uom': uom_id,
        }

InventoryLine()


class CompleteInventory(Wizard):
    'Complete Inventory'
    _name = 'stock.inventory.complete'
    states = {
        'init': {
            'result': {
                'type': 'action',
                'action': '_complete',
                'state': 'end',
                },
            },
        }

    def _complete(self, data):
        inventory_obj = Pool().get('stock.inventory')
        inventory_obj.complete_lines(data['ids'])

        return {}

CompleteInventory()