[IMP]: Generalization of tooltips: Added tooltips for 'origin' fields, renamed 'Ref...
[odoo/odoo.git] / addons / account / account_move_line.py
index c5e38b8..dacca14 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-2009 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/>.
 #
 ##############################################################################
@@ -28,6 +27,8 @@ from tools.translate import _
 import mx.DateTime
 from mx.DateTime import RelativeDateTime, now, DateTime, localtime
 
+import tools
+
 class account_move_line(osv.osv):
     _name = "account.move.line"
     _description = "Entry lines"
@@ -40,16 +41,22 @@ class account_move_line(osv.osv):
         else:
             fiscalyear_clause = '%s' % context['fiscalyear']
         state=context.get('state',False)
-        where_move_state=''
+        where_move_state = ''
+        where_move_lines_by_date = ''
+
+        if context.get('date_from', False) and context.get('date_to', False):
+            where_move_lines_by_date = " AND " +obj+".move_id in ( select id from account_move  where date >= '" +context['date_from']+"' AND date <= '"+context['date_to']+"')"
+
         if state:
             if state.lower() not in ['all']:
                 where_move_state= " AND "+obj+".move_id in (select id from account_move where account_move.state = '"+state+"')"
 
+
         if context.get('periods', False):
             ids = ','.join([str(x) for x in context['periods']])
-            return obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s)) %s" % (fiscalyear_clause, ids,where_move_state)
+            return obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s)) %s %s" % (fiscalyear_clause, ids,where_move_state,where_move_lines_by_date)
         else:
-            return obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) %s)" % (fiscalyear_clause,where_move_state)
+            return obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) %s %s)" % (fiscalyear_clause,where_move_state,where_move_lines_by_date)
 
     def default_get(self, cr, uid, fields, context={}):
         data = self._default_get(cr, uid, fields, context)
@@ -96,9 +103,10 @@ class account_move_line(osv.osv):
 
             total_new=0.00
             for i in context['lines']:
-                total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
-                for item in i[2]:
-                        data[item]=i[2][item]
+                if i[2]:
+                    total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
+                    for item in i[2]:
+                            data[item]=i[2][item]
             if context['journal']:
                 journal_obj=self.pool.get('account.journal').browse(cr,uid,context['journal'])
                 if journal_obj.type == 'purchase':
@@ -113,7 +121,7 @@ class account_move_line(osv.osv):
                         account = journal_obj.default_debit_account_id
 
 
-                if account and ((not fields) or ('debit' in fields) or ('credit' in fields)) and 'partner_id' in data:
+                if account and ((not fields) or ('debit' in fields) or ('credit' in fields)) and 'partner_id' in data and (data['partner_id']):
                     part = self.pool.get('res.partner').browse(cr, uid, data['partner_id'])
                     account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
                     account = self.pool.get('account.account').browse(cr, uid, account)
@@ -200,7 +208,8 @@ class account_move_line(osv.osv):
         part = partner_id and self.pool.get('res.partner').browse(cr, uid, partner_id) or False
         # part = False is acceptable for fiscal position.
         account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
-        account = self.pool.get('account.account').browse(cr, uid, account)
+        if account:
+            account = self.pool.get('account.account').browse(cr, uid, account)
 
         if account and ((not fields) or ('debit' in fields) or ('credit' in fields)):
             data['account_id'] = account.id
@@ -215,7 +224,7 @@ class account_move_line(osv.osv):
         data['debit'] = s>0  and s or 0.0
         data['credit'] = s<0  and -s or 0.0
 
-        if account.currency_id:
+        if account and account.currency_id:
             data['currency_id'] = account.currency_id.id
             acc = account
             if s>0:
@@ -274,6 +283,17 @@ class account_move_line(osv.osv):
                 result.append((line.id, line.name))
         return result
 
+    def _balance_search(self, cursor, user, obj, name, args):
+        if not len(args):
+            return []
+        where = ' and '.join(map(lambda x: '(abs(sum(debit-credit))'+x[1]+str(x[2])+')',args))
+        cursor.execute('select id, sum(debit-credit) from account_move_line \
+                     group by id,debit,credit having '+where)
+        res = cursor.fetchall()
+        if not len(res):
+            return [('id', '=', '0')]
+        return [('id', 'in', [x[0] for x in res])]
+
     def _invoice_search(self, cursor, user, obj, name, args):
         if not len(args):
             return []
