[IMP/REF] stock: Improve the code and remove the warning message on return picking...
[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):
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         res = super(stock_return_picking, self).default_get(cr, uid, fields, context=context)
43         record_id = context and context.get('active_id', False) or False
44         pick_obj = self.pool.get('stock.picking')
45         pick = pick_obj.browse(cr, uid, record_id)
46         if pick:
47             if 'invoice_state' in fields:
48                 if pick.invoice_state=='invoiced':
49                     res['invoice_state'] = '2binvoiced'
50                 else:
51                     res['invoice_state'] = 'none'
52             for line in pick.move_lines:
53                 return_id = 'return%s'%(line.id)
54                 if return_id in fields:
55                     res[return_id] = line.product_qty
56         return res
57
58     def view_init(self, cr, uid, fields_list, context=None):
59         """ 
60          Creates view dynamically and adding fields at runtime.
61          @param self: The object pointer.
62          @param cr: A database cursor
63          @param uid: ID of the user currently logged in
64          @param context: A standard dictionary 
65          @return: New arch of view with new columns.
66         """
67         res = super(stock_return_picking, self).view_init(cr, uid, fields_list, context=context)
68         record_id = context and context.get('active_id', False) 
69         if record_id:
70             pick_obj = self.pool.get('stock.picking')
71             pick = pick_obj.browse(cr, uid, record_id)
72             for m in [line for line in pick.move_lines]:
73                 if 'return%s'%(m.id) not in self._columns:
74                     self._columns['return%s'%(m.id)] = fields.float(string=m.name, required=True)
75                 if 'invoice_state' not in self._columns:
76                     self._columns['invoice_state'] = fields.selection([('2binvoiced', 'To be Invoiced'), ('none', 'None')], string='Invoice State', required=True)
77                 for rec in m.move_history_ids2:
78                     if rec.product_qty==m.product_qty:
79                         raise osv.except_osv(_('Warning !'), _("There is no product to return!"))
80         return res
81     
82     def fields_view_get(self, cr, uid, view_id=None, view_type='form', 
83                         context=None, toolbar=False, submenu=False):
84         """ 
85          Changes the view dynamically
86          @param self: The object pointer.
87          @param cr: A database cursor
88          @param uid: ID of the user currently logged in
89          @param context: A standard dictionary 
90          @return: New arch of view.
91         """
92         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)
93         record_id = context and context.get('active_id', False)
94         active_model = context.get('active_model')
95         if  active_model != 'stock.picking':
96             return res
97         if record_id:
98             pick_obj = self.pool.get('stock.picking')
99             pick = pick_obj.browse(cr, uid, record_id)
100             if pick.state != 'done':
101                 raise osv.except_osv(_('Warning !'), _("The Picking is not completed yet!\nYou cannot return picking which is not in 'Done' state!"))
102         
103             return_history = {}
104             for m_line in pick.move_lines:
105                 return_history[m_line.id] = 0
106                 for rec in m_line.move_history_ids2:
107                     return_history[m_line.id] += rec.product_qty
108             res['fields'].clear()
109             arch_lst=['<?xml version="1.0"?>', '<form string="%s">' % _('Return lines'), '<label string="%s" colspan="4"/>' % _('Provide the quantities of the returned products.')]
110             for m in [line for line in pick.move_lines]:
111                 quantity = m.product_qty
112                 if quantity > return_history[m.id] and (quantity - return_history[m.id])>0:
113                     arch_lst.append('<field name="return%s"/>\n<newline/>' % (m.id,))
114                     res['fields']['return%s' % m.id]={'string':m.name, 'type':'float', 'required':True} 
115                     res.setdefault('returns', []).append(m.id)
116 #            if not res.get('returns',False): Todo : It may be used 
117 #                raise osv.except_osv(_('Warning!'),_('There is no product to return!'))
118         
119             arch_lst.append('<field name="invoice_state"/>\n<newline/>')
120             if pick.invoice_state=='invoiced':
121                 new_invoice_state='2binvoiced'
122             else:
123                 new_invoice_state=pick.invoice_state
124             res['fields']['invoice_state']={'string':_('Invoice state'), 'type':'selection','required':True, 'selection':[('2binvoiced', _('To Be Invoiced')), ('none', _('None'))]}
125             arch_lst.append('<group col="2" colspan="4">')
126             arch_lst.append('<button icon="gtk-cancel" special="cancel" string="Cancel" />')
127             arch_lst.append('<button name="create_returns" string="Return" colspan="1" type="object" icon="gtk-apply" />')
128             arch_lst.append('</group>')
129             arch_lst.append('</form>')
130             res['arch'] = '\n'.join(arch_lst)
131         return res
132
133     def create_returns(self, cr, uid, ids, context):
134         """ 
135          Creates return picking.
136          @param self: The object pointer.
137          @param cr: A database cursor
138          @param uid: ID of the user currently logged in
139          @param ids: List of ids selected 
140          @param context: A standard dictionary 
141          @return: A dictionary which of fields with values. 
142         """ 
143         record_id = context and context.get('active_id', False) or False
144         move_obj = self.pool.get('stock.move')
145         pick_obj = self.pool.get('stock.picking')
146         uom_obj = self.pool.get('product.uom')
147         wf_service = netsvc.LocalService("workflow")
148     
149         pick = pick_obj.browse(cr, uid, record_id)
150         data = self.read(cr, uid, ids[0])
151         new_picking = None
152         date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
153     
154         move_ids = [m.id for m in [line for line in pick.move_lines]]
155         set_invoice_state_to_none = True
156         for move in move_obj.browse(cr, uid, move_ids):
157             if not new_picking:
158                 if pick.type=='out':
159                     new_type = 'in'
160                 elif pick.type=='in':
161                     new_type = 'out'
162                 else:
163                     new_type = 'internal'
164                 new_picking = pick_obj.copy(cr, uid, pick.id, {'name':'%s (return)' % pick.name,
165                         'move_lines':[], 'state':'draft', 'type':new_type,
166                         'date':date_cur, 'invoice_state':data['invoice_state'],})
167             new_location=move.location_dest_id.id
168     
169             new_qty = data['return%s' % move.id]
170             returned_qty = move.product_qty
171     
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     
178             new_move=move_obj.copy(cr, uid, move.id, {
179                 'product_qty': new_qty,
180                 'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id,
181                     new_qty, move.product_uos.id),
182                 'picking_id':new_picking, 'state':'draft',
183                 'location_id':new_location, 'location_dest_id':move.location_id.id,
184                 'date':date_cur, 'date_planned':date_cur,})
185             move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]})
186     
187         if set_invoice_state_to_none:
188             pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'})
189         if new_picking:
190             if new_picking:
191                 wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
192             pick_obj.force_assign(cr, uid, [new_picking], context)
193             return {
194                 'domain': "[('id', 'in', ["+str(new_picking)+"])]",
195                 'name': 'Picking List',
196                 'view_type':'form',
197                 'view_mode':'tree,form',
198                 'res_model':'stock.picking',
199                 'view_id':False,
200                 'type':'ir.actions.act_window',
201                 'context':context,
202             }            
203         return {}
204     
205 stock_return_picking()
206
207 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
208