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