1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
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.
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.
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/>.
21 ##############################################################################
23 from osv import fields, osv
25 #from tools.misc import currency
26 from _common import rounding
28 from tools import config
29 from tools.misc import ustr
30 from tools.translate import _
32 class price_type(osv.osv):
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.
39 def _price_field_get(self, cr, uid, context={}):
40 mf = self.pool.get('ir.model.fields')
41 ids = mf.search(cr, uid, [('model','in', (('product.product'),('product.template'))), ('ttype','=','float')], context=context)
43 for field in mf.browse(cr, uid, ids, context=context):
44 res.append((field.name, field.field_description))
47 def _get_currency(self, cr, uid, ctx):
48 comp = self.pool.get('res.users').browse(cr,uid,uid).company_id
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
54 _name = "product.price.type"
55 _description = "Price type"
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."),
63 "active": lambda *args: True,
64 "currency_id": _get_currency
68 #----------------------------------------------------------
70 #----------------------------------------------------------
72 class product_pricelist_type(osv.osv):
73 _name = "product.pricelist.type"
74 _description = "Pricelist Type"
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."),
79 product_pricelist_type()
82 class product_pricelist(osv.osv):
83 def _pricelist_type_get(self, cr, uid, context={}):
84 pricelist_type_obj = self.pool.get('product.pricelist.type')
85 pricelist_type_ids = pricelist_type_obj.search(cr, uid, [], order='name')
86 pricelist_types = pricelist_type_obj.read(cr, uid, pricelist_type_ids, ['key','name'], context=context)
90 for type in pricelist_types:
91 res.append((type['key'],type['name']))
94 # cr.execute('select key,name from product_pricelist_type order by name')
95 # return cr.fetchall()
96 _name = "product.pricelist"
97 _description = "Pricelist"
99 'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
100 'active': fields.boolean('Active'),
101 'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
102 'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
103 'currency_id': fields.many2one('res.currency', 'Currency', required=True),
106 def name_get(self, cr, uid, ids, context={}):
110 for pl in self.browse(cr, uid, ids, context):
111 name = pl.name + ' ('+ pl.currency_id.name + ')'
112 result.append((pl.id,name))
116 def _get_currency(self, cr, uid, ctx):
117 comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
119 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
120 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
121 return comp.currency_id.id
124 'active': lambda *a: 1,
125 "currency_id": _get_currency
128 def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
131 'uom': Unit of Measure (int),
132 'partner': Partner ID (int),
133 'date': Date of the pricelist (%Y-%m-%d),
136 context = context or {}
137 currency_obj = self.pool.get('res.currency')
138 product_obj = self.pool.get('product.product')
139 supplierinfo_obj = self.pool.get('product.supplierinfo')
140 price_type_obj = self.pool.get('product.price.type')
142 if context and ('partner_id' in context):
143 partner = context['partner_id']
144 context['partner_id'] = partner
145 date = time.strftime('%Y-%m-%d')
146 if context and ('date' in context):
147 date = context['date']
150 cr.execute('SELECT * ' \
151 'FROM product_pricelist_version ' \
152 'WHERE pricelist_id = %s AND active=True ' \
153 'AND (date_start IS NULL OR date_start <= %s) ' \
154 'AND (date_end IS NULL OR date_end >= %s) ' \
155 'ORDER BY id LIMIT 1', (id, date, date))
156 plversion = cr.dictfetchone()
159 raise osv.except_osv(_('Warning !'),
160 _('No active version for the selected pricelist !\n' \
161 'Please create or activate one.'))
163 cr.execute('SELECT id, categ_id ' \
164 'FROM product_template ' \
165 'WHERE id = (SELECT product_tmpl_id ' \
166 'FROM product_product ' \
167 'WHERE id = %s)', (prod_id,))
168 tmpl_id, categ = cr.fetchone()
171 categ_ids.append(str(categ))
172 cr.execute('SELECT parent_id ' \
173 'FROM product_category ' \
174 'WHERE id = %s', (categ,))
175 categ = cr.fetchone()[0]
176 if str(categ) in categ_ids:
177 raise osv.except_osv(_('Warning !'),
178 _('Could not resolve product category, ' \
179 'you have defined cyclic categories ' \
182 categ_where = '(categ_id IN (' + ','.join(categ_ids) + '))'
184 categ_where = '(categ_id IS NULL)'
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, plversion['id'], qty))
198 res = cr.dictfetchone()
200 if res['base'] == -1:
201 if not res['base_pricelist_id']:
204 price_tmp = self.price_get(cr, uid,
205 [res['base_pricelist_id']], prod_id,
206 qty)[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:
214 where = [('name', '=', partner) ]
215 sinfo = supplierinfo_obj.search(cr, uid,
216 [('product_id', '=', tmpl_id)] + where)
219 cr.execute('SELECT * ' \
220 'FROM pricelist_partnerinfo ' \
221 'WHERE suppinfo_id IN (' + \
222 ','.join(map(str, sinfo)) + ') ' \
223 'AND min_quantity <= %s ' \
224 'ORDER BY min_quantity DESC LIMIT 1', (qty,))
225 res2 = cr.dictfetchone()
227 price = res2['price']
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)
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'])
245 # False means no valid line found ! But we may not raise an
246 # exception here because it breaks the search
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'])
259 class product_pricelist_version(osv.osv):
260 _name = "product.pricelist.version"
261 _description = "Pricelist Version"
263 'pricelist_id': fields.many2one('product.pricelist', 'Price List',
264 required=True, select=True),
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."),
276 'active': lambda *a: 1,
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)
285 def _check_date(self, cursor, user, ids):
286 for pricelist_version in self.browse(cursor, user, ids):
287 if not pricelist_version.active:
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,))
295 cursor.execute('SELECT id ' \
296 'FROM product_pricelist_version ' \
297 'WHERE '+' and '.join(where) + (where and ' and ' or '')+
298 'pricelist_id = %s ' \
301 pricelist_version.pricelist_id.id,
302 pricelist_version.id))
303 if cursor.fetchall():
308 (_check_date, 'You cannot have 2 pricelist versions that overlap!',
309 ['date_start', 'date_end'])
312 product_pricelist_version()
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)
319 for line in pt.browse(cr, uid, ids, context=context):
320 result.append((line.id, line.name))
322 result.append((-1, _('Other Pricelist')))
323 result.append((-2, _('Partner section of the product form')))
326 _name = "product.pricelist.item"
327 _description = "Pricelist item"
328 _order = "sequence, min_quantity desc"
330 'base': lambda *a: -1,
331 'min_quantity': lambda *a: 0,
332 'sequence': lambda *a: 5,
333 'price_discount': lambda *a: 0,
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:
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),
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"),
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'),
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" \
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']))),
373 (_check_recursion, _('Error ! You cannot assign the Main Pricelist as Other Pricelist in PriceList Item!'), ['base_pricelist_id'])
376 def product_id_change(self, cr, uid, ids, product_id, context={}):
379 prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
381 return {'value': {'name': prod[0]['code']}}
383 product_pricelist_item()
387 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: