49b518a8078c1d8519a221e4518642d32aceeb7b
[odoo/odoo.git] / addons / product / pricelist.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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
24 from openerp import tools
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 from openerp.exceptions import except_orm
28
29 import openerp.addons.decimal_precision as dp
30
31
32 class price_type(osv.osv):
33     """
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.
38     """
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)
42         res = []
43         for field in mf.browse(cr, uid, ids, context=context):
44             res.append((field.name, field.field_description))
45         return res
46
47     def _get_field_currency(self, cr, uid, fname, ctx):
48         ids = self.search(cr, uid, [('field','=',fname)], context=ctx)
49         return self.browse(cr, uid, ids, context=ctx)[0].currency_id
50
51     def _get_currency(self, cr, uid, ctx):
52         comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
53         if not comp:
54             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
55             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
56         return comp.currency_id.id
57
58     _name = "product.price.type"
59     _description = "Price Type"
60     _columns = {
61         "name" : fields.char("Price Name", required=True, translate=True, help="Name of this kind of price."),
62         "active" : fields.boolean("Active"),
63         "field" : fields.selection(_price_field_get, "Product Field", size=32, required=True, help="Associated field in the product form."),
64         "currency_id" : fields.many2one('res.currency', "Currency", required=True, help="The currency the field is expressed in."),
65     }
66     _defaults = {
67         "active": lambda *args: True,
68         "currency_id": _get_currency
69     }
70
71
72 #----------------------------------------------------------
73 # Price lists
74 #----------------------------------------------------------
75
76 class product_pricelist_type(osv.osv):
77     _name = "product.pricelist.type"
78     _description = "Pricelist Type"
79     _columns = {
80         'name': fields.char('Name', required=True, translate=True),
81         'key': fields.char('Key', required=True, help="Used in the code to select specific prices based on the context. Keep unchanged."),
82     }
83
84
85 class product_pricelist(osv.osv):
86     def _pricelist_type_get(self, cr, uid, context=None):
87         pricelist_type_obj = self.pool.get('product.pricelist.type')
88         pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
89         pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
90
91         res = []
92
93         for type in pricelist_types:
94             res.append((type['key'],type['name']))
95
96         return res
97
98     _name = "product.pricelist"
99     _description = "Pricelist"
100     _order = 'name'
101     _columns = {
102         'name': fields.char('Pricelist Name', required=True, translate=True),
103         'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the pricelist without removing it."),
104         'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
105         'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions', copy=True),
106         'currency_id': fields.many2one('res.currency', 'Currency', required=True),
107         'company_id': fields.many2one('res.company', 'Company'),
108     }
109
110     def name_get(self, cr, uid, ids, context=None):
111         result= []
112         if not all(ids):
113             return result
114         for pl in self.browse(cr, uid, ids, context=context):
115             name = pl.name + ' ('+ pl.currency_id.name + ')'
116             result.append((pl.id,name))
117         return result
118
119     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
120         if name and operator == '=' and not args:
121             # search on the name of the pricelist and its currency, opposite of name_get(),
122             # Used by the magic context filter in the product search view.
123             query_args = {'name': name, 'limit': limit, 'lang': (context or {}).get('lang') or 'en_US'}
124             query = """SELECT p.id
125                        FROM ((
126                                 SELECT pr.id, pr.name
127                                 FROM product_pricelist pr JOIN
128                                      res_currency cur ON 
129                                          (pr.currency_id = cur.id)
130                                 WHERE pr.name || ' (' || cur.name || ')' = %(name)s
131                             )
132                             UNION (
133                                 SELECT tr.res_id as id, tr.value as name
134                                 FROM ir_translation tr JOIN
135                                      product_pricelist pr ON (
136                                         pr.id = tr.res_id AND
137                                         tr.type = 'model' AND
138                                         tr.name = 'product.pricelist,name' AND
139                                         tr.lang = %(lang)s
140                                      ) JOIN
141                                      res_currency cur ON 
142                                          (pr.currency_id = cur.id)
143                                 WHERE tr.value || ' (' || cur.name || ')' = %(name)s
144                             )
145                         ) p
146                        ORDER BY p.name"""
147             if limit:
148                 query += " LIMIT %(limit)s"
149             cr.execute(query, query_args)
150             ids = [r[0] for r in cr.fetchall()]
151             # regular search() to apply ACLs - may limit results below limit in some cases
152             ids = self.search(cr, uid, [('id', 'in', ids)], limit=limit, context=context)
153             if ids:
154                 return self.name_get(cr, uid, ids, context)
155         return super(product_pricelist, self).name_search(
156             cr, uid, name, args, operator=operator, context=context, limit=limit)
157
158
159     def _get_currency(self, cr, uid, ctx):
160         comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
161         if not comp:
162             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
163             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
164         return comp.currency_id.id
165
166     _defaults = {
167         'active': lambda *a: 1,
168         "currency_id": _get_currency
169     }
170
171     def price_get_multi(self, cr, uid, ids, products_by_qty_by_partner, context=None):
172         return dict((key, dict((key, price[0]) for key, price in value.items())) for key, value in self.price_rule_get_multi(cr, uid, ids, products_by_qty_by_partner, context=context).items())
173
174     def price_rule_get_multi(self, cr, uid, ids, products_by_qty_by_partner, context=None):
175         """multi products 'price_get'.
176            @param ids:
177            @param products_by_qty:
178            @param partner:
179            @param context: {
180              'date': Date of the pricelist (%Y-%m-%d),}
181            @return: a dict of dict with product_id as key and a dict 'price by pricelist' as value
182         """
183         if not ids:
184             ids = self.pool.get('product.pricelist').search(cr, uid, [], context=context)
185         results = {}
186         for pricelist in self.browse(cr, uid, ids, context=context):
187             subres = self._price_rule_get_multi(cr, uid, pricelist, products_by_qty_by_partner, context=context)
188             for product_id,price in subres.items():
189                 results.setdefault(product_id, {})
190                 results[product_id][pricelist.id] = price
191         return results
192
193     def _price_get_multi(self, cr, uid, pricelist, products_by_qty_by_partner, context=None):
194         return dict((key, price[0]) for key, price in self._price_rule_get_multi(cr, uid, pricelist, products_by_qty_by_partner, context=context).items())
195
196     def _price_rule_get_multi(self, cr, uid, pricelist, products_by_qty_by_partner, context=None):
197         context = context or {}
198         date = context.get('date') or time.strftime('%Y-%m-%d')
199
200         products = map(lambda x: x[0], products_by_qty_by_partner)
201         currency_obj = self.pool.get('res.currency')
202         product_obj = self.pool.get('product.template')
203         product_uom_obj = self.pool.get('product.uom')
204         price_type_obj = self.pool.get('product.price.type')
205
206         if not products:
207             return {}
208
209         version = False
210         for v in pricelist.version_id:
211             if ((v.date_start is False) or (v.date_start <= date)) and ((v.date_end is False) or (v.date_end >= date)):
212                 version = v
213                 break
214         if not version:
215             raise osv.except_osv(_('Warning!'), _("At least one pricelist has no active version !\nPlease create or activate one."))
216         categ_ids = {}
217         for p in products:
218             categ = p.categ_id
219             while categ:
220                 categ_ids[categ.id] = True
221                 categ = categ.parent_id
222         categ_ids = categ_ids.keys()
223
224         is_product_template = products[0]._name == "product.template"
225         if is_product_template:
226             prod_tmpl_ids = [tmpl.id for tmpl in products]
227             prod_ids = [product.id for product in tmpl.product_variant_ids for tmpl in products]
228         else:
229             prod_ids = [product.id for product in products]
230             prod_tmpl_ids = [product.product_tmpl_id.id for product in products]
231
232         # Load all rules
233         cr.execute(
234             'SELECT i.id '
235             'FROM product_pricelist_item AS i '
236             'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = any(%s)) '
237                 'AND (product_id IS NULL OR (product_id = any(%s))) '
238                 'AND ((categ_id IS NULL) OR (categ_id = any(%s))) '
239                 'AND (price_version_id = %s) '
240             'ORDER BY sequence, min_quantity desc',
241             (prod_tmpl_ids, prod_ids, categ_ids, version.id))
242         
243         item_ids = [x[0] for x in cr.fetchall()]
244         items = self.pool.get('product.pricelist.item').browse(cr, uid, item_ids, context=context)
245
246         price_types = {}
247
248         results = {}
249         for product, qty, partner in products_by_qty_by_partner:
250             uom_price_already_computed = False
251             results[product.id] = 0.0
252             price = False
253             rule_id = False
254             for rule in items:
255                 if 'uom' in context and product.uom_id and context['uom'] != product.uom_id.id:
256                     try:
257                         qty_in_product_uom = product_uom_obj._compute_qty(cr, uid, context['uom'], qty, product.uom_id.id, dict(context.items() + [('raise-exception', False)]))
258                     except except_orm:
259                         qty_in_product_uom = qty
260                 else:
261                     qty_in_product_uom = qty
262                 if rule.min_quantity and qty_in_product_uom<rule.min_quantity:
263                     continue
264                 if is_product_template:
265                     if rule.product_tmpl_id and product.id != rule.product_tmpl_id.id:
266                         continue
267                     if rule.product_id:
268                         continue
269                 else:
270                     if rule.product_tmpl_id and product.product_tmpl_id.id != rule.product_tmpl_id.id:
271                         continue
272                     if rule.product_id and product.id != rule.product_id.id:
273                         continue
274
275                 if rule.categ_id:
276                     cat = product.categ_id
277                     while cat:
278                         if cat.id == rule.categ_id.id:
279                             break
280                         cat = cat.parent_id
281                     if not cat:
282                         continue
283
284                 if rule.base == -1:
285                     if rule.base_pricelist_id:
286                         price_tmp = self._price_get_multi(cr, uid,
287                                 rule.base_pricelist_id, [(product,
288                                 qty, False)], context=context)[product.id]
289                         ptype_src = rule.base_pricelist_id.currency_id.id
290                         uom_price_already_computed = True
291                         price = currency_obj.compute(cr, uid,
292                                 ptype_src, pricelist.currency_id.id,
293                                 price_tmp, round=False,
294                                 context=context)
295                 elif rule.base == -2:
296                     seller = False
297                     for seller_id in product.seller_ids:
298                         if (not partner) or (seller_id.name.id != partner):
299                             continue
300                         seller = seller_id
301                     if not seller and product.seller_ids:
302                         seller = product.seller_ids[0]
303                     if seller:
304                         qty_in_seller_uom = qty
305                         from_uom = context.get('uom') or product.uom_id.id
306                         seller_uom = seller.product_uom and seller.product_uom.id or False
307                         if seller_uom and from_uom and from_uom != seller_uom:
308                             qty_in_seller_uom = product_uom_obj._compute_qty(cr, uid, from_uom, qty, to_uom_id=seller_uom)
309                         else:
310                             uom_price_already_computed = True
311                         for line in seller.pricelist_ids:
312                             if line.min_quantity <= qty_in_seller_uom:
313                                 price = line.price
314
315                 else:
316                     if rule.base not in price_types:
317                         price_types[rule.base] = price_type_obj.browse(cr, uid, int(rule.base))
318                     price_type = price_types[rule.base]
319
320                     uom_price_already_computed = True
321                     price = currency_obj.compute(cr, uid,
322                             price_type.currency_id.id, pricelist.currency_id.id,
323                             product_obj._price_get(cr, uid, [product],
324                             price_type.field, context=context)[product.id], round=False, context=context)
325
326                 if price is not False:
327                     price_limit = price
328                     price = price * (1.0+(rule.price_discount or 0.0))
329                     if rule.price_round:
330                         price = tools.float_round(price, precision_rounding=rule.price_round)
331                     if context.get('uom'):
332                         # compute price_surcharge based on reference uom
333                         factor = product_uom_obj.browse(cr, uid, context.get('uom'), context=context).factor
334                     else:
335                         factor = 1.0
336                     price += (rule.price_surcharge or 0.0) / factor
337                     if rule.price_min_margin:
338                         price = max(price, price_limit+rule.price_min_margin)
339                     if rule.price_max_margin:
340                         price = min(price, price_limit+rule.price_max_margin)
341                     rule_id = rule.id
342                 break
343
344             if price:
345                 if 'uom' in context and not uom_price_already_computed:
346                     uom = product.uos_id or product.uom_id
347                     price = product_uom_obj._compute_price(cr, uid, uom.id, price, context['uom'])
348
349             results[product.id] = (price, rule_id)
350         return results
351
352     def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
353         return dict((key, price[0]) for key, price in self.price_rule_get(cr, uid, ids, prod_id, qty, partner=partner, context=context).items())
354
355     def price_rule_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
356         product = self.pool.get('product.product').browse(cr, uid, prod_id, context=context)
357         res_multi = self.price_rule_get_multi(cr, uid, ids, products_by_qty_by_partner=[(product, qty, partner)], context=context)
358         res = res_multi[prod_id]
359         return res
360
361
362 class product_pricelist_version(osv.osv):
363     _name = "product.pricelist.version"
364     _description = "Pricelist Version"
365     _columns = {
366         'pricelist_id': fields.many2one('product.pricelist', 'Price List',
367             required=True, select=True, ondelete='cascade'),
368         'name': fields.char('Name', required=True, translate=True),
369         'active': fields.boolean('Active',
370             help="When a version is duplicated it is set to non active, so that the " \
371             "dates do not overlaps with original version. You should change the dates " \
372             "and reactivate the pricelist", copy=False),
373         'items_id': fields.one2many('product.pricelist.item',
374             'price_version_id', 'Price List Items', required=True, copy=True),
375         'date_start': fields.date('Start Date', help="First valid date for the version."),
376         'date_end': fields.date('End Date', help="Last valid date for the version."),
377         'company_id': fields.related('pricelist_id','company_id',type='many2one',
378             readonly=True, relation='res.company', string='Company', store=True)
379     }
380     _defaults = {
381         'active': lambda *a: 1,
382     }
383
384     def _check_date(self, cursor, user, ids, context=None):
385         for pricelist_version in self.browse(cursor, user, ids, context=context):
386             if not pricelist_version.active:
387                 continue
388             where = []
389             if pricelist_version.date_start:
390                 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
391             if pricelist_version.date_end:
392                 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
393
394             cursor.execute('SELECT id ' \
395                     'FROM product_pricelist_version ' \
396                     'WHERE '+' and '.join(where) + (where and ' and ' or '')+
397                         'pricelist_id = %s ' \
398                         'AND active ' \
399                         'AND id <> %s', (
400                             pricelist_version.pricelist_id.id,
401                             pricelist_version.id))
402             if cursor.fetchall():
403                 return False
404         return True
405
406     _constraints = [
407         (_check_date, 'You cannot have 2 pricelist versions that overlap!',
408             ['date_start', 'date_end'])
409     ]
410
411
412 class product_pricelist_item(osv.osv):
413     def _price_field_get(self, cr, uid, context=None):
414         pt = self.pool.get('product.price.type')
415         ids = pt.search(cr, uid, [], context=context)
416         result = []
417         for line in pt.browse(cr, uid, ids, context=context):
418             result.append((line.id, line.name))
419
420         result.append((-1, _('Other Pricelist')))
421         result.append((-2, _('Supplier Prices on the product form')))
422         return result
423
424 # Added default function to fetch the Price type Based on Pricelist type.
425     def _get_default_base(self, cr, uid, fields, context=None):
426         product_price_type_obj = self.pool.get('product.price.type')
427         if fields.get('type') == 'purchase':
428             product_price_type_ids = product_price_type_obj.search(cr, uid, [('field', '=', 'standard_price')], context=context)
429         elif fields.get('type') == 'sale':
430             product_price_type_ids = product_price_type_obj.search(cr, uid, [('field','=','list_price')], context=context)
431         else:
432             return -1
433         if not product_price_type_ids:
434             return False
435         else:
436             pricetype = product_price_type_obj.browse(cr, uid, product_price_type_ids, context=context)[0]
437             return pricetype.id
438
439     _name = "product.pricelist.item"
440     _description = "Pricelist item"
441     _order = "sequence, min_quantity desc"
442     _defaults = {
443         'base': _get_default_base,
444         'min_quantity': lambda *a: 0,
445         'sequence': lambda *a: 5,
446         'price_discount': lambda *a: 0,
447     }
448
449     def _check_recursion(self, cr, uid, ids, context=None):
450         for obj_list in self.browse(cr, uid, ids, context=context):
451             if obj_list.base == -1:
452                 main_pricelist = obj_list.price_version_id.pricelist_id.id
453                 other_pricelist = obj_list.base_pricelist_id.id
454                 if main_pricelist == other_pricelist:
455                     return False
456         return True
457
458     def _check_margin(self, cr, uid, ids, context=None):
459         for item in self.browse(cr, uid, ids, context=context):
460             if item.price_max_margin and item.price_min_margin and (item.price_min_margin > item.price_max_margin):
461                 return False
462         return True
463
464     _columns = {
465         'name': fields.char('Rule Name', help="Explicit rule name for this pricelist line."),
466         'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
467         '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."),
468         'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Specify a product if this rule only applies to one product. Keep empty otherwise."),
469         '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."),
470         'min_quantity': fields.integer('Min. Quantity', required=True,
471             help="For the rule to apply, bought/sold quantity must be greater "
472               "than or equal to the minimum quantity specified in this field.\n"
473               "Expressed in the default UoM of the product."
474             ),
475         '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."),
476         'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="Base price for computation."),
477         'base_pricelist_id': fields.many2one('product.pricelist', 'Other Pricelist'),
478
479         'price_surcharge': fields.float('Price Surcharge',
480             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.'),
481         'price_discount': fields.float('Price Discount', digits=(16,4)),
482         'price_round': fields.float('Price Rounding',
483             digits_compute= dp.get_precision('Product Price'),
484             help="Sets the price so that it is a multiple of this value.\n" \
485               "Rounding is applied after the discount and before the surcharge.\n" \
486               "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
487             ),
488         'price_min_margin': fields.float('Min. Price Margin',
489             digits_compute= dp.get_precision('Product Price'), help='Specify the minimum amount of margin over the base price.'),
490         'price_max_margin': fields.float('Max. Price Margin',
491             digits_compute= dp.get_precision('Product Price'), help='Specify the maximum amount of margin over the base price.'),
492         'company_id': fields.related('price_version_id','company_id',type='many2one',
493             readonly=True, relation='res.company', string='Company', store=True)
494     }
495
496     _constraints = [
497         (_check_recursion, 'Error! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!', ['base_pricelist_id']),
498         (_check_margin, 'Error! The minimum margin should be lower than the maximum margin.', ['price_min_margin', 'price_max_margin'])
499     ]
500
501     def product_id_change(self, cr, uid, ids, product_id, context=None):
502         if not product_id:
503             return {}
504         prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
505         if prod[0]['code']:
506             return {'value': {'name': prod[0]['code']}}
507         return {}
508
509
510
511 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
512