[IMP] contract managemnet
[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         res = {}
45
46         cr.execute('SELECT account_id as account_id, l.invoice_id '
47                 'FROM hr_analytic_timesheet h LEFT JOIN account_analytic_line l '
48                     'ON (h.line_id=l.id) '
49                     'WHERE l.account_id = ANY(%s)', (ids,))
50         account_to_invoice_map = {}
51         for rec in cr.dictfetchall():
52             account_to_invoice_map.setdefault(rec['account_id'], []).append(rec['invoice_id'])
53
54         for account in self.browse(cr, uid, ids, context=context):
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', 'Customer Pricelist',
67             help="The product to invoice is defined on the employee form, the price will be deduced by this pricelist on the product."),
68         'amount_max': fields.float('Max. Invoice Price',
69             help="Keep empty if this contract is not limited to a total fixed price."),
70         'amount_invoiced': fields.function(_invoiced_calc, string='Invoiced Amount',
71             help="Total invoiced"),
72         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Invoice on Timesheet & Costs',
73             help="Fill this field if you plan to automatically generate invoices based " \
74             "on the costs in this analytic account: timesheets, expenses, ..." \
75             "You can configure an automatic invoice rate on analytic accounts."),
76     }
77     _defaults = {
78         'pricelist_id': lambda self, cr, uid, ctx: ctx.get('pricelist_id', False),
79     }
80     def on_change_partner_id(self, cr, uid, id, partner_id, context={}):
81         res = super(account_analytic_account, self).on_change_partner_id(cr, uid, id, partner_id, context)
82         if (not res.get('value', False)) or not partner_id:
83             return res
84         part = self.pool.get('res.partner').browse(cr, uid, partner_id)
85         pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False
86         if pricelist:
87             res['value']['pricelist_id'] = pricelist
88         return res
89
90     def set_close(self, cr, uid, ids, context=None):
91         return self.write(cr, uid, ids, {'state':'close'}, context=context)
92     
93     def set_cancel(self, cr, uid, ids, context=None):
94         return self.write(cr, uid, ids, {'state':'cancelled'}, context=context)
95     
96     def set_open(self, cr, uid, ids, context=None):
97         return self.write(cr, uid, ids, {'state':'open'}, context=context)
98       
99     def set_pending(self, cr, uid, ids, context=None):
100         return self.write(cr, uid, ids, {'state':'pending'}, context=context)
101
102 account_analytic_account()
103
104
105 class account_analytic_line(osv.osv):
106     _inherit = 'account.analytic.line'
107     _columns = {
108         'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null"),
109         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Type of Invoicing', help="It allows to set the discount while making invoice"),
110     }
111
112     def unlink(self, cursor, user, ids, context=None):
113         return super(account_analytic_line,self).unlink(cursor, user, ids,
114                 context=context)
115
116     def write(self, cr, uid, ids, vals, context=None):
117         self._check_inv(cr, uid, ids, vals)
118         return super(account_analytic_line,self).write(cr, uid, ids, vals,
119                 context=context)
120
121     def _check_inv(self, cr, uid, ids, vals):
122         select = ids
123         if isinstance(select, (int, long)):
124             select = [ids]
125         if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
126             for line in self.browse(cr, uid, select):
127                 if line.invoice_id:
128                     raise osv.except_osv(_('Error !'),
129                         _('You cannot modify an invoiced analytic line!'))
130         return True
131
132     def copy(self, cursor, user, obj_id, default=None, context=None):
133         if default is None:
134             default = {}
135         default = default.copy()
136         default.update({'invoice_id': False})
137         return super(account_analytic_line, self).copy(cursor, user, obj_id,
138                 default, context=context)
139
140 account_analytic_line()
141
142
143 class hr_analytic_timesheet(osv.osv):
144     _inherit = "hr.analytic.timesheet"
145     def on_change_account_id(self, cr, uid, ids, account_id):
146         res = {}
147         if not account_id:
148             return res
149         res.setdefault('value',{})
150         acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
151         st = acc.to_invoice.id
152         res['value']['to_invoice'] = st or False
153         if acc.state=='pending':
154             res['warning'] = {
155                 'title': 'Warning',
156                 'message': 'The analytic account is in pending state.\nYou should not work on this account !'
157             }
158         return res
159
160     def copy(self, cursor, user, obj_id, default=None, context=None):
161         if default is None:
162             default = {}
163         default = default.copy()
164         default.update({'invoice_id': False})
165         return super(hr_analytic_timesheet, self).copy(cursor, user, obj_id,
166                 default, context=context)
167
168 hr_analytic_timesheet()
169
170 class account_invoice(osv.osv):
171     _inherit = "account.invoice"
172
173     def _get_analytic_lines(self, cr, uid, id):
174         iml = super(account_invoice, self)._get_analytic_lines(cr, uid, id)
175
176         inv = self.browse(cr, uid, [id])[0]
177         if inv.type == 'in_invoice':
178             obj_analytic_account = self.pool.get('account.analytic.account')
179             for il in iml:
180                 if il['account_analytic_id']:
181                     # *-* browse (or refactor to avoid read inside the loop)
182                     to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'])[0]['to_invoice']
183                     if to_invoice:
184                         il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0]
185         return iml
186
187 account_invoice()
188
189 class account_move_line(osv.osv):
190     _inherit = "account.move.line"
191
192     def create_analytic_lines(self, cr, uid, ids, context=None):
193         res = super(account_move_line, self).create_analytic_lines(cr, uid, ids,context=context)
194         analytic_line_obj = self.pool.get('account.analytic.line')
195         for move_line in self.browse(cr, uid, ids, context=context):
196             for line in move_line.analytic_lines:
197                 toinv = line.account_id.to_invoice.id
198                 if toinv:
199                     analytic_line_obj.write(cr, uid, line.id, {'to_invoice': toinv})
200         return res
201
202 account_move_line()
203
204 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
205