[MERGE] Forward-port of latest 7.0 bugfixes, up to aeaa826
[odoo/odoo.git] / addons / delivery / delivery.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 from openerp.osv import fields,osv
24 from openerp.tools.translate import _
25 import openerp.addons.decimal_precision as dp
26
27 class delivery_carrier(osv.osv):
28     _name = "delivery.carrier"
29     _description = "Carrier"
30
31     def name_get(self, cr, uid, ids, context=None):
32         if not len(ids):
33             return []
34         if context is None:
35             context = {}
36         order_id = context.get('order_id',False)
37         if not order_id:
38             res = super(delivery_carrier, self).name_get(cr, uid, ids, context=context)
39         else:
40             order = self.pool.get('sale.order').browse(cr, uid, order_id, context=context)
41             currency = order.pricelist_id.currency_id.name or ''
42             res = [(r['id'], r['name']+' ('+(str(r['price']))+' '+currency+')') for r in self.read(cr, uid, ids, ['name', 'price'], context)]
43         return res
44
45     def get_price(self, cr, uid, ids, field_name, arg=None, context=None):
46         res={}
47         if context is None:
48             context = {}
49         sale_obj=self.pool.get('sale.order')
50         grid_obj=self.pool.get('delivery.grid')
51         for carrier in self.browse(cr, uid, ids, context=context):
52             order_id=context.get('order_id',False)
53             price=False
54             if order_id:
55               order = sale_obj.browse(cr, uid, order_id, context=context)
56               carrier_grid=self.grid_get(cr,uid,[carrier.id],order.partner_shipping_id.id,context)
57               if carrier_grid:
58                   price=grid_obj.get_price(cr, uid, carrier_grid, order, time.strftime('%Y-%m-%d'), context)
59               else:
60                   price = 0.0
61             res[carrier.id]=price
62         return res
63
64     _columns = {
65         'name': fields.char('Delivery Method', size=64, required=True),
66         'partner_id': fields.many2one('res.partner', 'Transport Company', required=True, help="The partner that is doing the delivery service."),
67         'product_id': fields.many2one('product.product', 'Delivery Product', required=True),
68         'grids_id': fields.one2many('delivery.grid', 'carrier_id', 'Delivery Grids'),
69         'price' : fields.function(get_price, string='Price'),
70         '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."),
71         'normal_price': fields.float('Normal Price', help="Keep empty if the pricing depends on the advanced pricing per destination"),
72         '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"),
73         'amount': fields.float('Amount', help="Amount of the order to benefit from a free shipping, expressed in the company currency"),
74         '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."),
75         'pricelist_ids': fields.one2many('delivery.grid', 'carrier_id', 'Advanced Pricing'),
76     }
77
78     _defaults = {
79         'active': 1,
80         'free_if_more_than': False,
81     }
82
83     def grid_get(self, cr, uid, ids, contact_id, context=None):
84         contact = self.pool.get('res.partner').browse(cr, uid, contact_id, context=context)
85         for carrier in self.browse(cr, uid, ids, context=context):
86             for grid in carrier.grids_id:
87                 get_id = lambda x: x.id
88                 country_ids = map(get_id, grid.country_ids)
89                 state_ids = map(get_id, grid.state_ids)
90                 if country_ids and not contact.country_id.id in country_ids:
91                     continue
92                 if state_ids and not contact.state_id.id in state_ids:
93                     continue
94                 if grid.zip_from and (contact.zip or '')< grid.zip_from:
95                     continue
96                 if grid.zip_to and (contact.zip or '')> grid.zip_to:
97                     continue
98                 return grid.id
99         return False
100
101     def create_grid_lines(self, cr, uid, ids, vals, context=None):
102         if context is None:
103             context = {}
104         grid_line_pool = self.pool.get('delivery.grid.line')
105         grid_pool = self.pool.get('delivery.grid')
106         for record in self.browse(cr, uid, ids, context=context):
107             # if using advanced pricing per destination: do not change
108             if record.use_detailed_pricelist:
109                 continue
110
111             # not using advanced pricing per destination: override grid
112             grid_id = grid_pool.search(cr, uid, [('carrier_id', '=', record.id)], context=context)
113             if grid_id and not (record.normal_price or record.free_if_more_than):
114                 grid_pool.unlink(cr, uid, grid_id, context=context)
115
116             # Check that float, else 0.0 is False
117             if not (isinstance(record.normal_price,float) or record.free_if_more_than):
118                 continue
119
120             if not grid_id:
121                 grid_data = {
122                     'name': record.name,
123                     'carrier_id': record.id,
124                     'sequence': 10,
125                 }
126                 grid_id = [grid_pool.create(cr, uid, grid_data, context=context)]
127
128             lines = grid_line_pool.search(cr, uid, [('grid_id','in',grid_id)], context=context)
129             if lines:
130                 grid_line_pool.unlink(cr, uid, lines, context=context)
131
132             #create the grid lines
133             if record.free_if_more_than:
134                 line_data = {
135                     'grid_id': grid_id and grid_id[0],
136                     'name': _('Free if more than %.2f') % record.amount,
137                     'type': 'price',
138                     'operator': '>=',
139                     'max_value': record.amount,
140                     'standard_price': 0.0,
141                     'list_price': 0.0,
142                 }
143                 grid_line_pool.create(cr, uid, line_data, context=context)
144             if isinstance(record.normal_price,float):
145                 line_data = {
146                     'grid_id': grid_id and grid_id[0],
147                     'name': _('Default price'),
148                     'type': 'price',
149                     'operator': '>=',
150                     'max_value': 0.0,
151                     'standard_price': record.normal_price,
152                     'list_price': record.normal_price,
153                 }
154                 grid_line_pool.create(cr, uid, line_data, context=context)
155         return True
156
157     def write(self, cr, uid, ids, vals, context=None):
158         if isinstance(ids, (int,long)):
159             ids = [ids]
160         res = super(delivery_carrier, self).write(cr, uid, ids, vals, context=context)
161         self.create_grid_lines(cr, uid, ids, vals, context=context)
162         return res
163
164     def create(self, cr, uid, vals, context=None):
165         res_id = super(delivery_carrier, self).create(cr, uid, vals, context=context)
166         self.create_grid_lines(cr, uid, [res_id], vals, context=context)
167         return res_id
168
169
170 class delivery_grid(osv.osv):
171     _name = "delivery.grid"
172     _description = "Delivery Grid"
173     _columns = {
174         'name': fields.char('Grid Name', size=64, required=True),
175         'sequence': fields.integer('Sequence', size=64, required=True, help="Gives the sequence order when displaying a list of delivery grid."),
176         'carrier_id': fields.many2one('delivery.carrier', 'Carrier', required=True, ondelete='cascade'),
177         'country_ids': fields.many2many('res.country', 'delivery_grid_country_rel', 'grid_id', 'country_id', 'Countries'),
178         'state_ids': fields.many2many('res.country.state', 'delivery_grid_state_rel', 'grid_id', 'state_id', 'States'),
179         'zip_from': fields.char('Start Zip', size=12),
180         'zip_to': fields.char('To Zip', size=12),
181         'line_ids': fields.one2many('delivery.grid.line', 'grid_id', 'Grid Line'),
182         '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."),
183     }
184     _defaults = {
185         'active': lambda *a: 1,
186         'sequence': lambda *a: 1,
187     }
188     _order = 'sequence'
189
190     def get_price(self, cr, uid, id, order, dt, context=None):
191         total = 0
192         weight = 0
193         volume = 0
194         product_uom_obj = self.pool.get('product.uom')
195         for line in order.order_line:
196             if not line.product_id or line.is_delivery:
197                 continue
198             q = product_uom_obj._compute_qty(cr, uid, line.product_uom.id, line.product_uos_qty, line.product_id.uom_id.id)
199             weight += (line.product_id.weight or 0.0) * q
200             volume += (line.product_id.volume or 0.0) * q
201         total = order.amount_total or 0.0
202
203         return self.get_price_from_picking(cr, uid, id, total,weight, volume, context=context)
204
205     def get_price_from_picking(self, cr, uid, id, total, weight, volume, context=None):
206         grid = self.browse(cr, uid, id, context=context)
207         price = 0.0
208         ok = False
209         price_dict = {'price': total, 'volume':volume, 'weight': weight, 'wv':volume*weight}
210         for line in grid.line_ids:
211             test = eval(line.type+line.operator+str(line.max_value), price_dict)
212             if test:
213                 if line.price_type=='variable':
214                     price = line.list_price * price_dict[line.variable_factor]
215                 else:
216                     price = line.list_price
217                 ok = True
218                 break
219         if not ok:
220             raise osv.except_osv(_('No price available!'), _('No line matched this product or order in the chosen delivery grid.'))
221
222         return price
223
224
225
226 class delivery_grid_line(osv.osv):
227     _name = "delivery.grid.line"
228     _description = "Delivery Grid Line"
229     _columns = {
230         'name': fields.char('Name', size=64, required=True),
231         'grid_id': fields.many2one('delivery.grid', 'Grid',required=True, ondelete='cascade'),
232         'type': fields.selection([('weight','Weight'),('volume','Volume'),\
233                                   ('wv','Weight * Volume'), ('price','Price')],\
234                                   'Variable', required=True),
235         'operator': fields.selection([('==','='),('<=','<='),('>=','>=')], 'Operator', required=True),
236         'max_value': fields.float('Maximum Value', required=True),
237         'price_type': fields.selection([('fixed','Fixed'),('variable','Variable')], 'Price Type', required=True),
238         'variable_factor': fields.selection([('weight','Weight'),('volume','Volume'),('wv','Weight * Volume'), ('price','Price')], 'Variable Factor', required=True),
239         'list_price': fields.float('Sale Price', digits_compute= dp.get_precision('Product Price'), required=True),
240         'standard_price': fields.float('Cost Price', digits_compute= dp.get_precision('Product Price'), required=True),
241     }
242     _defaults = {
243         'type': lambda *args: 'weight',
244         'operator': lambda *args: '<=',
245         'price_type': lambda *args: 'fixed',
246         'variable_factor': lambda *args: 'weight',
247     }
248     _order = 'list_price'
249
250
251 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: