[IMP] STOCK :RD Project- old style wizard conversion
[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')], 'Invoicing3',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                     
73             for line in pick.move_lines:
74                 return_id = 'return%s'%(line.id)
75                 if return_id in fields:
76                     res[return_id] = line.product_qty
77                 result1.append({'product_id': line.product_id.id, 'quantity': line.product_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             return_history = {}
101             valid_lines = 0
102             for m in [line for line in pick.move_lines]:
103                 if m.state == 'done':
104                     return_history[m.id] = 0
105                     for rec in m.move_history_ids2:
106                         return_history[m.id] += (rec.product_qty * rec.product_uom.factor)
107                     if m.product_qty * m.product_uom.factor >= return_history[m.id]:
108                         valid_lines += 1
109             if not valid_lines:
110                 raise osv.except_osv(_('Warning !'), _("There are no products to return (only lines in Done state and not fully returned yet can be returned)!"))
111         return res
112
113     def fields_view_get(self, cr, uid, view_id=None, view_type='form',
114                         context=None, toolbar=False, submenu=False):
115         """
116          Changes the view dynamically
117          @param self: The object pointer.
118          @param cr: A database cursor
119          @param uid: ID of the user currently logged in
120          @param context: A standard dictionary
121          @return: New arch of view.
122         """
123         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)
124         record_id = context and context.get('active_id', False)
125         active_model = context.get('active_model')
126         if  active_model != 'stock.picking':
127             return res
128         if record_id:
129             pick_obj = self.pool.get('stock.picking')
130             pick = pick_obj.browse(cr, uid, record_id)
131             return_history = {}
132             res['fields'].clear()
133             arch_lst=['<?xml version="1.0"?>', '<form string="%s">' % _('Return lines')]
134             for m in pick.move_lines:
135                 return_history[m.id] = 0
136                 for rec in m.move_history_ids2:
137                     return_history[m.id] += rec.product_qty
138                 quantity = m.product_qty
139             arch_lst.append('<field name="product_return_moves" colspan="4" nolabel="1" mode="tree,form" width="550" height="200" ></field>')
140             _moves_fields = res['fields']
141             arch_lst.append('<field name="invoice_state"/>\n<newline/>')
142             res['fields']['invoice_state']={'string':_('Invoicing'), 'type':'selection','required':True, 'selection':[('2binvoiced', _('To be refunded/invoiced')), ('none', _('No invoicing'))]}
143             _moves_fields.update({
144                             'product_return_moves' : {'relation': 'stock.return.picking.memory', 'type' : 'one2many', 'string' : 'Product Moves'}, 
145                             })
146             arch_lst.append('<group col="2" colspan="4">')
147             arch_lst.append('<separator  colspan="2"/>')
148             arch_lst.append('<button icon="gtk-cancel" special="cancel" string="Cancel" />')
149             arch_lst.append('<button name="create_returns" string="Return" colspan="1" type="object" icon="gtk-apply" />')
150             arch_lst.append('</group>')
151             arch_lst.append('</form>')
152             res['arch'] = '\n'.join(arch_lst)
153             res['fields'] = _moves_fields
154         return res
155
156     def create_returns(self, cr, uid, ids, context=None):
157         """ 
158          Creates return picking.
159          @param self: The object pointer.
160          @param cr: A database cursor
161          @param uid: ID of the user currently logged in
162          @param ids: List of ids selected
163          @param context: A standard dictionary
164          @return: A dictionary which of fields with values.
165         """
166         if context is None:
167             context = {} 
168         record_id = context and context.get('active_id', False) or False
169         move_obj = self.pool.get('stock.move')
170         pick_obj = self.pool.get('stock.picking')
171         uom_obj = self.pool.get('product.uom')
172         data_obj = self.pool.get('stock.return.picking.memory')
173         wf_service = netsvc.LocalService("workflow")
174         pick = pick_obj.browse(cr, uid, record_id, context=context)
175         data = self.read(cr, uid, ids[0])
176         new_picking = None
177         date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
178         set_invoice_state_to_none = True
179         returned_lines = 0
180         
181 #        Create new picking for returned products
182         if pick.type=='out':
183             new_type = 'in'
184         elif pick.type=='in':
185             new_type = 'out'
186         else:
187             new_type = 'internal'
188         new_picking = pick_obj.copy(cr, uid, pick.id, {'name':'%s-return' % pick.name,
189                 'move_lines':[], 'state':'draft', 'type':new_type,
190                 'date':date_cur, 'invoice_state':data['invoice_state'],})
191         
192         val_id = data['product_return_moves']
193         for v in val_id:
194             data_get = data_obj.read(cr, uid, v)
195             mov_id = data_get['move_id']
196             new_qty = data_get['quantity']
197             move = move_obj.browse(cr, uid, mov_id, context=context)
198             new_location=move.location_dest_id.id
199             returned_qty = move.product_qty
200             for rec in move.move_history_ids2:
201                 returned_qty -= rec.product_qty
202
203             if returned_qty != new_qty:
204                 set_invoice_state_to_none = False
205             if new_qty:
206                 returned_lines += 1
207                 new_move=move_obj.copy(cr, uid, move.id, {
208                     'product_qty': new_qty,
209                     'product_uos_qty': uom_obj._compute_qty(cr, uid, move.product_uom.id,
210                         new_qty, move.product_uos.id),
211                     'picking_id':new_picking, 'state':'draft',
212                     'location_id':new_location, 'location_dest_id':move.location_id.id,
213                     'date':date_cur,})
214                 move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]})
215         if not returned_lines:
216             raise osv.except_osv(_('Warning !'), _("Please specify at least one non-zero quantity!"))
217
218         if set_invoice_state_to_none:
219             pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'})
220         wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
221         pick_obj.force_assign(cr, uid, [new_picking], context)
222         # Update view id in context, lp:702939
223         view_list = {
224                 'out': 'view_picking_out_tree',
225                 'in': 'view_picking_in_tree',
226                 'internal': 'vpicktree',
227             }
228         data_obj = self.pool.get('ir.model.data')
229         res = data_obj.get_object_reference(cr, uid, 'stock', view_list.get(new_type, 'vpicktree'))
230         context.update({'view_id': res and res[1] or False})
231         return {
232             'domain': "[('id', 'in', ["+str(new_picking)+"])]",
233             'name': 'Picking List',
234             'view_type':'form',
235             'view_mode':'tree,form',
236             'res_model':'stock.picking',
237             'type':'ir.actions.act_window',
238             'context':context,
239         }
240
241 stock_return_picking()
242
243 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
244