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