d4ed2567afc5b760406bd566ee4a7bb62f9d79d6
[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
28 import openerp.addons.decimal_precision as dp
29
30
31 class price_type(osv.osv):
32     """
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.
37     """
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)
41         res = []
42         for field in mf.browse(cr, uid, ids, context=context):
43             res.append((field.name, field.field_description))
44         return res
45
46     def _get_currency(self, cr, uid, ctx):
47         comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
48         if not comp:
49             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
50             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
51         return comp.currency_id.id
52
53     _name = "product.price.type"
54     _description = "Price Type"
55     _columns = {
56         "name" : fields.char("Price Name", size=32, required=True, translate=True, help="Name of this kind of price."),
57         "active" : fields.boolean("Active"),
58         "field" : fields.selection(_price_field_get, "Product Field", size=32, required=True, help="Associated field in the product form."),
59         "currency_id" : fields.many2one('res.currency', "Currency", required=True, help="The currency the field is expressed in."),
60     }
61     _defaults = {
62         "active": lambda *args: True,
63         "currency_id": _get_currency
64     }
65
66 price_type()
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 product_pricelist_type()
80
81
82 class product_pricelist(osv.osv):
83     def _pricelist_type_get(self, cr, uid, context=None):
84         pricelist_type_obj = self.pool.get('product.pricelist.type')
85         pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
86         pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
87
88         res = []
89
90         for type in pricelist_types:
91             res.append((type['key'],type['name']))
92
93         return res
94
95     _name = "product.pricelist"
96     _description = "Pricelist"
97     _order = 'name'
98     _columns = {
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'),
105     }
106
107     def name_get(self, cr, uid, ids, context=None):
108         result= []
109         if not all(ids):
110             return result
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))
114         return result
115
116     def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
117         if name and operator == '=' and not args:
118             # search on the name of the pricelist and its currency, opposite of name_get(),
119             # Used by the magic context filter in the product search view.
120             query_args = {'name': name, 'limit': limit}
121             query = """SELECT p.id
122                        FROM product_pricelist p JOIN
123                             res_currency c ON (p.currency_id = c.id)
124                        WHERE p.name || ' (' || c.name || ')' = %(name)s
125                        ORDER BY p.name"""
126             if limit:
127                 query += " LIMIT %(limit)s"
128             cr.execute(query, query_args)
129             ids = [r[0] for r in cr.fetchall()]
130             # regular search() to apply ACLs - may limit results below limit in some cases
131             ids = self.search(cr, uid, [('id', 'in', ids)], limit=limit, context=context)
132             if ids:
133                 return self.name_get(cr, uid, ids, context)
134         return super(product_pricelist, self).name_search(
135             cr, uid, name, args, operator=operator, context=context, limit=limit)
136
137
138     def _get_currency(self, cr, uid, ctx):
139         comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
140         if not comp:
141             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
142             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
143         return comp.currency_id.id
144
145     _defaults = {
146         'active': lambda *a: 1,
147         "currency_id": _get_currency
148     }
149
150     #def price_get_multi(self, cr, uid, product_ids, context=None):
151     def price_get_multi(self, cr, uid, pricelist_ids, products_by_qty_by_partner, context=None):
152         """multi products 'price_get'.
153            @param pricelist_ids:
154            @param products_by_qty:
155            @param partner:
156            @param context: {
157              'date': Date of the pricelist (%Y-%m-%d),}
158            @return: a dict of dict with product_id as key and a dict 'price by pricelist' as value
159         """
160
161         def _create_parent_category_list(id, lst):
162             if not id:
163                 return []
164             parent = product_category_tree.get(id)
165             if parent:
166                 lst.append(parent)
167                 return _create_parent_category_list(parent, lst)
168             else:
169                 return lst
170         # _create_parent_category_list
171
172         if context is None:
173             context = {}
174
175         date = context.get('date') or time.strftime('%Y-%m-%d')
176
177         currency_obj = self.pool.get('res.currency')
178         product_obj = self.pool.get('product.product')
179         product_category_obj = self.pool.get('product.category')
180         product_uom_obj = self.pool.get('product.uom')
181         supplierinfo_obj = self.pool.get('product.supplierinfo')
182         price_type_obj = self.pool.get('product.price.type')
183
184         # product.pricelist.version:
185         if not pricelist_ids:
186             pricelist_ids = self.pool.get('product.pricelist').search(cr, uid, [], context=context)
187
188         pricelist_version_ids = self.pool.get('product.pricelist.version').search(cr, uid, [
189                                                         ('pricelist_id', 'in', pricelist_ids),
190                                                         '|',
191                                                         ('date_start', '=', False),
192                                                         ('date_start', '<=', date),
193                                                         '|',
194                                                         ('date_end', '=', False),
195                                                         ('date_end', '>=', date),
196                                                     ])
197         if len(pricelist_ids) != len(pricelist_version_ids):
198             raise osv.except_osv(_('Warning!'), _("At least one pricelist has no active version !\nPlease create or activate one."))
199
200         # product.product:
201         product_ids = [i[0] for i in products_by_qty_by_partner]
202         #products = dict([(item['id'], item) for item in product_obj.read(cr, uid, product_ids, ['categ_id', 'product_tmpl_id', 'uos_id', 'uom_id'])])
203         products = product_obj.browse(cr, uid, product_ids, context=context)
204         products_dict = dict([(item.id, item) for item in products])
205
206         # product.category:
207         product_category_ids = product_category_obj.search(cr, uid, [])
208         product_categories = product_category_obj.read(cr, uid, product_category_ids, ['parent_id'])
209         product_category_tree = dict([(item['id'], item['parent_id'][0]) for item in product_categories if item['parent_id']])
210
211         results = {}
212         for product_id, qty, partner in products_by_qty_by_partner:
213             for pricelist_id in pricelist_ids:
214                 price = False
215
216                 tmpl_id = products_dict[product_id].product_tmpl_id and products_dict[product_id].product_tmpl_id.id or False
217
218                 categ_id = products_dict[product_id].categ_id and products_dict[product_id].categ_id.id or False
219                 categ_ids = _create_parent_category_list(categ_id, [categ_id])
220                 if categ_ids:
221                     categ_where = '(categ_id IN (' + ','.join(map(str, categ_ids)) + '))'
222                 else:
223                     categ_where = '(categ_id IS NULL)'
224
225                 if partner:
226                     partner_where = 'base <> -2 OR %s IN (SELECT name FROM product_supplierinfo WHERE product_id = %s) '
227                     partner_args = (partner, tmpl_id)
228                 else:
229                     partner_where = 'base <> -2 '
230                     partner_args = ()
231
232                 cr.execute(
233                     'SELECT i.*, pl.currency_id '
234                     'FROM product_pricelist_item AS i, '
235                         'product_pricelist_version AS v, product_pricelist AS pl '
236                     'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
237                         'AND (product_id IS NULL OR product_id = %s) '
238                         'AND (' + categ_where + ' OR (categ_id IS NULL)) '
239                         'AND (' + partner_where + ') '
240                         'AND price_version_id = %s '
241                         'AND (min_quantity IS NULL OR min_quantity <= %s) '
242                         'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
243                     'ORDER BY sequence',
244                     (tmpl_id, product_id) + partner_args + (pricelist_version_ids[0], qty))
245                 res1 = cr.dictfetchall()
246                 uom_price_already_computed = False
247                 for res in res1:
248                     if res:
249                         if res['base'] == -1:
250                             if not res['base_pricelist_id']:
251                                 price = 0.0
252                             else:
253                                 price_tmp = self.price_get(cr, uid,
254                                         [res['base_pricelist_id']], product_id,
255                                         qty, context=context)[res['base_pricelist_id']]
256                                 ptype_src = self.browse(cr, uid, res['base_pricelist_id']).currency_id.id
257                                 uom_price_already_computed = True
258                                 price = currency_obj.compute(cr, uid,
259                                         ptype_src, res['currency_id'],
260                                         price_tmp, round=False,
261                                         context=context)
262                         elif res['base'] == -2:
263                             # this section could be improved by moving the queries outside the loop:
264                             where = []
265                             if partner:
266                                 where = [('name', '=', partner) ]
267                             sinfo = supplierinfo_obj.search(cr, uid,
268                                     [('product_id', '=', tmpl_id)] + where)
269                             price = 0.0
270                             if sinfo:
271                                 qty_in_product_uom = qty
272                                 from_uom = context.get('uom') or product_obj.read(cr, uid, [product_id], ['uom_id'])[0]['uom_id'][0]
273                                 supplier = supplierinfo_obj.browse(cr, uid, sinfo, context=context)[0]
274                                 seller_uom = supplier.product_uom and supplier.product_uom.id or False
275                                 if seller_uom and from_uom and from_uom != seller_uom:
276                                     qty_in_product_uom = product_uom_obj._compute_qty(cr, uid, from_uom, qty, to_uom_id=seller_uom)
277                                 else:
278                                     uom_price_already_computed = True
279                                 cr.execute('SELECT * ' \
280                                         'FROM pricelist_partnerinfo ' \
281                                         'WHERE suppinfo_id IN %s' \
282                                             'AND min_quantity <= %s ' \
283                                         'ORDER BY min_quantity DESC LIMIT 1', (tuple(sinfo),qty_in_product_uom,))
284                                 res2 = cr.dictfetchone()
285                                 if res2:
286                                     price = res2['price']
287                         else:
288                             price_type = price_type_obj.browse(cr, uid, int(res['base']))
289                             uom_price_already_computed = True
290                             price = currency_obj.compute(cr, uid,
291                                     price_type.currency_id.id, res['currency_id'],
292                                     product_obj.price_get(cr, uid, [product_id],
293                                     price_type.field, context=context)[product_id], round=False, context=context)
294
295                         if price is not False:
296                             price_limit = price
297                             price = price * (1.0+(res['price_discount'] or 0.0))
298                             if res['price_round']:
299                                 price = tools.float_round(price, precision_rounding=res['price_round'])
300                             price += (res['price_surcharge'] or 0.0)
301                             if res['price_min_margin']:
302                                 price = max(price, price_limit+res['price_min_margin'])
303                             if res['price_max_margin']:
304                                 price = min(price, price_limit+res['price_max_margin'])
305                             break
306
307                     else:
308                         # False means no valid line found ! But we may not raise an
309                         # exception here because it breaks the search
310                         price = False
311
312                 if price:
313                     results['item_id'] = res['id']
314                     if 'uom' in context and not uom_price_already_computed:
315                         product = products_dict[product_id]
316                         uom = product.uos_id or product.uom_id
317                         price = product_uom_obj._compute_price(cr, uid, uom.id, price, context['uom'])
318
319                 if results.get(product_id):
320                     results[product_id][pricelist_id] = price
321                 else:
322                     results[product_id] = {pricelist_id: price}
323
324         return results
325
326     def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
327         res_multi = self.price_get_multi(cr, uid, pricelist_ids=ids, products_by_qty_by_partner=[(prod_id, qty, partner)], context=context)
328         res = res_multi[prod_id]
329         res.update({'item_id': {ids[-1]: res_multi.get('item_id', ids[-1])}})
330         return res
331
332 product_pricelist()
333
334
335 class product_pricelist_version(osv.osv):
336     _name = "product.pricelist.version"
337     _description = "Pricelist Version"
338     _columns = {
339         'pricelist_id': fields.many2one('product.pricelist', 'Price List',
340             required=True, select=True, ondelete='cascade'),
341         'name': fields.char('Name', size=64, required=True, translate=True),
342         'active': fields.boolean('Active',
343             help="When a version is duplicated it is set to non active, so that the " \
344             "dates do not overlaps with original version. You should change the dates " \
345             "and reactivate the pricelist"),
346         'items_id': fields.one2many('product.pricelist.item',
347             'price_version_id', 'Price List Items', required=True),
348         'date_start': fields.date('Start Date', help="First valid date for the version."),
349         'date_end': fields.date('End Date', help="Last valid date for the version."),
350         'company_id': fields.related('pricelist_id','company_id',type='many2one',
351             readonly=True, relation='res.company', string='Company', store=True)
352     }
353     _defaults = {
354         'active': lambda *a: 1,
355     }
356
357     # We desactivate duplicated pricelists, so that dates do not overlap
358     def copy(self, cr, uid, id, default=None, context=None):
359         if not default: default= {}
360         default['active'] = False
361         return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
362
363     def _check_date(self, cursor, user, ids, context=None):
364         for pricelist_version in self.browse(cursor, user, ids, context=context):
365             if not pricelist_version.active:
366                 continue
367             where = []
368             if pricelist_version.date_start:
369                 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
370             if pricelist_version.date_end:
371                 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
372
373             cursor.execute('SELECT id ' \
374                     'FROM product_pricelist_version ' \
375                     'WHERE '+' and '.join(where) + (where and ' and ' or '')+
376                         'pricelist_id = %s ' \
377                         'AND active ' \
378                         'AND id <> %s', (
379                             pricelist_version.pricelist_id.id,
380                             pricelist_version.id))
381             if cursor.fetchall():
382                 return False
383         return True
384
385     _constraints = [
386         (_check_date, 'You cannot have 2 pricelist versions that overlap!',
387             ['date_start', 'date_end'])
388     ]
389
390 product_pricelist_version()
391
392 class product_pricelist_item(osv.osv):
393     def _price_field_get(self, cr, uid, context=None):
394         pt = self.pool.get('product.price.type')
395         ids = pt.search(cr, uid, [], context=context)
396         result = []
397         for line in pt.browse(cr, uid, ids, context=context):
398             result.append((line.id, line.name))
399
400         result.append((-1, _('Other Pricelist')))
401         result.append((-2, _('Supplier Prices on the product form')))
402         return result
403
404     _name = "product.pricelist.item"
405     _description = "Pricelist item"
406     _order = "sequence, min_quantity desc"
407     _defaults = {
408         'base': lambda *a: -1,
409         'min_quantity': lambda *a: 0,
410         'sequence': lambda *a: 5,
411         'price_discount': lambda *a: 0,
412     }
413
414     def _check_recursion(self, cr, uid, ids, context=None):
415         for obj_list in self.browse(cr, uid, ids, context=context):
416             if obj_list.base == -1:
417                 main_pricelist = obj_list.price_version_id.pricelist_id.id
418                 other_pricelist = obj_list.base_pricelist_id.id
419                 if main_pricelist == other_pricelist:
420                     return False
421         return True
422
423     def _check_margin(self, cr, uid, ids, context=None):
424         for item in self.browse(cr, uid, ids, context=context):
425             if item.price_max_margin and item.price_min_margin and (item.price_min_margin > item.price_max_margin):
426                 return False
427         return True
428
429     _columns = {
430         'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
431         'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
432         '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."),
433         'product_id': fields.many2one('product.product', 'Product', ondelete='cascade', help="Specify a product if this rule only applies to one product. Keep empty otherwise."),
434         '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."),
435
436         'min_quantity': fields.integer('Min. Quantity', required=True, help="Specify the minimum quantity that needs to be bought/sold for the rule to apply."),
437         '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."),
438         'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="Base price for computation."),
439         'base_pricelist_id': fields.many2one('product.pricelist', 'Other Pricelist'),
440
441         'price_surcharge': fields.float('Price Surcharge',
442             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.'),
443         'price_discount': fields.float('Price Discount', digits=(16,4)),
444         'price_round': fields.float('Price Rounding',
445             digits_compute= dp.get_precision('Product Price'),
446             help="Sets the price so that it is a multiple of this value.\n" \
447               "Rounding is applied after the discount and before the surcharge.\n" \
448               "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
449             ),
450         'price_min_margin': fields.float('Min. Price Margin',
451             digits_compute= dp.get_precision('Product Price'), help='Specify the minimum amount of margin over the base price.'),
452         'price_max_margin': fields.float('Max. Price Margin',
453             digits_compute= dp.get_precision('Product Price'), help='Specify the maximum amount of margin over the base price.'),
454         'company_id': fields.related('price_version_id','company_id',type='many2one',
455             readonly=True, relation='res.company', string='Company', store=True)
456     }
457
458     _constraints = [
459         (_check_recursion, 'Error! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!', ['base_pricelist_id']),
460         (_check_margin, 'Error! The minimum margin should be lower than the maximum margin.', ['price_min_margin', 'price_max_margin'])
461     ]
462
463     def product_id_change(self, cr, uid, ids, product_id, context=None):
464         if not product_id:
465             return {}
466         prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
467         if prod[0]['code']:
468             return {'value': {'name': prod[0]['code']}}
469         return {}
470 product_pricelist_item()
471
472
473
474 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
475