1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from osv import fields, osv
24 #from tools.misc import currency
25 from _common import rounding
27 from tools import config
28 from tools.misc import ustr
29 from tools.translate import _
30 import decimal_precision as dp
33 class price_type(osv.osv):
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.
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)
44 for field in mf.browse(cr, uid, ids, context=context):
45 res.append((field.name, field.field_description))
48 def _get_currency(self, cr, uid, ctx):
49 comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
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
55 _name = "product.price.type"
56 _description = "Price Type"
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."),
64 "active": lambda *args: True,
65 "currency_id": _get_currency
70 #----------------------------------------------------------
72 #----------------------------------------------------------
74 class product_pricelist_type(osv.osv):
75 _name = "product.pricelist.type"
76 _description = "Pricelist Type"
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."),
81 product_pricelist_type()
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)
92 for type in pricelist_types:
93 res.append((type['key'],type['name']))
96 # cr.execute('select key,name from product_pricelist_type order by name')
97 # return cr.fetchall()
98 _name = "product.pricelist"
99 _description = "Pricelist"
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'),
109 def name_get(self, cr, uid, ids, context={}):
113 for pl in self.browse(cr, uid, ids, context):
114 name = pl.name + ' ('+ pl.currency_id.name + ')'
115 result.append((pl.id,name))
119 def _get_currency(self, cr, uid, ctx):
120 comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
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
127 'active': lambda *a: 1,
128 "currency_id": _get_currency
131 def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
134 'uom': Unit of Measure (int),
135 'partner': Partner ID (int),
136 'date': Date of the pricelist (%Y-%m-%d),
141 context = context or {}
142 currency_obj = self.pool.get('res.currency')
143 product_obj = self.pool.get('product.product')
144 supplierinfo_obj = self.pool.get('product.supplierinfo')
145 price_type_obj = self.pool.get('product.price.type')
147 if context and ('partner_id' in context):
148 partner = context['partner_id']
149 context['partner_id'] = partner
150 date = time.strftime('%Y-%m-%d')
151 if context and ('date' in context):
152 date = context['date']
154 result['item_id'] = {}
156 cr.execute('SELECT * ' \
157 'FROM product_pricelist_version ' \
158 'WHERE pricelist_id = %s AND active=True ' \
159 'AND (date_start IS NULL OR date_start <= %s) ' \
160 'AND (date_end IS NULL OR date_end >= %s) ' \
161 'ORDER BY id LIMIT 1', (id, date, date))
162 plversion = cr.dictfetchone()
165 raise osv.except_osv(_('Warning !'),
166 _('No active version for the selected pricelist !\n' \
167 'Please create or activate one.'))
169 cr.execute('SELECT id, categ_id ' \
170 'FROM product_template ' \
171 'WHERE id = (SELECT product_tmpl_id ' \
172 'FROM product_product ' \
173 'WHERE id = %s)', (prod_id,))
174 tmpl_id, categ = cr.fetchone()
177 categ_ids.append(str(categ))
178 cr.execute('SELECT parent_id ' \
179 'FROM product_category ' \
180 'WHERE id = %s', (categ,))
181 categ = cr.fetchone()[0]
182 if str(categ) in categ_ids:
183 raise osv.except_osv(_('Warning !'),
184 _('Could not resolve product category, ' \
185 'you have defined cyclic categories ' \
188 categ_where = '(categ_id IN (' + ','.join(categ_ids) + '))'
190 categ_where = '(categ_id IS NULL)'
193 'SELECT i.*, pl.currency_id '
194 'FROM product_pricelist_item AS i, '
195 'product_pricelist_version AS v, product_pricelist AS pl '
196 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
197 'AND (product_id IS NULL OR product_id = %s) '
198 'AND (' + categ_where + ' OR (categ_id IS NULL)) '
199 'AND price_version_id = %s '
200 'AND (min_quantity IS NULL OR min_quantity <= %s) '
201 'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
203 (tmpl_id, prod_id, plversion['id'], qty))
204 res1 = cr.dictfetchall()
209 if res['base'] == -1:
210 if not res['base_pricelist_id']:
213 price_tmp = self.price_get(cr, uid,
214 [res['base_pricelist_id']], prod_id,
215 qty)[res['base_pricelist_id']]
216 ptype_src = self.browse(cr, uid,
217 res['base_pricelist_id']).currency_id.id
218 price = currency_obj.compute(cr, uid, ptype_src,
219 res['currency_id'], price_tmp, round=False)
221 elif res['base'] == -2:
224 where = [('name', '=', partner) ]
225 sinfo = supplierinfo_obj.search(cr, uid,
226 [('product_id', '=', tmpl_id)] + where)
229 cr.execute('SELECT * ' \
230 'FROM pricelist_partnerinfo ' \
231 'WHERE suppinfo_id IN %s' \
232 'AND min_quantity <= %s ' \
233 'ORDER BY min_quantity DESC LIMIT 1', (tuple(sinfo),qty,))
234 res2 = cr.dictfetchone()
236 price = res2['price']
239 price_type = price_type_obj.browse(cr, uid, int(res['base']))
240 price = currency_obj.compute(cr, uid,
241 price_type.currency_id.id, res['currency_id'],
242 product_obj.price_get(cr, uid, [prod_id],
243 price_type.field)[prod_id], round=False, context=context)
248 price = price * (1.0+(res['price_discount'] or 0.0))
249 price = rounding(price, res['price_round'])
250 price += (res['price_surcharge'] or 0.0)
251 if res['price_min_margin']:
252 price = max(price, price_limit+res['price_min_margin'])
253 if res['price_max_margin']:
254 price = min(price, price_limit+res['price_max_margin'])
259 # False means no valid line found ! But we may not raise an
260 # exception here because it breaks the search
263 result['item_id'] = {id: item_id}
264 if context and ('uom' in context):
265 product = product_obj.browse(cr, uid, prod_id)
266 uom = product.uos_id or product.uom_id
267 result[id] = self.pool.get('product.uom')._compute_price(cr,
268 uid, uom.id, result[id], context['uom'])
274 class product_pricelist_version(osv.osv):
275 _name = "product.pricelist.version"
276 _description = "Pricelist Version"
278 'pricelist_id': fields.many2one('product.pricelist', 'Price List',
279 required=True, select=True, ondelete='cascade'),
280 'name': fields.char('Name', size=64, required=True, translate=True),
281 'active': fields.boolean('Active',
282 help="When a version is duplicated it is set to non active, so that the " \
283 "dates do not overlaps with original version. You should change the dates " \
284 "and reactivate the pricelist"),
285 'items_id': fields.one2many('product.pricelist.item',
286 'price_version_id', 'Price List Items', required=True),
287 'date_start': fields.date('Start Date', help="Starting date for this pricelist version to be valid."),
288 'date_end': fields.date('End Date', help="Ending date for this pricelist version to be valid."),
289 'company_id': fields.related('pricelist_id','company_id',type='many2one',
290 readonly=True, relation='res.company', string='Company', store=True)
293 'active': lambda *a: 1,
296 # We desactivate duplicated pricelists, so that dates do not overlap
297 def copy(self, cr, uid, id, default=None,context={}):
298 if not default: default= {}
299 default['active'] = False
300 return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
302 def _check_date(self, cursor, user, ids):
303 for pricelist_version in self.browse(cursor, user, ids):
304 if not pricelist_version.active:
307 if pricelist_version.date_start:
308 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
309 if pricelist_version.date_end:
310 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
312 cursor.execute('SELECT id ' \
313 'FROM product_pricelist_version ' \
314 'WHERE '+' and '.join(where) + (where and ' and ' or '')+
315 'pricelist_id = %s ' \
318 pricelist_version.pricelist_id.id,
319 pricelist_version.id))
320 if cursor.fetchall():
325 (_check_date, 'You cannot have 2 pricelist versions that overlap!',
326 ['date_start', 'date_end'])
329 product_pricelist_version()
331 class product_pricelist_item(osv.osv):
332 def _price_field_get(self, cr, uid, context={}):
333 pt = self.pool.get('product.price.type')
334 ids = pt.search(cr, uid, [], context=context)
336 for line in pt.browse(cr, uid, ids, context=context):
337 result.append((line.id, line.name))
339 result.append((-1, _('Other Pricelist')))
340 result.append((-2, _('Partner section of the product form')))
343 _name = "product.pricelist.item"
344 _description = "Pricelist item"
345 _order = "sequence, min_quantity desc"
347 'base': lambda *a: -1,
348 'min_quantity': lambda *a: 0,
349 'sequence': lambda *a: 5,
350 'price_discount': lambda *a: 0,
353 def _check_recursion(self, cr, uid, ids):
354 for obj_list in self.browse(cr, uid, ids):
355 if obj_list.base == -1:
356 main_pricelist = obj_list.price_version_id.pricelist_id.id
357 other_pricelist = obj_list.base_pricelist_id.id
358 if main_pricelist == other_pricelist:
363 'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
364 'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True, ondelete='cascade'),
365 '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"),
366 '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"),
367 '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"),
369 'min_quantity': fields.integer('Min. Quantity', required=True, help="The rule only applies if the partner buys/sells more than this quantity."),
370 'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when displaying a list of pricelist items."),
371 'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="The mode for computing the price for this rule."),
372 'base_pricelist_id': fields.many2one('product.pricelist', 'If Other Pricelist'),
374 'price_surcharge': fields.float('Price Surcharge',
375 digits_compute= dp.get_precision('Sale Price')),
376 'price_discount': fields.float('Price Discount', digits=(16,4)),
377 'price_round': fields.float('Price Rounding',
378 digits_compute= dp.get_precision('Sale Price'),
379 help="Sets the price so that it is a multiple of this value.\n" \
380 "Rounding is applied after the discount and before the surcharge.\n" \
381 "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
383 'price_min_margin': fields.float('Min. Price Margin',
384 digits_compute= dp.get_precision('Sale Price')),
385 'price_max_margin': fields.float('Max. Price Margin',
386 digits_compute= dp.get_precision('Sale Price')),
387 'company_id': fields.related('price_version_id','company_id',type='many2one',
388 readonly=True, relation='res.company', string='Company', store=True)
392 (_check_recursion, _('Error ! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!'), ['base_pricelist_id'])
395 def product_id_change(self, cr, uid, ids, product_id, context={}):
398 prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
400 return {'value': {'name': prod[0]['code']}}
402 product_pricelist_item()
406 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: