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-2010 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 from tools import config
27
28 class account_invoice(osv.osv):
29     _inherit = "account.invoice"
30     _columns = {
31         'price_type': fields.selection([('tax_included','Tax included'),
32                                         ('tax_excluded','Tax excluded')],
33                                         'Price method', required=True, readonly=True,
34                                         states={'draft':[('readonly',False)]}),
35     }
36     _defaults = {
37         'price_type': lambda *a: 'tax_excluded',
38     }
39
40     def refund(self, cr, uid, ids, date=None, period_id=None, description=None):
41         map_old_new = {}
42         refund_ids = []
43         for old_inv_id in ids:
44             new_id = super(account_invoice,self).refund(cr, uid, ids, date=date, period_id=period_id, description=description)
45             refund_ids += new_id
46             map_old_new[old_inv_id] = new_id[0]
47
48         for old_inv_id in map_old_new.keys():
49             old_inv_record = self.read(cr, uid, [old_inv_id], ['price_type'])[0]['price_type']
50             self.write(cr, uid, [map_old_new[old_inv_id]], {'price_type' : old_inv_record})
51         return refund_ids
52
53 account_invoice()
54
55 class account_invoice_line(osv.osv):
56     _inherit = "account.invoice.line"
57     def _amount_line2(self, cr, uid, ids, name, args, context=None):
58         """
59         Return the subtotal excluding taxes with respect to price_type.
60         """
61         res = {}
62         tax_obj = self.pool.get('account.tax')
63         cur_obj = self.pool.get('res.currency')
64         for line in self.browse(cr, uid, ids):
65             cur = line.invoice_id and line.invoice_id.currency_id or False
66             res_init = super(account_invoice_line, self)._amount_line(cr, uid, [line.id], name, args, context)
67             res[line.id] = {
68                 'price_subtotal': 0.0,
69                 'price_subtotal_incl': 0.0,
70                 'data': []
71             }
72             if not line.quantity:
73                 continue
74             if line.invoice_id:
75                 product_taxes = []
76                 if line.product_id:
77                     if line.invoice_id.type in ('out_invoice', 'out_refund'):
78                         product_taxes = filter(lambda x: x.price_include, line.product_id.taxes_id)
79                     else:
80                         product_taxes = filter(lambda x: x.price_include, line.product_id.supplier_taxes_id)
81
82                 if ((set(product_taxes) == set(line.invoice_line_tax_id)) or not product_taxes) and (line.invoice_id.price_type == 'tax_included'):
83                     res[line.id]['price_subtotal_incl'] = cur and cur_obj.round(cr, uid, cur, res_init[line.id]) or res_init[line.id]
84                 else:
85                     res[line.id]['price_subtotal'] = cur and cur_obj.round(cr, uid, cur, res_init[line.id]) or res_init[line.id]
86                     for tax in tax_obj.compute_inv(cr, uid, product_taxes, res_init[line.id]/line.quantity, line.quantity):
87                         res[line.id]['price_subtotal'] = res[line.id]['price_subtotal'] - round(tax['amount'], int(config['price_accuracy']))
88             else:
89                 res[line.id]['price_subtotal'] = cur and cur_obj.round(cr, uid, cur, res_init[line.id]) or res_init[line.id]
90
91             if res[line.id]['price_subtotal']:
92                 res[line.id]['price_subtotal_incl'] = res[line.id]['price_subtotal']
93                 for tax in tax_obj.compute(cr, uid, line.invoice_line_tax_id, res[line.id]['price_subtotal']/line.quantity, line.quantity):
94                     res[line.id]['price_subtotal_incl'] = res[line.id]['price_subtotal_incl'] + tax['amount']
95                     res[line.id]['data'].append( tax)
96             else:
97                 res[line.id]['price_subtotal'] = res[line.id]['price_subtotal_incl']
98                 for tax in tax_obj.compute_inv(cr, uid, line.invoice_line_tax_id, res[line.id]['price_subtotal_incl']/line.quantity, line.quantity):
99                     res[line.id]['price_subtotal'] = res[line.id]['price_subtotal'] - tax['amount']
100                     res[line.id]['data'].append( tax)
101
102             res[line.id]['price_subtotal']= round(res[line.id]['price_subtotal'], int(config['price_accuracy']))
103             res[line.id]['price_subtotal_incl']= round(res[line.id]['price_subtotal_incl'], int(config['price_accuracy']))
104         return res
105
106     def _price_unit_default(self, cr, uid, context=None):
107         if context is None:
108             context = {}
109         if 'check_total' in context:
110             t = context['check_total']
111             if context.get('price_type', False) == 'tax_included':
112                 for l in context.get('invoice_line', {}):
113                     if len(l) >= 3 and l[2]:
114                         p = l[2].get('price_unit', 0) * (1-l[2].get('discount', 0)/100.0)
115                         t = t - (p * l[2].get('quantity'))
116                 return t
117             return super(account_invoice_line, self)._price_unit_default(cr, uid, context)
118         return 0
119
120     def _get_invoice(self, cr, uid, ids, context):
121         result = {}
122         for inv in self.pool.get('account.invoice').browse(cr, uid, ids, context=context):
123             for line in inv.invoice_line:
124                 result[line.id] = True
125         return result.keys()
126     _columns = {
127         'price_subtotal': fields.function(_amount_line2, method=True, string='Subtotal w/o tax', multi='amount',
128             store={'account.invoice':(_get_invoice,['price_type'],10), 'account.invoice.line': (lambda self,cr,uid,ids,c={}: ids, None,10)}),
129         'price_subtotal_incl': fields.function(_amount_line2, method=True, string='Subtotal', multi='amount',
130             store={'account.invoice':(_get_invoice,['price_type'],10), 'account.invoice.line': (lambda self,cr,uid,ids,c={}: ids, None,10)}),
131     }
132
133     _defaults = {
134         'price_unit': _price_unit_default,
135     }
136
137     def move_line_get_item(self, cr, uid, line, context=None):
138         return {
139                 'type':'src',
140                 'name':line.name,
141                 'price_unit':(line.quantity) and (line.price_subtotal / line.quantity) or line.price_subtotal,
142                 'quantity':line.quantity,
143                 'price':line.price_subtotal,
144                 'account_id':line.account_id.id,
145                 'product_id': line.product_id.id,
146                 'uos_id':line.uos_id.id,
147                 'account_analytic_id':line.account_analytic_id.id,
148             }
149
150     def product_id_change_unit_price_inv(self, cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context=None):
151         if context is None:
152             context = {}
153         # if the tax is already included, just return the value without calculations
154         if context.get('price_type', False) == 'tax_included':
155             return {'price_unit': price_unit,'invoice_line_tax_id': tax_id}
156         else:
157             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)
158
159     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, currency_id=False, context=None):
160         # note: will call product_id_change_unit_price_inv with context...
161
162         # Temporary trap, for bad context that came from koo:
163         # if isinstance(context, str):
164         #       print "str context:", context
165
166         ctx = (context and context.copy()) or {}
167         ctx.update({'price_type': ctx.get('price_type','tax_excluded')})
168         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, currency_id=currency_id, context=ctx)
169 account_invoice_line()
170
171 class account_invoice_tax(osv.osv):
172     _inherit = "account.invoice.tax"
173
174     def compute(self, cr, uid, invoice_id, context=None):
175         inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id)
176         line_ids = map(lambda x: x.id, inv.invoice_line)
177
178         tax_grouped = {}
179         tax_obj = self.pool.get('account.tax')
180         cur_obj = self.pool.get('res.currency')
181         cur = inv.currency_id
182         company_currency = inv.company_id.currency_id.id
183
184         for line in inv.invoice_line:
185             data = self.pool.get('account.invoice.line')._amount_line2(cr, uid, [line.id], [], [], context)[line.id]
186             for tax in data['data']:
187                 val={}
188                 val['invoice_id'] = inv.id
189                 val['name'] = tax['name']
190                 val['amount'] = tax['amount']
191                 val['manual'] = False
192                 val['sequence'] = tax['sequence']
193                 val['base'] = tax['price_unit'] * line['quantity']
194
195                 if inv.type in ('out_invoice','in_invoice'):
196                     val['base_code_id'] = tax['base_code_id']
197                     val['tax_code_id'] = tax['tax_code_id']
198                     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)
199                     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)
200                     val['account_id'] = tax['account_collected_id'] or line.account_id.id
201                 else:
202                     val['base_code_id'] = tax['ref_base_code_id']
203                     val['tax_code_id'] = tax['ref_tax_code_id']
204                     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)
205                     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)
206                     val['account_id'] = tax['account_paid_id'] or line.account_id.id
207
208                 key = (val['tax_code_id'], val['base_code_id'], val['account_id'])
209                 if not key in tax_grouped:
210                     tax_grouped[key] = val
211                 else:
212                     tax_grouped[key]['amount'] += val['amount']
213                     tax_grouped[key]['base'] += val['base']
214                     tax_grouped[key]['base_amount'] += val['base_amount']
215                     tax_grouped[key]['tax_amount'] += val['tax_amount']
216
217         for t in tax_grouped.values():
218             t['amount'] = cur_obj.round(cr, uid, cur, t['amount'])
219             t['base_amount'] = cur_obj.round(cr, uid, cur, t['base_amount'])
220             t['tax_amount'] = cur_obj.round(cr, uid, cur, t['tax_amount'])
221
222         return tax_grouped
223 account_invoice_tax()
224
225
226 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
227