1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
24 from osv import fields, osv
25 from tools.translate import _
27 class hr_timesheet_invoice_factor(osv.osv):
28 _name = "hr_timesheet_invoice.factor"
29 _description = "Invoice Rate"
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"),
37 'factor': lambda *a: 0.0,
40 hr_timesheet_invoice_factor()
43 class account_analytic_account(osv.osv):
44 def _invoiced_calc(self, cr, uid, ids, name, arg, context=None):
45 obj_invoice = self.pool.get('account.invoice')
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'])
56 for account in self.browse(cr, uid, ids, context=context):
57 invoice_ids = filter(None, list(set(account_to_invoice_map.get(account.id, []))))
58 for invoice in obj_invoice.browse(cr, uid, invoice_ids, context=context):
59 res.setdefault(account.id, 0.0)
60 res[account.id] += invoice.amount_untaxed
62 res[id] = round(res.get(id, 0.0),2)
66 _inherit = "account.analytic.account"
68 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
69 help="The product to invoice is defined on the employee form, the price will be deducted by this pricelist on the product."),
70 'amount_max': fields.float('Max. Invoice Price',
71 help="Keep empty if this contract is not limited to a total fixed price."),
72 'amount_invoiced': fields.function(_invoiced_calc, string='Invoiced Amount',
73 help="Total invoiced"),
74 'to_invoice': fields.many2one('hr_timesheet_invoice.factor', 'Timesheet Invoicing Ratio',
75 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 sale order), you should invoice the rest on timesheet with a 80% ratio."),
78 'pricelist_id': lambda self, cr, uid, ctx: ctx.get('pricelist_id', False),
81 def on_change_partner_id(self, cr, uid, ids, partner_id, name, context=None):
82 res = super(account_analytic_account, self).on_change_partner_id(cr, uid, ids, partner_id, name, context=context)
83 part = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
84 pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False
86 res['value']['pricelist_id'] = pricelist
89 def set_close(self, cr, uid, ids, context=None):
90 self.write(cr, uid, ids, {'state': 'close'}, context=context)
91 message = _("Contract has been <b>closed</b>.")
92 self.message_post(cr, uid, ids, body=message, subtype="hr_timesheet_invoice.mt_account_closed", context=context)
95 def set_cancel(self, cr, uid, ids, context=None):
96 self.write(cr, uid, ids, {'state': 'cancelled'}, context=context)
97 message = _("Contract has been <b>canceled</b>.")
98 self.message_post(cr, uid, ids, body=message, subtype="hr_timesheet_invoice.mt_account_canceled", context=context)
101 def set_open(self, cr, uid, ids, context=None):
102 self.write(cr, uid, ids, {'state': 'open'}, context=context)
103 message = _("Contract has been <b>opened</b>.")
104 self.message_post(cr, uid, ids, body=message, context=context)
107 def set_pending(self, cr, uid, ids, context=None):
108 self.write(cr, uid, ids, {'state': 'pending'}, context=context)
109 message = _("Contract has been set as <b>pending</b>.")
110 self.message_post(cr, uid, ids, body=message, context=context)
113 account_analytic_account()
116 class account_analytic_line(osv.osv):
117 _inherit = 'account.analytic.line'
119 'invoice_id': fields.many2one('account.invoice', 'Invoice', ondelete="set null"),
120 '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."),
123 def _default_journal(self, cr, uid, context=None):
124 proxy = self.pool.get('hr.employee')
125 record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context)
127 employee = proxy.browse(cr, uid, record_ids[0], context=context)
128 return employee.journal_id and employee.journal_id.id or False
131 def _default_general_account(self, cr, uid, context=None):
132 proxy = self.pool.get('hr.employee')
133 record_ids = proxy.search(cr, uid, [('user_id', '=', uid)], context=context)
135 employee = proxy.browse(cr, uid, record_ids[0], context=context)
136 if employee.product_id and employee.product_id.property_account_income:
137 return employee.product_id.property_account_income.id
141 'journal_id' : _default_journal,
142 'general_account_id' : _default_general_account,
145 def write(self, cr, uid, ids, vals, context=None):
146 self._check_inv(cr, uid, ids, vals)
147 return super(account_analytic_line,self).write(cr, uid, ids, vals,
150 def _check_inv(self, cr, uid, ids, vals):
152 if isinstance(select, (int, long)):
154 if ( not vals.has_key('invoice_id')) or vals['invoice_id' ] == False:
155 for line in self.browse(cr, uid, select):
157 raise osv.except_osv(_('Error!'),
158 _('You cannot modify an invoiced analytic line!'))
161 def copy(self, cursor, user, obj_id, default=None, context=None):
164 default = default.copy()
165 default.update({'invoice_id': False})
166 return super(account_analytic_line, self).copy(cursor, user, obj_id,
167 default, context=context)
169 def _get_invoice_price(self, cr, uid, account, product_id, user_id, qty, context = {}):
170 pro_price_obj = self.pool.get('product.pricelist')
171 if account.pricelist_id:
172 pl = account.pricelist_id.id
173 price = pro_price_obj.price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id, context=context)[pl]
178 def invoice_cost_create(self, cr, uid, ids, data=None, context=None):
179 analytic_account_obj = self.pool.get('account.analytic.account')
180 account_payment_term_obj = self.pool.get('account.payment.term')
181 invoice_obj = self.pool.get('account.invoice')
182 product_obj = self.pool.get('product.product')
183 invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor')
184 fiscal_pos_obj = self.pool.get('account.fiscal.position')
185 product_uom_obj = self.pool.get('product.uom')
186 invoice_line_obj = self.pool.get('account.invoice.line')
194 for line in self.pool.get('account.analytic.line').browse(cr, uid, ids, context=context):
195 if line.journal_id.type not in journal_types:
196 journal_types[line.journal_id.type] = set()
197 journal_types[line.journal_id.type].add(line.account_id.id)
198 for journal_type, account_ids in journal_types.items():
199 for account in analytic_account_obj.browse(cr, uid, list(account_ids), context=context):
200 partner = account.partner_id
201 if (not partner) or not (account.pricelist_id):
202 raise osv.except_osv(_('Analytic Account incomplete !'),
203 _('Contract incomplete. Please fill in the Customer and Pricelist fields.'))
206 if partner.property_payment_term:
207 pterm_list= account_payment_term_obj.compute(cr, uid,
208 partner.property_payment_term.id, value=1,
209 date_ref=time.strftime('%Y-%m-%d'))
211 pterm_list = [line[0] for line in pterm_list]
213 date_due = pterm_list[-1]
216 'name': time.strftime('%d/%m/%Y') + ' - '+account.name,
217 'partner_id': account.partner_id.id,
218 'company_id': account.company_id.id,
219 'payment_term': partner.property_payment_term.id or False,
220 'account_id': partner.property_account_receivable.id,
221 'currency_id': account.pricelist_id.currency_id.id,
222 'date_due': date_due,
223 'fiscal_position': account.partner_id.property_account_position.id
226 context2 = context.copy()
227 context2['lang'] = partner.lang
228 # set company_id in context, so the correct default journal will be selected
229 context2['force_company'] = curr_invoice['company_id']
230 # set force_company in context so the correct product properties are selected (eg. income account)
231 context2['company_id'] = curr_invoice['company_id']
233 last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context2)
234 invoices.append(last_invoice)
236 cr.execute("""SELECT product_id, user_id, to_invoice, sum(unit_amount), product_uom_id
237 FROM account_analytic_line as line LEFT JOIN account_analytic_journal journal ON (line.journal_id = journal.id)
238 WHERE account_id = %s
239 AND line.id IN %s AND journal.type = %s AND to_invoice IS NOT NULL
240 GROUP BY product_id, user_id, to_invoice, product_uom_id""", (account.id, tuple(ids), journal_type))
242 for product_id, user_id, factor_id, qty, uom in cr.fetchall():
243 if data.get('product'):
244 product_id = data['product'][0]
245 product = product_obj.browse(cr, uid, product_id, context=context2)
247 raise osv.except_osv(_('Error!'), _('There is no product defined. Please select one or force the product through the wizard.'))
248 factor = invoice_factor_obj.browse(cr, uid, factor_id, context=context2)
249 factor_name = product_obj.name_get(cr, uid, [product_id], context=context2)[0][1]
250 if factor.customer_name:
251 factor_name += ' - ' + factor.customer_name
254 ctx.update({'uom':uom})
256 price = self._get_invoice_price(cr, uid, account, product_id, user_id, qty, ctx)
258 general_account = product.product_tmpl_id.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)
266 'discount':factor.factor,
267 'invoice_line_tax_id': [(6,0,tax )],
268 'invoice_id': last_invoice,
270 'product_id': product_id,
271 'invoice_line_tax_id': [(6,0,tax)],
273 'account_id': general_account.id,
274 'account_analytic_id': account.id,
280 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))
282 line_ids = cr.dictfetchall()
284 for line in line_ids:
285 # set invoice_line_note
287 if data.get('date', False):
288 details.append(line['date'])
289 if data.get('time', False):
290 if line['product_uom_id']:
291 details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name))
293 details.append("%s" % (line['unit_amount'], ))
294 if data.get('name', False):
295 details.append(line['name'])
296 note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
299 curr_line['name'] += "\n" + ("\n".join(map(lambda x: unicode(x) or '',note)))
300 invoice_line_obj.create(cr, uid, curr_line, context=context)
301 cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids)))
303 invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context)
306 account_analytic_line()
309 class hr_analytic_timesheet(osv.osv):
310 _inherit = "hr.analytic.timesheet"
311 def on_change_account_id(self, cr, uid, ids, account_id, user_id=False):
315 res.setdefault('value',{})
316 acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
317 st = acc.to_invoice.id
318 res['value']['to_invoice'] = st or False
319 if acc.state=='pending':
322 'message': 'The analytic account is in pending state.\nYou should not work on this account !'
326 def copy(self, cursor, user, obj_id, default=None, context=None):
329 default = default.copy()
330 default.update({'invoice_id': False})
331 return super(hr_analytic_timesheet, self).copy(cursor, user, obj_id,
332 default, context=context)
334 hr_analytic_timesheet()
337 class account_invoice(osv.osv):
338 _inherit = "account.invoice"
340 def _get_analytic_lines(self, cr, uid, id, context=None):
341 iml = super(account_invoice, self)._get_analytic_lines(cr, uid, id, context=context)
343 inv = self.browse(cr, uid, [id], context=context)[0]
344 if inv.type == 'in_invoice':
345 obj_analytic_account = self.pool.get('account.analytic.account')
347 if il['account_analytic_id']:
348 # *-* browse (or refactor to avoid read inside the loop)
349 to_invoice = obj_analytic_account.read(cr, uid, [il['account_analytic_id']], ['to_invoice'], context=context)[0]['to_invoice']
351 il['analytic_lines'][0][2]['to_invoice'] = to_invoice[0]
357 class account_move_line(osv.osv):
358 _inherit = "account.move.line"
360 def create_analytic_lines(self, cr, uid, ids, context=None):
361 res = super(account_move_line, self).create_analytic_lines(cr, uid, ids,context=context)
362 analytic_line_obj = self.pool.get('account.analytic.line')
363 for move_line in self.browse(cr, uid, ids, context=context):
364 #For customer invoice, link analytic line to the invoice so it is not proposed for invoicing in Bill Tasks Work
365 invoice_id = move_line.invoice and move_line.invoice.type in ('out_invoice','out_refund') and move_line.invoice.id or False
366 for line in move_line.analytic_lines:
367 analytic_line_obj.write(cr, uid, line.id, {
368 'invoice_id': invoice_id,
369 'to_invoice': line.account_id.to_invoice and line.account_id.to_invoice.id or False
375 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: