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