[FIX] Security fixes for sql injections
[odoo/odoo.git] / addons / hr_timesheet_invoice / wizard / hr_timesheet_invoice_create.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 osv import osv, fields
25 from tools.translate import _
26
27 ## Create an invoice based on selected timesheet lines
28 #
29
30 #
31 # TODO: check unit of measure !!!
32 #
33 class hr_timesheet_invoice_create(osv.osv_memory):
34
35     _name = 'hr.timesheet.invoice.create'
36     _description = 'Create invoice from timesheet'
37     _columns = {
38         'accounts': fields.many2many('account.analytic.account', 'invoice_id', 'account_id', 'Analytic Accounts', required=True),
39         'date': fields.boolean('Date', help='The real date of each work will be displayed on the invoice'),
40         'time': fields.boolean('Time spent', help='The time of each work done will be displayed on the invoice'),
41         'name': fields.boolean('Name of entry', help='The detail of each work done will be displayed on the invoice'),
42         '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'),
43         '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.'),
44                 }
45
46     def _get_accounts(self, cr, uid, context=None):
47         if context is None:
48             context = {}
49         if not len(context['active_ids']):
50             return {}
51         #Checking whether the analytic line is invoiced or not
52         analytic_line_obj = self.pool.get('account.analytic.line').browse(cr, uid, context['active_ids'], context)
53         for obj_acc in analytic_line_obj:
54             if obj_acc.invoice_id and obj_acc.invoice_id.state !='cancel':
55                 raise osv.except_osv(_('Warning'),_('The analytic entry "%s" is already invoiced!')%(obj_acc.name,))
56
57         cr.execute("SELECT distinct(account_id) from account_analytic_line where id IN %s",(tuple(context['active_ids']),))
58         account_ids = cr.fetchall()
59         return [x[0] for x in account_ids]
60
61     _defaults = {
62          'accounts': _get_accounts
63                  }
64
65     def do_create(self, cr, uid, ids, context=None):
66         mod_obj = self.pool.get('ir.model.data')
67         analytic_account_obj = self.pool.get('account.analytic.account')
68         res_partner_obj = self.pool.get('res.partner')
69         account_payment_term_obj = self.pool.get('account.payment.term')
70         invoices = []
71
72         result = mod_obj._get_id(cr, uid, 'account', 'view_account_invoice_filter')
73         res = mod_obj.read(cr, uid, result, ['res_id'])
74
75         data = self.read(cr, uid, ids, [], context)[0]
76         account_ids = data['accounts']
77         for account in analytic_account_obj.browse(cr, uid, account_ids, context):
78             partner = account.partner_id
79             if (not partner) or not (account.pricelist_id):
80                 raise osv.except_osv(_('Analytic Account incomplete'),
81                         _('Please fill in the Associate Partner and Sale Pricelist fields in the Analytic Account:\n%s') % (account.name,))
82
83             if not partner.address:
84                 raise osv.except_osv(_('Partner incomplete'),
85                         _('Please fill in the Address field in the Partner: %s.') % (partner.name,))
86
87             date_due = False
88             if partner.property_payment_term:
89                 pterm_list= account_payment_term_obj.compute(cr, uid,
90                         partner.property_payment_term.id, value=1,
91                         date_ref=time.strftime('%Y-%m-%d'))
92                 if pterm_list:
93                     pterm_list = [line[0] for line in pterm_list]
94                     pterm_list.sort()
95                     date_due = pterm_list[-1]
96
97             curr_invoice = {
98                 'name': time.strftime('%D')+' - '+account.name,
99                 'partner_id': account.partner_id.id,
100                 'address_contact_id': res_partner_obj.address_get(cr, uid,
101                     [account.partner_id.id], adr_pref=['contact'])['contact'],
102                 'address_invoice_id': res_partner_obj.address_get(cr, uid,
103                     [account.partner_id.id], adr_pref=['invoice'])['invoice'],
104                 'payment_term': partner.property_payment_term.id or False,
105                 'account_id': partner.property_account_receivable.id,
106                 'currency_id': account.pricelist_id.currency_id.id,
107                 'date_due': date_due,
108                 'fiscal_position': account.partner_id.property_account_position.id
109             }
110             last_invoice = self.pool.get('account.invoice').create(cr, uid, curr_invoice)
111             invoices.append(last_invoice)
112
113             context2=context.copy()
114             context2['lang'] = partner.lang
115             cr.execute("SELECT product_id, to_invoice, sum(unit_amount) " \
116                     "FROM account_analytic_line as line " \
117                     "WHERE account_id = %s " \
118                         "AND id IN %s AND to_invoice IS NOT NULL " \
119                     "GROUP BY product_id,to_invoice", (account.id,tuple(context['active_ids']),))
120
121             for product_id,factor_id,qty in cr.fetchall():
122                 product = pool.get('product.product').browse(cr, uid, product_id, context2)
123                 if not product:
124                     raise osv.except_osv(_('Error'), _('At least one line has no product !'))
125                 factor_name = ''
126                 factor = pool.get('hr_timesheet_invoice.factor').browse(cr, uid, factor_id, context2)
127
128                 if not data['product']:
129                     if factor.customer_name:
130                         factor_name = product.name+' - '+factor.customer_name
131                     else:
132                         factor_name = product.name
133                 else:
134                     factor_name = pool.get('product.product').name_get(cr, uid, [data['product']], context=context)[0][1]
135
136                 if account.pricelist_id:
137                     pl = account.pricelist_id.id
138                     price = pool.get('product.pricelist').price_get(cr,uid,[pl], data['product'] or product_id, qty or 1.0, account.partner_id.id)[pl]
139                 else:
140                     price = 0.0
141
142                 taxes = product.taxes_id
143                 tax = pool.get('account.fiscal.position').map_tax(cr, uid, account.partner_id.property_account_position, taxes)
144                 account_id = product.product_tmpl_id.property_account_income.id or product.categ_id.property_account_income_categ.id
145                 curr_line = {
146                     'price_unit': price,
147                     'quantity': qty,
148                     'discount':factor.factor,
149                     'invoice_line_tax_id': [(6,0,tax )],
150                     'invoice_id': last_invoice,
151                     'name': factor_name,
152                     'product_id': data['product'] or product_id,
153                     'invoice_line_tax_id': [(6,0,tax)],
154                     'uos_id': product.uom_id.id,
155                     'account_id': account_id,
156                     'account_analytic_id': account.id,
157                 }
158
159                 #
160                 # Compute for lines
161                 #
162                 cr.execute("SELECT * FROM account_analytic_line WHERE account_id = %s and id in %s AND product_id=%s and to_invoice=%s", (account.id, tuple(data['ids']), product_id, factor_id))
163
164                 line_ids = cr.dictfetchall()
165                 note = []
166                 for line in line_ids:
167                     # set invoice_line_note
168                     details = []
169                     if data['date']:
170                         details.append(line['date'])
171                     if data['time']:
172                         if line['product_uom_id']:
173                             details.append("%s %s" % (line['unit_amount'], pool.get('product.uom').browse(cr, uid, [line['product_uom_id']])[0].name))
174                         else:
175                             details.append("%s" % (line['unit_amount'], ))
176                     if data['name']:
177                         details.append(line['name'])
178                     #if data['price']:
179                     #   details.append(abs(line['amount']))
180                     note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
181
182                 curr_line['note'] = "\n".join(map(lambda x: unicode(x) or '',note))
183                 pool.get('account.invoice.line').create(cr, uid, curr_line)
184                 cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id in %s" ,(last_invoice, account.id,tuple(data['ids'])))
185
186         self.pool.get('account.invoice').button_reset_taxes(cr, uid, [last_invoice], context)
187
188         mod_obj = self.pool.get('ir.model.data')
189         act_obj = self.pool.get('ir.actions.act_window')
190
191         mod_id = mod_obj.search(cr, uid, [('name', '=', 'action_invoice_tree1')])[0]
192         res_id = mod_obj.read(cr, uid, mod_id, ['res_id'])['res_id']
193         act_win = act_obj.read(cr, uid, res_id, [])
194         act_win['domain'] = [('id','in',invoices),('type','=','out_invoice')]
195         act_win['name'] = _('Invoices')
196         return act_win
197
198 #        return {
199 #            'domain': "[('id','in', ["+','.join(map(str,invoices))+"])]",
200 #            'name': _('Invoices'),
201 #            'view_type': 'form',
202 #            'view_mode': 'tree,form',
203 #            'res_model': 'account.invoice',
204 #            'view_id': False,
205 #            'context': "{'type':'out_invoice'}",
206 #            'type': 'ir.actions.act_window',
207 #            'search_view_id': res['res_id']
208 #        }
209
210
211 hr_timesheet_invoice_create()
212
213 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
214