ec8c89dbe6454dc5d712694df27d993a6e11e2f9
[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 import time
23
24 from openerp.osv import fields, osv
25 from openerp.tools.translate import _
26
27 class hr_timesheet_invoice_factor(osv.osv):
28     _name = "hr_timesheet_invoice.factor"
29     _description = "Invoice Rate"
30     _order = 'factor'
31     _columns = {
32         'name': fields.char('Internal Name', required=True, translate=True),
33         'customer_name': fields.char('Name', help="Label for the customer"),
34         'factor': fields.float('Discount (%)', required=True, help="Discount in percentage"),
35     }
36     _defaults = {
37         'factor': lambda *a: 0.0,
38     }
39
40
41
42 class account_analytic_account(osv.osv):
43     def _invoiced_calc(self, cr, uid, ids, name, arg, context=None):
44         obj_invoice = self.pool.get('account.invoice')
45         res = {}
46
47         cr.execute('SELECT account_id as account_id, l.invoice_id '
48                 'FROM hr_analytic_timesheet h LEFT JOIN account_analytic_line l '
49                     'ON (h.line_id=l.id) '
50                     'WHERE l.account_id = ANY(%s)', (ids,))
51         account_to_invoice_map = {}
52         for rec in cr.dictfetchall():
53             account_to_invoice_map.setdefault(rec['account_id'], []).append(rec['invoice_id'])
54
55         for account in self.browse(cr, uid, ids, context=context):
56             invoice_ids = filter(None, list(set(account_to_invoice_map.get(account.id, []))))
57             for invoice in obj_invoice.browse(cr, uid, invoice_ids, context=context):
58                 res.setdefault(account.id, 0.0)
59                 res[account.id] += invoice.amount_untaxed
60         for id in ids:
61             res[id] = round(res.get(id, 0.0),2)
62
63         return res
64
65     _inherit = "account.analytic.account"
66     _columns = {
67         'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
68             help="The product to invoice is defined on the employee form, the price will be deducted by this pricelist on the product."),
69         'amount_max': fields.float('Max. Invoice Price',
70             help="Keep empty if this contract is not limited to a total fixed price."),
71         'amount_invoiced': fields.function(_invoiced_calc, string='Invoiced Amount',
72             help="Total invoiced"),
73         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Timesheet Invoicing Ratio',
74             help="You usually invoice 100% of the timesheets. But if you mix fixed price and timesheet invoicing, you may use another ratio. For instance, if you do a 20% advance invoice (fixed price, based on a sales order), you should invoice the rest on timesheet with a 80% ratio."),
75     }
76
77     def on_change_partner_id(self, cr, uid, ids, partner_id, name, context=None):
78         res = super(account_analytic_account, self).on_change_partner_id(cr, uid, ids, partner_id, name, context=context)
79         if partner_id:
80             part = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
81             pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False
82             if pricelist:
83                 res['value']['pricelist_id'] = pricelist
84         return res
85
86     def set_close(self, cr, uid, ids, context=None):
87         return self.write(cr, uid, ids, {'state': 'close'}, context=context)
88
89     def set_cancel(self, cr, uid, ids, context=None):
90         return self.write(cr, uid, ids, {'state': 'cancelled'}, context=context)
91
92     def set_open(self, cr, uid, ids, context=None):
93         return self.write(cr, uid, ids, {'state': 'open'}, context=context)
94
95     def set_pending(self, cr, uid, ids, context=None):
96         return self.write(cr, uid, ids, {'state': 'pending'}, context=context)
97
98
99 class account_analytic_line(osv.osv):
100     _inherit = 'account.analytic.line'
101     _columns = {
102         'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null", copy=False),
103         'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Invoiceable', help="It allows to set the discount while making invoice, keep empty if the activities should not be invoiced."),
104     }
105
106     def _default_journal(self, cr, uid, context=None):
107         proxy = self.pool.get('hr.employee')
108         record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context)
109         if record_ids:
110             employee = proxy.browse(cr, uid, record_ids[0], context=context)
111             return employee.journal_id and employee.journal_id.id or False
112         return False
113
114     def _default_general_account(self, cr, uid, context=None):
115         proxy = self.pool.get('hr.employee')
116         record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context)
117         if record_ids:
118             employee = proxy.browse(cr, uid, record_ids[0], context=context)
119             if employee.product_id and employee.product_id.property_account_income:
120                 return employee.product_id.property_account_income.id
121         return False
122
123     _defaults = {
124         'journal_id' : _default_journal,
125         'general_account_id' : _default_general_account,
126     }
127
128     def write(self, cr, uid, ids, vals, context=None):
129         self._check_inv(cr, uid, ids, vals)
130         return super(account_analytic_line,self).write(cr, uid, ids, vals,
131                 context=context)
132
133     def _check_inv(self, cr, uid, ids, vals):
134         select = ids
135         if isinstance(select, (int, long)):
136             select = [ids]
137         if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
138             for line in self.browse(cr, uid, select):
139                 if line.invoice_id:
140                     raise osv.except_osv(_('Error!'),
141                         _('You cannot modify an invoiced analytic line!'))
142         return True
143
144     def _get_invoice_price(self, cr, uid, account, product_id, user_id, qty, context = {}):
145         pro_price_obj = self.pool.get('product.pricelist')
146         if account.pricelist_id:
147             pl = account.pricelist_id.id
148             price = pro_price_obj.price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id, context=context)[pl]
149         else:
150             price = 0.0
151         return price
152
153     def invoice_cost_create(self, cr, uid, ids, data=None, context=None):
154         analytic_account_obj = self.pool.get('account.analytic.account')
155         account_payment_term_obj = self.pool.get('account.payment.term')
156         invoice_obj = self.pool.get('account.invoice')
157         product_obj = self.pool.get('product.product')
158         invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor')
159         fiscal_pos_obj = self.pool.get('account.fiscal.position')
160         product_uom_obj = self.pool.get('product.uom')
161         invoice_line_obj = self.pool.get('account.invoice.line')
162         invoices = []
163         if context is None:
164             context = {}
165         if data is None:
166             data = {}
167
168         journal_types = {}
169
170         # prepare for iteration on journal and accounts
171         for line in self.pool.get('account.analytic.line').browse(cr, uid, ids, context=context):
172             if line.journal_id.type not in journal_types:
173                 journal_types[line.journal_id.type] = set()
174             journal_types[line.journal_id.type].add(line.account_id.id)
175         for journal_type, account_ids in journal_types.items():
176             for account in analytic_account_obj.browse(cr, uid, list(account_ids), context=context):
177                 partner = account.partner_id
178                 if (not partner) or not (account.pricelist_id):
179                     raise osv.except_osv(_('Analytic Account Incomplete!'),
180                             _('Contract incomplete. Please fill in the Customer and Pricelist fields.'))
181
182                 date_due = False
183                 if partner.property_payment_term:
184                     pterm_list= account_payment_term_obj.compute(cr, uid,
185                             partner.property_payment_term.id, value=1,
186                             date_ref=time.strftime('%Y-%m-%d'))
187                     if pterm_list:
188                         pterm_list = [line[0] for line in pterm_list]
189                         pterm_list.sort()
190                         date_due = pterm_list[-1]
191
192                 curr_invoice = {
193                     'name': time.strftime('%d/%m/%Y') + ' - '+account.name,
194                     'partner_id': account.partner_id.id,
195                     'company_id': account.company_id.id,
196                     'payment_term': partner.property_payment_term.id or False,
197                     'account_id': partner.property_account_receivable.id,
198                     'currency_id': account.pricelist_id.currency_id.id,
199                     'date_due': date_due,
200                     'fiscal_position': account.partner_id.property_account_position.id
201                 }
202                 context2 = context.copy()
203                 context2['lang'] = partner.lang
204                 # set company_id in context, so the correct default journal will be selected
205                 context2['force_company'] = curr_invoice['company_id']
206                 # set force_company in context so the correct product properties are selected (eg. income account)
207                 context2['company_id'] = curr_invoice['company_id']
208
209                 last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context2)
210                 invoices.append(last_invoice)
211
212                 cr.execute("""SELECT product_id, user_id, to_invoice, sum(amount), sum(unit_amount), product_uom_id
213                         FROM account_analytic_line as line LEFT JOIN account_analytic_journal journal ON (line.journal_id = journal.id)
214                         WHERE account_id = %s
215                             AND line.id IN %s AND journal.type = %s AND to_invoice IS NOT NULL
216                         GROUP BY product_id, user_id, to_invoice, product_uom_id""", (account.id, tuple(ids), journal_type))
217
218                 for product_id, user_id, factor_id, total_price, qty, uom in cr.fetchall():
219                     context2.update({'uom': uom})
220
221                     if data.get('product'):
222                         # force product, use its public price
223                         product_id = data['product'][0]
224                         unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, context2)
225                     elif journal_type == 'general' and product_id:
226                         # timesheets, use sale price
227                         unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, context2)
228                     else:
229                         # expenses, using price from amount field
230                         unit_price = total_price*-1.0 / qty
231
232                     factor = invoice_factor_obj.browse(cr, uid, factor_id, context=context2)
233                     # factor_name = factor.customer_name and line_name + ' - ' + factor.customer_name or line_name
234                     factor_name = factor.customer_name
235                     curr_line = {
236                         'price_unit': unit_price,
237                         'quantity': qty,
238                         'product_id': product_id or False,
239                         'discount': factor.factor,
240                         'invoice_id': last_invoice,
241                         'name': factor_name,
242                         'uos_id': uom,
243                         'account_analytic_id': account.id,
244                     }
245                     product = product_obj.browse(cr, uid, product_id, context=context2)
246                     if product:
247                         factor_name = product_obj.name_get(cr, uid, [product_id], context=context2)[0][1]
248                         if factor.customer_name:
249                             factor_name += ' - ' + factor.customer_name
250
251                         general_account = product.property_account_income or product.categ_id.property_account_income_categ
252                         if not general_account:
253                             raise osv.except_osv(_("Configuration Error!"), _("Please define income account for product '%s'.") % product.name)
254                         taxes = product.taxes_id or general_account.tax_ids
255                         tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
256                         curr_line.update({
257                             'invoice_line_tax_id': [(6,0,tax )],
258                             'name': factor_name,
259                             'invoice_line_tax_id': [(6,0,tax)],
260                             'account_id': general_account.id,
261                         })
262                     #
263                     # Compute for lines
264                     #
265                     cr.execute("SELECT * FROM account_analytic_line WHERE account_id = %s and id IN %s AND product_id=%s and to_invoice=%s ORDER BY account_analytic_line.date", (account.id, tuple(ids), product_id, factor_id))
266
267                     line_ids = cr.dictfetchall()
268                     note = []
269                     for line in line_ids:
270                         # set invoice_line_note
271                         details = []
272                         if data.get('date', False):
273                             details.append(line['date'])
274                         if data.get('time', False):
275                             if line['product_uom_id']:
276                                 details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name))
277                             else:
278                                 details.append("%s" % (line['unit_amount'], ))
279                         if data.get('name', False):
280                             details.append(line['name'])
281                         note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
282                     if note:
283                         curr_line['name'] += "\n" + ("\n".join(map(lambda x: unicode(x) or '',note)))
284                     invoice_line_obj.create(cr, uid, curr_line, context=context)
285                     cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids)))
286                     self.invalidate_cache(cr, uid, ['invoice_id'], ids, context=context)
287
288                 invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context)
289         return invoices
290
291
292
293 class hr_analytic_timesheet(osv.osv):
294     _inherit = "hr.analytic.timesheet"
295     def on_change_account_id(self, cr, uid, ids, account_id, user_id=False):
296         res = {}
297         if not account_id:
298             return res
299         res.setdefault('value',{})
300         acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
301         st = acc.to_invoice.id
302         res['value']['to_invoice'] = st or False
303         if acc.state=='pending':
304             res['warning'] = {
305                 'title': 'Warning',
306                 'message': 'The analytic account is in pending state.\nYou should not work on this account !'
307             }
308         return res
309
310 class account_invoice(osv.osv):
311     _inherit = "account.invoice"
312
313     def _get_analytic_lines(self, cr, uid, ids, context=None):
314         iml = super(account_invoice, self)._get_analytic_lines(cr, uid, ids, context=context)
315
316         inv = self.browse(cr, uid, ids, context=context)[0]
317         if inv.type == 'in_invoice':
318             obj_analytic_account = self.pool.get('account.analytic.account')
319             for il in iml:
320                 if il['account_analytic_id']:
321                     # *-* browse (or refactor to avoid read inside the loop)
322                     to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'], context=context)[0]['to_invoice']
323                     if to_invoice:
324                         il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0]
325         return iml
326
327
328
329 class account_move_line(osv.osv):
330     _inherit = "account.move.line"
331
332     def create_analytic_lines(self, cr, uid, ids, context=None):
333         res = super(account_move_line, self).create_analytic_lines(cr, uid, ids,context=context)
334         analytic_line_obj = self.pool.get('account.analytic.line')
335         for move_line in self.browse(cr, uid, ids, context=context):
336             #For customer invoice, link analytic line to the invoice so it is not proposed for invoicing in Bill Tasks Work
337             invoice_id = move_line.invoice and move_line.invoice.type in ('out_invoice','out_refund') and move_line.invoice.id or False
338             for line in move_line.analytic_lines:
339                 analytic_line_obj.write(cr, uid, line.id, {
340                     'invoice_id': invoice_id,
341                     'to_invoice': line.account_id.to_invoice and line.account_id.to_invoice.id or False
342                     }, context=context)
343         return res
344
345
346 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: