Ejemplo n.º 1
0
    def _balance_check(self):
        for stmt in self:
            if not stmt.currency_id.is_zero(stmt.difference):
                if stmt.journal_type == 'cash':
                    if stmt.difference < 0.0:
                        account = stmt.journal_id.loss_account_id
                        name = _('Loss')
                    else:
                        # statement.difference > 0.0
                        account = stmt.journal_id.profit_account_id
                        name = _('Profit')
                    if not account:
                        raise UserError(_('There is no account defined on the journal %s for %s involved in a cash difference.') % (stmt.journal_id.name, name))

                    values = {
                        'statement_id': stmt.id,
                        'account_id': account.id,
                        'amount': stmt.difference,
                        'name': _("Cash difference observed during the counting (%s)") % name,
                    }
                    self.env['account.bank.statement.line'].create(values)
                else:
                    balance_end_real = formatLang(self.env, stmt.balance_end_real, currency_obj=stmt.currency_id)
                    balance_end = formatLang(self.env, stmt.balance_end, currency_obj=stmt.currency_id)
                    raise UserError(_('The ending balance is incorrect !\nThe expected balance (%s) is different from the computed one. (%s)')
                        % (balance_end_real, balance_end))
        return True
Ejemplo n.º 2
0
    def _balance_check(self):
        for stmt in self:
            if not stmt.currency_id.is_zero(stmt.difference):
                if stmt.journal_type == 'cash':
                    if stmt.difference < 0.0:
                        account = stmt.journal_id.loss_account_id
                        name = _('Loss')
                    else:
                        # statement.difference > 0.0
                        account = stmt.journal_id.profit_account_id
                        name = _('Profit')
                    if not account:
                        raise UserError(_('There is no account defined on the journal %s for %s involved in a cash difference.') % (stmt.journal_id.name, name))

                    values = {
                        'statement_id': stmt.id,
                        'account_id': account.id,
                        'amount': stmt.difference,
                        'name': _("Cash difference observed during the counting (%s)") % name,
                    }
                    self.env['account.bank.statement.line'].create(values)
                else:
                    balance_end_real = formatLang(self.env, stmt.balance_end_real, currency_obj=stmt.currency_id)
                    balance_end = formatLang(self.env, stmt.balance_end, currency_obj=stmt.currency_id)
                    raise UserError(_('The ending balance is incorrect !\nThe expected balance (%s) is different from the computed one. (%s)')
                        % (balance_end_real, balance_end))
        return True
Ejemplo n.º 3
0
    def get_journal_dashboard_datas(self):
        number_to_reconcile = last_balance = account_sum = 0
        ac_bnk_stmt = []
        title = ''
        number_draft = number_waiting = number_late = sum_draft = sum_waiting = sum_late = 0
        if self.type in ['bank', 'cash']:
            last_bank_stmt = self.env['account.bank.statement'].search([('journal_id', 'in', self.ids)], order="date desc, id desc", limit=1)
            last_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0
            ac_bnk_stmt = self.env['account.bank.statement'].search([('journal_id', 'in', self.ids),('state', '=', 'open')])
            for ac_bnk in ac_bnk_stmt:
                for line in ac_bnk.line_ids:
                    if not line.journal_entry_ids:
                        number_to_reconcile += 1
            # optimization to read sum of balance from account_move_line
            account_ids = tuple(filter(None, [self.default_debit_account_id.id, self.default_credit_account_id.id]))
            if account_ids:
                query = """SELECT sum(balance) FROM account_move_line WHERE account_id in %s;"""
                self.env.cr.execute(query, (account_ids,))
                query_results = self.env.cr.dictfetchall()
                if query_results and query_results[0].get('sum') != None:
                    account_sum = query_results[0].get('sum')
        #TODO need to check if all invoices are in the same currency than the journal!!!!
        elif self.type in ['sale', 'purchase']:
            title = _('Bills you need to pay') if self.type == 'purchase' else _('Invoices owed to you')
            # optimization to find total and sum of invoice that are in draft, open state
            query = """SELECT state, count(id) AS count, sum(amount_total) AS total FROM account_invoice WHERE journal_id = %s AND state NOT IN ('paid', 'cancel') GROUP BY state;"""
            self.env.cr.execute(query, (self.id,))
            query_results = self.env.cr.dictfetchall()
            today = datetime.today()
            query = """SELECT count(id) AS count_late, sum(amount_total) AS total FROM account_invoice WHERE journal_id = %s AND date < %s AND state = 'open';"""
            self.env.cr.execute(query, (self.id, today))
            late_query_results = self.env.cr.dictfetchall()
            for result in query_results:
                if result.get('state') in ['draft', 'proforma', 'proforma2']:
                    number_draft = result.get('count')
                    sum_draft = result.get('total')
                elif result.get('state') == 'open':
                    number_waiting = result.get('count')
                    sum_waiting = result.get('total')
            if late_query_results and late_query_results[0].get('count_late') != None:
                number_late = late_query_results[0].get('count_late')
                sum_late = late_query_results[0].get('total')

        return {
            'number_to_reconcile': number_to_reconcile,
            'account_balance': formatLang(self.env, account_sum, currency_obj=self.currency_id or self.company_id.currency_id),
            'last_balance': formatLang(self.env, last_balance, currency_obj=self.currency_id or self.company_id.currency_id),
            'number_draft': number_draft,
            'number_waiting': number_waiting,
            'number_late': number_late,
            'sum_draft': formatLang(self.env, sum_draft or 0.0, currency_obj=self.currency_id or self.company_id.currency_id),
            'sum_waiting': formatLang(self.env, sum_waiting or 0.0, currency_obj=self.currency_id or self.company_id.currency_id),
            'sum_late': formatLang(self.env, sum_late or 0.0, currency_obj=self.currency_id or self.company_id.currency_id),
            'currency_id': self.currency_id and self.currency_id.id or self.company_id.currency_id.id,
            'no_statement': bool(self.type in ['bank', 'cash'] and len(ac_bnk_stmt) == 0),
            'bank_statements_source': self.bank_statements_source,
            'title': title, 
        }
Ejemplo n.º 4
0
 def formatPrices(self, prices=None, dp='Product Price'):
     if prices is None:
         prices = {}
     dp = None
     prices['taxes'] = formatLang(self.env,
                                  prices['taxes'],
                                  monetary=True,
                                  dp=dp)
     prices['total'] = formatLang(self.env,
                                  prices['total'],
                                  monetary=True,
                                  dp=dp)
     prices['vals'] = [(v[0], v[1],
                        formatLang(self.env, v[2], monetary=True, dp=dp))
                       for v in prices['vals']]
     return prices
Ejemplo n.º 5
0
    def get_journal_dashboard_datas(self):
        domain_holding_third_checks = [
            # ('payment_method_id.code', '=', 'received_third_check'),
            ('type', '=', 'third_check'),
            ('journal_id', '=', self.id),
            # ('check_state', '=', 'holding')
            ('state', '=', 'holding')
        ]
        domain_handed_issue_checks = [
            # ('payment_method_id.code', '=', 'issue_check'),
            ('type', '=', 'issue_check'),
            ('journal_id', '=', self.id),
            ('state', '=', 'handed')
            # ('check_state', '=', 'handed')
        ]
        handed_checks = self.env['account.check'].search(
            domain_handed_issue_checks)
        holding_checks = self.env['account.check'].search(
            domain_holding_third_checks)

        num_checks_to_numerate = False
        if self.env['ir.actions.report.xml'].search(
                [('report_name', '=', 'check_report')]):
            num_checks_to_numerate = self.env['account.payment'].search_count([
                ('journal_id', '=', self.id),
                ('payment_method_id.code', '=', 'issue_check'),
                ('state', '=', 'draft'),
                ('check_name', '=', False),
            ])
        return dict(
            super(AccountJournal, self).get_journal_dashboard_datas(),
            num_checks_to_numerate=num_checks_to_numerate,
            num_holding_third_checks=len(holding_checks),
            show_third_checks=(
                'received_third_check' in
                self.inbound_payment_method_ids.mapped('code')),
            show_issue_checks=(
                'issue_check' in
                self.outbound_payment_method_ids.mapped('code')),
            num_handed_issue_checks=len(handed_checks),
            handed_amount=formatLang(
                self.env, sum(handed_checks.mapped('amount')),
                currency_obj=self.currency_id or self.company_id.currency_id),
            holding_amount=formatLang(
                self.env, sum(holding_checks.mapped('amount')),
                currency_obj=self.currency_id or self.company_id.currency_id),
        )
 def _format(self, value):
     if self.env.context.get('no_format'):
         return value
     currency_id = self.env.user.company_id.currency_id
     if currency_id.is_zero(value):
         # don't print -0.0 in reports
         value = abs(value)
     return formatLang(self.env, value, currency_obj=currency_id)
 def _format(self, value, currency=False):
     if self.env.context.get('no_format'):
         return value
     currency_id = currency or self.env.user.company_id.currency_id
     if currency_id.is_zero(value):
         value = abs(value)
     res = formatLang(self.env, value, currency_obj=currency_id)
     return res
    def get_lines(self, context_id, line_id=None):
        lines = []

        partner_ids = self.env['res.partner'].search([('vat_subjected', '!=', False), ('vat', 'ilike', 'BE%')]).ids
        if not partner_ids:
            return lines
        tag_ids = [self.env['ir.model.data'].xmlid_to_res_id(k) for k in ['l10n_be.tax_tag_base_00', 'l10n_be.tax_tag_base_01', 'l10n_be.tax_tag_base_02', 'l10n_be.tax_tag_base_03', 'l10n_be.tax_tag_base_45']]
        tag_ids_2 = [self.env['ir.model.data'].xmlid_to_res_id(k) for k in ['l10n_be.tax_tag_base_01', 'l10n_be.tax_tag_base_02', 'l10n_be.tax_tag_base_03']]
        self.env.cr.execute("""SELECT sub1.partner_id, sub1.name, sub1.vat, sub1.turnover, sub2.vat_amount
            FROM (SELECT l.partner_id, p.name, p.vat, SUM(l.balance) as turnover
                  FROM account_move_line l
                  LEFT JOIN res_partner p ON l.partner_id = p.id
                  LEFT JOIN account_move_line_account_tax_rel amlt ON l.id = amlt.account_move_line_id
                  LEFT JOIN account_tax_account_tag tt on amlt.account_tax_id = tt.account_tax_id
                  WHERE tt.account_account_tag_id IN %s
                  AND l.partner_id IN %s
                  AND l.date >= %s
                  AND l.date <= %s
                  GROUP BY l.partner_id, p.name, p.vat) AS sub1
            LEFT JOIN (SELECT l2.partner_id, SUM(l2.balance) as vat_amount
                  FROM account_move_line l2
                  LEFT JOIN account_tax_account_tag tt2 on l2.tax_line_id = tt2.account_tax_id
                  WHERE tt2.account_account_tag_id IN %s
                  AND l2.partner_id IN %s
                  AND l2.date > %s
                  AND l2.date < %s
                  GROUP BY l2.partner_id) AS sub2 ON sub1.partner_id = sub2.partner_id
                """, (tuple(tag_ids), tuple(partner_ids), context_id.date_from, context_id.date_to, tuple(tag_ids_2), tuple(partner_ids), context_id.date_from, context_id.date_to))
        for record in self.env.cr.dictfetchall():
            columns = [record['vat'].replace(' ', '').upper(), record['turnover'], record['vat_amount']]
            if not self.env.context.get('no_format', False):
                currency_id = self.env.user.company_id.currency_id
                columns[1] = formatLang(self.env, columns[1], currency_obj=currency_id)
                columns[2] = formatLang(self.env, columns[2], currency_obj=currency_id)
            lines.append({
                'id': record['partner_id'],
                'type': 'partner_id',
                'name': record['name'],
                'footnotes': context_id._get_footnotes('partner_id', record['partner_id']),
                'columns': columns,
                'level': 2,
                'unfoldable': False,
                'unfolded': False,
            })
        return lines
Ejemplo n.º 9
0
 def _compute_issued_total(self):
     """ Returns the issued total as will be displayed on partner view """
     today = fields.Date.context_today(self)
     for partner in self:
         domain = partner.get_followup_lines_domain(today, overdue_only=True)
         issued_total = 0
         for aml in self.env["account.move.line"].search(domain):
             issued_total += aml.amount_residual
         partner.issued_total = formatLang(self.env, issued_total, currency_obj=self.env.user.company_id.currency_id)
Ejemplo n.º 10
0
 def _get_tax_amount_by_group(self):
     self.ensure_one()
     res = {}
     currency = self.currency_id or self.company_id.currency_id
     for line in self.tax_line_ids:
         res.setdefault(line.tax_id.tax_group_id, 0.0)
         res[line.tax_id.tax_group_id] += line.amount
     res = sorted(res.items(), key=lambda l: l[0].sequence)
     res = map(lambda l: (l[0].name, formatLang(self.env, l[1], currency_obj=currency)), res)
     return res
Ejemplo n.º 11
0
 def name_get(self):
     result = []
     for po in self:
         name = po.name
         if po.partner_ref:
             name += ' ('+po.partner_ref+')'
         if po.amount_total:
             name += ': ' + formatLang(self.env, po.amount_total, currency_obj=po.currency_id)
         result.append((po.id, name))
     return result
Ejemplo n.º 12
0
 def name_get(self):
     result = []
     for po in self:
         name = po.name
         if po.partner_ref:
             name += ' ('+po.partner_ref+')'
         if po.amount_total:
             name += ': ' + formatLang(self.env, po.amount_total, currency_obj=po.currency_id)
         result.append((po.id, name))
     return result
Ejemplo n.º 13
0
 def _format(self, value):
     if self.env.context.get('no_format'):
         return value
     if self.figure_type == 'float':
         currency_id = self.env.user.company_id.currency_id
         if currency_id.is_zero(value):
             # don't print -0.0 in reports
             value = abs(value)
         return formatLang(self.env, value, currency_obj=currency_id)
     if self.figure_type == 'percents':
         return str(round(value * 100, 1)) + '%'
     return round(value, 1)
Ejemplo n.º 14
0
Archivo: sale.py Proyecto: AtomLaw/odoo
 def _get_tax_amount_by_group(self):
     self.ensure_one()
     res = {}
     currency = self.currency_id or self.company_id.currency_id
     for line in self.order_line:
         for tax in line.tax_id:
             group = tax.tax_group_id
             res.setdefault(group, 0.0)
             res[group] += tax.compute_all(line.price_unit, quantity=line.product_uom_qty)['taxes'][0]['amount']
     res = sorted(res.items(), key=lambda l: l[0].sequence)
     res = map(lambda l: (l[0].name, formatLang(self.env, l[1], currency_obj=currency)), res)
     return res
Ejemplo n.º 15
0
 def _get_tax_amount_by_group(self):
     self.ensure_one()
     res = {}
     currency = self.currency_id or self.company_id.currency_id
     for line in self.order_line:
         for tax in line.tax_id:
             group = tax.tax_group_id
             res.setdefault(group, 0.0)
             res[group] += tax.compute_all(line.price_unit, quantity=line.product_uom_qty)['taxes'][0]['amount']
     res = sorted(res.items(), key=lambda l: l[0].sequence)
     res = map(lambda l: (l[0].name, formatLang(self.env, l[1], currency_obj=currency)), res)
     return res
Ejemplo n.º 16
0
    def get_statement_line_for_reconciliation_widget(self):
        """ Returns the data required by the bank statement reconciliation widget to display a statement line """
        statement_currency = self.journal_id.currency_id or self.journal_id.company_id.currency_id
        if self.amount_currency and self.currency_id:
            amount = self.amount_currency
            amount_currency = self.amount
            amount_currency_str = amount_currency > 0 and amount_currency or -amount_currency
            amount_currency_str = formatLang(self.env, amount_currency_str, currency_obj=statement_currency)
        else:
            amount = self.amount
            amount_currency_str = ""
        amount_str = formatLang(self.env, abs(amount), currency_obj=self.currency_id or statement_currency)

        data = {
            'id': self.id,
            'ref': self.ref,
            'note': self.note or "",
            'name': self.name,
            'date': self.date,
            'amount': amount,
            'amount_str': amount_str,  # Amount in the statement line currency
            'currency_id': self.currency_id.id or statement_currency.id,
            'partner_id': self.partner_id.id,
            'journal_id': self.journal_id.id,
            'statement_id': self.statement_id.id,
            'account_code': self.journal_id.default_debit_account_id.code,
            'account_name': self.journal_id.default_debit_account_id.name,
            'partner_name': self.partner_id.name,
            'communication_partner_name': self.partner_name,
            'amount_currency_str': amount_currency_str,  # Amount in the statement currency
            'has_no_partner': not self.partner_id.id,
        }
        if self.partner_id:
            if amount > 0:
                data['open_balance_account_id'] = self.partner_id.property_account_receivable_id.id
            else:
                data['open_balance_account_id'] = self.partner_id.property_account_payable_id.id

        return data
Ejemplo n.º 17
0
    def userdef_calc_value(self, po_line, label, keyword, display, value,
                           po_type):

        if keyword == 'startup-amount':
            return value.replace(
                '{{startup-amount}}',
                formatLang(self.env,
                           po_line.startup_costs,
                           currency_obj=po_line.currency_id))

        return super(Purchase,
                     self).userdef_calc_value(po_line, label, keyword, display,
                                              value, po_type)
Ejemplo n.º 18
0
 def _compute_issued_total(self):
     """ Returns the issued total as will be displayed on partner view """
     today = fields.Date.context_today(self)
     for partner in self:
         domain = partner.get_followup_lines_domain(today,
                                                    overdue_only=True)
         issued_total = 0
         for aml in self.env['account.move.line'].search(domain):
             issued_total += aml.amount_residual
         partner.issued_total = formatLang(
             self.env,
             issued_total,
             currency_obj=self.env.user.company_id.currency_id)
Ejemplo n.º 19
0
    def get_statement_line_for_reconciliation_widget(self):
        """ Returns the data required by the bank statement reconciliation widget to display a statement line """
        statement_currency = self.journal_id.currency_id or self.journal_id.company_id.currency_id
        if self.amount_currency and self.currency_id:
            amount = self.amount_currency
            amount_currency = self.amount
            amount_currency_str = amount_currency > 0 and amount_currency or -amount_currency
            amount_currency_str = formatLang(self.env, amount_currency_str, currency_obj=statement_currency)
        else:
            amount = self.amount
            amount_currency_str = ""
        amount_str = formatLang(self.env, abs(amount), currency_obj=self.currency_id or statement_currency)

        data = {
            'id': self.id,
            'ref': self.ref,
            'note': self.note or "",
            'name': self.name,
            'date': self.date,
            'amount': amount,
            'amount_str': amount_str,  # Amount in the statement line currency
            'currency_id': self.currency_id.id or statement_currency.id,
            'partner_id': self.partner_id.id,
            'journal_id': self.journal_id.id,
            'statement_id': self.statement_id.id,
            'account_code': self.journal_id.default_debit_account_id.code,
            'account_name': self.journal_id.default_debit_account_id.name,
            'partner_name': self.partner_id.name,
            'communication_partner_name': self.partner_name,
            'amount_currency_str': amount_currency_str,  # Amount in the statement currency
            'has_no_partner': not self.partner_id.id,
        }
        if self.partner_id:
            if amount > 0:
                data['open_balance_account_id'] = self.partner_id.property_account_receivable_id.id
            else:
                data['open_balance_account_id'] = self.partner_id.property_account_payable_id.id

        return data
 def get_journal_dashboard_datas(self):
     domain_holding_third_checks = [
         # ('payment_method_id.code', '=', 'received_third_check'),
         ('type', '=', 'third_check'),
         ('journal_id', '=', self.id),
         # ('check_state', '=', 'holding')
         ('state', '=', 'holding')
     ]
     domain_handed_issue_checks = [
         # ('payment_method_id.code', '=', 'issue_check'),
         ('type', '=', 'issue_check'),
         ('journal_id', '=', self.id),
         ('state', '=', 'handed')
         # ('check_state', '=', 'handed')
     ]
     handed_checks = self.env['account.check'].search(
         domain_handed_issue_checks)
     holding_checks = self.env['account.check'].search(
         domain_holding_third_checks)
     return dict(
         super(account_journal, self).get_journal_dashboard_datas(),
         num_holding_third_checks=len(holding_checks),
         show_third_checks=(
             'received_third_check'
             in self.inbound_payment_method_ids.mapped('code')),
         show_issue_checks=(
             'issue_check'
             in self.outbound_payment_method_ids.mapped('code')),
         num_handed_issue_checks=len(handed_checks),
         handed_amount=formatLang(self.env,
                                  sum(handed_checks.mapped('amount')),
                                  currency_obj=self.currency_id
                                  or self.company_id.currency_id),
         holding_amount=formatLang(self.env,
                                   sum(holding_checks.mapped('amount')),
                                   currency_obj=self.currency_id
                                   or self.company_id.currency_id),
     )
Ejemplo n.º 21
0
 def _get_tax_amount_by_group(self):
     """
     we can not inherit because of function design, we overwrite
     """
     self.ensure_one()
     res = {}
     currency = self.currency_id or self.company_id.currency_id
     for line in self.report_tax_line_ids:
         res.setdefault(line.tax_id.tax_group_id, 0.0)
         res[line.tax_id.tax_group_id] += line.amount
     res = sorted(res.items(), key=lambda l: l[0].sequence)
     res = map(lambda l: (
         l[0].name, formatLang(self.env, l[1], currency_obj=currency)), res)
     return res
    def _get_tax_amount_by_group(self):
        self.ensure_one()
        res = {}
        currency = self.currency_id or self.company_id.currency_id
        for line in self.tax_line_ids:
            if not line.tax_id.dont_impact_balance:
                res.setdefault(line.tax_id.tax_group_id, 0.0)
                res[line.tax_id.tax_group_id] += line.amount
            
        res = sorted(res.items(), key=lambda l: l[0].sequence)
        res = map(lambda l: (l[0].name, formatLang(self.env, l[1], currency_obj=currency)), res)

        groups_not_in_invoice = self.env['account.tax.group'].search_read([('not_in_invoice','=',True)],['name'])

        for g in groups_not_in_invoice:
            for i in res:
                if g['name'] == i[0]:
                    res.remove(i)
        return res
