47599d5f99e72ef5a9225839224998fdfbc5576f
[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"),
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     _columns = {
79         'date': fields.datetime('Date', required=True),
80         'move_ids' : fields.one2many('stock.partial.picking.line', 'wizard_id', 'Product Moves'),
81         'picking_id': fields.many2one('stock.picking', 'Picking', required=True, ondelete='CASCADE'),
82         '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.'),
83      }
84
85     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
86         #override of fields_view_get in order to change the label of the process button and the separator accordingly to the shipping type
87         if context is None:
88             context={}
89         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)
90         type = context.get('default_type', False)
91         if type:
92             doc = etree.XML(res['arch'])
93             for node in doc.xpath("//button[@name='do_partial']"):
94                 if type == 'in':
95                     node.set('string', _('_Receive'))
96                 elif type == 'out':
97                     node.set('string', _('_Deliver'))
98             for node in doc.xpath("//separator[@name='product_separator']"):
99                 if type == 'in':
100                     node.set('string', _('Receive Products'))
101                 elif type == 'out':
102                     node.set('string', _('Deliver Products'))
103             res['arch'] = etree.tostring(doc)
104         return res
105
106     def default_get(self, cr, uid, fields, context=None):
107         if context is None: context = {}
108         res = super(stock_partial_picking, self).default_get(cr, uid, fields, context=context)
109         picking_ids = context.get('active_ids', [])
110         active_model = context.get('active_model')
111
112         if not picking_ids or len(picking_ids) != 1:
113             # Partial Picking Processing may only be done for one picking at a time
114             return res
115         assert active_model in ('stock.picking', 'stock.picking.in', 'stock.picking.out'), 'Bad context propagation'
116         picking_id, = picking_ids
117         if 'picking_id' in fields:
118             res.update(picking_id=picking_id)
119         if 'move_ids' in fields:
120             picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context)
121             moves = [self._partial_move_for(cr, uid, m) for m in picking.move_lines if m.state not in ('done','cancel')]
122             res.update(move_ids=moves)
123         if 'date' in fields:
124             res.update(date=time.strftime(DEFAULT_SERVER_DATETIME_FORMAT))
125         return res
126
127     def _product_cost_for_average_update(self, cr, uid, move):
128         """Returns product cost and currency ID for the given move, suited for re-computing
129            the average product cost.
130
131            :return: map of the form::
132
133                 {'cost': 123.34,
134                  'currency': 42}
135         """
136         # Currently, the cost on the product form is supposed to be expressed in the currency
137         # of the company owning the product. If not set, we fall back to the picking's company,
138         # which should work in simple cases.
139         product_currency_id = move.product_id.company_id.currency_id and move.product_id.company_id.currency_id.id
140         picking_currency_id = move.picking_id.company_id.currency_id and move.picking_id.company_id.currency_id.id
141         return {'cost': move.product_id.standard_price,
142                 'currency': product_currency_id or picking_currency_id or False}
143
144     def _partial_move_for(self, cr, uid, move):
145         partial_move = {
146             'product_id' : move.product_id.id,
147             'quantity' : move.product_qty if move.state in ('assigned','draft','confirmed') else 0,
148             'product_uom' : move.product_uom.id,
149             'prodlot_id' : move.prodlot_id.id,
150             'move_id' : move.id,
151             'location_id' : move.location_id.id,
152             'location_dest_id' : move.location_dest_id.id,
153         }
154         if move.picking_id.type == 'in' and move.product_id.cost_method == 'average':
155             partial_move.update(update_cost=True, **self._product_cost_for_average_update(cr, uid, move))
156         return partial_move
157
158     def do_partial(self, cr, uid, ids, context=None):
159         assert len(ids) == 1, 'Partial picking processing may only be done one at a time.'
160         stock_picking = self.pool.get('stock.picking')
161         stock_move = self.pool.get('stock.move')
162         uom_obj = self.pool.get('product.uom')
163         partial = self.browse(cr, uid, ids[0], context=context)
164         partial_data = {
165             'delivery_date' : partial.date
166         }
167         picking_type = partial.picking_id.type
168         for wizard_line in partial.move_ids:
169             line_uom = wizard_line.product_uom
170             move_id = wizard_line.move_id.id
171
172             #Quantiny must be Positive
173             if wizard_line.quantity < 0:
174                 raise osv.except_osv(_('Warning!'), _('Please provide proper Quantity.'))
175
176             #Compute the quantity for respective wizard_line in the line uom (this jsut do the rounding if necessary)
177             qty_in_line_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, line_uom.id)
178
179             if line_uom.factor and line_uom.factor <> 0:
180                 if float_compare(qty_in_line_uom, wizard_line.quantity, precision_rounding=line_uom.rounding) != 0:
181                     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))
182             if move_id:
183                 #Check rounding Quantity.ex.
184                 #picking: 1kg, uom kg rounding = 0.01 (rounding to 10g),
185                 #partial delivery: 253g
186                 #=> result= refused, as the qty left on picking would be 0.747kg and only 0.75 is accepted by the uom.
187                 initial_uom = wizard_line.move_id.product_uom
188                 #Compute the quantity for respective wizard_line in the initial uom
189                 qty_in_initial_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, initial_uom.id)
190                 without_rounding_qty = (wizard_line.quantity / line_uom.factor) * initial_uom.factor
191                 if float_compare(qty_in_initial_uom, without_rounding_qty, precision_rounding=initial_uom.rounding) != 0:
192                     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))
193             else:
194                 seq_obj_name =  'stock.picking.' + picking_type
195                 move_id = stock_move.create(cr,uid,{'name' : self.pool.get('ir.sequence').get(cr, uid, seq_obj_name),
196                                                     'product_id': wizard_line.product_id.id,
197                                                     'product_qty': wizard_line.quantity,
198                                                     'product_uom': wizard_line.product_uom.id,
199                                                     'prodlot_id': wizard_line.prodlot_id.id,
200                                                     'location_id' : wizard_line.location_id.id,
201                                                     'location_dest_id' : wizard_line.location_dest_id.id,
202                                                     'picking_id': partial.picking_id.id
203                                                     },context=context)
204                 stock_move.action_confirm(cr, uid, [move_id], context)
205             partial_data['move%s' % (move_id)] = {
206                 'product_id': wizard_line.product_id.id,
207                 'product_qty': wizard_line.quantity,
208                 'product_uom': wizard_line.product_uom.id,
209                 'prodlot_id': wizard_line.prodlot_id.id,
210             }
211             if (picking_type == 'in') and (wizard_line.product_id.cost_method == 'average'):
212                 partial_data['move%s' % (wizard_line.move_id.id)].update(product_price=wizard_line.cost,
213                                                                   product_currency=wizard_line.currency.id)
214         stock_picking.do_partial(cr, uid, [partial.picking_id.id], partial_data, context=context)
215         return {'type': 'ir.actions.act_window_close'}
216
217 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: