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