@@ -329,26 +349,26 @@ class account_move_line(osv.osv):
 
     _columns = {
         'name': fields.char('Name', size=64, required=True),
-        'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very usefull for some reports."),
+        'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very useful for some reports."),
         'product_uom_id': fields.many2one('product.uom', 'UoM'),
         'product_id': fields.many2one('product.product', 'Product'),
-        'debit': fields.float('Debit', digits=(16,2)),
-        'credit': fields.float('Credit', digits=(16,2)),
+        'debit': fields.float('Debit', digits=(16,int(tools.config['price_accuracy']))),
+        'credit': fields.float('Credit', digits=(16,int(tools.config['price_accuracy']))),
         'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2),
         'move_id': fields.many2one('account.move', 'Move', ondelete="cascade", states={'valid':[('readonly',True)]}, help="The move of this entry line.", select=2),
 
-        'ref': fields.char('Ref.', size=32),
+        'ref': fields.char('Reference', size=32),
         'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1),
         'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2),
         'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2),
-        'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency if it is a multi-currency entry."),
-        'currency_id': fields.many2one('res.currency', 'Currency', help="The optionnal other currency if it is a multi-currency entry."),
+        'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency if it is a multi-currency entry.", digits=(16,int(tools.config['price_accuracy']))),
+        'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
 
         'period_id': fields.many2one('account.period', 'Period', required=True, select=2),
         'journal_id': fields.many2one('account.journal', 'Journal', required=True, select=1),
         'blocked': fields.boolean('Litigation', help="You can check this box to mark the entry line as a litigation with the associated partner"),
 
-        'partner_id': fields.many2one('res.partner', 'Partner Ref.'),
+        'partner_id': fields.many2one('res.partner', 'Partner'),
         'date_maturity': fields.date('Maturity date', help="This field is used for payable and receivable entries. You can put the limit date for the payment of this entry line."),
         'date': fields.related('move_id','date', string='Effective date', type='date', required=True,
             store={
@@ -357,16 +377,19 @@ class account_move_line(osv.osv):
         'date_created': fields.date('Creation date'),
         'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'),
         'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation')], 'Centralisation', size=6),
-        'balance': fields.function(_balance, method=True, string='Balance'),
-        'state': fields.selection([('draft','Draft'), ('valid','Valid')], 'Status', readonly=True),
-        'tax_code_id': fields.many2one('account.tax.code', 'Tax Account'),
-        'tax_amount': fields.float('Tax/Base Amount', digits=(16,2), select=True),
+        'balance': fields.function(_balance, fnct_search=_balance_search, method=True, string='Balance'),
+        'state': fields.selection([('draft','Draft'), ('valid','Valid')], 'State', readonly=True,
+                                  help='When new move line is created the state will be \'Draft\'.\n* When all the payments are done it will be in \'Valid\' state.'),
+        'tax_code_id': fields.many2one('account.tax.code', 'Tax Account', help="The Account can either be a base tax code or tax code account."),
+        'tax_amount': fields.float('Tax/Base Amount', digits=(16,int(tools.config['price_accuracy'])), select=True, help="If the Tax account is a tax code account, this field will contain the taxed amount.If the tax account is base tax code,\
+                    this field will contain the basic amount(without tax)."),
         'invoice': fields.function(_invoice, method=True, string='Invoice',
             type='many2one', relation='account.invoice', fnct_search=_invoice_search),
         'account_tax_id':fields.many2one('account.tax', 'Tax'),
         'analytic_account_id' : fields.many2one('account.analytic.account', 'Analytic Account'),
 #TODO: remove this
-        'amount_taxed':fields.float("Taxed Amount",digits=(16,2)),
+        'amount_taxed':fields.float("Taxed Amount",digits=(16,int(tools.config['price_accuracy']))),
+        'company_id': fields.related('account_id','company_id',type='many2one',relation='res.company',string='Company',store=True)
 
     }
 
@@ -401,6 +424,7 @@ class account_move_line(osv.osv):
         'currency_id': _get_currency,
         'journal_id': lambda self, cr, uid, c: c.get('journal_id', False),
         'period_id': lambda self, cr, uid, c: c.get('period_id', False),
+        'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', c)
     }
     _order = "date desc,id desc"
     _sql_constraints = [
@@ -530,6 +554,7 @@ class account_move_line(osv.osv):
 
     def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context={}):
         id_set = ','.join(map(str, ids))
+
         lines = self.browse(cr, uid, ids, context=context)
         unrec_lines = filter(lambda x: not x['reconcile_id'], lines)
         credit = debit = 0.0
@@ -558,13 +583,13 @@ class account_move_line(osv.osv):
                 GROUP BY account_id,reconcile_id')
         r = cr.fetchall()
 #TODO: move this check to a constraint in the account_move_reconcile object
-        if (len(r) != 1) and context.get('same_account', True):
+        if (len(r) != 1) and not context.get('fy_closing', False):
             raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! '))
         if not unrec_lines:
             raise osv.except_osv(_('Error'), _('Entry is already reconciled'))
         account = self.pool.get('account.account').browse(cr, uid, account_id, context=context)
-        if not account.reconcile:
-            raise osv.except_osv(_('Error'), _('The account is not defined to be reconcile !'))
+        if not context.get('fy_closing', False) and not account.reconcile:
+            raise osv.except_osv(_('Error'), _('The account is not defined to be reconciled !'))
         if r[0][1] != None:
             raise osv.except_osv(_('Error'), _('Some entries are already reconciled !'))
 
