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 ##############################################################################
24 from openerp import tools
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
28 import openerp.addons.decimal_precision as dp
31 class price_type(osv.osv):
33 The price type is used to points which field in the product form
34 is a price and in which currency is this price expressed.
35 When a field is a price, you can use it in pricelists to base
36 sale and purchase prices based on some fields of the product.
38 def _price_field_get(self, cr, uid, context=None):
39 mf = self.pool.get('ir.model.fields')
40 ids = mf.search(cr, uid, [('model','in', (('product.product'),('product.template'))), ('ttype','=','float')], context=context)
42 for field in mf.browse(cr, uid, ids, context=context):
43 res.append((field.name, field.field_description))
46 def _get_field_currency(self, cr, uid, fname, ctx):
47 ids = self.search(cr, uid, [('field','=',fname)], context=ctx)
48 return self.browse(cr, uid, ids, context=ctx)[0].currency_id
50 def _get_currency(self, cr, uid, ctx):
51 comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
53 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
54 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
55 return comp.currency_id.id
57 _name = "product.price.type"
58 _description = "Price Type"
60 "name" : fields.char("Price Name", required=True, translate=True, help="Name of this kind of price."),
61 "active" : fields.boolean("Active"),
62 "field" : fields.selection(_price_field_get, "Product Field", size=32, required=True, help="Associated field in the product form."),
63 "currency_id" : fields.many2one('res.currency', "Currency", required=True, help="The currency the field is expressed in."),
66 "active": lambda *args: True,
67 "currency_id": _get_currency
71 #----------------------------------------------------------
73 #----------------------------------------------------------
75 class product_pricelist_type(osv.osv):
76 _name = "product.pricelist.type"
77 _description = "Pricelist Type"
79 'name': fields.char('Name', required=True, translate=True),
80 'key': fields.char('Key', required=True, help="Used in the code to select specific prices based on the context. Keep unchanged."),
84 class product_pricelist(osv.osv):
85 def _pricelist_type_get(self, cr, uid, context=None):
86 pricelist_type_obj = self.pool.get('product.pricelist.type')
87 pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
88 pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
92 for type in pricelist_types:
93 res.append((type['key'],type['name']))
97 _name = "product.pricelist"
98 _description = "Pricelist"
101 'name': fields.char('Pricelist Name', required=True, translate=True),
102 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the pricelist without removing it."),
103 'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
104 'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
105 'currency_id': fields.many2one('res.currency', 'Currency', required=True),
106 'company_id': fields.many2one('res.company', 'Company'),
109 def name_get(self, cr, uid, ids, context=None):
113 for pl in self.browse(cr, uid, ids, context=context):
114 name = pl.name + ' ('+ pl.currency_id.name + ')'
115 result.append((pl.id,name))
118 def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
119 if name and operator == '=' and not args:
120 # search on the name of the pricelist and its currency, opposite of name_get(),
121 # Used by the magic context filter in the product search view.
122 query_args = {'name': name, 'limit': limit, 'lang': (context or {}).get('lang') or 'en_US'}
123 query = """SELECT p.id
125 SELECT pr.id, pr.name
126 FROM product_pricelist pr JOIN
128 (pr.currency_id = cur.id)
129 WHERE pr.name || ' (' || cur.name || ')' = %(name)s
132 SELECT tr.res_id as id, tr.value as name
133 FROM ir_translation tr JOIN
134 product_pricelist pr ON (
135 pr.id = tr.res_id AND
136 tr.type = 'model' AND
137 tr.name = 'product.pricelist,name' AND
141 (pr.currency_id = cur.id)
142 WHERE tr.value || ' (' || cur.name || ')' = %(name)s
147 query += " LIMIT %(limit)s"
148 cr.execute(query, query_args)
149 ids = [r[0] for r in cr.fetchall()]
150 # regular search() to apply ACLs - may limit results below limit in some cases
151 ids = self.search(cr, uid, [('id', 'in', ids)], limit=limit, context=context)
153 return self.name_get(cr, uid, ids, context)
154 return super(product_pricelist, self).name_search(
155 cr, uid, name, args, operator=operator, context=context, limit=limit)
158 def _get_currency(self, cr, uid, ctx):
159 comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
161 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
162 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
163 return comp.currency_id.id
166 'active': lambda *a: 1,
167 "currency_id": _get_currency
170 def price_get_multi(self, cr, uid, pricelist_ids, products_by_qty_by_partner, context=None):
171 """multi products 'price_get'.
172 @param pricelist_ids:
173 @param products_by_qty:
176 'date': Date of the pricelist (%Y-%m-%d),}
177 @return: a dict of dict with product_id as key and a dict 'price by pricelist' as value
179 if not pricelist_ids:
180 pricelist_ids = self.pool.get('product.pricelist').search(cr, uid, [], context=context)
182 for pricelist in self.browse(cr, uid, pricelist_ids, context=context):
183 subres = self._price_get_multi(cr, uid, pricelist, products_by_qty_by_partner, context=context)
184 for product_id,price in subres.items():
185 results.setdefault(product_id, {})
186 results[product_id][pricelist.id] = price
189 def _price_get_multi(self, cr, uid, pricelist, products_by_qty_by_partner, context=None):
190 context = context or {}
191 date = context.get('date') or time.strftime('%Y-%m-%d')
193 products = map(lambda x: x[0], products_by_qty_by_partner)
194 currency_obj = self.pool.get('res.currency')
195 product_obj = self.pool.get('product.template')
196 product_uom_obj = self.pool.get('product.uom')
197 price_type_obj = self.pool.get('product.price.type')
203 for v in pricelist.version_id:
204 if ((v.date_start is False) or (v.date_start <= date)) and ((v.date_end is False) or (v.date_end >= date)):
208 raise osv.except_osv(_('Warning!'), _("At least one pricelist has no active version !\nPlease create or activate one."))
213 categ_ids[categ.id] = True
214 categ = categ.parent_id
215 categ_ids = categ_ids.keys()
217 is_product_template = products[0]._name == "product.template"
218 if is_product_template:
219 prod_tmpl_ids = [tmpl.id for tmpl in products]
220 prod_ids = [product.id for product in tmpl.product_variant_ids for tmpl in products]
222 prod_ids = [product.id for product in products]
223 prod_tmpl_ids = [product.product_tmpl_id.id for product in products]
228 'FROM product_pricelist_item AS i '
229 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = any(%s)) '
230 'AND (product_id IS NULL OR (product_id = any(%s))) '
231 'AND ((categ_id IS NULL) OR (categ_id = any(%s))) '
232 'AND (price_version_id = %s) '
233 'ORDER BY sequence, min_quantity desc',
234 (prod_tmpl_ids, prod_ids, categ_ids, version.id))
236 item_ids = [x[0] for x in cr.fetchall()]
237 items = self.pool.get('product.pricelist.item').browse(cr, uid, item_ids, context=context)
242 for product, qty, partner in products_by_qty_by_partner:
243 uom_price_already_computed = False
244 results[product.id] = 0.0
247 if rule.min_quantity and qty<rule.min_quantity:
249 if is_product_template:
250 if rule.product_tmpl_id and product.id<>rule.product_tmpl_id.id:
255 if rule.product_tmpl_id and product.product_tmpl_id.id<>rule.product_tmpl_id.id:
257 if rule.product_id and product.id<>rule.product_id.id:
261 cat = product.categ_id
263 if cat.id == rule.categ_id.id:
270 if rule.base_pricelist_id:
271 price_tmp = self._price_get_multi(cr, uid,
272 rule.base_pricelist_id, [(product,
273 qty, False)], context=context)[product.id]
274 ptype_src = rule.base_pricelist_id.currency_id.id
275 uom_price_already_computed = True
276 price = currency_obj.compute(cr, uid,
277 ptype_src, pricelist.currency_id.id,
278 price_tmp, round=False,
280 elif rule.base == -2:
281 for seller in product.seller_ids:
282 if (not partner) or (seller.name.id<>partner):
284 qty_in_seller_uom = qty
285 from_uom = context.get('uom') or product.uom_id.id
286 seller_uom = seller.product_uom and seller.product_uom.id or False
287 if seller_uom and from_uom and from_uom != seller_uom:
288 qty_in_seller_uom = product_uom_obj._compute_qty(cr, uid, from_uom, qty, to_uom_id=seller_uom)
290 uom_price_already_computed = True
291 for line in seller.pricelist_ids:
292 if line.min_quantity <= qty_in_seller_uom:
296 if rule.base not in price_types:
297 price_types[rule.base] = price_type_obj.browse(cr, uid, int(rule.base))
298 price_type = price_types[rule.base]
300 uom_price_already_computed = True
301 price = currency_obj.compute(cr, uid,
302 price_type.currency_id.id, pricelist.currency_id.id,
303 product_obj._price_get(cr, uid, [product],
304 price_type.field, context=context)[product.id], round=False, context=context)
306 if price is not False:
308 price = price * (1.0+(rule.price_discount or 0.0))
310 price = tools.float_round(price, precision_rounding=rule.price_round)
311 price += (rule.price_surcharge or 0.0)
312 if rule.price_min_margin:
313 price = max(price, price_limit+rule.price_min_margin)
314 if rule.price_max_margin:
315 price = min(price, price_limit+rule.price_max_margin)
319 if 'uom' in context and not uom_price_already_computed:
320 uom = product.uos_id or product.uom_id
321 price = product_uom_obj._compute_price(cr, uid, uom.id, price, context['uom'])
323 results[product.id] = price
326 def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
327 product = self.pool.get('product.product').browse(cr, uid, prod_id, context=context)
328 res_multi = self.price_get_multi(cr, uid, pricelist_ids=ids, products_by_qty_by_partner=[(product, qty, partner)], context=context)
329 res = res_multi[prod_id]
333 class product_pricelist_version(osv.osv):
334 _name = "product.pricelist.version"
335 _description = "Pricelist Version"
337 'pricelist_id': fields.many2one('product.pricelist', 'Price List',
338 required=True, select=True, ondelete='cascade'),
339 'name': fields.char('Name', required=True, translate=True),
340 'active': fields.boolean('Active',
341 help="When a version is duplicated it is set to non active, so that the " \
342 "dates do not overlaps with original version. You should change the dates " \
343 "and reactivate the pricelist"),
344 'items_id': fields.one2many('product.pricelist.item',
345 'price_version_id', 'Price List Items', required=True),
346 'date_start': fields.date('Start Date', help="First valid date for the version."),
347 'date_end': fields.date('End Date', help="Last valid date for the version."),
348 'company_id': fields.related('pricelist_id','company_id',type='many2one',
349 readonly=True, relation='res.company', string='Company', store=True)
352 'active': lambda *a: 1,
355 # We desactivate duplicated pricelists, so that dates do not overlap
356 def copy(self, cr, uid, id, default=None, context=None):
357 if not default: default= {}
358 default['active'] = False
359 return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
361 def _check_date(self, cursor, user, ids, context=None):
362 for pricelist_version in self.browse(cursor, user, ids, context=context):
363 if not pricelist_version.active:
366 if pricelist_version.date_start:
367 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
368 if pricelist_version.date_end:
369 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
371 cursor.execute('SELECT id ' \
372 'FROM product_pricelist_version ' \
373 'WHERE '+' and '.join(where) + (where and ' and ' or '')+
374 'pricelist_id = %s ' \
377 pricelist_version.pricelist_id.id,
378 pricelist_version.id))
379 if cursor.fetchall():
384 (_check_date, 'You cannot have 2 pricelist versions that overlap!',
385 ['date_start', 'date_end'])
389 class product_pricelist_item(osv.osv):
390 def _price_field_get(self, cr, uid, context=None):
391 pt = self.pool.get('product.price.type')
392 ids = pt.search(cr, uid, [], context=context)
394 for line in pt.browse(cr, uid, ids, context=context):
395 result.append((line.id, line.name))
397 result.append((-1, _('Other Pricelist')))
398 result.append((-2, _('Supplier Prices on the product form')))
401 # Added default function to fetch the Price type Based on Pricelist type.
402 def _get_default_base(self, cr, uid, fields, context=None):
403 product_price_type_obj = self.pool.get('product.price.type')
404 if fields.get('type') == 'purchase':
405 product_price_type_ids = product_price_type_obj.search(cr, uid, [('field', '=', 'standard_price')], context=context)
406 elif fields.get('type') == 'sale':
407 product_price_type_ids = product_price_type_obj.search(cr, uid, [('field','=','list_price')], context=context)
410 if not product_price_type_ids:
413 pricetype = product_price_type_obj.browse(cr, uid, product_price_type_ids, context=context)[0]
416 _name = "product.pricelist.item"
417 _description = "Pricelist item"
418 _order = "sequence, min_quantity desc"
420 'base': _get_default_base,
421 'min_quantity': lambda *a: 0,
422 'sequence': lambda *a: 5,
423 'price_discount': lambda *a: 0,
426 def _check_recursion(self, cr, uid, ids, context=None):
427 for obj_list in self.browse(cr, uid, ids, context=context):
428 if obj_list.base == -1:
429 main_pricelist = obj_list.price_version_id.pricelist_id.id
430 other_pricelist = obj_list.base_pricelist_id.id
431 if main_pricelist == other_pricelist:
435 def _check_margin(self, cr, uid, ids, context=None):
436 for item in self.browse(cr, uid, ids, context=context):
437 if item.price_max_margin and item.price_min_margin and (item.price_min_margin > item.price_max_margin):
442 'name': fields.char('Rule Name', help="Explicit rule name for this pricelist line."),
443 'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
444 'product_tmpl_id': fields.many2one('product.template', 'Product Template', ondelete='cascade', help="Specify a template if this rule only applies to one product template. Keep empty otherwise."),
445 'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Specify a product if this rule only applies to one product. Keep empty otherwise."),
446 'categ_id': fields.many2one('product.category', 'Product Category', ondelete='cascade', help="Specify a product category if this rule only applies to products belonging to this category or its children categories. Keep empty otherwise."),
448 'min_quantity': fields.integer('Min. Quantity', required=True, help="Specify the minimum quantity that needs to be bought/sold for the rule to apply."),
449 '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."),
450 'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="Base price for computation."),
451 'base_pricelist_id': fields.many2one('product.pricelist', 'Other Pricelist'),
453 'price_surcharge': fields.float('Price Surcharge',
454 digits_compute= dp.get_precision('Product Price'), help='Specify the fixed amount to add or substract(if negative) to the amount calculated with the discount.'),
455 'price_discount': fields.float('Price Discount', digits=(16,4)),
456 'price_round': fields.float('Price Rounding',
457 digits_compute= dp.get_precision('Product Price'),
458 help="Sets the price so that it is a multiple of this value.\n" \
459 "Rounding is applied after the discount and before the surcharge.\n" \
460 "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
462 'price_min_margin': fields.float('Min. Price Margin',
463 digits_compute= dp.get_precision('Product Price'), help='Specify the minimum amount of margin over the base price.'),
464 'price_max_margin': fields.float('Max. Price Margin',
465 digits_compute= dp.get_precision('Product Price'), help='Specify the maximum amount of margin over the base price.'),
466 'company_id': fields.related('price_version_id','company_id',type='many2one',
467 readonly=True, relation='res.company', string='Company', store=True)
471 (_check_recursion, 'Error! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!', ['base_pricelist_id']),
472 (_check_margin, 'Error! The minimum margin should be lower than the maximum margin.', ['price_min_margin', 'price_max_margin'])
475 def product_id_change(self, cr, uid, ids, product_id, context=None):
478 prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
480 return {'value': {'name': prod[0]['code']}}
485 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: