[MERGE]: Merge with lp:~openerp-dev/openobject-addons/trunk-dev-addons2
[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             if pick.state not in ['done','confirmed','assigned']:
73                 raise osv.except_osv(_('Warning !'), _("You may only return pickings that are Confirmed, Available or Done!"))
74             return_history = {}
75             valid_lines = 0
76             for m in [line for line in pick.move_lines]:
77                 if m.state == 'done':
78                     return_history[m.id] = 0
79                     for rec in m.move_history_ids2:
80                         return_history[m.id] += (rec.product_qty * rec.product_uom.factor)
81                     if m.product_qty * m.product_uom.factor >= return_history[m.id]:
82                         valid_lines += 1
83                         if 'return%s'%(m.id) not in self._columns:
84                             self._columns['return%s'%(m.id)] = fields.float(string=m.name, required=True)
85                         if 'invoice_state' not in self._columns:
86                             self._columns['invoice_state'] = fields.selection([('2binvoiced', 'To be refunded/invoiced'), ('none', 'No invoicing')], string='Invoicing', required=True)
87             if not valid_lines:
88                 raise osv.except_osv(_('Warning !'), _("There are no products to return (only lines in Done state and not fully returned yet can be returned)!"))
89         return res
90
91     def fields_view_get(self, cr, uid, view_id=None, view_type='form',
92                         context=None, toolbar=False, submenu=False):
93         """
94          Changes the view dynamically
95          @param self: The object pointer.
96          @param cr: A database cursor
97          @param uid: ID of the user currently logged in
98          @param context: A standard dictionary
99          @return: New arch of view.
100         """
101         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)
102         record_id = context and context.get('active_id', False)
103         active_model = context.get('active_model')
104         if  active_model != 'stock.picking':
105             return res
106         if record_id:
107             pick_obj = self.pool.get('stock.picking')
108             pick = pick_obj.browse(cr, uid, record_id)
109             return_history = {}
110             res['fields'].clear()
111             arch_lst=['<?xml version="1.0"?>', '<form string="%s">' % _('Return lines'), '<label string="%s" colspan="4"/>' % _('Provide the quantities of the returned products.')]
112             for m in pick.move_lines:
113                 return_history[m.id] = 0
114                 for rec in m.move_history_ids2:
115                     return_history[m.id] += rec.product_qty
116                 quantity = m.product_qty
117                 if m.state=='done' and quantity > return_history[m.id]:
118                     arch_lst.append('<field name="return%s"/>\n<newline/>' % (m.id,))
119                     res['fields']['return%s' % m.id]={'string':m.name, 'type':'float', 'required':True}
120                     res.setdefault('returns', []).append(m.id)
121             arch_lst.append('<field name="invoice_state"/>\n<newline/>')
122             res['fields']['invoice_state']={'string':_('Invoicing'), 'type':'selection','required':True, 'selection':[('2binvoiced', _('To be refunded/invoiced')), ('none', _('No invoicing'))]}
123             arch_lst.append('<group col="2" colspan="4">')
124             arch_lst.append('<button icon="gtk-cancel" special="cancel" string="Cancel" />')
125             arch_lst.append('<button name="create_returns" string="Return" colspan="1" type="object" icon="gtk-apply" />')
126             arch_lst.append('</group>')
127             arch_lst.append('</form>')
128             res['arch'] = '\n'.join(arch_lst)
129         return res
130
131     def create_returns(self, cr, uid, ids, context):
132         """
133          Creates return picking.
134          @param self: The object pointer.
135          @param cr: A database cursor
136          @param uid: ID of the user currently logged in
137          @param ids: List of ids selected
138          @param context: A standard dictionary
139          @return: A dictionary which of fields with values.
140         """
141         record_id = context and context.get('active_id', False) or False
142         move_obj = self.pool.get('stock.move')
143         pick_obj = self.pool.get('stock.picking')
144         uom_obj = self.pool.get('product.uom')
145         wf_service = netsvc.LocalService("workflow")
146
147         pick = pick_obj.browse(cr, uid, record_id)
148         data = self.read(cr, uid, ids[0])
149         new_picking = None
150         date_cur = time.strftime('%Y-%m-%d %H:%M:%S')
151
152         set_invoice_state_to_none = True
153         returned_lines = 0
154         for move in pick.move_lines:
155             if not new_picking:
156                 if pick.type=='out':
157                     new_type = 'in'
158                 elif pick.type=='in':
159                     new_type = 'out'
160                 else:
161                     new_type = 'internal'
162                 new_picking = pick_obj.copy(cr, uid, pick.id, {'name':'%s-return' % pick.name,
163                         'move_lines':[], 'state':'draft', 'type':new_type,
164                         'date':date_cur, 'invoice_state':data['invoice_state'],})
165             new_location=move.location_dest_id.id
166             if move.state=='done':
167                 new_qty = data['return%s' % move.id]
168                 returned_qty = move.product_qty
169
170                 for rec in move.move_history_ids2:
171                     returned_qty -= rec.product_qty
172
173                 if returned_qty != new_qty:
174                     set_invoice_state_to_none = False
175
176                 if new_qty:
177                     returned_lines += 1
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,})
185                     move_obj.write(cr, uid, [move.id], {'move_history_ids2':[(4,new_move)]})
186
187         if not returned_lines:
188             raise osv.except_osv(_('Warning !'), _("Please specify at least one non-zero quantity!"))
189
190         if set_invoice_state_to_none:
191             pick_obj.write(cr, uid, [pick.id], {'invoice_state':'none'})
192         wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
193         pick_obj.force_assign(cr, uid, [new_picking], context)
194         return {
195             'domain': "[('id', 'in', ["+str(new_picking)+"])]",
196             'name': 'Picking List',
197             'view_type':'form',
198             'view_mode':'tree,form',
199             'res_model':'stock.picking',
200             'view_id':False,
201             'type':'ir.actions.act_window',
202             'context':context,
203         }
204
205 stock_return_picking()
206
207 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
208