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