[IMP] simplified views
[odoo/odoo.git] / addons / hr_timesheet_invoice / wizard / hr_timesheet_invoice_create.py
index 0d2c712..7e5edca 100644 (file)
@@ -1,21 +1,20 @@
-# -*- encoding: utf-8 -*-
+# -*- coding: utf-8 -*-
 ##############################################################################
 #
 #    OpenERP, Open Source Management Solution
-#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
-#    $Id$
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
 #
 #    This program is free software: you can redistribute it and/or modify
-#    it under the terms of the GNU General Public License as published by
-#    the Free Software Foundation, either version 3 of the License, or
-#    (at your option) any later version.
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
 #
 #    This program is distributed in the hope that it will be useful,
 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#    GNU General Public License for more details.
+#    GNU Affero General Public License for more details.
 #
-#    You should have received a copy of the GNU General Public License
+#    You should have received a copy of the GNU Affero General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 ##############################################################################
@@ -36,12 +35,22 @@ class invoice_create(wizard.interface):
     def _get_accounts(self, cr, uid, data, context):
         if not len(data['ids']):
             return {}
-        cr.execute("SELECT distinct(account_id) from account_analytic_line where id IN (%s)"% (','.join(map(str,data['ids'])),))
+        #Checking whether the analytic line is invoiced or not
+        pool = pooler.get_pool(cr.dbname)
+        analytic_line_obj = pool.get('account.analytic.line').browse(cr, uid, data['ids'], context)
+        for obj_acc in analytic_line_obj:
+            if obj_acc.invoice_id and obj_acc.invoice_id.state !='cancel':
+                raise wizard.except_wizard(_('Warning'),_('The analytic entry "%s" is already invoiced!')%(obj_acc.name,))
+        
+        cr.execute("SELECT distinct(account_id) from account_analytic_line where id =ANY(%s)",(data['ids'],))
         account_ids = cr.fetchall()
         return {'accounts': [x[0] for x in account_ids]}
 
     def _do_create(self, cr, uid, data, context):
         pool = pooler.get_pool(cr.dbname)
+        mod_obj = pool.get('ir.model.data')
+        result = mod_obj._get_id(cr, uid, 'account', 'view_account_invoice_filter')
+        res = mod_obj.read(cr, uid, result, ['res_id'])
         analytic_account_obj = pool.get('account.analytic.account')
         res_partner_obj = pool.get('res.partner')
         account_payment_term_obj = pool.get('account.payment.term')
@@ -51,12 +60,12 @@ class invoice_create(wizard.interface):
         for account in analytic_account_obj.browse(cr, uid, account_ids, context):
             partner = account.partner_id
             if (not partner) or not (account.pricelist_id):
-                raise wizard.except_wizard(_('Analytic account incomplete'),
-                        _('Please fill in the partner and pricelist field in the analytic account:\n%s') % (account.name,))
+                raise wizard.except_wizard(_('Analytic Account incomplete'),
+                        _('Please fill in the Associate Partner and Sale Pricelist fields in the Analytic Account:\n%s') % (account.name,))
 
             if not partner.address:
                 raise wizard.except_wizard(_('Partner incomplete'),
-                        _('Please fill in the address field in the partner: %s.') % (partner.name,))
+                        _('Please fill in the Address field in the Partner: %s.') % (partner.name,))
 
             date_due = False
             if partner.property_payment_term:
@@ -79,6 +88,7 @@ class invoice_create(wizard.interface):
                 'account_id': partner.property_account_receivable.id,
                 'currency_id': account.pricelist_id.currency_id.id,
                 'date_due': date_due,
+                'fiscal_position': account.partner_id.property_account_position.id
             }
             last_invoice = pool.get('account.invoice').create(cr, uid, curr_invoice)
             invoices.append(last_invoice)
@@ -88,29 +98,33 @@ class invoice_create(wizard.interface):
             cr.execute("SELECT product_id, to_invoice, sum(unit_amount) " \
                     "FROM account_analytic_line as line " \
                     "WHERE account_id = %s " \
-                        "AND id IN (" + ','.join([str(x) for x in data['ids']]) + ") " \
-                        "AND to_invoice IS NOT NULL " \
-                    "GROUP BY product_id,to_invoice", (account.id,))
+                        "AND id =ANY(%s) AND to_invoice IS NOT NULL " \
+                    "GROUP BY product_id,to_invoice", (account.id,data['ids'],))
+
             for product_id,factor_id,qty in cr.fetchall():
                 product = pool.get('product.product').browse(cr, uid, product_id, context2)
                 if not product:
-                    raise wizard.except_wizard(_('Error'), _('At least on line have no product !'))
+                    raise wizard.except_wizard(_('Error'), _('At least one line has no product !'))
                 factor_name = ''
                 factor = pool.get('hr_timesheet_invoice.factor').browse(cr, uid, factor_id, context2)
-                if factor.customer_name:
-                    factor_name = product.name+' - '+factor.customer_name
+
+                if not data['form']['product']:
+                    if factor.customer_name:
+                        factor_name = product.name+' - '+factor.customer_name
+                    else:
+                        factor_name = product.name
                 else:
-                    factor_name = product.name
+                    factor_name = pool.get('product.product').name_get(cr, uid, [data['form']['product']], context=context)[0][1]
+
                 if account.pricelist_id:
                     pl = account.pricelist_id.id
-                    price = pool.get('product.pricelist').price_get(cr,uid,[pl], product_id, qty or 1.0, account.partner_id.id)[pl]
+                    price = pool.get('product.pricelist').price_get(cr,uid,[pl], data['form']['product'] or product_id, qty or 1.0, account.partner_id.id)[pl]
                 else:
                     price = 0.0
 
                 taxes = product.taxes_id
                 tax = pool.get('account.fiscal.position').map_tax(cr, uid, account.partner_id.property_account_position, taxes)
                 account_id = product.product_tmpl_id.property_account_income.id or product.categ_id.property_account_income_categ.id
-
                 curr_line = {
                     'price_unit': price,
                     'quantity': qty,
@@ -128,13 +142,8 @@ class invoice_create(wizard.interface):
                 #
                 # Compute for lines
                 #
-                cr.execute("SELECT * "  # TODO optimize this
-                           "  FROM account_analytic_line" 
-                           " WHERE account_id=%%s"
-                           "   AND id IN (%s)"
-                           "   AND product_id=%%s"
-                           "   AND to_invoice=%%s" % ','.join(['%s']*len(data['ids'])), 
-                           (account.id, data['ids'], product_id, factor_id))
+                cr.execute("SELECT * FROM account_analytic_line WHERE account_id = %s and id = ANY (%s) AND product_id=%s and to_invoice=%s", (account.id, data['ids'], product_id, factor_id))
+
                 line_ids = cr.dictfetchall()
                 note = []
                 for line in line_ids:
@@ -151,29 +160,40 @@ class invoice_create(wizard.interface):
                         details.append(line['name'])
                     #if data['form']['price']:
                     #   details.append(abs(line['amount']))
-                    note.append(' - '.join(map(str,details)))
+                    note.append(u' - '.join(map(lambda x: unicode(x) or '',details)))
 
-                curr_line['note'] = "\n".join(map(str,note))
+                curr_line['note'] = "\n".join(map(lambda x: unicode(x) or '',note))
                 pool.get('account.invoice.line').create(cr, uid, curr_line)
-                strids = ','.join(map(str, data['ids']))
-                cr.execute("update account_analytic_line set invoice_id=%%s WHERE account_id = %%s and id IN (%s)" % strids, (last_invoice,account.id,))
-
-        return {
-            'domain': "[('id','in', ["+','.join(map(str,invoices))+"])]",
-            'name': _('Invoices'),
-            'view_type': 'form',
-            'view_mode': 'tree,form',
-            'res_model': 'account.invoice',
-            'view_id': False,
-            'context': "{'type':'out_invoice'}",
-            'type': 'ir.actions.act_window'
-        }
-
+                cr.execute("update account_analytic_line set invoice_id=%s WHERE account_id = %s and id =ANY(%s)" ,(last_invoice,account.id,data['ids']))
+
+        pool.get('account.invoice').button_reset_taxes(cr, uid, [last_invoice], context)
+
+        mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data')
+        act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window')
+
+        mod_id = mod_obj.search(cr, uid, [('name', '=', 'action_invoice_tree1')])[0]
+        res_id = mod_obj.read(cr, uid, mod_id, ['res_id'])['res_id']
+        act_win = act_obj.read(cr, uid, res_id, [])
+        act_win['domain'] = [('id','in',invoices),('type','=','out_invoice')]
+        act_win['name'] = _('Invoices')
+        return act_win
+
+#        return {
+#            'domain': "[('id','in', ["+','.join(map(str,invoices))+"])]",
+#            'name': _('Invoices'),
+#            'view_type': 'form',
+#            'view_mode': 'tree,form',
+#            'res_model': 'account.invoice',
+#            'view_id': False,
+#            'context': "{'type':'out_invoice'}",
+#            'type': 'ir.actions.act_window',
+#            'search_view_id': res['res_id']
+#        }
 
     _create_form = """<?xml version="1.0"?>
-    <form title="Invoice on analytic entries">
+    <form string="Invoice on analytic entries">
         <notebook>
-        <page string="Invoicing Data">
+        <page string="Billing Data">
             <separator string="Do you want to show details of work in invoice ?" colspan="4"/>
             <field name="date"/>
             <field name="time"/>
@@ -201,7 +221,7 @@ class invoice_create(wizard.interface):
     states = {
         'init' : {
             'actions' : [_get_accounts],
-            'result' : {'type':'form', 'arch':_create_form, 'fields':_create_fields, 'state': [('end','Cancel'),('create','Create Invoices')]},
+            'result' : {'type':'form', 'arch':_create_form, 'fields':_create_fields, 'state': [('end','Cancel', 'gtk-cancel'),('create','Create Invoices', 'gtk-ok')]},
         },
         'create' : {
             'actions' : [],