[MERGE] Sync with trunk
[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 osv import fields, osv
22 from tools.translate import _
23 import 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 sale order'), ('percentage','Percentage'), ('fixed','Fixed price (deposit)'),
32                 ('lines', 'Some order lines')],
33             'What do you want to invoice?', required=True,
34             help="""Use All to create the final invoice.
35                 Use Percentage to invoice a percentage of the total amount.
36                 Use Fixed Price to invoice a specific amound in advance.
37                 Use Some Order Lines to invoice a selection of the sale order lines."""),
38         'qtty': fields.float('Quantity', digits=(16, 2), required=True),
39         'product_id': fields.many2one('product.product', 'Advance Product',
40             help="""Select a product of type service which is called 'Advance Product'.
41                 You may have to create it and set it as a default value on this field."""),
42         'amount': fields.float('Advance Amount', digits_compute= dp.get_precision('Account'),
43             help="The amount to be invoiced in advance."),
44     }
45
46     def _get_advance_product(self, cr, uid, context=None):
47         try:
48             product = self.pool.get('ir.model.data').get_object(cr, uid, 'sale', 'advance_product_0')
49         except ValueError:
50             # a ValueError is returned if the xml id given is not found in the table ir_model_data
51             return False
52         return product.id
53
54     _defaults = {
55         'advance_payment_method': 'all',
56         'qtty': 1.0,
57         'product_id': _get_advance_product,
58     }
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                     uom=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.id 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'] = _("Advance of %s %%") % (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                         res['name'] = _("Advance of %s %s") % (inv_amount, symbol)
114                     else:
115                         res['name'] = _("Advance of %s %s") % (symbol, inv_amount)
116
117             # determine taxes
118             if res.get('invoice_line_tax_id'):
119                 res['invoice_line_tax_id'] = [(6, 0, res.get('invoice_line_tax_id'))]
120             else:
121                 res['invoice_line_tax_id'] = False
122
123             # create the invoice
124             inv_line_values = {
125                 'name': res.get('name'),
126                 'account_id': res['account_id'],
127                 'price_unit': inv_amount,
128                 'quantity': wizard.qtty or 1.0,
129                 'discount': False,
130                 'uos_id': res.get('uos_id', False),
131                 'product_id': wizard.product_id.id,
132                 'invoice_line_tax_id': res.get('invoice_line_tax_id'),
133                 'account_analytic_id': sale.project_id.id or False,
134             }
135             inv_values = {
136                 'name': sale.client_order_ref or sale.name,
137                 'origin': sale.name,
138                 'type': 'out_invoice',
139                 'reference': False,
140                 'account_id': sale.partner_id.property_account_receivable.id,
141                 'partner_id': sale.partner_id.id,
142                 'invoice_line': [(0, 0, inv_line_values)],
143                 'currency_id': sale.pricelist_id.currency_id.id,
144                 'comment': '',
145                 'payment_term': sale.payment_term.id,
146                 'fiscal_position': sale.fiscal_position.id or sale.partner_id.property_account_position.id
147             }
148             result.append((sale.id, inv_values))
149         return result
150
151     def _create_invoices(self, cr, uid, inv_values, sale_id, context=None):
152         inv_obj = self.pool.get('account.invoice')
153         sale_obj = self.pool.get('sale.order')
154         inv_id = inv_obj.create(cr, uid, inv_values, context=context)
155         inv_obj.button_reset_taxes(cr, uid, [inv_id], context=context)
156         # add the invoice to the sale order's invoices
157         sale_obj.write(cr, uid, sale_id, {'invoice_ids': [(4, inv_id)]}, context=context)
158         return inv_id
159
160
161     def create_invoices(self, cr, uid, ids, context=None):
162         """ create invoices for the active sale orders """
163         sale_obj = self.pool.get('sale.order')
164         act_window = self.pool.get('ir.actions.act_window')
165         wizard = self.browse(cr, uid, ids[0], context)
166         sale_ids = context.get('active_ids', [])
167         if wizard.advance_payment_method == 'all':
168             # create the final invoices of the active sale orders
169             res = sale_obj.manual_invoice(cr, uid, sale_ids, context)
170             if context.get('open_invoices', False):
171                 return res
172             return {'type': 'ir.actions.act_window_close'}
173
174         if wizard.advance_payment_method == 'lines':
175             # open the list view of sale order lines to invoice
176             res = act_window.for_xml_id(cr, uid, 'sale', 'action_order_line_tree2', context)
177             res['context'] = {
178                 'search_default_uninvoiced': 1,
179                 'search_default_order_id': sale_ids and sale_ids[0] or False,
180             }
181             return res
182         assert wizard.advance_payment_method in ('fixed', 'percentage')
183
184         inv_ids = []
185         for sale_id, inv_values in self._prepare_advance_invoice_vals(cr, uid, ids, context=context):
186             inv_ids.append(self._create_invoices(cr, uid, inv_values, sale_id, context=context))
187
188         if context.get('open_invoices', False):
189             return self.open_invoices( cr, uid, ids, inv_ids, context=context)
190         return {'type': 'ir.actions.act_window_close'}
191
192     def open_invoices(self, cr, uid, ids, invoice_ids, context=None):
193         """ open a view on one of the given invoice_ids """
194         ir_model_data = self.pool.get('ir.model.data')
195         form_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_form')
196         form_id = form_res and form_res[1] or False
197         tree_res = ir_model_data.get_object_reference(cr, uid, 'account', 'invoice_tree')
198         tree_id = tree_res and tree_res[1] or False
199
200         return {
201             'name': _('Advance Invoice'),
202             'view_type': 'form',
203             'view_mode': 'form,tree',
204             'res_model': 'account.invoice',
205             'res_id': invoice_ids[0],
206             'view_id': False,
207             'views': [(form_id, 'form'), (tree_id, 'tree')],
208             'context': "{'type': 'out_invoice'}",
209             'type': 'ir.actions.act_window',
210         }
211
212 sale_advance_payment_inv()
213
214 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: