[FIX] res_lang : if value of thousands_sep is not present in language,method will...
[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 tools.misc import currency
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 import decimal_precision as dp
31
32
33 class price_type(osv.osv):
34     """
35         The price type is used to points which field in the product form
36         is a price and in which currency is this price expressed.
37         When a field is a price, you can use it in pricelists to base
38         sale and purchase prices based on some fields of the product.
39     """
40     def _price_field_get(self, cr, uid, context={}):
41         mf = self.pool.get('ir.model.fields')
42         ids = mf.search(cr, uid, [('model','in', (('product.product'),('product.template'))), ('ttype','=','float')], context=context)
43         res = []
44         for field in mf.browse(cr, uid, ids, context=context):
45             res.append((field.name, field.field_description))
46         return res
47
48     def _get_currency(self, cr, uid, ctx):
49         comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
50         if not comp:
51             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
52             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
53         return comp.currency_id.id
54
55     _name = "product.price.type"
56     _description = "Price type"
57     _columns = {
58         "name" : fields.char("Price Name", size=32, required=True, translate=True, help="Name of this kind of price."),
59         "active" : fields.boolean("Active"),
60         "field" : fields.selection(_price_field_get, "Product Field", size=32, required=True, help="Associated field in the product form."),
61         "currency_id" : fields.many2one('res.currency', "Currency", required=True, help="The currency the field is expressed in."),
62     }
63     _defaults = {
64         "active": lambda *args: True,
65         "currency_id": _get_currency
66     }
67     
68 price_type()
69
70 #----------------------------------------------------------
71 # Price lists
72 #----------------------------------------------------------
73
74 class product_pricelist_type(osv.osv):
75     _name = "product.pricelist.type"
76     _description = "Pricelist Type"
77     _columns = {
78         'name': fields.char('Name',size=64, required=True, translate=True),
79         'key': fields.char('Key', size=64, required=True, help="Used in the code to select specific prices based on the context. Keep unchanged."),
80     }
81 product_pricelist_type()
82
83
84 class product_pricelist(osv.osv):
85     def _pricelist_type_get(self, cr, uid, context={}):
86         pricelist_type_obj = self.pool.get('product.pricelist.type')
87         pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
88         pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
89
90         res = []
91
92         for type in pricelist_types:
93             res.append((type['key'],type['name']))
94
95         return res
96 #        cr.execute('select key,name from product_pricelist_type order by name')
97 #        return cr.fetchall()
98     _name = "product.pricelist"
99     _description = "Pricelist"
100     _columns = {
101         'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
102         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the pricelist without removing it."),
103         'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
104         'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
105         'currency_id': fields.many2one('res.currency', 'Currency', required=True),
106         'company_id': fields.many2one('res.company', 'Company'),
107     }
108
109     def name_get(self, cr, uid, ids, context={}):
110         result= []
111         if not all(ids):
112             return result
113         for pl in self.browse(cr, uid, ids, context):
114             name = pl.name + ' ('+ pl.currency_id.name + ')'
115             result.append((pl.id,name))
116         return result
117
118
119     def _get_currency(self, cr, uid, ctx):
120         comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
121         if not comp:
122             comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
123             comp = self.pool.get('res.company').browse(cr, uid, comp_id)
124         return comp.currency_id.id
125
126     _defaults = {
127         'active': lambda *a: 1,
128         "currency_id": _get_currency
129     }
130
131     def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
132         '''
133         context = {
134             'uom': Unit of Measure (int),
135             'partner': Partner ID (int),
136             'date': Date of the pricelist (%Y-%m-%d),
137         }
138         '''
139         context = context or {}
140         currency_obj = self.pool.get('res.currency')
141         product_obj = self.pool.get('product.product')
142         supplierinfo_obj = self.pool.get('product.supplierinfo')
143         price_type_obj = self.pool.get('product.price.type')
144
145         if context and ('partner_id' in context):
146             partner = context['partner_id']
147         context['partner_id'] = partner
148         date = time.strftime('%Y-%m-%d')
149         if context and ('date' in context):
150             date = context['date']
151         result = {}
152         result['item_id'] = {}
153         for id in ids:
154             cr.execute('SELECT * ' \
155                     'FROM product_pricelist_version ' \
156                     'WHERE pricelist_id = %s AND active=True ' \
157                         'AND (date_start IS NULL OR date_start <= %s) ' \
158                         'AND (date_end IS NULL OR date_end >= %s) ' \
159                     'ORDER BY id LIMIT 1', (id, date, date))
160             plversion = cr.dictfetchone()
161
162             if not plversion:
163                 raise osv.except_osv(_('Warning !'),
164                         _('No active version for the selected pricelist !\n' \
165                                 'Please create or activate one.'))
166
167             cr.execute('SELECT id, categ_id ' \
168                     'FROM product_template ' \
169                     'WHERE id = (SELECT product_tmpl_id ' \
170                         'FROM product_product ' \
171                         'WHERE id = %s)', (prod_id,))
172             tmpl_id, categ = cr.fetchone()
173             categ_ids = []
174             while categ:
175                 categ_ids.append(str(categ))
176                 cr.execute('SELECT parent_id ' \
177                         'FROM product_category ' \
178                         'WHERE id = %s', (categ,))
179                 categ = cr.fetchone()[0]
180                 if str(categ) in categ_ids:
181                     raise osv.except_osv(_('Warning !'),
182                             _('Could not resolve product category, ' \
183                                     'you have defined cyclic categories ' \
184                                     'of products!'))
185             if categ_ids:
186                 categ_where = '(categ_id IN (' + ','.join(categ_ids) + '))'
187             else:
188                 categ_where = '(categ_id IS NULL)'
189
190             cr.execute(
191                 'SELECT i.*, pl.currency_id '
192                 'FROM product_pricelist_item AS i, '
193                     'product_pricelist_version AS v, product_pricelist AS pl '
194                 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
195                     'AND (product_id IS NULL OR product_id = %s) '
196                     'AND (' + categ_where + ' OR (categ_id IS NULL)) '
197                     'AND price_version_id = %s '
198                     'AND (min_quantity IS NULL OR min_quantity <= %s) '
199                     'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
200                 'ORDER BY sequence',
201                 (tmpl_id, prod_id, plversion['id'], qty))
202             res1 = cr.dictfetchall()
203             
204             for res in res1:
205                 item_id = 0
206                 if res:
207                     if res['base'] == -1:
208                         if not res['base_pricelist_id']:
209                             price = 0.0
210                         else:
211                             price_tmp = self.price_get(cr, uid,
212                                     [res['base_pricelist_id']], prod_id,
213                                     qty)[res['base_pricelist_id']]
214                             ptype_src = self.browse(cr, uid,
215                                     res['base_pricelist_id']).currency_id.id
216                             price = currency_obj.compute(cr, uid, ptype_src,
217                                     res['currency_id'], price_tmp, round=False)
218                             break    
219                     elif res['base'] == -2:
220                         where = []
221                         if partner:
222                             where = [('name', '=', partner) ] 
223                         sinfo = supplierinfo_obj.search(cr, uid,
224                                 [('product_id', '=', tmpl_id)] + where)
225                         price = 0.0
226                         if sinfo:
227                             cr.execute('SELECT * ' \
228                                     'FROM pricelist_partnerinfo ' \
229                                     'WHERE suppinfo_id IN (' + \
230                                         ','.join(map(str, sinfo)) + ') ' \
231                                         'AND min_quantity <= %s ' \
232                                     'ORDER BY min_quantity DESC LIMIT 1', (qty,))
233                             res2 = cr.dictfetchone()
234                             if res2:
235                                 price = res2['price']
236                                 break
237                     else:
238                         price_type = price_type_obj.browse(cr, uid, int(res['base']))
239                         price = currency_obj.compute(cr, uid,
240                                 price_type.currency_id.id, res['currency_id'],
241                                 product_obj.price_get(cr, uid, [prod_id],
242                                     price_type.field)[prod_id], round=False)
243
244                     if price:
245                         price_limit = price
246         
247                         price = price * (1.0+(res['price_discount'] or 0.0))
248                         price = rounding(price, res['price_round'])
249                         price += (res['price_surcharge'] or 0.0)
250                         if res['price_min_margin']:
251                             price = max(price, price_limit+res['price_min_margin'])
252                         if res['price_max_margin']:
253                             price = min(price, price_limit+res['price_max_margin'])
254                         item_id = res['id']
255                         break    
256
257                 else:
258                     # False means no valid line found ! But we may not raise an
259                     # exception here because it breaks the search
260                     price = False
261             result[id] = price
262             result['item_id'] = {id: item_id}    
263             if context and ('uom' in context):
264                 product = product_obj.browse(cr, uid, prod_id)
265                 uom = product.uos_id or product.uom_id
266                 result[id] = self.pool.get('product.uom')._compute_price(cr,
267                         uid, uom.id, result[id], context['uom'])
268         return result
269
270 product_pricelist()
271
272
273 class product_pricelist_version(osv.osv):
274     _name = "product.pricelist.version"
275     _description = "Pricelist Version"
276     _columns = {
277         'pricelist_id': fields.many2one('product.pricelist', 'Price List',
278             required=True, select=True, ondelete='cascade'),
279         'name': fields.char('Name', size=64, required=True, translate=True),
280         'active': fields.boolean('Active',
281             help="When a version is duplicated it is set to non active, so that the " \
282             "dates do not overlaps with original version. You should change the dates " \
283             "and reactivate the pricelist"),
284         'items_id': fields.one2many('product.pricelist.item',
285             'price_version_id', 'Price List Items', required=True),
286         'date_start': fields.date('Start Date', help="Starting date for this pricelist version to be valid."),
287         'date_end': fields.date('End Date', help="Ending date for this pricelist version to be valid."),
288         'company_id': fields.related('pricelist_id','company_id',type='many2one',
289             readonly=True, relation='res.company', string='Company', store=True)
290     }
291     _defaults = {
292         'active': lambda *a: 1,
293     }
294
295     # We desactivate duplicated pricelists, so that dates do not overlap
296     def copy(self, cr, uid, id, default=None,context={}):
297         if not default: default= {}
298         default['active'] = False
299         return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
300
301     def _check_date(self, cursor, user, ids):
302         for pricelist_version in self.browse(cursor, user, ids):
303             if not pricelist_version.active:
304                 continue
305             where = []
306             if pricelist_version.date_start:
307                 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
308             if pricelist_version.date_end:
309                 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
310
311             cursor.execute('SELECT id ' \
312                     'FROM product_pricelist_version ' \
313                     'WHERE '+' and '.join(where) + (where and ' and ' or '')+
314                         'pricelist_id = %s ' \
315                         'AND active ' \
316                         'AND id <> %s', (
317                             pricelist_version.pricelist_id.id,
318                             pricelist_version.id))
319             if cursor.fetchall():
320                 return False
321         return True
322
323     _constraints = [
324         (_check_date, 'You cannot have 2 pricelist versions that overlap!',
325             ['date_start', 'date_end'])
326     ]
327
328 product_pricelist_version()
329
330 class product_pricelist_item(osv.osv):
331     def _price_field_get(self, cr, uid, context={}):
332         pt = self.pool.get('product.price.type')
333         ids = pt.search(cr, uid, [], context=context)
334         result = []
335         for line in pt.browse(cr, uid, ids, context=context):
336             result.append((line.id, line.name))
337
338         result.append((-1, _('Other Pricelist')))
339         result.append((-2, _('Partner section of the product form')))
340         return result
341
342     _name = "product.pricelist.item"
343     _description = "Pricelist item"
344     _order = "sequence, min_quantity desc"
345     _defaults = {
346         'base': lambda *a: -1,
347         'min_quantity': lambda *a: 0,
348         'sequence': lambda *a: 5,
349         'price_discount': lambda *a: 0,
350     }
351
352     def _check_recursion(self, cr, uid, ids):
353         for obj_list in self.browse(cr, uid, ids):
354             if obj_list.base == -1:
355                 main_pricelist = obj_list.price_version_id.pricelist_id.id
356                 other_pricelist = obj_list.base_pricelist_id.id
357                 if main_pricelist == other_pricelist:
358                     return False
359         return True
360
361     _columns = {
362         'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
363         'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
364         '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"),
365         '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"),
366         '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"),
367
368         'min_quantity': fields.integer('Min. Quantity', required=True, help="The rule only applies if the partner buys/sells more than this quantity."),
369         'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when displaying a list of pricelist items."),
370         'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="The mode for computing the price for this rule."),
371         'base_pricelist_id': fields.many2one('product.pricelist', 'If Other Pricelist'),
372
373         'price_surcharge': fields.float('Price Surcharge',
374             digits_compute= dp.get_precision('Sale Price')),
375         'price_discount': fields.float('Price Discount', digits=(16,4)),
376         'price_round': fields.float('Price Rounding',
377             digits_compute= dp.get_precision('Sale Price'),
378             help="Sets the price so that it is a multiple of this value.\n" \
379               "Rounding is applied after the discount and before the surcharge.\n" \
380               "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
381             ),
382         'price_min_margin': fields.float('Min. Price Margin',
383             digits_compute= dp.get_precision('Sale Price')),
384         'price_max_margin': fields.float('Max. Price Margin',
385             digits_compute= dp.get_precision('Sale Price')),
386         'company_id': fields.related('price_version_id','company_id',type='many2one',
387             readonly=True, relation='res.company', string='Company', store=True)
388     }
389
390     _constraints = [
391         (_check_recursion, _('Error ! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!'), ['base_pricelist_id'])
392     ]
393
394     def product_id_change(self, cr, uid, ids, product_id, context={}):
395         if not product_id:
396             return {}
397         prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
398         if prod[0]['code']:
399             return {'value': {'name': prod[0]['code']}}
400         return {}
401 product_pricelist_item()
402
403
404
405 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
406