Improve tax:
[odoo/odoo.git] / addons / account_tax_include / invoice_tax_incl.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id: account.py 1005 2005-07-25 08:41:42Z nicoe $
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 import time
32 import netsvc
33 from osv import fields, osv
34 import ir
35
36 class account_invoice(osv.osv):
37         def _amount_untaxed(self, cr, uid, ids, prop, unknow_none,unknow_dict):
38                 ti = []
39                 for inv in self.read(cr, uid, ids, ['price_type']):
40                         if inv['price_type']=='tax_included':
41                                 ti.append(inv['id'])
42                 id_set=",".join(map(str,ids))
43                 cr.execute("SELECT s.id,COALESCE(SUM(l.price_unit*l.quantity*(100.0-l.discount))/100.0,0)::decimal(16,2) AS amount FROM account_invoice s LEFT OUTER JOIN account_invoice_line l ON (s.id=l.invoice_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ")
44                 res=dict(cr.fetchall())
45                 if len(ti):
46                         tax = self._amount_tax(cr, uid, ti, prop, unknow_none,unknow_dict)
47                         for id in ti:
48                                 res[id] = res[id] - tax.get(id,0.0)
49                 return res
50
51         def _amount_total(self, cr, uid, ids, prop, unknow_none,unknow_dict):
52                 ti = []
53                 for inv in self.read(cr, uid, ids, ['price_type']):
54                         if inv['price_type']=='tax_excluded':
55                                 ti.append(inv['id'])
56                 id_set=",".join(map(str,ids))
57                 cr.execute("SELECT s.id,COALESCE(SUM(l.price_unit*l.quantity*(100.0-l.discount))/100.0,0)::decimal(16,2) AS amount FROM account_invoice s LEFT OUTER JOIN account_invoice_line l ON (s.id=l.invoice_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ")
58                 res=dict(cr.fetchall())
59                 if len(ti):
60                         tax = self._amount_tax(cr, uid, ti, prop, unknow_none,unknow_dict)
61                         for id in ti:
62                                 res[id] = res[id] + tax.get(id,0.0)
63                 return res
64
65         _inherit = "account.invoice"
66         _columns = {
67                 'price_type': fields.selection([
68                         ('tax_included','Tax included'),
69                         ('tax_excluded','Tax excluded')
70                 ], 'Price method', required=True),
71                 'amount_untaxed': fields.function(_amount_untaxed, method=True, string='Untaxed Amount'),
72                 'amount_total': fields.function(_amount_total, method=True, string='Total'),
73         }
74         _defaults = {
75                 'price_type': lambda *a: 'tax_excluded',
76         }
77 account_invoice()
78
79 class account_invoice_line(osv.osv):
80         _inherit = "account.invoice.line"
81
82         #
83         # Compute with VAT invluded in the price
84         #
85         def move_line_get(self, cr, uid, invoice_id, context={}):
86                 inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id)
87                 if inv.price_type=='tax_excluded':
88                         return super(account_invoice_line,self).move_line_get(cr, uid, invoice_id)
89
90                 res = []
91                 tax_grouped = {}
92                 tax_obj = self.pool.get('account.tax')
93                 cur_obj = self.pool.get('res.currency')
94                 ait_obj = self.pool.get('account.invoice.tax')
95                 cur = inv.currency_id
96
97                 for line in inv.invoice_line:
98                         res.append( {
99                                 'type':'src', 
100                                 'name':line.name, 
101                                 'price_unit':line.price_unit, 
102                                 'quantity':line.quantity, 
103                                 'price':round(line.quantity*line.price_unit * (1.0- (line.discount or 0.0)/100.0),2),
104                                 'account_id':line.account_id.id,
105                         })
106                         for tax in tax_obj.compute_inv(cr, uid, line.invoice_line_tax_id, (line.price_unit *(1.0-(line['discount'] or 0.0)/100.0)), line.quantity, inv.address_invoice_id.id, line.product_id):
107                                 val={}
108                                 val['invoice_id'] = inv.id
109                                 val['name'] = tax['name']
110                                 val['amount'] = cur_obj.round(cr, uid, cur, tax['amount'])
111                                 val['manual'] = False
112                                 val['sequence'] = tax['sequence']
113                                 val['base'] = tax['price_unit'] * line['quantity']
114
115                                 #
116                                 # Setting the tax account and amount for the line
117                                 #
118                                 if inv.type in ('out_invoice','in_invoice'):
119                                         val['base_code_id'] = tax['base_code_id']
120                                         val['tax_code_id'] = tax['tax_code_id']
121                                         val['base_amount'] = tax['base'] * tax['base_sign']
122                                         val['tax_amount'] = tax['amount'] * tax['tax_sign']
123                                         val['account_id'] = tax['account_collected_id'] or line.account_id.id
124                                 else:
125                                         val['base_code_id'] = tax['ref_base_code_id']
126                                         val['tax_code_id'] = tax['ref_tax_code_id']
127                                         val['base_amount'] = val['base'] * tax['ref_base_sign']
128                                         val['tax_amount'] = val['amount'] * tax['ref_tax_sign']
129                                         val['account_id'] = tax['account_paid_id'] or line.account_id.id
130
131                                 res[-1]['tax_code_id'] = val['base_code_id']
132                                 res[-1]['tax_amount'] = val['base_amount']
133
134                                 key = (val['tax_code_id'], val['base_code_id'], val['account_id'])
135                                 if not key in tax_grouped:
136                                         tax_grouped[key] = val
137                                 else:
138                                         tax_grouped[key]['amount'] += val['amount']
139                                         tax_grouped[key]['base'] += val['base']
140                                         tax_grouped[key]['base_amount'] += val['base_amount']
141                                         tax_grouped[key]['tax_amount'] += val['tax_amount']
142                 # delete automatic tax lines for this invoice
143                 cr.execute("DELETE FROM account_invoice_tax WHERE NOT manual AND invoice_id=%d", (invoice_id,))
144                 for t in tax_grouped.values():
145                         ait_obj.create(cr, uid, t)
146                 return res
147 account_invoice_line()