[MERGE] OPW 383510
[odoo/odoo.git] / addons / hr_timesheet_invoice / wizard / hr_timesheet_final_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 #
28 # Create an final invoice based on selected timesheet lines
29 #
30
31 #
32 # TODO: check unit of measure !!!
33 #
34 class final_invoice_create(osv.osv_memory):
35     _name = 'hr.timesheet.invoice.create.final'
36     _description = 'Create invoice from timesheet final'
37     _columns = {
38         'date': fields.boolean('Date', help='Display date in the history of works'),
39         'time': fields.boolean('Time spent', help='Display time in the history of works'),
40         'name': fields.boolean('Name of entry', help='Display detail of work in the invoice line.'),
41         'price': fields.boolean('Cost', help='Display cost of the item you reinvoice'),
42         'balance_product': fields.many2one('product.product', 'Balance product', help='The product that will be used to invoice the remaining amount'),
43                 }
44
45     def do_create(self, cr, uid, ids, context=None):
46         mod_obj = self.pool.get('ir.model.data')
47         analytic_account_obj = self.pool.get('account.analytic.account')
48         res_partner_obj = self.pool.get('res.partner')
49         account_payment_term_obj = self.pool.get('account.payment.term')
50         invoice_obj = self.pool.get('account.invoice')
51         product_obj = self.pool.get('product.product')
52         fiscal_pos_obj = self.pool.get('account.fiscal.position')
53         invoice_line_obj = self.pool.get('account.invoice.line')
54         invoices = []
55
56         if context is None:
57             context = {}
58         result = mod_obj._get_id(cr, uid, 'account', 'view_account_invoice_filter')
59         res = mod_obj.read(cr, uid, result, ['res_id'], context=context)
60
61         data = self.read(cr, uid, ids, [], context=context)[0]
62         account_ids = 'active_ids' in context and context['active_ids'] or []
63
64         for account in analytic_account_obj.browse(cr, uid, account_ids, context=context):
65             partner = account.partner_id
66             amount_total=0.0
67             if (not partner) or not (account.pricelist_id):
68                 raise osv.except_osv(_('Analytic account incomplete'),
69                         _('Please fill in the partner and pricelist field '
70                         'in the analytic account:\n%s') % (account.name,))
71
72             date_due = False
73             if partner.property_payment_term:
74                 pterm_list= account_payment_term_obj.compute(cr, uid,
75                         partner.property_payment_term.id, value=1,
76                         date_ref=time.strftime('%Y-%m-%d'))
77                 if pterm_list:
78                     pterm_list = [line[0] for line in pterm_list]
79                     pterm_list.sort()
80                     date_due = pterm_list[-1]
81
82             curr_invoice = {
83                 'name': time.strftime('%d/%m/%Y')+' - '+account.name,
84                 'partner_id': account.partner_id.id,
85                 'address_contact_id': res_partner_obj.address_get(cr, uid, [account.partner_id.id], adr_pref=['contact'])['contact'],
86                 'address_invoice_id': res_partner_obj.address_get(cr, uid, [account.partner_id.id], adr_pref=['invoice'])['invoice'],
87                 'payment_term': partner.property_payment_term.id or False,
88                 'account_id': partner.property_account_receivable.id,
89                 'currency_id': account.pricelist_id.currency_id.id,
90                 'date_due': date_due,
91                 'fiscal_position': account.partner_id.property_account_position.id
92             }
93             last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context)
94             invoices.append(last_invoice)
95
96             context2 = context.copy()
97             context2['lang'] = partner.lang
98
99             cr.execute("""SELECT
100                     line.product_id,
101                     sum(line.amount),
102                     line.general_account_id,
103                     line.product_uom_id,
104                     move_line.ref
105                 FROM
106                     account_analytic_line as line
107                     LEFT JOIN account_move_line as move_line on (line.move_id=move_line.id)
108                     LEFT JOIN account_analytic_journal as journal on (line.journal_id=journal.id)
109                 WHERE
110                     line.account_id = %s AND
111                     line.move_id IS NOT NULL AND
112                     journal.type = 'sale'
113                 GROUP BY
114                     line.product_id,
115                     line.general_account_id,
116                     line.product_uom_id,
117                     move_line.ref""", (account.id,))
118             for product_id, amount, account_id, product_uom_id, ref in cr.fetchall():
119                 product = product_obj.browse(cr, uid, product_id, context2)
120
121                 if product:
122                     taxes = product.taxes_id
123                 else:
124                     taxes = []
125
126                 tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
127                 curr_line = {
128                     'price_unit': -amount,
129                     'quantity': 1.0,
130                     'discount': 0.0,
131                     'invoice_line_tax_id': [(6,0,tax)],
132                     'invoice_id': last_invoice,
133                     'name': ref or '' +(product and ' - '+product.name or ''),
134                     'product_id': product_id,
135                     'uos_id': product_uom_id,
136                     'account_id': account_id,
137                     'account_analytic_id': account.id
138                 }
139                 invoice_line_obj.create(cr, uid, curr_line, context=context)
140
141             if not data['balance_product']:
142                 raise osv.except_osv(_('Balance product needed'), _('Please fill a Balance product in the wizard'))
143             product = product_obj.browse(cr, uid, data['balance_product'], context2)
144             taxes = product.taxes_id
145             tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
146             account_id = product.product_tmpl_id.property_account_income.id or product.categ_id.property_account_income_categ.id
147             curr_line = {
148                 'price_unit': account.amount_max - amount_total,
149                 'quantity': 1.0,
150                 'discount': 0.0,
151                 'invoice_line_tax_id': [(6,0,tax)],
152                 'invoice_id': last_invoice,
153                 'name': product.name,
154                 'product_id': product.id,
155                 'uos_id': product.uom_id.id,
156                 'account_id': account_id,
157                 'account_analytic_id': account.id
158             }
159             invoice_line_obj.create(cr, uid, curr_line, context=context)
160             if account.amount_max < amount_total:
161                 invoice_obj.write(cr, uid, [last_invoice], {'type': 'out_refund',}, context=context)
162             cr.execute('update account_analytic_line set invoice_id=%s where invoice_id is null and account_id=%s', (last_invoice, account.id))
163
164         return {
165             'domain': "[('id','in', ["+','.join(map(str,invoices))+"])]",
166             'name': 'Invoices',
167             'view_type': 'form',
168             'view_mode': 'tree,form',
169             'res_model': 'account.invoice',
170             'view_id': False,
171             'context': "{'type':'out_invoice'}",
172             'type': 'ir.actions.act_window',
173             'search_view_id': res['res_id']
174                 }
175
176 final_invoice_create()
177
178 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: