[MERGE] lp:~openerp-dev/openobject-addons/trunk-wiz-remove-btn-highlight-tch
[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 Unit of Measure'), 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 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         act_obj = self.pool.get('ir.actions.act_window')
147         model_obj = self.pool.get('ir.model.data')
148         wf_service = netsvc.LocalService("workflow")
149         pick = pick_obj.browse(cr, uid, record_id, context=context)
150         data = self.read(cr, uid, ids[0], context=context)
151         new_picking = None
152         date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
153         set_invoice_state_to_none = True
154         returned_lines = 0
155         
156 #        Create new picking for returned products
157         if pick.type =='out':
158             new_type = 'in'
159         elif pick.type =='in':
160             new_type = 'out'
161         else:
162             new_type = 'internal'
163         new_picking = pick_obj.copy(cr, uid, pick.id, {
164                                         'name': _('%s-return') % pick.name,
165                                         'move_lines': [], 
166                                         'state':'draft', 
167                                         'type': new_type,
168                                         'date':date_cur, 
169                                         'invoice_state': data['invoice_state'],
170         })
171         
172         val_id = data['product_return_moves']
173         for v in val_id:
174             data_get = data_obj.browse(cr, uid, v, context=context)
175             mov_id = data_get.move_id.id
176             new_qty = data_get.quantity
177             move = move_obj.browse(cr, uid, mov_id, context=context)
178             new_location = move.location_dest_id.id
179             returned_qty = move.product_qty
180             for rec in move.move_history_ids2:
181                 returned_qty -= rec.product_qty
182
183             if returned_qty != new_qty:
184                 set_invoice_state_to_none = False
185             if new_qty:
186                 returned_lines += 1
187                 new_move=move_obj.copy(cr, uid, move.id, {
188                                             'product_qty': new_qty,
189                                             'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id, new_qty, move.product_uos.id),
190                                             'picking_id':new_picking, 
191                                             'state': 'draft',
192                                             'location_id': new_location, 
193                                             'location_dest_id': move.location_id.id,
194                                             'date': date_cur,
195                 })
196                 move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]}, context=context)
197         if not returned_lines:
198             raise osv.except_osv(_('Warning !'), _("Please specify at least one non-zero quantity!"))
199
200         if set_invoice_state_to_none:
201             pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'}, context=context)
202         wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
203         pick_obj.force_assign(cr, uid, [new_picking], context)
204         # Update view id in context, lp:702939
205         model_list = {
206                 'out': 'stock.picking.out',
207                 'in': 'stock.picking.in',
208                 'internal': 'stock.picking',
209         }
210         return {
211             'domain': "[('id', 'in', ["+str(new_picking)+"])]",
212             'name': _('Returned Picking'),
213             'view_type':'form',
214             'view_mode':'tree,form',
215             'res_model': model_list.get(new_type, 'stock.picking'),
216             'type':'ir.actions.act_window',
217             'context':context,
218         }
219
220 stock_return_picking()
221
222 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: