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