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