[REF] hr_timesheet_invoice: moved sample invoicing rate to regular data for usability...
[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),
31         'customer_name': fields.char('Name', size=128, help="Name of 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 from hr_analytic_timesheet h left join account_analytic_line l on (h.line_id=l.id)')
49         account_to_invoice_map = {}
50         for rec in cr.dictfetchall():
51             account_to_invoice_map.setdefault(rec['account_id'], []).append(rec['invoice_id'])
52
53         for account in self.browse(cr, uid, ids, context=context):
54             invoiced = {}
55             invoice_ids = filter(None, list(set(account_to_invoice_map.get(account.id, []))))
56             for invoice in obj_invoice.browse(cr, uid, invoice_ids, context=context):
57                 res.setdefault(account.id, 0.0)
58                 res[account.id] += invoice.amount_untaxed
59         for id in ids:
60             res[id] = round(res.get(id, 0.0),2)
61
62         return res
63
64     _inherit = "account.analytic.account"
65     _columns = {
66         'pricelist_id' : fields.many2one('product.pricelist', 'Sale Pricelist'),
67         'amount_max': fields.float('Max. Invoice Price'),
68         'amount_invoiced': fields.function(_invoiced_calc, method=True, string='Invoiced Amount',
69             help="Total invoiced"),
70         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Reinvoice Costs',
71             help="Fill this field if you plan to automatically generate invoices based " \
72             "on the costs in this analytic account: timesheets, expenses, ..." \
73             "You can configure an automatic invoice rate on analytic accounts."),
74     }
75     _defaults = {
76         'pricelist_id': lambda self, cr, uid, ctx: ctx.get('pricelist_id', False),
77     }
78 account_analytic_account()
79
80
81 class account_analytic_line(osv.osv):
82     _inherit = 'account.analytic.line'
83     _columns = {
84         'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null"),
85         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Type of Invoicing', help="It allows to set the discount while making invoice"),
86     }
87
88     def unlink(self, cursor, user, ids, context=None):
89         if context is None:
90             context = {}
91         return super(account_analytic_line,self).unlink(cursor, user, ids,
92                 context=context)
93
94     def write(self, cr, uid, ids, vals, context=None):
95         if context is None:
96             context = {}
97         self._check_inv(cr, uid, ids, vals)
98         return super(account_analytic_line,self).write(cr, uid, ids, vals,
99                 context=context)
100
101     def _check_inv(self, cr, uid, ids, vals):
102         select = ids
103         if isinstance(select, (int, long)):
104             select = [ids]
105         if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
106             for line in self.browse(cr, uid, select):
107                 if line.invoice_id:
108                     raise osv.except_osv(_('Error !'),
109                         _('You can not modify an invoiced analytic line!'))
110         return True
111
112     def copy(self, cursor, user, obj_id, default=None, context=None):
113         if context is None:
114             context = {}
115         if default is None:
116             default = {}
117         default = default.copy()
118         default.update({'invoice_id': False})
119         return super(account_analytic_line, self).copy(cursor, user, obj_id,
120                 default, context=context)
121
122 account_analytic_line()
123
124
125 class hr_analytic_timesheet(osv.osv):
126     _inherit = "hr.analytic.timesheet"
127     def on_change_account_id(self, cr, uid, ids, account_id):
128         res = {}
129         if not account_id:
130             return res
131         res.setdefault('value',{})
132         acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
133         st = acc.to_invoice.id
134         res['value']['to_invoice'] = st or False
135         if acc.state=='pending':
136             res['warning'] = {
137                 'title': 'Warning',
138                 'message': 'The analytic account is in pending state.\nYou should not work on this account !'
139             }
140         return res
141
142     def copy(self, cursor, user, obj_id, default=None, context=None):
143         if context is None:
144             context = {}
145         if default is None:
146             default = {}
147         default = default.copy()
148         default.update({'invoice_id': False})
149         return super(hr_analytic_timesheet, self).copy(cursor, user, obj_id,
150                 default, context=context)
151
152 hr_analytic_timesheet()
153
154 class account_invoice(osv.osv):
155     _inherit = "account.invoice"
156
157     def _get_analytic_lines(self, cr, uid, id):
158         iml = super(account_invoice, self)._get_analytic_lines(cr, uid, id)
159
160         inv = self.browse(cr, uid, [id])[0]
161         if inv.type == 'in_invoice':
162             obj_analytic_account = self.pool.get('account.analytic.account')
163             for il in iml:
164                 if il['account_analytic_id']:
165                     to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'])[0]['to_invoice']
166                     if to_invoice:
167                         il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0]
168         return iml
169
170 account_invoice()
171
172 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
173