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 _common import rounding
26 from openerp.osv import fields, osv
27 from openerp.tools.translate import _
29 import openerp.addons.decimal_precision as dp
32 class price_type(osv.osv):
34 The price type is used to points which field in the product form
35 is a price and in which currency is this price expressed.
36 When a field is a price, you can use it in pricelists to base
37 sale and purchase prices based on some fields of the product.
39 def _price_field_get(self, cr, uid, context=None):
40 mf = self.pool.get('ir.model.fields')
41 ids = mf.search(cr, uid, [('model','in', (('product.product'),('product.template'))), ('ttype','=','float')], context=context)
43 for field in mf.browse(cr, uid, ids, context=context):
44 res.append((field.name, field.field_description))
47 def _get_currency(self, cr, uid, ctx):
48 comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
50 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
51 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
52 return comp.currency_id.id
54 _name = "product.price.type"
55 _description = "Price Type"
57 "name" : fields.char("Price Name", size=32, required=True, translate=True, help="Name of this kind of price."),
58 "active" : fields.boolean("Active"),
59 "field" : fields.selection(_price_field_get, "Product Field", size=32, required=True, help="Associated field in the product form."),
60 "currency_id" : fields.many2one('res.currency', "Currency", required=True, help="The currency the field is expressed in."),
63 "active": lambda *args: True,
64 "currency_id": _get_currency
69 #----------------------------------------------------------
71 #----------------------------------------------------------
73 class product_pricelist_type(osv.osv):
74 _name = "product.pricelist.type"
75 _description = "Pricelist Type"
77 'name': fields.char('Name',size=64, required=True, translate=True),
78 'key': fields.char('Key', size=64, required=True, help="Used in the code to select specific prices based on the context. Keep unchanged."),
80 product_pricelist_type()
83 class product_pricelist(osv.osv):
84 def _pricelist_type_get(self, cr, uid, context=None):
85 pricelist_type_obj = self.pool.get('product.pricelist.type')
86 pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
87 pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
91 for type in pricelist_types:
92 res.append((type['key'],type['name']))
96 _name = "product.pricelist"
97 _description = "Pricelist"
99 'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
100 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the pricelist without removing it."),
101 'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
102 'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
103 'currency_id': fields.many2one('res.currency', 'Currency', required=True),
104 'company_id': fields.many2one('res.company', 'Company'),
107 def name_get(self, cr, uid, ids, context=None):
111 for pl in self.browse(cr, uid, ids, context=context):
112 name = pl.name + ' ('+ pl.currency_id.name + ')'
113 result.append((pl.id,name))
117 def _get_currency(self, cr, uid, ctx):
118 comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
120 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
121 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
122 return comp.currency_id.id
125 'active': lambda *a: 1,
126 "currency_id": _get_currency
129 #def price_get_multi(self, cr, uid, product_ids, context=None):
130 def price_get_multi(self, cr, uid, pricelist_ids, products_by_qty_by_partner, context=None):
131 """multi products 'price_get'.
132 @param pricelist_ids:
133 @param products_by_qty:
136 'date': Date of the pricelist (%Y-%m-%d),}
137 @return: a dict of dict with product_id as key and a dict 'price by pricelist' as value
140 def _create_parent_category_list(id, lst):
143 parent = product_category_tree.get(id)
146 return _create_parent_category_list(parent, lst)
149 # _create_parent_category_list
154 date = context.get('date') or time.strftime('%Y-%m-%d')
155 if 'date' in context and context['date']:
156 date = context['date']
158 currency_obj = self.pool.get('res.currency')
159 product_obj = self.pool.get('product.product')
160 product_category_obj = self.pool.get('product.category')
161 product_uom_obj = self.pool.get('product.uom')
162 supplierinfo_obj = self.pool.get('product.supplierinfo')
163 price_type_obj = self.pool.get('product.price.type')
165 # product.pricelist.version:
166 if not pricelist_ids:
167 pricelist_ids = self.pool.get('product.pricelist').search(cr, uid, [], context=context)
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 partner_where = 'base <> -2 OR %s IN (SELECT name FROM product_supplierinfo WHERE product_id = %s) '
208 partner_args = (partner, tmpl_id)
210 partner_where = 'base <> -2 '
214 'SELECT i.*, pl.currency_id '
215 'FROM product_pricelist_item AS i, '
216 'product_pricelist_version AS v, product_pricelist AS pl '
217 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
218 'AND (product_id IS NULL OR product_id = %s) '
219 'AND (' + categ_where + ' OR (categ_id IS NULL)) '
220 'AND (' + partner_where + ') '
221 'AND price_version_id = %s '
222 'AND (min_quantity IS NULL OR min_quantity <= %s) '
223 'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
225 (tmpl_id, product_id) + partner_args + (pricelist_version_ids[0], qty))
226 res1 = cr.dictfetchall()
227 uom_price_already_computed = False
230 if res['base'] == -1:
231 if not res['base_pricelist_id']:
234 price_tmp = self.price_get(cr, uid,
235 [res['base_pricelist_id']], product_id,
236 qty, context=context)[res['base_pricelist_id']]
237 ptype_src = self.browse(cr, uid, res['base_pricelist_id']).currency_id.id
238 uom_price_already_computed = True
239 price = currency_obj.compute(cr, uid,
240 ptype_src, res['currency_id'],
241 price_tmp, round=False,
243 elif res['base'] == -2:
244 # this section could be improved by moving the queries outside the loop:
247 where = [('name', '=', partner) ]
248 sinfo = supplierinfo_obj.search(cr, uid,
249 [('product_id', '=', tmpl_id)] + where)
252 qty_in_product_uom = qty
253 product_default_uom = product_obj.read(cr, uid, [product_id], ['uom_id'])[0]['uom_id'][0]
254 supplier = supplierinfo_obj.browse(cr, uid, sinfo, context=context)[0]
255 seller_uom = supplier.product_uom and supplier.product_uom.id or False
256 if seller_uom and product_default_uom and product_default_uom != seller_uom:
257 uom_price_already_computed = True
258 qty_in_product_uom = product_uom_obj._compute_qty(cr, uid, product_default_uom, qty, to_uom_id=seller_uom)
259 cr.execute('SELECT * ' \
260 'FROM pricelist_partnerinfo ' \
261 'WHERE suppinfo_id IN %s' \
262 'AND min_quantity <= %s ' \
263 'ORDER BY min_quantity DESC LIMIT 1', (tuple(sinfo),qty_in_product_uom,))
264 res2 = cr.dictfetchone()
266 price = res2['price']
268 price_type = price_type_obj.browse(cr, uid, int(res['base']))
269 uom_price_already_computed = True
270 price = currency_obj.compute(cr, uid,
271 price_type.currency_id.id, res['currency_id'],
272 product_obj.price_get(cr, uid, [product_id],
273 price_type.field, context=context)[product_id], round=False, context=context)
275 if price is not False:
277 price = price * (1.0+(res['price_discount'] or 0.0))
278 price = rounding(price, res['price_round']) #TOFIX: rounding with tools.float_rouding
279 price += (res['price_surcharge'] or 0.0)
280 if res['price_min_margin']:
281 price = max(price, price_limit+res['price_min_margin'])
282 if res['price_max_margin']:
283 price = min(price, price_limit+res['price_max_margin'])
287 # False means no valid line found ! But we may not raise an
288 # exception here because it breaks the search
292 results['item_id'] = res['id']
293 if 'uom' in context and not uom_price_already_computed:
294 product = products_dict[product_id]
295 uom = product.uos_id or product.uom_id
296 price = product_uom_obj._compute_price(cr, uid, uom.id, price, context['uom'])
298 if results.get(product_id):
299 results[product_id][pricelist_id] = price
301 results[product_id] = {pricelist_id: price}
305 def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
306 res_multi = self.price_get_multi(cr, uid, pricelist_ids=ids, products_by_qty_by_partner=[(prod_id, qty, partner)], context=context)
307 res = res_multi[prod_id]
308 res.update({'item_id': {ids[-1]: res_multi.get('item_id', ids[-1])}})
314 class product_pricelist_version(osv.osv):
315 _name = "product.pricelist.version"
316 _description = "Pricelist Version"
318 'pricelist_id': fields.many2one('product.pricelist', 'Price List',
319 required=True, select=True, ondelete='cascade'),
320 'name': fields.char('Name', size=64, required=True, translate=True),
321 'active': fields.boolean('Active',
322 help="When a version is duplicated it is set to non active, so that the " \
323 "dates do not overlaps with original version. You should change the dates " \
324 "and reactivate the pricelist"),
325 'items_id': fields.one2many('product.pricelist.item',
326 'price_version_id', 'Price List Items', required=True),
327 'date_start': fields.date('Start Date', help="First valid date for the version."),
328 'date_end': fields.date('End Date', help="Last valid date for the version."),
329 'company_id': fields.related('pricelist_id','company_id',type='many2one',
330 readonly=True, relation='res.company', string='Company', store=True)
333 'active': lambda *a: 1,
336 # We desactivate duplicated pricelists, so that dates do not overlap
337 def copy(self, cr, uid, id, default=None, context=None):
338 if not default: default= {}
339 default['active'] = False
340 return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
342 def _check_date(self, cursor, user, ids, context=None):
343 for pricelist_version in self.browse(cursor, user, ids, context=context):
344 if not pricelist_version.active:
347 if pricelist_version.date_start:
348 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
349 if pricelist_version.date_end:
350 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
352 cursor.execute('SELECT id ' \
353 'FROM product_pricelist_version ' \
354 'WHERE '+' and '.join(where) + (where and ' and ' or '')+
355 'pricelist_id = %s ' \
358 pricelist_version.pricelist_id.id,
359 pricelist_version.id))
360 if cursor.fetchall():
365 (_check_date, 'You cannot have 2 pricelist versions that overlap!',
366 ['date_start', 'date_end'])
369 product_pricelist_version()
371 class product_pricelist_item(osv.osv):
372 def _price_field_get(self, cr, uid, context=None):
373 pt = self.pool.get('product.price.type')
374 ids = pt.search(cr, uid, [], context=context)
376 for line in pt.browse(cr, uid, ids, context=context):
377 result.append((line.id, line.name))
379 result.append((-1, _('Other Pricelist')))
380 result.append((-2, _('Supplier Prices on the product form')))
383 _name = "product.pricelist.item"
384 _description = "Pricelist item"
385 _order = "sequence, min_quantity desc"
387 'base': lambda *a: -1,
388 'min_quantity': lambda *a: 0,
389 'sequence': lambda *a: 5,
390 'price_discount': lambda *a: 0,
393 def _check_recursion(self, cr, uid, ids, context=None):
394 for obj_list in self.browse(cr, uid, ids, context=context):
395 if obj_list.base == -1:
396 main_pricelist = obj_list.price_version_id.pricelist_id.id
397 other_pricelist = obj_list.base_pricelist_id.id
398 if main_pricelist == other_pricelist:
402 def _check_margin(self, cr, uid, ids, context=None):
403 for item in self.browse(cr, uid, ids, context=context):
404 if item.price_max_margin and item.price_min_margin and (item.price_min_margin > item.price_max_margin):
409 'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
410 'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
411 '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."),
412 'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Specify a product if this rule only applies to one product. Keep empty otherwise."),
413 '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."),
415 'min_quantity': fields.integer('Min. Quantity', required=True, help="Specify the minimum quantity that needs to be bought/sold for the rule to apply."),
416 '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."),
417 'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="Base price for computation."),
418 'base_pricelist_id': fields.many2one('product.pricelist', 'Other Pricelist'),
420 'price_surcharge': fields.float('Price Surcharge',
421 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.'),
422 'price_discount': fields.float('Price Discount', digits=(16,4)),
423 'price_round': fields.float('Price Rounding',
424 digits_compute= dp.get_precision('Product Price'),
425 help="Sets the price so that it is a multiple of this value.\n" \
426 "Rounding is applied after the discount and before the surcharge.\n" \
427 "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
429 'price_min_margin': fields.float('Min. Price Margin',
430 digits_compute= dp.get_precision('Product Price'), help='Specify the minimum amount of margin over the base price.'),
431 'price_max_margin': fields.float('Max. Price Margin',
432 digits_compute= dp.get_precision('Product Price'), help='Specify the maximum amount of margin over the base price.'),
433 'company_id': fields.related('price_version_id','company_id',type='many2one',
434 readonly=True, relation='res.company', string='Company', store=True)
438 (_check_recursion, 'Error! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!', ['base_pricelist_id']),
439 (_check_margin, 'Error! The minimum margin should be lower than the maximum margin.', ['price_min_margin', 'price_max_margin'])
442 def product_id_change(self, cr, uid, ids, product_id, context=None):
445 prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
447 return {'value': {'name': prod[0]['code']}}
449 product_pricelist_item()
453 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: