[FIX] stock: check if the move exists to avoid the key error
[odoo/odoo.git] / addons / stock / wizard / stock_return_picking.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 import netsvc
23 import time
24
25 from osv import osv,fields
26 from tools.translate import _
27 import decimal_precision as dp
28
29 class stock_return_picking_memory(osv.osv_memory):
30     _name = "stock.return.picking.memory"
31     _rec_name = 'product_id'
32     _columns = {
33         'product_id' : fields.many2one('product.product', string="Product", required=True),
34         'quantity' : fields.float("Quantity", digits_compute=dp.get_precision('Product UoM'), required=True),
35         'wizard_id' : fields.many2one('stock.return.picking', string="Wizard"),
36         'move_id' : fields.many2one('stock.move', "Move"),
37     }
38
39 stock_return_picking_memory()
40
41
42 class stock_return_picking(osv.osv_memory):
43     _name = 'stock.return.picking'
44     _description = 'Return Picking'
45     _columns = {
46         'product_return_moves' : fields.one2many('stock.return.picking.memory', 'wizard_id', 'Moves'),
47         'invoice_state': fields.selection([('2binvoiced', 'To be refunded/invoiced'), ('none', 'No invoicing')], 'Invoicing',required=True),
48      }
49
50     def default_get(self, cr, uid, fields, context=None):
51         """
52          To get default values for the object.
53          @param self: The object pointer.
54          @param cr: A database cursor
55          @param uid: ID of the user currently logged in
56          @param fields: List of fields for which we want default values
57          @param context: A standard dictionary
58          @return: A dictionary with default values for all field in ``fields``
59         """
60         result1 = []
61         if context is None:
62             context = {}
63         res = super(stock_return_picking, self).default_get(cr, uid, fields, context=context)
64         record_id = context and context.get('active_id', False) or False
65         pick_obj = self.pool.get('stock.picking')
66         pick = pick_obj.browse(cr, uid, record_id, context=context)
67         if pick:
68             if 'invoice_state' in fields:
69                 if pick.invoice_state=='invoiced':
70                     res.update({'invoice_state': '2binvoiced'})
71                 else:
72                     res.update({'invoice_state': 'none'})
73             return_history = self.get_return_history(cr, uid, record_id, context)       
74             for line in pick.move_lines:
75                 qty = line.product_qty - return_history[line.id]
76                 if qty > 0:
77                     result1.append({'product_id': line.product_id.id, 'quantity': qty,'move_id':line.id})
78             if 'product_return_moves' in fields:
79                 res.update({'product_return_moves': result1})
80         return res
81
82     def view_init(self, cr, uid, fields_list, context=None):
83         """
84          Creates view dynamically and adding fields at runtime.
85          @param self: The object pointer.
86          @param cr: A database cursor
87          @param uid: ID of the user currently logged in
88          @param context: A standard dictionary
89          @return: New arch of view with new columns.
90         """
91         if context is None:
92             context = {}
93         res = super(stock_return_picking, self).view_init(cr, uid, fields_list, context=context)
94         record_id = context and context.get('active_id', False)
95         if record_id:
96             pick_obj = self.pool.get('stock.picking')
97             pick = pick_obj.browse(cr, uid, record_id, context=context)
98             if pick.state not in ['done','confirmed','assigned']:
99                 raise osv.except_osv(_('Warning !'), _("You may only return pickings that are Confirmed, Available or Done!"))
100             valid_lines = 0
101             return_history = self.get_return_history(cr, uid, record_id, context)
102             for m  in pick.move_lines:
103                 if return_history.get(m.id) and m.product_qty * m.product_uom.factor > return_history[m.id]:
104                         valid_lines += 1
105             if not valid_lines:
106                 raise osv.except_osv(_('Warning !'), _("There are no products to return (only lines in Done state and not fully returned yet can be returned)!"))
107         return res
108     
109     def get_return_history(self, cr, uid, pick_id, context=None):
110         """ 
111          Get  return_history.
112          @param self: The object pointer.
113          @param cr: A database cursor
114          @param uid: ID of the user currently logged in
115          @param pick_id: Picking id
116          @param context: A standard dictionary
117          @return: A dictionary which of values.
118         """
119         pick_obj = self.pool.get('stock.picking')
120         pick = pick_obj.browse(cr, uid, pick_id, context=context)
121         return_history = {}
122         for m  in pick.move_lines:
123             if m.state == 'done':
124                 return_history[m.id] = 0
125                 for rec in m.move_history_ids2:
126                     return_history[m.id] += (rec.product_qty * rec.product_uom.factor)
127         return return_history
128
129     def create_returns(self, cr, uid, ids, context=None):
130         """ 
131          Creates return picking.
132          @param self: The object pointer.
133          @param cr: A database cursor
134          @param uid: ID of the user currently logged in
135          @param ids: List of ids selected
136          @param context: A standard dictionary
137          @return: A dictionary which of fields with values.
138         """
139         if context is None:
140             context = {} 
141         record_id = context and context.get('active_id', False) or False
142         move_obj = self.pool.get('stock.move')
143         pick_obj = self.pool.get('stock.picking')
144         uom_obj = self.pool.get('product.uom')
145         data_obj = self.pool.get('stock.return.picking.memory')
146         wf_service = netsvc.LocalService("workflow")
147         pick = pick_obj.browse(cr, uid, record_id, context=context)
148         data = self.read(cr, uid, ids[0], context=context)
149         new_picking = None
150         date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
151         set_invoice_state_to_none = True
152         returned_lines = 0
153         
154 #        Create new picking for returned products
155         if pick.type=='out':
156             new_type = 'in'
157         elif pick.type=='in':
158             new_type = 'out'
159         else:
160             new_type = 'internal'
161         new_picking = pick_obj.copy(cr, uid, pick.id, {'name':'%s-return' % pick.name,
162                 'move_lines':[], 'state':'draft', 'type':new_type,
163                 'date':date_cur, 'invoice_state':data['invoice_state'],})
164         
165         val_id = data['product_return_moves']
166         for v in val_id:
167             data_get = data_obj.browse(cr, uid, v, context=context)
168             mov_id = data_get.move_id.id
169             new_qty = data_get.quantity
170             move = move_obj.browse(cr, uid, mov_id, context=context)
171             new_location = move.location_dest_id.id
172             returned_qty = move.product_qty
173             for rec in move.move_history_ids2:
174                 returned_qty -= rec.product_qty
175
176             if returned_qty != new_qty:
177                 set_invoice_state_to_none = False
178             if new_qty:
179                 returned_lines += 1
180                 new_move=move_obj.copy(cr, uid, move.id, {
181                     'product_qty': new_qty,
182                     'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id,
183                         new_qty, move.product_uos.id),
184                     'picking_id':new_picking, 'state':'draft',
185                     'location_id':new_location, 'location_dest_id':move.location_id.id,
186                     'date':date_cur,})
187                 move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]})
188         if not returned_lines:
189             raise osv.except_osv(_('Warning !'), _("Please specify at least one non-zero quantity!"))
190
191         if set_invoice_state_to_none:
192             pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'})
193         wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
194         pick_obj.force_assign(cr, uid, [new_picking], context)
195         # Update view id in context, lp:702939
196         view_list = {
197                 'out': 'view_picking_out_tree',
198                 'in': 'view_picking_in_tree',
199                 'internal': 'vpicktree',
200             }
201         data_obj = self.pool.get('ir.model.data')
202         res = data_obj.get_object_reference(cr, uid, 'stock', view_list.get(new_type, 'vpicktree'))
203         context.update({'view_id': res and res[1] or False})
204         return {
205             'domain': "[('id', 'in', ["+str(new_picking)+"])]",
206             'name': 'Picking List',
207             'view_type':'form',
208             'view_mode':'tree,form',
209             'res_model':'stock.picking',
210             'type':'ir.actions.act_window',
211             'context':context,
212         }
213
214 stock_return_picking()
215
216 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
217