2e47eccf803fb94f61fb4d2ad45b56931cad0ec2
[odoo/odoo.git] / addons / account_tax_include / invoice_tax_incl.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 import time
24 import netsvc
25 from osv import fields, osv
26 import ir
27 from tools import config
28
29 class account_invoice(osv.osv):
30     _inherit = "account.invoice"
31     _columns = {
32         'price_type': fields.selection([('tax_included','Tax included'),
33                                         ('tax_excluded','Tax excluded')],
34                                         'Price method', required=True, readonly=True,
35                                         states={'draft':[('readonly',False)]}),
36     }
37     _defaults = {
38         'price_type': lambda *a: 'tax_excluded',
39     }
40 account_invoice()
41
42 class account_invoice_line(osv.osv):
43     _inherit = "account.invoice.line"
44     def _amount_line2(self, cr, uid, ids, name, args, context=None):
45         """
46         Return the subtotal excluding taxes with respect to price_type.
47         """
48         res = {}
49         tax_obj = self.pool.get('account.tax')
50         cur_obj = self.pool.get('res.currency')
51         for line in self.browse(cr, uid, ids):
52             cur = line.invoice_id.currency_id
53             res_init = super(account_invoice_line, self)._amount_line(cr, uid, [line.id], name, args, context)
54             res[line.id] = {
55                 'price_subtotal': 0.0,
56                 'price_subtotal_incl': 0.0,
57                 'data': []
58             }
59             if not line.quantity:
60                 continue
61             if line.invoice_id:
62                 product_taxes = []
63                 if line.product_id:
64                     if line.invoice_id.type in ('out_invoice', 'out_refund'):
65                         product_taxes = filter(lambda x: x.price_include, line.product_id.taxes_id)
66                     else:
67                         product_taxes = filter(lambda x: x.price_include, line.product_id.supplier_taxes_id)
68
69                 if ((set(product_taxes) == set(line.invoice_line_tax_id)) or not product_taxes) and (line.invoice_id.price_type == 'tax_included'):
70                     res[line.id]['price_subtotal_incl'] = cur_obj.round(cr, uid, cur, res_init[line.id])
71                 else:
72                     res[line.id]['price_subtotal'] = cur_obj.round(cr, uid, cur, res_init[line.id])
73                     for tax in tax_obj.compute_inv(cr, uid, product_taxes, res_init[line.id]/line.quantity, line.quantity):
74                         res[line.id]['price_subtotal'] = res[line.id]['price_subtotal'] - round(tax['amount'], int(config['price_accuracy']))
75             else:
76                 res[line.id]['price_subtotal'] = cur_obj.round(cr, uid, cur, res_init[line.id])
77
78             if res[line.id]['price_subtotal']:
79                 res[line.id]['price_subtotal_incl'] = res[line.id]['price_subtotal']
80                 for tax in tax_obj.compute(cr, uid, line.invoice_line_tax_id, res[line.id]['price_subtotal']/line.quantity, line.quantity):
81                     res[line.id]['price_subtotal_incl'] = res[line.id]['price_subtotal_incl'] + tax['amount']
82                     res[line.id]['data'].append( tax)
83             else:
84                 res[line.id]['price_subtotal'] = res[line.id]['price_subtotal_incl']
85                 for tax in tax_obj.compute_inv(cr, uid, line.invoice_line_tax_id, res[line.id]['price_subtotal_incl']/line.quantity, line.quantity):
86                     res[line.id]['price_subtotal'] = res[line.id]['price_subtotal'] - tax['amount']
87                     res[line.id]['data'].append( tax)
88
89         res[line.id]['price_subtotal']= round(res[line.id]['price_subtotal'], int(config['price_accuracy']))
90         res[line.id]['price_subtotal_incl']= round(res[line.id]['price_subtotal_incl'], int(config['price_accuracy']))
91         return res
92
93     def _price_unit_default(self, cr, uid, context=None):
94         if context is None:
95             context = {}
96         if 'check_total' in context:
97             t = context['check_total']
98             if context.get('price_type', False) == 'tax_included':
99                 for l in context.get('invoice_line', {}):
100                     if len(l) >= 3 and l[2]:
101                         p = l[2].get('price_unit', 0) * (1-l[2].get('discount', 0)/100.0)
102                         t = t - (p * l[2].get('quantity'))
103                 return t
104             return super(account_invoice_line, self)._price_unit_default(cr, uid, context)
105         return 0
106
107     def _get_invoice(self, cr, uid, ids, context):
108         result = {}
109         for inv in self.pool.get('account.invoice').browse(cr, uid, ids, context=context):
110             for line in inv.invoice_line:
111                 result[line.id] = True
112         return result.keys()
113     _columns = {
114         'price_subtotal': fields.function(_amount_line2, method=True, string='Subtotal w/o tax', multi='amount',
115             store={'account.invoice':(_get_invoice,['price_type'],10), 'account.invoice.line': (lambda self,cr,uid,ids,c={}: ids, None,10)}),
116         'price_subtotal_incl': fields.function(_amount_line2, method=True, string='Subtotal', multi='amount',
117             store={'account.invoice':(_get_invoice,['price_type'],10), 'account.invoice.line': (lambda self,cr,uid,ids,c={}: ids, None,10)}),
118     }
119
120     _defaults = {
121         'price_unit': _price_unit_default,
122     }
123
124     def move_line_get_item(self, cr, uid, line, context=None):
125         return {
126                 'type':'src',
127                 'name':line.name,
128                 'price_unit':(line.quantity) and (line.price_subtotal / line.quantity) or line.price_subtotal,
129                 'quantity':line.quantity,
130                 'price':line.price_subtotal,
131                 'account_id':line.account_id.id,
132                 'product_id': line.product_id.id,
133                 'uos_id':line.uos_id.id,
134                 'account_analytic_id':line.account_analytic_id.id,
135             }
136
137     def product_id_change_unit_price_inv(self, cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context=None):
138         if context is None:
139             context = {}
140         # if the tax is already included, just return the value without calculations
141         if context.get('price_type', False) == 'tax_included':
142             return {'price_unit': price_unit,'invoice_line_tax_id': tax_id}
143         else:
144             return super(account_invoice_line, self).product_id_change_unit_price_inv(cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context=context)
145
146     def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, context=None):
147         # note: will call product_id_change_unit_price_inv with context...
148         if context is None:
149             context = {}
150         context.update({'price_type': context.get('price_type','tax_excluded')})
151         return super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition_id, price_unit, address_invoice_id, context=context)
152 account_invoice_line()
153
154 class account_invoice_tax(osv.osv):
155     _inherit = "account.invoice.tax"
156
157     def compute(self, cr, uid, invoice_id, context=None):
158         inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id)
159         line_ids = map(lambda x: x.id, inv.invoice_line)
160
161         tax_grouped = {}
162         tax_obj = self.pool.get('account.tax')
163         cur_obj = self.pool.get('res.currency')
164         cur = inv.currency_id
165         company_currency = inv.company_id.currency_id.id
166         
167         for line in inv.invoice_line:
168             data = self.pool.get('account.invoice.line')._amount_line2(cr, uid, [line.id], [], [], context)[line.id]
169             for tax in data['data']:
170                 val={}
171                 val['invoice_id'] = inv.id
172                 val['name'] = tax['name']
173                 val['amount'] = cur_obj.round(cr, uid, cur, tax['amount'])
174                 val['manual'] = False
175                 val['sequence'] = tax['sequence']
176                 val['base'] = tax['price_unit'] * line['quantity']
177
178                 if inv.type in ('out_invoice','in_invoice'):
179                     val['base_code_id'] = tax['base_code_id']
180                     val['tax_code_id'] = tax['tax_code_id']
181                     val['base_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['base_sign'], context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False)
182                     val['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['tax_sign'], context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False)
183                     val['account_id'] = tax['account_collected_id'] or line.account_id.id
184                 else:
185                     val['base_code_id'] = tax['ref_base_code_id']
186                     val['tax_code_id'] = tax['ref_tax_code_id']
187                     val['base_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['ref_base_sign'], context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False)
188                     val['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['ref_tax_sign'], context={'date': inv.date_invoice or time.strftime('%Y-%m-%d')}, round=False)
189                     val['account_id'] = tax['account_paid_id'] or line.account_id.id
190
191                 key = (val['tax_code_id'], val['base_code_id'], val['account_id'])
192                 if not key in tax_grouped:
193                     tax_grouped[key] = val
194                 else:
195                     tax_grouped[key]['amount'] += val['amount']
196                     tax_grouped[key]['base'] += val['base']
197                     tax_grouped[key]['base_amount'] += val['base_amount']
198                     tax_grouped[key]['tax_amount'] += val['tax_amount']
199
200         for t in tax_grouped.values():
201             t['amount'] = cur_obj.round(cr, uid, cur, t['amount'])
202             t['base_amount'] = cur_obj.round(cr, uid, cur, t['base_amount'])
203             t['tax_amount'] = cur_obj.round(cr, uid, cur, t['tax_amount'])
204         
205         return tax_grouped
206 account_invoice_tax()
207
208
209 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
210