~serpentcs/openobject-addons/trunk-webkit-reports-addons

« back to all changes in this revision

Viewing changes to hr_timesheet_invoice/hr_timesheet_invoice.py

  • Committer: Hemangini Patel
  • Date: 2013-10-16 10:19:06 UTC
  • Revision ID: h.patel.serpentcs@gmail.com-20131016101906-9bqrmodzzepjw5zs
[ADD] Added hr_timesheet_invoice module with webkit reports.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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', size=128, required=True, translate=True),
 
33
        'customer_name': fields.char('Name', size=128, 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
        part = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
 
80
        pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False
 
81
        if pricelist:
 
82
            res['value']['pricelist_id'] = pricelist
 
83
        return res
 
84
 
 
85
    def set_close(self, cr, uid, ids, context=None):
 
86
        return self.write(cr, uid, ids, {'state': 'close'}, context=context)
 
87
 
 
88
    def set_cancel(self, cr, uid, ids, context=None):
 
89
        return self.write(cr, uid, ids, {'state': 'cancelled'}, context=context)
 
90
 
 
91
    def set_open(self, cr, uid, ids, context=None):
 
92
        return self.write(cr, uid, ids, {'state': 'open'}, context=context)
 
93
 
 
94
    def set_pending(self, cr, uid, ids, context=None):
 
95
        return self.write(cr, uid, ids, {'state': 'pending'}, context=context)
 
96
 
 
97
 
 
98
class account_analytic_line(osv.osv):
 
99
    _inherit = 'account.analytic.line'
 
100
    _columns = {
 
101
        'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null"),
 
102
        '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."),
 
103
    }
 
104
 
 
105
    def _default_journal(self, cr, uid, context=None):
 
106
        proxy = self.pool.get('hr.employee')
 
107
        record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context)
 
108
        if record_ids:
 
109
            employee = proxy.browse(cr, uid, record_ids[0], context=context)
 
110
            return employee.journal_id and employee.journal_id.id or False
 
111
        return False
 
112
 
 
113
    def _default_general_account(self, cr, uid, context=None):
 
114
        proxy = self.pool.get('hr.employee')
 
115
        record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context)
 
116
        if record_ids:
 
117
            employee = proxy.browse(cr, uid, record_ids[0], context=context)
 
118
            if employee.product_id and employee.product_id.property_account_income:
 
119
                return employee.product_id.property_account_income.id
 
120
        return False
 
121
 
 
122
    _defaults = {
 
123
        'journal_id' : _default_journal,
 
124
        'general_account_id' : _default_general_account,
 
125
    }
 
126
 
 
127
    def write(self, cr, uid, ids, vals, context=None):
 
128
        self._check_inv(cr, uid, ids, vals)
 
129
        return super(account_analytic_line,self).write(cr, uid, ids, vals,
 
130
                context=context)
 
131
 
 
132
    def _check_inv(self, cr, uid, ids, vals):
 
133
        select = ids
 
134
        if isinstance(select, (int, long)):
 
135
            select = [ids]
 
136
        if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
 
137
            for line in self.browse(cr, uid, select):
 
138
                if line.invoice_id:
 
139
                    raise osv.except_osv(_('Error!'),
 
140
                        _('You cannot modify an invoiced analytic line!'))
 
141
        return True
 
142
 
 
143
    def copy(self, cursor, user, obj_id, default=None, context=None):
 
144
        if default is None:
 
145
            default = {}
 
146
        default = default.copy()
 
147
        default.update({'invoice_id': False})
 
148
        return super(account_analytic_line, self).copy(cursor, user, obj_id,
 
149
                default, context=context)
 
150
 
 
151
    def _get_invoice_price(self, cr, uid, account, product_id, user_id, qty, context = {}):
 
152
        pro_price_obj = self.pool.get('product.pricelist')
 
153
        if account.pricelist_id:
 
154
            pl = account.pricelist_id.id
 
155
            price = pro_price_obj.price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id, context=context)[pl]
 
156
        else:
 
157
            price = 0.0
 
158
        return price
 
159
 
 
160
    def invoice_cost_create(self, cr, uid, ids, data=None, context=None):
 
161
        analytic_account_obj = self.pool.get('account.analytic.account')
 
162
        account_payment_term_obj = self.pool.get('account.payment.term')
 
163
        invoice_obj = self.pool.get('account.invoice')
 
164
        product_obj = self.pool.get('product.product')
 
165
        invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor')
 
166
        fiscal_pos_obj = self.pool.get('account.fiscal.position')
 
167
        product_uom_obj = self.pool.get('product.uom')
 
168
        invoice_line_obj = self.pool.get('account.invoice.line')
 
169
        invoices = []
 
170
        if context is None:
 
171
            context = {}
 
172
        if data is None:
 
173
            data = {}
 
174
 
 
175
        journal_types = {}
 
176
 
 
177
        # prepare for iteration on journal and accounts
 
178
        for line in self.pool.get('account.analytic.line').browse(cr, uid, ids, context=context):
 
179
            if line.journal_id.type not in journal_types:
 
180
                journal_types[line.journal_id.type] = set()
 
181
            journal_types[line.journal_id.type].add(line.account_id.id)
 
182
        for journal_type, account_ids in journal_types.items():
 
183
            for account in analytic_account_obj.browse(cr, uid, list(account_ids), context=context):
 
184
                partner = account.partner_id
 
185
                if (not partner) or not (account.pricelist_id):
 
186
                    raise osv.except_osv(_('Analytic Account Incomplete!'),
 
187
                            _('Contract incomplete. Please fill in the Customer and Pricelist fields.'))
 
188
 
 
189
                date_due = False
 
190
                if partner.property_payment_term:
 
191
                    pterm_list= account_payment_term_obj.compute(cr, uid,
 
192
                            partner.property_payment_term.id, value=1,
 
193
                            date_ref=time.strftime('%Y-%m-%d'))
 
194
                    if pterm_list:
 
195
                        pterm_list = [line[0] for line in pterm_list]
 
196
                        pterm_list.sort()
 
197
                        date_due = pterm_list[-1]
 
198
 
 
199
                curr_invoice = {
 
200
                    'name': time.strftime('%d/%m/%Y') + ' - '+account.name,
 
201
                    'partner_id': account.partner_id.id,
 
202
                    'company_id': account.company_id.id,
 
203
                    'payment_term': partner.property_payment_term.id or False,
 
204
                    'account_id': partner.property_account_receivable.id,
 
205
                    'currency_id': account.pricelist_id.currency_id.id,
 
206
                    'date_due': date_due,
 
207
                    'fiscal_position': account.partner_id.property_account_position.id
 
208
                }
 
209
                context2 = context.copy()
 
210
                context2['lang'] = partner.lang
 
211
                # set company_id in context, so the correct default journal will be selected
 
212
                context2['force_company'] = curr_invoice['company_id']
 
213
                # set force_company in context so the correct product properties are selected (eg. income account)
 
214
                context2['company_id'] = curr_invoice['company_id']
 
215
 
 
216
                last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context2)
 
217
                invoices.append(last_invoice)
 
218
 
 
219
                cr.execute("""SELECT product_id, user_id, to_invoice, sum(amount), sum(unit_amount), product_uom_id
 
220
                        FROM account_analytic_line as line LEFT JOIN account_analytic_journal journal ON (line.journal_id = journal.id)
 
221
                        WHERE account_id = %s
 
222
                            AND line.id IN %s AND journal.type = %s AND to_invoice IS NOT NULL
 
223
                        GROUP BY product_id, user_id, to_invoice, product_uom_id""", (account.id, tuple(ids), journal_type))
 
224
 
 
225
                for product_id, user_id, factor_id, total_price, qty, uom in cr.fetchall():
 
226
                    context2.update({'uom': uom})
 
227
 
 
228
                    if data.get('product'):
 
229
                        # force product, use its public price
 
230
                        product_id = data['product'][0]
 
231
                        unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, context2)
 
232
                    elif journal_type == 'general' and product_id:
 
233
                        # timesheets, use sale price
 
234
                        unit_price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, context2)
 
235
                    else:
 
236
                        # expenses, using price from amount field
 
237
                        unit_price = total_price*-1.0 / qty
 
238
 
 
239
                    factor = invoice_factor_obj.browse(cr, uid, factor_id, context=context2)
 
240
                    # factor_name = factor.customer_name and line_name + ' - ' + factor.customer_name or line_name
 
241
                    factor_name = factor.customer_name
 
242
                    curr_line = {
 
243
                        'price_unit': unit_price,
 
244
                        'quantity': qty,
 
245
                        'product_id': product_id or False,
 
246
                        'discount': factor.factor,
 
247
                        'invoice_id': last_invoice,
 
248
                        'name': factor_name,
 
249
                        'uos_id': uom,
 
250
                        'account_analytic_id': account.id,
 
251
                    }
 
252
                    product = product_obj.browse(cr, uid, product_id, context=context2)
 
253
                    if product:
 
254
                        factor_name = product_obj.name_get(cr, uid, [product_id], context=context2)[0][1]
 
255
                        if factor.customer_name:
 
256
                            factor_name += ' - ' + factor.customer_name
 
