[FIX] sale, sale_stock: send by email button visible when sent, progress or manual
[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 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 sales 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_id=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'] = _("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                 'origin': sale.name,
127                 'account_id': res['account_id'],
128                 'price_unit': inv_amount,
129                 'quantity': wizard.qtty or 1.0,
130                 'discount': False,
131                 'uos_id': res.get('uos_id', False),
132                 'product_id': wizard.product_id.id,
133                 'invoice_line_tax_id': res.get('invoice_line_tax_id'),
134                 'account_analytic_id': sale.project_id.id or False,
135             }
136             inv_values = {
137                 'name': sale.client_order_ref or sale.name,
138                 'origin': sale.name,
139                 'type': 'out_invoice',
140                 'reference': False,
141                 'account_id': sale.partner_id.property_account_receivable.id,
142                 'partner_id': sale.partner_invoice_id.id,
143                 'invoice_line': [(0, 0, inv_line_values)],
144                 'currency_id': sale.pricelist_id.currency_id.id,
145                 'comment': '',
146                 'payment_term': sale.payment_term.id,
147                 'fiscal_position': sale.fiscal_position.id or sale.partner_id.property_account_position.id
148             }
149             result.append((sale.id, inv_values))
150         return result
151
152     def _create_invoices(self, cr, uid, inv_values, sale_id, context=None):
153         inv_obj = self.pool.get('account.invoice')
154         sale_obj = self.pool.get('sale.order')
155         inv_id = inv_obj.create(cr, uid, inv_values, context=context)
156         inv_obj.button_reset_taxes(cr, uid, [inv_id], context=context)
157         # add the invoice to the sales order's invoices
158         sale_obj.write(cr, uid, sale_id, {'invoice_ids': [(4, inv_id)]}, context=context)
159         return inv_id
160
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 sale_advance_payment_inv()
214
215 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: