[FIX] Pricelist : Proper context passed to price_get to make use of pricelist version...
[odoo/odoo.git] / addons / product / pricelist.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import fields, osv
24
25 from _common import rounding
26 import time
27 from tools import config
28 from tools.misc import ustr
29 from tools.translate import _
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={}):
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 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={}):
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     _name = "product.pricelist"
94     _description = "Pricelist"
95     _columns = {
96         'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
97         'active': fields.boolean('Active'),
98         'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
99         'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
100         'currency_id': fields.many2one('res.currency', 'Currency', required=True),
101     }
102
103     def name_get(self, cr, uid, ids, context={}):
104         result= []
105         if not all(ids):
106             return result
107         for pl in self.browse(cr, uid, ids, context):
108             name = pl.name + ' ('+ pl.currency_id.name + ')'
109             result.append((pl.id,name))
110         return result
111
112
113     def _get_currency(self, cr, uid, ctx):
114         comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
115         if not comp:
116             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
117             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
118         return comp.currency_id.id
119
120     _defaults = {
121         'active': lambda *a: 1,
122         "currency_id": _get_currency
123     }
124
125     def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
126         '''
127         context = {
128             'uom': Unit of Measure (int),
129             'partner': Partner ID (int),
130             'date': Date of the pricelist (%Y-%m-%d),
131         }
132         '''
133         if context is None:
134             context = {}
135         currency_obj = self.pool.get('res.currency')
136         product_obj = self.pool.get('product.product')
137         supplierinfo_obj = self.pool.get('product.supplierinfo')
138         price_type_obj = self.pool.get('product.price.type')
139
140         if context and ('partner_id' in context):
141             partner = context['partner_id']
142         context['partner_id'] = partner
143         date = time.strftime('%Y-%m-%d')
144         if context and ('date' in context):
145             date = context['date']
146         result = {}
147         for id in ids:
148             cr.execute('SELECT * ' \
149                     'FROM product_pricelist_version ' \
150                     'WHERE pricelist_id = %s AND active=True ' \
151                         'AND (date_start IS NULL OR date_start <= %s) ' \
152                         'AND (date_end IS NULL OR date_end >= %s) ' \
153                     'ORDER BY id LIMIT 1', (id, date, date))
154             plversion = cr.dictfetchone()
155
156             if not plversion:
157                 raise osv.except_osv(_('Warning !'),
158                         _('No active version for the selected pricelist !\n' \
159                                 'Please create or activate one.'))
160
161             cr.execute('SELECT id, categ_id ' \
162                     'FROM product_template ' \
163                     'WHERE id = (SELECT product_tmpl_id ' \
164                         'FROM product_product ' \
165                         'WHERE id = %s)', (prod_id,))
166             tmpl_id, categ = cr.fetchone()
167             categ_ids = []
168             while categ:
169                 categ_ids.append(str(categ))
170                 cr.execute('SELECT parent_id ' \
171                         'FROM product_category ' \
172                         'WHERE id = %s', (categ,))
173                 categ = cr.fetchone()[0]
174                 if str(categ) in categ_ids:
175                     raise osv.except_osv(_('Warning !'),
176                             _('Could not resolve product category, ' \
177                                     'you have defined cyclic categories ' \
178                                     'of products!'))
179             if categ_ids:
180                 categ_where = '(categ_id IN %s)'
181                 sqlargs = (tuple(categ_ids),)
182             else:
183                 categ_where = '(categ_id IS NULL)'
184                 sqlargs = ()
185
186             cr.execute(
187                 'SELECT i.*, pl.currency_id '
188                 'FROM product_pricelist_item AS i, '
189                     'product_pricelist_version AS v, product_pricelist AS pl '
190                 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
191                     'AND (product_id IS NULL OR product_id = %s) '
192                     'AND (' + categ_where + ' OR (categ_id IS NULL)) '
193                     'AND price_version_id = %s '
194                     'AND (min_quantity IS NULL OR min_quantity <= %s) '
195                     'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
196                 'ORDER BY sequence LIMIT 1',
197                 (tmpl_id, prod_id) + sqlargs + ( plversion['id'], qty))
198             res = cr.dictfetchone()
199             if res:
200                 if res['base'] == -1:
201                     if not res['base_pricelist_id']:
202                         price = 0.0
203                     else:
204                         price_tmp = self.price_get(cr, uid,
205                                 [res['base_pricelist_id']], prod_id,
206                                 qty, context=context)[res['base_pricelist_id']]
207                         ptype_src = self.browse(cr, uid,
208                                 res['base_pricelist_id']).currency_id.id
209                         price = currency_obj.compute(cr, uid, ptype_src,
210                                 res['currency_id'], price_tmp, round=False)
211                 elif res['base'] == -2:
212                     where = []
213                     if partner:
214                         where = [('name', '=', partner) ]
215                     sinfo = supplierinfo_obj.search(cr, uid,
216                             [('product_id', '=', tmpl_id)] + where)
217                     price = 0.0
218                     if sinfo:
219                         cr.execute('SELECT * ' \
220                                 'FROM pricelist_partnerinfo ' \
221                                 'WHERE suppinfo_id IN %s ' \
222                                     'AND min_quantity <= %s ' \
223                                 'ORDER BY min_quantity DESC LIMIT 1',
224                                    (tuple(sinfo), qty))
225                         res2 = cr.dictfetchone()
226                         if res2:
227                             price = res2['price']
228                 else:
229                     price_type = price_type_obj.browse(cr, uid, int(res['base']))
230                     price = currency_obj.compute(cr, uid,
231                             price_type.currency_id.id, res['currency_id'],
232                             product_obj.price_get(cr, uid, [prod_id],
233                                 price_type.field)[prod_id], round=False, context=context)
234
235                 price_limit = price
236
237                 price = price * (1.0+(res['price_discount'] or 0.0))
238                 price = rounding(price, res['price_round'])
239                 price += (res['price_surcharge'] or 0.0)
240                 if res['price_min_margin']:
241                     price = max(price, price_limit+res['price_min_margin'])
242                 if res['price_max_margin']:
243                     price = min(price, price_limit+res['price_max_margin'])
244             else:
245                 # False means no valid line found ! But we may not raise an
246                 # exception here because it breaks the search
247                 price = False
248             result[id] = price
249             if context and ('uom' in context):
250                 product = product_obj.browse(cr, uid, prod_id)
251                 uom = product.uos_id or product.uom_id
252                 result[id] = self.pool.get('product.uom')._compute_price(cr,
253                         uid, uom.id, result[id], context['uom'])
254         return result
255
256 product_pricelist()
257
258
259 class product_pricelist_version(osv.osv):
260     _name = "product.pricelist.version"
261     _description = "Pricelist Version"
262     _columns = {
263         'pricelist_id': fields.many2one('product.pricelist', 'Price List',
264             required=True, select=True, ondelete='cascade'),
265         'name': fields.char('Name', size=64, required=True, translate=True),
266         'active': fields.boolean('Active',
267             help="When a version is duplicated it is set to non active, so that the " \
268             "dates do not overlaps with original version. You should change the dates " \
269             "and reactivate the pricelist"),
270         'items_id': fields.one2many('product.pricelist.item',
271             'price_version_id', 'Price List Items', required=True),
272         'date_start': fields.date('Start Date', help="Starting date for this pricelist version to be valid."),
273         'date_end': fields.date('End Date', help="Ending date for this pricelist version to be valid."),
274     }
275     _defaults = {
276         'active': lambda *a: 1,
277     }
278
279     # We desactivate duplicated pricelists, so that dates do not overlap
280     def copy(self, cr, uid, id, default=None,context={}):
281         if not default: default= {}
282         default['active'] = False
283         return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
284
285     def _check_date(self, cursor, user, ids):
286         for pricelist_version in self.browse(cursor, user, ids):
287             if not pricelist_version.active:
288                 continue
289             where = []
290             if pricelist_version.date_start:
291                 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
292             if pricelist_version.date_end:
293                 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
294
295             cursor.execute('SELECT id ' \
296                     'FROM product_pricelist_version ' \
297                     'WHERE '+' and '.join(where) + (where and ' and ' or '')+
298                         'pricelist_id = %s ' \
299                         'AND active ' \
300                         'AND id <> %s', (
301                             pricelist_version.pricelist_id.id,
302                             pricelist_version.id))
303             if cursor.fetchall():
304                 return False
305         return True
306
307     _constraints = [
308         (_check_date, 'You cannot have 2 pricelist versions that overlap!',
309             ['date_start', 'date_end'])
310     ]
311
312 product_pricelist_version()
313
314 class product_pricelist_item(osv.osv):
315     def _price_field_get(self, cr, uid, context={}):
316         pt = self.pool.get('product.price.type')
317         ids = pt.search(cr, uid, [], context=context)
318         result = []
319         for line in pt.browse(cr, uid, ids, context=context):
320             result.append((line.id, line.name))
321
322         result.append((-1, _('Other Pricelist')))
323         result.append((-2, _('Partner section of the product form')))
324         return result
325
326     _name = "product.pricelist.item"
327     _description = "Pricelist item"
328     _order = "sequence, min_quantity desc"
329     _defaults = {
330         'base': lambda *a: -1,
331         'min_quantity': lambda *a: 0,
332         'sequence': lambda *a: 5,
333         'price_discount': lambda *a: 0,
334     }
335
336     def _check_recursion(self, cr, uid, ids):
337         for obj_list in self.browse(cr, uid, ids):
338             if obj_list.base == -1:
339                 main_pricelist = obj_list.price_version_id.pricelist_id.id
340                 other_pricelist = obj_list.base_pricelist_id.id
341                 if main_pricelist == other_pricelist:
342                     return False
343         return True
344
345     _columns = {
346         'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
347         'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
348         '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"),
349         '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"),
350         '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 childs. Keep empty for all products"),
351
352         'min_quantity': fields.integer('Min. Quantity', required=True, help="The rule only applies if the partner buys/sells more than this quantity."),
353         'sequence': fields.integer('Sequence', required=True),
354         'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="The mode for computing the price for this rule."),
355         'base_pricelist_id': fields.many2one('product.pricelist', 'If Other Pricelist'),
356
357         'price_surcharge': fields.float('Price Surcharge',
358             digits=(16, int(config['price_accuracy']))),
359         'price_discount': fields.float('Price Discount', digits=(16,4)),
360         'price_round': fields.float('Price Rounding',
361             digits=(16, int(config['price_accuracy'])),
362             help="Sets the price so that it is a multiple of this value.\n" \
363               "Rounding is applied after the discount and before the surcharge.\n" \
364               "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
365             ),
366         'price_min_margin': fields.float('Min. Price Margin',
367             digits=(16, int(config['price_accuracy']))),
368         'price_max_margin': fields.float('Max. Price Margin',
369             digits=(16, int(config['price_accuracy']))),
370     }
371
372     _constraints = [
373         (_check_recursion, _('Error ! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!'), ['base_pricelist_id'])
374     ]
375
376     def product_id_change(self, cr, uid, ids, product_id, context={}):
377         if not product_id:
378             return {}
379         prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
380         if prod[0]['code']:
381             return {'value': {'name': prod[0]['code']}}
382         return {}
383 product_pricelist_item()
384
385 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: