1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
12 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
18 # You should have received a copy of the GNU Affero General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
22 from datetime import datetime, timedelta
23 from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare
24 from openerp.osv import fields, osv
25 from openerp.tools.safe_eval import safe_eval as eval
26 from openerp.tools.translate import _
28 from openerp import SUPERUSER_ID
30 class sale_order(osv.osv):
31 _inherit = "sale.order"
33 def copy(self, cr, uid, id, default=None, context=None):
40 return super(sale_order, self).copy(cr, uid, id, default, context=context)
42 def _get_default_warehouse(self, cr, uid, context=None):
43 company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
44 warehouse_ids = self.pool.get('stock.warehouse').search(cr, uid, [('company_id', '=', company_id)], context=context)
47 return warehouse_ids[0]
49 def _get_shipped(self, cr, uid, ids, name, args, context=None):
51 for sale in self.browse(cr, uid, ids, context=context):
52 group = sale.procurement_group_id
54 res[sale.id] = all([proc.state in ['cancel', 'done'] for proc in group.procurement_ids])
59 def _get_orders(self, cr, uid, ids, context=None):
61 for move in self.browse(cr, uid, ids, context=context):
62 if move.procurement_id and move.procurement_id.sale_line_id:
63 res.add(move.procurement_id.sale_line_id.order_id.id)
66 def _get_orders_procurements(self, cr, uid, ids, context=None):
68 for proc in self.pool.get('procurement.order').browse(cr, uid, ids, context=context):
69 if proc.state =='done' and proc.sale_line_id:
70 res.add(proc.sale_line_id.order_id.id)
73 def _get_picking_ids(self, cr, uid, ids, name, args, context=None):
75 for sale in self.browse(cr, uid, ids, context=context):
76 if not sale.procurement_group_id:
79 res[sale.id] = self.pool.get('stock.picking').search(cr, uid, [('group_id', '=', sale.procurement_group_id.id)], context=context)
82 def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None):
83 vals = super(sale_order, self)._prepare_order_line_procurement(cr, uid, order, line, group_id=group_id, context=context)
84 location_id = order.partner_shipping_id.property_stock_customer.id
85 vals['location_id'] = location_id
86 routes = line.route_id and [(4, line.route_id.id)] or []
87 vals['route_ids'] = routes
88 vals['warehouse_id'] = order.warehouse_id and order.warehouse_id.id or False
89 vals['partner_dest_id'] = order.partner_shipping_id.id
93 'incoterm': fields.many2one('stock.incoterms', 'Incoterm', help="International Commercial Terms are a series of predefined commercial terms used in international transactions."),
94 'picking_policy': fields.selection([('direct', 'Deliver each product when available'), ('one', 'Deliver all products at once')],
95 'Shipping Policy', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
96 help="""Pick 'Deliver each product when available' if you allow partial delivery."""),
97 'order_policy': fields.selection([
98 ('manual', 'On Demand'),
99 ('picking', 'On Delivery Order'),
100 ('prepaid', 'Before Delivery'),
101 ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
102 help="""On demand: A draft invoice can be created from the sales order when needed. \nOn delivery order: A draft invoice can be created from the delivery order when the products have been delivered. \nBefore delivery: A draft invoice is created from the sales order and must be paid before the products can be delivered."""),
103 'shipped': fields.function(_get_shipped, string='Delivered', type='boolean', store={
104 'procurement.order': (_get_orders_procurements, ['state'], 10)
106 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True),
107 'picking_ids': fields.function(_get_picking_ids, method=True, type='one2many', relation='stock.picking', string='Picking associated to this sale'),
110 'warehouse_id': _get_default_warehouse,
111 'picking_policy': 'direct',
112 'order_policy': 'manual',
114 def onchange_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):
117 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
118 if warehouse.company_id:
119 val['company_id'] = warehouse.company_id.id
120 return {'value': val}
122 def action_view_delivery(self, cr, uid, ids, context=None):
124 This function returns an action that display existing delivery orders
125 of given sales order ids. It can either be a in a list or in a form
126 view, if there is only one delivery order to show.
129 mod_obj = self.pool.get('ir.model.data')
130 act_obj = self.pool.get('ir.actions.act_window')
132 result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_picking_tree_all')
133 id = result and result[1] or False
134 result = act_obj.read(cr, uid, [id], context=context)[0]
136 #compute the number of delivery orders to display
138 for so in self.browse(cr, uid, ids, context=context):
139 pick_ids += [picking.id for picking in so.picking_ids]
141 #choose the view_mode accordingly
142 if len(pick_ids) > 1:
143 result['domain'] = "[('id','in',[" + ','.join(map(str, pick_ids)) + "])]"
145 res = mod_obj.get_object_reference(cr, uid, 'stock', 'view_picking_form')
146 result['views'] = [(res and res[1] or False, 'form')]
147 result['res_id'] = pick_ids and pick_ids[0] or False
150 def action_invoice_create(self, cr, uid, ids, grouped=False, states=['confirmed', 'done', 'exception'], date_invoice = False, context=None):
151 move_obj = self.pool.get("stock.move")
152 res = super(sale_order,self).action_invoice_create(cr, uid, ids, grouped=grouped, states=states, date_invoice = date_invoice, context=context)
153 for order in self.browse(cr, uid, ids, context=context):
154 if order.order_policy == 'picking':
155 for picking in order.picking_ids:
156 move_obj.write(cr, uid, [x.id for x in picking.move_lines], {'invoice_state': 'invoiced'}, context=context)
159 def action_cancel(self, cr, uid, ids, context=None):
162 sale_order_line_obj = self.pool.get('sale.order.line')
163 proc_obj = self.pool.get('procurement.order')
164 stock_obj = self.pool.get('stock.picking')
165 for sale in self.browse(cr, uid, ids, context=context):
166 for pick in sale.picking_ids:
167 if pick.state not in ('draft', 'cancel'):
168 raise osv.except_osv(
169 _('Cannot cancel sales order!'),
170 _('You must first cancel all delivery order(s) attached to this sales order.'))
171 stock_obj.signal_button_cancel(cr, uid, [p.id for p in sale.picking_ids])
172 return super(sale_order, self).action_cancel(cr, uid, ids, context=context)
174 def action_wait(self, cr, uid, ids, context=None):
175 res = super(sale_order, self).action_wait(cr, uid, ids, context=context)
176 for o in self.browse(cr, uid, ids):
177 noprod = self.test_no_product(cr, uid, o, context)
178 if noprod and o.order_policy=='picking':
179 self.write(cr, uid, [o.id], {'order_policy': 'manual'}, context=context)
182 def _get_date_planned(self, cr, uid, order, line, start_date, context=None):
183 date_planned = super(sale_order, self)._get_date_planned(cr, uid, order, line, start_date, context=context)
184 date_planned = (date_planned - timedelta(days=order.company_id.security_lead)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
187 def _prepare_procurement_group(self, cr, uid, order, context=None):
188 res = super(sale_order, self)._prepare_procurement_group(cr, uid, order, context=None)
189 res.update({'move_type': order.picking_policy})
192 def action_ship_end(self, cr, uid, ids, context=None):
193 super(sale_order, self).action_ship_end(cr, uid, ids, context=context)
194 for order in self.browse(cr, uid, ids, context=context):
195 val = {'shipped': True}
196 if order.state == 'shipping_except':
197 val['state'] = 'progress'
198 if (order.order_policy == 'manual'):
199 for line in order.order_line:
200 if (not line.invoiced) and (line.state not in ('cancel', 'draft')):
201 val['state'] = 'manual'
203 res = self.write(cr, uid, [order.id], val)
209 def has_stockable_products(self, cr, uid, ids, *args):
210 for order in self.browse(cr, uid, ids):
211 for order_line in order.order_line:
212 if order_line.product_id and order_line.product_id.type in ('product', 'consu'):
217 class sale_order_line(osv.osv):
218 _inherit = 'sale.order.line'
220 def need_procurement(self, cr, uid, ids, context=None):
221 #when sale is installed alone, there is no need to create procurements, but with sale_stock
222 #we must create a procurement for each product that is not a service.
223 for line in self.browse(cr, uid, ids, context=context):
224 if line.product_id and line.product_id.type != 'service':
226 return super(sale_order_line, self).need_procurement(cr, uid, ids, context=context)
228 def _number_packages(self, cr, uid, ids, field_name, arg, context=None):
230 for line in self.browse(cr, uid, ids, context=context):
232 res[line.id] = int((line.product_uom_qty+line.product_packaging.qty-0.0001) / line.product_packaging.qty)
238 'product_packaging': fields.many2one('product.packaging', 'Packaging'),
239 'number_packages': fields.function(_number_packages, type='integer', string='Number Packages'),
240 'route_id': fields.many2one('stock.location.route', 'Route', domain=[('sale_selectable', '=', True)]),
244 'product_packaging': False,
247 def button_cancel(self, cr, uid, ids, context=None):
248 res = super(sale_order_line, self).button_cancel(cr, uid, ids, context=context)
249 for line in self.browse(cr, uid, ids, context=context):
250 for move_line in line.move_ids:
251 if move_line.state != 'cancel':
252 raise osv.except_osv(
253 _('Cannot cancel sales order line!'),
254 _('You must first cancel stock moves attached to this sales order line.'))
257 def copy_data(self, cr, uid, id, default=None, context=None):
260 default.update({'move_ids': []})
261 return super(sale_order_line, self).copy_data(cr, uid, id, default, context=context)
263 def product_packaging_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False,
264 partner_id=False, packaging=False, flag=False, context=None):
266 return {'value': {'product_packaging': False}}
267 product_obj = self.pool.get('product.product')
268 product_uom_obj = self.pool.get('product.uom')
269 pack_obj = self.pool.get('product.packaging')
274 res = self.product_id_change(cr, uid, ids, pricelist=pricelist,
275 product=product, qty=qty, uom=uom, partner_id=partner_id,
276 packaging=packaging, flag=False, context=context)
277 warning_msgs = res.get('warning') and res['warning'].get('message', '') or ''
279 products = product_obj.browse(cr, uid, product, context=context)
280 if not products.packaging_ids:
281 packaging = result['product_packaging'] = False
284 default_uom = products.uom_id and products.uom_id.id
285 pack = pack_obj.browse(cr, uid, packaging, context=context)
286 q = product_uom_obj._compute_qty(cr, uid, uom, pack.qty, default_uom)
287 # qty = qty - qty % q + q
288 if qty and (q and not (qty % q) == 0):
289 ean = pack.ean or _('(n/a)')
293 warn_msg = _("You selected a quantity of %d Units.\n"
294 "But it's not compatible with the selected packaging.\n"
295 "Here is a proposition of quantities according to the packaging:\n"
296 "EAN: %s Quantity: %s Type of ul: %s") % \
297 (qty, ean, qty_pack, type_ul.name)
298 warning_msgs += _("Picking Information ! : ") + warn_msg + "\n\n"
300 'title': _('Configuration Error!'),
301 'message': warning_msgs
303 result['product_uom_qty'] = qty
305 return {'value': result, 'warning': warning}
308 def product_id_change_with_wh(self, cr, uid, ids, pricelist, product, qty=0,
309 uom=False, qty_uos=0, uos=False, name='', partner_id=False,
310 lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, context=None):
311 context = context or {}
312 product_uom_obj = self.pool.get('product.uom')
313 product_obj = self.pool.get('product.product')
315 res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty,
316 uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id,
317 lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, context=context)
320 res['value'].update({'product_packaging': False})
323 #update of result obtained in super function
324 product_obj = product_obj.browse(cr, uid, product, context=context)
325 res['value']['delay'] = (product_obj.sale_delay or 0.0)
327 # Calling product_packaging_change function after updating UoM
328 res_packing = self.product_packaging_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, packaging, context=context)
329 res['value'].update(res_packing.get('value', {}))
330 warning_msgs = res_packing.get('warning') and res_packing['warning']['message'] or ''
332 #determine if the product is MTO or not (for a further check)
335 warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)
336 for product_route in product_obj.route_ids:
337 if warehouse.mto_pull_id and warehouse.mto_pull_id.route_id and warehouse.mto_pull_id.route_id.id == product_route.id:
342 mto_route_id = self.pool.get('ir.model.data').get_object(cr, uid, 'stock', 'route_warehouse0_mto').id
344 # if route MTO not found in ir_model_data, we treat the product as in MTS
347 for product_route in product_obj.route_ids:
348 if product_route.id == mto_route_id:
352 #check if product is available, and if not: raise a warning, but do this only for products that aren't processed in MTO
356 uom2 = product_uom_obj.browse(cr, uid, uom, context=context)
357 if product_obj.uom_id.category_id.id != uom2.category_id.id:
360 uom2 = product_obj.uom_id
361 compare_qty = float_compare(product_obj.virtual_available, qty, precision_rounding=uom2.rounding)
362 if (product_obj.type=='product') and int(compare_qty) == -1:
363 warn_msg = _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') % \
365 max(0,product_obj.virtual_available), uom2.name,
366 max(0,product_obj.qty_available), uom2.name)
367 warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n"
369 #update of warning messages
372 'title': _('Configuration Error!'),
373 'message' : warning_msgs
375 res.update({'warning': warning})
378 class stock_move(osv.osv):
379 _inherit = 'stock.move'
381 def action_cancel(self, cr, uid, ids, context=None):
383 for move in self.browse(cr, uid, ids, context=context):
384 if move.procurement_id and move.procurement_id.sale_line_id:
385 sale_ids.append(move.procurement_id.sale_line_id.order_id.id)
387 self.pool.get('sale.order').signal_ship_except(cr, uid, sale_ids)
388 return super(stock_move, self).action_cancel(cr, uid, ids, context=context)
390 def _create_invoice_line_from_vals(self, cr, uid, move, invoice_line_vals, context=None):
391 invoice_line_id = super(stock_move, self)._create_invoice_line_from_vals(cr, uid, move, invoice_line_vals, context=context)
392 if move.procurement_id and move.procurement_id.sale_line_id:
393 sale_line = move.procurement_id.sale_line_id
394 self.pool.get('sale.order.line').write(cr, uid, [sale_line.id], {
395 'invoice_lines': [(4, invoice_line_id)]
397 self.pool.get('sale.order').write(cr, uid, [sale_line.order_id.id], {
398 'invoice_ids': [(4, invoice_line_vals['invoice_id'])],
400 return invoice_line_id
402 def _get_master_data(self, cr, uid, move, company, context=None):
403 if move.procurement_id and move.procurement_id.sale_line_id:
404 sale_order = move.procurement_id.sale_line_id.order_id
405 return sale_order.partner_invoice_id, sale_order.user_id.id, sale_order.pricelist_id.currency_id.id
406 return super(stock_move, self)._get_master_data(cr, uid, move, company, context=context)
408 def _get_invoice_line_vals(self, cr, uid, move, partner, inv_type, context=None):
409 res = super(stock_move, self)._get_invoice_line_vals(cr, uid, move, partner, inv_type, context=context)
410 if move.procurement_id and move.procurement_id.sale_line_id:
411 sale_line = move.procurement_id.sale_line_id
412 res['invoice_line_tax_id'] = [(6, 0, [x.id for x in sale_line.tax_id])]
413 res['account_analytic_id'] = sale_line.order_id.project_id and sale_line.order_id.project_id.id or False
414 res['price_unit'] = sale_line.price_unit
415 res['discount'] = sale_line.discount
419 class stock_location_route(osv.osv):
420 _inherit = "stock.location.route"
422 'sale_selectable': fields.boolean("Selectable on Sales Order Line")
426 class stock_picking(osv.osv):
427 _inherit = "stock.picking"
429 def _get_sale_id(self, cr, uid, ids, name, args, context=None):
430 sale_obj = self.pool.get("sale.order")
432 for picking in self.browse(cr, uid, ids, context=context):
433 res[picking.id] = False
435 sale_ids = sale_obj.search(cr, uid, [('procurement_group_id', '=', picking.group_id.id)], context=context)
437 res[picking.id] = sale_ids[0]
441 'sale_id': fields.function(_get_sale_id, type="many2one", relation="sale.order", string="Sale Order"),
444 def _create_invoice_from_picking(self, cr, uid, picking, vals, context=None):
445 sale_obj = self.pool.get('sale.order')
446 sale_line_obj = self.pool.get('sale.order.line')
447 invoice_line_obj = self.pool.get('account.invoice.line')
448 invoice_id = super(stock_picking, self)._create_invoice_from_picking(cr, uid, picking, vals, context=context)
450 sale_ids = sale_obj.search(cr, uid, [('procurement_group_id', '=', picking.group_id.id)], context=context)
452 sale_line_ids = sale_line_obj.search(cr, uid, [('order_id', 'in', sale_ids), ('product_id.type', '=', 'service'), ('invoiced', '=', False)], context=context)
454 created_lines = sale_line_obj.invoice_line_create(cr, uid, sale_line_ids, context=context)
455 invoice_line_obj.write(cr, uid, created_lines, {'invoice_id': invoice_id}, context=context)