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 cr.execute('select key,name from product_pricelist_type order by name')
86 _name = "product.pricelist"
87 _description = "Pricelist"
89 'name': fields.char('Pricelist Name',size=64, required=True, translate=True),
90 'active': fields.boolean('Active'),
91 'type': fields.selection(_pricelist_type_get, 'Pricelist Type', required=True),
92 'version_id': fields.one2many('product.pricelist.version', 'pricelist_id', 'Pricelist Versions'),
93 'currency_id': fields.many2one('res.currency', 'Currency', required=True),
96 def name_get(self, cr, uid, ids, context={}):
100 for pl in self.browse(cr, uid, ids, context):
101 name = pl.name + ' ('+ pl.currency_id.name + ')'
102 result.append((pl.id,name))
106 def _get_currency(self, cr, uid, ctx):
107 comp = self.pool.get('res.users').browse(cr, uid, uid).company_id
109 comp_id = self.pool.get('res.company').search(cr, uid, [])[0]
110 comp = self.pool.get('res.company').browse(cr, uid, comp_id)
111 return comp.currency_id.id
114 'active': lambda *a: 1,
115 "currency_id": _get_currency
118 def price_get(self, cr, uid, ids, prod_id, qty, partner=None, context=None):
121 'uom': Unit of Measure (int),
122 'partner': Partner ID (int),
123 'date': Date of the pricelist (%Y-%m-%d),
126 context = context or {}
127 currency_obj = self.pool.get('res.currency')
128 product_obj = self.pool.get('product.product')
129 supplierinfo_obj = self.pool.get('product.supplierinfo')
130 price_type_obj = self.pool.get('product.price.type')
132 if context and ('partner_id' in context):
133 partner = context['partner_id']
134 context['partner_id'] = partner
135 date = time.strftime('%Y-%m-%d')
136 if context and ('date' in context):
137 date = context['date']
140 cr.execute('SELECT * ' \
141 'FROM product_pricelist_version ' \
142 'WHERE pricelist_id = %s AND active=True ' \
143 'AND (date_start IS NULL OR date_start <= %s) ' \
144 'AND (date_end IS NULL OR date_end >= %s) ' \
145 'ORDER BY id LIMIT 1', (id, date, date))
146 plversion = cr.dictfetchone()
149 raise osv.except_osv(_('Warning !'),
150 _('No active version for the selected pricelist !\n' \
151 'Please create or activate one.'))
153 cr.execute('SELECT id, categ_id ' \
154 'FROM product_template ' \
155 'WHERE id = (SELECT product_tmpl_id ' \
156 'FROM product_product ' \
157 'WHERE id = %s)', (prod_id,))
158 tmpl_id, categ = cr.fetchone()
161 categ_ids.append(str(categ))
162 cr.execute('SELECT parent_id ' \
163 'FROM product_category ' \
164 'WHERE id = %s', (categ,))
165 categ = cr.fetchone()[0]
166 if str(categ) in categ_ids:
167 raise osv.except_osv(_('Warning !'),
168 _('Could not resolve product category, ' \
169 'you have defined cyclic categories ' \
172 categ_where = '(categ_id IN (' + ','.join(categ_ids) + '))'
174 categ_where = '(categ_id IS NULL)'
177 'SELECT i.*, pl.currency_id '
178 'FROM product_pricelist_item AS i, '
179 'product_pricelist_version AS v, product_pricelist AS pl '
180 'WHERE (product_tmpl_id IS NULL OR product_tmpl_id = %s) '
181 'AND (product_id IS NULL OR product_id = %s) '
182 'AND (' + categ_where + ' OR (categ_id IS NULL)) '
183 'AND price_version_id = %s '
184 'AND (min_quantity IS NULL OR min_quantity <= %s) '
185 'AND i.price_version_id = v.id AND v.pricelist_id = pl.id '
186 'ORDER BY sequence LIMIT 1',
187 (tmpl_id, prod_id, plversion['id'], qty))
188 res = cr.dictfetchone()
190 if res['base'] == -1:
191 if not res['base_pricelist_id']:
194 price_tmp = self.price_get(cr, uid,
195 [res['base_pricelist_id']], prod_id,
196 qty)[res['base_pricelist_id']]
197 ptype_src = self.browse(cr, uid,
198 res['base_pricelist_id']).currency_id.id
199 price = currency_obj.compute(cr, uid, ptype_src,
200 res['currency_id'], price_tmp, round=False)
201 elif res['base'] == -2:
204 where = [('name', '=', partner) ]
205 sinfo = supplierinfo_obj.search(cr, uid,
206 [('product_id', '=', tmpl_id)] + where)
209 cr.execute('SELECT * ' \
210 'FROM pricelist_partnerinfo ' \
211 'WHERE suppinfo_id IN (' + \
212 ','.join(map(str, sinfo)) + ') ' \
213 'AND min_quantity <= %s ' \
214 'ORDER BY min_quantity DESC LIMIT 1', (qty,))
215 res2 = cr.dictfetchone()
217 price = res2['price']
219 price_type = price_type_obj.browse(cr, uid, int(res['base']))
220 price = currency_obj.compute(cr, uid,
221 price_type.currency_id.id, res['currency_id'],
222 product_obj.price_get(cr, uid, [prod_id],
223 price_type.field)[prod_id], round=False)
227 price = price * (1.0+(res['price_discount'] or 0.0))
228 price = rounding(price, res['price_round'])
229 price += (res['price_surcharge'] or 0.0)
230 if res['price_min_margin']:
231 price = max(price, price_limit+res['price_min_margin'])
232 if res['price_max_margin']:
233 price = min(price, price_limit+res['price_max_margin'])
235 # False means no valid line found ! But we may not raise an
236 # exception here because it breaks the search
239 if context and ('uom' in context):
240 product = product_obj.browse(cr, uid, prod_id)
241 uom = product.uos_id or product.uom_id
242 result[id] = self.pool.get('product.uom')._compute_price(cr,
243 uid, uom.id, result[id], context['uom'])
249 class product_pricelist_version(osv.osv):
250 _name = "product.pricelist.version"
251 _description = "Pricelist Version"
253 'pricelist_id': fields.many2one('product.pricelist', 'Price List',
254 required=True, select=True),
255 'name': fields.char('Name', size=64, required=True, translate=True),
256 'active': fields.boolean('Active',
257 help="When a version is duplicated it is set to non active, so that the " \
258 "dates do not overlaps with original version. You should change the dates " \
259 "and reactivate the pricelist"),
260 'items_id': fields.one2many('product.pricelist.item',
261 'price_version_id', 'Price List Items', required=True),
262 'date_start': fields.date('Start Date', help="Starting date for this pricelist version to be valid."),
263 'date_end': fields.date('End Date', help="Ending date for this pricelist version to be valid."),
266 'active': lambda *a: 1,
269 # We desactivate duplicated pricelists, so that dates do not overlap
270 def copy(self, cr, uid, id, default=None,context={}):
271 if not default: default= {}
272 default['active'] = False
273 return super(product_pricelist_version, self).copy(cr, uid, id, default, context)
275 def _check_date(self, cursor, user, ids):
276 for pricelist_version in self.browse(cursor, user, ids):
277 if not pricelist_version.active:
280 if pricelist_version.date_start:
281 where.append("((date_end>='%s') or (date_end is null))" % (pricelist_version.date_start,))
282 if pricelist_version.date_end:
283 where.append("((date_start<='%s') or (date_start is null))" % (pricelist_version.date_end,))
285 cursor.execute('SELECT id ' \
286 'FROM product_pricelist_version ' \
287 'WHERE '+' and '.join(where) + (where and ' and ' or '')+
288 'pricelist_id = %s ' \
291 pricelist_version.pricelist_id.id,
292 pricelist_version.id))
293 if cursor.fetchall():
298 (_check_date, 'You cannot have 2 pricelist versions that overlap!',
299 ['date_start', 'date_end'])
302 product_pricelist_version()
304 class product_pricelist_item(osv.osv):
305 def _price_field_get(self, cr, uid, context={}):
306 pt = self.pool.get('product.price.type')
307 ids = pt.search(cr, uid, [], context=context)
309 for line in pt.browse(cr, uid, ids, context=context):
310 result.append((line.id, line.name))
312 result.append((-1, _('Other Pricelist')))
313 result.append((-2, _('Partner section of the product form')))
316 _name = "product.pricelist.item"
317 _description = "Pricelist item"
318 _order = "sequence, min_quantity desc"
320 'base': lambda *a: -1,
321 'min_quantity': lambda *a: 0,
322 'sequence': lambda *a: 5,
323 'price_discount': lambda *a: 0,
326 'name': fields.char('Rule Name', size=64, help="Explicit rule name for this pricelist line."),
327 'price_version_id': fields.many2one('product.pricelist.version', 'Price List Version', required=True, select=True),
328 '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"),
329 '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"),
330 '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"),
332 'min_quantity': fields.integer('Min. Quantity', required=True, help="The rule only applies if the partner buys/sells more than this quantity."),
333 'sequence': fields.integer('Sequence', required=True),
334 'base': fields.selection(_price_field_get, 'Based on', required=True, size=-1, help="The mode for computing the price for this rule."),
335 'base_pricelist_id': fields.many2one('product.pricelist', 'If Other Pricelist'),
337 'price_surcharge': fields.float('Price Surcharge',
338 digits=(16, int(config['price_accuracy']))),
339 'price_discount': fields.float('Price Discount', digits=(16,4)),
340 'price_round': fields.float('Price Rounding',
341 digits=(16, int(config['price_accuracy'])),
342 help="Sets the price so that it is a multiple of this value.\n" \
343 "Rounding is applied after the discount and before the surcharge.\n" \
344 "To have prices that end in 9.99, set rounding 10, surcharge -0.01" \
346 'price_min_margin': fields.float('Min. Price Margin',
347 digits=(16, int(config['price_accuracy']))),
348 'price_max_margin': fields.float('Max. Price Margin',
349 digits=(16, int(config['price_accuracy']))),
351 def product_id_change(self, cr, uid, ids, product_id, context={}):
354 prod = self.pool.get('product.product').read(cr, uid, [product_id], ['code','name'])
356 return {'value': {'name': prod[0]['code']}}
358 product_pricelist_item()
362 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: