[MERGE] forward port of branch 8.0 up to 2b192be
[odoo/odoo.git] / addons / website_quote / models / order.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
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 from openerp.osv import osv, fields
23 import uuid
24 import time
25 import datetime
26
27 import openerp.addons.decimal_precision as dp
28
29 class sale_quote_template(osv.osv):
30     _name = "sale.quote.template"
31     _description = "Sale Quotation Template"
32     _columns = {
33         'name': fields.char('Quotation Template', required=True),
34         'website_description': fields.html('Description', translate=True),
35         'quote_line': fields.one2many('sale.quote.line', 'quote_id', 'Quotation Template Lines', copy=True),
36         'note': fields.text('Terms and conditions'),
37         'options': fields.one2many('sale.quote.option', 'template_id', 'Optional Products Lines', copy=True),
38         'number_of_days': fields.integer('Quotation Duration', help='Number of days for the validity date computation of the quotation'),
39     }
40     def open_template(self, cr, uid, quote_id, context=None):
41         return {
42             'type': 'ir.actions.act_url',
43             'target': 'self',
44             'url': '/quote/template/%d' % quote_id[0]
45         }
46
47 class sale_quote_line(osv.osv):
48     _name = "sale.quote.line"
49     _description = "Quotation Template Lines"
50     _columns = {
51         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of sale quote lines."),
52         'quote_id': fields.many2one('sale.quote.template', 'Quotation Template Reference', required=True, ondelete='cascade', select=True),
53         'name': fields.text('Description', required=True, translate=True),
54         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True),
55         'website_description': fields.related('product_id', 'product_tmpl_id', 'quote_description', string='Line Description', type='html', translate=True),
56         'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price')),
57         'discount': fields.float('Discount (%)', digits_compute= dp.get_precision('Discount')),
58         'product_uom_qty': fields.float('Quantity', required=True, digits_compute= dp.get_precision('Product UoS')),
59         'product_uom_id': fields.many2one('product.uom', 'Unit of Measure ', required=True),
60     }
61     _order = 'sequence, id'
62     _defaults = {
63         'product_uom_qty': 1,
64         'discount': 0.0,
65         'sequence': 10,
66     }
67     def on_change_product_id(self, cr, uid, ids, product, context=None):
68         vals = {}
69         product_obj = self.pool.get('product.product').browse(cr, uid, product, context=context)
70         name = product_obj.name
71         if product_obj.description_sale:
72             name += '\n' + product_obj.description_sale
73         vals.update({
74             'price_unit': product_obj.list_price,
75             'product_uom_id': product_obj.uom_id.id,
76             'website_description': product_obj and (product_obj.quote_description or product_obj.website_description) or '',
77             'name': name,
78         })
79         return {'value': vals}
80
81     def _inject_quote_description(self, cr, uid, values, context=None):
82         values = dict(values or {})
83         if not values.get('website_description') and values.get('product_id'):
84             product = self.pool['product.product'].browse(cr, uid, values['product_id'], context=context)
85             values['website_description'] = product.quote_description or product.website_description or ''
86         return values
87
88     def create(self, cr, uid, values, context=None):
89         values = self._inject_quote_description(cr, uid, values, context)
90         ret = super(sale_quote_line, self).create(cr, uid, values, context=context)
91         # hack because create don t make the job for a related field
92         if values.get('website_description'):
93             self.write(cr, uid, ret, {'website_description': values['website_description']}, context=context)
94         return ret
95
96     def write(self, cr, uid, ids, values, context=None):
97         values = self._inject_quote_description(cr, uid, values, context)
98         return super(sale_quote_line, self).write(cr, uid, ids, values, context=context)
99
100
101 class sale_order_line(osv.osv):
102     _inherit = "sale.order.line"
103     _description = "Sales Order Line"
104     _columns = {
105         'website_description': fields.html('Line Description'),
106         'option_line_id': fields.one2many('sale.order.option', 'line_id', 'Optional Products Lines'),
107     }
108
109     def _inject_quote_description(self, cr, uid, values, context=None):
110         values = dict(values or {})
111         if not values.get('website_description') and values.get('product_id'):
112             product = self.pool['product.product'].browse(cr, uid, values['product_id'], context=context)
113             values['website_description'] = product.quote_description or product.website_description
114         return values
115
116     def create(self, cr, uid, values, context=None):
117         values = self._inject_quote_description(cr, uid, values, context)
118         ret = super(sale_order_line, self).create(cr, uid, values, context=context)
119         # hack because create don t make the job for a related field
120         if values.get('website_description'):
121             self.write(cr, uid, ret, {'website_description': values['website_description']}, context=context)
122         return ret
123
124     def write(self, cr, uid, ids, values, context=None):
125         values = self._inject_quote_description(cr, uid, values, context)
126         return super(sale_order_line, self).write(cr, uid, ids, values, context=context)
127
128
129 class sale_order(osv.osv):
130     _inherit = 'sale.order'
131
132     def _get_total(self, cr, uid, ids, name, arg, context=None):
133         res = {}
134         for order in self.browse(cr, uid, ids, context=context):
135             total = 0.0
136             for line in order.order_line:
137                 total += (line.product_uom_qty * line.price_unit)
138             res[order.id] = total
139         return res
140
141     _columns = {
142         'access_token': fields.char('Security Token', required=True, copy=False),
143         'template_id': fields.many2one('sale.quote.template', 'Quotation Template', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}),
144         'website_description': fields.html('Description'),
145         'options' : fields.one2many('sale.order.option', 'order_id', 'Optional Products Lines', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=True),
146         'amount_undiscounted': fields.function(_get_total, string='Amount Before Discount', type="float",
147             digits_compute=dp.get_precision('Account')),
148         'quote_viewed': fields.boolean('Quotation Viewed')
149     }
150
151     def _get_template_id(self, cr, uid, context=None):
152         try:
153             template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'website_quote', 'website_quote_template_default')[1]
154         except ValueError:
155             template_id = False
156         return template_id
157
158     _defaults = {
159         'access_token': lambda self, cr, uid, ctx={}: str(uuid.uuid4()),
160         'template_id' : _get_template_id,
161     }
162
163     def open_quotation(self, cr, uid, quote_id, context=None):
164         quote = self.browse(cr, uid, quote_id[0], context=context)
165         self.write(cr, uid, quote_id[0], {'quote_viewed': True}, context=context)
166         return {
167             'type': 'ir.actions.act_url',
168             'target': 'self',
169             'url': '/quote/%s' % (quote.id)
170         }
171
172     def onchange_template_id(self, cr, uid, ids, template_id, partner=False, fiscal_position=False, context=None):
173         if not template_id:
174             return True
175
176         if context is None:
177             context = {}
178         if partner:
179             context['lang'] = self.pool['res.partner'].browse(cr, uid, partner, context).lang
180
181         lines = [(5,)]
182         quote_template = self.pool.get('sale.quote.template').browse(cr, uid, template_id, context=context)
183         for line in quote_template.quote_line:
184             res = self.pool.get('sale.order.line').product_id_change(cr, uid, False,
185                 False, line.product_id.id, line.product_uom_qty, line.product_uom_id.id, line.product_uom_qty,
186                 line.product_uom_id.id, line.name, partner, False, True, time.strftime('%Y-%m-%d'),
187                 False, fiscal_position, True, context)
188             data = res.get('value', {})
189             if 'tax_id' in data:
190                 data['tax_id'] = [(6, 0, data['tax_id'])]
191             data.update({
192                 'name': line.name,
193                 'price_unit': line.price_unit,
194                 'discount': line.discount,
195                 'product_uom_qty': line.product_uom_qty,
196                 'product_id': line.product_id.id,
197                 'product_uom': line.product_uom_id.id,
198                 'website_description': line.website_description,
199                 'state': 'draft',
200             })
201             lines.append((0, 0, data))
202         options = []
203         for option in quote_template.options:
204             options.append((0, 0, {
205                 'product_id': option.product_id.id,
206                 'name': option.name,
207                 'quantity': option.quantity,
208                 'uom_id': option.uom_id.id,
209                 'price_unit': option.price_unit,
210                 'discount': option.discount,
211                 'website_description': option.website_description,
212             }))
213         date = False
214         if quote_template.number_of_days > 0:
215             date = (datetime.datetime.now() + datetime.timedelta(quote_template.number_of_days)).strftime("%Y-%m-%d")
216         data = {'order_line': lines, 'website_description': quote_template.website_description, 'note': quote_template.note, 'options': options, 'validity_date': date}
217         return {'value': data}
218
219     def recommended_products(self, cr, uid, ids, context=None):
220         order_line = self.browse(cr, uid, ids[0], context=context).order_line
221         product_pool = self.pool.get('product.product')
222         products = []
223         for line in order_line:
224             products += line.product_id.product_tmpl_id.recommended_products(context=context)
225         return products
226
227     def get_access_action(self, cr, uid, id, context=None):
228         """ Override method that generated the link to access the document. Instead
229         of the classic form view, redirect to the online quote if exists. """
230         quote = self.browse(cr, uid, id, context=context)
231         if not quote.template_id:
232             return super(sale_order, self).get_access_action(cr, uid, id, context=context)
233         return {
234             'type': 'ir.actions.act_url',
235             'url': '/quote/%s' % id,
236             'target': 'self',
237             'res_id': id,
238         }
239
240     def action_quotation_send(self, cr, uid, ids, context=None):
241         action = super(sale_order, self).action_quotation_send(cr, uid, ids, context=context)
242         ir_model_data = self.pool.get('ir.model.data')
243         quote_template_id = self.read(cr, uid, ids, ['template_id'], context=context)[0]['template_id']
244         if quote_template_id:
245             try:
246                 template_id = ir_model_data.get_object_reference(cr, uid, 'website_quote', 'email_template_edi_sale')[1]
247             except ValueError:
248                 pass
249             else:
250                 action['context'].update({
251                     'default_template_id': template_id,
252                     'default_use_template': True
253                 })
254
255         return action
256
257
258 class sale_quote_option(osv.osv):
259     _name = "sale.quote.option"
260     _description = "Quotation Option"
261     _columns = {
262         'template_id': fields.many2one('sale.quote.template', 'Quotation Template Reference', ondelete='cascade', select=True, required=True),
263         'name': fields.text('Description', required=True, translate=True),
264         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True),
265         'website_description': fields.html('Option Description', translate=True),
266         'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price')),
267         'discount': fields.float('Discount (%)', digits_compute= dp.get_precision('Discount')),
268         'uom_id': fields.many2one('product.uom', 'Unit of Measure ', required=True),
269         'quantity': fields.float('Quantity', required=True, digits_compute= dp.get_precision('Product UoS')),
270     }
271     _defaults = {
272         'quantity': 1,
273     }
274     def on_change_product_id(self, cr, uid, ids, product, context=None):
275         vals = {}
276         product_obj = self.pool.get('product.product').browse(cr, uid, product, context=context)
277         vals.update({
278             'price_unit': product_obj.list_price,
279             'website_description': product_obj.product_tmpl_id.quote_description,
280             'name': product_obj.name,
281             'uom_id': product_obj.product_tmpl_id.uom_id.id,
282         })
283         return {'value': vals}
284
285 class sale_order_option(osv.osv):
286     _name = "sale.order.option"
287     _description = "Sale Options"
288     _columns = {
289         'order_id': fields.many2one('sale.order', 'Sale Order Reference', ondelete='cascade', select=True),
290         'line_id': fields.many2one('sale.order.line', on_delete="set null"),
291         'name': fields.text('Description', required=True),
292         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)]),
293         'website_description': fields.html('Line Description'),
294         'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price')),
295         'discount': fields.float('Discount (%)', digits_compute= dp.get_precision('Discount')),
296         'uom_id': fields.many2one('product.uom', 'Unit of Measure ', required=True),
297         'quantity': fields.float('Quantity', required=True,
298             digits_compute= dp.get_precision('Product UoS')),
299     }
300
301     _defaults = {
302         'quantity': 1,
303     }
304     def on_change_product_id(self, cr, uid, ids, product, context=None):
305         vals = {}
306         if not product:
307             return vals
308         product_obj = self.pool.get('product.product').browse(cr, uid, product, context=context)
309         vals.update({
310             'price_unit': product_obj.list_price,
311             'website_description': product_obj and (product_obj.quote_description or product_obj.website_description),
312             'name': product_obj.name,
313             'uom_id': product_obj.product_tmpl_id.uom_id.id,
314         })
315         return {'value': vals}
316
317 class product_template(osv.Model):
318     _inherit = "product.template"
319
320     _columns = {
321         'website_description': fields.html('Description for the website'), # hack, if website_sale is not installed
322         'quote_description': fields.html('Description for the quote'),
323     }
324