f3f720687cfb57d9b2a04b030e052b25eadc0cfc
[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         'date': fields.boolean('Date', help='The real date of each work will be displayed on the invoice'),
39         'time': fields.boolean('Time spent', help='The time of each work done will be displayed on the invoice'),
40         'name': fields.boolean('Description', help='The detail of each work done will be displayed on the invoice'),
41         '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'),
42         '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.'),
43     }
44
45     _defaults = {
46          'date': lambda *args: 1,
47          'name': lambda *args: 1
48     }
49
50     def do_create(self, cr, uid, ids, context=None):
51         mod_obj = self.pool.get('ir.model.data')
52         analytic_account_obj = self.pool.get('account.analytic.account')
53         res_partner_obj = self.pool.get('res.partner')
54         account_payment_term_obj = self.pool.get('account.payment.term')
55         invoice_obj = self.pool.get('account.invoice')
56         product_obj = self.pool.get('product.product')
57         invoice_factor_obj = self.pool.get('hr_timesheet_invoice.factor')
58         pro_price_obj = self.pool.get('product.pricelist')
59         fiscal_pos_obj = self.pool.get('account.fiscal.position')
60         product_uom_obj = self.pool.get('product.uom')
61         invoice_line_obj = self.pool.get('account.invoice.line')
62         invoices = []
63         if context is None:
64             context = {}
65         result = mod_obj._get_id(cr, uid, 'account', 'view_account_invoice_filter')
66         data = self.read(cr, uid, ids, [], context=context)[0]
67
68         account_ids = {}
69         for line in self.pool.get('account.analytic.line').browse(cr, uid, context['active_ids'], context=context):
70             account_ids[line.account_id.id] = True
71
72         account_ids = account_ids.keys() #data['accounts']
73         for account in analytic_account_obj.browse(cr, uid, account_ids, context=context):
74             partner = account.partner_id
75             if (not partner) or not (account.pricelist_id):
76                 raise osv.except_osv(_('Analytic Account incomplete'),
77                         _('Please fill in the Partner or Customer and Sale Pricelist fields in the Analytic Account:\n%s') % (account.name,))
78
79             if not partner.address:
80                 raise osv.except_osv(_('Partner incomplete'),
81                         _('Please fill in the Address field in the Partner: %s.') % (partner.name,))
82
83             date_due = False
84             if partner.property_payment_term:
85                 pterm_list= account_payment_term_obj.compute(cr, uid,
86                         partner.property_payment_term.id, value=1,
87                         date_ref=time.strftime('%Y-%m-%d'))
88                 if pterm_list:
89                     pterm_list = [line[0] for line in pterm_list]
90                     pterm_list.sort()
91                     date_due = pterm_list[-1]
92
93             curr_invoice = {
94                 'name': time.strftime('%d/%m/%Y')+' - '+account.name,
95                 'partner_id': account.partner_id.id,
96                 'address_contact_id': res_partner_obj.address_get(cr, uid,
97                     [account.partner_id.id], adr_pref=['contact'])['contact'],
98                 'address_invoice_id': res_partner_obj.address_get(cr, uid,
99                     [account.partner_id.id], adr_pref=['invoice'])['invoice'],
100                 'payment_term': partner.property_payment_term.id or False,
101                 'account_id': partner.property_account_receivable.id,
102                 'currency_id': account.pricelist_id.currency_id.id,
103                 'date_due': date_due,
104                 'fiscal_position': account.partner_id.property_account_position.id
105             }
106             last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context)
107             invoices.append(last_invoice)
108
109             context2 = context.copy()
110             context2['lang'] = partner.lang
111             cr.execute("SELECT product_id, to_invoice, sum(unit_amount) " \
112                     "FROM account_analytic_line as line " \
113                     "WHERE account_id = %s " \
114                         "AND id IN %s AND to_invoice IS NOT NULL " \
115                     "GROUP BY product_id,to_invoice", (account.id, tuple(context['active_ids']),))
116
117             for product_id, factor_id, qty in cr.fetchall():
118                 product = product_obj.browse(cr, uid, product_id, context2)
119                 if not product:
120                     raise osv.except_osv(_('Error'), _('At least one line has no product !'))
121                 factor_name = ''
122                 factor = invoice_factor_obj.browse(cr, uid, factor_id, context2)
123
124                 if not data['product']:
125                     if factor.customer_name:
126                         factor_name = product.name+' - '+factor.customer_name
127                     else:
128                         factor_name = product.name
129                 else:
130                     factor_name = product_obj.name_get(cr, uid, [data['product']], context=context)[0][1]
131
132                 if account.pricelist_id:
133                     pl = account.pricelist_id.id
134                     price = pro_price_obj.price_get(cr,uid,[pl], data['product'] or product_id, qty or 1.0, account.partner_id.id)[pl]
135                 else:
136                     price = 0.0
137
138                 taxes = product.taxes_id
139                 tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
140                 account_id = product.product_tmpl_id.property_account_income.id or product.categ_id.property_account_income_categ.id
141                 curr_line = {
142                     'price_unit': price,
143                     'quantity': qty,
144                     'discount':factor.factor,
145                     'invoice_line_tax_id': [(6,0,tax )],
146                     'invoice_id': last_invoice,
147                     'name': factor_name,
148                     'product_id': data['product'] or product_id,
149                     'invoice_line_tax_id': [(6,0,tax)],
150                     'uos_id': product.uom_id.id,
151                     'account_id': account_id,
152                     'account_analytic_id': account.id,
153                 }
154
155                 #
156                 # Compute for lines
157                 #
158                 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(context['active_ids']), product_id, factor_id))
159
160                 line_ids = cr.dictfetchall()
161                 note = []
162                 for line in line_ids:
163                     # set invoice_line_note
164                     details = []
165                     if data['date']:
166                         details.append(line['date'])
167                     if data['time']:
168                         if line['product_uom_id']:
169                             details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name))
170                         else:
171                             details.append("%s" % (line['unit_amount'], ))
172                     if data['name']:
173                         details.append(line['name'])
174                     note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
175
176                 curr_line['note'] = "\n".join(map(lambda x: unicode(x) or '',note))
177                 invoice_line_obj.create(cr, uid, curr_line, context=context)
178                 cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(context['active_ids'])))
179
180             invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context)
181
182         mod_obj = self.pool.get('ir.model.data')
183         act_obj = self.pool.get('ir.actions.act_window')
184
185         mod_ids = mod_obj.search(cr, uid, [('name', '=', 'action_invoice_tree1')], context=context)[0]
186         res_id = mod_obj.read(cr, uid, mod_ids, ['res_id'], context=context)['res_id']
187         act_win = act_obj.read(cr, uid, res_id, [], context=context)
188         act_win['domain'] = [('id','in',invoices),('type','=','out_invoice')]
189         act_win['name'] = _('Invoices')
190         return act_win
191
192
193 hr_timesheet_invoice_create()
194
195 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
196