Ejemplo n.º 23
0
    def _get_tax_amount_by_group(self):
        self.ensure_one()
        res = {}
        currency = self.currency_id or self.company_id.currency_id
        for line in self.tax_line_ids:
            if not line.tax_id.dont_impact_balance:
                res.setdefault(line.tax_id.tax_group_id, 0.0)
                res[line.tax_id.tax_group_id] += line.amount

        res = sorted(res.items(), key=lambda l: l[0].sequence)
        res = map(
            lambda l:
            (l[0].name, formatLang(self.env, l[1], currency_obj=currency)),
            res)

        groups_not_in_invoice = self.env['account.tax.group'].search_read(
            [('not_in_invoice', '=', True)], ['name'])

        for g in groups_not_in_invoice:
            for i in res:
                if g['name'] == i[0]:
                    res.remove(i)
        return res
Ejemplo n.º 24
0
 def get_journal_dashboard_datas(self):
     res = super(AccountJournal, self).get_journal_dashboard_datas()
     if self.type in ['sale', 'purchase']:
         currency = self.currency_id or self.company_id.currency_id
         sum_waiting = 0
         query = """SELECT state, residual_signed, currency_id AS currency
                    FROM account_invoice
                    WHERE journal_id = %s
                    AND state NOT IN ('paid', 'cancel');"""
         self.env.cr.execute(query, (self.id, ))
         query_results = self.env.cr.dictfetchall()
         for result in query_results:
             cur = self.env['res.currency'].browse(result.get('currency'))
             if result.get('state') == 'open':
                 sum_waiting += cur.compute(result.get('residual_signed'),
                                            currency)
         res.update({
             'sum_waiting':
             formatLang(self.env,
                        sum_waiting or 0.0,
                        currency_obj=self.currency_id
                        or self.company_id.currency_id)
         })
     return res
    def get_journal_dashboard_datas(self):
        currency = self.currency_id or self.company_id.currency_id
        number_to_reconcile = last_balance = account_sum = 0
        ac_bnk_stmt = []
        title = ''
        number_draft = number_waiting = number_late = 0
        sum_draft = sum_waiting = sum_late = 0.0
        if self.type in ['bank', 'cash']:
            last_bank_stmt = self.env['account.bank.statement'].search(
                [('journal_id', 'in', self.ids)],
                order="date desc, id desc",
                limit=1)
            last_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0
            #Get the number of items to reconcile for that bank journal
            self.env.cr.execute(
                """SELECT COUNT(DISTINCT(statement_line_id)) 
                        FROM account_move where statement_line_id 
                        IN (SELECT line.id 
                            FROM account_bank_statement_line AS line 
                            LEFT JOIN account_bank_statement AS st 
                            ON line.statement_id = st.id 
                            WHERE st.journal_id IN %s and st.state = 'open')""",
                (tuple(self.ids), ))
            already_reconciled = self.env.cr.fetchone()[0]
            self.env.cr.execute(
                """SELECT COUNT(line.id) 
                            FROM account_bank_statement_line AS line 
                            LEFT JOIN account_bank_statement AS st 
                            ON line.statement_id = st.id 
                            WHERE st.journal_id IN %s and st.state = 'open'""",
                (tuple(self.ids), ))
            all_lines = self.env.cr.fetchone()[0]
            number_to_reconcile = all_lines - already_reconciled
            # optimization to read sum of balance from account_move_line
            account_ids = tuple(
                filter(None, [
                    self.default_debit_account_id.id,
                    self.default_credit_account_id.id
                ]))
            if account_ids:
                amount_field = 'balance' if not self.currency_id else 'amount_currency'
                query = """SELECT sum(%s) FROM account_move_line WHERE account_id in %%s;""" % (
                    amount_field, )
                self.env.cr.execute(query, (account_ids, ))
                query_results = self.env.cr.dictfetchall()
                if query_results and query_results[0].get('sum') != None:
                    account_sum = query_results[0].get('sum')
        #TODO need to check if all invoices are in the same currency than the journal!!!!
        elif self.type in ['sale', 'purchase']:
            title = _('Bills to pay') if self.type == 'purchase' else _(
                'Invoices owed to you')
            # optimization to find total and sum of invoice that are in draft, open state
            query = """SELECT state, amount_total, currency_id AS currency, type FROM account_invoice WHERE journal_id = %s AND state NOT IN ('paid', 'cancel');"""
            self.env.cr.execute(query, (self.id, ))
            query_results = self.env.cr.dictfetchall()
            today = datetime.today()
            query = """SELECT amount_total, currency_id AS currency, type FROM account_invoice WHERE journal_id = %s AND date < %s AND state = 'open';"""
            self.env.cr.execute(query, (self.id, today))
            late_query_results = self.env.cr.dictfetchall()
            for result in query_results:
                if result['type'] in ['in_refund', 'out_refund']:
                    factor = -1
                else:
                    factor = 1
                cur = self.env['res.currency'].browse(result.get('currency'))
                if result.get('state') in ['draft', 'proforma', 'proforma2']:
                    number_draft += 1
                    sum_draft += cur.compute(result.get('amount_total'),
                                             currency) * factor
                elif result.get('state') == 'open':
                    number_waiting += 1
                    sum_waiting += cur.compute(result.get('amount_total'),
                                               currency) * factor
            for result in late_query_results:
                if result['type'] in ['in_refund', 'out_refund']:
                    factor = -1
                else:
                    factor = 1
                cur = self.env['res.currency'].browse(result.get('currency'))
                number_late += 1
                sum_late += cur.compute(result.get('amount_total'),
                                        currency) * factor

        return {
            'number_to_reconcile':
            number_to_reconcile,
            'account_balance':
            formatLang(self.env,
                       account_sum,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'last_balance':
            formatLang(self.env,
                       last_balance,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'number_draft':
            number_draft,
            'number_waiting':
            number_waiting,
            'number_late':
            number_late,
            'sum_draft':
            formatLang(self.env,
                       sum_draft or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_waiting':
            formatLang(self.env,
                       sum_waiting or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_late':
            formatLang(self.env,
                       sum_late or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'currency_id':
            self.currency_id and self.currency_id.id
            or self.company_id.currency_id.id,
            'bank_statements_source':
            self.bank_statements_source,
            'title':
            title,
        }
Ejemplo n.º 26
0
    def get_journal_dashboard_datas(self):
        currency = self.currency_id or self.company_id.currency_id
        number_to_reconcile = last_balance = account_sum = 0
        ac_bnk_stmt = []
        title = ''
        number_draft = number_waiting = number_late = sum_draft = sum_waiting = sum_late = 0
        if self.type in ['bank', 'cash']:
            last_bank_stmt = self.env['account.bank.statement'].search(
                [('journal_id', 'in', self.ids)],
                order="date desc, id desc",
                limit=1)
            last_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0
            ac_bnk_stmt = self.env['account.bank.statement'].search([
                ('journal_id', 'in', self.ids), ('state', '=', 'open')
            ])
            for ac_bnk in ac_bnk_stmt:
                for line in ac_bnk.line_ids:
                    if not line.journal_entry_ids:
                        number_to_reconcile += 1
            # optimization to read sum of balance from account_move_line
            account_ids = tuple(
                filter(None, [
                    self.default_debit_account_id.id,
                    self.default_credit_account_id.id
                ]))
            if account_ids:
                amount_field = 'balance' if not self.currency_id else 'amount_currency'
                query = """SELECT sum(%s) FROM account_move_line WHERE account_id in %%s;""" % (
                    amount_field, )
                self.env.cr.execute(query, (account_ids, ))
                query_results = self.env.cr.dictfetchall()
                if query_results and query_results[0].get('sum') != None:
                    account_sum = query_results[0].get('sum')
        #TODO need to check if all invoices are in the same currency than the journal!!!!
        elif self.type in ['sale', 'purchase']:
            title = _('Bills to pay') if self.type == 'purchase' else _(
                'Invoices owed to you')
            # optimization to find total and sum of invoice that are in draft, open state
            query = """SELECT state, amount_total, currency_id AS currency FROM account_invoice WHERE journal_id = %s AND state NOT IN ('paid', 'cancel');"""
            self.env.cr.execute(query, (self.id, ))
            query_results = self.env.cr.dictfetchall()
            today = datetime.today()
            query = """SELECT amount_total, currency_id AS currency FROM account_invoice WHERE journal_id = %s AND date < %s AND state = 'open';"""
            self.env.cr.execute(query, (self.id, today))
            late_query_results = self.env.cr.dictfetchall()
            sum_draft = 0.0
            number_draft = 0
            number_waiting = 0
            for result in query_results:
                cur = self.env['res.currency'].browse(result.get('currency'))
                if result.get('state') in ['draft', 'proforma', 'proforma2']:
                    number_draft += 1
                    sum_draft += cur.compute(result.get('amount_total'),
                                             currency)
                elif result.get('state') == 'open':
                    number_waiting += 1
                    sum_waiting += cur.compute(result.get('amount_total'),
                                               currency)
            sum_late = 0.0
            number_late = 0
            for result in late_query_results:
                cur = self.env['res.currency'].browse(result.get('currency'))
                number_late += 1
                sum_late += cur.compute(result.get('amount_total'), currency)

        return {
            'number_to_reconcile':
            number_to_reconcile,
            'account_balance':
            formatLang(self.env,
                       account_sum,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'last_balance':
            formatLang(self.env,
                       last_balance,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'difference': (last_balance - account_sum) and formatLang(
                self.env,
                last_balance - account_sum,
                currency_obj=self.currency_id or self.company_id.currency_id)
            or False,
            'number_draft':
            number_draft,
            'number_waiting':
            number_waiting,
            'number_late':
            number_late,
            'sum_draft':
            formatLang(self.env,
                       sum_draft or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_waiting':
            formatLang(self.env,
                       sum_waiting or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_late':
            formatLang(self.env,
                       sum_late or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'currency_id':
            self.currency_id and self.currency_id.id
            or self.company_id.currency_id.id,
            'bank_statements_source':
            self.bank_statements_source,
            'title':
            title,
        }
 def number_format( self, currency_id, amount ):
     return formatLang(self.env, amount, currency_obj = currency_id, digits=0 ).replace(",", ".")
Ejemplo n.º 28
0
    def get_lines(self, context_id, line_id=None, public=False):
        # Get date format for the lang
        lang_code = context_id.partner_id.lang or self.env.user.lang or 'en_US'
        lang_ids = self.env['res.lang'].search([('code', '=', lang_code)],
                                               limit=1)
        date_format = lang_ids.date_format or DEFAULT_SERVER_DATE_FORMAT

        def formatLangDate(date):
            date_dt = datetime.strptime(date, DEFAULT_SERVER_DATE_FORMAT)
            return date_dt.strftime(date_format)

        lines = []
        res = {}
        today = datetime.today().strftime('%Y-%m-%d')
        line_num = 0
        for l in context_id.partner_id.unreconciled_aml_ids:
            if public and l.blocked:
                continue
            currency = l.currency_id or l.company_id.currency_id
            if currency not in res:
                res[currency] = []
            res[currency].append(l)
        for currency, aml_recs in res.items():
            total = 0
            total_issued = 0
            aml_recs = sorted(aml_recs, key=lambda aml: aml.blocked)
            for aml in aml_recs:
                amount = aml.currency_id and aml.amount_residual_currency or aml.amount_residual
                date_due = formatLangDate(aml.date_maturity or aml.date)
                total += not aml.blocked and amount or 0
                is_overdue = today > aml.date_maturity if aml.date_maturity else today > aml.date
                is_payment = aml.payment_id
                if is_overdue or is_payment:
                    total_issued += not aml.blocked and amount or 0
                if is_overdue:
                    date_due = (date_due, 'color: red;')
                if is_payment:
                    date_due = ''
                amount = formatLang(self.env, amount, currency_obj=currency)
                line_num += 1
                lines.append({
                    'id':
                    aml.id,
                    'name':
                    aml.move_id.name,
                    'action':
                    aml.get_model_id_and_name(),
                    'move_id':
                    aml.move_id.id,
                    'type':
                    is_payment and 'payment' or 'unreconciled_aml',
                    'footnotes': {},
                    'unfoldable':
                    False,
                    'columns': [
                        formatLangDate(aml.date), date_due,
                        aml.invoice_id.reference
                    ] + (not public and [
                        aml.expected_pay_date and
                        (aml.expected_pay_date, aml.internal_note) or
                        ('', ''), aml.blocked
                    ] or []) + [amount],
                    'blocked':
                    aml.blocked,
                })
            total = formatLang(self.env, total, currency_obj=currency)
            line_num += 1
            lines.append({
                'id':
                line_num,
                'name':
                '',
                'type':
                'total',
                'footnotes': {},
                'unfoldable':
                False,
                'level':
                0,
                'columns': (not public and ['', ''] or []) +
                ['', '', total >= 0 and _('Total Due') or ''] + [total],
            })
            if total_issued > 0:
                total_issued = formatLang(self.env,
                                          total_issued,
                                          currency_obj=currency)
                line_num += 1
                lines.append({
                    'id':
                    line_num,
                    'name':
                    '',
                    'type':
                    'total',
                    'footnotes': {},
                    'unfoldable':
                    False,
                    'level':
                    0,
                    'columns': (not public and ['', ''] or []) +
                    ['', '', _('Total Overdue')] + [total_issued],
                })
        return lines
 def number_format(self, currency_id, amount):
     return formatLang(self.env, amount, currency_obj=currency_id,
                       digits=0).replace(",", ".")
Ejemplo n.º 30
0
    def get_lines(self, context_id, line_id=None, public=False):
        # res = super(report_account_followup_report, self).get_lines(
        #     context_id, line_id=line_id, public=public)

        # Get date format for the lang
        lang_code = context_id.partner_id.lang or self.env.user.lang or 'en_US'
        lang_ids = self.env['res.lang'].search([('code', '=', lang_code)],
                                               limit=1)
        date_format = lang_ids.date_format or DEFAULT_SERVER_DATE_FORMAT

        def formatLangDate(date):
            date_dt = datetime.strptime(date, DEFAULT_SERVER_DATE_FORMAT)
            return date_dt.strftime(
                date_format.encode('utf-8')).decode('utf-8')

        lines = []
        res = {}
        today = datetime.today().strftime('%Y-%m-%d')
        line_num = 0
        # we use debt lines instead of move lines
        # we use commercial partner instead of partner to fix this for portal
        # user / contacts
        commercial_partner = context_id.partner_id.commercial_partner_id
        for l in commercial_partner.unreconciled_adl_ids:
            if public and l.blocked:
                continue
            # nativamente odoo separa la deuda en usd y en ars en distintas
            # secciones, nosotros las juntamos
            currency = l.company_id.currency_id
            # currency = l.currency_id or l.company_id.currency_id
            if currency not in res:
                res[currency] = []
            res[currency].append(l)
        for currency, aml_recs in res.items():
            total = 0
            total_issued = 0
            aml_recs = sorted(aml_recs, key=lambda aml: aml.blocked)
            for aml in aml_recs:
                # odoo separa por monedas, nosotros lo juntamos
                amount = aml.amount_residual
                # amount = (
                #     aml.currency_id and aml.amount_residual_currency or
                #     aml.amount_residual)
                date_due = formatLangDate(aml.date_maturity or aml.date)
                total += not aml.blocked and amount or 0
                is_overdue = (today > aml.date_maturity
                              if aml.date_maturity else today > aml.date)
                is_payment = aml.payment_group_id
                if is_overdue or is_payment:
                    total_issued += not aml.blocked and amount or 0
                if is_overdue:
                    date_due = (date_due, 'color: red;')
                if is_payment:
                    date_due = ''
                amount = formatLang(self.env, amount, currency_obj=currency)
                line_num += 1
                lines.append({
                    'id':
                    aml.id,
                    'name':
                    aml.document_number,
                    # 'name': aml.move_id.name,
                    'action':
                    aml.get_model_id_and_name(),
                    # TODO ver que hacemos cuando el resultado es mas de un
                    # move
                    'move_id':
                    aml.move_id.id,
                    'type':
                    is_payment and 'payment' or 'unreconciled_aml',
                    'footnotes': {},
                    'unfoldable':
                    False,
                    'columns': [
                        formatLangDate(aml.date), date_due, aml.invoice_id.name
                        or aml.name
                    ] + (not public and [
                        aml.expected_pay_date and
                        (aml.expected_pay_date, aml.internal_note) or
                        ('', ''), aml.blocked
                    ] or []) + [amount],
                    'blocked':
                    aml.blocked,
                })
            total = formatLang(self.env, total, currency_obj=currency)
            line_num += 1
            lines.append({
                'id':
                line_num,
                'name':
                '',
                'type':
                'total',
                'footnotes': {},
                'unfoldable':
                False,
                'level':
                0,
                'columns': (not public and ['', ''] or []) +
                ['', '', total >= 0 and _('Total Due') or ''] + [total],
            })
            if total_issued > 0:
                total_issued = formatLang(self.env,
                                          total_issued,
                                          currency_obj=currency)
                line_num += 1
                lines.append({
                    'id':
                    line_num,
                    'name':
                    '',
                    'type':
                    'total',
                    'footnotes': {},
                    'unfoldable':
                    False,
                    'level':
                    0,
                    'columns': (not public and ['', ''] or []) +
                    ['', '', _('Total Overdue')] + [total_issued],
                })
        return lines
Ejemplo n.º 31
0
    def get_journal_dashboard_datas(self):
        number_to_reconcile = last_balance = account_sum = 0
        ac_bnk_stmt = []
        title = ''
        number_draft = number_waiting = number_late = sum_draft = sum_waiting = sum_late = 0
        if self.type in ['bank', 'cash']:
            last_bank_stmt = self.env['account.bank.statement'].search(
                [('journal_id', 'in', self.ids)],
                order="date desc, id desc",
                limit=1)
            last_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0
            ac_bnk_stmt = self.env['account.bank.statement'].search([
                ('journal_id', 'in', self.ids), ('state', '=', 'open')
            ])
            for ac_bnk in ac_bnk_stmt:
                for line in ac_bnk.line_ids:
                    if not line.journal_entry_ids:
                        number_to_reconcile += 1
            # optimization to read sum of balance from account_move_line
            account_ids = tuple(
                filter(None, [
                    self.default_debit_account_id.id,
                    self.default_credit_account_id.id
                ]))
            if account_ids:
                query = """SELECT sum(balance) FROM account_move_line WHERE account_id in %s;"""
                self.env.cr.execute(query, (account_ids, ))
                query_results = self.env.cr.dictfetchall()
                if query_results and query_results[0].get('sum') != None:
                    account_sum = query_results[0].get('sum')
        #TODO need to check if all invoices are in the same currency than the journal!!!!
        elif self.type in ['sale', 'purchase']:
            title = _(
                'Bills you need to pay') if self.type == 'purchase' else _(
                    'Invoices owed to you')
            # optimization to find total and sum of invoice that are in draft, open state
            query = """SELECT state, count(id) AS count, sum(amount_total) AS total FROM account_invoice WHERE journal_id = %s AND state NOT IN ('paid', 'cancel') GROUP BY state;"""
            self.env.cr.execute(query, (self.id, ))
            query_results = self.env.cr.dictfetchall()
            today = datetime.today()
            query = """SELECT count(id) AS count_late, sum(amount_total) AS total FROM account_invoice WHERE journal_id = %s AND date < %s AND state = 'open';"""
            self.env.cr.execute(query, (self.id, today))
            late_query_results = self.env.cr.dictfetchall()
            for result in query_results:
                if result.get('state') in ['draft', 'proforma', 'proforma2']:
                    number_draft = result.get('count')
                    sum_draft = result.get('total')
                elif result.get('state') == 'open':
                    number_waiting = result.get('count')
                    sum_waiting = result.get('total')
            if late_query_results and late_query_results[0].get(
                    'count_late') != None:
                number_late = late_query_results[0].get('count_late')
                sum_late = late_query_results[0].get('total')

        return {
            'number_to_reconcile':
            number_to_reconcile,
            'account_balance':
            formatLang(self.env,
                       account_sum,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'last_balance':
            formatLang(self.env,
                       last_balance,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'number_draft':
            number_draft,
            'number_waiting':
            number_waiting,
            'number_late':
            number_late,
            'sum_draft':
            formatLang(self.env,
                       sum_draft or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_waiting':
            formatLang(self.env,
                       sum_waiting or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_late':
            formatLang(self.env,
                       sum_late or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'currency_id':
            self.currency_id and self.currency_id.id
            or self.company_id.currency_id.id,
            'show_import':
            True if self.type in ['bank', 'cash'] and len(ac_bnk_stmt) == 0
            and last_balance == 0 else False,
            'title':
            title,
        }
    def get_journal_dashboard_datas(self):
        currency = self.currency_id or self.company_id.currency_id
        number_to_reconcile = last_balance = account_sum = 0
        ac_bnk_stmt = []
        title = ''
        number_draft = number_waiting = number_late = sum_draft = sum_waiting = sum_late = 0
        if self.type in ['bank', 'cash']:
            last_bank_stmt = self.env['account.bank.statement'].search([('journal_id', 'in', self.ids)], order="date desc, id desc", limit=1)
            last_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0
            #Get the number of items to reconcile for that bank journal
            self.env.cr.execute("""SELECT COUNT(DISTINCT(statement_line_id)) 
                        FROM account_move where statement_line_id 
                        IN (SELECT line.id 
                            FROM account_bank_statement_line AS line 
                            LEFT JOIN account_bank_statement AS st 
                            ON line.statement_id = st.id 
                            WHERE st.journal_id IN %s and st.state = 'open')""", (tuple(self.ids),))
            already_reconciled = self.env.cr.fetchone()[0]
            self.env.cr.execute("""SELECT COUNT(line.id) 
                            FROM account_bank_statement_line AS line 
                            LEFT JOIN account_bank_statement AS st 
                            ON line.statement_id = st.id 
                            WHERE st.journal_id IN %s and st.state = 'open'""", (tuple(self.ids),))
            all_lines = self.env.cr.fetchone()[0]
            number_to_reconcile = all_lines - already_reconciled
            # optimization to read sum of balance from account_move_line
            account_ids = tuple(filter(None, [self.default_debit_account_id.id, self.default_credit_account_id.id]))
            if account_ids:
                amount_field = 'balance' if not self.currency_id else 'amount_currency'
                query = """SELECT sum(%s) FROM account_move_line WHERE account_id in %%s;""" % (amount_field,)
                self.env.cr.execute(query, (account_ids,))
                query_results = self.env.cr.dictfetchall()
                if query_results and query_results[0].get('sum') != None:
                    account_sum = query_results[0].get('sum')
        #TODO need to check if all invoices are in the same currency than the journal!!!!
        elif self.type in ['sale', 'purchase']:
            title = _('Bills to pay') if self.type == 'purchase' else _('Invoices owed to you')
            # optimization to find total and sum of invoice that are in draft, open state
            query = """SELECT state, amount_total, currency_id AS currency FROM account_invoice WHERE journal_id = %s AND state NOT IN ('paid', 'cancel');"""
            self.env.cr.execute(query, (self.id,))
            query_results = self.env.cr.dictfetchall()
            today = datetime.today()
            query = """SELECT amount_total, currency_id AS currency FROM account_invoice WHERE journal_id = %s AND date < %s AND state = 'open';"""
            self.env.cr.execute(query, (self.id, today))
            late_query_results = self.env.cr.dictfetchall()
            sum_draft = 0.0
            number_draft = 0
            number_waiting = 0
            for result in query_results:
                cur = self.env['res.currency'].browse(result.get('currency'))
                if result.get('state') in ['draft', 'proforma', 'proforma2']:
                    number_draft += 1
                    sum_draft += cur.compute(result.get('amount_total'), currency)
                elif result.get('state') == 'open':
                    number_waiting += 1
                    sum_waiting += cur.compute(result.get('amount_total'), currency)
            sum_late = 0.0
            number_late = 0
            for result in late_query_results:
                cur = self.env['res.currency'].browse(result.get('currency'))
                number_late += 1
                sum_late += cur.compute(result.get('amount_total'), currency)

        return {
            'number_to_reconcile': number_to_reconcile,
            'account_balance': formatLang(self.env, account_sum, currency_obj=self.currency_id or self.company_id.currency_id),
            'last_balance': formatLang(self.env, last_balance, currency_obj=self.currency_id or self.company_id.currency_id),
            'number_draft': number_draft,
            'number_waiting': number_waiting,
            'number_late': number_late,
            'sum_draft': formatLang(self.env, sum_draft or 0.0, currency_obj=self.currency_id or self.company_id.currency_id),
            'sum_waiting': formatLang(self.env, sum_waiting or 0.0, currency_obj=self.currency_id or self.company_id.currency_id),
            'sum_late': formatLang(self.env, sum_late or 0.0, currency_obj=self.currency_id or self.company_id.currency_id),
            'currency_id': self.currency_id and self.currency_id.id or self.company_id.currency_id.id,
            'bank_statements_source': self.bank_statements_source,
            'title': title, 
        }
Ejemplo n.º 33
0
    def get_journal_dashboard_datas(self):
        currency = self.currency_id or self.company_id.currency_id
        number_to_reconcile = last_balance = account_sum = unreconcile = 0
        ac_bnk_stmt = []
        title = ''
        invoice_wait = 0
        number_draft = number_waiting = number_rejected = no_waiting_approval = number_late = sum_draft = sum_waiting = sum_rejected = sum_waiting_approval = sum_late = 0
        unclear_cheque = todays_cheque = tomorrows_cheque = future_cheque = pro_balance = 0
        p_cnt = t_cnt = tm_cnt = f_cnt = chq_cnt = 0
        pre_chq = t_chq = tm_chq = f_chq = 0
        last_transaction = False
        if self.type in ['bank', 'cash']:
            last_bank_stmt = self.env['account.bank.statement'].search(
                [('journal_id', 'in', self.ids)],
                order="date desc, id desc",
                limit=1)
            last_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0
            #Get the number of items to reconcile for that bank journal
            self.env.cr.execute(
                """SELECT COUNT(DISTINCT(statement_line_id)) 
                        FROM account_move where statement_line_id 
                        IN (SELECT line.id 
                            FROM account_bank_statement_line AS line 
                            LEFT JOIN account_bank_statement AS st 
                            ON line.statement_id = st.id 
                            WHERE st.journal_id IN %s and st.state = 'open')""",
                (tuple(self.ids), ))
            already_reconciled = self.env.cr.fetchone()[0]
            self.env.cr.execute(
                """SELECT COUNT(line.id) 
                            FROM account_bank_statement_line AS line 
                            LEFT JOIN account_bank_statement AS st 
                            ON line.statement_id = st.id 
                            WHERE st.journal_id IN %s and st.state = 'open'""",
                (tuple(self.ids), ))
            all_lines = self.env.cr.fetchone()[0]
            number_to_reconcile = all_lines - already_reconciled
            # optimization to read sum of balance from account_move_line
            account_ids = tuple(
                filter(None, [
                    self.default_debit_account_id.id,
                    self.default_credit_account_id.id
                ]))
            if account_ids:
                #amount_field = 'balance' if not self.currency_id else 'amount_currency'
                #query = """SELECT sum(%s) FROM account_move_line WHERE account_id in %%s;""" % (amount_field,)
                #self.env.cr.execute(query, (account_ids,))
                #query_results = self.env.cr.dictfetchall()
                #if query_results and query_results[0].get('sum') != None:
                #    account_sum = query_results[0].get('sum')
                account_sum, pro_balance, last_transaction = self.calculate_outstanding_balance(
                )
                #self.env.cr.execute("select getjournalbalance(%s)"%self.id)
                #query_results = self.env.cr.fetchone()
#if query_results and query_results['getjournalbalance']:
#	account_sum,unreconcile = tuple(query_results['getjournalbalance'])
            cheque_ids = self.env['bank.cheque.details'].search([
                '|', ('payment_id.journal_id', '=', self.id),
                ('payment_id.destination_journal_id', '=', self.id),
                ('reconcile_date', '=', False),
                ('payment_id.state', '=', 'posted')
            ])
            for line in cheque_ids:
                if line.payment_id.payment_type in (
                        'outbound', 'transfer'
                ) and line.payment_id.journal_id.id == self.id:
                    if line.cheque_date <= str(date.today()):
                        p_cnt += 1
                        unclear_cheque += line.amount
                    elif line.cheque_date == str(date.today()):
                        t_cnt += 1
                        todays_cheque += line.amount
                    elif line.cheque_date == str(date.today() +
                                                 timedelta(days=1)):
                        tm_cnt += 1
                        tomorrows_cheque += line.amount
                    else:
                        f_cnt += 1
                        future_cheque += line.amount
                else:
                    chq_cnt += 1
                    unreconcile += line.amount

            if unclear_cheque and account_sum < (unclear_cheque +
                                                 todays_cheque):
                pre_chq = 1
            #if todays_cheque and account_sum < (unclear_cheque+todays_cheque):
#	t_chq = 1
            if tomorrows_cheque and account_sum < (
                    unclear_cheque + todays_cheque + tomorrows_cheque):
                tm_chq = 1
            if future_cheque and account_sum < (
                    unclear_cheque + todays_cheque + tomorrows_cheque +
                    future_cheque):
                f_chq = 1

        #TODO need to check if all invoices are in the same currency than the journal!!!!
        elif self.type in ['sale', 'purchase']:
            title = _('Bills to pay') if self.type == 'purchase' else _(
                'Invoices owed to you')
            # optimization to find total and sum of invoice that are in draft, open state
            query = """SELECT state, amount_total,currency_id AS currency,residual_company_signed FROM account_invoice WHERE journal_id = %s AND state NOT IN ('paid', 'cancel');"""
            self.env.cr.execute(query, (self.id, ))
            query_results = self.env.cr.dictfetchall()
            today = datetime.today()
            query = """SELECT amount_total, currency_id AS currency FROM account_invoice WHERE journal_id = %s AND date < %s AND state = 'open';"""
            self.env.cr.execute(query, (self.id, today))
            late_query_results = self.env.cr.dictfetchall()
            sum_draft = 0.0
            sum_rejected = 0.0
            sum_waiting_approval = 0.0
            number_draft = 0
            number_waiting = 0
            number_rejected = 0
            no_waiting_approval = 0
            for result in query_results:
                cur = self.env['res.currency'].browse(result.get('currency'))
                if result.get('state') in ['open', 'draft']:
                    if fields.Date.context_today(self) < result.get(
                            'payment_date_inv'):
                        invoice_wait += 1
                if result.get('state') in ['draft', 'proforma', 'proforma2']:
                    number_draft += 1
                    sum_draft += cur.compute(result.get('amount_total'),
                                             currency)

                elif result.get('state') == 'open':
                    number_waiting += 1
                    sum_waiting += result.get(
                        'residual_company_signed'
                    )  #cur.compute(result.get('amount_total'), currency)
                elif result.get('state') == 'rejected':
                    number_rejected += 1
                    sum_rejected += cur.compute(
                        result.get('amount_total'), currency
                    )  #cur.compute(result.get('amount_total'), currency)
                    print "number_rejectedv", number_rejected, sum_rejected
                elif result.get('state') == 'waiting_approval':
                    no_waiting_approval += 1
                    sum_waiting_approval += cur.compute(
                        result.get('amount_total'), currency
                    )  #cur.compute(result.get('amount_total'), currency)
                    print "no_waiting_approval", no_waiting_approval, sum_waiting_approval
            sum_late = 0.0
            number_late = 0
            for result in late_query_results:
                cur = self.env['res.currency'].browse(result.get('currency'))
                number_late += 1
                sum_late += cur.compute(result.get('amount_total'), currency)
        requests = []
        #credit=self.env['res.partner.credit'].search([('state','=','request')])
        # if credit:
        #   credit=len(credit)
        if self.user_has_groups('base.group_system'):
            requests = self.env['account.payment.term.request'].search([
                ('state', '=', 'requested'),
                ('customer_id.customer', '=', True)
            ])
        elif self.user_has_groups('account.group_account_user'):
            requests = self.env['account.payment.term.request'].search([
                ('state', '=', 'requested'),
                ('accountant_id', 'in', [False, self.env.uid]),
                ('customer_id.customer', '=', True)
            ])
        num_req = '0'
        if requests:
            num_req = len(requests)

        sup_request = []
        if self.user_has_groups('base.group_system'):
            sup_request = self.env['account.payment.term.request'].search([
                ('state', '=', 'requested'),
                ('customer_id.supplier', '=', True)
            ])
        elif self.user_has_groups('account.group_account_user'):
            sup_request = self.env['account.payment.term.request'].search([
                ('state', '=', 'requested'),
                ('accountant_id', 'in', [False, self.env.uid]),
                ('customer_id.supplier', '=', True)
            ])
        num_req_sup = '0'
        if sup_request:
            num_req_sup = len(sup_request)
        credt_req = 0
        credt = self.env['res.partner.credit'].search([('state', '=',
                                                        'request')])
        if credt:
            partner_list = []
            for each in credt:
                if each.partner_id.id not in partner_list:
                    partner_list.append(each.partner_id.id)
            credt_req = len(partner_list)
        pending_rqst = self.env['purchase.order'].search([('state', '=',
                                                           'awaiting')])
        lst_rqst = []
        for pend in pending_rqst:
            if pend.management_user.id == self.env.user.id and not pend.approve_mgnt:
                lst_rqst.append(pend.id)
            if pend.procurement_user.id == self.env.user.id and not pend.approve_prq:
                lst_rqst.append(pend.id)

            if pend.inventory_user.id == self.env.user.id and not pend.approve_inv:
                lst_rqst.append(pend.id)
        advance_payment = self.env['account.payment'].search([
            ('partner_type', '=', 'customer'), ('sale_id', '!=', False),
            ('state', '=', 'draft')
        ])
        lines = []
        not_match = "select order_id  from sale_order_line where qty_delivered != qty_invoiced and state ='sale'"
        self._cr.execute(not_match)
        lines = [i[0] for i in self._cr.fetchall()]

        return {
            'number_to_reconcile':
            number_to_reconcile,
            'account_balance':
            formatLang(self.env,
                       account_sum,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'last_balance':
            formatLang(self.env,
                       last_balance,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'number_draft':
            number_draft,
            'number_waiting':
            number_waiting,
            'number_rejected':
            number_rejected,
            'no_waiting_approval':
            no_waiting_approval,
            'number_late':
            number_late,
            'sum_draft':
            formatLang(self.env,
                       sum_draft or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_rejected':
            formatLang(self.env,
                       sum_rejected or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_waiting_approval':
            formatLang(self.env,
                       sum_waiting_approval or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_waiting':
            formatLang(self.env,
                       sum_waiting or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'sum_late':
            formatLang(self.env,
                       sum_late or 0.0,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'currency_id':
            self.currency_id and self.currency_id.id
            or self.company_id.currency_id.id,
            'bank_statements_source':
            self.bank_statements_source,
            'title':
            title,
            'num_req':
            num_req,
            'invoice_wait':
            invoice_wait,
            'num_req_sup':
            num_req_sup,
            'credit_request':
            credt_req,
            'pending_rqst':
            len(lst_rqst),
            'advance_payment':
            len(advance_payment),
            'not_match':
            len(set(lines)),
            'unclear_cheque':
            formatLang(self.env, (unclear_cheque + todays_cheque),
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            # 'todays_cheque': formatLang(self.env, todays_cheque, currency_obj=self.currency_id or self.company_id.currency_id) ,
            'tomorrows_cheque':
            formatLang(self.env,
                       tomorrows_cheque,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'future_cheque':
            formatLang(self.env,
                       future_cheque,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'unreconcile_data':
            formatLang(self.env,
                       unreconcile,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            #'unreconcile':unreconcile,
            'chq_cnt':
            chq_cnt,
            'erp_balance':
            formatLang(self.env,
                       account_sum - (unclear_cheque + todays_cheque),
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'color':
            0,
            'total_cheque':
            formatLang(self.env, (unclear_cheque + todays_cheque +
                                  tomorrows_cheque + future_cheque),
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'total_chq_cnt': (p_cnt + t_cnt + tm_cnt + f_cnt),
            'pro_balance':
            formatLang(self.env,
                       pro_balance,
                       currency_obj=self.currency_id
                       or self.company_id.currency_id),
            'pre_chq':
            pre_chq,
            #'t_chq':t_chq,
            'tm_chq':
            tm_chq,
            'f_chq':
            f_chq,
            'last_transaction':
            last_transaction,
        }