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,
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.
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/>.
20 ##############################################################################
22 from osv import fields, osv
24 from _common import rounding
26 from tools.translate import _
27 import decimal_precision as dp
30 class price_type(osv.osv):
32 The price type is used to points which field in the product form
33 is a price and in which currency is this price expressed.
34 When a field is a price, you can use it in pricelists to base
35 sale and purchase prices based on some fields of the product.
37 def _price_field_get(self, cr, uid, context=None):
38 mf = self.pool.get('ir.model.fields')
39 ids = mf.search(cr, uid, [('model','in', (('product.product'),('product.template'))), ('ttype','=','float')], context=context)
41 for field in mf.browse(cr, uid, ids, context=context):
42 res.append((field.name, field.field_description))
45 def _get_currency(self, cr, uid, ctx):
46 comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
48 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
49 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
50 return comp.currency_id.id
52 _name = "product.price.type"
53 _description = "Price Type"
55 "name" : fields.char("Price Name", size=32, required=True, translate=True, help="Name of this kind of price."),
56 "active" : fields.boolean("Active"),
57 "field" : fields.selection(_price_field_get, "Product Field", size=32, required=True, help="Associated field in the product form."),
58 "currency_id" : fields.many2one('res.currency', "Currency", required=True, help="The currency the field is expressed in."),
61 "active": lambda *args: True,
62 "currency_id": _get_currency
67 #----------------------------------------------------------
69 #----------------------------------------------------------
71 class product_pricelist_type(osv.osv):
72 _name = "product.pricelist.type"
73 _description = "Pricelist Type"
75 'name': fields.char('Name',size=64, required=True, translate=True),
76 'key': fields.char('Key', size=64, required=True, help="Used in the code to select specific prices based on the context. Keep unchanged."),
78 product_pricelist_type()
81 class product_pricelist(osv.osv):
82 def _pricelist_type_get(self, cr, uid, context=None):
83 pricelist_type_obj = self.pool.get('product.pricelist.type')
84 pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
85 pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
89 for type in pricelist_types:
90 res.append((type['key'],type['name']))
94 _name = "product.pricelist"
95 _description = "Pricelist"
97 'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
98 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the pricelist without removing it."),
99 'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
100 'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
101 'currency_id': fields.many2one('res.currency', 'Currency', required=True),
102 'company_id': fields.many2one('res.company', 'Company'),
105 def name_get(self, cr, uid, ids, context=None):
109 for pl in self.browse(cr, uid, ids, context=context):
110 name = pl.name + ' ('+ pl.currency_id.name + ')'
111 result.append((pl.id,name))
115 def _get_currency(self, cr, uid, ctx):
116 comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
118 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
119 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
120 return comp.currency_id.id
123 'active': lambda *a: 1,
124 "currency_id": _get_currency
127 #def price_get_multi(self, cr, uid, product_ids, context=None):
128 def price_get_multi(self, cr, uid, pricelist_ids, products_by_qty_by_partner, context=None):
129 """multi products 'price_get'.
130 @param pricelist_ids:
131 @param products_by_qty:
134 'date': Date of the pricelist (%Y-%m-%d),}
135 @return: a dict of dict with product_id as key and a dict 'price by pricelist' as value
138 def _create_parent_category_list(id, lst):
141 parent = product_category_tree.get(id)
144 return _create_parent_category_list(parent, lst)
147 # _create_parent_category_list
152 date = time.strftime('%Y-%m-%d')
153 if 'date' in context:
154 date = context['date']
156 currency_obj = self.pool.get('res.currency')
157 product_obj = self.pool.get('product.product')
158 product_template_obj = self.pool.get('product.template')
159 product_category_obj = self.pool.get('product.category')
160 product_uom_obj = self.pool.get('product.uom')
161 supplierinfo_obj = self.pool.get('product.supplierinfo')
162 price_type_obj = self.pool.get('product.price.type')
164 # product.pricelist.version:
165 if not pricelist_ids:
166 pricelist_ids = self.pool.get('product.pricelist').search(cr, uid, [], context=context)
168 pricelist_ids = list(set(pricelist_ids))
169 pricelist_version_ids = self.pool.get('product.pricelist.version').search(cr, uid, [
170 ('pricelist_id', 'in', pricelist_ids),
172 ('date_start', '=', False),
173 ('date_start', '<=', date),
175 ('date_end', '=', False),
176 ('date_end', '>=', date),
178 if len(pricelist_ids) != len(pricelist_version_ids):
179 raise osv.except_osv(_('Warning !'), _("At least one pricelist has no active version !\nPlease create or activate one."))
182 product_ids = [i[0] for i in products_by_qty_by_partner]
183 #products = dict([(item['id'], item) for item in product_obj.read(cr, uid, product_ids, ['categ_id', 'product_tmpl_id', 'uos_id', 'uom_id'])])
184 products = product_obj.browse(cr, uid, product_ids, context=context)
185 products_dict = dict([(item.id, item) for item in products])
188 product_category_ids = product_category_obj.search(cr, uid, [])
189 product_categories = product_category_obj.read(cr, uid, product_category_ids, ['parent_id'])
190 product_category_tree = dict([(item['id'], item['parent_id'][0]) for item in product_categories if item['parent_id']])
193 for product_id, qty, partner in products_by_qty_by_partner:
194 for pricelist_id in pricelist_ids:
197 tmpl_id = products_dict[product_id].product_tmpl_id and products_dict[product_id].product_tmpl_id.id or False
199 categ_id = products_dict[product_id].categ_id and products_dict[product_id].categ_id.id or False
200 categ_ids = _create_parent_category_list(categ_id, [categ_id])
202 categ_where = '(categ_id IN (' + ','.join(map(str, categ_ids)) + '))'
204 categ_where = '(categ_id IS NULL)'
207 'SELECT i.*, pl.currency_id '
208 'FROM product_pricelist_item AS i, '
209 'product_pricelist_version AS v, product_pricelist AS pl '
210 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
211 'AND (product_id IS NULL OR product_id = %s) '
212 'AND (' + categ_where + ' OR (categ_id IS NULL)) '
213 'AND price_version_id = %s '
214 'AND (min_quantity IS NULL OR min_quantity <= %s) '
215 'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
217 (tmpl_id, product_id, pricelist_version_ids[0], qty))
218 res1 = cr.dictfetchall()
219 uom_price_already_computed = False
222 if res['base'] == -1:
223 if not res['base_pricelist_id']:
226 price_tmp = self.price_get(cr, uid,
227 [res['base_pricelist_id']], product_id,
228 qty, context=context)[res['base_pricelist_id']]
229 ptype_src = self.browse(cr, uid, res['base_pricelist_id']).currency_id.id
230 uom_price_already_computed = True
231 price = currency_obj.compute(cr, uid, ptype_src, res['currency_id'], price_tmp, round=False)
232 elif res['base'] == -2:
233 # this section could be improved by moving the queries outside the loop:
236 where = [('name', '=', partner) ]
237 sinfo = supplierinfo_obj.search(cr, uid,
238 [('product_id', '=', tmpl_id)] + where)
241 qty_in_product_uom = qty
242 product_default_uom = product_template_obj.read(cr, uid, [tmpl_id], ['uom_id'])[0]['uom_id'][0]
243 supplier = supplierinfo_obj.browse(cr, uid, sinfo, context=context)[0]
244 seller_uom = supplier.product_uom and supplier.product_uom.id or False
245 if seller_uom and product_default_uom and product_default_uom != seller_uom:
246 uom_price_already_computed = True
247 qty_in_product_uom = product_uom_obj._compute_qty(cr, uid, product_default_uom, qty, to_uom_id=seller_uom)
248 cr.execute('SELECT * ' \
249 'FROM pricelist_partnerinfo ' \
250 'WHERE suppinfo_id IN %s' \
251 'AND min_quantity <= %s ' \
252 'ORDER BY min_quantity DESC LIMIT 1', (tuple(sinfo),qty_in_product_uom,))
253 res2 = cr.dictfetchone()
255 price = res2['price']
257 price_type = price_type_obj.browse(cr, uid, int(res['base']))
258 uom_price_already_computed = True
259 price = currency_obj.compute(cr, uid,
260 price_type.currency_id.id, res['currency_id'],
261 product_obj.price_get(cr, uid, [product_id],
262 price_type.field, context=context)[product_id], round=False, context=context)
264 if price is not False:
266 price = price * (1.0+(res['price_discount'] or 0.0))
267 price = rounding(price, res['price_round'])
268 price += (res['price_surcharge'] or 0.0)
269 if res['price_min_margin']:
270 price = max(price, price_limit+res['price_min_margin'])
271 if res['price_max_margin']:
272 price = min(price, price_limit+res['price_max_margin'])
276 # False means no valid line found ! But we may not raise an
277 # exception here because it breaks the search
281 results['item_id'] = res['id']
282 if 'uom' in context and not uom_price_already_computed:
283 product = products_dict[product_id]
284 uom = product.uos_id or product.uom_id
285 price = self.pool.get('product.uom')._compute_price(cr, uid, uom.id, price, context['uom'])
287 if results.get(product_id):
288 results[product_id][pricelist_id] = price
290 results[product_id] = {pricelist_id: price}
294 def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
295 res_multi = self.price_get_multi(cr, uid, pricelist_ids=ids, products_by_qty_by_partner=[(prod_id, qty, partner)], context=context)
296 res = res_multi[prod_id]
297 res.update({'item_id': {ids[-1]: res_multi.get('item_id', ids[-1])}})
300 def price_get_old(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
303 'uom': Unit of Measure (int),
304 'partner': Partner ID (int),
305 'date': Date of the pricelist (%Y-%m-%d),
312 currency_obj = self.pool.get('res.currency')
313 product_obj = self.pool.get('product.product')
314 supplierinfo_obj = self.pool.get('product.supplierinfo')
315 price_type_obj = self.pool.get('product.price.type')
317 if context and ('partner_id' in context):
318 partner = context['partner_id']
319 context['partner_id'] = partner
320 date = time.strftime('%Y-%m-%d')
321 if context and ('date' in context):
322 date = context['date']
324 result['item_id'] = {}
326 cr.execute('SELECT * ' \
327 'FROM product_pricelist_version ' \
328 'WHERE pricelist_id = %s AND active=True ' \
329 'AND (date_start IS NULL OR date_start <= %s) ' \
330 'AND (date_end IS NULL OR date_end >= %s) ' \
331 'ORDER BY id LIMIT 1', (id, date, date))
332 plversion = cr.dictfetchone()
335 raise osv.except_osv(_('Warning !'),
336 _('No active version for the selected pricelist !\n' \
337 'Please create or activate one.'))
339 cr.execute('SELECT id, categ_id ' \
340 'FROM product_template ' \
341 'WHERE id = (SELECT product_tmpl_id ' \
342 'FROM product_product ' \
343 'WHERE id = %s)', (prod_id,))
344 tmpl_id, categ = cr.fetchone()
347 categ_ids.append(str(categ))
348 cr.execute('SELECT parent_id ' \
349 'FROM product_category ' \
350 'WHERE id = %s', (categ,))
351 categ = cr.fetchone()[0]
352 if str(categ) in categ_ids:
353 raise osv.except_osv(_('Warning !'),
354 _('Could not resolve product category, ' \
355 'you have defined cyclic categories ' \
358 categ_where = '(categ_id IN (' + ','.join(categ_ids) + '))'
360 categ_where = '(categ_id IS NULL)'
363 'SELECT i.*, pl.currency_id '
364 'FROM product_pricelist_item AS i, '
365 'product_pricelist_version AS v, product_pricelist AS pl '
366 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
367 'AND (product_id IS NULL OR product_id = %s) '
368 'AND (' + categ_where + ' OR (categ_id IS NULL)) '
369 'AND price_version_id = %s '
370 'AND (min_quantity IS NULL OR min_quantity <= %s) '
371 'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
373 (tmpl_id, prod_id, plversion['id'], qty))
374 res1 = cr.dictfetchall()
379 if res['base'] == -1:
380 if not res['base_pricelist_id']:
383 price_tmp = self.price_get(cr, uid,
384 [res['base_pricelist_id']], prod_id,
385 qty, context=context)[res['base_pricelist_id']]
386 ptype_src = self.browse(cr, uid,
387 res['base_pricelist_id']).currency_id.id
388 price = currency_obj.compute(cr, uid, ptype_src,
389 res['currency_id'], price_tmp, round=False)
391 elif res['base'] == -2:
394 where = [('name', '=', partner) ]
395 sinfo = supplierinfo_obj.search(cr, uid,
396 [('product_id', '=', tmpl_id)] + where)
399 cr.execute('SELECT * ' \
400 'FROM pricelist_partnerinfo ' \
401 'WHERE suppinfo_id IN %s' \
402 'AND min_quantity <= %s ' \
403 'ORDER BY min_quantity DESC LIMIT 1', (tuple(sinfo),qty,))
404 res2 = cr.dictfetchone()
406 price = res2['price']
409 price_type = price_type_obj.browse(cr, uid, int(res['base']))
410 price = currency_obj.compute(cr, uid,
411 price_type.currency_id.id, res['currency_id'],
412 product_obj.price_get(cr, uid, [prod_id],
413 price_type.field, context=context)[prod_id], round=False, context=context)
418 price = price * (1.0+(res['price_discount'] or 0.0))
419 price = rounding(price, res['price_round'])
420 price += (res['price_surcharge'] or 0.0)
421 if res['price_min_margin']:
422 price = max(price, price_limit+res['price_min_margin'])
423 if res['price_max_margin']:
424 price = min(price, price_limit+res['price_max_margin'])
429 # False means no valid line found ! But we may not raise an
430 # exception here because it breaks the search
433 result['item_id'] = {id: item_id}
434 if context and ('uom' in context):
435 product = product_obj.browse(cr, uid, prod_id)
436 uom = product.uos_id or product.uom_id
437 result[id] = self.pool.get('product.uom')._compute_price(cr,
438 uid, uom.id, result[id], context['uom'])
445 class product_pricelist_version(osv.osv):
446 _name = "product.pricelist.version"
447 _description = "Pricelist Version"
449 'pricelist_id': fields.many2one('product.pricelist', 'Price List',
450 required=True, select=True, ondelete='cascade'),
451 'name': fields.char('Name', size=64, required=True, translate=True),
452 'active': fields.boolean('Active',
453 help="When a version is duplicated it is set to non active, so that the " \
454 "dates do not overlaps with original version. You should change the dates " \
455 "and reactivate the pricelist"),
456 'items_id': fields.one2many('product.pricelist.item',
457 'price_version_id', 'Price List Items', required=True),
458 'date_start': fields.date('Start Date', help="Starting date for this pricelist version to be valid."),
459 'date_end': fields.date('End Date', help="Ending date for this pricelist version to be valid."),
460 'company_id': fields.related('pricelist_id','company_id',type='many2one',
461 readonly=True, relation='res.company', string='Company', store=True)
464 'active': lambda *a: 1,
467 # We desactivate duplicated pricelists, so that dates do not overlap
468 def copy(self, cr, uid, id, default=None, context=None):
469 if not default: default= {}
470 default['active'] = False
471 return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
473 def _check_date(self, cursor, user, ids, context=None):
474 for pricelist_version in self.browse(cursor, user, ids, context=context):
475 if not pricelist_version.active:
478 if pricelist_version.date_start:
479 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
480 if pricelist_version.date_end:
481 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
483 cursor.execute('SELECT id ' \
484 'FROM product_pricelist_version ' \
485 'WHERE '+' and '.join(where) + (where and ' and ' or '')+
486 'pricelist_id = %s ' \
489 pricelist_version.pricelist_id.id,
490 pricelist_version.id))
491 if cursor.fetchall():
496 (_check_date, 'You cannot have 2 pricelist versions that overlap!',
497 ['date_start', 'date_end'])
500 product_pricelist_version()
502 class product_pricelist_item(osv.osv):
503 def _price_field_get(self, cr, uid, context=None):
504 pt = self.pool.get('product.price.type')
505 ids = pt.search(cr, uid, [], context=context)
507 for line in pt.browse(cr, uid, ids, context=context):
508 result.append((line.id, line.name))
510 result.append((-1, _('Other Pricelist')))
511 result.append((-2, _('Partner section of the product form')))
514 _name = "product.pricelist.item"
515 _description = "Pricelist item"
516 _order = "sequence, min_quantity desc"
518 'base': lambda *a: -1,
519 'min_quantity': lambda *a: 0,
520 'sequence': lambda *a: 5,
521 'price_discount': lambda *a: 0,
524 def _check_recursion(self, cr, uid, ids, context=None):
525 for obj_list in self.browse(cr, uid, ids, context=context):
526 if obj_list.base == -1:
527 main_pricelist = obj_list.price_version_id.pricelist_id.id
528 other_pricelist = obj_list.base_pricelist_id.id
529 if main_pricelist == other_pricelist:
534 'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
535 'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
536 'product_tmpl_id': fields.many2one('product.template', 'Product Template', ondelete='cascade', help="Set a template if this rule only apply to a template of product. Keep empty for all products"),
537 'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Set a product if this rule only apply to one product. Keep empty for all products"),
538 'categ_id': fields.many2one('product.category', 'Product Category', ondelete='cascade', help="Set a category of product if this rule only apply to products of a category and his children. Keep empty for all products"),
540 'min_quantity': fields.integer('Min. Quantity', required=True, help="The rule only applies if the partner buys/sells more than this quantity."),
541 'sequence': fields.integer('Sequence', required=True, help="Gives the order in which the pricelist items will be checked. The evaluation gives highest priority to lowest sequence and stops as soon as a matching item is found."),
542 'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="The mode for computing the price for this rule."),
543 'base_pricelist_id': fields.many2one('product.pricelist', 'If Other Pricelist'),
545 'price_surcharge': fields.float('Price Surcharge',
546 digits_compute= dp.get_precision('Sale Price')),
547 'price_discount': fields.float('Price Discount', digits=(16,4)),
548 'price_round': fields.float('Price Rounding',
549 digits_compute= dp.get_precision('Sale Price'),
550 help="Sets the price so that it is a multiple of this value.\n" \
551 "Rounding is applied after the discount and before the surcharge.\n" \
552 "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
554 'price_min_margin': fields.float('Min. Price Margin',
555 digits_compute= dp.get_precision('Sale Price')),
556 'price_max_margin': fields.float('Max. Price Margin',
557 digits_compute= dp.get_precision('Sale Price')),
558 'company_id': fields.related('price_version_id','company_id',type='many2one',
559 readonly=True, relation='res.company', string='Company', store=True)
563 (_check_recursion, 'Error ! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!', ['base_pricelist_id'])
566 def product_id_change(self, cr, uid, ids, product_id, context=None):
569 prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
571 return {'value': {'name': prod[0]['code']}}
573 product_pricelist_item()
577 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: