5419d2dda2a93178f736ff065444e16db62add8c
[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 openerp.osv import fields, osv
25 from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
26 from openerp.tools.float_utils import float_compare
27 import openerp.addons.decimal_precision as dp
28 from openerp.tools.translate import _
29
30 class stock_partial_picking_line(osv.TransientModel):
31
32     def _tracking(self, cursor, user, ids, name, arg, context=None):
33         res = {}
34         for tracklot in self.browse(cursor, user, ids, context=context):
35             tracking = False
36             if (tracklot.move_id.picking_id.type == 'in' and tracklot.product_id.track_incoming == True) or \
37                 (tracklot.move_id.picking_id.type == 'out' and tracklot.product_id.track_outgoing == True):
38                 tracking = True
39             res[tracklot.id] = tracking
40         return res
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", digits_compute=dp.get_precision('Product Price')),
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     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
60         uom_id = False
61         if product_id:
62             product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
63             uom_id = product.uom_id.id
64         return {'value': {'product_uom': uom_id}}
65
66
67 class stock_partial_picking(osv.osv_memory):
68     _name = "stock.partial.picking"
69     _rec_name = 'picking_id'
70     _description = "Partial Picking Processing Wizard"
71
72     def _hide_tracking(self, cursor, user, ids, name, arg, context=None):
73         res = {}
74         for wizard in self.browse(cursor, user, ids, context=context):
75             res[wizard.id] = any([not(x.tracking) for x in wizard.move_ids])
76         return res
77
78     def __get_help_text(self, cursor, user, picking_id, context=None):
79         text = _("The proposed cost is made based on %s")
80         value = _("standard prices set on the products")
81         return text % value
82
83     def _get_help_text(self, cursor, user, ids, name, arg, context=None):
84         res = {}
85         for wiz in self.browse(cursor, user, ids, context=context):
86             res[wiz.id] = self.__get_help_text(cursor, user, wiz.picking_id.id, context=context)
87         return res
88
89     _columns = {
90         'date': fields.datetime('Date', required=True),
91         'move_ids' : fields.one2many('stock.partial.picking.line', 'wizard_id', 'Product Moves'),
92         'picking_id': fields.many2one('stock.picking', 'Picking', required=True, ondelete='CASCADE'),
93         '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 production lot has to be shown on the moves or not.'),
94         'help_text': fields.function(_get_help_text, string='Note', type='char'),
95      }
96
97     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
98         #override of fields_view_get in order to change the label of the process button and the separator accordingly to the shipping type
99         if context is None:
100             context={}
101         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)
102         type = context.get('default_type', False)
103         if type:
104             doc = etree.XML(res['arch'])
105             for node in doc.xpath("//button[@name='do_partial']"):
106                 if type == 'in':
107                     node.set('string', _('_Receive'))
108                 elif type == 'out':
109                     node.set('string', _('_Deliver'))
110             for node in doc.xpath("//separator[@name='product_separator']"):
111                 if type == 'in':
112                     node.set('string', _('Receive Products'))
113                 elif type == 'out':
114                     node.set('string', _('Deliver Products'))
115             res['arch'] = etree.tostring(doc)
116         return res
117
118     def default_get(self, cr, uid, fields, context=None):
119         if context is None: context = {}
120         res = super(stock_partial_picking, self).default_get(cr, uid, fields, context=context)
121         picking_ids = context.get('active_ids', [])
122         active_model = context.get('active_model')
123
124         if not picking_ids or len(picking_ids) != 1:
125             # Partial Picking Processing may only be done for one picking at a time
126             return res
127         assert active_model in ('stock.picking', 'stock.picking.in', 'stock.picking.out'), 'Bad context propagation'
128         picking_id, = picking_ids
129         if 'picking_id' in fields:
130             res.update(picking_id=picking_id)
131         if 'move_ids' in fields:
132             picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context)
133             moves = [self._partial_move_for(cr, uid, m) for m in picking.move_lines if m.state not in ('done','cancel')]
134             res.update(move_ids=moves)
135         if 'date' in fields:
136             res.update(date=time.strftime(DEFAULT_SERVER_DATETIME_FORMAT))
137         res['help_text'] = self.__get_help_text(cr, uid, picking_id, context=context)
138         return res
139
140     def _product_cost_for_average_update(self, cr, uid, move):
141         """Returns product cost and currency ID for the given move, suited for re-computing
142            the average product cost.
143
144            :return: map of the form::
145
146                 {'cost': 123.34,
147                  'currency': 42}
148         """
149         # Currently, the cost on the product form is supposed to be expressed in the currency
150         # of the company owning the product. If not set, we fall back to the picking's company,
151         # which should work in simple cases.
152         product_currency_id = move.product_id.company_id.currency_id and move.product_id.company_id.currency_id.id
153         picking_currency_id = move.picking_id.company_id.currency_id and move.picking_id.company_id.currency_id.id
154         return {'cost': move.product_id.standard_price,
155                 'currency': product_currency_id or picking_currency_id or False}
156
157     def _partial_move_for(self, cr, uid, move):
158         partial_move = {
159             'product_id' : move.product_id.id,
160             'quantity' : move.product_qty if move.state == 'assigned' or move.picking_id.type == 'in' else 0,
161             'product_uom' : move.product_uom.id,
162             'prodlot_id' : move.prodlot_id.id,
163             'move_id' : move.id,
164             'location_id' : move.location_id.id,
165             'location_dest_id' : move.location_dest_id.id,
166             'currency': move.picking_id and move.picking_id.company_id.currency_id.id or False,
167         }
168         if move.picking_id.type == 'in' and move.product_id.cost_method == 'average':
169             partial_move.update(update_cost=True, **self._product_cost_for_average_update(cr, uid, move))
170         return partial_move
171
172     def do_partial(self, cr, uid, ids, context=None):
173         if context is None:
174             context = {}
175         assert len(ids) == 1, 'Partial picking processing may only be done one at a time.'
176         stock_picking = self.pool.get('stock.picking')
177         stock_move = self.pool.get('stock.move')
178         uom_obj = self.pool.get('product.uom')
179         partial = self.browse(cr, uid, ids[0], context=context)
180         partial_data = {
181             'delivery_date' : partial.date
182         }
183         picking_type = partial.picking_id.type
184         for wizard_line in partial.move_ids:
185             line_uom = wizard_line.product_uom
186             move_id = wizard_line.move_id.id
187
188             #Quantiny must be Positive
189             if wizard_line.quantity < 0:
190                 raise osv.except_osv(_('Warning!'), _('Please provide proper Quantity.'))
191
192             #Compute the quantity for respective wizard_line in the line uom (this jsut do the rounding if necessary)
193             qty_in_line_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, line_uom.id)
194
195             if line_uom.factor and line_uom.factor <> 0:
196                 if float_compare(qty_in_line_uom, wizard_line.quantity, precision_rounding=line_uom.rounding) != 0:
197                     raise osv.except_osv(_('Warning!'), _('The unit of measure rounding does not allow you to ship "%s %s", only rounding of "%s %s" is accepted by the Unit of Measure.') % (wizard_line.quantity, line_uom.name, line_uom.rounding, line_uom.name))
198             if move_id:
199                 #Check rounding Quantity.ex.
200                 #picking: 1kg, uom kg rounding = 0.01 (rounding to 10g),
201                 #partial delivery: 253g
202                 #=> result= refused, as the qty left on picking would be 0.747kg and only 0.75 is accepted by the uom.
203                 initial_uom = wizard_line.move_id.product_uom
204                 #Compute the quantity for respective wizard_line in the initial uom
205                 qty_in_initial_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, initial_uom.id)
206                 without_rounding_qty = (wizard_line.quantity / line_uom.factor) * initial_uom.factor
207                 if float_compare(qty_in_initial_uom, without_rounding_qty, precision_rounding=initial_uom.rounding) != 0:
208                     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 rounding 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))
209             else:
210                 seq_obj_name =  'stock.picking.' + picking_type
211                 move_id = stock_move.create(cr,uid,{'name' : self.pool.get('ir.sequence').get(cr, uid, seq_obj_name),
212                                                     'product_id': wizard_line.product_id.id,
213                                                     'product_qty': wizard_line.quantity,
214                                                     'product_uom': wizard_line.product_uom.id,
215                                                     'prodlot_id': wizard_line.prodlot_id.id,
216                                                     'location_id' : wizard_line.location_id.id,
217                                                     'location_dest_id' : wizard_line.location_dest_id.id,
218                                                     'picking_id': partial.picking_id.id
219                                                     },context=context)
220                 stock_move.action_confirm(cr, uid, [move_id], context)
221             partial_data['move%s' % (move_id)] = {
222                 'product_id': wizard_line.product_id.id,
223                 'product_qty': wizard_line.quantity,
224                 'product_uom': wizard_line.product_uom.id,
225                 'prodlot_id': wizard_line.prodlot_id.id,
226             }
227             if (picking_type == 'in') and (wizard_line.product_id.cost_method == 'average'):
228                 partial_data['move%s' % (wizard_line.move_id.id)].update(product_price=wizard_line.cost,
229                                                                   product_currency=wizard_line.currency.id)
230         
231         # Do the partial delivery and open the picking that was delivered
232         # We don't need to find which view is required, stock.picking does it.
233         done = stock_picking.do_partial(
234             cr, uid, [partial.picking_id.id], partial_data, context=context)
235         if done[partial.picking_id.id]['delivered_picking'] == partial.picking_id.id:
236             return {'type': 'ir.actions.act_window_close'}
237         return {
238             'type': 'ir.actions.act_window',
239             'res_model': context.get('active_model', 'stock.picking'),
240             'name': _('Partial Delivery'),
241             'res_id': done[partial.picking_id.id]['delivered_picking'],
242             'view_type': 'form',
243             'view_mode': 'form,tree,calendar',
244             'context': context,
245         }
246
247 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: