Remplace all occurences of my_browse_rec.product_id.product_tmpl_id.field to my_brows...
[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 class account_analytic_line(osv.osv):
31     _inherit = "account.analytic.line"
32
33     #
34     # data = {
35     #   'date': boolean
36     #   'time': boolean
37     #   'name': boolean
38     #   'price': boolean
39     #   'product': many2one id
40     # }
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')
52         invoices = []
53         if context is None:
54             context = {}
55
56         account_ids = {}
57         for line in self.pool.get('account.analytic.line').browse(cr, uid, ids, context=context):
58             account_ids[line.account_id.id] = True
59
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,))
66
67
68
69             date_due = False
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'))
74                 if pterm_list:
75                     pterm_list = [line[0] for line in pterm_list]
76                     pterm_list.sort()
77                     date_due = pterm_list[-1]
78
79             curr_invoice = {
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,
85                 'date_due': date_due,
86                 'fiscal_position': account.partner_id.property_account_position.id
87             }
88             last_invoice = invoice_obj.create(cr, uid, curr_invoice, context=context)
89             invoices.append(last_invoice)
90
91             context2 = context.copy()
92             context2['lang'] = partner.lang
93             cr.execute("SELECT product_id, to_invoice, sum(unit_amount), product_uom_id, name " \
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, name", (account.id, tuple(ids),))
98
99             for product_id, factor_id, qty, uom, line_name in cr.fetchall():
100                 if data.get('product'):
101                      product_id = data['product'][0]
102                 product = product_obj.browse(cr, uid, product_id, context=context2)
103                 if not product:
104                     raise osv.except_osv(_('Error'), _('There is no product defined for the line %s. Please select one or force the product through the wizard.') % (line_name))
105                 factor = invoice_factor_obj.browse(cr, uid, factor_id, context=context2)
106                 factor_name = product_obj.name_get(cr, uid, [product_id], context=context2)[0][1] 
107                 if factor.customer_name:
108                     factor_name += ' - ' + factor.customer_name
109
110                 ctx =  context.copy()
111                 ctx.update({'uom':uom})
112                 if account.pricelist_id:
113                     pl = account.pricelist_id.id
114                     price = pro_price_obj.price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id, context=ctx)[pl]
115                 else:
116                     price = 0.0
117
118                 taxes = product.taxes_id
119                 tax = fiscal_pos_obj.map_tax(cr, uid, account.partner_id.property_account_position, taxes)
120                 account_id = product.property_account_income.id or product.categ_id.property_account_income_categ.id
121                 if not account_id:
122                     raise osv.except_osv(_("Configuration Error"), _("No income account defined for product '%s'") % product.name)
123                 curr_line = {
124                     'price_unit': price,
125                     'quantity': qty,
126                     'discount':factor.factor,
127                     'invoice_line_tax_id': [(6,0,tax )],
128                     'invoice_id': last_invoice,
129                     'name': factor_name,
130                     'product_id': product_id,
131                     'invoice_line_tax_id': [(6,0,tax)],
132                     'uos_id': uom,
133                     'account_id': account_id,
134                     'account_analytic_id': account.id,
135                 }
136
137                 #
138                 # Compute for lines
139                 #
140                 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))
141
142                 line_ids = cr.dictfetchall()
143                 note = []
144                 for line in line_ids:
145                     # set invoice_line_note
146                     details = []
147                     if data.get('date', False):
148                         details.append(line['date'])
149                     if data.get('time', False):
150                         if line['product_uom_id']:
151                             details.append("%s %s" % (line['unit_amount'], product_uom_obj.browse(cr, uid, [line['product_uom_id']],context2)[0].name))
152                         else:
153                             details.append("%s" % (line['unit_amount'], ))
154                     if data.get('name', False):
155                         details.append(line['name'])
156                     note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
157
158                 curr_line['name'] += "\n".join(map(lambda x: unicode(x) or '',note))
159                 invoice_line_obj.create(cr, uid, curr_line, context=context)
160                 cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id IN %s", (last_invoice, account.id, tuple(ids)))
161
162             invoice_obj.button_reset_taxes(cr, uid, [last_invoice], context)
163         return invoices
164
165 #
166 # TODO: check unit of measure !!!
167 #
168
169 class hr_timesheet_invoice_create(osv.osv_memory):
170
171     _name = 'hr.timesheet.invoice.create'
172     _description = 'Create invoice from timesheet'
173     _columns = {
174         'date': fields.boolean('Date', help='The real date of each work will be displayed on the invoice'),
175         'time': fields.boolean('Time spent', help='The time of each work done will be displayed on the invoice'),
176         'name': fields.boolean('Description', help='The detail of each work done will be displayed on the invoice'),
177         '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'),
178         'product': fields.many2one('product.product', 'Force Product', help='Fill 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.'),
179     }
180
181     _defaults = {
182          'date': lambda *args: 1,
183          'name': lambda *args: 1
184     }
185
186     def view_init(self, cr, uid, fields, context=None):
187         """
188         This function checks for precondition before wizard executes
189         @param self: The object pointer
190         @param cr: the current row, from the database cursor,
191         @param uid: the current user’s ID for security checks,
192         @param fields: List of fields for default value
193         @param context: A standard dictionary for contextual values
194         """
195         analytic_obj = self.pool.get('account.analytic.line')
196         data = context and context.get('active_ids', [])
197         for analytic in analytic_obj.browse(cr, uid, data, context=context):
198             if analytic.invoice_id:
199                      raise osv.except_osv(_('Warning !'), _("Invoice is already linked to some of the analytic line(s)!"))
200
201     def do_create(self, cr, uid, ids, context=None):
202         data = self.read(cr, uid, ids, [], context=context)[0]
203         invs = self.pool.get('account.analytic.line').invoice_cost_create(cr, uid, context['active_ids'], data, context=context)
204         mod_obj = self.pool.get('ir.model.data')
205         act_obj = self.pool.get('ir.actions.act_window')
206         mod_ids = mod_obj.search(cr, uid, [('name', '=', 'action_invoice_tree1')], context=context)[0]
207         res_id = mod_obj.read(cr, uid, mod_ids, ['res_id'], context=context)['res_id']
208         act_win = act_obj.read(cr, uid, res_id, [], context=context)
209         act_win['domain'] = [('id','in',invs),('type','=','out_invoice')]
210         act_win['name'] = _('Invoices')
211         return act_win
212
213
214 hr_timesheet_invoice_create()
215
216 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
217