account.analytic.line: fix on_change_unit_amount()
[odoo/odoo.git] / addons / hr_timesheet_invoice / hr_timesheet_invoice.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 from osv import fields, osv
23
24 from tools.translate import _
25
26 class hr_timesheet_invoice_factor(osv.osv):
27     _name = "hr_timesheet_invoice.factor"
28     _description = "Invoice Rate"
29     _columns = {
30         'name': fields.char('Internal name', size=128, required=True, translate=True),
31         'customer_name': fields.char('Name', size=128, help="Label for the customer"),
32         'factor': fields.float('Discount (%)', required=True, help="Discount in percentage"),
33     }
34     _defaults = {
35         'factor': lambda *a: 0.0,
36     }
37
38 hr_timesheet_invoice_factor()
39
40
41 class account_analytic_account(osv.osv):
42     def _invoiced_calc(self, cr, uid, ids, name, arg, context=None):
43         obj_invoice = self.pool.get('account.invoice')
44         if context is None:
45             context = {}
46         res = {}
47
48         cr.execute('SELECT account_id as account_id, l.invoice_id '
49                 'FROM hr_analytic_timesheet h LEFT JOIN account_analytic_line l '
50                     'ON (h.line_id=l.id) '
51                     'WHERE l.account_id = ANY(%s)', (ids,))
52         account_to_invoice_map = {}
53         for rec in cr.dictfetchall():
54             account_to_invoice_map.setdefault(rec['account_id'], []).append(rec['invoice_id'])
55
56         for account in self.browse(cr, uid, ids, context=context):
57             invoiced = {}
58             invoice_ids = filter(None, list(set(account_to_invoice_map.get(account.id, []))))
59             for invoice in obj_invoice.browse(cr, uid, invoice_ids, context=context):
60                 res.setdefault(account.id, 0.0)
61                 res[account.id] += invoice.amount_untaxed
62         for id in ids:
63             res[id] = round(res.get(id, 0.0),2)
64
65         return res
66
67     _inherit = "account.analytic.account"
68     _columns = {
69         'pricelist_id': fields.many2one('product.pricelist', 'Sale Pricelist',
70             help="The product to invoice is defined on the employee form, the price will be deduced by this pricelist on the product."),
71         'amount_max': fields.float('Max. Invoice Price'),
72         'amount_invoiced': fields.function(_invoiced_calc, method=True, string='Invoiced Amount',
73             help="Total invoiced"),
74         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Reinvoice Costs',
75             help="Fill this field if you plan to automatically generate invoices based " \
76             "on the costs in this analytic account: timesheets, expenses, ..." \
77             "You can configure an automatic invoice rate on analytic accounts."),
78     }
79     _defaults = {
80         'pricelist_id': lambda self, cr, uid, ctx: ctx.get('pricelist_id', False),
81     }
82 account_analytic_account()
83
84
85 class account_analytic_line(osv.osv):
86     _inherit = 'account.analytic.line'
87     _columns = {
88         'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null"),
89         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Type of Invoicing', help="It allows to set the discount while making invoice"),
90     }
91
92     def unlink(self, cursor, user, ids, context=None):
93         if context is None:
94             context = {}
95         return super(account_analytic_line,self).unlink(cursor, user, ids,
96                 context=context)
97
98     def write(self, cr, uid, ids, vals, context=None):
99         if context is None:
100             context = {}
101         self._check_inv(cr, uid, ids, vals)
102         return super(account_analytic_line,self).write(cr, uid, ids, vals,
103                 context=context)
104
105     def _check_inv(self, cr, uid, ids, vals):
106         select = ids
107         if isinstance(select, (int, long)):
108             select = [ids]
109         if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
110             for line in self.browse(cr, uid, select):
111                 if line.invoice_id:
112                     raise osv.except_osv(_('Error !'),
113                         _('You can not modify an invoiced analytic line!'))
114         return True
115
116     def copy(self, cursor, user, obj_id, default=None, context=None):
117         if context is None:
118             context = {}
119         if default is None:
120             default = {}
121         default = default.copy()
122         default.update({'invoice_id': False})
123         return super(account_analytic_line, self).copy(cursor, user, obj_id,
124                 default, context=context)
125
126 account_analytic_line()
127
128
129 class hr_analytic_timesheet(osv.osv):
130     _inherit = "hr.analytic.timesheet"
131     def on_change_account_id(self, cr, uid, ids, account_id):
132         res = {}
133         if not account_id:
134             return res
135         res.setdefault('value',{})
136         acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
137         st = acc.to_invoice.id
138         res['value']['to_invoice'] = st or False
139         if acc.state=='pending':
140             res['warning'] = {
141                 'title': 'Warning',
142                 'message': 'The analytic account is in pending state.\nYou should not work on this account !'
143             }
144         return res
145
146     def copy(self, cursor, user, obj_id, default=None, context=None):
147         if context is None:
148             context = {}
149         if default is None:
150             default = {}
151         default = default.copy()
152         default.update({'invoice_id': False})
153         return super(hr_analytic_timesheet, self).copy(cursor, user, obj_id,
154                 default, context=context)
155
156 hr_analytic_timesheet()
157
158 class account_invoice(osv.osv):
159     _inherit = "account.invoice"
160
161     def _get_analytic_lines(self, cr, uid, id):
162         iml = super(account_invoice, self)._get_analytic_lines(cr, uid, id)
163
164         inv = self.browse(cr, uid, [id])[0]
165         if inv.type == 'in_invoice':
166             obj_analytic_account = self.pool.get('account.analytic.account')
167             for il in iml:
168                 if il['account_analytic_id']:
169                     # *-* browse (or refactor to avoid read inside the loop)
170                     to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'])[0]['to_invoice']
171                     if to_invoice:
172                         il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0]
173         return iml
174
175 account_invoice()
176
177 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
178