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