merge
[odoo/odoo.git] / addons / product / pricelist.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2008 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 tools.misc import currency
26 from _common import rounding
27 import time
28 from tools import config
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", 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),
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         cr.execute('select key,name from product_pricelist_type order by name')
84         return cr.fetchall()
85     _name = "product.pricelist"
86     _description = "Pricelist"
87     _columns = {
88         'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
89         'active': fields.boolean('Active'),
90         'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
91         'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
92         'currency_id': fields.many2one('res.currency', 'Currency', required=True),
93     }
94     def name_get(self, cr, uid, ids, context={}):
95         result= {}
96         for pl in self.browse(cr, uid, ids, context):
97             result[pl.id] = pl.name + ' ('+ pl.currency_id.name + ')'
98         return result
99
100     def _get_currency(self, cr, uid, ctx):
101         comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
102         if not comp:
103             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
104             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
105         return comp.currency_id.id
106
107     _defaults = {
108         'active': lambda *a: 1,
109         "currency_id": _get_currency
110     }
111
112     def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
113         '''
114         context = {
115             'uom': Unit of Measure (int),
116             'partner': Partner ID (int),
117             'date': Date of the pricelist (%Y-%m-%d),
118         }
119         '''
120         context = context or {}
121         currency_obj = self.pool.get('res.currency')
122         product_obj = self.pool.get('product.product')
123         supplierinfo_obj = self.pool.get('product.supplierinfo')
124         price_type_obj = self.pool.get('product.price.type')
125
126         if context and ('partner_id' in context):
127             partner = context['partner_id']
128         context['partner_id'] = partner
129         date = time.strftime('%Y-%m-%d')
130         if context and ('date' in context):
131             date = context['date']
132         result = {}
133         for id in ids:
134             cr.execute('SELECT * ' \
135                     'FROM product_pricelist_version ' \
136                     'WHERE pricelist_id = %s AND active=True ' \
137                         'AND (date_start IS NULL OR date_start <= %s) ' \
138                         'AND (date_end IS NULL OR date_end >= %s) ' \
139                     'ORDER BY id LIMIT 1', (id, date, date))
140             plversion = cr.dictfetchone()
141
142             if not plversion:
143                 raise osv.except_osv(_('Warning !'),
144                         _('No active version for the selected pricelist !\n' \
145                                 'Please create or activate one.'))
146
147             cr.execute('SELECT id, categ_id ' \
148                     'FROM product_template ' \
149                     'WHERE id = (SELECT product_tmpl_id ' \
150                         'FROM product_product ' \
151                         'WHERE id = %s)', (prod_id,))
152             tmpl_id, categ = cr.fetchone()
153             categ_ids = []
154             while categ:
155                 categ_ids.append(str(categ))
156                 cr.execute('SELECT parent_id ' \
157                         'FROM product_category ' \
158                         'WHERE id = %s', (categ,))
159                 categ = cr.fetchone()[0]
160                 if str(categ) in categ_ids:
161                     raise osv.except_osv(_('Warning !'),
162                             _('Could not resolve product category, ' \
163                                     'you have defined cyclic categories ' \
164                                     'of products!'))
165             if categ_ids:
166                 categ_where = '(categ_id IN (' + ','.join(categ_ids) + '))'
167             else:
168                 categ_where = '(categ_id IS NULL)'
169
170             cr.execute(
171                 'SELECT i.*, pl.currency_id '
172                 'FROM product_pricelist_item AS i, '
173                     'product_pricelist_version AS v, product_pricelist AS pl '
174                 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
175                     'AND (product_id IS NULL OR product_id = %s) '
176                     'AND (' + categ_where + ' OR (categ_id IS NULL)) '
177                     'AND price_version_id = %s '
178                     'AND (min_quantity IS NULL OR min_quantity <= %s) '
179                     'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
180                 'ORDER BY sequence LIMIT 1',
181                 (tmpl_id, prod_id, plversion['id'], qty))
182             res = cr.dictfetchone()
183             if res:
184                 if res['base'] == -1:
185                     if not res['base_pricelist_id']:
186                         price = 0.0
187                     else:
188                         price_tmp = self.price_get(cr, uid,
189                                 [res['base_pricelist_id']], prod_id,
190                                 qty)[res['base_pricelist_id']]
191                         ptype_src = self.browse(cr, uid,
192                                 res['base_pricelist_id']).currency_id.id
193                         price = currency_obj.compute(cr, uid, ptype_src,
194                                 res['currency_id'], price_tmp, round=False)
195                 elif res['base'] == -2:
196                     where = []
197                     if partner:
198                         where = [('name', '=', partner) ] 
199                     sinfo = supplierinfo_obj.search(cr, uid,
200                             [('product_id', '=', tmpl_id)] + where)
201                     price = 0.0
202                     if sinfo:
203                         cr.execute('SELECT * ' \
204                                 'FROM pricelist_partnerinfo ' \
205                                 'WHERE suppinfo_id IN (' + \
206                                     ','.join(map(str, sinfo)) + ') ' \
207                                     'AND min_quantity <= %s ' \
208                                 'ORDER BY min_quantity DESC LIMIT 1', (qty,))
209                         res2 = cr.dictfetchone()
210                         if res2:
211                             price = res2['price']
212                 else:
213                     price_type = price_type_obj.browse(cr, uid, int(res['base']))
214                     price = currency_obj.compute(cr, uid,
215                             price_type.currency_id.id, res['currency_id'],
216                             product_obj.price_get(cr, uid, [prod_id],
217                                 price_type.field)[prod_id], round=False)
218
219                 price_limit = price
220
221                 price = price * (1.0+(res['price_discount'] or 0.0))
222                 price = rounding(price, res['price_round'])
223                 price += (res['price_surcharge'] or 0.0)
224                 if res['price_min_margin']:
225                     price = max(price, price_limit+res['price_min_margin'])
226                 if res['price_max_margin']:
227                     price = min(price, price_limit+res['price_max_margin'])
228             else:
229                 # False means no valid line found ! But we may not raise an
230                 # exception here because it breaks the search
231                 price = False
232             result[id] = price            
233             if context and ('uom' in context):
234                 product = product_obj.browse(cr, uid, prod_id)
235                 uom = product.uos_id or product.uom_id
236                 result[id] = self.pool.get('product.uom')._compute_price(cr,
237                         uid, uom.id, result[id], context['uom'])                
238         return result
239
240 product_pricelist()
241
242
243 class product_pricelist_version(osv.osv):
244     _name = "product.pricelist.version"
245     _description = "Pricelist Version"
246     _columns = {
247         'pricelist_id': fields.many2one('product.pricelist', 'Price List',
248             required=True, select=True),
249         'name': fields.char('Name', size=64, required=True),
250         'active': fields.boolean('Active'),
251         'items_id': fields.one2many('product.pricelist.item',
252             'price_version_id', 'Price List Items', required=True),
253         'date_start': fields.date('Start Date', help="Starting date for validity of this pricelist version."),
254         'date_end': fields.date('End Date', help="Ending date for validity of this pricelist version."),
255     }
256     _defaults = {
257         'active': lambda *a: 1,
258     }
259
260     #
261     # TODO: improve this function ?
262     #
263     def _check_date(self, cursor, user, ids):
264         for pricelist_version in self.browse(cursor, user, ids):
265             if not pricelist_version.active:
266                 continue
267             cursor.execute('SELECT id ' \
268                     'FROM product_pricelist_version ' \
269                     'WHERE ((date_start <= %s AND %s <= date_end ' \
270                             'AND date_end IS NOT NULL) ' \
271                         'OR (date_end IS NULL AND date_start IS NOT NULL ' \
272                             'AND date_start <= %s) ' \
273                         'OR (date_start IS NULL AND date_end IS NOT NULL ' \
274                             'AND %s <= date_end) ' \
275                         'OR (date_start IS NULL AND date_end IS NULL) ' \
276                         'OR (%s = \'0000-01-01\' AND date_start IS NULL) ' \
277                         'OR (%s = \'0000-01-01\' AND date_end IS NULL) ' \
278                         'OR (%s = \'0000-01-01\' AND %s = \'0000-01-01\') ' \
279                         'OR (%s = \'0000-01-01\' AND date_start <= %s) ' \
280                         'OR (%s = \'0000-01-01\' AND %s <= date_end)) ' \
281                         'AND pricelist_id = %s ' \
282                         'AND active ' \
283                         'AND id <> %s', (pricelist_version.date_end or '0000-01-01',
284                             pricelist_version.date_start or '0000-01-01',
285                             pricelist_version.date_end or '0000-01-01',
286                             pricelist_version.date_start or '0000-01-01',
287                             pricelist_version.date_start or '0000-01-01',
288                             pricelist_version.date_end or '0000-01-01',
289                             pricelist_version.date_start or '0000-01-01',
290                             pricelist_version.date_end or '0000-01-01',
291                             pricelist_version.date_start or '0000-01-01',
292                             pricelist_version.date_end or '0000-01-01',
293                             pricelist_version.date_end or '0000-01-01',
294                             pricelist_version.date_start or '0000-01-01',
295                             pricelist_version.pricelist_id.id,
296                             pricelist_version.id))
297             if cursor.fetchall():
298                 return False
299         return True
300
301     _constraints = [
302         (_check_date, 'You can not have 2 pricelist version that overlaps!',
303             ['date_start', 'date_end'])
304     ]
305
306 product_pricelist_version()
307
308 class product_pricelist_item(osv.osv):
309     def _price_field_get(self, cr, uid, context={}):
310         pt = self.pool.get('product.price.type')
311         ids = pt.search(cr, uid, [], context=context)
312         result = []
313         for line in pt.browse(cr, uid, ids, context=context):
314             result.append((line.id, line.name))
315
316         result.append((-1, _('Other Pricelist')))
317         result.append((-2, _('Partner section of the product form')))
318         return result
319
320     _name = "product.pricelist.item"
321     _description = "Pricelist item"
322     _order = "sequence, min_quantity desc"
323     _defaults = {
324         'base': lambda *a: -1,
325         'min_quantity': lambda *a: 0,
326         'sequence': lambda *a: 5,
327         'price_discount': lambda *a: 0,
328     }
329     _columns = {
330         'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
331         'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True),
332         '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"),
333         '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"),
334         '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"),
335
336         'min_quantity': fields.integer('Min. Quantity', required=True, help="The rule only apply if the partner buys/sells more than this quantity."),
337         'sequence': fields.integer('Sequence', required=True),
338         'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="The mode of computation of the price for this rule."),
339         'base_pricelist_id': fields.many2one('product.pricelist', 'If Other Pricelist'),
340
341         'price_surcharge': fields.float('Price Surcharge',
342             digits=(16, int(config['price_accuracy']))),
343         'price_discount': fields.float('Price Discount', digits=(16,4)),
344         'price_round': fields.float('Price Rounding',
345             digits=(16, int(config['price_accuracy'])),
346             help="Sets the price so that it is a multiple of this value.\n" \
347               "Rounding is applied after the discount and before the surcharge.\n" \
348               "To have prices that ends by 9.99, set rounding 10, surcharge -0.01" \
349             ),
350         'price_min_margin': fields.float('Price Min. Margin',
351             digits=(16, int(config['price_accuracy']))),
352         'price_max_margin': fields.float('Price Max. Margin',
353             digits=(16, int(config['price_accuracy']))),
354     }
355     def product_id_change(self, cr, uid, ids, product_id, context={}):
356         if not product_id:
357             return {}
358         prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
359         if prod[0]['code']:
360             return {'value': {'name': prod[0]['code']}}
361         return {}
362 product_pricelist_item()
363
364
365
366 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
367