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