257
 
 
258
                        general_account = product.property_account_income or product.categ_id.property_account_income_categ
 
259
                        if not general_account:
 
260
                            raise osv.except_osv(_("Configuration Error!"), _("Please define income account for product '%s'.") % product.name)
 
261
                        taxes = product.taxes_id or general_account.tax_ids
 
262
                        tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
 
263
                        curr_line.update({
 
264
                            'invoice_line_tax_id': [(6,0,tax )],
 
265
                            'name': factor_name,
 
266
                            'invoice_line_tax_id': [(6,0,tax)],
 
267
                            'account_id': general_account.id,
 
268
                        })
 
269
                    #
 
270
                    # Compute for lines
 
271
                    #
 
272
                    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))
 
273
 
 
274
                    line_ids = cr.dictfetchall()
 
275
                    note = []
 
276
                    for line in line_ids:
 
277
                        # set invoice_line_note
 
278
                        details = []
 
279
                        if data.get('date', False):
 
280
                            details.append(line['date'])
 
281
                        if data.get('time', False):
 
282
                            if line['product_uom_id']:
 
283
                                details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name))
 
284
                            else:
 
285
                                details.append("%s" % (line['unit_amount'], ))
 
286
                        if data.get('name', False):
 
287
                            details.append(line['name'])
 
288
                        note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
 
289
                    if note:
 
290
                        curr_line['name'] += "\n" + ("\n".join(map(lambda x: unicode(x) or '',note)))
 
291
                    invoice_line_obj.create(cr, uid, curr_line, context=context)
 
292
                    cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids)))
 
293
 
 
294
                invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context)
 
295
        return invoices
 
296
 
 
297
 
 
298
 
 
299
class hr_analytic_timesheet(osv.osv):
 
300
    _inherit = "hr.analytic.timesheet"
 
301
    def on_change_account_id(self, cr, uid, ids, account_id, user_id=False):
 
302
        res = {}
 
303
        if not account_id:
 
304
            return res
 
305
        res.setdefault('value',{})
 
306
        acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
 
307
        st = acc.to_invoice.id
 
308
        res['value']['to_invoice'] = st or False
 
309
        if acc.state=='pending':
 
310
            res['warning'] = {
 
311
                'title': 'Warning',
 
312
                'message': 'The analytic account is in pending state.\nYou should not work on this account !'
 
313
            }
 
314
        return res
 
315
 
 
316
    def copy(self, cursor, user, obj_id, default=None, context=None):
 
317
        if default is None:
 
318
            default = {}
 
319
        default = default.copy()
 
320
        default.update({'invoice_id': False})
 
321
        return super(hr_analytic_timesheet, self).copy(cursor, user, obj_id,
 
322
                default, context=context)
 
323
 
 
324
 
 
325
 
 
326
class account_invoice(osv.osv):
 
327
    _inherit = "account.invoice"
 
328
 
 
329
    def _get_analytic_lines(self, cr, uid, id, context=None):
 
330
        iml = super(account_invoice, self)._get_analytic_lines(cr, uid, id, context=context)
 
331
 
 
332
        inv = self.browse(cr, uid, [id], context=context)[0]
 
333
        if inv.type == 'in_invoice':
 
334
            obj_analytic_account = self.pool.get('account.analytic.account')
 
335
            for il in iml:
 
336
                if il['account_analytic_id']:
 
337
                    # *-* browse (or refactor to avoid read inside the loop)
 
338
                    to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'], context=context)[0]['to_invoice']
 
339
                    if to_invoice:
 
340
                        il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0]
 
341
        return iml
 
342
 
 
343
 
 
344
 
 
345
class account_move_line(osv.osv):
 
346
    _inherit = "account.move.line"
 
347
 
 
348
    def create_analytic_lines(self, cr, uid, ids, context=None):
 
349
        res = super(account_move_line, self).create_analytic_lines(cr, uid, ids,context=context)
 
350
        analytic_line_obj = self.pool.get('account.analytic.line')
 
351
        for move_line in self.browse(cr, uid, ids, context=context):
 
352
            #For customer invoice, link analytic line to the invoice so it is not proposed for invoicing in Bill Tasks Work
 
353
            invoice_id = move_line.invoice and move_line.invoice.type in ('out_invoice','out_refund') and move_line.invoice.id or False
 
354
            for line in move_line.analytic_lines:
 
355
                analytic_line_obj.write(cr, uid, line.id, {
 
356
                    'invoice_id': invoice_id,
 
357
                    'to_invoice': line.account_id.to_invoice and line.account_id.to_invoice.id or False
 
358
                    }, context=context)
 
359
        return res
 
360
 
 
361
 
 
362
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: