[MERGE] forward port of branch saas-5 up to e4cb520
[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 logging
23 import time
24 from openerp.osv import fields,osv
25 from openerp.tools.translate import _
26 import openerp.addons.decimal_precision as dp
27
28 _logger = logging.getLogger(__name__)
29
30 class delivery_carrier(osv.osv):
31     _name = "delivery.carrier"
32     _description = "Carrier"
33
34     def name_get(self, cr, uid, ids, context=None):
35         if not len(ids):
36             return []
37         if context is None:
38             context = {}
39         order_id = context.get('order_id',False)
40         if not order_id:
41             res = super(delivery_carrier, self).name_get(cr, uid, ids, context=context)
42         else:
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)]
46         return res
47
48     def get_price(self, cr, uid, ids, field_name, arg=None, context=None):
49         res={}
50         if context is None:
51             context = {}
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)
56             price=False
57             available = False
58             if order_id:
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)
61               if carrier_grid:
62                   try:
63                     price=grid_obj.get_price(cr, uid, carrier_grid, order, time.strftime('%Y-%m-%d'), context)
64                     available = True
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))
68                     price = 0.0
69               else:
70                   price = 0.0
71             res[carrier.id] = {
72                 'price': price,
73                 'available': available
74             }
75         return res
76
77     _columns = {
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'),
91     }
92
93     _defaults = {
94         'active': 1,
95         'free_if_more_than': False,
96     }
97
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:
106                     continue
107                 if state_ids and not contact.state_id.id in state_ids:
108                     continue
109                 if grid.zip_from and (contact.zip or '')< grid.zip_from:
110                     continue
111                 if grid.zip_to and (contact.zip or '')> grid.zip_to:
112                     continue
113                 return grid.id
114         return False
115
116     def create_grid_lines(self, cr, uid, ids, vals, context=None):
117         if context is None:
118             context = {}
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:
124                 continue
125
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)
130
131             # Check that float, else 0.0 is False
132             if not (isinstance(record.normal_price,float) or record.free_if_more_than):
133                 continue
134
135             if not grid_id:
136                 grid_data = {
137                     'name': record.name,
138                     'carrier_id': record.id,
139                     'sequence': 10,
140                 }
141                 grid_id = [grid_pool.create(cr, uid, grid_data, context=context)]
142
143             lines = grid_line_pool.search(cr, uid, [('grid_id','in',grid_id)], context=context)
144             if lines:
145                 grid_line_pool.unlink(cr, uid, lines, context=context)
146
147             #create the grid lines
148             if record.free_if_more_than:
149                 line_data = {
150                     'grid_id': grid_id and grid_id[0],
151                     'name': _('Free if more than %.2f') % record.amount,
152                     'type': 'price',
153                     'operator': '>=',
154                     'max_value': record.amount,
155                     'standard_price': 0.0,
156                     'list_price': 0.0,
157                 }
158                 grid_line_pool.create(cr, uid, line_data, context=context)
159             if isinstance(record.normal_price,float):
160                 line_data = {
161                     'grid_id': grid_id and grid_id[0],
162                     'name': _('Default price'),
163                     'type': 'price',
164                     'operator': '>=',
165                     'max_value': 0.0,
166                     'standard_price': record.normal_price,
167                     'list_price': record.normal_price,
168                 }
169                 grid_line_pool.create(cr, uid, line_data, context=context)
170         return True
171
172     def write(self, cr, uid, ids, vals, context=None):
173         if isinstance(ids, (int,long)):
174             ids = [ids]
175         res = super(delivery_carrier, self).write(cr, uid, ids, vals, context=context)
176         self.create_grid_lines(cr, uid, ids, vals, context=context)
177         return res
178
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)
182         return res_id
183
184
185 class delivery_grid(osv.osv):
186     _name = "delivery.grid"
187     _description = "Delivery Grid"
188     _columns = {
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."),
198     }
199     _defaults = {
200         'active': lambda *a: 1,
201         'sequence': lambda *a: 1,
202     }
203     _order = 'sequence'
204
205     def get_price(self, cr, uid, id, order, dt, context=None):
206         total = 0
207         weight = 0
208         volume = 0
209         quantity = 0
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:
213                 continue
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
217             quantity += q
218         total = order.amount_total or 0.0
219
220         return self.get_price_from_picking(cr, uid, id, total,weight, volume, quantity, context=context)
221
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)
224         price = 0.0
225         ok = False
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)
229             if test:
230                 if line.price_type=='variable':
231                     price = line.list_price * price_dict[line.variable_factor]
232                 else:
233                     price = line.list_price
234                 ok = True
235                 break
236         if not ok:
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."))
238
239         return price
240
241
242
243 class delivery_grid_line(osv.osv):
244     _name = "delivery.grid.line"
245     _description = "Delivery Grid Line"
246     _columns = {
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),
259     }
260     _defaults = {
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',
266     }
267     _order = 'sequence, list_price'
268
269
270 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: