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