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 ##############################################################################
24 from openerp.osv import fields,osv
25 from openerp.tools.translate import _
26 import openerp.addons.decimal_precision as dp
28 _logger = logging.getLogger(__name__)
30 class delivery_carrier(osv.osv):
31 _name = "delivery.carrier"
32 _description = "Carrier"
34 def name_get(self, cr, uid, ids, context=None):
39 order_id = context.get('order_id',False)
41 res = super(delivery_carrier, self).name_get(cr, uid, ids, context=context)
43 order = self.pool.get('sale.order').browse(cr, uid, order_id, context=context)
44 currency = order.pricelist_id.currency_id.name or ''
45 res = [(r['id'], r['name']+' ('+(str(r['price']))+' '+currency+')') for r in self.read(cr, uid, ids, ['name', 'price'], context)]
48 def get_price(self, cr, uid, ids, field_name, arg=None, context=None):
52 sale_obj=self.pool.get('sale.order')
53 grid_obj=self.pool.get('delivery.grid')
54 for carrier in self.browse(cr, uid, ids, context=context):
55 order_id=context.get('order_id',False)
59 order = sale_obj.browse(cr, uid, order_id, context=context)
60 carrier_grid=self.grid_get(cr,uid,[carrier.id],order.partner_shipping_id.id,context)
63 price=grid_obj.get_price(cr, uid, carrier_grid, order, time.strftime('%Y-%m-%d'), context)
65 except osv.except_osv, e:
66 # no suitable delivery method found, probably configuration error
67 _logger.error("Carrier %s: %s\n%s" % (carrier.name, e.name, e.value))
73 'available': available
78 'name': fields.char('Delivery Method', required=True),
79 'partner_id': fields.many2one('res.partner', 'Transport Company', required=True, help="The partner that is doing the delivery service."),
80 'product_id': fields.many2one('product.product', 'Delivery Product', required=True),
81 'grids_id': fields.one2many('delivery.grid', 'carrier_id', 'Delivery Grids'),
82 'available' : fields.function(get_price, string='Available',type='boolean', multi='price',
83 help="Is the carrier method possible with the current order."),
84 'price' : fields.function(get_price, string='Price', multi='price'),
85 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the delivery carrier without removing it."),
86 'normal_price': fields.float('Normal Price', help="Keep empty if the pricing depends on the advanced pricing per destination"),
87 'free_if_more_than': fields.boolean('Free If Order Total Amount Is More Than', help="If the order is more expensive than a certain amount, the customer can benefit from a free shipping"),
88 'amount': fields.float('Amount', help="Amount of the order to benefit from a free shipping, expressed in the company currency"),
89 'use_detailed_pricelist': fields.boolean('Advanced Pricing per Destination', help="Check this box if you want to manage delivery prices that depends on the destination, the weight, the total of the order, etc."),
90 'pricelist_ids': fields.one2many('delivery.grid', 'carrier_id', 'Advanced Pricing'),
95 'free_if_more_than': False,
98 def grid_get(self, cr, uid, ids, contact_id, context=None):
99 contact = self.pool.get('res.partner').browse(cr, uid, contact_id, context=context)
100 for carrier in self.browse(cr, uid, ids, context=context):
101 for grid in carrier.grids_id:
102 get_id = lambda x: x.id
103 country_ids = map(get_id, grid.country_ids)
104 state_ids = map(get_id, grid.state_ids)
105 if country_ids and not contact.country_id.id in country_ids:
107 if state_ids and not contact.state_id.id in state_ids:
109 if grid.zip_from and (contact.zip or '')< grid.zip_from:
111 if grid.zip_to and (contact.zip or '')> grid.zip_to:
116 def create_grid_lines(self, cr, uid, ids, vals, context=None):
119 grid_line_pool = self.pool.get('delivery.grid.line')
120 grid_pool = self.pool.get('delivery.grid')
121 for record in self.browse(cr, uid, ids, context=context):
122 # if using advanced pricing per destination: do not change
123 if record.use_detailed_pricelist:
126 # not using advanced pricing per destination: override grid
127 grid_id = grid_pool.search(cr, uid, [('carrier_id', '=', record.id)], context=context)
128 if grid_id and not (record.normal_price or record.free_if_more_than):
129 grid_pool.unlink(cr, uid, grid_id, context=context)
131 # Check that float, else 0.0 is False
132 if not (isinstance(record.normal_price,float) or record.free_if_more_than):
138 'carrier_id': record.id,
141 grid_id = [grid_pool.create(cr, uid, grid_data, context=context)]
143 lines = grid_line_pool.search(cr, uid, [('grid_id','in',grid_id)], context=context)
145 grid_line_pool.unlink(cr, uid, lines, context=context)
147 #create the grid lines
148 if record.free_if_more_than:
150 'grid_id': grid_id and grid_id[0],
151 'name': _('Free if more than %.2f') % record.amount,
154 'max_value': record.amount,
155 'standard_price': 0.0,
158 grid_line_pool.create(cr, uid, line_data, context=context)
159 if isinstance(record.normal_price,float):
161 'grid_id': grid_id and grid_id[0],
162 'name': _('Default price'),
166 'standard_price': record.normal_price,
167 'list_price': record.normal_price,
169 grid_line_pool.create(cr, uid, line_data, context=context)
172 def write(self, cr, uid, ids, vals, context=None):
173 if isinstance(ids, (int,long)):
175 res = super(delivery_carrier, self).write(cr, uid, ids, vals, context=context)
176 self.create_grid_lines(cr, uid, ids, vals, context=context)
179 def create(self, cr, uid, vals, context=None):
180 res_id = super(delivery_carrier, self).create(cr, uid, vals, context=context)
181 self.create_grid_lines(cr, uid, [res_id], vals, context=context)
185 class delivery_grid(osv.osv):
186 _name = "delivery.grid"
187 _description = "Delivery Grid"
189 'name': fields.char('Grid Name', required=True),
190 'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when displaying a list of delivery grid."),
191 'carrier_id': fields.many2one('delivery.carrier', 'Carrier', required=True, ondelete='cascade'),
192 'country_ids': fields.many2many('res.country', 'delivery_grid_country_rel', 'grid_id', 'country_id', 'Countries'),
193 'state_ids': fields.many2many('res.country.state', 'delivery_grid_state_rel', 'grid_id', 'state_id', 'States'),
194 'zip_from': fields.char('Start Zip', size=12),
195 'zip_to': fields.char('To Zip', size=12),
196 'line_ids': fields.one2many('delivery.grid.line', 'grid_id', 'Grid Line', copy=True),
197 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the delivery grid without removing it."),
200 'active': lambda *a: 1,
201 'sequence': lambda *a: 1,
205 def get_price(self, cr, uid, id, order, dt, context=None):
210 product_uom_obj = self.pool.get('product.uom')
211 for line in order.order_line:
212 if not line.product_id or line.is_delivery:
214 q = product_uom_obj._compute_qty(cr, uid, line.product_uom.id, line.product_uom_qty, line.product_id.uom_id.id)
215 weight += (line.product_id.weight or 0.0) * q
216 volume += (line.product_id.volume or 0.0) * q
218 total = order.amount_total or 0.0
220 return self.get_price_from_picking(cr, uid, id, total,weight, volume, quantity, context=context)
222 def get_price_from_picking(self, cr, uid, id, total, weight, volume, quantity, context=None):
223 grid = self.browse(cr, uid, id, context=context)
226 price_dict = {'price': total, 'volume':volume, 'weight': weight, 'wv':volume*weight, 'quantity': quantity}
227 for line in grid.line_ids:
228 test = eval(line.type+line.operator+str(line.max_value), price_dict)
230 if line.price_type=='variable':
231 price = line.list_price * price_dict[line.variable_factor]
233 price = line.list_price
237 raise osv.except_osv(_("Unable to fetch delivery method!"), _("Selected product in the delivery method doesn't fulfill any of the delivery grid(s) criteria."))
243 class delivery_grid_line(osv.osv):
244 _name = "delivery.grid.line"
245 _description = "Delivery Grid Line"
247 'name': fields.char('Name', required=True),
248 'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when calculating delivery grid."),
249 'grid_id': fields.many2one('delivery.grid', 'Grid',required=True, ondelete='cascade'),
250 'type': fields.selection([('weight','Weight'),('volume','Volume'),\
251 ('wv','Weight * Volume'), ('price','Price'), ('quantity','Quantity')],\
252 'Variable', required=True),
253 'operator': fields.selection([('==','='),('<=','<='),('<','<'),('>=','>='),('>','>')], 'Operator', required=True),
254 'max_value': fields.float('Maximum Value', required=True),
255 'price_type': fields.selection([('fixed','Fixed'),('variable','Variable')], 'Price Type', required=True),
256 'variable_factor': fields.selection([('weight','Weight'),('volume','Volume'),('wv','Weight * Volume'), ('price','Price'), ('quantity','Quantity')], 'Variable Factor', required=True),
257 'list_price': fields.float('Sale Price', digits_compute= dp.get_precision('Product Price'), required=True),
258 'standard_price': fields.float('Cost Price', digits_compute= dp.get_precision('Product Price'), required=True),
261 'sequence': lambda *args: 10,
262 'type': lambda *args: 'weight',
263 'operator': lambda *args: '<=',
264 'price_type': lambda *args: 'fixed',
265 'variable_factor': lambda *args: 'weight',
267 _order = 'sequence, list_price'
270 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: