Launchpad automatic translations update.
[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) is not None) 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                     # only take into account 'product return' moves, ignoring any other
127                     # kind of upstream moves, such as internal procurements, etc.
128                     # a valid return move will be the exact opposite of ours:
129                     #     (src location, dest location) <=> (dest location, src location))
130                     if rec.location_dest_id.id == m.location_id.id \
131                         and rec.location_id.id == m.location_dest_id.id:
132                         return_history[m.id] += (rec.product_qty * rec.product_uom.factor)
133         return return_history
134
135     def create_returns(self, cr, uid, ids, context=None):
136         """ 
137          Creates return picking.
138          @param self: The object pointer.
139          @param cr: A database cursor
140          @param uid: ID of the user currently logged in
141          @param ids: List of ids selected
142          @param context: A standard dictionary
143          @return: A dictionary which of fields with values.
144         """
145         if context is None:
146             context = {} 
147         record_id = context and context.get('active_id', False) or False
148         move_obj = self.pool.get('stock.move')
149         pick_obj = self.pool.get('stock.picking')
150         uom_obj = self.pool.get('product.uom')
151         data_obj = self.pool.get('stock.return.picking.memory')
152         wf_service = netsvc.LocalService("workflow")
153         pick = pick_obj.browse(cr, uid, record_id, context=context)
154         data = self.read(cr, uid, ids[0], context=context)
155         new_picking = None
156         date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
157         set_invoice_state_to_none = True
158         returned_lines = 0
159         
160 #        Create new picking for returned products
161         if pick.type=='out':
162             new_type = 'in'
163         elif pick.type=='in':
164             new_type = 'out'
165         else:
166             new_type = 'internal'
167         seq_obj_name = 'stock.picking.' + new_type
168         new_pick_name = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name)
169         new_picking = pick_obj.copy(cr, uid, pick.id, {'name':'%s-%s-return' % (new_pick_name, pick.name),
170                 'move_lines':[], 'state':'draft', 'type':new_type,
171                 'date':date_cur, 'invoice_state':data['invoice_state'],})
172         
173         val_id = data['product_return_moves']
174         for v in val_id:
175             data_get = data_obj.browse(cr, uid, v, context=context)
176             mov_id = data_get.move_id.id
177             new_qty = data_get.quantity
178             move = move_obj.browse(cr, uid, mov_id, context=context)
179             new_location = move.location_dest_id.id
180             returned_qty = move.product_qty
181             for rec in move.move_history_ids2:
182                 returned_qty -= rec.product_qty
183
184             if returned_qty != new_qty:
185                 set_invoice_state_to_none = False
186             if new_qty:
187                 returned_lines += 1
188                 new_move=move_obj.copy(cr, uid, move.id, {
189                     'product_qty': new_qty,
190                     'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id,
191                         new_qty, move.product_uos.id),
192                     'picking_id':new_picking, 'state':'draft',
193                     'location_id':new_location, 'location_dest_id':move.location_id.id,
194                     'date':date_cur,})
195                 move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]})
196         if not returned_lines:
197             raise osv.except_osv(_('Warning !'), _("Please specify at least one non-zero quantity!"))
198
199         if set_invoice_state_to_none:
200             pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'})
201         wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
202         pick_obj.force_assign(cr, uid, [new_picking], context)
203         # Update view id in context, lp:702939
204         view_list = {
205                 'out': 'view_picking_out_tree',
206                 'in': 'view_picking_in_tree',
207                 'internal': 'vpicktree',
208             }
209         data_obj = self.pool.get('ir.model.data')
210         res = data_obj.get_object_reference(cr, uid, 'stock', view_list.get(new_type, 'vpicktree'))
211         context.update({'view_id': res and res[1] or False})
212         return {
213             'domain': "[('id', 'in', ["+str(new_picking)+"])]",
214             'name': 'Picking List',
215             'view_type':'form',
216             'view_mode':'tree,form',
217             'res_model':'stock.picking',
218             'type':'ir.actions.act_window',
219             'context':context,
220         }
221
222 stock_return_picking()
223
224 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
225