[MERGE]sync with trunk
[odoo/odoo.git] / addons / stock / wizard / stock_fill_inventory.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from openerp.osv import fields, osv
23 from openerp.tools.translate import _
24
25 class stock_fill_inventory(osv.osv_memory):
26     _name = "stock.fill.inventory"
27     _description = "Import Inventory"
28
29     def _default_location(self, cr, uid, ids, context=None):
30         try:
31             loc_model, location_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock', 'stock_location_stock')
32         except ValueError, e:
33             return False
34         return location_id or False
35
36     _columns = {
37         'location_id': fields.many2one('stock.location', 'Location', required=True),
38         'recursive': fields.boolean("Include children",help="If checked, products contained in child locations of selected location will be included as well."),
39         'set_stock_zero': fields.boolean("Set to zero",help="If checked, all product quantities will be set to zero to help ensure a real physical inventory is done"),
40     }
41     _defaults = {
42         'location_id': _default_location,
43     }
44
45     def view_init(self, cr, uid, fields_list, context=None):
46         """
47          Creates view dynamically and adding fields at runtime.
48          @param self: The object pointer.
49          @param cr: A database cursor
50          @param uid: ID of the user currently logged in
51          @param context: A standard dictionary
52          @return: New arch of view with new columns.
53         """
54         if context is None:
55             context = {}
56         super(stock_fill_inventory, self).view_init(cr, uid, fields_list, context=context)
57
58         if len(context.get('active_ids',[])) > 1:
59             raise osv.except_osv(_('Error!'), _('You cannot perform this operation on more than one Stock Inventories.'))
60
61         if context.get('active_id', False):
62             stock = self.pool.get('stock.inventory').browse(cr, uid, context.get('active_id', False))
63         return True
64
65     def fill_inventory(self, cr, uid, ids, context=None):
66         """ To Import stock inventory according to products available in the selected locations.
67         @param self: The object pointer.
68         @param cr: A database cursor
69         @param uid: ID of the user currently logged in
70         @param ids: the ID or list of IDs if we want more than one
71         @param context: A standard dictionary
72         @return:
73         """
74         if context is None:
75             context = {}
76
77         inventory_line_obj = self.pool.get('stock.inventory.line')
78         location_obj = self.pool.get('stock.location')
79         move_obj = self.pool.get('stock.move')
80         uom_obj = self.pool.get('product.uom')
81         if ids and len(ids):
82             ids = ids[0]
83         else:
84              return {'type': 'ir.actions.act_window_close'}
85         fill_inventory = self.browse(cr, uid, ids, context=context)
86         res = {}
87         res_location = {}
88
89         if fill_inventory.recursive:
90             location_ids = location_obj.search(cr, uid, [('location_id',
91                              'child_of', [fill_inventory.location_id.id])], order="id",
92                              context=context)
93         else:
94             location_ids = [fill_inventory.location_id.id]
95
96         res = {}
97         flag = False
98
99         for location in location_ids:
100             datas = {}
101             res[location] = {}
102             move_ids = move_obj.search(cr, uid, ['|',('location_dest_id','=',location),('location_id','=',location),('state','=','done')], context=context)
103
104             for move in move_obj.browse(cr, uid, move_ids, context=context):
105                 lot_id = move.prodlot_id.id
106                 prod_id = move.product_id.id
107                 if move.location_dest_id.id != move.location_id.id:
108                     if move.location_dest_id.id == location:
109                         qty = uom_obj._compute_qty(cr, uid, move.product_uom.id,move.product_qty, move.product_id.uom_id.id)
110                     else:
111                         qty = -uom_obj._compute_qty(cr, uid, move.product_uom.id,move.product_qty, move.product_id.uom_id.id)
112
113
114                     if datas.get((prod_id, lot_id)):
115                         qty += datas[(prod_id, lot_id)]['product_qty']
116
117                     datas[(prod_id, lot_id)] = {'product_id': prod_id, 'location_id': location, 'product_qty': qty, 'product_uom': move.product_id.uom_id.id, 'prod_lot_id': lot_id}
118
119             if datas:
120                 flag = True
121                 res[location] = datas
122
123         if not flag:
124             raise osv.except_osv(_('Warning!'), _('No product in this location. Please select a location in the product form.'))
125
126         for stock_move in res.values():
127             for stock_move_details in stock_move.values():
128                 stock_move_details.update({'inventory_id': context['active_ids'][0]})
129                 domain = []
130                 for field, value in stock_move_details.items():
131                     if field == 'product_qty' and fill_inventory.set_stock_zero:
132                          domain.append((field, 'in', [value,'0']))
133                          continue
134                     domain.append((field, '=', value))
135
136                 if fill_inventory.set_stock_zero:
137                     stock_move_details.update({'product_qty': 0})
138
139                 line_ids = inventory_line_obj.search(cr, uid, domain, context=context)
140
141                 if not line_ids:
142                     inventory_line_obj.create(cr, uid, stock_move_details, context=context)
143
144         return {'type': 'ir.actions.act_window_close'}
145
146
147 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: