Invoice on analytic line fill now the due date
[odoo/odoo.git] / addons / hr_timesheet_invoice / wizard / hr_timesheet_invoice_create.py
1 ##############################################################################
2 #
3 # Copyright (c) 2004-2007 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #
5 # $Id: account.py 1005 2005-07-25 08:41:42Z nicoe $
6 #
7 # WARNING: This program as such is intended to be used by professional
8 # programmers who take the whole responsability of assessing all potential
9 # consequences resulting from its eventual inadequacies and bugs
10 # End users who are looking for a ready-to-use solution with commercial
11 # garantees and support are strongly adviced to contract a Free Software
12 # Service Company
13 #
14 # This program is Free Software; you can redistribute it and/or
15 # modify it under the terms of the GNU General Public License
16 # as published by the Free Software Foundation; either version 2
17 # of the License, or (at your option) any later version.
18 #
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
27 #
28 ##############################################################################
29
30 import wizard
31 import pooler
32 import time
33
34 #
35 # Create an invoice based on selected timesheet lines
36 #
37
38 #
39 # TODO: check unit of measure !!!
40 #
41 class invoice_create(wizard.interface):
42         def _get_accounts(self, cr, uid, data, context):
43                 if not len(data['ids']):
44                         return {}
45                 cr.execute("SELECT distinct(account_id) from account_analytic_line where id IN (%s)"% (','.join(map(str,data['ids'])),))
46                 account_ids = cr.fetchall()
47                 return {'accounts': [x[0] for x in account_ids]}
48
49         def _do_create(self, cr, uid, data, context):
50                 pool = pooler.get_pool(cr.dbname)
51                 analytic_account_obj = pool.get('account.analytic.account')
52                 res_partner_obj = pool.get('res.partner')
53                 account_payment_term_obj = pool.get('account.payment.term')
54
55                 account_ids = data['form']['accounts'][0][2]
56                 invoices = []
57                 for account in analytic_account_obj.browse(cr, uid, account_ids, context):
58                         partner = account.partner_id
59                         if (not partner) or not (account.pricelist_id):
60                                 raise wizard.except_wizard('Analytic account incomplete',
61                                                 'Please fill in the partner and pricelist field '
62                                                 'in the analytic account:\n%s' % (account.name,))
63
64                         date_due = False
65                         if partner.property_payment_term:
66                                 pterm_list= account_payment_term_obj.compute(cr, uid,
67                                                 partner.property_payment_term.id, value=1,
68                                                 date_ref=time.strftime('%Y-%m-%d'))
69                                 if pterm_list:
70                                         pterm_list = [line[0] for line in pterm_list]
71                                         pterm_list.sort()
72                                         date_due = pterm_list[-1]
73
74                         curr_invoice = {
75                                 'name': time.strftime('%D')+' - '+account.name,
76                                 'partner_id': account.partner_id.id,
77                                 'address_contact_id': res_partner_obj.address_get(cr, uid,
78                                         [account.partner_id.id], adr_pref=['contact'])['contact'],
79                                 'address_invoice_id': res_partner_obj.address_get(cr, uid,
80                                         [account.partner_id.id], adr_pref=['invoice'])['invoice'],
81                                 'payment_term': partner.property_payment_term.id or False,
82                                 'account_id': partner.property_account_receivable.id,
83                                 'currency_id': account.pricelist_id.currency_id.id,
84                                 'date_due': date_due,
85                         }
86                         last_invoice = pool.get('account.invoice').create(cr, uid, curr_invoice)
87                         invoices.append(last_invoice)
88
89                         context2=context.copy()
90                         context2['lang'] = partner.lang
91                         cr.execute("SELECT product_id, to_invoice, sum(unit_amount) \
92                                         FROM account_analytic_line as line \
93                                         WHERE account_id = %d AND id IN ("+','.join(map(str,data['ids']))+") \
94                                                 AND to_invoice IS NOT NULL \
95                                         GROUP BY product_id, to_invoice", (account.id,))
96                         for product_id, factor_id, qty in cr.fetchall():
97                                 product = pool.get('product.product').browse(cr, uid, product_id, context2)
98                                 if not product:
99                                         raise wizard.except_wizard('Error', 'At least on line have no product !')
100                                 factor_name = ''
101                                 factor = pool.get('hr_timesheet_invoice.factor').browse(cr, uid, factor_id, context2)
102                                 if factor.customer_name:
103                                         factor_name = product.name+' - '+factor.customer_name
104                                 else:
105                                         factor_name = product.name
106                                 if account.pricelist_id:
107                                         pl = account.pricelist_id.id
108                                         price = pool.get('product.pricelist').price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id)[pl]
109                                 else:
110                                         price = 0.0
111
112                                 taxes = product.taxes_id
113                                 taxep = account.partner_id.property_account_tax
114                                 if not taxep.id:
115                                         tax = [x.id for x in taxes or []]
116                                 else:
117                                         tax = [taxep.id]
118                                         for t in taxes:
119                                                 if not t.tax_group==taxep.tax_group:
120                                                         tax.append(t.id)
121
122                                 account_id = product.product_tmpl_id.property_account_income.id or product.categ_id.property_account_income_categ.id
123
124                                 curr_line = {
125                                         'price_unit': price,
126                                         'quantity': qty,
127                                         'discount':factor.factor,
128                                         'invoice_line_tax_id': [(6,0,tax )],
129                                         'invoice_id': last_invoice,
130                                         'name': factor_name,
131                                         'product_id': data['form']['product'] or product_id,
132                                         'invoice_line_tax_id': [(6,0,tax)],
133                                         'uos_id': product.uom_id.id,
134                                         'account_id': account_id,
135                                         'account_analytic_id': account.id,
136                                 }
137
138                                 #
139                                 # Compute for lines
140                                 #
141                                 cr.execute("SELECT * FROM account_analytic_line WHERE account_id = %d and id IN (%s) AND product_id=%d and to_invoice=%d" % (account.id, ','.join(map(str,data['ids'])), product_id, factor_id))
142                                 line_ids = cr.dictfetchall()
143                                 note = []
144                                 for line in line_ids:
145                                         # set invoice_line_note
146                                         details = []
147                                         if data['form']['date']:
148                                                 details.append(line['date'])
149                                         if data['form']['time']:
150                                                 details.append("%s %s" % (line['unit_amount'], pool.get('product.uom').browse(cr, uid, [line['product_uom_id']])[0].name))
151                                         if data['form']['name']:
152                                                 details.append(line['name'])
153                                         #if data['form']['price']:
154                                         #       details.append(abs(line['amount']))
155                                         note.append(' - '.join(map(str,details)))
156
157                                 curr_line['note'] = "\n".join(map(str,note))
158                                 pool.get('account.invoice.line').create(cr, uid, curr_line)
159                                 cr.execute("update account_analytic_line set invoice_id=%d WHERE account_id = %d and id IN (%s)" % (last_invoice,account.id, ','.join(map(str,data['ids']))))
160
161                 return {
162                         'domain': "[('id','in', ["+','.join(map(str,invoices))+"])]",
163                         'name': 'Invoices',
164                         'view_type': 'form',
165                         'view_mode': 'tree,form',
166                         'res_model': 'account.invoice',
167                         'view_id': False,
168                         'context': "{'type':'out_invoice'}",
169                         'type': 'ir.actions.act_window'
170                 }
171
172
173         _create_form = """<?xml version="1.0"?>
174         <form title="Invoice on analytic entries">
175                 <separator string="Do you want details for each line of the invoices ?" colspan="4"/>
176                 <field name="date"/>
177                 <field name="time"/>
178                 <field name="name"/>
179                 <field name="price"/>
180                 <separator string="Choose accounts you want to invoice" colspan="4"/>
181                 <field name="accounts" colspan="4"/>
182                 <separator string="Choose a product for intermediary invoice" colspan="4"/>
183                 <field name="product"/>
184         </form>"""
185
186         _create_fields = {
187                 'accounts': {'string':'Analytic Accounts', 'type':'many2many', 'required':'true', 'relation':'account.analytic.account'},
188                 'date': {'string':'Date', 'type':'boolean'},
189                 'time': {'string':'Time spent', 'type':'boolean'},
190                 'name': {'string':'Name of entry', 'type':'boolean'},
191                 'price': {'string':'Cost', 'type':'boolean'},
192                 'product': {'string':'Product', 'type':'many2one', 'relation': 'product.product'},
193         }
194
195         states = {
196                 'init' : {
197                         'actions' : [_get_accounts], 
198                         'result' : {'type':'form', 'arch':_create_form, 'fields':_create_fields, 'state': [('end','Cancel'),('create','Create invoices')]},
199                 },
200                 'create' : {
201                         'actions' : [],
202                         'result' : {'type':'action', 'action':_do_create, 'state':'end'},
203                 },
204         }
205 invoice_create('hr.timesheet.invoice.create')