@@ -605,6 +630,7 @@ class account_move_line(osv.osv):
                     'debit':debit,
                     'credit':credit,
                     'account_id':writeoff_acc_id,
+                    'analytic_account_id': context.get('analytic_id', False),
                     'date':date,
                     'partner_id':partner_id
                 })
@@ -613,7 +639,7 @@ class account_move_line(osv.osv):
             writeoff_move_id = self.pool.get('account.move').create(cr, uid, {
                 'period_id': writeoff_period_id,
                 'journal_id': writeoff_journal_id,
-
+                'date':date,
                 'state': 'draft',
                 'line_id': writeoff_lines
             })
@@ -650,8 +676,8 @@ class account_move_line(osv.osv):
             return j+(p and (':'+p) or '')
         return False
 
-    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False):
-        result = super(osv.osv, self).fields_view_get(cr, uid, view_id,view_type,context,toolbar=toolbar)
+    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False, submenu=False):
+        result = super(osv.osv, self).fields_view_get(cr, uid, view_id,view_type,context,toolbar=toolbar, submenu=submenu)
         if view_type=='tree' and 'journal_id' in context:
             title = self.view_header_get(cr, uid, view_id, view_type, context)
             journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
@@ -791,6 +817,7 @@ class account_move_line(osv.osv):
             context['period_id'] = m.period_id.id
 
         self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context)
+        company_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
 
         move_id = vals.get('move_id', False)
         journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
@@ -803,7 +830,7 @@ class account_move_line(osv.osv):
                 if res:
                     if res[1] != 'draft':
                         raise osv.except_osv(_('UserError'),
-                                _('The account move (%s) for centralisation ' \
+                                _('The Ledger Posting (%s) for centralisation ' \
                                         'has been confirmed!') % res[2])
                     vals['move_id'] = res[0]
 
@@ -827,7 +854,7 @@ class account_move_line(osv.osv):
             if journal.type_control_ids:
                 type = account.user_type
                 for t in journal.type_control_ids:
-                    if type==t.code:
+                    if type.code == t.code:
                         ok = True
                         break
             if journal.account_control_ids and not ok:
@@ -835,7 +862,7 @@ class account_move_line(osv.osv):
                     if a.id==vals['account_id']:
                         ok = True
                         break
-            if (account.currency_id) and 'amount_currency' not in vals:
+            if (account.currency_id) and 'amount_currency' not in vals and account.currency_id.id <> company_currency:
                 vals['currency_id'] = account.currency_id.id
                 cur_obj = self.pool.get('res.currency')
                 ctx = {}
@@ -847,7 +874,6 @@ class account_move_line(osv.osv):
         if not ok:
             raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !'))
 
-#        result = super(osv.osv, self).create(cr, uid, vals, context)
         if 'analytic_account_id' in vals and vals['analytic_account_id']:
             if journal.analytic_journal_id:
                 vals['analytic_lines'] = [(0,0, {
@@ -858,7 +884,7 @@ class account_move_line(osv.osv):
                         'amount': vals['debit'] or vals['credit'],
                         'general_account_id': vals['account_id'],
                         'journal_id': journal.analytic_journal_id.id,
-                        'ref': vals['ref'],
+                        'ref': vals.get('ref', False),
                     })]
             #else:
             #    raise osv.except_osv(_('No analytic journal !'), _('Please set an analytic journal on this financial journal !'))
@@ -899,7 +925,7 @@ class account_move_line(osv.osv):
                         'move_id': vals['move_id'],
                         'journal_id': vals['journal_id'],
                         'period_id': vals['period_id'],
-                        'name': vals['name']+' '+tax['name'],
+                        'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
                         'date': vals['date'],
                         'partner_id': vals.get('partner_id',False),
                         'ref': vals.get('ref',False),
@@ -918,7 +944,7 @@ class account_move_line(osv.osv):
                     'move_id': vals['move_id'],
                     'journal_id': vals['journal_id'],
                     'period_id': vals['period_id'],
-                    'name': vals['name']+' '+tax['name'],
+                    'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
                     'date': vals['date'],
                     'partner_id': vals.get('partner_id',False),
                     'ref': vals.get('ref',False),
@@ -933,9 +959,12 @@ class account_move_line(osv.osv):
                     self.create(cr, uid, data, context)
             del vals['account_tax_id']
 
-        if not is_new_move and 'date' in vals:
-            self.pool.get('account.move').write(cr, uid, [move_id], {'date':vals['date']}, context=context)
-        if check:
+        # No needed, related to the job
+        #if not is_new_move and 'date' in vals:
+        #    if context and ('__last_update' in context):
+        #        del context['__last_update']
+        #    self.pool.get('account.move').write(cr, uid, [move_id], {'date':vals['date']}, context=context)
+        if check and not context.get('no_store_function'):
             tmp = self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context)
             if journal.entry_posted and tmp:
                 self.pool.get('account.move').button_validate(cr,uid, [vals['move_id']],context)