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