[MERGE] forward port of branch 8.0 up to 262eb66
[odoo/odoo.git] / addons / sale / wizard / sale_make_invoice_advance.py
1 ##############################################################################
2 #
3 #    OpenERP, Open Source Management Solution
4 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
5 #
6 #    This program is free software: you can redistribute it and/or modify
7 #    it under the terms of the GNU Affero General Public License as
8 #    published by the Free Software Foundation, either version 3 of the
9 #    License, or (at your option) any later version.
10 #
11 #    This program is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU Affero General Public License for more details.
15 #
16 #    You should have received a copy of the GNU Affero General Public License
17 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 ##############################################################################
20
21 from openerp.osv import fields, osv
22 from openerp.tools.translate import _
23 import openerp.addons.decimal_precision as dp
24
25 class sale_advance_payment_inv(osv.osv_memory):
26     _name = "sale.advance.payment.inv"
27     _description = "Sales Advance Payment Invoice"
28
29     _columns = {
30         'advance_payment_method':fields.selection(
31             [('all', 'Invoice the whole sales order'), ('percentage','Percentage'), ('fixed','Fixed price (deposit)'),
32                 ('lines', 'Some order lines')],
33             'What do you want to invoice?', required=True,
34             help="""Use Invoice the whole sale order to create the final invoice.\nUse Percentage to invoice a percentage of the total amount.\nUse Fixed Price to invoice a specific amount in advance.\nUse Some Order Lines to invoice a selection of the sales order lines."""),
35         'qtty': fields.float('Quantity', digits=(16, 2), required=True),
36         'product_id': fields.many2one('product.product', 'Advance Product',
37             domain=[('type', '=', 'service')],
38             help="Select a product of type service which is called 'Advance Product'.\nYou may have to create it and set it as a default value on this field."),
39         'amount': fields.float('Advance Amount', digits_compute= dp.get_precision('Account'),
40             help="The amount to be invoiced in advance. \nTaxes are not taken into account for advance invoices."),
41     }
42
43     def _get_advance_product(self, cr, uid, context=None):
44         try:
45             product = self.pool.get('ir.model.data').get_object(cr, uid, 'sale', 'advance_product_0')
46         except ValueError:
47             # a ValueError is returned if the xml id given is not found in the table ir_model_data
48             return False
49         return product.id
50
51     _defaults = {
52         'advance_payment_method': 'all',
53         'qtty': 1.0,
54         'product_id': _get_advance_product,
55     }
56
57     def _translate_advance(self, cr, uid, percentage=False, context=None):
58         return _("Advance of %s %%") if percentage else _("Advance of %s %s")
59
60     def onchange_method(self, cr, uid, ids, advance_payment_method, product_id, context=None):
61         if advance_payment_method == 'percentage':
62             return {'value': {'amount':0, 'product_id':False }}
63         if product_id:
64             product = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
65             return {'value': {'amount': product.list_price}}
66         return {'value': {'amount': 0}}
67
68     def _prepare_advance_invoice_vals(self, cr, uid, ids, context=None):
69         if context is None:
70             context = {}
71         sale_obj = self.pool.get('sale.order')
72         ir_property_obj = self.pool.get('ir.property')
73         fiscal_obj = self.pool.get('account.fiscal.position')
74         inv_line_obj = self.pool.get('account.invoice.line')
75         wizard = self.browse(cr, uid, ids[0], context)
76         sale_ids = context.get('active_ids', [])
77
78         result = []
79         for sale in sale_obj.browse(cr, uid, sale_ids, context=context):
80             val = inv_line_obj.product_id_change(cr, uid, [], wizard.product_id.id,
81                     False, partner_id=sale.partner_id.id, fposition_id=sale.fiscal_position.id)
82             res = val['value']
83
84             # determine and check income account
85             if not wizard.product_id.id :
86                 prop = ir_property_obj.get(cr, uid,
87                             'property_account_income_categ', 'product.category', context=context)
88                 prop_id = prop and prop.id or False
89                 account_id = fiscal_obj.map_account(cr, uid, sale.fiscal_position or False, prop_id)
90                 if not account_id:
91                     raise osv.except_osv(_('Configuration Error!'),
92                             _('There is no income account defined as global property.'))
93                 res['account_id'] = account_id
94             if not res.get('account_id'):
95                 raise osv.except_osv(_('Configuration Error!'),
96                         _('There is no income account defined for this product: "%s" (id:%d).') % \
97                             (wizard.product_id.name, wizard.product_id.id,))
98
99             # determine invoice amount
100             if wizard.amount <= 0.00:
101                 raise osv.except_osv(_('Incorrect Data'),
102                     _('The value of Advance Amount must be positive.'))
103             if wizard.advance_payment_method == 'percentage':
104                 inv_amount = sale.amount_total * wizard.amount / 100
105                 if not res.get('name'):
106                     res['name'] = self._translate_advance(cr, uid, percentage=True, context=dict(context, lang=sale.partner_id.lang)) % (wizard.amount)
107             else:
108                 inv_amount = wizard.amount
109                 if not res.get('name'):
110                     #TODO: should find a way to call formatLang() from rml_parse
111                     symbol = sale.pricelist_id.currency_id.symbol
112                     if sale.pricelist_id.currency_id.position == 'after':
113                         symbol_order = (inv_amount, symbol)
114                     else:
115                         symbol_order = (symbol, inv_amount)
116                     res['name'] = self._translate_advance(cr, uid, context=dict(context, lang=sale.partner_id.lang)) % symbol_order
117
118             # determine taxes
119             if res.get('invoice_line_tax_id'):
120                 res['invoice_line_tax_id'] = [(6, 0, res.get('invoice_line_tax_id'))]
121             else:
122                 res['invoice_line_tax_id'] = False
123
124             # create the invoice
125             inv_line_values = {
126                 'name': res.get('name'),
127                 'origin': sale.name,
128                 'account_id': res['account_id'],
129                 'price_unit': inv_amount,
130                 'quantity': wizard.qtty or 1.0,
131                 'discount': False,
132                 'uos_id': res.get('uos_id', False),
133                 'product_id': wizard.product_id.id,
134                 'invoice_line_tax_id': res.get('invoice_line_tax_id'),
135                 'account_analytic_id': sale.project_id.id or False,
136             }
137             inv_values = {
138                 'name': sale.client_order_ref or sale.name,
139                 'origin': sale.name,
140                 'type': 'out_invoice',
141                 'reference': False,
142                 'account_id': sale.partner_id.property_account_receivable.id,
143                 'partner_id': sale.partner_invoice_id.id,
144                 'invoice_line': [(0, 0, inv_line_values)],
145                 'currency_id': sale.pricelist_id.currency_id.id,
146                 'comment': '',
147                 'payment_term': sale.payment_term.id,
148                 'fiscal_position': sale.fiscal_position.id or sale.partner_id.property_account_position.id
149             }
150             result.append((sale.id, inv_values))
151         return result
152
153     def _create_invoices(self, cr, uid, inv_values, sale_id, context=None):
154         inv_obj = self.pool.get('account.invoice')
155         sale_obj = self.pool.get('sale.order')
156         inv_id = inv_obj.create(cr, uid, inv_values, context=context)
157         inv_obj.button_reset_taxes(cr, uid, [inv_id], context=context)
158         # add the invoice to the sales order's invoices
159         sale_obj.write(cr, uid, sale_id, {'invoice_ids': [(4, inv_id)]}, context=context)
160         return inv_id
161
162     def create_invoices(self, cr, uid, ids, context=None):
163         """ create invoices for the active sales orders """
164         sale_obj = self.pool.get('sale.order')
165         act_window = self.pool.get('ir.actions.act_window')
166         wizard = self.browse(cr, uid, ids[0], context)
167         sale_ids = context.get('active_ids', [])
168         if wizard.advance_payment_method == 'all':
169             # create the final invoices of the active sales orders
170             res = sale_obj.manual_invoice(cr, uid, sale_ids, context)
171             if context.get('open_invoices', False):
172                 return res
173             return {'type': 'ir.actions.act_window_close'}
174
175         if wizard.advance_payment_method == 'lines':
176             # open the list view of sales order lines to invoice
177             res = act_window.for_xml_id(cr, uid, 'sale', 'action_order_line_tree2', context)
178             res['context'] = {
179                 'search_default_uninvoiced': 1,
180                 'search_default_order_id': sale_ids and sale_ids[0] or False,
181             }
182             return res
183         assert wizard.advance_payment_method in ('fixed', 'percentage')
184
185         inv_ids = []
186         for sale_id, inv_values in self._prepare_advance_invoice_vals(cr, uid, ids, context=context):
187             inv_ids.append(self._create_invoices(cr, uid, inv_values, sale_id, context=context))
188
189         if context.get('open_invoices', False):
190             return self.open_invoices( cr, uid, ids, inv_ids, context=context)
191         return {'type': 'ir.actions.act_window_close'}
192
193     def open_invoices(self, cr, uid, ids, invoice_ids, context=None):
194         """ open a view on one of the given invoice_ids """
195         ir_model_data = self.pool.get('ir.model.data')
196         form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
197         form_id = form_res and form_res[1] or False
198         tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree')
199         tree_id = tree_res and tree_res[1] or False
200
201         return {
202             'name': _('Advance Invoice'),
203             'view_type': 'form',
204             'view_mode': 'form,tree',
205             'res_model': 'account.invoice',
206             'res_id': invoice_ids[0],
207             'view_id': False,
208             'views': [(form_id, 'form'), (tree_id, 'tree')],
209             'context': "{'type': 'out_invoice'}",
210             'type': 'ir.actions.act_window',
211         }
212
213
214 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: