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 osv, fields
25 from tools.translate import _
27 ## Create an invoice based on selected timesheet lines
30 class account_analytic_line(osv.osv):
31 _inherit = "account.analytic.line"
39 # 'product': many2one id
41 def invoice_cost_create(self, cr, uid, ids, data={}, context=None):
42 analytic_account_obj = self.pool.get('account.analytic.account')
43 res_partner_obj = self.pool.get('res.partner')
44 account_payment_term_obj = self.pool.get('account.payment.term')
45 invoice_obj = self.pool.get('account.invoice')
46 product_obj = self.pool.get('product.product')
47 invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor')
48 pro_price_obj = self.pool.get('product.pricelist')
49 fiscal_pos_obj = self.pool.get('account.fiscal.position')
50 product_uom_obj = self.pool.get('product.uom')
51 invoice_line_obj = self.pool.get('account.invoice.line')
57 for line in self.pool.get('account.analytic.line').browse(cr, uid, ids, context=context):
58 account_ids[line.account_id.id] = True
60 account_ids = account_ids.keys() #data['accounts']
61 for account in analytic_account_obj.browse(cr, uid, account_ids, context=context):
62 partner = account.partner_id
63 if (not partner) or not (account.pricelist_id):
64 raise osv.except_osv(_('Analytic Account incomplete'),
65 _('Please fill in the Partner or Customer and Sale Pricelist fields in the Analytic Account:\n%s') % (account.name,))
70 if partner.property_payment_term:
71 pterm_list= account_payment_term_obj.compute(cr, uid,
72 partner.property_payment_term.id, value=1,
73 date_ref=time.strftime('%Y-%m-%d'))
75 pterm_list = [line[0] for line in pterm_list]
77 date_due = pterm_list[-1]
80 'name': time.strftime('%d/%m/%Y')+' - '+account.name,
81 'partner_id': account.partner_id.id,
82 'payment_term': partner.property_payment_term.id or False,
83 'account_id': partner.property_account_receivable.id,
84 'currency_id': account.pricelist_id.currency_id.id,
86 'fiscal_position': account.partner_id.property_account_position.id
88 last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context)
89 invoices.append(last_invoice)
91 context2 = context.copy()
92 context2['lang'] = partner.lang
93 cr.execute("SELECT product_id, to_invoice, sum(unit_amount), product_uom_id " \
94 "FROM account_analytic_line as line " \
95 "WHERE account_id = %s " \
96 "AND id IN %s AND to_invoice IS NOT NULL " \
97 "GROUP BY product_id,to_invoice,product_uom_id", (account.id, tuple(ids),))
99 for product_id, factor_id, qty, uom in cr.fetchall():
100 product = product_obj.browse(cr, uid, product_id, context2)
102 raise osv.except_osv(_('Error'), _('At least one line has no product !'))
104 factor = invoice_factor_obj.browse(cr, uid, factor_id, context2)
105 if not data.get('product', False):
106 if factor.customer_name:
107 factor_name = product.name+' - '+factor.customer_name
109 factor_name = product.name
111 data['product'] = data['product'][0]
112 factor_name = product_obj.name_get(cr, uid, [data['product']], context=context)[0][1]
115 ctx.update({'uom':uom})
116 if account.pricelist_id:
117 pl = account.pricelist_id.id
118 price = pro_price_obj.price_get(cr,uid,[pl], data.get('product', False) or product_id, qty or 1.0, account.partner_id.id, context=ctx)[pl]
122 taxes = product.taxes_id
123 tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
124 account_id = product.product_tmpl_id.property_account_income.id or product.categ_id.property_account_income_categ.id
126 raise osv.except_osv(_("Configuration Error"), _("No income account defined for product '%s'") % product.name)
130 'discount':factor.factor,
131 'invoice_line_tax_id': [(6,0,tax )],
132 'invoice_id': last_invoice,
134 'product_id': data.get('product',product_id),
135 'invoice_line_tax_id': [(6,0,tax)],
137 'account_id': account_id,
138 'account_analytic_id': account.id,
144 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))
146 line_ids = cr.dictfetchall()
148 for line in line_ids:
149 # set invoice_line_note
151 if data.get('date', False):
152 details.append(line['date'])
153 if data.get('time', False):
154 if line['product_uom_id']:
155 details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name))
157 details.append("%s" % (line['unit_amount'], ))
158 if data.get('name', False):
159 details.append(line['name'])
160 note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
162 curr_line['note'] = "\n".join(map(lambda x: unicode(x) or '',note))
163 invoice_line_obj.create(cr, uid, curr_line, context=context)
164 cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids)))
166 invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context)
170 # TODO: check unit of measure !!!
173 class hr_timesheet_invoice_create(osv.osv_memory):
175 _name = 'hr.timesheet.invoice.create'
176 _description = 'Create invoice from timesheet'
178 'date': fields.boolean('Date', help='The real date of each work will be displayed on the invoice'),
179 'time': fields.boolean('Time spent', help='The time of each work done will be displayed on the invoice'),
180 'name': fields.boolean('Description', help='The detail of each work done will be displayed on the invoice'),
181 'price': fields.boolean('Cost', help='The cost of each work done will be displayed on the invoice. You probably don\'t want to check this'),
182 'product': fields.many2one('product.product', 'Product', help='Complete this field only if you want to force to use a specific product. Keep empty to use the real product that comes from the cost.'),
186 'date': lambda *args: 1,
187 'name': lambda *args: 1
190 def view_init(self, cr, uid, fields, context=None):
192 This function checks for precondition before wizard executes
193 @param self: The object pointer
194 @param cr: the current row, from the database cursor,
195 @param uid: the current user’s ID for security checks,
196 @param fields: List of fields for default value
197 @param context: A standard dictionary for contextual values
199 analytic_obj = self.pool.get('account.analytic.line')
200 data = context and context.get('active_ids', [])
201 for analytic in analytic_obj.browse(cr, uid, data, context=context):
202 if analytic.invoice_id:
203 raise osv.except_osv(_('Warning !'), _("Invoice is already linked to some of the analytic line(s)!"))
205 def do_create(self, cr, uid, ids, context=None):
206 data = self.read(cr, uid, ids, [], context=context)[0]
207 invs = self.pool.get('account.analytic.line').invoice_cost_create(cr, uid, context['active_ids'], data, context=context)
208 mod_obj = self.pool.get('ir.model.data')
209 act_obj = self.pool.get('ir.actions.act_window')
210 mod_ids = mod_obj.search(cr, uid, [('name', '=', 'action_invoice_tree1')], context=context)[0]
211 res_id = mod_obj.read(cr, uid, mod_ids, ['res_id'], context=context)['res_id']
212 act_win = act_obj.read(cr, uid, res_id, [], context=context)
213 act_win['domain'] = [('id','in',invs),('type','=','out_invoice')]
214 act_win['name'] = _('Invoices')
218 hr_timesheet_invoice_create()
220 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: