[MERGE] lp:~openerp-dev/openobject-addons/trunk-wiz-remove-btn-highlight-tch
[odoo/odoo.git] / addons / stock / wizard / stock_partial_picking.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-TODAY OpenERP SA (<http://openerp.com>).
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 time
23 from lxml import etree
24 from osv import fields, osv
25 from tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
26 import decimal_precision as dp
27 from tools.translate import _
28
29 class stock_partial_picking_line(osv.TransientModel):
30
31     def _tracking(self, cursor, user, ids, name, arg, context=None):
32         res = {}
33         for tracklot in self.browse(cursor, user, ids, context=context):
34             tracking = False
35             if (tracklot.move_id.picking_id.type == 'in' and tracklot.product_id.track_incoming == True) or \
36                 (tracklot.move_id.picking_id.type == 'out' and tracklot.product_id.track_outgoing == True):
37                 tracking = True
38             res[tracklot.id] = tracking
39         return res
40
41
42     _name = "stock.partial.picking.line"
43     _rec_name = 'product_id'
44     _columns = {
45         'product_id' : fields.many2one('product.product', string="Product", required=True, ondelete='CASCADE'),
46         'quantity' : fields.float("Quantity", digits_compute=dp.get_precision('Product Unit of Measure'), required=True),
47         'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, ondelete='CASCADE'),
48         'prodlot_id' : fields.many2one('stock.production.lot', 'Serial Number', ondelete='CASCADE'),
49         'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete='CASCADE', domain = [('usage','<>','view')]),
50         'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, ondelete='CASCADE',domain = [('usage','<>','view')]),
51         'move_id' : fields.many2one('stock.move', "Move", ondelete='CASCADE'),
52         'wizard_id' : fields.many2one('stock.partial.picking', string="Wizard", ondelete='CASCADE'),
53         'update_cost': fields.boolean('Need cost update'),
54         'cost' : fields.float("Cost", help="Unit Cost for this product line"),
55         'currency' : fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'),
56         'tracking': fields.function(_tracking, string='Tracking', type='boolean'), 
57     }
58
59 class stock_partial_picking(osv.osv_memory):
60     _name = "stock.partial.picking"
61     _description = "Partial Picking Processing Wizard"
62
63     def _hide_tracking(self, cursor, user, ids, name, arg, context=None):
64         res = {}
65         for wizard in self.browse(cursor, user, ids, context=context):
66             res[wizard.id] = any([not(x.tracking) for x in wizard.move_ids])
67         return res
68
69     _columns = {
70         'date': fields.datetime('Date', required=True),
71         'move_ids' : fields.one2many('stock.partial.picking.line', 'wizard_id', 'Product Moves'),
72         'picking_id': fields.many2one('stock.picking', 'Picking', required=True, ondelete='CASCADE'),
73         'hide_tracking': fields.function(_hide_tracking, string='Tracking', type='boolean', help='This field is for internal purpose. It is used to decide if the column prodlot has to be shown on the move_ids field or not'),
74      }
75     
76     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
77         #override of fields_view_get in order to change the label of the process button and the separator accordingly to the shipping type
78         if context is None:
79             context={}
80         res = super(stock_partial_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
81         type = context.get('active_model','').split('.')[-1]
82         if type:
83             doc = etree.XML(res['arch'])
84             for node in doc.xpath("//button[@name='do_partial']"):
85                 if type == 'in':
86                     node.set('string', _('_Receive'))
87                 elif type == 'out':
88                     node.set('string', _('_Deliver'))
89             for node in doc.xpath("//separator[@name='product_separator']"):
90                 if type == 'in':
91                     node.set('string', _('Receive Products'))
92                 elif type == 'out':
93                     node.set('string', _('Deliver Products'))
94             res['arch'] = etree.tostring(doc)
95         return res
96
97     def default_get(self, cr, uid, fields, context=None):
98         if context is None: context = {}
99         res = super(stock_partial_picking, self).default_get(cr, uid, fields, context=context)
100         picking_ids = context.get('active_ids', [])
101         if not picking_ids or len(picking_ids) != 1:
102             # Partial Picking Processing may only be done for one picking at a time
103             return res
104         # The check about active_model is there in case the client mismatched the context during propagation of it
105         # (already seen in previous bug where context passed was containing ir.ui.menu as active_model and the menu 
106         # ID as active_id). Though this should be fixed in clients now, this place is sensitive enough to ensure the
107         # consistancy of the context.
108         assert context.get('active_model') in ('stock.picking', 'stock.picking.in', 'stock.picking.out'), 'Bad context propagation'
109         picking_id, = picking_ids
110         if 'picking_id' in fields:
111             res.update(picking_id=picking_id)
112         if 'move_ids' in fields:
113             picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context)
114             moves = [self._partial_move_for(cr, uid, m) for m in picking.move_lines if m.state not in ('done','cancel')]
115             res.update(move_ids=moves)
116         if 'date' in fields:
117             res.update(date=time.strftime(DEFAULT_SERVER_DATETIME_FORMAT))
118         return res
119
120     def _product_cost_for_average_update(self, cr, uid, move):
121         """Returns product cost and currency ID for the given move, suited for re-computing
122            the average product cost.
123
124            :return: map of the form::
125
126                 {'cost': 123.34,
127                  'currency': 42}
128         """
129         # Currently, the cost on the product form is supposed to be expressed in the currency
130         # of the company owning the product. If not set, we fall back to the picking's company,
131         # which should work in simple cases.
132         return {'cost': move.product_id.standard_price,
133                 'currency': move.product_id.company_id.currency_id.id \
134                                 or move.picking_id.company_id.currency_id.id \
135                                 or False}
136
137     def _partial_move_for(self, cr, uid, move):
138         partial_move = {
139             'product_id' : move.product_id.id,
140             'quantity' : move.state in ('assigned','draft','confirmed') and move.product_qty or 0,
141             'product_uom' : move.product_uom.id,
142             'prodlot_id' : move.prodlot_id.id,
143             'move_id' : move.id,
144             'location_id' : move.location_id.id,
145             'location_dest_id' : move.location_dest_id.id,
146         }
147         if move.picking_id.type == 'in' and move.product_id.cost_method == 'average':
148             partial_move.update(update_cost=True, **self._product_cost_for_average_update(cr, uid, move))
149         return partial_move
150
151     def do_partial(self, cr, uid, ids, context=None):
152         assert len(ids) == 1, 'Partial picking processing may only be done one at a time'
153         stock_picking = self.pool.get('stock.picking')
154         stock_move = self.pool.get('stock.move')
155         uom_obj = self.pool.get('product.uom')
156         partial = self.browse(cr, uid, ids[0], context=context)
157         partial_data = {
158             'delivery_date' : partial.date
159         }
160         picking_type = partial.picking_id.type
161         for wizard_line in partial.move_ids:
162             line_uom = wizard_line.product_uom
163             move_id = wizard_line.move_id.id
164
165             #Quantiny must be Positive
166             if wizard_line.quantity < 0:
167                 raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
168
169             #Compute the quantity for respective wizard_line in the line uom (this jsut do the rounding if necessary)
170             qty_in_line_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, line_uom.id)
171
172             if line_uom.factor and line_uom.factor <> 0:
173                 if qty_in_line_uom <> wizard_line.quantity:
174                     raise osv.except_osv(_('Warning'), _('The unit of measure rounding does not allow you to ship "%s %s", only roundings of "%s %s" is accepted by the Unit of Measure.') % (wizard_line.quantity, line_uom.name, line_uom.rounding, line_uom.name))
175             if move_id:
176                 #Check rounding Quantity.ex.
177                 #picking: 1kg, uom kg rounding = 0.01 (rounding to 10g), 
178                 #partial delivery: 253g
179                 #=> result= refused, as the qty left on picking would be 0.747kg and only 0.75 is accepted by the uom.
180                 initial_uom = wizard_line.move_id.product_uom
181                 #Compute the quantity for respective wizard_line in the initial uom
182                 qty_in_initial_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, initial_uom.id)
183                 without_rounding_qty = (wizard_line.quantity / line_uom.factor) * initial_uom.factor
184                 if qty_in_initial_uom <> without_rounding_qty:
185                     raise osv.except_osv(_('Warning'), _('The rounding of the initial uom does not allow you to ship "%s %s", as it would let a quantity of "%s %s" to ship and only roundings of "%s %s" is accepted by the uom.') % (wizard_line.quantity, line_uom.name, wizard_line.move_id.product_qty - without_rounding_qty, initial_uom.name, initial_uom.rounding, initial_uom.name))
186             else:
187                 seq_obj_name =  'stock.picking.' + picking_type
188                 move_id = stock_move.create(cr,uid,{'name' : self.pool.get('ir.sequence').get(cr, uid, seq_obj_name),
189                                                     'product_id': wizard_line.product_id.id,
190                                                     'product_qty': wizard_line.quantity,
191                                                     'product_uom': wizard_line.product_uom.id,
192                                                     'prodlot_id': wizard_line.prodlot_id.id,
193                                                     'location_id' : wizard_line.location_id.id,
194                                                     'location_dest_id' : wizard_line.location_dest_id.id,
195                                                     'picking_id': partial.picking_id.id
196                                                     },context=context)
197                 stock_move.action_confirm(cr, uid, [move_id], context)
198             partial_data['move%s' % (move_id)] = {
199                 'product_id': wizard_line.product_id.id,
200                 'product_qty': wizard_line.quantity,
201                 'product_uom': wizard_line.product_uom.id,
202                 'prodlot_id': wizard_line.prodlot_id.id,
203             }
204             if (picking_type == 'in') and (wizard_line.product_id.cost_method == 'average'):
205                 partial_data['move%s' % (wizard_line.move_id.id)].update(product_price=wizard_line.cost,
206                                                                   product_currency=wizard_line.currency.id)
207         stock_picking.do_partial(cr, uid, [partial.picking_id.id], partial_data, context=context)
208         return {'type': 'ir.actions.act_window_close'}
209
210 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: