Browse Source

Merge pull request #6 from acsone/7.0-pep8

[IMP] PEP8 fix
pull/11/head
Pedro M. Baeza 10 years ago
parent
commit
bad25d3d49
  1. 5
      account_export_csv/__init__.py
  2. 27
      account_export_csv/__openerp__.py
  3. 5
      account_export_csv/wizard/__init__.py
  4. 241
      account_export_csv/wizard/account_export_csv.py
  5. 8
      account_financial_report/__init__.py
  6. 8
      account_financial_report/model/__init__.py
  7. 111
      account_financial_report/model/account_financial_report.py
  8. 11
      account_financial_report/model/res_company.py
  9. 2
      account_financial_report/report/__init__.py
  10. 602
      account_financial_report/report/parser.py
  11. 2
      account_financial_report/wizard/__init__.py
  12. 201
      account_financial_report/wizard/wizard.py
  13. 4
      account_financial_report_horizontal/__init__.py
  14. 6
      account_financial_report_horizontal/report/__init__.py
  15. 34
      account_financial_report_horizontal/report/account_balance_sheet.py
  16. 20
      account_financial_report_horizontal/report/account_profit_loss.py
  17. 27
      account_financial_report_horizontal/report/common_report_header.py
  18. 8
      account_financial_report_horizontal/wizard/__init__.py
  19. 2
      account_financial_report_horizontal/wizard/account_report_balance_sheet.py
  20. 4
      account_financial_report_horizontal/wizard/account_report_common.py
  21. 2
      account_financial_report_horizontal/wizard/account_report_common_account.py
  22. 2
      account_financial_report_horizontal/wizard/account_report_profit_loss.py
  23. 4
      account_financial_report_webkit/__init__.py
  24. 49
      account_financial_report_webkit/__openerp__.py
  25. 45
      account_financial_report_webkit/account_move_line.py
  26. 37
      account_financial_report_webkit/report/aged_partner_balance.py
  27. 170
      account_financial_report_webkit/report/common_balance_reports.py
  28. 208
      account_financial_report_webkit/report/common_partner_balance_reports.py
  29. 157
      account_financial_report_webkit/report/common_partner_reports.py
  30. 235
      account_financial_report_webkit/report/common_reports.py
  31. 103
      account_financial_report_webkit/report/general_ledger.py
  32. 122
      account_financial_report_webkit/report/open_invoices.py
  33. 43
      account_financial_report_webkit/report/partner_balance.py
  34. 106
      account_financial_report_webkit/report/partners_ledger.py
  35. 68
      account_financial_report_webkit/report/print_journal.py
  36. 39
      account_financial_report_webkit/report/trial_balance.py
  37. 62
      account_financial_report_webkit/report/webkit_parser_header_fix.py
  38. 193
      account_financial_report_webkit/wizard/balance_common.py
  39. 78
      account_financial_report_webkit/wizard/general_ledger_wizard.py
  40. 103
      account_financial_report_webkit/wizard/open_invoices_wizard.py
  41. 19
      account_financial_report_webkit/wizard/partner_balance_wizard.py
  42. 60
      account_financial_report_webkit/wizard/partners_ledger_wizard.py
  43. 63
      account_financial_report_webkit/wizard/print_journal.py
  44. 2
      account_financial_report_webkit/wizard/trial_balance_wizard.py
  45. 4
      account_financial_report_webkit_xls/__init__.py
  46. 13
      account_financial_report_webkit_xls/__openerp__.py
  47. 2
      account_financial_report_webkit_xls/report/__init__.py
  48. 259
      account_financial_report_webkit_xls/report/general_ledger_xls.py
  49. 1088
      account_financial_report_webkit_xls/report/open_invoices_xls.py
  50. 392
      account_financial_report_webkit_xls/report/partner_ledger_xls.py
  51. 391
      account_financial_report_webkit_xls/report/partners_balance_xls.py
  52. 263
      account_financial_report_webkit_xls/report/trial_balance_xls.py
  53. 2
      account_financial_report_webkit_xls/wizard/__init__.py
  54. 11
      account_financial_report_webkit_xls/wizard/general_ledger_wizard.py
  55. 10
      account_financial_report_webkit_xls/wizard/open_invoices_wizard.py
  56. 18
      account_financial_report_webkit_xls/wizard/partners_balance_wizard.py
  57. 10
      account_financial_report_webkit_xls/wizard/partners_ledger_wizard.py
  58. 11
      account_financial_report_webkit_xls/wizard/trial_balance_wizard.py
  59. 5
      account_journal_report_xls/__init__.py
  60. 2
      account_journal_report_xls/__openerp__.py
  61. 28
      account_journal_report_xls/account_journal.py
  62. 6
      account_journal_report_xls/report/__init__.py
  63. 215
      account_journal_report_xls/report/nov_account_journal.py
  64. 199
      account_journal_report_xls/report/nov_account_journal_xls.py
  65. 2
      account_journal_report_xls/wizard/__init__.py
  66. 80
      account_journal_report_xls/wizard/print_journal_wizard.py
  67. 5
      account_move_line_report_xls/__init__.py
  68. 12
      account_move_line_report_xls/account_move_line.py
  69. 232
      account_move_line_report_xls/report/move_line_list_xls.py

5
account_export_csv/__init__.py

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
############################################################################## ##############################################################################
# #
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013 Camptocamp SA
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013
# Camptocamp SA
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as # it under the terms of the GNU Affero General Public License as
@ -18,4 +19,4 @@
# #
############################################################################## ##############################################################################
import wizard
from . import wizard

27
account_export_csv/__openerp__.py

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
############################################################################## ##############################################################################
# #
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013 Camptocamp SA
# Author Joel Grand-Guillaume and Vincent Renaville
# Copyright 2013 Camptocamp SA
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as # it under the terms of the GNU Affero General Public License as
@ -19,15 +20,16 @@
############################################################################## ##############################################################################
{ {
'name' : 'Account Export CSV',
'version' : '1.1',
'depends' : [
'account',
],
'author' : 'Camptocamp',
'name': 'Account Export CSV',
'version': '1.1',
'depends': [
'account',
],
'author': 'Camptocamp',
'description': """ 'description': """
Add a wizard that allow you to export a csv file based on accounting journal entries
Add a wizard that allow you to export a csv file based on accounting
journal entries
- Trial Balance - Trial Balance
- Analytic Balance (with accounts) - Analytic Balance (with accounts)
@ -35,13 +37,14 @@
You can filter by period You can filter by period
TODO: rearange wizard view with only one button to generate file plus define a selection list to select report type
TODO: rearange wizard view with only one button to generate file plus
define a selection list to select report type
""", """,
'website': 'http://www.camptocamp.com', 'website': 'http://www.camptocamp.com',
'data': [ 'data': [
'wizard/account_export_csv_view.xml',
'menu.xml',
],
'wizard/account_export_csv_view.xml',
'menu.xml',
],
'installable': True, 'installable': True,
'active': False, 'active': False,
} }

5
account_export_csv/wizard/__init__.py

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
############################################################################## ##############################################################################
# #
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013 Camptocamp SA
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013
# Camptocamp SA
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as # it under the terms of the GNU Affero General Public License as
@ -18,4 +19,4 @@
# #
############################################################################## ##############################################################################
import account_export_csv
from . import account_export_csv

241
account_export_csv/wizard/account_export_csv.py

@ -1,8 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
############################################################################## ##############################################################################
# #
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013 Camptocamp SA
# CSV data formating inspired from http://docs.python.org/2.7/library/csv.html?highlight=csv#examples
# Author Joel Grand-Guillaume and Vincent Renaville Copyright 2013
# Camptocamp SA
# CSV data formating inspired from
# http://docs.python.org/2.7/library/csv.html?highlight=csv#examples
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as # it under the terms of the GNU Affero General Public License as
@ -20,7 +22,6 @@
############################################################################## ##############################################################################
import itertools import itertools
import time
import tempfile import tempfile
import StringIO import StringIO
import cStringIO import cStringIO
@ -34,6 +35,7 @@ from openerp.tools.translate import _
class AccountUnicodeWriter(object): class AccountUnicodeWriter(object):
""" """
A CSV writer which will write rows to CSV file "f", A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding. which is encoded in the given encoding.
@ -48,10 +50,11 @@ class AccountUnicodeWriter(object):
self.encoder = codecs.getincrementalencoder(encoding)() self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row): def writerow(self, row):
#we ensure that we do not try to encode none or bool
# we ensure that we do not try to encode none or bool
row = (x or u'' for x in row) row = (x or u'' for x in row)
encoded_row = [c.encode("utf-8") if isinstance(c, unicode) else c for c in row]
encoded_row = [
c.encode("utf-8") if isinstance(c, unicode) else c for c in row]
self.writer.writerow(encoded_row) self.writer.writerow(encoded_row)
# Fetch UTF-8 output from the queue ... # Fetch UTF-8 output from the queue ...
@ -68,32 +71,47 @@ class AccountUnicodeWriter(object):
for row in rows: for row in rows:
self.writerow(row) self.writerow(row)
class AccountCSVExport(orm.TransientModel): class AccountCSVExport(orm.TransientModel):
_name = 'account.csv.export' _name = 'account.csv.export'
_description = 'Export Accounting' _description = 'Export Accounting'
_columns = { _columns = {
'data': fields.binary('CSV',readonly=True),
'company_id': fields.many2one('res.company', 'Company', invisible=True),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscalyear', required=True),
'periods': fields.many2many('account.period','rel_wizard_period','wizard_id','period_id','Periods',help='All periods in the fiscal year if empty'),
'journal_ids': fields.many2many('account.journal','rel_wizard_journal','wizard_id','journal_id','Journals', help='If empty, use all journals, only used for journal entries'),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscalyear', required=True),
'data': fields.binary('CSV', readonly=True),
'company_id': fields.many2one('res.company', 'Company',
invisible=True),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscalyear',
required=True),
'periods': fields.many2many(
'account.period', 'rel_wizard_period',
'wizard_id', 'period_id', 'Periods',
help='All periods in the fiscal year if empty'),
'journal_ids': fields.many2many(
'account.journal',
'rel_wizard_journal',
'wizard_id',
'journal_id',
'Journals',
help='If empty, use all journals, only used for journal entries'),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscalyear',
required=True),
'export_filename': fields.char('Export CSV Filename', size=128), 'export_filename': fields.char('Export CSV Filename', size=128),
} }
def _get_company_default(self, cr, uid, context=None): def _get_company_default(self, cr, uid, context=None):
comp_obj = self.pool['res.company'] comp_obj = self.pool['res.company']
return comp_obj._company_default_get(cr, uid, 'account.fiscalyear', context=context)
return comp_obj._company_default_get(cr, uid, 'account.fiscalyear',
context=context)
def _get_fiscalyear_default(self, cr, uid, context=None): def _get_fiscalyear_default(self, cr, uid, context=None):
fiscalyear_obj = self.pool['account.fiscalyear'] fiscalyear_obj = self.pool['account.fiscalyear']
context['company_id'] = self._get_company_default(cr, uid, context) context['company_id'] = self._get_company_default(cr, uid, context)
return fiscalyear_obj.find(cr,uid,dt=None,exception=True, context=context)
return fiscalyear_obj.find(cr, uid, dt=None, exception=True,
context=context)
_defaults = {'company_id': _get_company_default, _defaults = {'company_id': _get_company_default,
'fiscalyear_id' : _get_fiscalyear_default,
'export_filename' : 'account_export.csv'}
'fiscalyear_id': _get_fiscalyear_default,
'export_filename': 'account_export.csv'}
def action_manual_export_account(self, cr, uid, ids, context=None): def action_manual_export_account(self, cr, uid, ids, context=None):
this = self.browse(cr, uid, ids)[0] this = self.browse(cr, uid, ids)[0]
@ -118,7 +136,6 @@ class AccountCSVExport(orm.TransientModel):
'target': 'new', 'target': 'new',
} }
def _get_header_account(self, cr, uid, ids, context=None): def _get_header_account(self, cr, uid, ids, context=None):
return [_(u'CODE'), return [_(u'CODE'),
_(u'NAME'), _(u'NAME'),
@ -128,24 +145,27 @@ class AccountCSVExport(orm.TransientModel):
] ]
def _get_rows_account(self, cr, uid, ids, def _get_rows_account(self, cr, uid, ids,
fiscalyear_id,
period_range_ids,
journal_ids,
context=None):
fiscalyear_id,
period_range_ids,
journal_ids,
context=None):
""" """
Return list to generate rows of the CSV file Return list to generate rows of the CSV file
""" """
cr.execute(""" cr.execute("""
select ac.code,ac.name,
sum(debit) as sum_debit,sum(credit) as sum_credit,sum(debit) - sum(credit) as balance
from account_move_line as aml,account_account as ac
where aml.account_id = ac.id
and period_id in %(period_ids)s
group by ac.id,ac.code,ac.name
order by ac.code
select ac.code,ac.name,
sum(debit) as sum_debit,
sum(credit) as sum_credit,
sum(debit) - sum(credit) as balance
from account_move_line as aml,account_account as ac
where aml.account_id = ac.id
and period_id in %(period_ids)s
group by ac.id,ac.code,ac.name
order by ac.code
""", """,
{'fiscalyear_id': fiscalyear_id, 'period_ids':tuple(period_range_ids)}
)
{'fiscalyear_id': fiscalyear_id,
'period_ids': tuple(period_range_ids)}
)
res = cr.fetchall() res = cr.fetchall()
rows = [] rows = []
@ -155,7 +175,7 @@ class AccountCSVExport(orm.TransientModel):
def action_manual_export_analytic(self, cr, uid, ids, context=None): def action_manual_export_analytic(self, cr, uid, ids, context=None):
this = self.browse(cr, uid, ids)[0] this = self.browse(cr, uid, ids)[0]
rows = self.get_data(cr, uid, ids,"analytic", context)
rows = self.get_data(cr, uid, ids, "analytic", context)
file_data = StringIO.StringIO() file_data = StringIO.StringIO()
try: try:
writer = AccountUnicodeWriter(file_data) writer = AccountUnicodeWriter(file_data)
@ -187,16 +207,20 @@ class AccountCSVExport(orm.TransientModel):
] ]
def _get_rows_analytic(self, cr, uid, ids, def _get_rows_analytic(self, cr, uid, ids,
fiscalyear_id,
period_range_ids,
journal_ids,
context=None):
fiscalyear_id,
period_range_ids,
journal_ids,
context=None):
""" """
Return list to generate rows of the CSV file Return list to generate rows of the CSV file
""" """
cr.execute(""" select aac.code as analytic_code,aac.name as analytic_name,ac.code,ac.name,
sum(debit) as sum_debit,sum(credit) as sum_credit,sum(debit) - sum(credit) as balance
from account_move_line
cr.execute(""" select aac.code as analytic_code,
aac.name as analytic_name,
ac.code,ac.name,
sum(debit) as sum_debit,
sum(credit) as sum_credit,
sum(debit) - sum(credit) as balance
from account_move_line
left outer join account_analytic_account as aac left outer join account_analytic_account as aac
on (account_move_line.analytic_account_id = aac.id) on (account_move_line.analytic_account_id = aac.id)
inner join account_account as ac inner join account_account as ac
@ -205,8 +229,9 @@ class AccountCSVExport(orm.TransientModel):
group by aac.id,aac.code,aac.name,ac.id,ac.code,ac.name group by aac.id,aac.code,aac.name,ac.id,ac.code,ac.name
order by aac.code order by aac.code
""", """,
{'fiscalyear_id': fiscalyear_id, 'period_ids':tuple(period_range_ids)}
)
{'fiscalyear_id': fiscalyear_id,
'period_ids': tuple(period_range_ids)}
)
res = cr.fetchall() res = cr.fetchall()
rows = [] rows = []
@ -214,14 +239,15 @@ class AccountCSVExport(orm.TransientModel):
rows.append(list(line)) rows.append(list(line))
return rows return rows
def action_manual_export_journal_entries(self, cr, uid, ids, context=None): def action_manual_export_journal_entries(self, cr, uid, ids, context=None):
""" """
Here we use TemporaryFile to avoid full filling the OpenERP worker Memory
We also write the data to the wizard with SQL query as write seams to use
too much memory as well.
Here we use TemporaryFile to avoid full filling the OpenERP worker
Memory
We also write the data to the wizard with SQL query as write seams
to use too much memory as well.
Those improvements permitted to improve the export from a 100k line to 200k lines
Those improvements permitted to improve the export from a 100k line to
200k lines
with default `limit_memory_hard = 805306368` (768MB) with more lines, with default `limit_memory_hard = 805306368` (768MB) with more lines,
you might encounter a MemoryError when trying to download the file even you might encounter a MemoryError when trying to download the file even
if it has been generated. if it has been generated.
@ -241,7 +267,10 @@ class AccountCSVExport(orm.TransientModel):
file_data.seek(0) file_data.seek(0)
base64.encode(file_data, base64_data) base64.encode(file_data, base64_data)
base64_data.seek(0) base64_data.seek(0)
cr.execute("""UPDATE account_csv_export SET data = %s WHERE id = %s""", (base64_data.read(), ids[0]) )
cr.execute("""
UPDATE account_csv_export
SET data = %s
WHERE id = %s""", (base64_data.read(), ids[0]))
return { return {
'type': 'ir.actions.act_window', 'type': 'ir.actions.act_window',
'res_model': 'account.csv.export', 'res_model': 'account.csv.export',
@ -252,44 +281,42 @@ class AccountCSVExport(orm.TransientModel):
'target': 'new', 'target': 'new',
} }
def _get_header_journal_entries(self, cr, uid, ids, context=None): def _get_header_journal_entries(self, cr, uid, ids, context=None):
return [
# Standard Sage export fields
_(u'DATE'),
_(u'JOURNAL CODE'),
_(u'ACCOUNT CODE'),
_(u'PARTNER NAME'),
_(u'REF'),
_(u'DESCRIPTION'),
_(u'DEBIT'),
_(u'CREDIT'),
_(u'FULL RECONCILE'),
_(u'PARTIAL RECONCILE'),
_(u'ANALYTIC ACCOUNT CODE'),
# Other fields
_(u'ENTRY NUMBER'),
_(u'ACCOUNT NAME'),
_(u'BALANCE'),
_(u'AMOUNT CURRENCY'),
_(u'CURRENCY'),
_(u'ANALYTIC ACCOUNT NAME'),
_(u'JOURNAL'),
_(u'MONTH'),
_(u'FISCAL YEAR'),
_(u'TAX CODE CODE'),
_(u'TAX CODE NAME'),
_(u'TAX AMOUNT'),
]
return [
# Standard Sage export fields
_(u'DATE'),
_(u'JOURNAL CODE'),
_(u'ACCOUNT CODE'),
_(u'PARTNER NAME'),
_(u'REF'),
_(u'DESCRIPTION'),
_(u'DEBIT'),
_(u'CREDIT'),
_(u'FULL RECONCILE'),
_(u'PARTIAL RECONCILE'),
_(u'ANALYTIC ACCOUNT CODE'),
# Other fields
_(u'ENTRY NUMBER'),
_(u'ACCOUNT NAME'),
_(u'BALANCE'),
_(u'AMOUNT CURRENCY'),
_(u'CURRENCY'),
_(u'ANALYTIC ACCOUNT NAME'),
_(u'JOURNAL'),
_(u'MONTH'),
_(u'FISCAL YEAR'),
_(u'TAX CODE CODE'),
_(u'TAX CODE NAME'),
_(u'TAX AMOUNT'),
]
def _get_rows_journal_entries(self, cr, uid, ids, def _get_rows_journal_entries(self, cr, uid, ids,
fiscalyear_id,
period_range_ids,
journal_ids,
context=None):
fiscalyear_id,
period_range_ids,
journal_ids,
context=None):
""" """
Create a generator of rows of the CSV file Create a generator of rows of the CSV file
""" """
@ -306,7 +333,6 @@ class AccountCSVExport(orm.TransientModel):
account_move_reconcile.name as full_reconcile, account_move_reconcile.name as full_reconcile,
account_move_line.reconcile_partial_id AS partial_reconcile_id, account_move_line.reconcile_partial_id AS partial_reconcile_id,
account_analytic_account.code AS analytic_account_code, account_analytic_account.code AS analytic_account_code,
account_move.name AS entry_number, account_move.name AS entry_number,
account_account.name AS account_name, account_account.name AS account_name,
account_move_line.debit - account_move_line.credit AS balance, account_move_line.debit - account_move_line.credit AS balance,
@ -321,52 +347,67 @@ class AccountCSVExport(orm.TransientModel):
account_move_line.tax_amount AS aml_tax_amount account_move_line.tax_amount AS aml_tax_amount
FROM FROM
public.account_move_line public.account_move_line
JOIN account_account on (account_account.id=account_move_line.account_id)
JOIN account_period on (account_period.id=account_move_line.period_id)
JOIN account_fiscalyear on (account_fiscalyear.id=account_period.fiscalyear_id)
JOIN account_journal on (account_journal.id = account_move_line.journal_id)
LEFT JOIN res_currency on (res_currency.id=account_move_line.currency_id)
LEFT JOIN account_move_reconcile on (account_move_reconcile.id = account_move_line.reconcile_id)
LEFT JOIN res_partner on (res_partner.id=account_move_line.partner_id)
LEFT JOIN account_move on (account_move.id=account_move_line.move_id)
LEFT JOIN account_tax on (account_tax.id=account_move_line.account_tax_id)
LEFT JOIN account_tax_code on (account_tax_code.id=account_move_line.tax_code_id)
LEFT JOIN account_analytic_account on (account_analytic_account.id=account_move_line.analytic_account_id)
JOIN account_account on
(account_account.id=account_move_line.account_id)
JOIN account_period on
(account_period.id=account_move_line.period_id)
JOIN account_fiscalyear on
(account_fiscalyear.id=account_period.fiscalyear_id)
JOIN account_journal on
(account_journal.id = account_move_line.journal_id)
LEFT JOIN res_currency on
(res_currency.id=account_move_line.currency_id)
LEFT JOIN account_move_reconcile on
(account_move_reconcile.id = account_move_line.reconcile_id)
LEFT JOIN res_partner on
(res_partner.id=account_move_line.partner_id)
LEFT JOIN account_move on
(account_move.id=account_move_line.move_id)
LEFT JOIN account_tax on
(account_tax.id=account_move_line.account_tax_id)
LEFT JOIN account_tax_code on
(account_tax_code.id=account_move_line.tax_code_id)
LEFT JOIN account_analytic_account on
(account_analytic_account.id=account_move_line.analytic_account_id)
WHERE account_period.id IN %(period_ids)s WHERE account_period.id IN %(period_ids)s
AND account_journal.id IN %(journal_ids)s AND account_journal.id IN %(journal_ids)s
ORDER BY account_move_line.date ORDER BY account_move_line.date
""", """,
{'period_ids': tuple(period_range_ids), 'journal_ids': tuple(journal_ids)}
)
{'period_ids': tuple(
period_range_ids), 'journal_ids': tuple(journal_ids)}
)
while 1: while 1:
# http://initd.org/psycopg/docs/cursor.html#cursor.fetchmany # http://initd.org/psycopg/docs/cursor.html#cursor.fetchmany
# Set cursor.arraysize to minimize network round trips # Set cursor.arraysize to minimize network round trips
cr.arraysize=100
cr.arraysize = 100
rows = cr.fetchmany() rows = cr.fetchmany()
if not rows: if not rows:
break break
for row in rows: for row in rows:
yield row yield row
def get_data(self, cr, uid, ids,result_type,context=None):
get_header_func = getattr(self,("_get_header_%s"%(result_type)), None)
get_rows_func = getattr(self,("_get_rows_%s"%(result_type)), None)
def get_data(self, cr, uid, ids, result_type, context=None):
get_header_func = getattr(
self, ("_get_header_%s" % (result_type)), None)
get_rows_func = getattr(self, ("_get_rows_%s" % (result_type)), None)
form = self.browse(cr, uid, ids[0], context=context) form = self.browse(cr, uid, ids[0], context=context)
fiscalyear_id = form.fiscalyear_id.id fiscalyear_id = form.fiscalyear_id.id
user_obj = self.pool.get('res.users')
if form.periods: if form.periods:
period_range_ids = [x.id for x in form.periods] period_range_ids = [x.id for x in form.periods]
else: else:
# If not period selected , we take all periods # If not period selected , we take all periods
p_obj = self.pool.get("account.period") p_obj = self.pool.get("account.period")
period_range_ids = p_obj.search(cr, uid, [('fiscalyear_id','=',fiscalyear_id)], context=context)
period_range_ids = p_obj.search(
cr, uid, [('fiscalyear_id', '=', fiscalyear_id)],
context=context)
journal_ids = None journal_ids = None
if form.journal_ids: if form.journal_ids:
journal_ids = [x.id for x in form.journal_ids] journal_ids = [x.id for x in form.journal_ids]
else: else:
j_obj = self.pool.get("account.journal") j_obj = self.pool.get("account.journal")
journal_ids = j_obj.search(cr, uid, [], context=context) journal_ids = j_obj.search(cr, uid, [], context=context)
rows = itertools.chain((get_header_func(cr, uid, ids, context=context),),
rows = itertools.chain((get_header_func(cr, uid, ids,
context=context),),
get_rows_func(cr, uid, ids, get_rows_func(cr, uid, ids,
fiscalyear_id, fiscalyear_id,
period_range_ids, period_range_ids,

8
account_financial_report/__init__.py

@ -3,7 +3,7 @@
# Module Writen to OpenERP, Open Source Management Solution # Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>). # Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved # All Rights Reserved
###############Credits######################################################
# Credits######################################################
# Coded by: Humberto Arocha humberto@openerp.com.ve # Coded by: Humberto Arocha humberto@openerp.com.ve
# Angelica Barrios angelicaisabelb@gmail.com # Angelica Barrios angelicaisabelb@gmail.com
# Jordi Esteve <jesteve@zikzakmedia.com> # Jordi Esteve <jesteve@zikzakmedia.com>
@ -25,6 +25,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## ##############################################################################
import model
import report
import wizard
from . import model
from . import report
from . import wizard

8
account_financial_report/model/__init__.py

@ -10,8 +10,8 @@
# Audited by: Nhomar Hernandez <nhomar@vauxoo.com> # Audited by: Nhomar Hernandez <nhomar@vauxoo.com>
############################################################################# #############################################################################
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# 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
# 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. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
@ -23,5 +23,5 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
########################################################################## ##########################################################################
import account_financial_report
import res_company
from . import account_financial_report
from . import res_company

111
account_financial_report/model/account_financial_report.py

@ -26,10 +26,9 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## ##############################################################################
from osv import osv, fields
import pooler
from openerp.osv import osv, fields
import time import time
from tools.translate import _
from openerp.tools.translate import _
class account_financial_report(osv.osv): class account_financial_report(osv.osv):
@ -38,45 +37,75 @@ class account_financial_report(osv.osv):
_columns = { _columns = {
'name': fields.char('Name', size=128, required=True), 'name': fields.char('Name', size=128, required=True),
'company_id': fields.many2one('res.company', 'Company', required=True), 'company_id': fields.many2one('res.company', 'Company', required=True),
'currency_id': fields.many2one(
'res.currency', 'Currency', help="Currency at which this report will be expressed. If not selected will be used the one set in the company"),
'inf_type': fields.selection(
[('BS', 'Balance Sheet'), ('IS', 'Income Statement')], 'Type', required=True),
'columns': fields.selection([('one', 'End. Balance'), ('two', 'Debit | Credit'), ('four', 'Initial | Debit | Credit | YTD'),
('five', 'Initial | Debit | Credit | Period | YTD'), ('qtr', "4 QTR's | YTD"), ('thirteen', '12 Months | YTD')], 'Columns', required=True),
'display_account': fields.selection([('all', 'All Accounts'), ('bal', 'With Balance'),
('mov', 'With movements'), ('bal_mov', 'With Balance / Movements')], 'Display accounts'),
'display_account_level': fields.integer(
'Up to level', help='Display accounts up to this level (0 to show all)'),
'account_ids': fields.many2many(
'account.account', 'afr_account_rel', 'afr_id', 'account_id', 'Root accounts', required=True),
'fiscalyear_id': fields.many2one(
'account.fiscalyear', 'Fiscal year', help='Fiscal Year for this report', required=True),
'period_ids': fields.many2many('account.period', 'afr_period_rel', 'afr_id',
'period_id', 'Periods', help='All periods in the fiscal year if empty'),
'currency_id': fields.many2one('res.currency', 'Currency',
help="Currency at which this report \
will be expressed. If not selected \
will be used the one set in the \
company"),
'inf_type': fields.selection([('BS', 'Balance Sheet'),
('IS', 'Income Statement')],
'Type',
required=True),
'columns': fields.selection(
[('one', 'End. Balance'),
('two', 'Debit | Credit'),
('four', 'Initial | Debit | Credit | YTD'),
('five', 'Initial | Debit | Credit | Period | YTD'),
('qtr', "4 QTR's | YTD"),
('thirteen', '12 Months | YTD')], 'Columns', required=True),
'display_account': fields.selection(
[('all', 'All Accounts'),
('bal', 'With Balance'),
('mov', 'With movements'),
('bal_mov', 'With Balance / Movements')], 'Display accounts'),
'display_account_level': fields.integer('Up to level',
help='Display accounts up to \
this level (0 to show all)'),
'account_ids': fields.many2many('account.account', 'afr_account_rel',
'afr_id', 'account_id',
'Root accounts', required=True),
'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal year',
help='Fiscal Year for this report',
required=True),
'period_ids': fields.many2many(
'account.period', 'afr_period_rel', 'afr_id', 'period_id',
'Periods', help='All periods in the fiscal year if empty'),
'analytic_ledger': fields.boolean( 'analytic_ledger': fields.boolean(
'Analytic Ledger', help="Allows to Generate an Analytic Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
'Analytic Ledger',
help="Allows to Generate an Analytic Ledger for accounts with \
moves. Available when Balance Sheet and 'Initial | Debit \
| Credit | YTD' are selected"),
'journal_ledger': fields.boolean( 'journal_ledger': fields.boolean(
'journal Ledger', help="Allows to Generate an journal Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
'partner_balance': fields.boolean('Partner Balance', help="Allows to "
"Generate a Partner Balance for accounts with moves. Available when "
"Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
'journal Ledger',
help="Allows to Generate an journal Ledger for accounts with \
moves. Available when Balance Sheet and 'Initial | Debit | \
Credit | YTD' are selected"),
'partner_balance': fields.boolean(
'Partner Balance',
help="Allows to Generate a Partner Balance for accounts with \
moves. Available when Balance Sheet and 'Initial | Debit | \
Credit | YTD' are selected"),
'tot_check': fields.boolean( 'tot_check': fields.boolean(
'Summarize?', help='Checking will add a new line at the end of the Report which will Summarize Columns in Report'),
'lab_str':
fields.char(
'Description',
help='Description for the Summary',
size=128),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Entries to Include', required=True,
help='Print All Accounting Entries or just Posted Accounting Entries'),
#~ Deprecated fields
'filter': fields.selection([('bydate', 'By Date'), ('byperiod', 'By Period'),
('all', 'By Date and Period'), ('none', 'No Filter')], 'Date/Period Filter'),
'Summarize?',
help='Checking will add a new line at the end of the Report which \
will Summarize Columns in Report'),
'lab_str': fields.char('Description',
help='Description for the Summary',
size=128),
'target_move': fields.selection(
[('posted', 'All Posted Entries'),
('all', 'All Entries'), ],
'Entries to Include', required=True,
help='Print All Accounting Entries or just Posted \
Accounting Entries'),
# ~ Deprecated fields
'filter': fields.selection([('bydate', 'By Date'),
('byperiod', 'By Period'),
('all', 'By Date and Period'),
('none', 'No Filter')],
'Date/Period Filter'),
'date_to': fields.date('End date'), 'date_to': fields.date('End date'),
'date_from': fields.date('Start date'), 'date_from': fields.date('Start date'),
} }
@ -144,8 +173,10 @@ class account_financial_report(osv.osv):
if columns in ('qtr', 'thirteen'): if columns in ('qtr', 'thirteen'):
p_obj = self.pool.get("account.period") p_obj = self.pool.get("account.period")
period_ids = p_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear_id), (
'special', '=', False)], context=context)
period_ids = p_obj.search(cr, uid,
[('fiscalyear_id', '=', fiscalyear_id),
('special', '=', False)],
context=context)
res['value'].update({'period_ids': period_ids}) res['value'].update({'period_ids': period_ids})
else: else:
res['value'].update({'period_ids': []}) res['value'].update({'period_ids': []})

11
account_financial_report/model/res_company.py

@ -10,8 +10,8 @@
# Audited by: Nhomar Hernandez <nhomar@vauxoo.com> # Audited by: Nhomar Hernandez <nhomar@vauxoo.com>
############################################################################# #############################################################################
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# 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
# 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. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
@ -23,12 +23,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
########################################################################## ##########################################################################
from osv import osv
from osv import fields
from tools.translate import _
from openerp.osv import orm, fields
class res_company(osv.osv):
class res_company(orm.Model):
_inherit = 'res.company' _inherit = 'res.company'
_columns = { _columns = {
'credit_account_ids': fields.many2many('account.account', 'credit_account_ids': fields.many2many('account.account',
@ -40,4 +38,3 @@ class res_company(osv.osv):
'company_id', 'account_id', 'company_id', 'account_id',
'Debitable Accounts'), 'Debitable Accounts'),
} }
res_company()

2
account_financial_report/report/__init__.py

@ -25,4 +25,4 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## ##############################################################################
import parser
from . import parser

602
account_financial_report/report/parser.py

@ -26,16 +26,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## ##############################################################################
import xml
import copy
from operator import itemgetter
import time import time
import datetime
from report import report_sxw
from tools import config
from tools.translate import _
from osv import osv
from openerp.tools.safe_eval import safe_eval as eval
from openerp.report import report_sxw
from openerp.tools.translate import _
from openerp.osv import osv
class account_balance(report_sxw.rml_parse): class account_balance(report_sxw.rml_parse):
@ -68,14 +62,17 @@ class account_balance(report_sxw.rml_parse):
""" """
rc_obj = self.pool.get('res.company') rc_obj = self.pool.get('res.company')
country_code = rc_obj.browse(self.cr, self.uid, country_code = rc_obj.browse(self.cr, self.uid,
form['company_id'][0]).partner_id.country_id.code or ''
form['company_id'][0]).partner_id.\
country_id.code or ''
string_vat = rc_obj.browse(self.cr, self.uid, string_vat = rc_obj.browse(self.cr, self.uid,
form['company_id'][0]).partner_id.vat or '' form['company_id'][0]).partner_id.vat or ''
if string_vat: if string_vat:
if country_code == 'MX': if country_code == 'MX':
return '%s' % (string_vat[2:]) return '%s' % (string_vat[2:])
elif country_code == 'VE': elif country_code == 'VE':
return '- %s-%s-%s' % (string_vat[2:3], string_vat[3:11], string_vat[11:12])
return '- %s-%s-%s' % (string_vat[2:3],
string_vat[3:11],
string_vat[11:12])
else: else:
return string_vat return string_vat
else: else:
@ -85,7 +82,7 @@ class account_balance(report_sxw.rml_parse):
""" """
Returns the fiscal year text used on the report. Returns the fiscal year text used on the report.
""" """
fiscalyear_obj = self.pool.get('account.fiscalyear')
fiscalyear_obj = self.pool['account.fiscalyear']
fiscalyear = None fiscalyear = None
if form.get('fiscalyear'): if form.get('fiscalyear'):
fiscalyear = fiscalyear_obj.browse( fiscalyear = fiscalyear_obj.browse(
@ -104,7 +101,8 @@ class account_balance(report_sxw.rml_parse):
list, tuple) and form['afr_id'][0] or form['afr_id'] list, tuple) and form['afr_id'][0] or form['afr_id']
if afr_id: if afr_id:
name = self.pool.get('afr').browse(self.cr, self.uid, afr_id).name name = self.pool.get('afr').browse(self.cr, self.uid, afr_id).name
elif form['analytic_ledger'] and form['columns'] == 'four' and form['inf_type'] == 'BS':
elif form['analytic_ledger'] and form['columns'] == 'four' \
and form['inf_type'] == 'BS':
name = _('Analytic Ledger') name = _('Analytic Ledger')
elif form['inf_type'] == 'BS': elif form['inf_type'] == 'BS':
name = _('Balance Sheet') name = _('Balance Sheet')
@ -118,41 +116,43 @@ class account_balance(report_sxw.rml_parse):
return day, year and month return day, year and month
''' '''
if form['filter'] in ['bydate', 'all']: if form['filter'] in ['bydate', 'all']:
months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
"Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]
mes = months[time.strptime(form['date_to'], "%Y-%m-%d")[1] - 1]
ano = time.strptime(form['date_to'], "%Y-%m-%d")[0]
dia = time.strptime(form['date_to'], "%Y-%m-%d")[2]
return _('From ') + self.formatLang(form['date_from'], date=True) + _(' to ') + self.formatLang(form['date_to'], date=True)
return _('From ') + self.formatLang(form['date_from'], date=True) \
+ _(' to ') + self.formatLang(form['date_to'], date=True)
elif form['filter'] in ['byperiod', 'all']: elif form['filter'] in ['byperiod', 'all']:
aux = [] aux = []
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
for period in period_obj.browse(self.cr, self.uid, form['periods']):
for period in period_obj.browse(self.cr, self.uid,
form['periods']):
aux.append(period.date_start) aux.append(period.date_start)
aux.append(period.date_stop) aux.append(period.date_stop)
sorted(aux) sorted(aux)
return _('From ') + self.formatLang(aux[0], date=True) + _(' to ') + self.formatLang(aux[-1], date=True)
return _('From ') + self.formatLang(aux[0], date=True) + \
_(' to ') + self.formatLang(aux[-1], date=True)
def get_periods_and_date_text(self, form): def get_periods_and_date_text(self, form):
""" """
Returns the text with the periods/dates used on the report. Returns the text with the periods/dates used on the report.
""" """
period_obj = self.pool.get('account.period')
periods_str = None
period_obj = self.pool['account.period']
fiscalyear_obj = self.pool['account.fiscalyear']
fiscalyear_id = form[ fiscalyear_id = form[
'fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid) 'fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
period_ids = period_obj.search(self.cr, self.uid, [( period_ids = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear_id), ('special', '=', False)]) 'fiscalyear_id', '=', fiscalyear_id), ('special', '=', False)])
if form['filter'] in ['byperiod', 'all']: if form['filter'] in ['byperiod', 'all']:
period_ids = form['periods'] period_ids = form['periods']
periods_str = ', '.join([period.name or period.code for period in period_obj.browse(
self.cr, self.uid, period_ids)])
periods_str = ', '.join([period.name or period.code
for period in period_obj.browse(self.cr,
self.uid,
period_ids)])
dates_str = None dates_str = None
if form['filter'] in ['bydate', 'all']: if form['filter'] in ['bydate', 'all']:
dates_str = self.formatLang(form[ dates_str = self.formatLang(form[
'date_from'], date=True) + ' - ' + self.formatLang(form['date_to'], date=True) + ' '
'date_from'], date=True) + ' - ' + \
self.formatLang(form['date_to'],
date=True) + ' '
return {'periods': periods_str, 'date': dates_str} return {'periods': periods_str, 'date': dates_str}
def special_period(self, periods): def special_period(self, periods):
@ -164,20 +164,26 @@ class account_balance(report_sxw.rml_parse):
return False return False
def exchange_name(self, form): def exchange_name(self, form):
self.from_currency_id = self.get_company_currency(form['company_id'] and type(form[
'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'])
self.from_currency_id = self.\
get_company_currency(form['company_id']
and type(form['company_id']) in (list, tuple)
and form['company_id'][0]
or form['company_id'])
if not form['currency_id']: if not form['currency_id']:
self.to_currency_id = self.from_currency_id self.to_currency_id = self.from_currency_id
else: else:
self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (
list, tuple) and form['currency_id'][0] or form['currency_id']
return self.pool.get('res.currency').browse(self.cr, self.uid, self.to_currency_id).name
self.to_currency_id = form['currency_id'] \
and type(form['currency_id']) in (list, tuple) \
and form['currency_id'][0] or form['currency_id']
return self.pool.get('res.currency').browse(self.cr, self.uid,
self.to_currency_id).name
def exchange(self, from_amount): def exchange(self, from_amount):
if self.from_currency_id == self.to_currency_id: if self.from_currency_id == self.to_currency_id:
return from_amount return from_amount
curr_obj = self.pool.get('res.currency') curr_obj = self.pool.get('res.currency')
return curr_obj.compute(self.cr, self.uid, self.from_currency_id, self.to_currency_id, from_amount)
return curr_obj.compute(self.cr, self.uid, self.from_currency_id,
self.to_currency_id, from_amount)
def get_company_currency(self, company_id): def get_company_currency(self, company_id):
rc_obj = self.pool.get('res.company') rc_obj = self.pool.get('res.company')
@ -186,20 +192,25 @@ class account_balance(report_sxw.rml_parse):
def get_company_accounts(self, company_id, acc='credit'): def get_company_accounts(self, company_id, acc='credit'):
rc_obj = self.pool.get('res.company') rc_obj = self.pool.get('res.company')
if acc == 'credit': if acc == 'credit':
return [brw.id for brw in rc_obj.browse(self.cr, self.uid, company_id).credit_account_ids]
return [brw.id for brw in rc_obj.browse(
self.cr, self.uid,
company_id).credit_account_ids]
else: else:
return [brw.id for brw in rc_obj.browse(self.cr, self.uid, company_id).debit_account_ids]
return [brw.id for brw in rc_obj.browse(
self.cr, self.uid,
company_id).debit_account_ids]
def _get_partner_balance(self, account, init_period, ctx=None): def _get_partner_balance(self, account, init_period, ctx=None):
rp_obj = self.pool.get('res.partner')
res = [] res = []
ctx = ctx or {} ctx = ctx or {}
if account['type'] in ('other', 'liquidity', 'receivable', 'payable'): if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
sql_query = """ sql_query = """
SELECT
SELECT
CASE CASE
WHEN aml.partner_id IS NOT NULL WHEN aml.partner_id IS NOT NULL
THEN (SELECT name FROM res_partner WHERE aml.partner_id = id)
THEN (SELECT name
FROM res_partner
WHERE aml.partner_id = id)
ELSE 'UNKNOWN' ELSE 'UNKNOWN'
END AS partner_name, END AS partner_name,
CASE CASE
@ -213,7 +224,7 @@ class account_balance(report_sxw.rml_parse):
%s %s
FROM account_move_line AS aml FROM account_move_line AS aml
INNER JOIN account_account aa ON aa.id = aml.account_id INNER JOIN account_account aa ON aa.id = aml.account_id
INNER JOIN account_move am ON am.id = aml.move_id
INNER JOIN account_move am ON am.id = aml.move_id
%s %s
GROUP BY p_idx, partner_name GROUP BY p_idx, partner_name
""" """
@ -226,8 +237,8 @@ class account_balance(report_sxw.rml_parse):
init_periods = ', '.join([str(i) for i in init_period]) init_periods = ', '.join([str(i) for i in init_period])
WHERE = """ WHERE = """
WHERE aml.period_id IN (%s)
AND aa.id = %s
WHERE aml.period_id IN (%s)
AND aa.id = %s
AND aml.state <> 'draft' AND aml.state <> 'draft'
""" % (init_periods, account['id']) """ % (init_periods, account['id'])
query_init = sql_query % ('SUM(aml.debit) AS init_dr', query_init = sql_query % ('SUM(aml.debit) AS init_dr',
@ -237,8 +248,8 @@ class account_balance(report_sxw.rml_parse):
WHERE + WHERE_POSTED) WHERE + WHERE_POSTED)
WHERE = """ WHERE = """
WHERE aml.period_id IN (%s)
AND aa.id = %s
WHERE aml.period_id IN (%s)
AND aa.id = %s
AND aml.state <> 'draft' AND aml.state <> 'draft'
""" % (cur_periods, account['id']) """ % (cur_periods, account['id'])
@ -250,12 +261,13 @@ class account_balance(report_sxw.rml_parse):
query = ''' query = '''
SELECT SELECT
partner_name,
p_idx,
partner_name,
p_idx,
SUM(init_dr)-SUM(init_cr) AS balanceinit, SUM(init_dr)-SUM(init_cr) AS balanceinit,
SUM(bal_dr) AS debit, SUM(bal_dr) AS debit,
SUM(bal_cr) AS credit, SUM(bal_cr) AS credit,
SUM(init_dr) - SUM(init_cr) + SUM(bal_dr) - SUM(bal_cr) AS balance
SUM(init_dr) - SUM(init_cr)
+ SUM(bal_dr) - SUM(bal_cr) AS balance
FROM ( FROM (
SELECT SELECT
* *
@ -292,29 +304,50 @@ class account_balance(report_sxw.rml_parse):
res = [] res = []
if account['type'] in ('other', 'liquidity', 'receivable', 'payable'): if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
#~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS DEL EJERCICIO
#~ FISCAL, SIN LOS PERIODOS ESPECIALES
# ~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS
# DEL EJERCICIO
# ~ FISCAL, SIN LOS PERIODOS ESPECIALES
periods = ', '.join([str(i) for i in ctx['periods']]) periods = ', '.join([str(i) for i in ctx['periods']])
#~ periods = str(tuple(ctx['periods']))
where = """where aml.period_id in (%s) and aa.id = %s and aml.state <> 'draft'""" % (
periods, account['id'])
# ~ periods = str(tuple(ctx['periods']))
where = """where aml.period_id in (%s)
and aa.id = %s
and aml.state <> 'draft'""" % (periods, account['id'])
if ctx.get('state', 'posted') == 'posted': if ctx.get('state', 'posted') == 'posted':
where += "AND am.state = 'posted'" where += "AND am.state = 'posted'"
sql_detalle = """select aml.id as id, aj.name as diario, aa.name as descripcion,
(select name from res_partner where aml.partner_id = id) as partner,
aa.code as cuenta, aml.name as name,
aml.ref as ref,
case when aml.debit is null then 0.00 else aml.debit end as debit,
case when aml.credit is null then 0.00 else aml.credit end as credit,
(select code from account_analytic_account where aml.analytic_account_id = id) as analitica,
aml.date as date, ap.name as periodo,
am.name as asiento
from account_move_line aml
inner join account_journal aj on aj.id = aml.journal_id
inner join account_account aa on aa.id = aml.account_id
inner join account_period ap on ap.id = aml.period_id
inner join account_move am on am.id = aml.move_id """ + where +\
""" order by date, am.name"""
sql_detalle = """select aml.id as id,
aj.name as diario,
aa.name as descripcion,
(select name
from res_partner
where aml.partner_id = id) as partner,
aa.code as cuenta,
aml.name as name,
aml.ref as ref,
case when aml.debit is null
then 0.00
else aml.debit
end as debit,
case when aml.credit is null
then 0.00
else aml.credit
end as credit,
(select code
from account_analytic_account
where aml.analytic_account_id = id)
as analitica,
aml.date as date,
ap.name as periodo,
am.name as asiento
from account_move_line aml
inner join account_journal aj
on aj.id = aml.journal_id
inner join account_account aa
on aa.id = aml.account_id
inner join account_period ap
on ap.id = aml.period_id
inner join account_move am
on am.id = aml.move_id """ \
+ where + """ order by date, am.name"""
self.cr.execute(sql_detalle) self.cr.execute(sql_detalle)
resultat = self.cr.dictfetchall() resultat = self.cr.dictfetchall()
@ -342,26 +375,28 @@ class account_balance(report_sxw.rml_parse):
am_obj = self.pool.get('account.move') am_obj = self.pool.get('account.move')
print 'AM OBJ ', am_obj print 'AM OBJ ', am_obj
if account['type'] in ('other', 'liquidity', 'receivable', 'payable'): if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
#~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS DEL EJERCICIO
#~ FISCAL, SIN LOS PERIODOS ESPECIALES
# ~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS
# DEL EJERCICIO
# ~ FISCAL, SIN LOS PERIODOS ESPECIALES
periods = ', '.join([str(i) for i in ctx['periods']]) periods = ', '.join([str(i) for i in ctx['periods']])
#~ periods = str(tuple(ctx['periods']))
where = """where aml.period_id in (%s) and aa.id = %s and aml.state <> 'draft'""" % (
periods, account['id'])
# ~ periods = str(tuple(ctx['periods']))
where = """where aml.period_id in (%s)
and aa.id = %s
and aml.state <> 'draft'""" % (periods, account['id'])
if ctx.get('state', 'posted') == 'posted': if ctx.get('state', 'posted') == 'posted':
where += "AND am.state = 'posted'" where += "AND am.state = 'posted'"
sql_detalle = """SELECT
sql_detalle = """SELECT
DISTINCT am.id as am_id, DISTINCT am.id as am_id,
aj.name as diario, aj.name as diario,
am.name as name, am.name as name,
am.date as date,
am.date as date,
ap.name as periodo ap.name as periodo
from account_move_line aml from account_move_line aml
inner join account_journal aj on aj.id = aml.journal_id inner join account_journal aj on aj.id = aml.journal_id
inner join account_account aa on aa.id = aml.account_id inner join account_account aa on aa.id = aml.account_id
inner join account_period ap on ap.id = aml.period_id inner join account_period ap on ap.id = aml.period_id
inner join account_move am on am.id = aml.move_id """ + where +\
""" order by date, am.name"""
inner join account_move am on am.id = aml.move_id """ \
+ where + """ order by date, am.name"""
self.cr.execute(sql_detalle) self.cr.execute(sql_detalle)
resultat = self.cr.dictfetchall() resultat = self.cr.dictfetchall()
@ -374,7 +409,8 @@ class account_balance(report_sxw.rml_parse):
'period': det['periodo'], 'period': det['periodo'],
'obj': am_obj.browse(self.cr, self.uid, det['am_id']) 'obj': am_obj.browse(self.cr, self.uid, det['am_id'])
}) })
print 'ACCOUNT NAME', am_obj.browse(self.cr, self.uid, det['am_id']).name
print 'ACCOUNT NAME', am_obj.browse(self.cr, self.uid,
det['am_id']).name
return res return res
def lines(self, form, level=0): def lines(self, form, level=0):
@ -387,15 +423,18 @@ class account_balance(report_sxw.rml_parse):
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
fiscalyear_obj = self.pool.get('account.fiscalyear') fiscalyear_obj = self.pool.get('account.fiscalyear')
def _get_children_and_consol(cr, uid, ids, level, context={}, change_sign=False):
def _get_children_and_consol(cr, uid, ids, level, context={},
change_sign=False):
aa_obj = self.pool.get('account.account') aa_obj = self.pool.get('account.account')
ids2 = [] ids2 = []
for aa_brw in aa_obj.browse(cr, uid, ids, context): for aa_brw in aa_obj.browse(cr, uid, ids, context):
if aa_brw.child_id and aa_brw.level < level and aa_brw.type != 'consolidation':
if aa_brw.child_id and aa_brw.level < level \
and aa_brw.type != 'consolidation':
if not change_sign: if not change_sign:
ids2.append([aa_brw.id, True, False, aa_brw]) ids2.append([aa_brw.id, True, False, aa_brw])
ids2 += _get_children_and_consol(cr, uid, [
x.id for x in aa_brw.child_id], level, context, change_sign=change_sign)
ids2 += _get_children_and_consol(
cr, uid, [x.id for x in aa_brw.child_id], level,
context, change_sign=change_sign)
if change_sign: if change_sign:
ids2.append(aa_brw.id) ids2.append(aa_brw.id)
else: else:
@ -408,13 +447,15 @@ class account_balance(report_sxw.rml_parse):
return ids2 return ids2
####################################################################### #######################################################################
# CONTEXT FOR ENDIND BALANCE #
# CONTEXT FOR ENDIND BALANCE #
####################################################################### #######################################################################
def _ctx_end(ctx): def _ctx_end(ctx):
ctx_end = ctx ctx_end = ctx
ctx_end['filter'] = form.get('filter', 'all') ctx_end['filter'] = form.get('filter', 'all')
ctx_end['fiscalyear'] = fiscalyear.id ctx_end['fiscalyear'] = fiscalyear.id
#~ ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)])
# ~ ctx_end['periods'] = period_obj.\
# search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),
# ('special','=',False)])
if ctx_end['filter'] not in ['bydate', 'none']: if ctx_end['filter'] not in ['bydate', 'none']:
special = self.special_period(form['periods']) special = self.special_period(form['periods'])
@ -423,11 +464,16 @@ class account_balance(report_sxw.rml_parse):
if form['filter'] in ['byperiod', 'all']: if form['filter'] in ['byperiod', 'all']:
if special: if special:
ctx_end['periods'] = period_obj.search(self.cr, self.uid, [(
'id', 'in', form['periods'] or ctx_end.get('periods', False))])
ctx_end['periods'] = period_obj.search(
self.cr, self.uid,
[('id', 'in', form['periods'] or ctx_end.get('periods',
False))])
else: else:
ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('id', 'in', form[
'periods'] or ctx_end.get('periods', False)), ('special', '=', False)])
ctx_end['periods'] = period_obj.search(
self.cr, self.uid,
[('id', 'in', form['periods'] or ctx_end.get('periods',
False)),
('special', '=', False)])
if form['filter'] in ['bydate', 'all', 'none']: if form['filter'] in ['bydate', 'all', 'none']:
ctx_end['date_from'] = form['date_from'] ctx_end['date_from'] = form['date_from']
@ -437,14 +483,22 @@ class account_balance(report_sxw.rml_parse):
def missing_period(ctx_init): def missing_period(ctx_init):
ctx_init['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop', '<', fiscalyear.date_start)], order='date_stop') and \
fiscalyear_obj.search(self.cr, self.uid, [(
'date_stop', '<', fiscalyear.date_start)], order='date_stop')[-1] or []
ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', ctx_init['fiscalyear']), ('date_stop', '<', fiscalyear.date_start)])
ctx_init['fiscalyear'] = \
fiscalyear_obj.search(self.cr, self.uid,
[('date_stop', '<',
fiscalyear.date_start)],
order='date_stop') \
and fiscalyear_obj.search(self.cr, self.uid,
[('date_stop', '<',
fiscalyear.date_start)],
order='date_stop')[-1] or []
ctx_init['periods'] = period_obj.search(
self.cr, self.uid,
[('fiscalyear_id', '=', ctx_init['fiscalyear']),
('date_stop', '<', fiscalyear.date_start)])
return ctx_init return ctx_init
####################################################################### #######################################################################
# CONTEXT FOR INITIAL BALANCE #
# CONTEXT FOR INITIAL BALANCE #
####################################################################### #######################################################################
def _ctx_init(ctx): def _ctx_init(ctx):
@ -456,22 +510,30 @@ class account_balance(report_sxw.rml_parse):
ctx_init['periods'] = form['periods'] ctx_init['periods'] = form['periods']
if not ctx_init['periods']: if not ctx_init['periods']:
ctx_init = missing_period(ctx_init.copy()) ctx_init = missing_period(ctx_init.copy())
date_start = min([period.date_start for period in period_obj.browse(
self.cr, self.uid, ctx_init['periods'])])
ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('date_stop', '<=', date_start)])
date_start = min([period.date_start for period in period_obj.
browse(self.cr, self.uid,
ctx_init['periods'])])
ctx_init['periods'] = period_obj.search(
self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
('date_stop', '<=', date_start)])
elif form['filter'] in ['bydate']: elif form['filter'] in ['bydate']:
ctx_init['date_from'] = fiscalyear.date_start ctx_init['date_from'] = fiscalyear.date_start
ctx_init['date_to'] = form['date_from'] ctx_init['date_to'] = form['date_from']
ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('date_stop', '<=', ctx_init['date_to'])])
ctx_init['periods'] = period_obj.search(
self.cr, self.uid,
[('fiscalyear_id', '=', fiscalyear.id),
('date_stop', '<=', ctx_init['date_to'])])
elif form['filter'] == 'none': elif form['filter'] == 'none':
ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('special', '=', True)])
date_start = min([period.date_start for period in period_obj.browse(
self.cr, self.uid, ctx_init['periods'])])
ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('date_start', '<=', date_start), ('special', '=', True)])
ctx_init['periods'] = period_obj.search(
self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
('special', '=', True)])
date_start = min([period.date_start for period in period_obj.
browse(self.cr, self.uid,
ctx_init['periods'])])
ctx_init['periods'] = period_obj.search(
self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
('date_start', '<=', date_start),
('special', '=', True)])
return ctx_init.copy() return ctx_init.copy()
@ -480,24 +542,35 @@ class account_balance(report_sxw.rml_parse):
self.context['state'] = form['target_move'] or 'posted' self.context['state'] = form['target_move'] or 'posted'
self.from_currency_id = self.get_company_currency(form['company_id'] and type(form[
'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'])
self.from_currency_id = self.\
get_company_currency(form['company_id']
and type(form['company_id']) in (list, tuple)
and form['company_id'][0]
or form['company_id'])
if not form['currency_id']: if not form['currency_id']:
self.to_currency_id = self.from_currency_id self.to_currency_id = self.from_currency_id
else: else:
self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (
list, tuple) and form['currency_id'][0] or form['currency_id']
self.to_currency_id = form['currency_id'] \
and type(form['currency_id']) in (list, tuple) \
and form['currency_id'][0] \
or form['currency_id']
if 'account_list' in form and form['account_list']: if 'account_list' in form and form['account_list']:
account_ids = form['account_list'] account_ids = form['account_list']
account_list = form['account_list'] account_list = form['account_list']
del form['account_list'] del form['account_list']
credit_account_ids = self.get_company_accounts(form['company_id'] and type(form[
'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'], 'credit')
credit_account_ids = self.\
get_company_accounts(form['company_id']
and type(form['company_id']) in (list, tuple)
and form['company_id'][0]
or form['company_id'], 'credit')
debit_account_ids = self.get_company_accounts(form['company_id'] and type(form[
'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'], 'debit')
debit_account_ids = self.\
get_company_accounts(form['company_id']
and type(form['company_id']) in (list, tuple)
and form['company_id'][0]
or form['company_id'], 'debit')
if form.get('fiscalyear'): if form.get('fiscalyear'):
if type(form.get('fiscalyear')) in (list, tuple): if type(form.get('fiscalyear')) in (list, tuple):
@ -512,14 +585,19 @@ class account_balance(report_sxw.rml_parse):
all_account_ids = _get_children_and_consol( all_account_ids = _get_children_and_consol(
self.cr, self.uid, account_ids, 100, self.context) self.cr, self.uid, account_ids, 100, self.context)
account_ids = _get_children_and_consol(self.cr, self.uid, account_ids, form[
'display_account_level'] and form['display_account_level'] or 100, self.context)
account_ids = _get_children_and_consol(
self.cr, self.uid, account_ids,
form['display_account_level']
and form['display_account_level']
or 100, self.context)
credit_account_ids = _get_children_and_consol( credit_account_ids = _get_children_and_consol(
self.cr, self.uid, credit_account_ids, 100, self.context, change_sign=True)
self.cr, self.uid, credit_account_ids, 100, self.context,
change_sign=True)
debit_account_ids = _get_children_and_consol( debit_account_ids = _get_children_and_consol(
self.cr, self.uid, debit_account_ids, 100, self.context, change_sign=True)
self.cr, self.uid, debit_account_ids, 100, self.context,
change_sign=True)
credit_account_ids = list(set( credit_account_ids = list(set(
credit_account_ids) - set(debit_account_ids)) credit_account_ids) - set(debit_account_ids))
@ -530,35 +608,41 @@ class account_balance(report_sxw.rml_parse):
tot_check = False tot_check = False
if not form['periods']: if not form['periods']:
form['periods'] = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('special', '=', False)], order='date_start asc')
form['periods'] = period_obj.search(
self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
('special', '=', False)],
order='date_start asc')
if not form['periods']: if not form['periods']:
raise osv.except_osv(_('UserError'), _( raise osv.except_osv(_('UserError'), _(
'The Selected Fiscal Year Does not have Regular Periods')) 'The Selected Fiscal Year Does not have Regular Periods'))
if form['columns'] == 'qtr': if form['columns'] == 'qtr':
period_ids = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('special', '=', False)], order='date_start asc')
period_ids = period_obj.search(
self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
('special', '=', False)],
order='date_start asc')
a = 0 a = 0
l = [] l = []
p = [] p = []
for x in period_ids: for x in period_ids:
a += 1 a += 1
if a < 3: if a < 3:
l.append(x)
l.append(x)
else: else:
l.append(x)
p.append(l)
l = []
a = 0
l.append(x)
p.append(l)
l = []
a = 0
tot_bal1 = 0.0 tot_bal1 = 0.0
tot_bal2 = 0.0 tot_bal2 = 0.0
tot_bal3 = 0.0 tot_bal3 = 0.0
tot_bal4 = 0.0 tot_bal4 = 0.0
tot_bal5 = 0.0 tot_bal5 = 0.0
elif form['columns'] == 'thirteen': elif form['columns'] == 'thirteen':
period_ids = period_obj.search(self.cr, self.uid, [(
'fiscalyear_id', '=', fiscalyear.id), ('special', '=', False)], order='date_start asc')
period_ids = period_obj.search(
self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
('special', '=', False)],
order='date_start asc')
tot_bal1 = 0.0 tot_bal1 = 0.0
tot_bal1 = 0.0 tot_bal1 = 0.0
tot_bal2 = 0.0 tot_bal2 = 0.0
@ -590,19 +674,21 @@ class account_balance(report_sxw.rml_parse):
# without repeating operations. # without repeating operations.
############################################################### ###############################################################
account_black_ids = account_obj.search(self.cr, self.uid, (
[('id', 'in', [i[0] for i in all_account_ids]),
('type', 'not in',
('view', 'consolidation'))]))
account_black_ids = account_obj.search(
self.cr, self.uid, (
[('id', 'in', [i[0] for i in all_account_ids]),
('type', 'not in', ('view', 'consolidation'))]))
account_not_black_ids = account_obj.search(self.cr, self.uid, ([('id', 'in', [
i[0] for i in all_account_ids]), ('type', '=', 'view')]))
account_not_black_ids = account_obj.search(
self.cr, self.uid, ([('id', 'in', [i[0] for i in all_account_ids]),
('type', '=', 'view')]))
acc_cons_ids = account_obj.search(self.cr, self.uid, ([('id', 'in', [
i[0] for i in all_account_ids]), ('type', 'in', ('consolidation',))]))
acc_cons_ids = account_obj.search(
self.cr, self.uid, ([('id', 'in', [i[0] for i in all_account_ids]),
('type', 'in', ('consolidation',))]))
account_consol_ids = acc_cons_ids and account_obj._get_children_and_consol(
self.cr, self.uid, acc_cons_ids) or []
account_consol_ids = acc_cons_ids and account_obj.\
_get_children_and_consol(self.cr, self.uid, acc_cons_ids) or []
account_black_ids += account_obj.search(self.cr, self.uid, ( account_black_ids += account_obj.search(self.cr, self.uid, (
[('id', 'in', account_consol_ids), [('id', 'in', account_consol_ids),
@ -612,8 +698,7 @@ class account_balance(report_sxw.rml_parse):
account_black_ids = list(set(account_black_ids)) account_black_ids = list(set(account_black_ids))
c_account_not_black_ids = account_obj.search(self.cr, self.uid, ([ c_account_not_black_ids = account_obj.search(self.cr, self.uid, ([
('id', 'in',
account_consol_ids),
('id', 'in', account_consol_ids),
('type', '=', 'view')])) ('type', '=', 'view')]))
delete_cons = False delete_cons = False
if c_account_not_black_ids: if c_account_not_black_ids:
@ -684,7 +769,7 @@ class account_balance(report_sxw.rml_parse):
account_black_init = account_obj.browse( account_black_init = account_obj.browse(
self.cr, self.uid, account_black_ids, ctx_i) self.cr, self.uid, account_black_ids, ctx_i)
#~ Black
# ~ Black
dict_black = {} dict_black = {}
for i in account_black: for i in account_black:
d = i.debit d = i.debit
@ -704,7 +789,7 @@ class account_balance(report_sxw.rml_parse):
for i in account_black_init: for i in account_black_init:
dict_black.get(i.id)['balanceinit'] = i.balance dict_black.get(i.id)['balanceinit'] = i.balance
#~ Not black
# ~ Not black
dict_not_black = {} dict_not_black = {}
for i in account_not_black: for i in account_not_black:
dict_not_black[i.id] = { dict_not_black[i.id] = {
@ -716,7 +801,8 @@ class account_balance(report_sxw.rml_parse):
) # It makes a copy because they modify ) # It makes a copy because they modify
for acc_id in account_not_black_ids: for acc_id in account_not_black_ids:
acc_childs = dict_not_black.get(acc_id).get('obj').type == 'view' \
acc_childs = dict_not_black.get(acc_id).get('obj').\
type == 'view' \
and dict_not_black.get(acc_id).get('obj').child_id \ and dict_not_black.get(acc_id).get('obj').child_id \
or dict_not_black.get(acc_id).get('obj').child_consol_ids or dict_not_black.get(acc_id).get('obj').child_consol_ids
for child_id in acc_childs: for child_id in acc_childs:
@ -729,8 +815,8 @@ class account_balance(report_sxw.rml_parse):
dict_not_black.get(acc_id)['balance'] += all_account.get( dict_not_black.get(acc_id)['balance'] += all_account.get(
child_id.id).get('balance') child_id.id).get('balance')
if form['inf_type'] == 'BS': if form['inf_type'] == 'BS':
dict_not_black.get(acc_id)['balanceinit'] += all_account.get(
child_id.id).get('balanceinit')
dict_not_black.get(acc_id)['balanceinit'] += \
all_account.get(child_id.id).get('balanceinit')
all_account[acc_id] = dict_not_black[acc_id] all_account[acc_id] = dict_not_black[acc_id]
if p_act == limit - 1: if p_act == limit - 1:
@ -753,17 +839,21 @@ class account_balance(report_sxw.rml_parse):
# #
# Check if we need to include this level # Check if we need to include this level
# #
if not form['display_account_level'] or aa_id[3].level <= form['display_account_level']:
if not form['display_account_level'] \
or aa_id[3].level <= form['display_account_level']:
res = { res = {
'id': id, 'id': id,
'type': aa_id[3].type, 'type': aa_id[3].type,
'code': aa_id[3].code, 'code': aa_id[3].code,
'name': (aa_id[2] and not aa_id[1]) and 'TOTAL %s' % (aa_id[3].name.upper()) or aa_id[3].name,
'name': (aa_id[2] and not aa_id[1])
and 'TOTAL %s' % (aa_id[3].name.upper())
or aa_id[3].name,
'parent_id': aa_id[3].parent_id and aa_id[3].parent_id.id, 'parent_id': aa_id[3].parent_id and aa_id[3].parent_id.id,
'level': aa_id[3].level, 'level': aa_id[3].level,
'label': aa_id[1], 'label': aa_id[1],
'total': aa_id[2], 'total': aa_id[2],
'change_sign': credit_account_ids and (id in credit_account_ids and -1 or 1) or 1
'change_sign': credit_account_ids
and (id in credit_account_ids and -1 or 1) or 1
} }
if form['columns'] == 'qtr': if form['columns'] == 'qtr':
@ -771,7 +861,12 @@ class account_balance(report_sxw.rml_parse):
if form['inf_type'] == 'IS': if form['inf_type'] == 'IS':
d, c, b = map(z, [ d, c, b = map(z, [
all_account_period.get(pn - 1).get(id).get('debit', 0.0), all_account_period.get(pn - 1).get(id).get('credit', 0.0), all_account_period.get(pn - 1).get(id).get('balance', 0.0)])
all_account_period.get(pn - 1).
get(id).get('debit', 0.0),
all_account_period.get(pn - 1).
get(id).get('credit', 0.0),
all_account_period.get(pn - 1).
get(id).get('balance', 0.0)])
res.update({ res.update({
'dbr%s' % pn: self.exchange(d), 'dbr%s' % pn: self.exchange(d),
'cdr%s' % pn: self.exchange(c), 'cdr%s' % pn: self.exchange(c),
@ -779,7 +874,12 @@ class account_balance(report_sxw.rml_parse):
}) })
else: else:
i, d, c = map(z, [ i, d, c = map(z, [
all_account_period.get(pn - 1).get(id).get('balanceinit', 0.0), all_account_period.get(pn - 1).get(id).get('debit', 0.0), all_account_period.get(pn - 1).get(id).get('credit', 0.0)])
all_account_period.get(pn - 1).
get(id).get('balanceinit', 0.0),
all_account_period.get(pn - 1).
get(id).get('debit', 0.0),
all_account_period.get(pn - 1).
get(id).get('credit', 0.0)])
b = z(i + d - c) b = z(i + d - c)
res.update({ res.update({
'dbr%s' % pn: self.exchange(d), 'dbr%s' % pn: self.exchange(d),
@ -789,7 +889,12 @@ class account_balance(report_sxw.rml_parse):
if form['inf_type'] == 'IS': if form['inf_type'] == 'IS':
d, c, b = map(z, [ d, c, b = map(z, [
all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0), all_account_period.get('all').get(id).get('balance')])
all_account_period.get('all').get(id).
get('debit', 0.0),
all_account_period.get('all').get(id).
get('credit', 0.0),
all_account_period.get('all').get(id).
get('balance')])
res.update({ res.update({
'dbr5': self.exchange(d), 'dbr5': self.exchange(d),
'cdr5': self.exchange(c), 'cdr5': self.exchange(c),
@ -797,7 +902,12 @@ class account_balance(report_sxw.rml_parse):
}) })
else: else:
i, d, c = map(z, [ i, d, c = map(z, [
all_account_period.get('all').get(id).get('balanceinit', 0.0), all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0)])
all_account_period.get('all').get(id).
get('balanceinit', 0.0),
all_account_period.get('all').get(id).
get('debit', 0.0),
all_account_period.get('all').get(id).
get('credit', 0.0)])
b = z(i + d - c) b = z(i + d - c)
res.update({ res.update({
'dbr5': self.exchange(d), 'dbr5': self.exchange(d),
@ -811,7 +921,12 @@ class account_balance(report_sxw.rml_parse):
if form['inf_type'] == 'IS': if form['inf_type'] == 'IS':
d, c, b = map(z, [ d, c, b = map(z, [
all_account_period.get(p_num).get(id).get('debit', 0.0), all_account_period.get(p_num).get(id).get('credit', 0.0), all_account_period.get(p_num).get(id).get('balance', 0.0)])
all_account_period.get(p_num).
get(id).get('debit', 0.0),
all_account_period.get(p_num).
get(id).get('credit', 0.0),
all_account_period.get(p_num).
get(id).get('balance', 0.0)])
res.update({ res.update({
'dbr%s' % pn: self.exchange(d), 'dbr%s' % pn: self.exchange(d),
'cdr%s' % pn: self.exchange(c), 'cdr%s' % pn: self.exchange(c),
@ -819,7 +934,12 @@ class account_balance(report_sxw.rml_parse):
}) })
else: else:
i, d, c = map(z, [ i, d, c = map(z, [
all_account_period.get(p_num).get(id).get('balanceinit', 0.0), all_account_period.get(p_num).get(id).get('debit', 0.0), all_account_period.get(p_num).get(id).get('credit', 0.0)])
all_account_period.get(p_num).
get(id).get('balanceinit', 0.0),
all_account_period.get(p_num).
get(id).get('debit', 0.0),
all_account_period.get(p_num).
get(id).get('credit', 0.0)])
b = z(i + d - c) b = z(i + d - c)
res.update({ res.update({
'dbr%s' % pn: self.exchange(d), 'dbr%s' % pn: self.exchange(d),
@ -831,7 +951,12 @@ class account_balance(report_sxw.rml_parse):
if form['inf_type'] == 'IS': if form['inf_type'] == 'IS':
d, c, b = map(z, [ d, c, b = map(z, [
all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0), all_account_period.get('all').get(id).get('balance', 0.0)])
all_account_period.get('all').get(id).
get('debit', 0.0),
all_account_period.get('all').get(id).
get('credit', 0.0),
all_account_period.get('all').get(id).
get('balance', 0.0)])
res.update({ res.update({
'dbr13': self.exchange(d), 'dbr13': self.exchange(d),
'cdr13': self.exchange(c), 'cdr13': self.exchange(c),
@ -839,7 +964,12 @@ class account_balance(report_sxw.rml_parse):
}) })
else: else:
i, d, c = map(z, [ i, d, c = map(z, [
all_account_period.get('all').get(id).get('balanceinit', 0.0), all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0)])
all_account_period.get('all').get(id).
get('balanceinit', 0.0),
all_account_period.get('all').get(id).
get('debit', 0.0),
all_account_period.get('all').get(id).
get('credit', 0.0)])
b = z(i + d - c) b = z(i + d - c)
res.update({ res.update({
'dbr13': self.exchange(d), 'dbr13': self.exchange(d),
@ -849,7 +979,12 @@ class account_balance(report_sxw.rml_parse):
else: else:
i, d, c = map(z, [ i, d, c = map(z, [
all_account_period.get('all').get(id).get('balanceinit', 0.0), all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0)])
all_account_period.get('all').get(id).
get('balanceinit', 0.0),
all_account_period.get('all').get(id).
get('debit', 0.0),
all_account_period.get('all').get(id).
get('credit', 0.0)])
b = z(i + d - c) b = z(i + d - c)
res.update({ res.update({
'balanceinit': self.exchange(i), 'balanceinit': self.exchange(i),
@ -884,7 +1019,8 @@ class account_balance(report_sxw.rml_parse):
if any(to_test): if any(to_test):
to_include = True to_include = True
elif form['display_account'] == 'bal' and aa_id[3].parent_id:
elif form['display_account'] == 'bal' and aa_id[3].\
parent_id:
# Include accounts with balance # Include accounts with balance
for x in range(pn - 1): for x in range(pn - 1):
to_test.append(res.get( to_test.append(res.get(
@ -892,7 +1028,8 @@ class account_balance(report_sxw.rml_parse):
if any(to_test): if any(to_test):
to_include = True to_include = True
elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
elif form['display_account'] == 'bal_mov' and aa_id[3].\
parent_id:
# Include accounts with balance or movements # Include accounts with balance or movements
for x in range(pn - 1): for x in range(pn - 1):
to_test.append(res.get( to_test.append(res.get(
@ -913,24 +1050,40 @@ class account_balance(report_sxw.rml_parse):
# Include accounts with movements # Include accounts with movements
if abs(d) >= 0.005 or abs(c) >= 0.005: if abs(d) >= 0.005 or abs(c) >= 0.005:
to_include = True to_include = True
elif form['display_account'] == 'bal' and aa_id[3].parent_id:
elif form['display_account'] == 'bal' and aa_id[3].\
parent_id:
# Include accounts with balance # Include accounts with balance
if abs(b) >= 0.005: if abs(b) >= 0.005:
to_include = True to_include = True
elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
elif form['display_account'] == 'bal_mov' and aa_id[3].\
parent_id:
# Include accounts with balance or movements # Include accounts with balance or movements
if abs(b) >= 0.005 or abs(d) >= 0.005 or abs(c) >= 0.005:
if abs(b) >= 0.005 \
or abs(d) >= 0.005 \
or abs(c) >= 0.005:
to_include = True to_include = True
else: else:
# Include all accounts # Include all accounts
to_include = True to_include = True
#~ ANALYTIC LEDGER
if to_include and form['analytic_ledger'] and form['columns'] == 'four' and form['inf_type'] == 'BS' and res['type'] in ('other', 'liquidity', 'receivable', 'payable'):
# ~ ANALYTIC LEDGER
if to_include and form['analytic_ledger'] \
and form['columns'] == 'four' \
and form['inf_type'] == 'BS' \
and res['type'] in ('other', 'liquidity',
'receivable', 'payable'):
res['mayor'] = self._get_analytic_ledger(res, ctx=ctx_end) res['mayor'] = self._get_analytic_ledger(res, ctx=ctx_end)
elif to_include and form['journal_ledger'] and form['columns'] == 'four' and form['inf_type'] == 'BS' and res['type'] in ('other', 'liquidity', 'receivable', 'payable'):
elif to_include and form['journal_ledger'] \
and form['columns'] == 'four' \
and form['inf_type'] == 'BS' \
and res['type'] in ('other', 'liquidity',
'receivable', 'payable'):
res['journal'] = self._get_journal_ledger(res, ctx=ctx_end) res['journal'] = self._get_journal_ledger(res, ctx=ctx_end)
elif to_include and form['partner_balance'] and form['columns'] == 'four' and form['inf_type'] == 'BS' and res['type'] in ('other', 'liquidity', 'receivable', 'payable'):
elif to_include and form['partner_balance'] \
and form['columns'] == 'four' \
and form['inf_type'] == 'BS' \
and res['type'] in ('other', 'liquidity',
'receivable', 'payable'):
res['partner'] = self._get_partner_balance( res['partner'] = self._get_partner_balance(
res, ctx_i['periods'], ctx=ctx_end) res, ctx_i['periods'], ctx=ctx_end)
else: else:
@ -939,9 +1092,11 @@ class account_balance(report_sxw.rml_parse):
if to_include: if to_include:
result_acc.append(res) result_acc.append(res)
# #
# Check whether we must sumarize this line in the report or not
# Check whether we must sumarize this line in the report
# or not
# #
if form['tot_check'] and (res['id'] in account_list) and (res['id'] not in tot):
if form['tot_check'] and (res['id'] in account_list) \
and (res['id'] not in tot):
if form['columns'] == 'qtr': if form['columns'] == 'qtr':
tot_check = True tot_check = True
tot[res['id']] = True tot[res['id']] = True
@ -1019,56 +1174,65 @@ class account_balance(report_sxw.rml_parse):
result_acc.append(res2) result_acc.append(res2)
return result_acc return result_acc
report_sxw.report_sxw('report.afr.1cols',
'wizard.report',
'account_financial_report/report/balance_full.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.2cols',
'wizard.report',
'account_financial_report/report/balance_full_2_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.4cols',
'wizard.report',
'account_financial_report/report/balance_full_4_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.analytic.ledger',
'wizard.report',
'account_financial_report/report/balance_full_4_cols_analytic_ledger.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.partner.balance',
'wizard.report',
'account_financial_report/report/balance_full_4_cols_partner_balance.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.journal.ledger',
'wizard.report',
'account_financial_report/report/balance_full_4_cols_journal_ledger.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.5cols',
'wizard.report',
'account_financial_report/report/balance_full_5_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.qtrcols',
'wizard.report',
'account_financial_report/report/balance_full_qtr_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw('report.afr.13cols',
'wizard.report',
'account_financial_report/report/balance_full_13_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.1cols',
'wizard.report',
'account_financial_report/report/balance_full.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.2cols',
'wizard.report',
'account_financial_report/report/balance_full_2_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.4cols',
'wizard.report',
'account_financial_report/report/balance_full_4_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.analytic.ledger',
'wizard.report',
'account_financial_report/report/balance_full_4_cols_analytic_ledger.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.partner.balance',
'wizard.report',
'account_financial_report/report/balance_full_4_cols_partner_balance.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.journal.ledger',
'wizard.report',
'account_financial_report/report/balance_full_4_cols_journal_ledger.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.5cols',
'wizard.report',
'account_financial_report/report/balance_full_5_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.qtrcols',
'wizard.report',
'account_financial_report/report/balance_full_qtr_cols.rml',
parser=account_balance,
header=False)
report_sxw.report_sxw(
'report.afr.13cols',
'wizard.report',
'account_financial_report/report/balance_full_13_cols.rml',
parser=account_balance,
header=False)

2
account_financial_report/wizard/__init__.py

@ -25,4 +25,4 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## ##############################################################################
import wizard
from . import wizard

201
account_financial_report/wizard/wizard.py

@ -26,43 +26,94 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## ##############################################################################
from osv import osv, fields
import pooler
from openerp.osv import osv, fields
import time import time
from tools.translate import _
from openerp.tools.translate import _
class wizard_report(osv.osv_memory): class wizard_report(osv.osv_memory):
_name = "wizard.report" _name = "wizard.report"
_columns = { _columns = {
'afr_id': fields.many2one('afr', 'Custom Report', help='If you have already set a Custom Report, Select it Here.'),
'afr_id': fields.many2one(
'afr', 'Custom Report',
help='If you have already set a Custom Report, Select it Here.'),
'company_id': fields.many2one('res.company', 'Company', required=True), 'company_id': fields.many2one('res.company', 'Company', required=True),
'currency_id': fields.many2one('res.currency', 'Currency', help="Currency at which this report will be expressed. If not selected will be used the one set in the company"),
'inf_type': fields.selection([('BS', 'Balance Sheet'), ('IS', 'Income Statement')], 'Type', required=True),
'columns': fields.selection([('one', 'End. Balance'), ('two', 'Debit | Credit'), ('four', 'Initial | Debit | Credit | YTD'), ('five', 'Initial | Debit | Credit | Period | YTD'), ('qtr', "4 QTR's | YTD"), ('thirteen', '12 Months | YTD')], 'Columns', required=True),
'display_account': fields.selection([('all', 'All Accounts'), ('bal', 'With Balance'), ('mov', 'With movements'), ('bal_mov', 'With Balance / Movements')], 'Display accounts'),
'display_account_level': fields.integer('Up to level', help='Display accounts up to this level (0 to show all)'),
'account_list': fields.many2many('account.account', 'rel_wizard_account', 'account_list', 'account_id', 'Root accounts', required=True),
'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscal year', help='Fiscal Year for this report', required=True),
'periods': fields.many2many('account.period', 'rel_wizard_period', 'wizard_id', 'period_id', 'Periods', help='All periods in the fiscal year if empty'),
'analytic_ledger': fields.boolean('Analytic Ledger', help="Allows to Generate an Analytic Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
'journal_ledger': fields.boolean('Journal Ledger', help="Allows to Generate an Journal Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
'partner_balance': fields.boolean('Partner Balance', help="Allows to "
"Generate a Partner Balance for accounts with moves. Available when "
"Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
'tot_check': fields.boolean('Summarize?', help='Checking will add a new line at the end of the Report which will Summarize Columns in Report'),
'lab_str': fields.char('Description', help='Description for the Summary', size=128),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Entries to Include', required=True,
help='Print All Accounting Entries or just Posted Accounting Entries'),
#~ Deprecated fields
'filter': fields.selection([('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')], 'Date/Period Filter'),
'currency_id': fields.many2one(
'res.currency', 'Currency',
help="Currency at which this report will be expressed. If not \
selected will be used the one set in the company"),
'inf_type': fields.selection([('BS', 'Balance Sheet'),
('IS', 'Income Statement')],
'Type',
required=True),
'columns': fields.selection(
[('one', 'End. Balance'),
('two', 'Debit | Credit'),
('four', 'Initial | Debit | Credit | YTD'),
('five', 'Initial | Debit | Credit | Period | YTD'),
('qtr', "4 QTR's | YTD"), ('thirteen', '12 Months | YTD')],
'Columns', required=True),
'display_account': fields.selection(
[('all', 'All Accounts'),
('bal', 'With Balance'),
('mov', 'With movements'),
('bal_mov', 'With Balance / Movements')],
'Display accounts'),
'display_account_level': fields.integer(
'Up to level',
help='Display accounts up to this level (0 to show all)'),
'account_list': fields.many2many('account.account',
'rel_wizard_account',
'account_list',
'account_id',
'Root accounts',
required=True),
'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscal year',
help='Fiscal Year for this report',
required=True),
'periods': fields.many2many(
'account.period', 'rel_wizard_period',
'wizard_id', 'period_id', 'Periods',
help='All periods in the fiscal year if empty'),
'analytic_ledger': fields.boolean(
'Analytic Ledger',
help="Allows to Generate an Analytic Ledger for accounts with \
moves. Available when Balance Sheet and 'Initial | Debit | Credit \
| YTD' are selected"),
'journal_ledger': fields.boolean(
'Journal Ledger',
help="Allows to Generate an Journal Ledger for accounts with \
moves. Available when Balance Sheet and 'Initial | Debit | Credit \
| YTD' are selected"),
'partner_balance': fields.boolean(
'Partner Balance',
help="Allows to Generate a Partner Balance for accounts with \
moves. Available when Balance Sheet and 'Initial | Debit | Credit \
| YTD' are selected"),
'tot_check': fields.boolean('Summarize?',
help='Checking will add a new line at the \
end of the Report which will Summarize \
Columns in Report'),
'lab_str': fields.char('Description',
help='Description for the Summary', size=128),
'target_move': fields.selection(
[('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Entries to Include',
required=True,
help='Print All Accounting Entries or just Posted Accounting \
Entries'),
# ~ Deprecated fields
'filter': fields.selection([('bydate', 'By Date'),
('byperiod', 'By Period'),
('all', 'By Date and Period'),
('none', 'No Filter')],
'Date/Period Filter'),
'date_to': fields.date('End date'), 'date_to': fields.date('End date'),
'date_from': fields.date('Start date'), 'date_from': fields.date('Start date'),
} }
@ -73,8 +124,10 @@ class wizard_report(osv.osv_memory):
'filter': lambda *a: 'byperiod', 'filter': lambda *a: 'byperiod',
'display_account_level': lambda *a: 0, 'display_account_level': lambda *a: 0,
'inf_type': lambda *a: 'BS', 'inf_type': lambda *a: 'BS',
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.invoice', context=c),
'fiscalyear': lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(cr, uid),
'company_id': lambda self, cr, uid, c: self.pool['res.company'].
_company_default_get(cr, uid, 'account.invoice', context=c),
'fiscalyear': lambda self, cr, uid, c: self.
pool['account.fiscalyear'].find(cr, uid),
'display_account': lambda *a: 'bal_mov', 'display_account': lambda *a: 'bal_mov',
'columns': lambda *a: 'five', 'columns': lambda *a: 'five',
'target_move': 'posted', 'target_move': 'posted',
@ -90,14 +143,16 @@ class wizard_report(osv.osv_memory):
return res return res
def onchange_columns(self, cr, uid, ids, columns, fiscalyear, periods, context=None):
def onchange_columns(self, cr, uid, ids, columns, fiscalyear, periods,
context=None):
if context is None: if context is None:
context = {} context = {}
res = {'value': {}} res = {'value': {}}
p_obj = self.pool.get("account.period") p_obj = self.pool.get("account.period")
all_periods = p_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear), (
'special', '=', False)], context=context)
all_periods = p_obj.search(cr, uid,
[('fiscalyear_id', '=', fiscalyear),
('special', '=', False)], context=context)
s = set(periods[0][2]) s = set(periods[0][2])
t = set(all_periods) t = set(all_periods)
go = periods[0][2] and s.issubset(t) or False go = periods[0][2] and s.issubset(t) or False
@ -114,7 +169,8 @@ class wizard_report(osv.osv_memory):
res['value'].update({'periods': []}) res['value'].update({'periods': []})
return res return res
def onchange_analytic_ledger(self, cr, uid, ids, company_id, analytic_ledger, context=None):
def onchange_analytic_ledger(self, cr, uid, ids, company_id,
analytic_ledger, context=None):
if context is None: if context is None:
context = {} context = {}
context['company_id'] = company_id context['company_id'] = company_id
@ -152,20 +208,26 @@ class wizard_report(osv.osv_memory):
return res return res
afr_brw = self.pool.get('afr').browse(cr, uid, afr_id, context=context) afr_brw = self.pool.get('afr').browse(cr, uid, afr_id, context=context)
res['value'].update({ res['value'].update({
'currency_id': afr_brw.currency_id and afr_brw.currency_id.id or afr_brw.company_id.currency_id.id})
'currency_id': afr_brw.currency_id
and afr_brw.currency_id.id
or afr_brw.company_id.currency_id.id})
res['value'].update({'inf_type': afr_brw.inf_type or 'BS'}) res['value'].update({'inf_type': afr_brw.inf_type or 'BS'})
res['value'].update({'columns': afr_brw.columns or 'five'}) res['value'].update({'columns': afr_brw.columns or 'five'})
res['value'].update({ res['value'].update({
'display_account': afr_brw.display_account or 'bal_mov'})
'display_account': afr_brw.display_account
or 'bal_mov'})
res['value'].update({ res['value'].update({
'display_account_level': afr_brw.display_account_level or 0})
'display_account_level': afr_brw.
display_account_level or 0})
res['value'].update({ res['value'].update({
'fiscalyear': afr_brw.fiscalyear_id and afr_brw.fiscalyear_id.id})
'fiscalyear': afr_brw.fiscalyear_id
and afr_brw.fiscalyear_id.id})
res['value'].update({'account_list': [ res['value'].update({'account_list': [
acc.id for acc in afr_brw.account_ids]}) acc.id for acc in afr_brw.account_ids]})
res['value'].update({'periods': [p.id for p in afr_brw.period_ids]}) res['value'].update({'periods': [p.id for p in afr_brw.period_ids]})
res['value'].update({ res['value'].update({
'analytic_ledger': afr_brw.analytic_ledger or False})
'analytic_ledger':
afr_brw.analytic_ledger or False})
res['value'].update({'tot_check': afr_brw.tot_check or False}) res['value'].update({'tot_check': afr_brw.tot_check or False})
res['value'].update({'lab_str': afr_brw.lab_str or _( res['value'].update({'lab_str': afr_brw.lab_str or _(
'Write a Description for your Summary Total')}) 'Write a Description for your Summary Total')})
@ -174,15 +236,14 @@ class wizard_report(osv.osv_memory):
def _get_defaults(self, cr, uid, data, context=None): def _get_defaults(self, cr, uid, data, context=None):
if context is None: if context is None:
context = {} context = {}
user = pooler.get_pool(cr.dbname).get(
'res.users').browse(cr, uid, uid, context=context)
user = self.pool['res.users'].browse(cr, uid, uid, context=context)
if user.company_id: if user.company_id:
company_id = user.company_id.id company_id = user.company_id.id
else: else:
company_id = pooler.get_pool(cr.dbname).get(
'res.company').search(cr, uid, [('parent_id', '=', False)])[0]
company_id = self.pool['res.company'].search(
cr, uid, [('parent_id', '=', False)])[0]
data['form']['company_id'] = company_id data['form']['company_id'] = company_id
fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
fiscalyear_obj = self.pool['account.fiscalyear']
data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
data['form']['context'] = context data['form']['context'] = context
return data['form'] return data['form']
@ -209,9 +270,12 @@ class wizard_report(osv.osv_memory):
res = cr.dictfetchall() res = cr.dictfetchall()
if res: if res:
if (data['form']['date_to'] > res[0]['date_stop'] or data['form']['date_from'] < res[0]['date_start']):
raise osv.except_osv(_('UserError'), 'Las fechas deben estar entre %s y %s' % (
res[0]['date_start'], res[0]['date_stop']))
if (data['form']['date_to'] > res[0]['date_stop']
or data['form']['date_from'] < res[0]['date_start']):
raise osv.except_osv(_('UserError'),
'Las fechas deben estar entre %s y %s'
% (res[0]['date_start'],
res[0]['date_stop']))
else: else:
return 'report' return 'report'
else: else:
@ -223,14 +287,20 @@ class wizard_report(osv.osv_memory):
ap_obj = self.pool.get('account.period') ap_obj = self.pool.get('account.period')
fy_id = fy_id and type(fy_id) in (list, tuple) and fy_id[0] or fy_id fy_id = fy_id and type(fy_id) in (list, tuple) and fy_id[0] or fy_id
if not ids: if not ids:
#~ No hay periodos
return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id), ('special', '=', False)], order='date_start asc')
# ~ No hay periodos
return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id),
('special', '=', False)],
order='date_start asc')
ap_brws = ap_obj.browse(cr, uid, ids, context=context) ap_brws = ap_obj.browse(cr, uid, ids, context=context)
date_start = min([period.date_start for period in ap_brws]) date_start = min([period.date_start for period in ap_brws])
date_stop = max([period.date_stop for period in ap_brws]) date_stop = max([period.date_stop for period in ap_brws])
return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id), ('special', '=', False), ('date_start', '>=', date_start), ('date_stop', '<=', date_stop)], order='date_start asc')
return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id),
('special', '=', False),
('date_start', '>=', date_start),
('date_stop', '<=', date_stop)],
order='date_start asc')
def print_report(self, cr, uid, ids, data, context=None): def print_report(self, cr, uid, ids, data, context=None):
if context is None: if context is None:
@ -245,8 +315,10 @@ class wizard_report(osv.osv_memory):
del data['form']['date_from'] del data['form']['date_from']
del data['form']['date_to'] del data['form']['date_to']
data['form']['periods'] = self.period_span(cr, uid, data[
'form']['periods'], data['form']['fiscalyear'])
data['form']['periods'] = self.period_span(
cr, uid,
data['form']['periods'],
data['form']['fiscalyear'])
elif data['form']['filter'] == 'bydate': elif data['form']['filter'] == 'bydate':
self._check_date(cr, uid, data) self._check_date(cr, uid, data)
@ -259,13 +331,15 @@ class wizard_report(osv.osv_memory):
self._check_date(cr, uid, data) self._check_date(cr, uid, data)
lis2 = str(data['form']['periods']).replace( lis2 = str(data['form']['periods']).replace(
"[", "(").replace("]", ")") "[", "(").replace("]", ")")
sqlmm = """select min(p.date_start) as inicio, max(p.date_stop) as fin
from account_period p
where p.id in %s""" % lis2
sqlmm = """select min(p.date_start) as inicio,
max(p.date_stop) as fin
from account_period p
where p.id in %s""" % lis2
cr.execute(sqlmm) cr.execute(sqlmm)
minmax = cr.dictfetchall() minmax = cr.dictfetchall()
if minmax: if minmax:
if (data['form']['date_to'] < minmax[0]['inicio']) or (data['form']['date_from'] > minmax[0]['fin']):
if (data['form']['date_to'] < minmax[0]['inicio']) \
or (data['form']['date_from'] > minmax[0]['fin']):
raise osv.except_osv(_('Error !'), _( raise osv.except_osv(_('Error !'), _(
'La interseccion entre el periodo y fecha es vacio')) 'La interseccion entre el periodo y fecha es vacio'))
@ -274,11 +348,14 @@ class wizard_report(osv.osv_memory):
if data['form']['columns'] == 'two': if data['form']['columns'] == 'two':
name = 'afr.2cols' name = 'afr.2cols'
if data['form']['columns'] == 'four': if data['form']['columns'] == 'four':
if data['form']['analytic_ledger'] and data['form']['inf_type'] == 'BS':
if data['form']['analytic_ledger'] \
and data['form']['inf_type'] == 'BS':
name = 'afr.analytic.ledger' name = 'afr.analytic.ledger'
elif data['form']['journal_ledger'] and data['form']['inf_type'] == 'BS':
elif data['form']['journal_ledger'] \
and data['form']['inf_type'] == 'BS':
name = 'afr.journal.ledger' name = 'afr.journal.ledger'
elif data['form']['partner_balance'] and data['form']['inf_type'] == 'BS':
elif data['form']['partner_balance'] \
and data['form']['inf_type'] == 'BS':
name = 'afr.partner.balance' name = 'afr.partner.balance'
else: else:
name = 'afr.4cols' name = 'afr.4cols'
@ -289,6 +366,8 @@ class wizard_report(osv.osv_memory):
if data['form']['columns'] == 'thirteen': if data['form']['columns'] == 'thirteen':
name = 'afr.13cols' name = 'afr.13cols'
return {'type': 'ir.actions.report.xml', 'report_name': name, 'datas': data}
return {'type': 'ir.actions.report.xml',
'report_name': name,
'datas': data}
wizard_report() wizard_report()

4
account_financial_report_horizontal/__init__.py

@ -1,2 +1,2 @@
import report
import wizard
from . import report
from . import wizard

6
account_financial_report_horizontal/report/__init__.py

@ -1,3 +1,3 @@
#import account_balance
import account_balance_sheet
import account_profit_loss
# import account_balance
from . import account_balance_sheet
from . import account_profit_loss

34
account_financial_report_horizontal/report/account_balance_sheet.py

@ -24,18 +24,18 @@
import time import time
import pooler
from report import report_sxw
from openerp.report import report_sxw
from openerp.addons.account_financial_report_horizontal.report import ( from openerp.addons.account_financial_report_horizontal.report import (
account_profit_loss account_profit_loss
) )
from common_report_header import common_report_header from common_report_header import common_report_header
from tools.translate import _
from openerp.tools.translate import _
class report_balancesheet_horizontal( class report_balancesheet_horizontal(
report_sxw.rml_parse, common_report_header report_sxw.rml_parse, common_report_header
): ):
def __init__(self, cr, uid, name, context=None): def __init__(self, cr, uid, name, context=None):
super(report_balancesheet_horizontal, self).__init__( super(report_balancesheet_horizontal, self).__init__(
cr, uid, name, context=context) cr, uid, name, context=context)
@ -69,11 +69,9 @@ class report_balancesheet_horizontal(
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
new_ids = ids new_ids = ids
if (data['model'] == 'ir.ui.menu'): if (data['model'] == 'ir.ui.menu'):
new_ids = 'chart_account_id' in data['form'] and data[
'form'
]['chart_account_id'] and [data[
'form'
]['chart_account_id'][0]] or []
new_ids = 'chart_account_id' in data['form'] \
and data['form']['chart_account_id'] \
and [data['form']['chart_account_id'][0]] or []
objects = self.pool.get('account.account').browse( objects = self.pool.get('account.account').browse(
self.cr, self.uid, new_ids) self.cr, self.uid, new_ids)
lang_dict = self.pool.get('res.users').read( lang_dict = self.pool.get('res.users').read(
@ -81,7 +79,7 @@ class report_balancesheet_horizontal(
data['lang'] = lang_dict.get('context_lang') or False data['lang'] = lang_dict.get('context_lang') or False
return super( return super(
report_balancesheet_horizontal, self report_balancesheet_horizontal, self
).set_context(objects, data, new_ids, report_type=report_type)
).set_context(objects, data, new_ids, report_type=report_type)
def sum_dr(self): def sum_dr(self):
if self.res_bl['type'] == _('Net Profit'): if self.res_bl['type'] == _('Net Profit'):
@ -98,14 +96,13 @@ class report_balancesheet_horizontal(
def get_data(self, data): def get_data(self, data):
cr, uid = self.cr, self.uid cr, uid = self.cr, self.uid
db_pool = pooler.get_pool(self.cr.dbname)
#Getting Profit or Loss Balance from profit and Loss report
# Getting Profit or Loss Balance from profit and Loss report
self.obj_pl.get_data(data) self.obj_pl.get_data(data)
self.res_bl = self.obj_pl.final_result() self.res_bl = self.obj_pl.final_result()
account_pool = db_pool.get('account.account')
currency_pool = db_pool.get('res.currency')
account_pool = self.pool['account.account']
currency_pool = self.pool['res.currency']
types = [ types = [
'liability', 'liability',
@ -124,7 +121,6 @@ class report_balancesheet_horizontal(
ctx['date_to'] = data['form'].get('date_to', False) ctx['date_to'] = data['form'].get('date_to', False)
ctx['state'] = data['form'].get('target_move', 'all') ctx['state'] = data['form'].get('target_move', 'all')
cal_list = {} cal_list = {}
pl_dict = {}
account_dict = {} account_dict = {}
account_id = data['form'].get('chart_account_id', False) account_id = data['form'].get('chart_account_id', False)
if account_id: if account_id:
@ -161,13 +157,13 @@ class report_balancesheet_horizontal(
'level': account.level, 'level': account.level,
'balance': ( 'balance': (
account.balance and typ == 'liability' and -1 or 1 account.balance and typ == 'liability' and -1 or 1
) * account.balance,
) * account.balance,
'type': account.type, 'type': account.type,
} }
currency = ( currency = (
account.currency_id and account.currency_id account.currency_id and account.currency_id
or account.company_id.currency_id or account.company_id.currency_id
)
)
if typ == 'liability' and account.type != 'view' and ( if typ == 'liability' and account.type != 'view' and (
account.debit != account.credit account.debit != account.credit
): ):
@ -184,7 +180,7 @@ class report_balancesheet_horizontal(
not currency_pool.is_zero( not currency_pool.is_zero(
self.cr, self.uid, currency, account.debit self.cr, self.uid, currency, account.debit
) )
) or (
) or (
not currency_pool.is_zero( not currency_pool.is_zero(
self.cr, self.uid, currency, self.cr, self.uid, currency,
account.balance account.balance
@ -226,7 +222,7 @@ class report_balancesheet_horizontal(
'level1': cal_list['asset'][i]['level'], 'level1': cal_list['asset'][i]['level'],
'balance1': cal_list['asset'][i]['balance'], 'balance1': cal_list['asset'][i]['balance'],
'type1': cal_list['asset'][i]['type'], 'type1': cal_list['asset'][i]['type'],
}
}
self.result_temp.append(temp) self.result_temp.append(temp)
else: else:
if i < len(cal_list['asset']): if i < len(cal_list['asset']):
@ -278,5 +274,3 @@ report_sxw.report_sxw(
'account_balance_sheet.rml', 'account_balance_sheet.rml',
parser=report_balancesheet_horizontal, parser=report_balancesheet_horizontal,
header='internal') header='internal')
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

20
account_financial_report_horizontal/report/account_profit_loss.py

@ -22,10 +22,9 @@
############################################################################## ##############################################################################
import time import time
import pooler
from report import report_sxw
from openerp.report import report_sxw
from common_report_header import common_report_header from common_report_header import common_report_header
from tools.translate import _
from openerp.tools.translate import _
class report_pl_account_horizontal(report_sxw.rml_parse, common_report_header): class report_pl_account_horizontal(report_sxw.rml_parse, common_report_header):
@ -63,8 +62,8 @@ class report_pl_account_horizontal(report_sxw.rml_parse, common_report_header):
new_ids = ids new_ids = ids
if (data['model'] == 'ir.ui.menu'): if (data['model'] == 'ir.ui.menu'):
new_ids = 'chart_account_id' in data['form'] and data['form'][ new_ids = 'chart_account_id' in data['form'] and data['form'][
'chart_account_id'] and [data['form'][
'chart_account_id'][0]] or []
'chart_account_id'] and [data['form']['chart_account_id'][0]] \
or []
objects = self.pool.get('account.account').browse( objects = self.pool.get('account.account').browse(
self.cr, self.uid, new_ids) self.cr, self.uid, new_ids)
lang_dict = self.pool.get('res.users').read( lang_dict = self.pool.get('res.users').read(
@ -98,18 +97,17 @@ class report_pl_account_horizontal(report_sxw.rml_parse, common_report_header):
'balance': account.balance and ( 'balance': account.balance and (
account_type == 'income' and -1 or 1) * account.balance, account_type == 'income' and -1 or 1) * account.balance,
'type': account.type, 'type': account.type,
}
}
cr, uid = self.cr, self.uid cr, uid = self.cr, self.uid
db_pool = pooler.get_pool(self.cr.dbname)
account_pool = db_pool.get('account.account')
currency_pool = db_pool.get('res.currency')
account_pool = self.pool['account.account']
currency_pool = self.pool['res.currency']
types = [ types = [
'expense', 'expense',
'income' 'income'
]
]
ctx = self.context.copy() ctx = self.context.copy()
ctx['fiscalyear'] = data['form'].get('fiscalyear_id', False) ctx['fiscalyear'] = data['form'].get('fiscalyear_id', False)
@ -247,5 +245,3 @@ report_sxw.report_sxw(
'addons/account_financial_report_horizontal/report/' 'addons/account_financial_report_horizontal/report/'
'account_profit_loss.rml', 'account_profit_loss.rml',
parser=report_pl_account_horizontal, header='internal') parser=report_pl_account_horizontal, header='internal')
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

27
account_financial_report_horizontal/report/common_report_header.py

@ -19,8 +19,7 @@
# #
############################################################################## ##############################################################################
import pooler
from tools.translate import _
from openerp.tools.translate import _
class common_report_header(object): class common_report_header(object):
@ -44,25 +43,25 @@ class common_report_header(object):
def get_start_period(self, data): def get_start_period(self, data):
if data.get('form', False) and data['form'].get('period_from', False): if data.get('form', False) and data['form'].get('period_from', False):
return pooler.get_pool(self.cr.dbname).get(
'account.period').browse(self.cr, self.uid, data[
'form']['period_from'][0]).name
return self.pool['account.period'].browse(
self.cr, self.uid,
data['form']['period_from'][0]).name
return '' return ''
def get_end_period(self, data): def get_end_period(self, data):
if data.get('form', False) and data['form'].get('period_to', False): if data.get('form', False) and data['form'].get('period_to', False):
return pooler.get_pool(self.cr.dbname).get(
'account.period').browse(self.cr, self.uid, data[
'form']['period_to'][0]).name
return self.pool['account.period'].browse(
self.cr, self.uid,
data['form']['period_to'][0]).name
return '' return ''
def _get_account(self, data): def _get_account(self, data):
if data.get('form', False) and data['form'].get( if data.get('form', False) and data['form'].get(
'chart_account_id', False 'chart_account_id', False
): ):
return pooler.get_pool(self.cr.dbname).get(
'account.account').browse(self.cr, self.uid, data[
'form']['chart_account_id'][0]).name
return self.pool['account.account'].browse(
self.cr, self.uid,
data['form']['chart_account_id'][0]).name
return '' return ''
def _get_sortby(self, data): def _get_sortby(self, data):
@ -80,7 +79,7 @@ class common_report_header(object):
if data.get('form', False) and data['form'].get( if data.get('form', False) and data['form'].get(
'fiscalyear_id', False 'fiscalyear_id', False
): ):
return pooler.get_pool(self.cr.dbname).get(
'account.fiscalyear').browse(self.cr, self.uid, data[
'form']['fiscalyear_id'][0]).name
return self.pool['account.fiscalyear'].browse(
self.cr, self.uid,
data['form']['fiscalyear_id'][0]).name
return '' return ''

8
account_financial_report_horizontal/wizard/__init__.py

@ -1,4 +1,4 @@
import account_report_common
import account_report_common_account
import account_report_balance_sheet
import account_report_profit_loss
from . import account_report_common
from . import account_report_common_account
from . import account_report_balance_sheet
from . import account_report_profit_loss

2
account_financial_report_horizontal/wizard/account_report_balance_sheet.py

@ -21,7 +21,7 @@
# #
############################################################################## ##############################################################################
from osv import orm, fields
from openerp.osv import orm, fields
class account_bs_report(orm.TransientModel): class account_bs_report(orm.TransientModel):

4
account_financial_report_horizontal/wizard/account_report_common.py

@ -24,8 +24,8 @@
import time import time
from lxml import etree from lxml import etree
from osv import fields, orm
from tools.translate import _
from openerp.osv import fields, orm
from openerp.tools.translate import _
class account_common_report(orm.TransientModel): class account_common_report(orm.TransientModel):

2
account_financial_report_horizontal/wizard/account_report_common_account.py

@ -21,7 +21,7 @@
# #
############################################################################## ##############################################################################
from osv import orm, fields
from openerp.osv import orm, fields
class account_common_account_report(orm.TransientModel): class account_common_account_report(orm.TransientModel):

2
account_financial_report_horizontal/wizard/account_report_profit_loss.py

@ -21,7 +21,7 @@
# #
############################################################################## ##############################################################################
from osv import orm, fields
from openerp.osv import orm, fields
class account_pl_report(orm.TransientModel): class account_pl_report(orm.TransientModel):

4
account_financial_report_webkit/__init__.py

@ -17,7 +17,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
############################################################################## ##############################################################################
import account
from . import account
from . import wizard from . import wizard
from . import report from . import report
from . import account_move_line
from . import account_move_line

49
account_financial_report_webkit/__openerp__.py

@ -35,7 +35,8 @@ This module adds or replaces the following standard OpenERP financial reports:
Main improvements per report: Main improvements per report:
----------------------------- -----------------------------
The General ledger: details of all entries posted in your books sorted by account.
The General ledger: details of all entries posted in your books sorted by
account.
* Filter by account is available in the wizard (no need to go to the * Filter by account is available in the wizard (no need to go to the
Chart of Accounts to do this anymore) or by View account (the report Chart of Accounts to do this anymore) or by View account (the report
@ -114,7 +115,8 @@ like the trial balance but add an extra information :
Overdue data are also split by period. Overdue data are also split by period.
* For each partner following columns will be displayed: * For each partner following columns will be displayed:
* Total balance (all figures must match with same date partner balance report).
* Total balance (all figures must match with same date partner balance
report).
This column equals the sum of all following columns) This column equals the sum of all following columns)
* Due * Due
@ -126,11 +128,11 @@ like the trial balance but add an extra information :
Hypothesis / Contraints of aged partner balance Hypothesis / Contraints of aged partner balance
* Overdues columns will be by default be based on 30 days range fix number of days.
This can be changed by changes the RANGES constraint
* Overdues columns will be by default be based on 30 days range fix number of
days. This can be changed by changes the RANGES constraint
* All data will be displayed in company currency * All data will be displayed in company currency
* When partial payments, the payment must appear in the same colums than the invoice
(Except if multiple payment terms)
* When partial payments, the payment must appear in the same colums than the
invoice (Except if multiple payment terms)
* Data granularity: partner (will not display figures at invoices level) * Data granularity: partner (will not display figures at invoices level)
* The report aggregate data per account with sub-totals * The report aggregate data per account with sub-totals
* Initial balance must be calculated the same way that * Initial balance must be calculated the same way that
@ -173,25 +175,24 @@ wkhtmltopdf. The texts are defined inside the report classes.
'category': 'Finance', 'category': 'Finance',
'website': 'http://www.camptocamp.com', 'website': 'http://www.camptocamp.com',
'images': [ 'images': [
'images/ledger.png',],
'images/ledger.png', ],
'depends': ['account', 'depends': ['account',
'report_webkit'], 'report_webkit'],
'init_xml': [],
'demo_xml' : [],
'update_xml': ['account_view.xml',
'data/financial_webkit_header.xml',
'report/report.xml',
'wizard/wizard.xml',
'wizard/balance_common_view.xml',
'wizard/general_ledger_wizard_view.xml',
'wizard/partners_ledger_wizard_view.xml',
'wizard/trial_balance_wizard_view.xml',
'wizard/partner_balance_wizard_view.xml',
'wizard/open_invoices_wizard_view.xml',
'wizard/aged_partner_balance_wizard.xml',
'wizard/print_journal_view.xml',
'report_menus.xml',
],
'demo': [],
'data': ['account_view.xml',
'data/financial_webkit_header.xml',
'report/report.xml',
'wizard/wizard.xml',
'wizard/balance_common_view.xml',
'wizard/general_ledger_wizard_view.xml',
'wizard/partners_ledger_wizard_view.xml',
'wizard/trial_balance_wizard_view.xml',
'wizard/partner_balance_wizard_view.xml',
'wizard/open_invoices_wizard_view.xml',
'wizard/aged_partner_balance_wizard.xml',
'wizard/print_journal_view.xml',
'report_menus.xml',
],
# tests order matter # tests order matter
'test': ['tests/general_ledger.yml', 'test': ['tests/general_ledger.yml',
'tests/partner_ledger.yml', 'tests/partner_ledger.yml',
@ -199,7 +200,7 @@ wkhtmltopdf. The texts are defined inside the report classes.
'tests/partner_balance.yml', 'tests/partner_balance.yml',
'tests/open_invoices.yml', 'tests/open_invoices.yml',
'tests/aged_trial_balance.yml'], 'tests/aged_trial_balance.yml'],
#'tests/account_move_line.yml'
# 'tests/account_move_line.yml'
'active': False, 'active': False,
'installable': True, 'installable': True,
'application': True, 'application': True,

45
account_financial_report_webkit/account_move_line.py

@ -20,16 +20,18 @@
############################################################################## ##############################################################################
from openerp.osv import fields, orm from openerp.osv import fields, orm
from openerp.tools.translate import _
class AccountMoveLine(orm.Model): class AccountMoveLine(orm.Model):
"""Overriding Account move line in order to add last_rec_date. """Overriding Account move line in order to add last_rec_date.
Last rec date is the date of the last reconciliation (full or partial) account move line"""
Last rec date is the date of the last reconciliation (full or partial)
account move line"""
_inherit = 'account.move.line' _inherit = 'account.move.line'
def init(self, cr): def init(self, cr):
##We do not want to catch error as if sql is not run it will give invalid data
# We do not want to catch error as if sql is not run it will give
# invalid data
cr.execute("UPDATE account_move_line as acm " cr.execute("UPDATE account_move_line as acm "
" SET last_rec_date =" " SET last_rec_date ="
" (SELECT date from account_move_line" " (SELECT date from account_move_line"
@ -41,14 +43,16 @@ class AccountMoveLine(orm.Model):
cr.execute("UPDATE account_move_line as acm " cr.execute("UPDATE account_move_line as acm "
" SET last_rec_date =" " SET last_rec_date ="
" (SELECT date from account_move_line" " (SELECT date from account_move_line"
" WHERE reconcile_partial_id = acm.reconcile_partial_id"
" WHERE reconcile_partial_id"
" = acm.reconcile_partial_id"
" AND reconcile_partial_id IS NOT NULL" " AND reconcile_partial_id IS NOT NULL"
" ORDER BY date DESC LIMIT 1)" " ORDER BY date DESC LIMIT 1)"
" WHERE last_rec_date is null;") " WHERE last_rec_date is null;")
def _get_move_line_from_line_rec(self, cr, uid, ids, context=None): def _get_move_line_from_line_rec(self, cr, uid, ids, context=None):
moves = [] moves = []
for reconcile in self.pool.get('account.move.reconcile').browse(cr, uid, ids, context=context):
for reconcile in self.pool['account.move.reconcile'].browse(
cr, uid, ids, context=context):
for move_line in reconcile.line_partial_ids: for move_line in reconcile.line_partial_ids:
moves.append(move_line.id) moves.append(move_line.id)
for move_line in reconcile.line_id: for move_line in reconcile.line_id:
@ -64,22 +68,27 @@ class AccountMoveLine(orm.Model):
rec = line.reconcile_id or line.reconcile_partial_id or False rec = line.reconcile_id or line.reconcile_partial_id or False
if rec: if rec:
# we use cursor in order to gain some perfs # we use cursor in order to gain some perfs
cursor.execute('SELECT date from account_move_line where'
' reconcile_id = %s OR reconcile_partial_id = %s'
' ORDER BY date DESC LIMIT 1 ',
(rec.id, rec.id))
cursor.execute('SELECT date from account_move_line'
' WHERE reconcile_id = %s'
' OR reconcile_partial_id = %s'
' ORDER BY date DESC LIMIT 1 ',
(rec.id, rec.id))
res_set = cursor.fetchone() res_set = cursor.fetchone()
if res_set: if res_set:
res[line.id] = {'last_rec_date': res_set[0]} res[line.id] = {'last_rec_date': res_set[0]}
return res return res
_columns = { _columns = {
'last_rec_date': fields.function(_get_last_rec_date,
method=True,
string='Last reconciliation date',
store={'account.move.line': (lambda self, cr, uid, ids, c={}: ids, ['date'], 20),
'account.move.reconcile': (_get_move_line_from_line_rec, None, 20)},
type='date',
multi='all',
help="the date of the last reconciliation (full or partial) account move line"),
}
'last_rec_date': fields.function(
_get_last_rec_date,
method=True,
string='Last reconciliation date',
store={'account.move.line': (lambda self, cr, uid, ids, c={}: ids,
['date'], 20),
'account.move.reconcile': (_get_move_line_from_line_rec,
None, 20)},
type='date',
multi='all',
help="the date of the last reconciliation (full or partial) \
account move line"),
}

37
account_financial_report_webkit/report/aged_partner_balance.py

@ -35,14 +35,15 @@ def make_ranges(top, offset):
:param offset: offset for ranges :param offset: offset for ranges
:returns: list of sorted ranges tuples in days :returns: list of sorted ranges tuples in days
eg. [(-100000, 0), (0, offset), (offset, n*offset), ... (top, 100000)]
eg. [(-100000, 0), (0, offset),
(offset, n*offset), ... (top, 100000)]
""" """
ranges = [(n, min(n + offset, top)) for n in xrange(0, top, offset)] ranges = [(n, min(n + offset, top)) for n in xrange(0, top, offset)]
ranges.insert(0, (-100000000000, 0)) ranges.insert(0, (-100000000000, 0))
ranges.append((top, 100000000000)) ranges.append((top, 100000000000))
return ranges return ranges
#list of overdue ranges
# list of overdue ranges
RANGES = make_ranges(120, 30) RANGES = make_ranges(120, 30)
@ -53,20 +54,22 @@ def make_ranges_titles():
titles.append(_('Older')) titles.append(_('Older'))
return titles return titles
#list of overdue ranges title
# list of overdue ranges title
RANGES_TITLES = make_ranges_titles() RANGES_TITLES = make_ranges_titles()
#list of payable journal types
# list of payable journal types
REC_PAY_TYPE = ('purchase', 'sale') REC_PAY_TYPE = ('purchase', 'sale')
#list of refund payable type
# list of refund payable type
REFUND_TYPE = ('purchase_refund', 'sale_refund') REFUND_TYPE = ('purchase_refund', 'sale_refund')
INV_TYPE = REC_PAY_TYPE + REFUND_TYPE INV_TYPE = REC_PAY_TYPE + REFUND_TYPE
class AccountAgedTrialBalanceWebkit(PartnersOpenInvoicesWebkit): class AccountAgedTrialBalanceWebkit(PartnersOpenInvoicesWebkit):
"""Compute Aged Partner Balance based on result of Open Invoices""" """Compute Aged Partner Balance based on result of Open Invoices"""
def __init__(self, cursor, uid, name, context=None): def __init__(self, cursor, uid, name, context=None):
"""Constructor, refer to :class:`openerp.report.report_sxw.rml_parse`"""
"""Constructor,
refer to :class:`openerp.report.report_sxw.rml_parse`"""
super(AccountAgedTrialBalanceWebkit, self).__init__(cursor, uid, name, super(AccountAgedTrialBalanceWebkit, self).__init__(cursor, uid, name,
context=context) context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
@ -95,7 +98,8 @@ class AccountAgedTrialBalanceWebkit(PartnersOpenInvoicesWebkit):
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right',
' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
@ -141,9 +145,10 @@ class AccountAgedTrialBalanceWebkit(PartnersOpenInvoicesWebkit):
data) data)
if aged_lines: if aged_lines:
acc.aged_lines[part_id] = aged_lines acc.aged_lines[part_id] = aged_lines
acc.aged_totals = totals = self.compute_totals(acc.aged_lines.values())
acc.aged_totals = totals = self.compute_totals(
acc.aged_lines.values())
acc.aged_percents = self.compute_percents(totals) acc.aged_percents = self.compute_percents(totals)
#Free some memory
# Free some memory
del(acc.ledger_lines) del(acc.ledger_lines)
return res return res
@ -265,17 +270,18 @@ class AccountAgedTrialBalanceWebkit(PartnersOpenInvoicesWebkit):
:returns: delta in days :returns: delta in days
""" """
sale_lines = [x for x in ledger_lines if x['jtype'] in REC_PAY_TYPE and
line['rec_id'] == x['rec_id']]
refund_lines = [x for x in ledger_lines if x['jtype'] in REFUND_TYPE and
line['rec_id'] == x['rec_id']]
sale_lines = [x for x in ledger_lines if x['jtype'] in REC_PAY_TYPE
and line['rec_id'] == x['rec_id']]
refund_lines = [x for x in ledger_lines if x['jtype'] in REFUND_TYPE
and line['rec_id'] == x['rec_id']]
if len(sale_lines) == 1: if len(sale_lines) == 1:
reference_line = sale_lines[0] reference_line = sale_lines[0]
elif len(refund_lines) == 1: elif len(refund_lines) == 1:
reference_line = refund_lines[0] reference_line = refund_lines[0]
else: else:
reference_line = line reference_line = line
key = 'date_maturity' if reference_line.get('date_maturity') else 'ldate'
key = 'date_maturity' if reference_line.get(
'date_maturity') else 'ldate'
return self._compute_delay_from_key(key, return self._compute_delay_from_key(key,
reference_line, reference_line,
end_date) end_date)
@ -398,6 +404,7 @@ class AccountAgedTrialBalanceWebkit(PartnersOpenInvoicesWebkit):
HeaderFooterTextWebKitParser( HeaderFooterTextWebKitParser(
'report.account.account_aged_trial_balance_webkit', 'report.account.account_aged_trial_balance_webkit',
'account.account', 'account.account',
'addons/account_financial_report_webkit/report/templates/aged_trial_webkit.mako',
'addons/account_financial_report_webkit/report/templates/\
aged_trial_webkit.mako',
parser=AccountAgedTrialBalanceWebkit, parser=AccountAgedTrialBalanceWebkit,
) )

170
account_financial_report_webkit/report/common_balance_reports.py

@ -26,7 +26,9 @@ from .common_reports import CommonReportHeaderWebkit
class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit): class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
"""Define common helper for balance (trial balance, P&L, BS oriented financial report"""
"""Define common helper for balance (trial balance, P&L, BS oriented
financial report"""
def _get_numbers_display(self, data): def _get_numbers_display(self, data):
return self._get_form_param('numbers_display', data) return self._get_form_param('numbers_display', data)
@ -35,7 +37,9 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
def find_key_by_value_in_list(dic, value): def find_key_by_value_in_list(dic, value):
return [key for key, val in dic.iteritems() if value in val][0] return [key for key, val in dic.iteritems() if value in val][0]
def _get_account_details(self, account_ids, target_move, fiscalyear, main_filter, start, stop, initial_balance_mode, context=None):
def _get_account_details(self, account_ids, target_move, fiscalyear,
main_filter, start, stop, initial_balance_mode,
context=None):
""" """
Get details of accounts to display on the report Get details of accounts to display on the report
@param account_ids: ids of accounts to get details @param account_ids: ids of accounts to get details
@ -44,21 +48,26 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
@param main_filter: selection filter period / date or none @param main_filter: selection filter period / date or none
@param start: start date or start period browse instance @param start: start date or start period browse instance
@param stop: stop date or stop period browse instance @param stop: stop date or stop period browse instance
@param initial_balance_mode: False: no calculation, 'opening_balance': from the opening period, 'initial_balance': computed from previous year / periods
@return: dict of list containing accounts details, keys are the account ids
@param initial_balance_mode: False: no calculation,
'opening_balance': from the opening period,
'initial_balance': computed from previous year / periods
@return: dict of list containing accounts details, keys are
the account ids
""" """
if context is None: if context is None:
context = {} context = {}
account_obj = self.pool.get('account.account') account_obj = self.pool.get('account.account')
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
use_period_ids = main_filter in ('filter_no', 'filter_period', 'filter_opening')
use_period_ids = main_filter in (
'filter_no', 'filter_period', 'filter_opening')
if use_period_ids: if use_period_ids:
if main_filter == 'filter_opening': if main_filter == 'filter_opening':
period_ids = [start.id] period_ids = [start.id]
else: else:
period_ids = period_obj.build_ctx_periods(self.cursor, self.uid, start.id, stop.id)
period_ids = period_obj.build_ctx_periods(
self.cursor, self.uid, start.id, stop.id)
# never include the opening in the debit / credit amounts # never include the opening in the debit / credit amounts
period_ids = self.exclude_opening_periods(period_ids) period_ids = self.exclude_opening_periods(period_ids)
@ -66,7 +75,8 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
if initial_balance_mode == 'opening_balance': if initial_balance_mode == 'opening_balance':
init_balance = self._read_opening_balance(account_ids, start) init_balance = self._read_opening_balance(account_ids, start)
elif initial_balance_mode: elif initial_balance_mode:
init_balance = self._compute_initial_balances(account_ids, start, fiscalyear)
init_balance = self._compute_initial_balances(
account_ids, start, fiscalyear)
ctx = context.copy() ctx = context.copy()
ctx.update({'state': target_move, ctx.update({'state': target_move,
@ -79,42 +89,52 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
'date_to': stop}) 'date_to': stop})
accounts = account_obj.read( accounts = account_obj.read(
self.cursor,
self.uid,
account_ids,
['type', 'code', 'name', 'debit', 'credit', 'balance', 'parent_id', 'level', 'child_id'],
ctx)
self.cursor,
self.uid,
account_ids,
['type', 'code', 'name', 'debit', 'credit',
'balance', 'parent_id', 'level', 'child_id'],
ctx)
accounts_by_id = {} accounts_by_id = {}
for account in accounts: for account in accounts:
if init_balance: if init_balance:
# sum for top level views accounts # sum for top level views accounts
child_ids = account_obj._get_children_and_consol(self.cursor, self.uid, account['id'], ctx)
child_ids = account_obj._get_children_and_consol(
self.cursor, self.uid, account['id'], ctx)
if child_ids: if child_ids:
child_init_balances = [ child_init_balances = [
init_bal['init_balance']
for acnt_id, init_bal in init_balance.iteritems()
if acnt_id in child_ids]
init_bal['init_balance']
for acnt_id, init_bal in init_balance.iteritems()
if acnt_id in child_ids]
top_init_balance = reduce(add, child_init_balances) top_init_balance = reduce(add, child_init_balances)
account['init_balance'] = top_init_balance account['init_balance'] = top_init_balance
else: else:
account.update(init_balance[account['id']]) account.update(init_balance[account['id']])
account['balance'] = account['init_balance'] + account['debit'] - account['credit']
account['balance'] = account['init_balance'] + \
account['debit'] - account['credit']
accounts_by_id[account['id']] = account accounts_by_id[account['id']] = account
return accounts_by_id return accounts_by_id
def _get_comparison_details(self, data, account_ids, target_move, comparison_filter, index):
def _get_comparison_details(self, data, account_ids, target_move,
comparison_filter, index):
""" """
@param data: data of the wizard form @param data: data of the wizard form
@param account_ids: ids of the accounts to get details @param account_ids: ids of the accounts to get details
@param comparison_filter: selected filter on the form for the comparison (filter_no, filter_year, filter_period, filter_date)
@param index: index of the fields to get (ie. comp1_fiscalyear_id where 1 is the index)
@param comparison_filter: selected filter on the form for
the comparison (filter_no, filter_year, filter_period,
filter_date)
@param index: index of the fields to get
(ie. comp1_fiscalyear_id where 1 is the index)
@return: dict of account details (key = account id) @return: dict of account details (key = account id)
""" """
fiscalyear = self._get_info(data, "comp%s_fiscalyear_id" % (index,), 'account.fiscalyear')
start_period = self._get_info(data, "comp%s_period_from" % (index,), 'account.period')
stop_period = self._get_info(data, "comp%s_period_to" % (index,), 'account.period')
fiscalyear = self._get_info(
data, "comp%s_fiscalyear_id" % (index,), 'account.fiscalyear')
start_period = self._get_info(
data, "comp%s_period_from" % (index,), 'account.period')
stop_period = self._get_info(
data, "comp%s_period_to" % (index,), 'account.period')
start_date = self._get_form_param("comp%s_date_from" % (index,), data) start_date = self._get_form_param("comp%s_date_from" % (index,), data)
stop_date = self._get_form_param("comp%s_date_to" % (index,), data) stop_date = self._get_form_param("comp%s_date_to" % (index,), data)
init_balance = self.is_initial_balance_enabled(comparison_filter) init_balance = self.is_initial_balance_enabled(comparison_filter)
@ -124,13 +144,17 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
details_filter = comparison_filter details_filter = comparison_filter
if comparison_filter != 'filter_no': if comparison_filter != 'filter_no':
start_period, stop_period, start, stop = \ start_period, stop_period, start, stop = \
self._get_start_stop_for_filter(comparison_filter, fiscalyear, start_date, stop_date, start_period, stop_period)
self._get_start_stop_for_filter(
comparison_filter, fiscalyear, start_date, stop_date,
start_period, stop_period)
if comparison_filter == 'filter_year': if comparison_filter == 'filter_year':
details_filter = 'filter_no' details_filter = 'filter_no'
initial_balance_mode = init_balance and self._get_initial_balance_mode(start) or False
accounts_by_ids = self._get_account_details(account_ids, target_move, fiscalyear, details_filter,
start, stop, initial_balance_mode)
initial_balance_mode = init_balance \
and self._get_initial_balance_mode(start) or False
accounts_by_ids = self._get_account_details(
account_ids, target_move, fiscalyear, details_filter,
start, stop, initial_balance_mode)
comp_params = { comp_params = {
'comparison_filter': comparison_filter, 'comparison_filter': comparison_filter,
'fiscalyear': fiscalyear, 'fiscalyear': fiscalyear,
@ -146,14 +170,16 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
""" """
@param balance: current balance @param balance: current balance
@param previous_balance: last balance @param previous_balance: last balance
@return: dict of form {'diff': difference, 'percent_diff': diff in percentage}
@return: dict of form {'diff': difference,
'percent_diff': diff in percentage}
""" """
diff = balance - previous_balance diff = balance - previous_balance
obj_precision = self.pool.get('decimal.precision') obj_precision = self.pool.get('decimal.precision')
precision = obj_precision.precision_get(self.cursor, self.uid, 'Account')
# round previous balance with account precision to avoid big numbers if previous
# balance is 0.0000001 or a any very small number
precision = obj_precision.precision_get(
self.cursor, self.uid, 'Account')
# round previous balance with account precision to avoid big numbers
# if previous balance is 0.0000001 or a any very small number
if round(previous_balance, precision) == 0: if round(previous_balance, precision) == 0:
percent_diff = False percent_diff = False
else: else:
@ -165,13 +191,18 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
""" """
@param data: data of the report @param data: data of the report
@param comparison_number: number of comparisons @param comparison_number: number of comparisons
@return: list of comparison filters, nb of comparisons used and comparison mode (no_comparison, single, multiple)
@return: list of comparison filters, nb of comparisons used and
comparison mode (no_comparison, single, multiple)
""" """
comp_filters = [] comp_filters = []
for index in range(comparison_number): for index in range(comparison_number):
comp_filters.append(self._get_form_param("comp%s_filter" % (index,), data, default='filter_no'))
comp_filters.append(
self._get_form_param("comp%s_filter" % (index,), data,
default='filter_no'))
nb_comparisons = len([comp_filter for comp_filter in comp_filters if comp_filter != 'filter_no'])
nb_comparisons = len(
[comp_filter for comp_filter in comp_filters
if comp_filter != 'filter_no'])
if not nb_comparisons: if not nb_comparisons:
comparison_mode = 'no_comparison' comparison_mode = 'no_comparison'
elif nb_comparisons > 1: elif nb_comparisons > 1:
@ -180,12 +211,14 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
comparison_mode = 'single' comparison_mode = 'single'
return comp_filters, nb_comparisons, comparison_mode return comp_filters, nb_comparisons, comparison_mode
def _get_start_stop_for_filter(self, main_filter, fiscalyear, start_date, stop_date, start_period, stop_period):
def _get_start_stop_for_filter(self, main_filter, fiscalyear, start_date,
stop_date, start_period, stop_period):
if main_filter in ('filter_no', 'filter_year'): if main_filter in ('filter_no', 'filter_year'):
start_period = self.get_first_fiscalyear_period(fiscalyear) start_period = self.get_first_fiscalyear_period(fiscalyear)
stop_period = self.get_last_fiscalyear_period(fiscalyear) stop_period = self.get_last_fiscalyear_period(fiscalyear)
elif main_filter == 'filter_opening': elif main_filter == 'filter_opening':
opening_period = self._get_st_fiscalyear_period(fiscalyear, special=True)
opening_period = self._get_st_fiscalyear_period(
fiscalyear, special=True)
start_period = stop_period = opening_period start_period = stop_period = opening_period
if main_filter == 'filter_date': if main_filter == 'filter_date':
start = start_date start = start_date
@ -197,11 +230,14 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
return start_period, stop_period, start, stop return start_period, stop_period, start, stop
def compute_balance_data(self, data, filter_report_type=None): def compute_balance_data(self, data, filter_report_type=None):
new_ids = data['form']['account_ids'] or data['form']['chart_account_id']
max_comparison = self._get_form_param('max_comparison', data, default=0)
new_ids = data['form']['account_ids'] or data[
'form']['chart_account_id']
max_comparison = self._get_form_param(
'max_comparison', data, default=0)
main_filter = self._get_form_param('filter', data, default='filter_no') main_filter = self._get_form_param('filter', data, default='filter_no')
comp_filters, nb_comparisons, comparison_mode = self._comp_filters(data, max_comparison)
comp_filters, nb_comparisons, comparison_mode = self._comp_filters(
data, max_comparison)
fiscalyear = self.get_fiscalyear_br(data) fiscalyear = self.get_fiscalyear_br(data)
@ -214,51 +250,75 @@ class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
chart_account = self._get_chart_account_id_br(data) chart_account = self._get_chart_account_id_br(data)
start_period, stop_period, start, stop = \ start_period, stop_period, start, stop = \
self._get_start_stop_for_filter(main_filter, fiscalyear, start_date, stop_date, start_period, stop_period)
self._get_start_stop_for_filter(main_filter, fiscalyear,
start_date, stop_date,
start_period, stop_period)
init_balance = self.is_initial_balance_enabled(main_filter) init_balance = self.is_initial_balance_enabled(main_filter)
initial_balance_mode = init_balance and self._get_initial_balance_mode(start) or False
initial_balance_mode = init_balance and self._get_initial_balance_mode(
start) or False
# Retrieving accounts # Retrieving accounts
account_ids = self.get_all_accounts(new_ids, only_type=filter_report_type)
account_ids = self.get_all_accounts(
new_ids, only_type=filter_report_type)
# get details for each accounts, total of debit / credit / balance # get details for each accounts, total of debit / credit / balance
accounts_by_ids = self._get_account_details(account_ids, target_move, fiscalyear, main_filter, start, stop, initial_balance_mode)
accounts_by_ids = self._get_account_details(
account_ids, target_move, fiscalyear, main_filter, start, stop,
initial_balance_mode)
comparison_params = [] comparison_params = []
comp_accounts_by_ids = [] comp_accounts_by_ids = []
for index in range(max_comparison): for index in range(max_comparison):
if comp_filters[index] != 'filter_no': if comp_filters[index] != 'filter_no':
comparison_result, comp_params = self._get_comparison_details(data, account_ids, target_move, comp_filters[index], index)
comparison_result, comp_params = self._get_comparison_details(
data, account_ids, target_move, comp_filters[index], index)
comparison_params.append(comp_params) comparison_params.append(comp_params)
comp_accounts_by_ids.append(comparison_result) comp_accounts_by_ids.append(comparison_result)
to_display = dict.fromkeys(account_ids, True) to_display = dict.fromkeys(account_ids, True)
objects = [] objects = []
for account in self.pool.get('account.account').browse(self.cursor, self.uid, account_ids):
for account in self.pool.get('account.account').browse(self.cursor,
self.uid,
account_ids):
if not account.parent_id: # hide top level account if not account.parent_id: # hide top level account
continue continue
if account.type == 'consolidation': if account.type == 'consolidation':
to_display.update(dict([(a.id, False) for a in account.child_consol_ids]))
to_display.update(
dict([(a.id, False) for a in account.child_consol_ids]))
elif account.type == 'view': elif account.type == 'view':
to_display.update(dict([(a.id, True) for a in account.child_id]))
to_display.update(
dict([(a.id, True) for a in account.child_id]))
account.debit = accounts_by_ids[account.id]['debit'] account.debit = accounts_by_ids[account.id]['debit']
account.credit = accounts_by_ids[account.id]['credit'] account.credit = accounts_by_ids[account.id]['credit']
account.balance = accounts_by_ids[account.id]['balance'] account.balance = accounts_by_ids[account.id]['balance']
account.init_balance = accounts_by_ids[account.id].get('init_balance', 0.0)
account.init_balance = accounts_by_ids[
account.id].get('init_balance', 0.0)
display_account = False # if any amount is != 0 in comparisons, we have to display the whole account
# if any amount is != 0 in comparisons, we have to display the
# whole account
display_account = False
comp_accounts = [] comp_accounts = []
for comp_account_by_id in comp_accounts_by_ids: for comp_account_by_id in comp_accounts_by_ids:
values = comp_account_by_id.get(account.id) values = comp_account_by_id.get(account.id)
values.update(self._get_diff(account.balance, values['balance']))
display_account = any((values.get('credit', 0.0), values.get('debit', 0.0), values.get('balance', 0.0), values.get('init_balance', 0.0)))
values.update(
self._get_diff(account.balance, values['balance']))
display_account = any((values.get('credit', 0.0),
values.get('debit', 0.0),
values.get('balance', 0.0),
values.get('init_balance', 0.0)))
comp_accounts.append(values) comp_accounts.append(values)
account.comparisons = comp_accounts account.comparisons = comp_accounts
# we have to display the account if a comparison as an amount or if we have an amount in the main column
# we set it as a property to let the data in the report if someone want to use it in a custom report
display_account = display_account or any((account.debit, account.credit, account.balance, account.init_balance))
to_display.update({account.id: display_account and to_display[account.id]})
# we have to display the account if a comparison as an amount or
# if we have an amount in the main column
# we set it as a property to let the data in the report if someone
# want to use it in a custom report
display_account = display_account or any((account.debit,
account.credit,
account.balance,
account.init_balance))
to_display.update(
{account.id: display_account and to_display[account.id]})
objects.append(account) objects.append(account)
for account in objects: for account in objects:

208
account_financial_report_webkit/report/common_partner_balance_reports.py

@ -27,11 +27,16 @@ from .common_balance_reports import CommonBalanceReportHeaderWebkit
from .common_partner_reports import CommonPartnersReportHeaderWebkit from .common_partner_reports import CommonPartnersReportHeaderWebkit
class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, CommonPartnersReportHeaderWebkit):
"""Define common helper for balance (trial balance, P&L, BS oriented financial report"""
class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit,
CommonPartnersReportHeaderWebkit):
def _get_account_partners_details(self, account_by_ids, main_filter, target_move, start,
stop, initial_balance_mode, partner_filter_ids=False):
"""Define common helper for balance (trial balance, P&L,
BS oriented financial report"""
def _get_account_partners_details(self, account_by_ids, main_filter,
target_move, start, stop,
initial_balance_mode,
partner_filter_ids=False):
res = {} res = {}
filter_from = False filter_from = False
if main_filter in ('filter_period', 'filter_no', 'filter_opening'): if main_filter in ('filter_period', 'filter_no', 'filter_opening'):
@ -41,51 +46,71 @@ class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, Co
partners_init_balances_by_ids = {} partners_init_balances_by_ids = {}
for account_id, account_details in account_by_ids.iteritems(): for account_id, account_details in account_by_ids.iteritems():
partners_init_balances_by_ids.update(self._get_partners_initial_balances(account_id,
start,
initial_balance_mode,
partner_filter_ids=partner_filter_ids,
exclude_reconcile=False)) # we'll never exclude reconciled entries in the legal reports
partners_init_balances_by_ids.update(
self._get_partners_initial_balances(
account_id, start, initial_balance_mode,
partner_filter_ids=partner_filter_ids,
# we'll never exclude reconciled entries in the legal
# reports
exclude_reconcile=False))
opening_mode = 'exclude_opening' opening_mode = 'exclude_opening'
if main_filter == 'filter_opening': if main_filter == 'filter_opening':
opening_mode = 'include_opening' opening_mode = 'include_opening'
# get credit and debit for partner # get credit and debit for partner
details = self._get_partners_totals_account(filter_from,
account_id,
start,
stop,
target_move,
partner_filter_ids=partner_filter_ids,
mode=opening_mode)
details = self._get_partners_totals_account(
filter_from,
account_id,
start,
stop,
target_move,
partner_filter_ids=partner_filter_ids,
mode=opening_mode)
# merge initial balances in partner details # merge initial balances in partner details
if partners_init_balances_by_ids.get(account_id): if partners_init_balances_by_ids.get(account_id):
for partner_id, initial_balances in partners_init_balances_by_ids[account_id].iteritems():
for partner_id, initial_balances in \
partners_init_balances_by_ids[account_id].iteritems():
if initial_balances.get('init_balance'): if initial_balances.get('init_balance'):
details[partner_id].update({'init_balance': initial_balances['init_balance']})
details[partner_id].update(
{'init_balance': initial_balances['init_balance']})
# compute balance for the partner # compute balance for the partner
for partner_id, partner_details in details.iteritems(): for partner_id, partner_details in details.iteritems():
details[partner_id]['balance'] = details[partner_id].get('init_balance', 0.0) +\
details[partner_id].get('debit', 0.0) -\
details[partner_id].get('credit', 0.0)
details[partner_id]['balance'] = details[partner_id].\
get('init_balance', 0.0) + \
details[partner_id].get('debit', 0.0) - \
details[partner_id].get('credit', 0.0)
res[account_id] = details res[account_id] = details
return res return res
def _get_partners_initial_balances(self, account_ids, start_period, initial_balance_mode, partner_filter_ids=None, exclude_reconcile=False):
# we get the initial balance from the opening period (opening_balance) when the opening period is included in the start period and
# when there is at least one entry in the opening period. Otherwise we compute it from previous periods
def _get_partners_initial_balances(self, account_ids, start_period,
initial_balance_mode,
partner_filter_ids=None,
exclude_reconcile=False):
# we get the initial balance from the opening period (opening_balance)
# when the opening period is included in the start period and
# when there is at least one entry in the opening period. Otherwise we
# compute it from previous periods
if initial_balance_mode == 'opening_balance': if initial_balance_mode == 'opening_balance':
opening_period_selected = self.get_included_opening_period(start_period)
res = self._compute_partners_initial_balances(account_ids, start_period, partner_filter_ids, force_period_ids=opening_period_selected, exclude_reconcile=exclude_reconcile)
opening_period_selected = self.get_included_opening_period(
start_period)
res = self._compute_partners_initial_balances(
account_ids, start_period, partner_filter_ids,
force_period_ids=opening_period_selected,
exclude_reconcile=exclude_reconcile)
elif initial_balance_mode == 'initial_balance': elif initial_balance_mode == 'initial_balance':
res = self._compute_partners_initial_balances(account_ids, start_period, partner_filter_ids, exclude_reconcile=exclude_reconcile)
res = self._compute_partners_initial_balances(
account_ids, start_period, partner_filter_ids,
exclude_reconcile=exclude_reconcile)
else: else:
res = {} res = {}
return res return res
def _get_partners_totals_account(self, filter_from, account_id, start, stop, target_move, partner_filter_ids=None, mode='exclude_opening'):
def _get_partners_totals_account(self, filter_from, account_id, start,
stop, target_move,
partner_filter_ids=None,
mode='exclude_opening'):
final_res = defaultdict(dict) final_res = defaultdict(dict)
sql_select = """ sql_select = """
@ -94,17 +119,20 @@ class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, Co
sum(account_move_line.credit) AS credit sum(account_move_line.credit) AS credit
FROM account_move_line""" FROM account_move_line"""
sql_joins = '' sql_joins = ''
sql_where = "WHERE account_move_line.account_id = %(account_id)s AND account_move_line.state = 'valid' "
sql_where = "WHERE account_move_line.account_id = %(account_id)s \
AND account_move_line.state = 'valid' "
method = getattr(self, '_get_query_params_from_' + filter_from + 's') method = getattr(self, '_get_query_params_from_' + filter_from + 's')
sql_conditions, search_params = method(start, stop, mode=mode) sql_conditions, search_params = method(start, stop, mode=mode)
sql_where += sql_conditions sql_where += sql_conditions
if partner_filter_ids: if partner_filter_ids:
sql_where += " AND account_move_line.partner_id in %(partner_ids)s"
sql_where += " AND account_move_line.partner_id \
in %(partner_ids)s"
search_params.update({'partner_ids': tuple(partner_filter_ids)}) search_params.update({'partner_ids': tuple(partner_filter_ids)})
if target_move == 'posted': if target_move == 'posted':
sql_joins += "INNER JOIN account_move ON account_move_line.move_id = account_move.id"
sql_joins += "INNER JOIN account_move \
ON account_move_line.move_id = account_move.id"
sql_where += " AND account_move.state = %(target_move)s" sql_where += " AND account_move.state = %(target_move)s"
search_params.update({'target_move': target_move}) search_params.update({'target_move': target_move})
@ -128,19 +156,26 @@ class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, Co
filter_type = ('payable',) filter_type = ('payable',)
return filter_type return filter_type
def _get_partners_comparison_details(self, data, account_ids, target_move, comparison_filter, index, partner_filter_ids=False):
def _get_partners_comparison_details(self, data, account_ids, target_move,
comparison_filter, index,
partner_filter_ids=False):
""" """
@param data: data of the wizard form @param data: data of the wizard form
@param account_ids: ids of the accounts to get details @param account_ids: ids of the accounts to get details
@param comparison_filter: selected filter on the form for the comparison (filter_no, filter_year, filter_period, filter_date)
@param index: index of the fields to get (ie. comp1_fiscalyear_id where 1 is the index)
@param comparison_filter: selected filter on the form for
the comparison (filter_no, filter_year, filter_period, filter_date)
@param index: index of the fields to get (ie. comp1_fiscalyear_id
where 1 is the index)
@param partner_filter_ids: list of ids of partners to select @param partner_filter_ids: list of ids of partners to select
@return: dict of account details (key = account id) @return: dict of account details (key = account id)
""" """
fiscalyear = self._get_info(data, "comp%s_fiscalyear_id" % (index,), 'account.fiscalyear')
start_period = self._get_info(data, "comp%s_period_from" % (index,), 'account.period')
stop_period = self._get_info(data, "comp%s_period_to" % (index,), 'account.period')
fiscalyear = self._get_info(
data, "comp%s_fiscalyear_id" % (index,), 'account.fiscalyear')
start_period = self._get_info(
data, "comp%s_period_from" % (index,), 'account.period')
stop_period = self._get_info(
data, "comp%s_period_to" % (index,), 'account.period')
start_date = self._get_form_param("comp%s_date_from" % (index,), data) start_date = self._get_form_param("comp%s_date_from" % (index,), data)
stop_date = self._get_form_param("comp%s_date_to" % (index,), data) stop_date = self._get_form_param("comp%s_date_to" % (index,), data)
init_balance = self.is_initial_balance_enabled(comparison_filter) init_balance = self.is_initial_balance_enabled(comparison_filter)
@ -149,22 +184,30 @@ class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, Co
accounts_details_by_ids = defaultdict(dict) accounts_details_by_ids = defaultdict(dict)
if comparison_filter != 'filter_no': if comparison_filter != 'filter_no':
start_period, stop_period, start, stop = \ start_period, stop_period, start, stop = \
self._get_start_stop_for_filter(comparison_filter, fiscalyear, start_date, stop_date, start_period, stop_period)
self._get_start_stop_for_filter(
comparison_filter, fiscalyear, start_date, stop_date,
start_period, stop_period)
details_filter = comparison_filter details_filter = comparison_filter
if comparison_filter == 'filter_year': if comparison_filter == 'filter_year':
details_filter = 'filter_no' details_filter = 'filter_no'
initial_balance_mode = init_balance and self._get_initial_balance_mode(start) or False
initial_balance_mode = init_balance \
and self._get_initial_balance_mode(start) or False
accounts_by_ids = self._get_account_details(account_ids, target_move, fiscalyear, details_filter, start, stop, initial_balance_mode)
accounts_by_ids = self._get_account_details(
account_ids, target_move, fiscalyear, details_filter, start,
stop, initial_balance_mode)
partner_details_by_ids = self._get_account_partners_details(accounts_by_ids, details_filter,
target_move, start, stop, initial_balance_mode,
partner_filter_ids=partner_filter_ids)
partner_details_by_ids = self._get_account_partners_details(
accounts_by_ids, details_filter,
target_move, start, stop, initial_balance_mode,
partner_filter_ids=partner_filter_ids)
for account_id in account_ids: for account_id in account_ids:
accounts_details_by_ids[account_id]['account'] = accounts_by_ids[account_id]
accounts_details_by_ids[account_id]['partners_amounts'] = partner_details_by_ids[account_id]
accounts_details_by_ids[account_id][
'account'] = accounts_by_ids[account_id]
accounts_details_by_ids[account_id][
'partners_amounts'] = partner_details_by_ids[account_id]
comp_params = { comp_params = {
'comparison_filter': comparison_filter, 'comparison_filter': comparison_filter,
@ -177,11 +220,14 @@ class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, Co
return accounts_details_by_ids, comp_params return accounts_details_by_ids, comp_params
def compute_partner_balance_data(self, data, filter_report_type=None): def compute_partner_balance_data(self, data, filter_report_type=None):
new_ids = data['form']['account_ids'] or data['form']['chart_account_id']
max_comparison = self._get_form_param('max_comparison', data, default=0)
new_ids = data['form']['account_ids'] or data[
'form']['chart_account_id']
max_comparison = self._get_form_param(
'max_comparison', data, default=0)
main_filter = self._get_form_param('filter', data, default='filter_no') main_filter = self._get_form_param('filter', data, default='filter_no')
comp_filters, nb_comparisons, comparison_mode = self._comp_filters(data, max_comparison)
comp_filters, nb_comparisons, comparison_mode = self._comp_filters(
data, max_comparison)
fiscalyear = self.get_fiscalyear_br(data) fiscalyear = self.get_fiscalyear_br(data)
@ -197,62 +243,78 @@ class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, Co
filter_type = self._get_filter_type(result_selection) filter_type = self._get_filter_type(result_selection)
start_period, stop_period, start, stop = \ start_period, stop_period, start, stop = \
self._get_start_stop_for_filter(main_filter, fiscalyear, start_date, stop_date, start_period, stop_period)
self._get_start_stop_for_filter(
main_filter, fiscalyear, start_date, stop_date, start_period,
stop_period)
initial_balance = self.is_initial_balance_enabled(main_filter) initial_balance = self.is_initial_balance_enabled(main_filter)
initial_balance_mode = initial_balance and self._get_initial_balance_mode(start) or False
initial_balance_mode = initial_balance \
and self._get_initial_balance_mode(start) or False
# Retrieving accounts # Retrieving accounts
account_ids = self.get_all_accounts(new_ids, only_type=filter_type,
filter_report_type=filter_report_type)
account_ids = self.get_all_accounts(
new_ids, only_type=filter_type,
filter_report_type=filter_report_type)
# get details for each accounts, total of debit / credit / balance # get details for each accounts, total of debit / credit / balance
accounts_by_ids = self._get_account_details(account_ids, target_move, fiscalyear, main_filter, start, stop, initial_balance_mode)
accounts_by_ids = self._get_account_details(
account_ids, target_move, fiscalyear, main_filter, start, stop,
initial_balance_mode)
partner_details_by_ids = self._get_account_partners_details(accounts_by_ids,
main_filter,
target_move,
start,
stop,
initial_balance_mode,
partner_filter_ids=partner_ids)
partner_details_by_ids = self._get_account_partners_details(
accounts_by_ids, main_filter, target_move, start, stop,
initial_balance_mode, partner_filter_ids=partner_ids)
comparison_params = [] comparison_params = []
comp_accounts_by_ids = [] comp_accounts_by_ids = []
for index in range(max_comparison): for index in range(max_comparison):
if comp_filters[index] != 'filter_no': if comp_filters[index] != 'filter_no':
comparison_result, comp_params = self._get_partners_comparison_details(data, account_ids,
target_move, comp_filters[index],
index, partner_filter_ids=partner_ids)
comparison_result, comp_params = self.\
_get_partners_comparison_details(
data, account_ids,
target_move,
comp_filters[index],
index,
partner_filter_ids=partner_ids)
comparison_params.append(comp_params) comparison_params.append(comp_params)
comp_accounts_by_ids.append(comparison_result) comp_accounts_by_ids.append(comparison_result)
objects = [] objects = []
for account in self.pool.get('account.account').browse(self.cursor, self.uid, account_ids):
for account in self.pool.get('account.account').browse(self.cursor,
self.uid,
account_ids):
if not account.parent_id: # hide top level account if not account.parent_id: # hide top level account
continue continue
account.debit = accounts_by_ids[account.id]['debit'] account.debit = accounts_by_ids[account.id]['debit']
account.credit = accounts_by_ids[account.id]['credit'] account.credit = accounts_by_ids[account.id]['credit']
account.balance = accounts_by_ids[account.id]['balance'] account.balance = accounts_by_ids[account.id]['balance']
account.init_balance = accounts_by_ids[account.id].get('init_balance', 0.0)
account.init_balance = accounts_by_ids[
account.id].get('init_balance', 0.0)
account.partners_amounts = partner_details_by_ids[account.id] account.partners_amounts = partner_details_by_ids[account.id]
comp_accounts = [] comp_accounts = []
for comp_account_by_id in comp_accounts_by_ids: for comp_account_by_id in comp_accounts_by_ids:
values = comp_account_by_id.get(account.id) values = comp_account_by_id.get(account.id)
values['account'].update(self._get_diff(account.balance, values['account'].get('balance', 0.0)))
values['account'].update(
self._get_diff(account.balance,
values['account'].get('balance', 0.0)))
comp_accounts.append(values) comp_accounts.append(values)
for partner_id, partner_values in values['partners_amounts'].copy().iteritems():
base_partner_balance = account.partners_amounts[partner_id]['balance'] if \
account.partners_amounts.get(partner_id) else 0.0
partner_values.update(self._get_diff(base_partner_balance,
partner_values.get('balance', 0.0)))
values['partners_amounts'][partner_id].update(partner_values)
for partner_id, partner_values in \
values['partners_amounts'].copy().iteritems():
base_partner_balance = account.partners_amounts[
partner_id]['balance'] if \
account.partners_amounts.get(partner_id) else 0.0
partner_values.update(self._get_diff(
base_partner_balance,
partner_values.get('balance', 0.0)))
values['partners_amounts'][
partner_id].update(partner_values)
account.comparisons = comp_accounts account.comparisons = comp_accounts
all_partner_ids = reduce(add, [comp['partners_amounts'].keys() for comp in comp_accounts],
all_partner_ids = reduce(add, [comp['partners_amounts'].keys()
for comp in comp_accounts],
account.partners_amounts.keys()) account.partners_amounts.keys())
account.partners_order = self._order_partners(all_partner_ids) account.partners_order = self._order_partners(all_partner_ids)

157
account_financial_report_webkit/report/common_partner_reports.py

@ -30,10 +30,15 @@ from .common_reports import CommonReportHeaderWebkit
class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit): class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
"""Define common helper for partner oriented financial report""" """Define common helper for partner oriented financial report"""
####################Account move line retrieval helper ##########################
def get_partners_move_lines_ids(self, account_id, main_filter, start, stop, target_move,
######################################
# Account move line retrieval helper #
######################################
def get_partners_move_lines_ids(self, account_id, main_filter, start, stop,
target_move,
exclude_reconcile=False, exclude_reconcile=False,
partner_filter=False): partner_filter=False):
filter_from = False filter_from = False
@ -42,13 +47,10 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
elif main_filter == 'filter_date': elif main_filter == 'filter_date':
filter_from = 'date' filter_from = 'date'
if filter_from: if filter_from:
return self._get_partners_move_line_ids(filter_from,
account_id,
start,
stop,
target_move,
exclude_reconcile=exclude_reconcile,
partner_filter=partner_filter)
return self._get_partners_move_line_ids(
filter_from, account_id, start, stop, target_move,
exclude_reconcile=exclude_reconcile,
partner_filter=partner_filter)
def _get_first_special_period(self): def _get_first_special_period(self):
""" """
@ -59,8 +61,8 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
and it returns the id of the first period for which `special` is True and it returns the id of the first period for which `special` is True
in this fiscal year. in this fiscal year.
It is used for example in the partners reports, where we have to include
the first, and only the first opening period.
It is used for example in the partners reports, where we have to
include the first, and only the first opening period.
:return: browse record of the first special period. :return: browse record of the first special period.
""" """
@ -71,31 +73,36 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
# it may so # it may so
if not first_entry_id: if not first_entry_id:
return return
first_entry = move_line_obj.browse(self.cr, self.uid, first_entry_id[0])
first_entry = move_line_obj.browse(
self.cr, self.uid, first_entry_id[0])
fiscalyear = first_entry.period_id.fiscalyear_id fiscalyear = first_entry.period_id.fiscalyear_id
special_periods = [period for period in fiscalyear.period_ids if period.special]
special_periods = [
period for period in fiscalyear.period_ids if period.special]
# so, we have no opening period on the first year, nothing to return # so, we have no opening period on the first year, nothing to return
if not special_periods: if not special_periods:
return return
return min(special_periods, return min(special_periods,
key=lambda p: datetime.strptime(p.date_start, DEFAULT_SERVER_DATE_FORMAT))
key=lambda p: datetime.strptime(p.date_start,
DEFAULT_SERVER_DATE_FORMAT))
def _get_period_range_from_start_period(self, start_period, include_opening=False,
def _get_period_range_from_start_period(self, start_period,
include_opening=False,
fiscalyear=False, fiscalyear=False,
stop_at_previous_opening=False): stop_at_previous_opening=False):
"""We retrieve all periods before start period""" """We retrieve all periods before start period"""
periods = super(CommonPartnersReportHeaderWebkit, self).\ periods = super(CommonPartnersReportHeaderWebkit, self).\
_get_period_range_from_start_period(
start_period,
include_opening=include_opening,
fiscalyear=fiscalyear,
stop_at_previous_opening=stop_at_previous_opening)
_get_period_range_from_start_period(
start_period,
include_opening=include_opening,
fiscalyear=fiscalyear,
stop_at_previous_opening=stop_at_previous_opening)
first_special = self._get_first_special_period() first_special = self._get_first_special_period()
if first_special and first_special.id not in periods: if first_special and first_special.id not in periods:
periods.append(first_special.id) periods.append(first_special.id)
return periods return periods
def _get_query_params_from_periods(self, period_start, period_stop, mode='exclude_opening'):
def _get_query_params_from_periods(self, period_start, period_stop,
mode='exclude_opening'):
""" """
Build the part of the sql "where clause" which filters on the selected Build the part of the sql "where clause" which filters on the selected
periods. periods.
@ -106,7 +113,7 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
""" """
# we do not want opening period so we exclude opening # we do not want opening period so we exclude opening
periods = self.pool.get('account.period').build_ctx_periods( periods = self.pool.get('account.period').build_ctx_periods(
self.cr, self.uid, period_start.id, period_stop.id)
self.cr, self.uid, period_start.id, period_stop.id)
if not periods: if not periods:
return [] return []
@ -118,7 +125,8 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
sql_conditions = "" sql_conditions = ""
if periods: if periods:
sql_conditions = " AND account_move_line.period_id in %(period_ids)s"
sql_conditions = " AND account_move_line.period_id in \
%(period_ids)s"
return sql_conditions, search_params return sql_conditions, search_params
@ -138,14 +146,18 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
'date_start': date_start, 'date_start': date_start,
'date_stop': date_stop} 'date_stop': date_stop}
sql_conditions = " AND account_move_line.period_id not in %(period_ids)s" \
" AND account_move_line.date between date(%(date_start)s) and date((%(date_stop)s))"
sql_conditions = " AND account_move_line.period_id not \
in %(period_ids)s \
AND account_move_line.date between \
date(%(date_start)s) and date((%(date_stop)s))"
return sql_conditions, search_params return sql_conditions, search_params
def _get_partners_move_line_ids(self, filter_from, account_id, start, stop, def _get_partners_move_line_ids(self, filter_from, account_id, start, stop,
target_move, opening_mode='exclude_opening',
exclude_reconcile=False, partner_filter=None):
target_move,
opening_mode='exclude_opening',
exclude_reconcile=False,
partner_filter=None):
""" """
:param str filter_from: "periods" or "dates" :param str filter_from: "periods" or "dates"
@ -162,7 +174,8 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
final_res = defaultdict(list) final_res = defaultdict(list)
sql_select = "SELECT account_move_line.id, account_move_line.partner_id FROM account_move_line"
sql_select = "SELECT account_move_line.id, \
account_move_line.partner_id FROM account_move_line"
sql_joins = '' sql_joins = ''
sql_where = " WHERE account_move_line.account_id = %(account_ids)s " \ sql_where = " WHERE account_move_line.account_id = %(account_ids)s " \
" AND account_move_line.state = 'valid' " " AND account_move_line.state = 'valid' "
@ -174,13 +187,17 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
if exclude_reconcile: if exclude_reconcile:
sql_where += (" AND ((account_move_line.reconcile_id IS NULL)" sql_where += (" AND ((account_move_line.reconcile_id IS NULL)"
" OR (account_move_line.reconcile_id IS NOT NULL AND account_move_line.last_rec_date > date(%(date_stop)s)))")
" OR (account_move_line.reconcile_id IS NOT NULL \
AND account_move_line.last_rec_date > \
date(%(date_stop)s)))")
if partner_filter: if partner_filter:
sql_where += " AND account_move_line.partner_id in %(partner_ids)s"
sql_where += " AND account_move_line.partner_id \
in %(partner_ids)s"
if target_move == 'posted': if target_move == 'posted':
sql_joins += "INNER JOIN account_move ON account_move_line.move_id = account_move.id"
sql_joins += "INNER JOIN account_move \
ON account_move_line.move_id = account_move.id"
sql_where += " AND account_move.state = %(target_move)s" sql_where += " AND account_move.state = %(target_move)s"
search_params.update({'target_move': target_move}) search_params.update({'target_move': target_move})
@ -197,14 +214,16 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
final_res[row['partner_id']].append(row['id']) final_res[row['partner_id']].append(row['id'])
return final_res return final_res
def _get_clearance_move_line_ids(self, move_line_ids, date_stop, date_until):
def _get_clearance_move_line_ids(self, move_line_ids, date_stop,
date_until):
if not move_line_ids: if not move_line_ids:
return [] return []
move_line_obj = self.pool.get('account.move.line') move_line_obj = self.pool.get('account.move.line')
# we do not use orm in order to gain perfo # we do not use orm in order to gain perfo
# In this case I have to test the effective gain over an itteration # In this case I have to test the effective gain over an itteration
# Actually ORM does not allows distinct behavior # Actually ORM does not allows distinct behavior
sql = "Select distinct reconcile_id from account_move_line where id in %s"
sql = "Select distinct reconcile_id from account_move_line \
where id in %s"
self.cursor.execute(sql, (tuple(move_line_ids),)) self.cursor.execute(sql, (tuple(move_line_ids),))
rec_ids = self.cursor.fetchall() rec_ids = self.cursor.fetchall()
if rec_ids: if rec_ids:
@ -218,7 +237,9 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
else: else:
return [] return []
####################Initial Partner Balance helper ########################
##############################################
# Initial Partner Balance helper #
##############################################
def _tree_move_line_ids(self, move_lines_data, key=None): def _tree_move_line_ids(self, move_lines_data, key=None):
""" """
@ -243,19 +264,24 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
res[account_id][partner_id] = row res[account_id][partner_id] = row
return res return res
def _partners_initial_balance_line_ids(self, account_ids, start_period, partner_filter, exclude_reconcile=False, force_period_ids=False, date_stop=None):
def _partners_initial_balance_line_ids(self, account_ids, start_period,
partner_filter,
exclude_reconcile=False,
force_period_ids=False,
date_stop=None):
# take ALL previous periods # take ALL previous periods
period_ids = force_period_ids \ period_ids = force_period_ids \
if force_period_ids \
else self._get_period_range_from_start_period(start_period, fiscalyear=False, include_opening=False)
if force_period_ids \
else self._get_period_range_from_start_period(
start_period, fiscalyear=False, include_opening=False)
if not period_ids: if not period_ids:
period_ids = [-1] period_ids = [-1]
search_param = { search_param = {
'date_start': start_period.date_start,
'period_ids': tuple(period_ids),
'account_ids': tuple(account_ids),
}
'date_start': start_period.date_start,
'period_ids': tuple(period_ids),
'account_ids': tuple(account_ids),
}
sql = ("SELECT ml.id, ml.account_id, ml.partner_id " sql = ("SELECT ml.id, ml.account_id, ml.partner_id "
"FROM account_move_line ml " "FROM account_move_line ml "
"INNER JOIN account_account a " "INNER JOIN account_account a "
@ -264,10 +290,12 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
"AND ml.account_id in %(account_ids)s ") "AND ml.account_id in %(account_ids)s ")
if exclude_reconcile: if exclude_reconcile:
if not date_stop: if not date_stop:
raise Exception("Missing \"date_stop\" to compute the open invoices.")
raise Exception(
"Missing \"date_stop\" to compute the open invoices.")
search_param.update({'date_stop': date_stop}) search_param.update({'date_stop': date_stop})
sql += ("AND ((ml.reconcile_id IS NULL)"
"OR (ml.reconcile_id IS NOT NULL AND ml.last_rec_date > date(%(date_stop)s))) ")
sql += ("AND ((ml.reconcile_id IS NULL) "
"OR (ml.reconcile_id IS NOT NULL \
AND ml.last_rec_date > date(%(date_stop)s))) ")
if partner_filter: if partner_filter:
sql += "AND ml.partner_id in %(partner_ids)s " sql += "AND ml.partner_id in %(partner_ids)s "
search_param.update({'partner_ids': tuple(partner_filter)}) search_param.update({'partner_ids': tuple(partner_filter)})
@ -275,21 +303,28 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
self.cursor.execute(sql, search_param) self.cursor.execute(sql, search_param)
return self.cursor.dictfetchall() return self.cursor.dictfetchall()
def _compute_partners_initial_balances(self, account_ids, start_period, partner_filter=None, exclude_reconcile=False, force_period_ids=False):
def _compute_partners_initial_balances(self, account_ids, start_period,
partner_filter=None,
exclude_reconcile=False,
force_period_ids=False):
"""We compute initial balance. """We compute initial balance.
If form is filtered by date all initial balance are equal to 0 If form is filtered by date all initial balance are equal to 0
This function will sum pear and apple in currency amount if account as no secondary currency"""
This function will sum pear and apple in currency amount if account
as no secondary currency"""
if isinstance(account_ids, (int, long)): if isinstance(account_ids, (int, long)):
account_ids = [account_ids] account_ids = [account_ids]
move_line_ids = self._partners_initial_balance_line_ids(account_ids, start_period, partner_filter,
exclude_reconcile=exclude_reconcile,
force_period_ids=force_period_ids)
move_line_ids = self._partners_initial_balance_line_ids(
account_ids, start_period, partner_filter,
exclude_reconcile=exclude_reconcile,
force_period_ids=force_period_ids)
if not move_line_ids: if not move_line_ids:
move_line_ids = [{'id': -1}] move_line_ids = [{'id': -1}]
sql = ("SELECT ml.account_id, ml.partner_id," sql = ("SELECT ml.account_id, ml.partner_id,"
" sum(ml.debit) as debit, sum(ml.credit) as credit," " sum(ml.debit) as debit, sum(ml.credit) as credit,"
" sum(ml.debit-ml.credit) as init_balance," " sum(ml.debit-ml.credit) as init_balance,"
" CASE WHEN a.currency_id ISNULL THEN 0.0 ELSE sum(ml.amount_currency) END as init_balance_currency, "
" CASE WHEN a.currency_id ISNULL THEN 0.0\
ELSE sum(ml.amount_currency) \
END as init_balance_currency, "
" c.name as currency_name " " c.name as currency_name "
"FROM account_move_line ml " "FROM account_move_line ml "
"INNER JOIN account_account a " "INNER JOIN account_account a "
@ -298,12 +333,17 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
"ON c.id = a.currency_id " "ON c.id = a.currency_id "
"WHERE ml.id in %(move_line_ids)s " "WHERE ml.id in %(move_line_ids)s "
"GROUP BY ml.account_id, ml.partner_id, a.currency_id, c.name") "GROUP BY ml.account_id, ml.partner_id, a.currency_id, c.name")
search_param = {'move_line_ids': tuple([move_line['id'] for move_line in move_line_ids])}
search_param = {
'move_line_ids': tuple([move_line['id'] for move_line in
move_line_ids])}
self.cursor.execute(sql, search_param) self.cursor.execute(sql, search_param)
res = self.cursor.dictfetchall() res = self.cursor.dictfetchall()
return self._tree_move_line_ids(res) return self._tree_move_line_ids(res)
####################Partner specific helper ################################
############################################################
# Partner specific helper #
############################################################
def _order_partners(self, *args): def _order_partners(self, *args):
"""We get the partner linked to all current accounts that are used. """We get the partner linked to all current accounts that are used.
We also use ensure that partner are ordered by name We also use ensure that partner are ordered by name
@ -316,11 +356,16 @@ class CommonPartnersReportHeaderWebkit(CommonReportHeaderWebkit):
if not partner_ids: if not partner_ids:
return [] return []
existing_partner_ids = [partner_id for partner_id in partner_ids if partner_id]
existing_partner_ids = [
partner_id for partner_id in partner_ids if partner_id]
if existing_partner_ids: if existing_partner_ids:
# We may use orm here as the performance optimization is not that big
sql = ("SELECT name|| ' ' ||CASE WHEN ref IS NOT NULL THEN '('||ref||')' ELSE '' END, id, ref, name"
" FROM res_partner WHERE id IN %s ORDER BY LOWER(name), ref")
# We may use orm here as the performance optimization is not that
# big
sql = ("SELECT name|| ' ' ||CASE WHEN ref IS NOT NULL \
THEN '('||ref||')' \
ELSE '' END, id, ref, name"
" FROM res_partner \
WHERE id IN %s ORDER BY LOWER(name), ref")
self.cursor.execute(sql, (tuple(set(existing_partner_ids)),)) self.cursor.execute(sql, (tuple(set(existing_partner_ids)),))
res = self.cursor.fetchall() res = self.cursor.fetchall()

235
account_financial_report_webkit/report/common_reports.py

@ -26,15 +26,22 @@ import logging
from openerp.osv import osv from openerp.osv import osv
from openerp.tools.translate import _ from openerp.tools.translate import _
from openerp.addons.account.report.common_report_header import common_report_header
from openerp.addons.account.report.common_report_header \
import common_report_header
_logger = logging.getLogger('financial.reports.webkit') _logger = logging.getLogger('financial.reports.webkit')
MAX_MONSTER_SLICE = 50000 MAX_MONSTER_SLICE = 50000
class CommonReportHeaderWebkit(common_report_header): class CommonReportHeaderWebkit(common_report_header):
"""Define common helper for financial report""" """Define common helper for financial report"""
####################From getter helper #####################################
######################################################################
# From getter helper #
######################################################################
def get_start_period_br(self, data): def get_start_period_br(self, data):
return self._get_info(data, 'period_from', 'account.period') return self._get_info(data, 'period_from', 'account.period')
@ -112,20 +119,26 @@ class CommonReportHeaderWebkit(common_report_header):
def _get_form_param(self, param, data, default=False): def _get_form_param(self, param, data, default=False):
return data.get('form', {}).get(param, default) return data.get('form', {}).get(param, default)
####################Account and account line filter helper #################
#############################################
# Account and account line filter helper #
#############################################
def sort_accounts_with_structure(self, root_account_ids, account_ids, context=None):
def sort_accounts_with_structure(self, root_account_ids, account_ids,
context=None):
"""Sort accounts by code respecting their structure""" """Sort accounts by code respecting their structure"""
def recursive_sort_by_code(accounts, parent): def recursive_sort_by_code(accounts, parent):
sorted_accounts = [] sorted_accounts = []
# add all accounts with same parent # add all accounts with same parent
level_accounts = [account for account in accounts level_accounts = [account for account in accounts
if account['parent_id'] and account['parent_id'][0] == parent['id']]
# add consolidation children of parent, as they are logically on the same level
if account['parent_id']
and account['parent_id'][0] == parent['id']]
# add consolidation children of parent, as they are logically on
# the same level
if parent.get('child_consol_ids'): if parent.get('child_consol_ids'):
level_accounts.extend([account for account in accounts level_accounts.extend([account for account in accounts
if account['id'] in parent['child_consol_ids']])
if account['id']
in parent['child_consol_ids']])
# stop recursion if no children found # stop recursion if no children found
if not level_accounts: if not level_accounts:
return [] return []
@ -134,16 +147,17 @@ class CommonReportHeaderWebkit(common_report_header):
for level_account in level_accounts: for level_account in level_accounts:
sorted_accounts.append(level_account['id']) sorted_accounts.append(level_account['id'])
sorted_accounts.extend(recursive_sort_by_code(accounts, parent=level_account))
sorted_accounts.extend(
recursive_sort_by_code(accounts, parent=level_account))
return sorted_accounts return sorted_accounts
if not account_ids: if not account_ids:
return [] return []
accounts_data = self.pool.get('account.account').read(self.cr, self.uid,
account_ids,
['id', 'parent_id', 'level', 'code', 'child_consol_ids'],
context=context)
accounts_data = self.pool.get('account.account').read(
self.cr, self.uid, account_ids,
['id', 'parent_id', 'level', 'code', 'child_consol_ids'],
context=context)
sorted_accounts = [] sorted_accounts = []
@ -151,7 +165,8 @@ class CommonReportHeaderWebkit(common_report_header):
if account_data['id'] in root_account_ids] if account_data['id'] in root_account_ids]
for root_account_data in root_accounts_data: for root_account_data in root_accounts_data:
sorted_accounts.append(root_account_data['id']) sorted_accounts.append(root_account_data['id'])
sorted_accounts.extend(recursive_sort_by_code(accounts_data, root_account_data))
sorted_accounts.extend(
recursive_sort_by_code(accounts_data, root_account_data))
# fallback to unsorted accounts when sort failed # fallback to unsorted accounts when sort failed
# sort fails when the levels are miscalculated by account.account # sort fails when the levels are miscalculated by account.account
@ -162,11 +177,14 @@ class CommonReportHeaderWebkit(common_report_header):
return sorted_accounts return sorted_accounts
def get_all_accounts(self, account_ids, exclude_type=None, only_type=None, filter_report_type=None, context=None):
def get_all_accounts(self, account_ids, exclude_type=None, only_type=None,
filter_report_type=None, context=None):
"""Get all account passed in params with their childrens """Get all account passed in params with their childrens
@param exclude_type: list of types to exclude (view, receivable, payable, consolidation, other)
@param only_type: list of types to filter on (view, receivable, payable, consolidation, other)
@param exclude_type: list of types to exclude (view, receivable,
payable, consolidation, other)
@param only_type: list of types to filter on (view, receivable,
payable, consolidation, other)
@param filter_report_type: list of report type to filter on @param filter_report_type: list of report type to filter on
""" """
context = context or {} context = context or {}
@ -176,9 +194,11 @@ class CommonReportHeaderWebkit(common_report_header):
acc_obj = self.pool.get('account.account') acc_obj = self.pool.get('account.account')
for account_id in account_ids: for account_id in account_ids:
accounts.append(account_id) accounts.append(account_id)
accounts += acc_obj._get_children_and_consol(self.cursor, self.uid, account_id, context=context)
accounts += acc_obj._get_children_and_consol(
self.cursor, self.uid, account_id, context=context)
res_ids = list(set(accounts)) res_ids = list(set(accounts))
res_ids = self.sort_accounts_with_structure(account_ids, res_ids, context=context)
res_ids = self.sort_accounts_with_structure(
account_ids, res_ids, context=context)
if exclude_type or only_type or filter_report_type: if exclude_type or only_type or filter_report_type:
sql_filters = {'ids': tuple(res_ids)} sql_filters = {'ids': tuple(res_ids)}
@ -207,17 +227,22 @@ class CommonReportHeaderWebkit(common_report_header):
res_ids = [res_id for res_id in res_ids if res_id in only_ids] res_ids = [res_id for res_id in res_ids if res_id in only_ids]
return res_ids return res_ids
####################Periods and fiscal years helper #######################
##########################################
# Periods and fiscal years helper #
##########################################
def _get_opening_periods(self): def _get_opening_periods(self):
"""Return the list of all journal that can be use to create opening entries
We actually filter on this instead of opening period as older version of OpenERP
did not have this notion"""
return self.pool.get('account.period').search(self.cursor, self.uid, [('special', '=', True)])
"""Return the list of all journal that can be use to create opening
entries.
We actually filter on this instead of opening period as older version
of OpenERP did not have this notion"""
return self.pool.get('account.period').search(self.cursor, self.uid,
[('special', '=', True)])
def exclude_opening_periods(self, period_ids): def exclude_opening_periods(self, period_ids):
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
return period_obj.search(self.cr, self.uid, [['special', '=', False], ['id', 'in', period_ids]])
return period_obj.search(self.cr, self.uid, [['special', '=', False],
['id', 'in', period_ids]])
def get_included_opening_period(self, period): def get_included_opening_period(self, period):
"""Return the opening included in normal period we use the assumption """Return the opening included in normal period we use the assumption
@ -228,7 +253,7 @@ class CommonReportHeaderWebkit(common_report_header):
('date_start', '>=', period.date_start), ('date_start', '>=', period.date_start),
('date_stop', '<=', period.date_stop), ('date_stop', '<=', period.date_stop),
('company_id', '=', period.company_id.id)], ('company_id', '=', period.company_id.id)],
limit=1)
limit=1)
def periods_contains_move_lines(self, period_ids): def periods_contains_move_lines(self, period_ids):
if not period_ids: if not period_ids:
@ -236,12 +261,16 @@ class CommonReportHeaderWebkit(common_report_header):
mv_line_obj = self.pool.get('account.move.line') mv_line_obj = self.pool.get('account.move.line')
if isinstance(period_ids, (int, long)): if isinstance(period_ids, (int, long)):
period_ids = [period_ids] period_ids = [period_ids]
return mv_line_obj.search(self.cursor, self.uid, [('period_id', 'in', period_ids)], limit=1) and True or False
return mv_line_obj.search(self.cursor, self.uid,
[('period_id', 'in', period_ids)], limit=1) \
and True or False
def _get_period_range_from_periods(self, start_period, stop_period, mode=None):
def _get_period_range_from_periods(self, start_period, stop_period,
mode=None):
""" """
Deprecated. We have to use now the build_ctx_periods of period_obj otherwise we'll have
inconsistencies, because build_ctx_periods does never filter on the the special
Deprecated. We have to use now the build_ctx_periods of period_obj
otherwise we'll have inconsistencies, because build_ctx_periods does
never filter on the the special
""" """
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
search_period = [('date_start', '>=', start_period.date_start), search_period = [('date_start', '>=', start_period.date_start),
@ -252,8 +281,10 @@ class CommonReportHeaderWebkit(common_report_header):
res = period_obj.search(self.cursor, self.uid, search_period) res = period_obj.search(self.cursor, self.uid, search_period)
return res return res
def _get_period_range_from_start_period(self, start_period, include_opening=False,
fiscalyear=False, stop_at_previous_opening=False):
def _get_period_range_from_start_period(self, start_period,
include_opening=False,
fiscalyear=False,
stop_at_previous_opening=False):
"""We retrieve all periods before start period""" """We retrieve all periods before start period"""
opening_period_id = False opening_period_id = False
past_limit = [] past_limit = []
@ -262,24 +293,28 @@ class CommonReportHeaderWebkit(common_report_header):
# We look for previous opening period # We look for previous opening period
if stop_at_previous_opening: if stop_at_previous_opening:
opening_search = [('special', '=', True), opening_search = [('special', '=', True),
('date_stop', '<', start_period.date_start)]
('date_stop', '<', start_period.date_start)]
if fiscalyear: if fiscalyear:
opening_search.append(('fiscalyear_id', '=', fiscalyear.id)) opening_search.append(('fiscalyear_id', '=', fiscalyear.id))
opening_periods = period_obj.search(self.cursor, self.uid, opening_search,
opening_periods = period_obj.search(self.cursor, self.uid,
opening_search,
order='date_stop desc') order='date_stop desc')
for opening_period in opening_periods: for opening_period in opening_periods:
validation_res = mv_line_obj.search(self.cursor, validation_res = mv_line_obj.search(self.cursor,
self.uid, self.uid,
[('period_id', '=', opening_period)],
[('period_id', '=',
opening_period)],
limit=1) limit=1)
if validation_res: if validation_res:
opening_period_id = opening_period opening_period_id = opening_period
break break
if opening_period_id: if opening_period_id:
#we also look for overlapping periods
opening_period_br = period_obj.browse(self.cursor, self.uid, opening_period_id)
past_limit = [('date_start', '>=', opening_period_br.date_stop)]
# we also look for overlapping periods
opening_period_br = period_obj.browse(
self.cursor, self.uid, opening_period_id)
past_limit = [
('date_start', '>=', opening_period_br.date_stop)]
periods_search = [('date_stop', '<=', start_period.date_stop)] periods_search = [('date_stop', '<=', start_period.date_stop)]
periods_search += past_limit periods_search += past_limit
@ -303,7 +338,8 @@ class CommonReportHeaderWebkit(common_report_header):
def get_last_fiscalyear_period(self, fiscalyear): def get_last_fiscalyear_period(self, fiscalyear):
return self._get_st_fiscalyear_period(fiscalyear, order='DESC') return self._get_st_fiscalyear_period(fiscalyear, order='DESC')
def _get_st_fiscalyear_period(self, fiscalyear, special=False, order='ASC'):
def _get_st_fiscalyear_period(self, fiscalyear, special=False,
order='ASC'):
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
p_id = period_obj.search(self.cursor, p_id = period_obj.search(self.cursor,
self.uid, self.uid,
@ -315,9 +351,12 @@ class CommonReportHeaderWebkit(common_report_header):
raise osv.except_osv(_('No period found'), '') raise osv.except_osv(_('No period found'), '')
return period_obj.browse(self.cursor, self.uid, p_id[0]) return period_obj.browse(self.cursor, self.uid, p_id[0])
####################Initial Balance helper #################################
###############################
# Initial Balance helper #
###############################
def _compute_init_balance(self, account_id=None, period_ids=None, mode='computed', default_values=False):
def _compute_init_balance(self, account_id=None, period_ids=None,
mode='computed', default_values=False):
if not isinstance(period_ids, list): if not isinstance(period_ids, list):
period_ids = [period_ids] period_ids = [period_ids]
res = {} res = {}
@ -332,10 +371,11 @@ class CommonReportHeaderWebkit(common_report_header):
" sum(amount_currency) AS curr_balance" " sum(amount_currency) AS curr_balance"
" FROM account_move_line" " FROM account_move_line"
" WHERE period_id in %s" " WHERE period_id in %s"
" AND account_id = %s", (tuple(period_ids), account_id))
" AND account_id = %s",
(tuple(period_ids), account_id))
res = self.cursor.dictfetchone() res = self.cursor.dictfetchone()
except Exception, exc:
except Exception:
self.cursor.rollback() self.cursor.rollback()
raise raise
@ -348,67 +388,81 @@ class CommonReportHeaderWebkit(common_report_header):
def _read_opening_balance(self, account_ids, start_period): def _read_opening_balance(self, account_ids, start_period):
""" Read opening balances from the opening balance """ Read opening balances from the opening balance
""" """
opening_period_selected = self.get_included_opening_period(start_period)
opening_period_selected = self.get_included_opening_period(
start_period)
if not opening_period_selected: if not opening_period_selected:
raise osv.except_osv( raise osv.except_osv(
_('Error'),
_('No opening period found to compute the opening balances.\n'
'You have to configure a period on the first of January'
' with the special flag.'))
_('Error'),
_('No opening period found to compute the opening balances.\n'
'You have to configure a period on the first of January'
' with the special flag.'))
res = {} res = {}
for account_id in account_ids: for account_id in account_ids:
res[account_id] = self._compute_init_balance(account_id, opening_period_selected, mode='read')
res[account_id] = self._compute_init_balance(
account_id, opening_period_selected, mode='read')
return res return res
def _compute_initial_balances(self, account_ids, start_period, fiscalyear): def _compute_initial_balances(self, account_ids, start_period, fiscalyear):
"""We compute initial balance. """We compute initial balance.
If form is filtered by date all initial balance are equal to 0 If form is filtered by date all initial balance are equal to 0
This function will sum pear and apple in currency amount if account as no secondary currency"""
# if opening period is included in start period we do not need to compute init balance
# we just read it from opening entries
This function will sum pear and apple in currency amount if account as
no secondary currency"""
# if opening period is included in start period we do not need to
# compute init balance we just read it from opening entries
res = {} res = {}
# PNL and Balance accounts are not computed the same way look for attached doc
# We include opening period in pnl account in order to see if opening entries
# were created by error on this account
pnl_periods_ids = self._get_period_range_from_start_period(start_period, fiscalyear=fiscalyear,
include_opening=True)
bs_period_ids = self._get_period_range_from_start_period(start_period, include_opening=True,
stop_at_previous_opening=True)
opening_period_selected = self.get_included_opening_period(start_period)
for acc in self.pool.get('account.account').browse(self.cursor, self.uid, account_ids):
# PNL and Balance accounts are not computed the same way look for
# attached doc We include opening period in pnl account in order to see
# if opening entries were created by error on this account
pnl_periods_ids = self._get_period_range_from_start_period(
start_period, fiscalyear=fiscalyear, include_opening=True)
bs_period_ids = self._get_period_range_from_start_period(
start_period, include_opening=True, stop_at_previous_opening=True)
opening_period_selected = self.get_included_opening_period(
start_period)
for acc in self.pool.get('account.account').browse(self.cursor,
self.uid,
account_ids):
res[acc.id] = self._compute_init_balance(default_values=True) res[acc.id] = self._compute_init_balance(default_values=True)
if acc.user_type.close_method == 'none': if acc.user_type.close_method == 'none':
# we compute the initial balance for close_method == none only when we print a GL
# during the year, when the opening period is not included in the period selection!
# we compute the initial balance for close_method == none only
# when we print a GL during the year, when the opening period
# is not included in the period selection!
if pnl_periods_ids and not opening_period_selected: if pnl_periods_ids and not opening_period_selected:
res[acc.id] = self._compute_init_balance(acc.id, pnl_periods_ids)
res[acc.id] = self._compute_init_balance(
acc.id, pnl_periods_ids)
else: else:
res[acc.id] = self._compute_init_balance(acc.id, bs_period_ids) res[acc.id] = self._compute_init_balance(acc.id, bs_period_ids)
return res return res
####################Account move retrieval helper ##########################
def _get_move_ids_from_periods(self, account_id, period_start, period_stop, target_move):
################################################
# Account move retrieval helper #
################################################
def _get_move_ids_from_periods(self, account_id, period_start, period_stop,
target_move):
move_line_obj = self.pool.get('account.move.line') move_line_obj = self.pool.get('account.move.line')
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
periods = period_obj.build_ctx_periods(self.cursor, self.uid, period_start.id, period_stop.id)
periods = period_obj.build_ctx_periods(
self.cursor, self.uid, period_start.id, period_stop.id)
if not periods: if not periods:
return [] return []
search = [('period_id', 'in', periods), ('account_id', '=', account_id)]
search = [
('period_id', 'in', periods), ('account_id', '=', account_id)]
if target_move == 'posted': if target_move == 'posted':
search += [('move_id.state', '=', 'posted')] search += [('move_id.state', '=', 'posted')]
return move_line_obj.search(self.cursor, self.uid, search) return move_line_obj.search(self.cursor, self.uid, search)
def _get_move_ids_from_dates(self, account_id, date_start, date_stop, target_move, mode='include_opening'):
def _get_move_ids_from_dates(self, account_id, date_start, date_stop,
target_move, mode='include_opening'):
# TODO imporve perfomance by setting opening period as a property # TODO imporve perfomance by setting opening period as a property
move_line_obj = self.pool.get('account.move.line') move_line_obj = self.pool.get('account.move.line')
search_period = [('date', '>=', date_start), search_period = [('date', '>=', date_start),
('date', '<=', date_stop), ('date', '<=', date_stop),
('account_id', '=', account_id)] ('account_id', '=', account_id)]
# actually not used because OpenERP itself always include the opening when we
# get the periods from january to december
# actually not used because OpenERP itself always include the opening
# when we get the periods from january to december
if mode == 'exclude_opening': if mode == 'exclude_opening':
opening = self._get_opening_periods() opening = self._get_opening_periods()
if opening: if opening:
@ -419,20 +473,28 @@ class CommonReportHeaderWebkit(common_report_header):
return move_line_obj.search(self.cursor, self.uid, search_period) return move_line_obj.search(self.cursor, self.uid, search_period)
def get_move_lines_ids(self, account_id, main_filter, start, stop, target_move, mode='include_opening'):
def get_move_lines_ids(self, account_id, main_filter, start, stop,
target_move, mode='include_opening'):
"""Get account move lines base on form data""" """Get account move lines base on form data"""
if mode not in ('include_opening', 'exclude_opening'): if mode not in ('include_opening', 'exclude_opening'):
raise osv.except_osv(_('Invalid query mode'), _('Must be in include_opening, exclude_opening'))
raise osv.except_osv(
_('Invalid query mode'),
_('Must be in include_opening, exclude_opening'))
if main_filter in ('filter_period', 'filter_no'): if main_filter in ('filter_period', 'filter_no'):
return self._get_move_ids_from_periods(account_id, start, stop, target_move)
return self._get_move_ids_from_periods(account_id, start, stop,
target_move)
elif main_filter == 'filter_date': elif main_filter == 'filter_date':
return self._get_move_ids_from_dates(account_id, start, stop, target_move)
return self._get_move_ids_from_dates(account_id, start, stop,
target_move)
else: else:
raise osv.except_osv(_('No valid filter'), _('Please set a valid time filter'))
raise osv.except_osv(
_('No valid filter'), _('Please set a valid time filter'))
def _get_move_line_datas(self, move_line_ids, order='per.special DESC, l.date ASC, per.date_start ASC, m.name ASC'):
def _get_move_line_datas(self, move_line_ids,
order='per.special DESC, l.date ASC, \
per.date_start ASC, m.name ASC'):
# Possible bang if move_line_ids is too long # Possible bang if move_line_ids is too long
# We can not slice here as we have to do the sort. # We can not slice here as we have to do the sort.
# If slice has to be done it means that we have to reorder in python # If slice has to be done it means that we have to reorder in python
@ -475,7 +537,8 @@ SELECT l.id AS id,
FROM account_move_line l FROM account_move_line l
JOIN account_move m on (l.move_id=m.id) JOIN account_move m on (l.move_id=m.id)
LEFT JOIN res_currency c on (l.currency_id=c.id) LEFT JOIN res_currency c on (l.currency_id=c.id)
LEFT JOIN account_move_reconcile partialrec on (l.reconcile_partial_id = partialrec.id)
LEFT JOIN account_move_reconcile partialrec
on (l.reconcile_partial_id = partialrec.id)
LEFT JOIN account_move_reconcile fullrec on (l.reconcile_id = fullrec.id) LEFT JOIN account_move_reconcile fullrec on (l.reconcile_id = fullrec.id)
LEFT JOIN res_partner p on (l.partner_id=p.id) LEFT JOIN res_partner p on (l.partner_id=p.id)
LEFT JOIN account_invoice i on (m.id =i.move_id) LEFT JOIN account_invoice i on (m.id =i.move_id)
@ -486,7 +549,7 @@ FROM account_move_line l
try: try:
self.cursor.execute(monster, (tuple(move_line_ids),)) self.cursor.execute(monster, (tuple(move_line_ids),))
res = self.cursor.dictfetchall() res = self.cursor.dictfetchall()
except Exception, exc:
except Exception:
self.cursor.rollback() self.cursor.rollback()
raise raise
return res or [] return res or []
@ -506,14 +569,16 @@ SELECT account_move.id,
AND m2.account_id<>%s limit %s) , ', ') AND m2.account_id<>%s limit %s) , ', ')
FROM account_move FROM account_move
JOIN account_move_line on (account_move_line.move_id = account_move.id)
JOIN account_account on (account_move_line.account_id = account_account.id)
JOIN account_move_line
on (account_move_line.move_id = account_move.id)
JOIN account_account
on (account_move_line.account_id = account_account.id)
WHERE move_id in %s""" WHERE move_id in %s"""
try: try:
self.cursor.execute(sql, (account_id, limit, tuple(move_ids))) self.cursor.execute(sql, (account_id, limit, tuple(move_ids)))
res = self.cursor.fetchall() res = self.cursor.fetchall()
except Exception as exc:
except Exception:
self.cursor.rollback() self.cursor.rollback()
raise raise
return res and dict(res) or {} return res and dict(res) or {}
@ -524,8 +589,10 @@ WHERE move_id in %s"""
return True return True
def _get_initial_balance_mode(self, start_period): def _get_initial_balance_mode(self, start_period):
opening_period_selected = self.get_included_opening_period(start_period)
opening_move_lines = self.periods_contains_move_lines(opening_period_selected)
opening_period_selected = self.get_included_opening_period(
start_period)
opening_move_lines = self.periods_contains_move_lines(
opening_period_selected)
if opening_move_lines: if opening_move_lines:
return 'opening_balance' return 'opening_balance'
else: else:

103
account_financial_report_webkit/report/general_ledger.py

@ -33,14 +33,18 @@ from .webkit_parser_header_fix import HeaderFooterTextWebKitParser
class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit): class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
def __init__(self, cursor, uid, name, context): def __init__(self, cursor, uid, name, context):
super(GeneralLedgerWebkit, self).__init__(cursor, uid, name, context=context)
super(GeneralLedgerWebkit, self).__init__(
cursor, uid, name, context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr self.cursor = self.cr
company = self.pool.get('res.users').browse(self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('GENERAL LEDGER'), company.name, company.currency_id.name))
company = self.pool.get('res.users').browse(
self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join(
(_('GENERAL LEDGER'), company.name, company.currency_id.name))
footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
footer_date_time = self.formatLang(
str(datetime.today()), date_time=True)
self.localcontext.update({ self.localcontext.update({
'cr': cursor, 'cr': cursor,
@ -62,15 +66,17 @@ class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right',
' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will be used
by mako template"""
new_ids = data['form']['account_ids'] or data['form']['chart_account_id']
"""Populate a ledger_lines attribute on each browse record that will be
used by mako template"""
new_ids = data['form']['account_ids'] or data[
'form']['chart_account_id']
# Account initial balance memoizer # Account initial balance memoizer
init_balance_memoizer = {} init_balance_memoizer = {}
@ -99,23 +105,31 @@ class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
stop = stop_period stop = stop_period
initial_balance = self.is_initial_balance_enabled(main_filter) initial_balance = self.is_initial_balance_enabled(main_filter)
initial_balance_mode = initial_balance and self._get_initial_balance_mode(start) or False
initial_balance_mode = initial_balance \
and self._get_initial_balance_mode(start) or False
# Retrieving accounts # Retrieving accounts
accounts = self.get_all_accounts(new_ids, exclude_type=['view']) accounts = self.get_all_accounts(new_ids, exclude_type=['view'])
if initial_balance_mode == 'initial_balance': if initial_balance_mode == 'initial_balance':
init_balance_memoizer = self._compute_initial_balances(accounts, start, fiscalyear)
init_balance_memoizer = self._compute_initial_balances(
accounts, start, fiscalyear)
elif initial_balance_mode == 'opening_balance': elif initial_balance_mode == 'opening_balance':
init_balance_memoizer = self._read_opening_balance(accounts, start) init_balance_memoizer = self._read_opening_balance(accounts, start)
ledger_lines_memoizer = self._compute_account_ledger_lines(accounts, init_balance_memoizer,
main_filter, target_move, start, stop)
ledger_lines_memoizer = self._compute_account_ledger_lines(
accounts, init_balance_memoizer, main_filter, target_move, start,
stop)
objects = [] objects = []
for account in self.pool.get('account.account').browse(self.cursor, self.uid, accounts):
if do_centralize and account.centralized and ledger_lines_memoizer.get(account.id):
account.ledger_lines = self._centralize_lines(main_filter, ledger_lines_memoizer.get(account.id, []))
for account in self.pool.get('account.account').browse(self.cursor,
self.uid,
accounts):
if do_centralize and account.centralized \
and ledger_lines_memoizer.get(account.id):
account.ledger_lines = self._centralize_lines(
main_filter, ledger_lines_memoizer.get(account.id, []))
else: else:
account.ledger_lines = ledger_lines_memoizer.get(account.id, [])
account.ledger_lines = ledger_lines_memoizer.get(
account.id, [])
account.init_balance = init_balance_memoizer.get(account.id, {}) account.init_balance = init_balance_memoizer.get(account.id, {})
objects.append(account) objects.append(account)
@ -130,17 +144,20 @@ class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
'initial_balance_mode': initial_balance_mode, 'initial_balance_mode': initial_balance_mode,
}) })
return super(GeneralLedgerWebkit, self).set_context(objects, data, new_ids,
report_type=report_type)
return super(GeneralLedgerWebkit, self).set_context(
objects, data, new_ids, report_type=report_type)
def _centralize_lines(self, filter, ledger_lines, context=None): def _centralize_lines(self, filter, ledger_lines, context=None):
""" Group by period in filter mode 'period' or on one line in filter mode 'date'
ledger_lines parameter is a list of dict built by _get_ledger_lines"""
""" Group by period in filter mode 'period' or on one line in filter
mode 'date' ledger_lines parameter is a list of dict built
by _get_ledger_lines"""
def group_lines(lines): def group_lines(lines):
if not lines: if not lines:
return {} return {}
sums = reduce(lambda line, memo: dict((key, value + memo[key]) for key, value
in line.iteritems() if key in ('balance', 'debit', 'credit')), lines)
sums = reduce(lambda line, memo:
dict((key, value + memo[key]) for key, value
in line.iteritems() if key in
('balance', 'debit', 'credit')), lines)
res_lines = { res_lines = {
'balance': sums['balance'], 'balance': sums['balance'],
@ -161,32 +178,38 @@ class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
period_obj = self.pool.get('account.period') period_obj = self.pool.get('account.period')
# we need to sort the lines per period in order to use groupby # we need to sort the lines per period in order to use groupby
# unique ids of each used period id in lines # unique ids of each used period id in lines
period_ids = list(set([line['lperiod_id'] for line in ledger_lines]))
period_ids = list(
set([line['lperiod_id'] for line in ledger_lines]))
# search on account.period in order to sort them by date_start # search on account.period in order to sort them by date_start
sorted_period_ids = period_obj.search(self.cr, self.uid,
[('id', 'in', period_ids)],
order='special desc, date_start',
context=context)
sorted_ledger_lines = sorted(ledger_lines, key=lambda x: sorted_period_ids.index(x['lperiod_id']))
for period_id, lines_per_period_iterator in groupby(sorted_ledger_lines, itemgetter('lperiod_id')):
sorted_period_ids = period_obj.search(
self.cr, self.uid, [('id', 'in', period_ids)],
order='special desc, date_start', context=context)
sorted_ledger_lines = sorted(
ledger_lines, key=lambda x: sorted_period_ids.
index(x['lperiod_id']))
for period_id, lines_per_period_iterator in groupby(
sorted_ledger_lines, itemgetter('lperiod_id')):
lines_per_period = list(lines_per_period_iterator) lines_per_period = list(lines_per_period_iterator)
if not lines_per_period: if not lines_per_period:
continue continue
group_per_period = group_lines(lines_per_period) group_per_period = group_lines(lines_per_period)
group_per_period.update({ group_per_period.update({
'lperiod_id': period_id, 'lperiod_id': period_id,
'period_code': lines_per_period[0]['period_code'], # period code is anyway the same on each line per period
# period code is anyway the same on each line per period
'period_code': lines_per_period[0]['period_code'],
}) })
centralized_lines.append(group_per_period) centralized_lines.append(group_per_period)
return centralized_lines return centralized_lines
def _compute_account_ledger_lines(self, accounts_ids, init_balance_memoizer, main_filter,
def _compute_account_ledger_lines(self, accounts_ids,
init_balance_memoizer, main_filter,
target_move, start, stop): target_move, start, stop):
res = {} res = {}
for acc_id in accounts_ids: for acc_id in accounts_ids:
move_line_ids = self.get_move_lines_ids(acc_id, main_filter, start, stop, target_move)
move_line_ids = self.get_move_lines_ids(
acc_id, main_filter, start, stop, target_move)
if not move_line_ids: if not move_line_ids:
res[acc_id] = [] res[acc_id] = []
continue continue
@ -199,8 +222,8 @@ class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
if not move_line_ids: if not move_line_ids:
return [] return []
res = self._get_move_line_datas(move_line_ids) res = self._get_move_line_datas(move_line_ids)
## computing counter part is really heavy in term of ressouces consuption
## looking for a king of SQL to help me improve it
# computing counter part is really heavy in term of ressouces
# consuption looking for a king of SQL to help me improve it
move_ids = [x.get('move_id') for x in res] move_ids = [x.get('move_id') for x in res]
counter_parts = self._get_moves_counterparts(move_ids, account_id) counter_parts = self._get_moves_counterparts(move_ids, account_id)
for line in res: for line in res:
@ -208,7 +231,9 @@ class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
return res return res
HeaderFooterTextWebKitParser('report.account.account_report_general_ledger_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/account_report_general_ledger.mako',
parser=GeneralLedgerWebkit)
HeaderFooterTextWebKitParser(
'report.account.account_report_general_ledger_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/\
account_report_general_ledger.mako',
parser=GeneralLedgerWebkit)

122
account_financial_report_webkit/report/open_invoices.py

@ -43,17 +43,23 @@ def get_mako_template(obj, *args):
report_helper.WebKitHelper.get_mako_template = get_mako_template report_helper.WebKitHelper.get_mako_template = get_mako_template
class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebkit):
class PartnersOpenInvoicesWebkit(report_sxw.rml_parse,
CommonPartnersReportHeaderWebkit):
def __init__(self, cursor, uid, name, context): def __init__(self, cursor, uid, name, context):
super(PartnersOpenInvoicesWebkit, self).__init__(cursor, uid, name, context=context)
super(PartnersOpenInvoicesWebkit, self).__init__(
cursor, uid, name, context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr self.cursor = self.cr
company = self.pool.get('res.users').browse(self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('OPEN INVOICES REPORT'), company.name, company.currency_id.name))
company = self.pool.get('res.users').browse(
self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('OPEN INVOICES REPORT'),
company.name,
company.currency_id.name))
footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
footer_date_time = self.formatLang(
str(datetime.today()), date_time=True)
self.localcontext.update({ self.localcontext.update({
'cr': cursor, 'cr': cursor,
@ -73,7 +79,8 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right',
' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
@ -85,13 +92,15 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
for part_id, plane_lines in account_br.ledger_lines.items(): for part_id, plane_lines in account_br.ledger_lines.items():
account_br.grouped_ledger_lines[part_id] = [] account_br.grouped_ledger_lines[part_id] = []
plane_lines.sort(key=itemgetter('currency_code')) plane_lines.sort(key=itemgetter('currency_code'))
for curr, lines in groupby(plane_lines, key=itemgetter('currency_code')):
for curr, lines in groupby(plane_lines,
key=itemgetter('currency_code')):
tmp = [x for x in lines] tmp = [x for x in lines]
account_br.grouped_ledger_lines[part_id].append((curr, tmp)) # I want to reiter many times
account_br.grouped_ledger_lines[part_id].append(
(curr, tmp)) # I want to reiter many times
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will be used
by mako template"""
"""Populate a ledger_lines attribute on each browse record that will
be used by mako template"""
new_ids = data['form']['chart_account_id'] new_ids = data['form']['chart_account_id']
# Account initial balance memoizer # Account initial balance memoizer
init_balance_memoizer = {} init_balance_memoizer = {}
@ -120,7 +129,8 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
if result_selection == 'supplier': if result_selection == 'supplier':
filter_type = ('payable',) filter_type = ('payable',)
account_ids = self.get_all_accounts(new_ids, exclude_type=['view'], only_type=filter_type)
account_ids = self.get_all_accounts(
new_ids, exclude_type=['view'], only_type=filter_type)
if not account_ids: if not account_ids:
raise osv.except_osv(_('Error'), _('No accounts to print.')) raise osv.except_osv(_('Error'), _('No accounts to print.'))
@ -132,26 +142,28 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
else: else:
start = start_period start = start_period
stop = stop_period stop = stop_period
ledger_lines_memoizer = self._compute_open_transactions_lines(account_ids,
main_filter,
target_move,
start,
stop,
date_until,
partner_filter=partner_ids)
ledger_lines_memoizer = self._compute_open_transactions_lines(
account_ids, main_filter, target_move, start, stop, date_until,
partner_filter=partner_ids)
objects = [] objects = []
for account in self.pool.get('account.account').browse(self.cursor, self.uid, account_ids):
for account in self.pool.get('account.account').browse(self.cursor,
self.uid,
account_ids):
account.ledger_lines = ledger_lines_memoizer.get(account.id, {}) account.ledger_lines = ledger_lines_memoizer.get(account.id, {})
account.init_balance = init_balance_memoizer.get(account.id, {}) account.init_balance = init_balance_memoizer.get(account.id, {})
## we have to compute partner order based on inital balance
## and ledger line as we may have partner with init bal
## that are not in ledger line and vice versa
# we have to compute partner order based on inital balance
# and ledger line as we may have partner with init bal
# that are not in ledger line and vice versa
ledg_lines_pids = ledger_lines_memoizer.get(account.id, {}).keys() ledg_lines_pids = ledger_lines_memoizer.get(account.id, {}).keys()
non_null_init_balances = dict([(ib, amounts) for ib, amounts in account.init_balance.iteritems()
if amounts['init_balance'] or amounts['init_balance_currency']])
non_null_init_balances = dict([
(ib, amounts) for ib, amounts
in account.init_balance.iteritems()
if amounts['init_balance']
or amounts['init_balance_currency']])
init_bal_lines_pids = non_null_init_balances.keys() init_bal_lines_pids = non_null_init_balances.keys()
account.partners_order = self._order_partners(ledg_lines_pids, init_bal_lines_pids)
account.partners_order = self._order_partners(
ledg_lines_pids, init_bal_lines_pids)
account.ledger_lines = ledger_lines_memoizer.get(account.id, {}) account.ledger_lines = ledger_lines_memoizer.get(account.id, {})
if group_by_currency: if group_by_currency:
self._group_lines_by_currency(account) self._group_lines_by_currency(account)
@ -168,13 +180,16 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
'chart_account': chart_account, 'chart_account': chart_account,
}) })
return super(PartnersOpenInvoicesWebkit, self).set_context(objects, data, new_ids,
report_type=report_type)
return super(PartnersOpenInvoicesWebkit, self).set_context(
objects, data, new_ids, report_type=report_type)
def _compute_open_transactions_lines(self, accounts_ids, main_filter, target_move, start, stop, date_until=False, partner_filter=False):
def _compute_open_transactions_lines(self, accounts_ids, main_filter,
target_move, start, stop,
date_until=False,
partner_filter=False):
res = defaultdict(dict) res = defaultdict(dict)
## we check if until date and date stop have the same value
# we check if until date and date stop have the same value
if main_filter in ('filter_period', 'filter_no'): if main_filter in ('filter_period', 'filter_no'):
date_stop = stop.date_stop date_stop = stop.date_stop
date_until_match = (date_stop == date_until) date_until_match = (date_stop == date_until)
@ -185,7 +200,8 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
else: else:
raise osv.except_osv(_('Unsuported filter'), raise osv.except_osv(_('Unsuported filter'),
_('Filter has to be in filter date, period, or none'))
_('Filter has to be in filter date, period, \
or none'))
initial_move_lines_per_account = {} initial_move_lines_per_account = {}
if main_filter in ('filter_period', 'filter_no'): if main_filter in ('filter_period', 'filter_no'):
@ -195,34 +211,38 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
partner_filter, partner_filter,
exclude_reconcile=True, exclude_reconcile=True,
force_period_ids=False, force_period_ids=False,
date_stop=date_stop), key='id')
date_stop=date_stop),
key='id')
for account_id in accounts_ids: for account_id in accounts_ids:
initial_move_lines_ids_per_partner = initial_move_lines_per_account.get(account_id, {})
initial_move_lines_ids_per_partner = \
initial_move_lines_per_account.get(account_id, {})
# We get the move line ids of the account # We get the move line ids of the account
move_line_ids_per_partner = self.get_partners_move_lines_ids(account_id,
main_filter,
start,
stop,
target_move,
exclude_reconcile=True,
partner_filter=partner_filter)
if not initial_move_lines_ids_per_partner and not move_line_ids_per_partner:
move_line_ids_per_partner = self.get_partners_move_lines_ids(
account_id, main_filter, start, stop, target_move,
exclude_reconcile=True, partner_filter=partner_filter)
if not initial_move_lines_ids_per_partner \
and not move_line_ids_per_partner:
continue continue
for partner_id in list(set(initial_move_lines_ids_per_partner.keys() + move_line_ids_per_partner.keys())):
partner_line_ids = (move_line_ids_per_partner.get(partner_id, []) +
initial_move_lines_ids_per_partner.get(partner_id, []))
for partner_id in list(
set(initial_move_lines_ids_per_partner.keys() +
move_line_ids_per_partner.keys())):
partner_line_ids = (
move_line_ids_per_partner.get(partner_id, []) +
initial_move_lines_ids_per_partner.get(partner_id, []))
clearance_line_ids = [] clearance_line_ids = []
if date_until and not date_until_match and partner_line_ids: if date_until and not date_until_match and partner_line_ids:
clearance_line_ids = self._get_clearance_move_line_ids(partner_line_ids, date_stop, date_until)
clearance_line_ids = self._get_clearance_move_line_ids(
partner_line_ids, date_stop, date_until)
partner_line_ids += clearance_line_ids partner_line_ids += clearance_line_ids
lines = self._get_move_line_datas(list(set(partner_line_ids))) lines = self._get_move_line_datas(list(set(partner_line_ids)))
for line in lines: for line in lines:
if line['id'] in initial_move_lines_ids_per_partner.get(partner_id, []):
if line['id'] in initial_move_lines_ids_per_partner.\
get(partner_id, []):
line['is_from_previous_periods'] = True line['is_from_previous_periods'] = True
if line['id'] in clearance_line_ids: if line['id'] in clearance_line_ids:
line['is_clearance_line'] = True line['is_clearance_line'] = True
@ -231,7 +251,9 @@ class PartnersOpenInvoicesWebkit(report_sxw.rml_parse, CommonPartnersReportHeade
return res return res
HeaderFooterTextWebKitParser('report.account.account_report_open_invoices_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/account_report_open_invoices.mako',
parser=PartnersOpenInvoicesWebkit)
HeaderFooterTextWebKitParser(
'report.account.account_report_open_invoices_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/\
account_report_open_invoices.mako',
parser=PartnersOpenInvoicesWebkit)

43
account_financial_report_webkit/report/partner_balance.py

@ -25,21 +25,28 @@ from datetime import datetime
from openerp import pooler from openerp import pooler
from openerp.report import report_sxw from openerp.report import report_sxw
from openerp.tools.translate import _ from openerp.tools.translate import _
from .common_partner_balance_reports import CommonPartnerBalanceReportHeaderWebkit
from .common_partner_balance_reports \
import CommonPartnerBalanceReportHeaderWebkit
from .webkit_parser_header_fix import HeaderFooterTextWebKitParser from .webkit_parser_header_fix import HeaderFooterTextWebKitParser
class PartnerBalanceWebkit(report_sxw.rml_parse, CommonPartnerBalanceReportHeaderWebkit):
class PartnerBalanceWebkit(report_sxw.rml_parse,
CommonPartnerBalanceReportHeaderWebkit):
def __init__(self, cursor, uid, name, context): def __init__(self, cursor, uid, name, context):
super(PartnerBalanceWebkit, self).__init__(cursor, uid, name, context=context)
super(PartnerBalanceWebkit, self).__init__(
cursor, uid, name, context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr self.cursor = self.cr
company = self.pool.get('res.users').browse(self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('PARTNER BALANCE'), company.name, company.currency_id.name))
company = self.pool.get('res.users').browse(
self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('PARTNER BALANCE'),
company.name,
company.currency_id.name))
footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
footer_date_time = self.formatLang(
str(datetime.today()), date_time=True)
self.localcontext.update({ self.localcontext.update({
'cr': cursor, 'cr': cursor,
@ -60,7 +67,8 @@ class PartnerBalanceWebkit(report_sxw.rml_parse, CommonPartnerBalanceReportHeade
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right',
' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
@ -76,15 +84,18 @@ class PartnerBalanceWebkit(report_sxw.rml_parse, CommonPartnerBalanceReportHeade
return 'initial_balance' return 'initial_balance'
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will be used
by mako template"""
objects, new_ids, context_report_values = self.compute_partner_balance_data(data)
"""Populate a ledger_lines attribute on each browse record that will
be used by mako template"""
objects, new_ids, context_report_values = self.\
compute_partner_balance_data(data)
self.localcontext.update(context_report_values) self.localcontext.update(context_report_values)
return super(PartnerBalanceWebkit, self).set_context(objects, data, new_ids,
report_type=report_type)
return super(PartnerBalanceWebkit, self).set_context(
objects, data, new_ids, report_type=report_type)
HeaderFooterTextWebKitParser('report.account.account_report_partner_balance_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/account_report_partner_balance.mako',
parser=PartnerBalanceWebkit)
HeaderFooterTextWebKitParser(
'report.account.account_report_partner_balance_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/\
account_report_partner_balance.mako',
parser=PartnerBalanceWebkit)

106
account_financial_report_webkit/report/partners_ledger.py

@ -30,17 +30,23 @@ from .common_partner_reports import CommonPartnersReportHeaderWebkit
from .webkit_parser_header_fix import HeaderFooterTextWebKitParser from .webkit_parser_header_fix import HeaderFooterTextWebKitParser
class PartnersLedgerWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebkit):
class PartnersLedgerWebkit(report_sxw.rml_parse,
CommonPartnersReportHeaderWebkit):
def __init__(self, cursor, uid, name, context): def __init__(self, cursor, uid, name, context):
super(PartnersLedgerWebkit, self).__init__(cursor, uid, name, context=context)
super(PartnersLedgerWebkit, self).__init__(
cursor, uid, name, context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr self.cursor = self.cr
company = self.pool.get('res.users').browse(self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('PARTNER LEDGER'), company.name, company.currency_id.name))
company = self.pool.get('res.users').browse(
self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('PARTNER LEDGER'),
company.name,
company.currency_id.name))
footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
footer_date_time = self.formatLang(
str(datetime.today()), date_time=True)
self.localcontext.update({ self.localcontext.update({
'cr': cursor, 'cr': cursor,
@ -61,7 +67,8 @@ class PartnersLedgerWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebki
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right',
' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
@ -77,8 +84,8 @@ class PartnersLedgerWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebki
return 'initial_balance' return 'initial_balance'
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will be used
by mako template"""
"""Populate a ledger_lines attribute on each browse record that will
be used by mako template"""
new_ids = data['form']['chart_account_id'] new_ids = data['form']['chart_account_id']
# account partner memoizer # account partner memoizer
@ -118,45 +125,50 @@ class PartnersLedgerWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebki
start = start_period start = start_period
stop = stop_period stop = stop_period
# when the opening period is included in the selected range of periods and
# the opening period contains move lines, we must not compute the initial balance from previous periods
# but only display the move lines of the opening period
# we identify them as:
# - 'initial_balance' means compute the sums of move lines from previous periods
# - 'opening_balance' means display the move lines of the opening period
# when the opening period is included in the selected range of periods
# and the opening period contains move lines, we must not compute the
# initial balance from previous periods but only display the move lines
# of the opening period we identify them as:
# - 'initial_balance' means compute the sums of move lines from
# previous periods
# - 'opening_balance' means display the move lines of the opening
# period
init_balance = main_filter in ('filter_no', 'filter_period') init_balance = main_filter in ('filter_no', 'filter_period')
initial_balance_mode = init_balance and self._get_initial_balance_mode(start) or False
initial_balance_mode = init_balance and self._get_initial_balance_mode(
start) or False
initial_balance_lines = {} initial_balance_lines = {}
if initial_balance_mode == 'initial_balance': if initial_balance_mode == 'initial_balance':
initial_balance_lines = self._compute_partners_initial_balances(accounts,
start_period,
partner_filter=partner_ids,
exclude_reconcile=False)
ledger_lines = self._compute_partner_ledger_lines(accounts,
main_filter,
target_move,
start,
stop,
partner_filter=partner_ids)
initial_balance_lines = self._compute_partners_initial_balances(
accounts, start_period, partner_filter=partner_ids,
exclude_reconcile=False)
ledger_lines = self._compute_partner_ledger_lines(
accounts, main_filter, target_move, start, stop,
partner_filter=partner_ids)
objects = [] objects = []
for account in self.pool.get('account.account').browse(self.cursor, self.uid, accounts):
for account in self.pool.get('account.account').browse(self.cursor,
self.uid,
accounts):
account.ledger_lines = ledger_lines.get(account.id, {}) account.ledger_lines = ledger_lines.get(account.id, {})
account.init_balance = initial_balance_lines.get(account.id, {}) account.init_balance = initial_balance_lines.get(account.id, {})
## we have to compute partner order based on inital balance
## and ledger line as we may have partner with init bal
## that are not in ledger line and vice versa
# we have to compute partner order based on inital balance
# and ledger line as we may have partner with init bal
# that are not in ledger line and vice versa
ledg_lines_pids = ledger_lines.get(account.id, {}).keys() ledg_lines_pids = ledger_lines.get(account.id, {}).keys()
if initial_balance_mode: if initial_balance_mode:
non_null_init_balances = dict([(ib, amounts) for ib, amounts in account.init_balance.iteritems()
if amounts['init_balance'] or amounts['init_balance_currency']])
non_null_init_balances = dict(
[(ib, amounts) for ib, amounts
in account.init_balance.iteritems()
if amounts['init_balance']
or amounts['init_balance_currency']])
init_bal_lines_pids = non_null_init_balances.keys() init_bal_lines_pids = non_null_init_balances.keys()
else: else:
account.init_balance = {} account.init_balance = {}
init_bal_lines_pids = [] init_bal_lines_pids = []
account.partners_order = self._order_partners(ledg_lines_pids, init_bal_lines_pids)
account.partners_order = self._order_partners(
ledg_lines_pids, init_bal_lines_pids)
objects.append(account) objects.append(account)
self.localcontext.update({ self.localcontext.update({
@ -170,20 +182,18 @@ class PartnersLedgerWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebki
'initial_balance_mode': initial_balance_mode, 'initial_balance_mode': initial_balance_mode,
}) })
return super(PartnersLedgerWebkit, self).set_context(objects, data, new_ids,
report_type=report_type)
return super(PartnersLedgerWebkit, self).set_context(
objects, data, new_ids, report_type=report_type)
def _compute_partner_ledger_lines(self, accounts_ids, main_filter, target_move, start, stop, partner_filter=False):
def _compute_partner_ledger_lines(self, accounts_ids, main_filter,
target_move, start, stop,
partner_filter=False):
res = defaultdict(dict) res = defaultdict(dict)
for acc_id in accounts_ids: for acc_id in accounts_ids:
move_line_ids = self.get_partners_move_lines_ids(acc_id,
main_filter,
start,
stop,
target_move,
exclude_reconcile=False,
partner_filter=partner_filter)
move_line_ids = self.get_partners_move_lines_ids(
acc_id, main_filter, start, stop, target_move,
exclude_reconcile=False, partner_filter=partner_filter)
if not move_line_ids: if not move_line_ids:
continue continue
for partner_id in move_line_ids: for partner_id in move_line_ids:
@ -193,7 +203,9 @@ class PartnersLedgerWebkit(report_sxw.rml_parse, CommonPartnersReportHeaderWebki
return res return res
HeaderFooterTextWebKitParser('report.account.account_report_partners_ledger_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/account_report_partners_ledger.mako',
parser=PartnersLedgerWebkit)
HeaderFooterTextWebKitParser(
'report.account.account_report_partners_ledger_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/\
account_report_partners_ledger.mako',
parser=PartnersLedgerWebkit)

68
account_financial_report_webkit/report/print_journal.py

@ -1,19 +1,20 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
############################################################################## ##############################################################################
# #
# account_financial_report_webkit module for OpenERP, Webkit based extended report financial report
# account_financial_report_webkit module for OpenERP, Webkit based
# extended report financial report
# Copyright (C) 2012 SYLEAM Info Services (<http://www.syleam.fr/>) # Copyright (C) 2012 SYLEAM Info Services (<http://www.syleam.fr/>)
# Sebastien LANGE <sebastien.lange@syleam.fr> # Sebastien LANGE <sebastien.lange@syleam.fr>
# #
# This file is a part of account_financial_report_webkit # This file is a part of account_financial_report_webkit
# #
# account_financial_report_webkit is free software: you can redistribute it and/or modify
# 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.
# account_financial_report_webkit is free software: you can redistribute it
# and/or modify 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.
# #
# account_financial_report_webkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# account_financial_report_webkit 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 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details. # GNU Affero General Public License for more details.
# #
@ -34,17 +35,22 @@ from webkit_parser_header_fix import HeaderFooterTextWebKitParser
class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit): class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
def __init__(self, cursor, uid, name, context): def __init__(self, cursor, uid, name, context):
super(PrintJournalWebkit, self).__init__(cursor, uid, name, context=context)
super(PrintJournalWebkit, self).__init__(cursor, uid, name,
context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr self.cursor = self.cr
company_obj = self.pool.get('res.company') company_obj = self.pool.get('res.company')
company_id = company_obj._company_default_get(self.cr, uid, 'res.users', context=context)
company_id = company_obj._company_default_get(self.cr, uid,
'res.users',
context=context)
company = company_obj.browse(self.cr, uid, company_id, context=context) company = company_obj.browse(self.cr, uid, company_id, context=context)
header_report_name = ' - '.join((_('JOURNALS'), company.name, company.currency_id.name))
header_report_name = ' - '.join((_('JOURNALS'), company.name,
company.currency_id.name))
footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
footer_date_time = self.formatLang(str(datetime.today()),
date_time=True)
self.localcontext.update({ self.localcontext.update({
'cr': cursor, 'cr': cursor,
@ -66,14 +72,15 @@ class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'),
'[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will be used
by mako template"""
"""Populate a ledger_lines attribute on each browse record that will
be used by mako template"""
# Reading form # Reading form
main_filter = self._get_form_param('filter', data, default='filter_no') main_filter = self._get_form_param('filter', data, default='filter_no')
@ -90,8 +97,10 @@ class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
domain = [('journal_id', 'in', journal_ids)] domain = [('journal_id', 'in', journal_ids)]
if main_filter == 'filter_no': if main_filter == 'filter_no':
domain += [ domain += [
('date', '>=', self.get_first_fiscalyear_period(fiscalyear).date_start),
('date', '<=', self.get_last_fiscalyear_period(fiscalyear).date_stop),
('date', '>=',
self.get_first_fiscalyear_period(fiscalyear).date_start),
('date', '<=',
self.get_last_fiscalyear_period(fiscalyear).date_stop),
] ]
# computation of move lines # computation of move lines
elif main_filter == 'filter_date': elif main_filter == 'filter_date':
@ -100,7 +109,10 @@ class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
('date', '<=', stop_date), ('date', '<=', stop_date),
] ]
elif main_filter == 'filter_period': elif main_filter == 'filter_period':
period_ids = account_period_obj.build_ctx_periods(self.cursor, self.uid, start_period.id, stop_period.id)
period_ids = account_period_obj.build_ctx_periods(self.cursor,
self.uid,
start_period.id,
stop_period.id)
domain = [ domain = [
('period_id', 'in', period_ids), ('period_id', 'in', period_ids),
] ]
@ -111,7 +123,8 @@ class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
('journal_id', 'in', journal_ids), ('journal_id', 'in', journal_ids),
('period_id', 'in', period_ids), ('period_id', 'in', period_ids),
]) ])
objects = account_journal_period_obj.browse(self.cursor, self.uid, new_ids)
objects = account_journal_period_obj.browse(self.cursor, self.uid,
new_ids)
# Sort by journal and period # Sort by journal and period
objects.sort(key=lambda a: (a.journal_id.code, a.period_id.date_start)) objects.sort(key=lambda a: (a.journal_id.code, a.period_id.date_start))
move_obj = self.pool.get('account.move') move_obj = self.pool.get('account.move')
@ -122,8 +135,10 @@ class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
] ]
if target_move == 'posted': if target_move == 'posted':
domain_arg += [('state', '=', 'posted')] domain_arg += [('state', '=', 'posted')]
move_ids = move_obj.search(self.cursor, self.uid, domain_arg, order="name")
journal_period.moves = move_obj.browse(self.cursor, self.uid, move_ids)
move_ids = move_obj.search(self.cursor, self.uid, domain_arg,
order="name")
journal_period.moves = move_obj.browse(self.cursor, self.uid,
move_ids)
# Sort account move line by account accountant # Sort account move line by account accountant
for move in journal_period.moves: for move in journal_period.moves:
move.line_id.sort(key=lambda a: (a.date, a.account_id.code)) move.line_id.sort(key=lambda a: (a.date, a.account_id.code))
@ -137,11 +152,14 @@ class PrintJournalWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
'chart_account': chart_account, 'chart_account': chart_account,
}) })
return super(PrintJournalWebkit, self).set_context(objects, data, new_ids, report_type=report_type)
return super(PrintJournalWebkit, self).set_context(
objects, data, new_ids, report_type=report_type)
HeaderFooterTextWebKitParser('report.account.account_report_print_journal_webkit',
'account.journal.period',
'addons/account_financial_report_webkit/report/templates/account_report_print_journal.mako',
parser=PrintJournalWebkit)
HeaderFooterTextWebKitParser(
'report.account.account_report_print_journal_webkit',
'account.journal.period',
'addons/account_financial_report_webkit/report/templates/\
account_report_print_journal.mako',
parser=PrintJournalWebkit)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

39
account_financial_report_webkit/report/trial_balance.py

@ -33,17 +33,22 @@ def sign(number):
return cmp(number, 0) return cmp(number, 0)
class TrialBalanceWebkit(report_sxw.rml_parse, CommonBalanceReportHeaderWebkit):
class TrialBalanceWebkit(report_sxw.rml_parse,
CommonBalanceReportHeaderWebkit):
def __init__(self, cursor, uid, name, context): def __init__(self, cursor, uid, name, context):
super(TrialBalanceWebkit, self).__init__(cursor, uid, name, context=context)
super(TrialBalanceWebkit, self).__init__(cursor, uid, name,
context=context)
self.pool = pooler.get_pool(self.cr.dbname) self.pool = pooler.get_pool(self.cr.dbname)
self.cursor = self.cr self.cursor = self.cr
company = self.pool.get('res.users').browse(self.cr, uid, uid, context=context).company_id
header_report_name = ' - '.join((_('TRIAL BALANCE'), company.name, company.currency_id.name))
company = self.pool.get('res.users').browse(self.cr, uid, uid,
context=context).company_id
header_report_name = ' - '.join((_('TRIAL BALANCE'), company.name,
company.currency_id.name))
footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
footer_date_time = self.formatLang(str(datetime.today()),
date_time=True)
self.localcontext.update({ self.localcontext.update({
'cr': cursor, 'cr': cursor,
@ -63,22 +68,26 @@ class TrialBalanceWebkit(report_sxw.rml_parse, CommonBalanceReportHeaderWebkit):
('--header-left', header_report_name), ('--header-left', header_report_name),
('--header-spacing', '2'), ('--header-spacing', '2'),
('--footer-left', footer_date_time), ('--footer-left', footer_date_time),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
('--footer-right', ' '.join((_('Page'), '[page]', _('of'),
'[topage]'))),
('--footer-line',), ('--footer-line',),
], ],
}) })
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
"""Populate a ledger_lines attribute on each browse record that will be used
by mako template"""
objects, new_ids, context_report_values = self.compute_balance_data(data)
"""Populate a ledger_lines attribute on each browse record that will
be used by mako template"""
objects, new_ids, context_report_values = self.\
compute_balance_data(data)
self.localcontext.update(context_report_values) self.localcontext.update(context_report_values)
return super(TrialBalanceWebkit, self).set_context(objects, data, new_ids,
report_type=report_type)
return super(TrialBalanceWebkit, self).set_context(
objects, data, new_ids, report_type=report_type)
HeaderFooterTextWebKitParser('report.account.account_report_trial_balance_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/account_report_trial_balance.mako',
parser=TrialBalanceWebkit)
HeaderFooterTextWebKitParser(
'report.account.account_report_trial_balance_webkit',
'account.account',
'addons/account_financial_report_webkit/report/templates/\
account_report_trial_balance.mako',
parser=TrialBalanceWebkit)

62
account_financial_report_webkit/report/webkit_parser_header_fix.py

@ -56,7 +56,8 @@ _logger = logging.getLogger('financial.reports.webkit')
# them in the localcontext with a key 'additional_args' # them in the localcontext with a key 'additional_args'
# for instance: # for instance:
# header_report_name = _('PARTNER LEDGER') # header_report_name = _('PARTNER LEDGER')
# footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
# footer_date_time = self.formatLang(str(datetime.today()),
# date_time=True)
# self.localcontext.update({ # self.localcontext.update({
# 'additional_args': [ # 'additional_args': [
# ('--header-font-name', 'Helvetica'), # ('--header-font-name', 'Helvetica'),
@ -65,7 +66,8 @@ _logger = logging.getLogger('financial.reports.webkit')
# ('--footer-font-size', '7'), # ('--footer-font-size', '7'),
# ('--header-left', header_report_name), # ('--header-left', header_report_name),
# ('--footer-left', footer_date_time), # ('--footer-left', footer_date_time),
# ('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
# ('--footer-right', ' '.join((_('Page'), '[page]', _('of'),
# '[topage]'))),
# ('--footer-line',), # ('--footer-line',),
# ], # ],
# }) # })
@ -82,8 +84,10 @@ def mako_template(text):
This template uses UTF-8 encoding This template uses UTF-8 encoding
""" """
tmp_lookup = TemplateLookup() # we need it in order to allow inclusion and inheritance
return Template(text, input_encoding='utf-8', output_encoding='utf-8', lookup=tmp_lookup)
tmp_lookup = TemplateLookup(
) # we need it in order to allow inclusion and inheritance
return Template(text, input_encoding='utf-8', output_encoding='utf-8',
lookup=tmp_lookup)
class HeaderFooterTextWebKitParser(webkit_report.WebKitParser): class HeaderFooterTextWebKitParser(webkit_report.WebKitParser):
@ -106,17 +110,29 @@ class HeaderFooterTextWebKitParser(webkit_report.WebKitParser):
command.extend(['--encoding', 'utf-8']) command.extend(['--encoding', 'utf-8'])
if webkit_header.margin_top: if webkit_header.margin_top:
command.extend(['--margin-top', str(webkit_header.margin_top).replace(',', '.')])
command.extend(
['--margin-top',
str(webkit_header.margin_top).replace(',', '.')])
if webkit_header.margin_bottom: if webkit_header.margin_bottom:
command.extend(['--margin-bottom', str(webkit_header.margin_bottom).replace(',', '.')])
command.extend(
['--margin-bottom',
str(webkit_header.margin_bottom).replace(',', '.')])
if webkit_header.margin_left: if webkit_header.margin_left:
command.extend(['--margin-left', str(webkit_header.margin_left).replace(',', '.')])
command.extend(
['--margin-left',
str(webkit_header.margin_left).replace(',', '.')])
if webkit_header.margin_right: if webkit_header.margin_right:
command.extend(['--margin-right', str(webkit_header.margin_right).replace(',', '.')])
command.extend(
['--margin-right',
str(webkit_header.margin_right).replace(',', '.')])
if webkit_header.orientation: if webkit_header.orientation:
command.extend(['--orientation', str(webkit_header.orientation).replace(',', '.')])
command.extend(
['--orientation',
str(webkit_header.orientation).replace(',', '.')])
if webkit_header.format: if webkit_header.format:
command.extend(['--page-size', str(webkit_header.format).replace(',', '.')])
command.extend(
['--page-size',
str(webkit_header.format).replace(',', '.')])
if parser_instance.localcontext.get('additional_args', False): if parser_instance.localcontext.get('additional_args', False):
for arg in parser_instance.localcontext['additional_args']: for arg in parser_instance.localcontext['additional_args']:
@ -143,10 +159,14 @@ class HeaderFooterTextWebKitParser(webkit_report.WebKitParser):
if not error_message: if not error_message:
error_message = _('No diagnosis message was provided') error_message = _('No diagnosis message was provided')
else: else:
error_message = _('The following diagnosis message was provided:\n') + error_message
error_message = _(
'The following diagnosis message was provided:\n') + \
error_message
if status: if status:
raise except_osv(_('Webkit error'), raise except_osv(_('Webkit error'),
_("The command 'wkhtmltopdf' failed with error code = %s. Message: %s") % (status, error_message))
_("The command 'wkhtmltopdf' failed with \
error code = %s. Message: %s") %
(status, error_message))
with open(out_filename, 'rb') as pdf_file: with open(out_filename, 'rb') as pdf_file:
pdf = pdf_file.read() pdf = pdf_file.read()
os.close(fd) os.close(fd)
@ -161,7 +181,8 @@ class HeaderFooterTextWebKitParser(webkit_report.WebKitParser):
return pdf return pdf
# override needed to keep the attachments' storing procedure # override needed to keep the attachments' storing procedure
def create_single_pdf(self, cursor, uid, ids, data, report_xml, context=None):
def create_single_pdf(self, cursor, uid, ids, data, report_xml,
context=None):
"""generate the PDF""" """generate the PDF"""
if context is None: if context is None:
@ -184,27 +205,30 @@ class HeaderFooterTextWebKitParser(webkit_report.WebKitParser):
template = False template = False
if report_xml.report_file: if report_xml.report_file:
path = addons.get_module_resource(*report_xml.report_file.split(os.path.sep))
path = addons.get_module_resource(
*report_xml.report_file.split(os.path.sep))
if os.path.exists(path): if os.path.exists(path):
template = file(path).read() template = file(path).read()
if not template and report_xml.report_webkit_data: if not template and report_xml.report_webkit_data:
template = report_xml.report_webkit_data template = report_xml.report_webkit_data
if not template: if not template:
raise except_osv(_('Error!'), _('Webkit Report template not found !'))
raise except_osv(
_('Error!'), _('Webkit Report template not found !'))
header = report_xml.webkit_header.html header = report_xml.webkit_header.html
if not header and report_xml.header: if not header and report_xml.header:
raise except_osv( raise except_osv(
_('No header defined for this Webkit report!'),
_('Please set a header in company settings.')
)
_('No header defined for this Webkit report!'),
_('Please set a header in company settings.')
)
css = report_xml.webkit_header.css css = report_xml.webkit_header.css
if not css: if not css:
css = '' css = ''
translate_call = partial(self.translate_call, parser_instance) translate_call = partial(self.translate_call, parser_instance)
#default_filters=['unicode', 'entity'] can be used to set global filter
# default_filters=['unicode', 'entity'] can be used to set global
# filter
body_mako_tpl = mako_template(template) body_mako_tpl = mako_template(template)
helper = WebKitHelper(cursor, uid, report_xml.id, context) helper = WebKitHelper(cursor, uid, report_xml.id, context)
if report_xml.precise_mode: if report_xml.precise_mode:

193
account_financial_report_webkit/wizard/balance_common.py

@ -47,6 +47,7 @@ def previous_year_date(date, nb_prev=1):
class AccountBalanceCommonWizard(orm.TransientModel): class AccountBalanceCommonWizard(orm.TransientModel):
"""Will launch trial balance report and pass required args""" """Will launch trial balance report and pass required args"""
_inherit = "account.common.account.report" _inherit = "account.common.account.report"
@ -66,53 +67,68 @@ class AccountBalanceCommonWizard(orm.TransientModel):
M2O_DYNAMIC_FIELDS = [f % index for f in ["comp%s_fiscalyear_id", M2O_DYNAMIC_FIELDS = [f % index for f in ["comp%s_fiscalyear_id",
"comp%s_period_from", "comp%s_period_from",
"comp%s_period_to"] "comp%s_period_to"]
for index in range(COMPARISON_LEVEL)]
for index in range(COMPARISON_LEVEL)]
SIMPLE_DYNAMIC_FIELDS = [f % index for f in ["comp%s_filter", SIMPLE_DYNAMIC_FIELDS = [f % index for f in ["comp%s_filter",
"comp%s_date_from", "comp%s_date_from",
"comp%s_date_to"] "comp%s_date_to"]
for index in range(COMPARISON_LEVEL)]
for index in range(COMPARISON_LEVEL)]
DYNAMIC_FIELDS = M2O_DYNAMIC_FIELDS + SIMPLE_DYNAMIC_FIELDS DYNAMIC_FIELDS = M2O_DYNAMIC_FIELDS + SIMPLE_DYNAMIC_FIELDS
def _get_account_ids(self, cr, uid, context=None): def _get_account_ids(self, cr, uid, context=None):
res = False res = False
if context.get('active_model', False) == 'account.account' and context.get('active_ids', False):
if context.get('active_model', False) == 'account.account' \
and context.get('active_ids', False):
res = context['active_ids'] res = context['active_ids']
return res return res
_columns = { _columns = {
'account_ids': fields.many2many('account.account', string='Filter on accounts',
help="Only selected accounts will be printed. Leave empty to print all accounts."),
'filter': fields.selection([('filter_no', 'No Filters'),
('filter_date', 'Date'),
('filter_period', 'Periods'),
('filter_opening', 'Opening Only')],
"Filter by",
required=True,
help='Filter by date: no opening balance will be displayed. '
'(opening balance can only be computed based on period to be correct).'),
'account_ids': fields.many2many(
'account.account', string='Filter on accounts',
help="Only selected accounts will be printed. Leave empty to \
print all accounts."),
'filter': fields.selection(
[('filter_no', 'No Filters'),
('filter_date', 'Date'),
('filter_period', 'Periods'),
('filter_opening', 'Opening Only')],
"Filter by",
required=True,
help='Filter by date: no opening balance will be displayed. '
'(opening balance can only be computed based on period to be \
correct).'),
} }
for index in range(COMPARISON_LEVEL): for index in range(COMPARISON_LEVEL):
_columns.update( _columns.update(
{"comp%s_filter" % index: fields.selection(COMPARE_SELECTION, string='Compare By', required=True),
"comp%s_fiscalyear_id" % index: fields.many2one('account.fiscalyear', 'Fiscal Year'),
"comp%s_period_from" % index: fields.many2one('account.period', 'Start Period'),
"comp%s_period_to" % index: fields.many2one('account.period', 'End Period'),
"comp%s_date_from" % index: fields.date("Start Date"),
"comp%s_date_to" % index: fields.date("End Date")})
{"comp%s_filter" % index:
fields.selection(
COMPARE_SELECTION, string='Compare By', required=True),
"comp%s_fiscalyear_id" % index:
fields.many2one('account.fiscalyear', 'Fiscal Year'),
"comp%s_period_from" % index:
fields.many2one('account.period', 'Start Period'),
"comp%s_period_to" % index:
fields.many2one('account.period', 'End Period'),
"comp%s_date_from" % index:
fields.date("Start Date"),
"comp%s_date_to" % index:
fields.date("End Date")})
_defaults = { _defaults = {
'account_ids': _get_account_ids, 'account_ids': _get_account_ids,
} }
def _check_fiscalyear(self, cr, uid, ids, context=None): def _check_fiscalyear(self, cr, uid, ids, context=None):
obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
obj = self.read(
cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no': if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no':
return False return False
return True return True
_constraints = [ _constraints = [
(_check_fiscalyear, 'When no Fiscal year is selected, you must choose to filter by periods or by date.', ['filter']),
(_check_fiscalyear,
'When no Fiscal year is selected, you must choose to filter by \
periods or by date.', ['filter']),
] ]
def default_get(self, cr, uid, fields, context=None): def default_get(self, cr, uid, fields, context=None):
@ -128,15 +144,19 @@ class AccountBalanceCommonWizard(orm.TransientModel):
@return: A dictionary which of fields with values. @return: A dictionary which of fields with values.
""" """
res = super(AccountBalanceCommonWizard, self).default_get(cr, uid, fields, context=context)
res = super(AccountBalanceCommonWizard, self).default_get(
cr, uid, fields, context=context)
for index in range(self.COMPARISON_LEVEL): for index in range(self.COMPARISON_LEVEL):
field = "comp%s_filter" % (index,) field = "comp%s_filter" % (index,)
if not res.get(field, False): if not res.get(field, False):
res[field] = 'filter_no' res[field] = 'filter_no'
return res return res
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
res = super(AccountBalanceCommonWizard, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu)
def fields_view_get(self, cr, uid, view_id=None, view_type='form',
context=None, toolbar=False, submenu=False):
res = super(AccountBalanceCommonWizard, self).fields_view_get(
cr, uid, view_id, view_type, context=context, toolbar=toolbar,
submenu=submenu)
res['fields'].update(self.fields_get(cr, uid, res['fields'].update(self.fields_get(cr, uid,
allfields=self.DYNAMIC_FIELDS, allfields=self.DYNAMIC_FIELDS,
@ -161,16 +181,23 @@ class AccountBalanceCommonWizard(orm.TransientModel):
modifiers_and_append(etree.Element( modifiers_and_append(etree.Element(
'field', 'field',
{'name': "comp%s_filter" % index, {'name': "comp%s_filter" % index,
'on_change': "onchange_comp_filter(%(index)s, filter, comp%(index)s_filter, fiscalyear_id, date_from, date_to)" % {'index': index}}))
'on_change': "onchange_comp_filter(%(index)s, filter,\
comp%(index)s_filter, fiscalyear_id, date_from, date_to)"
% {'index': index}}))
modifiers_and_append(etree.Element( modifiers_and_append(etree.Element(
'field', 'field',
{'name': "comp%s_fiscalyear_id" % index, {'name': "comp%s_fiscalyear_id" % index,
'attrs': 'attrs':
"{'required': [('comp%(index)s_filter','in',('filter_year','filter_opening'))]," \
" 'invisible': [('comp%(index)s_filter','not in',('filter_year','filter_opening'))]}" % {'index': index}}))
dates_attrs = "{'required': [('comp%(index)s_filter','=','filter_date')], " \
" 'invisible': [('comp%(index)s_filter','!=','filter_date')]}" % {'index': index}
"{'required': [('comp%(index)s_filter','in',\
('filter_year','filter_opening'))],"
" 'invisible': [('comp%(index)s_filter','not in',\
('filter_year','filter_opening'))]}" % {'index': index}}))
dates_attrs = "{'required': [('comp%(index)s_filter','=',\
'filter_date')], " \
" 'invisible': [('comp%(index)s_filter','!=',\
'filter_date')]}" % {
'index': index}
modifiers_and_append(etree.Element( modifiers_and_append(etree.Element(
'separator', 'separator',
{'string': _('Dates'), {'string': _('Dates'),
@ -185,8 +212,11 @@ class AccountBalanceCommonWizard(orm.TransientModel):
{'name': "comp%s_date_to" % index, {'name': "comp%s_date_to" % index,
'attrs': dates_attrs})) 'attrs': dates_attrs}))
periods_attrs = "{'required': [('comp%(index)s_filter','=','filter_period')]," \
" 'invisible': [('comp%(index)s_filter','!=','filter_period')]}" % {'index': index}
periods_attrs = "{'required': [('comp%(index)s_filter','=',\
'filter_period')]," \
" 'invisible': [('comp%(index)s_filter','!=',\
'filter_period')]}" % {
'index': index}
periods_domain = "[('special', '=', False)]" periods_domain = "[('special', '=', False)]"
modifiers_and_append(etree.Element( modifiers_and_append(etree.Element(
'separator', 'separator',
@ -209,24 +239,34 @@ class AccountBalanceCommonWizard(orm.TransientModel):
res['arch'] = etree.tostring(eview) res['arch'] = etree.tostring(eview)
return res return res
def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):
def onchange_filter(self, cr, uid, ids, filter='filter_no',
fiscalyear_id=False, context=None):
res = {} res = {}
if filter == 'filter_no': if filter == 'filter_no':
res['value'] = {'period_from': False, 'period_to': False, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': False,
'period_to': False,
'date_from': False,
'date_to': False}
if filter == 'filter_date': if filter == 'filter_date':
if fiscalyear_id: if fiscalyear_id:
fyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id, context=context)
fyear = self.pool.get('account.fiscalyear').browse(
cr, uid, fiscalyear_id, context=context)
date_from = fyear.date_start date_from = fyear.date_start
date_to = fyear.date_stop > time.strftime('%Y-%m-%d') and time.strftime('%Y-%m-%d') or fyear.date_stop
date_to = fyear.date_stop > time.strftime(
'%Y-%m-%d') and time.strftime('%Y-%m-%d') \
or fyear.date_stop
else: else:
date_from, date_to = time.strftime('%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = {'period_from': False, 'period_to': False, 'date_from': date_from, 'date_to': date_to}
date_from, date_to = time.strftime(
'%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = {'period_from': False, 'period_to':
False, 'date_from': date_from, 'date_to': date_to}
if filter == 'filter_period' and fiscalyear_id: if filter == 'filter_period' and fiscalyear_id:
start_period = end_period = False start_period = end_period = False
cr.execute(''' cr.execute('''
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_start ASC ORDER BY p.date_start ASC
@ -234,31 +274,41 @@ class AccountBalanceCommonWizard(orm.TransientModel):
UNION ALL UNION ALL
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND p.date_start < NOW() AND p.date_start < NOW()
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_stop DESC ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
LIMIT 1) AS period_stop''',
(fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()] periods = [i[0] for i in cr.fetchall()]
if periods: if periods:
start_period = end_period = periods[0] start_period = end_period = periods[0]
if len(periods) > 1: if len(periods) > 1:
end_period = periods[1] end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': start_period, 'period_to':
end_period, 'date_from': False, 'date_to': False}
return res return res
def onchange_comp_filter(self, cr, uid, ids, index, main_filter='filter_no', comp_filter='filter_no', fiscalyear_id=False, start_date=False, stop_date=False, context=None):
def onchange_comp_filter(self, cr, uid, ids, index,
main_filter='filter_no', comp_filter='filter_no',
fiscalyear_id=False, start_date=False,
stop_date=False, context=None):
res = {} res = {}
fy_obj = self.pool.get('account.fiscalyear') fy_obj = self.pool.get('account.fiscalyear')
last_fiscalyear_id = False last_fiscalyear_id = False
if fiscalyear_id: if fiscalyear_id:
fiscalyear = fy_obj.browse(cr, uid, fiscalyear_id, context=context) fiscalyear = fy_obj.browse(cr, uid, fiscalyear_id, context=context)
last_fiscalyear_ids = fy_obj.search(cr, uid, [('date_stop', '<', fiscalyear.date_start)],
limit=self.COMPARISON_LEVEL, order='date_start desc', context=context)
last_fiscalyear_ids = fy_obj.search(
cr, uid, [('date_stop', '<', fiscalyear.date_start)],
limit=self.COMPARISON_LEVEL, order='date_start desc',
context=context)
if last_fiscalyear_ids: if last_fiscalyear_ids:
if len(last_fiscalyear_ids) > index: if len(last_fiscalyear_ids) > index:
last_fiscalyear_id = last_fiscalyear_ids[index] # first element for the comparison 1, second element for the comparison 2
# first element for the comparison 1, second element for
# the comparison 2
last_fiscalyear_id = last_fiscalyear_ids[index]
fy_id_field = "comp%s_fiscalyear_id" % (index,) fy_id_field = "comp%s_fiscalyear_id" % (index,)
period_from_field = "comp%s_period_from" % (index,) period_from_field = "comp%s_period_from" % (index,)
@ -268,37 +318,46 @@ class AccountBalanceCommonWizard(orm.TransientModel):
if comp_filter == 'filter_no': if comp_filter == 'filter_no':
res['value'] = { res['value'] = {
fy_id_field: False,
period_from_field: False,
period_to_field: False,
date_from_field: False,
date_to_field: False
}
fy_id_field: False,
period_from_field: False,
period_to_field: False,
date_from_field: False,
date_to_field: False
}
if comp_filter in ('filter_year', 'filter_opening'): if comp_filter in ('filter_year', 'filter_opening'):
res['value'] = { res['value'] = {
fy_id_field: last_fiscalyear_id,
period_from_field: False,
period_to_field: False,
date_from_field: False,
date_to_field: False
}
fy_id_field: last_fiscalyear_id,
period_from_field: False,
period_to_field: False,
date_from_field: False,
date_to_field: False
}
if comp_filter == 'filter_date': if comp_filter == 'filter_date':
dates = {} dates = {}
if main_filter == 'filter_date': if main_filter == 'filter_date':
dates = { dates = {
'date_start': previous_year_date(start_date, index + 1).strftime('%Y-%m-%d'),
'date_stop': previous_year_date(stop_date, index + 1).strftime('%Y-%m-%d'),
}
'date_start': previous_year_date(start_date, index + 1).
strftime('%Y-%m-%d'),
'date_stop': previous_year_date(stop_date, index + 1).
strftime('%Y-%m-%d'),
}
elif last_fiscalyear_id: elif last_fiscalyear_id:
dates = fy_obj.read(cr, uid, last_fiscalyear_id, ['date_start', 'date_stop'], context=context)
dates = fy_obj.read(
cr, uid, last_fiscalyear_id, ['date_start', 'date_stop'],
context=context)
res['value'] = {fy_id_field: False, period_from_field: False, period_to_field: False, date_from_field: dates.get('date_start', False), date_to_field: dates.get('date_stop', False)}
res['value'] = {fy_id_field: False,
period_from_field: False,
period_to_field: False,
date_from_field: dates.get('date_start', False),
date_to_field: dates.get('date_stop', False)}
if comp_filter == 'filter_period' and last_fiscalyear_id: if comp_filter == 'filter_period' and last_fiscalyear_id:
start_period = end_period = False start_period = end_period = False
cr.execute(''' cr.execute('''
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %(fiscalyear)s WHERE f.id = %(fiscalyear)s
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_start ASC ORDER BY p.date_start ASC
@ -306,12 +365,14 @@ class AccountBalanceCommonWizard(orm.TransientModel):
UNION ALL UNION ALL
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %(fiscalyear)s WHERE f.id = %(fiscalyear)s
AND p.date_start < NOW() AND p.date_start < NOW()
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_stop DESC ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', {'fiscalyear': last_fiscalyear_id})
LIMIT 1) AS period_stop''',
{'fiscalyear': last_fiscalyear_id})
periods = [i[0] for i in cr.fetchall()] periods = [i[0] for i in cr.fetchall()]
if periods and len(periods) > 1: if periods and len(periods) > 1:
start_period = end_period = periods[0] start_period = end_period = periods[0]

78
account_financial_report_webkit/wizard/general_ledger_wizard.py

@ -25,6 +25,7 @@ from openerp.osv import fields, orm
class AccountReportGeneralLedgerWizard(orm.TransientModel): class AccountReportGeneralLedgerWizard(orm.TransientModel):
"""Will launch general ledger report and pass required args""" """Will launch general ledger report and pass required args"""
_inherit = "account.common.account.report" _inherit = "account.common.account.report"
@ -33,7 +34,8 @@ class AccountReportGeneralLedgerWizard(orm.TransientModel):
def _get_account_ids(self, cr, uid, context=None): def _get_account_ids(self, cr, uid, context=None):
res = False res = False
if context.get('active_model', False) == 'account.account' and context.get('active_ids', False):
if context.get('active_model', False) == 'account.account' \
and context.get('active_ids', False):
res = context['active_ids'] res = context['active_ids']
return res return res
@ -41,13 +43,18 @@ class AccountReportGeneralLedgerWizard(orm.TransientModel):
'amount_currency': fields.boolean("With Currency", 'amount_currency': fields.boolean("With Currency",
help="It adds the currency column"), help="It adds the currency column"),
'display_account': fields.selection([('bal_all', 'All'),
('bal_mix', 'With transactions or non zero balance')],
'Display accounts',
required=True),
'account_ids': fields.many2many('account.account', string='Filter on accounts',
help="""Only selected accounts will be printed. Leave empty to print all accounts."""),
'centralize': fields.boolean('Activate Centralization', help='Uncheck to display all the details of centralized accounts.')
'display_account': fields.selection(
[('bal_all', 'All'),
('bal_mix', 'With transactions or non zero balance')],
'Display accounts',
required=True),
'account_ids': fields.many2many(
'account.account', string='Filter on accounts',
help="""Only selected accounts will be printed. Leave empty to
print all accounts."""),
'centralize': fields.boolean(
'Activate Centralization',
help='Uncheck to display all the details of centralized accounts.')
} }
_defaults = { _defaults = {
'amount_currency': False, 'amount_currency': False,
@ -57,17 +64,21 @@ class AccountReportGeneralLedgerWizard(orm.TransientModel):
} }
def _check_fiscalyear(self, cr, uid, ids, context=None): def _check_fiscalyear(self, cr, uid, ids, context=None):
obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
obj = self.read(
cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no': if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no':
return False return False
return True return True
_constraints = [ _constraints = [
(_check_fiscalyear, 'When no Fiscal year is selected, you must choose to filter by periods or by date.', ['filter']),
(_check_fiscalyear,
'When no Fiscal year is selected, you must choose to filter by \
periods or by date.', ['filter']),
] ]
def pre_print_report(self, cr, uid, ids, data, context=None): def pre_print_report(self, cr, uid, ids, data, context=None):
data = super(AccountReportGeneralLedgerWizard, self).pre_print_report(cr, uid, ids, data, context)
data = super(AccountReportGeneralLedgerWizard, self).pre_print_report(
cr, uid, ids, data, context)
# will be used to attach the report on the main account # will be used to attach the report on the main account
data['ids'] = [data['form']['chart_account_id']] data['ids'] = [data['form']['chart_account_id']]
vals = self.read(cr, uid, ids, vals = self.read(cr, uid, ids,
@ -79,34 +90,40 @@ class AccountReportGeneralLedgerWizard(orm.TransientModel):
data['form'].update(vals) data['form'].update(vals)
return data return data
def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):
def onchange_filter(self, cr, uid, ids, filter='filter_no',
fiscalyear_id=False, context=None):
res = {} res = {}
if filter == 'filter_no': if filter == 'filter_no':
res['value'] = { res['value'] = {
'period_from': False,
'period_to': False,
'date_from': False,
'date_to': False,
}
'period_from': False,
'period_to': False,
'date_from': False,
'date_to': False,
}
if filter == 'filter_date': if filter == 'filter_date':
if fiscalyear_id: if fiscalyear_id:
fyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id, context=context)
fyear = self.pool.get('account.fiscalyear').browse(
cr, uid, fiscalyear_id, context=context)
date_from = fyear.date_start date_from = fyear.date_start
date_to = fyear.date_stop > time.strftime('%Y-%m-%d') and time.strftime('%Y-%m-%d') or fyear.date_stop
date_to = fyear.date_stop > time.strftime(
'%Y-%m-%d') and time.strftime('%Y-%m-%d') \
or fyear.date_stop
else: else:
date_from, date_to = time.strftime('%Y-01-01'), time.strftime('%Y-%m-%d')
date_from, date_to = time.strftime(
'%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = { res['value'] = {
'period_from': False,
'period_to': False,
'date_from': date_from,
'date_to': date_to
}
'period_from': False,
'period_to': False,
'date_from': date_from,
'date_to': date_to
}
if filter == 'filter_period' and fiscalyear_id: if filter == 'filter_period' and fiscalyear_id:
start_period = end_period = False start_period = end_period = False
cr.execute(''' cr.execute('''
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_start ASC ORDER BY p.date_start ASC
@ -114,18 +131,21 @@ class AccountReportGeneralLedgerWizard(orm.TransientModel):
UNION ALL UNION ALL
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND p.date_start < NOW() AND p.date_start < NOW()
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_stop DESC ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
LIMIT 1) AS period_stop''',
(fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()] periods = [i[0] for i in cr.fetchall()]
if periods: if periods:
start_period = end_period = periods[0] start_period = end_period = periods[0]
if len(periods) > 1: if len(periods) > 1:
end_period = periods[1] end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': start_period, 'period_to':
end_period, 'date_from': False, 'date_to': False}
return res return res
def _print_report(self, cursor, uid, ids, data, context=None): def _print_report(self, cursor, uid, ids, data, context=None):

103
account_financial_report_webkit/wizard/open_invoices_wizard.py

@ -22,6 +22,7 @@ from openerp.osv import fields, orm
class AccountReportOpenInvoicesWizard(orm.TransientModel): class AccountReportOpenInvoicesWizard(orm.TransientModel):
"""Will launch partner ledger report and pass required args""" """Will launch partner ledger report and pass required args"""
_inherit = "partners.ledger.webkit" _inherit = "partners.ledger.webkit"
@ -30,20 +31,27 @@ class AccountReportOpenInvoicesWizard(orm.TransientModel):
_columns = { _columns = {
'group_by_currency': fields.boolean('Group Partner by currency'), 'group_by_currency': fields.boolean('Group Partner by currency'),
'until_date': fields.date("Clearance date",
required=True,
help="""The clearance date is essentially a tool used for debtors provisionning calculation.
By default, this date is equal to the the end date (ie: 31/12/2011 if you select fy 2011).
By amending the clearance date, you will be, for instance, able to answer the question : 'based on my last year end debtors open invoices, which invoices are still unpaid today (today is my clearance date)?'
'until_date': fields.date(
"Clearance date",
required=True,
help="""The clearance date is essentially a tool used for debtors
provisionning calculation.
By default, this date is equal to the the end date (ie: 31/12/2011 if you
select fy 2011).
By amending the clearance date, you will be, for instance, able to answer the
question : 'based on my last year end debtors open invoices, which invoices
are still unpaid today (today is my clearance date)?'
""")} """)}
def _check_until_date(self, cr, uid, ids, context=None): def _check_until_date(self, cr, uid, ids, context=None):
def get_key_id(obj, field): def get_key_id(obj, field):
return obj.get(field) and obj[field][0] or False return obj.get(field) and obj[field][0] or False
obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'period_to', 'date_to', 'until_date'], context=context)
obj = self.read(cr, uid, ids[0], [
'fiscalyear_id', 'period_to', 'date_to', 'until_date'],
context=context)
min_date = self.default_until_date(cr, uid, ids, min_date = self.default_until_date(cr, uid, ids,
get_key_id(obj, 'fiscalyear_id'), get_key_id(obj, 'fiscalyear_id'),
get_key_id(obj, 'period_to'), get_key_id(obj, 'period_to'),
@ -54,59 +62,78 @@ By amending the clearance date, you will be, for instance, able to answer the qu
return True return True
_constraints = [ _constraints = [
(_check_until_date, 'Clearance date must be the very last date of the last period or later.', ['until_date']),
(_check_until_date, 'Clearance date must be the very last date of the \
last period or later.', ['until_date']),
] ]
def default_until_date(self, cr, uid, ids, fiscalyear_id=False, period_id=False, date_to=False, context=None):
def default_until_date(self, cr, uid, ids, fiscalyear_id=False,
period_id=False, date_to=False, context=None):
res_date = False res_date = False
# first priority: period or date filters # first priority: period or date filters
if period_id: if period_id:
res_date = self.pool.get('account.period').read(cr, uid, period_id, ['date_stop'], context=context)['date_stop']
res_date = self.pool.get('account.period').read(
cr, uid, period_id, ['date_stop'],
context=context)['date_stop']
elif date_to: elif date_to:
res_date = date_to res_date = date_to
elif fiscalyear_id: elif fiscalyear_id:
res_date = self.pool.get('account.fiscalyear').read(cr, uid, fiscalyear_id, ['date_stop'], context=context)['date_stop']
res_date = self.pool.get('account.fiscalyear').read(
cr, uid, fiscalyear_id, ['date_stop'],
context=context)['date_stop']
return res_date return res_date
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear=False, period_id=False, date_to=False, until_date=False, context=None):
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear=False,
period_id=False, date_to=False, until_date=False,
context=None):
res = {'value': {}} res = {'value': {}}
res['value']['until_date'] = self.default_until_date(cr, uid, ids,
fiscalyear_id=fiscalyear,
period_id=period_id,
date_to=date_to,
context=context)
res['value']['until_date'] = self.default_until_date(
cr, uid, ids,
fiscalyear_id=fiscalyear,
period_id=period_id,
date_to=date_to,
context=context)
return res return res
def onchange_date_to(self, cr, uid, ids, fiscalyear=False, period_id=False, date_to=False, until_date=False, context=None):
def onchange_date_to(self, cr, uid, ids, fiscalyear=False, period_id=False,
date_to=False, until_date=False, context=None):
res = {'value': {}} res = {'value': {}}
res['value']['until_date'] = self.default_until_date(cr, uid, ids,
fiscalyear_id=fiscalyear,
period_id=period_id,
date_to=date_to,
context=context)
res['value']['until_date'] = self.default_until_date(
cr, uid, ids,
fiscalyear_id=fiscalyear,
period_id=period_id,
date_to=date_to,
context=context)
return res return res
def onchange_period_to(self, cr, uid, ids, fiscalyear=False, period_id=False, date_to=False, until_date=False, context=None):
def onchange_period_to(self, cr, uid, ids, fiscalyear=False,
period_id=False, date_to=False, until_date=False,
context=None):
res = {'value': {}} res = {'value': {}}
res['value']['until_date'] = self.default_until_date(cr, uid, ids,
fiscalyear_id=fiscalyear,
period_id=period_id,
date_to=date_to,
context=context)
res['value']['until_date'] = self.default_until_date(
cr, uid, ids,
fiscalyear_id=fiscalyear,
period_id=period_id,
date_to=date_to,
context=context)
return res return res
def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):
res = super(AccountReportOpenInvoicesWizard, self).onchange_filter(cr, uid, ids, filter=filter, fiscalyear_id=fiscalyear_id, context=context)
def onchange_filter(self, cr, uid, ids, filter='filter_no',
fiscalyear_id=False, context=None):
res = super(AccountReportOpenInvoicesWizard, self).onchange_filter(
cr, uid, ids, filter=filter, fiscalyear_id=fiscalyear_id,
context=context)
if res.get('value', False): if res.get('value', False):
res['value']['until_date'] = self.default_until_date(cr, uid, ids,
fiscalyear_id=fiscalyear_id,
period_id=res['value'].get('period_to', False),
date_to=res['value'].get('date_to', False),
context=context)
res['value']['until_date'] = self.default_until_date(
cr, uid, ids,
fiscalyear_id=fiscalyear_id,
period_id=res['value'].get('period_to', False),
date_to=res['value'].get('date_to', False),
context=context)
return res return res
def pre_print_report(self, cr, uid, ids, data, context=None): def pre_print_report(self, cr, uid, ids, data, context=None):
data = super(AccountReportOpenInvoicesWizard, self).pre_print_report(cr, uid, ids, data, context)
data = super(AccountReportOpenInvoicesWizard, self).pre_print_report(
cr, uid, ids, data, context)
vals = self.read(cr, uid, ids, vals = self.read(cr, uid, ids,
['until_date', 'group_by_currency'], ['until_date', 'group_by_currency'],
context=context)[0] context=context)[0]

19
account_financial_report_webkit/wizard/partner_balance_wizard.py

@ -23,6 +23,7 @@ from openerp.osv import fields, orm
class AccountPartnerBalanceWizard(orm.TransientModel): class AccountPartnerBalanceWizard(orm.TransientModel):
"""Will launch partner balance report and pass required args""" """Will launch partner balance report and pass required args"""
_inherit = "account.common.balance.report" _inherit = "account.common.balance.report"
@ -30,12 +31,15 @@ class AccountPartnerBalanceWizard(orm.TransientModel):
_description = "Partner Balance Report" _description = "Partner Balance Report"
_columns = { _columns = {
'result_selection': fields.selection([('customer', 'Receivable Accounts'),
('supplier', 'Payable Accounts'),
('customer_supplier', 'Receivable and Payable Accounts')],
"Partner's", required=True),
'partner_ids': fields.many2many('res.partner', string='Filter on partner',
help="Only selected partners will be printed. Leave empty to print all partners."),
'result_selection': fields.selection(
[('customer', 'Receivable Accounts'),
('supplier', 'Payable Accounts'),
('customer_supplier', 'Receivable and Payable Accounts')],
"Partner's", required=True),
'partner_ids': fields.many2many(
'res.partner', string='Filter on partner',
help="Only selected partners will be printed. \
Leave empty to print all partners."),
} }
_defaults = { _defaults = {
@ -43,7 +47,8 @@ class AccountPartnerBalanceWizard(orm.TransientModel):
} }
def pre_print_report(self, cr, uid, ids, data, context=None): def pre_print_report(self, cr, uid, ids, data, context=None):
data = super(AccountPartnerBalanceWizard, self).pre_print_report(cr, uid, ids, data, context)
data = super(AccountPartnerBalanceWizard, self).\
pre_print_report(cr, uid, ids, data, context)
vals = self.read(cr, uid, ids, vals = self.read(cr, uid, ids,
['result_selection', 'partner_ids'], ['result_selection', 'partner_ids'],
context=context)[0] context=context)[0]

60
account_financial_report_webkit/wizard/partners_ledger_wizard.py

@ -24,6 +24,7 @@ from openerp.osv import fields, orm
class AccountReportPartnersLedgerWizard(orm.TransientModel): class AccountReportPartnersLedgerWizard(orm.TransientModel):
"""Will launch partner ledger report and pass required args""" """Will launch partner ledger report and pass required args"""
_inherit = "account.common.partner.report" _inherit = "account.common.partner.report"
@ -33,14 +34,18 @@ class AccountReportPartnersLedgerWizard(orm.TransientModel):
_columns = { _columns = {
'amount_currency': fields.boolean("With Currency", 'amount_currency': fields.boolean("With Currency",
help="It adds the currency column"), help="It adds the currency column"),
'partner_ids': fields.many2many('res.partner', string='Filter on partner',
help="Only selected partners will be printed. "
"Leave empty to print all partners."),
'filter': fields.selection([('filter_no', 'No Filters'),
('filter_date', 'Date'),
('filter_period', 'Periods')], "Filter by", required=True,
help='Filter by date: no opening balance will be displayed. '
'(opening balance can only be computed based on period to be correct).'),
'partner_ids': fields.many2many(
'res.partner',
string='Filter on partner',
help="Only selected partners will be printed. "
"Leave empty to print all partners."),
'filter': fields.selection(
[('filter_no', 'No Filters'),
('filter_date', 'Date'),
('filter_period', 'Periods')], "Filter by", required=True,
help='Filter by date: no opening balance will be displayed. '
'(opening balance can only be computed based on period to be \
correct).'),
} }
_defaults = { _defaults = {
'amount_currency': False, 'amount_currency': False,
@ -48,7 +53,8 @@ class AccountReportPartnersLedgerWizard(orm.TransientModel):
} }
def _check_fiscalyear(self, cr, uid, ids, context=None): def _check_fiscalyear(self, cr, uid, ids, context=None):
obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
obj = self.read(
cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no': if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no':
return False return False
return True return True
@ -60,25 +66,35 @@ class AccountReportPartnersLedgerWizard(orm.TransientModel):
['filter']), ['filter']),
] ]
def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):
def onchange_filter(self, cr, uid, ids, filter='filter_no',
fiscalyear_id=False, context=None):
res = {} res = {}
if filter == 'filter_no': if filter == 'filter_no':
res['value'] = {'period_from': False, 'period_to': False, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': False,
'period_to': False,
'date_from': False,
'date_to': False}
if filter == 'filter_date': if filter == 'filter_date':
if fiscalyear_id: if fiscalyear_id:
fyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id, context=context)
fyear = self.pool.get('account.fiscalyear').browse(
cr, uid, fiscalyear_id, context=context)
date_from = fyear.date_start date_from = fyear.date_start
date_to = fyear.date_stop > time.strftime('%Y-%m-%d') and time.strftime('%Y-%m-%d') or fyear.date_stop
date_to = fyear.date_stop > time.strftime(
'%Y-%m-%d') and time.strftime('%Y-%m-%d') \
or fyear.date_stop
else: else:
date_from, date_to = time.strftime('%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = {'period_from': False, 'period_to': False, 'date_from': date_from, 'date_to': date_to}
date_from, date_to = time.strftime(
'%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = {'period_from': False, 'period_to':
False, 'date_from': date_from, 'date_to': date_to}
if filter == 'filter_period' and fiscalyear_id: if filter == 'filter_period' and fiscalyear_id:
start_period = end_period = False start_period = end_period = False
cr.execute(''' cr.execute('''
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_start ASC ORDER BY p.date_start ASC
@ -86,22 +102,26 @@ class AccountReportPartnersLedgerWizard(orm.TransientModel):
UNION ALL UNION ALL
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND p.date_start < NOW() AND p.date_start < NOW()
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_stop DESC ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
LIMIT 1) AS period_stop''',
(fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()] periods = [i[0] for i in cr.fetchall()]
if periods: if periods:
start_period = end_period = periods[0] start_period = end_period = periods[0]
if len(periods) > 1: if len(periods) > 1:
end_period = periods[1] end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': start_period, 'period_to':
end_period, 'date_from': False, 'date_to': False}
return res return res
def pre_print_report(self, cr, uid, ids, data, context=None): def pre_print_report(self, cr, uid, ids, data, context=None):
data = super(AccountReportPartnersLedgerWizard, self).pre_print_report(cr, uid, ids, data, context)
data = super(AccountReportPartnersLedgerWizard, self).pre_print_report(
cr, uid, ids, data, context)
if context is None: if context is None:
context = {} context = {}
# will be used to attach the report on the main account # will be used to attach the report on the main account

63
account_financial_report_webkit/wizard/print_journal.py

@ -7,13 +7,13 @@
# #
# This file is a part of account_financial_report_webkit # This file is a part of account_financial_report_webkit
# #
# account_financial_report_webkit is free software: you can redistribute it and/or modify
# 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.
# account_financial_report_webkit is free software: you can redistribute it
# and/or modify 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.
# #
# account_financial_report_webkit is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# account_financial_report_webkit 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 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details. # GNU Affero General Public License for more details.
# #
@ -24,10 +24,10 @@
from openerp.osv import fields, orm from openerp.osv import fields, orm
import time import time
from lxml import etree
class AccountReportPrintJournalWizard(orm.TransientModel): class AccountReportPrintJournalWizard(orm.TransientModel):
"""Will launch print journal report and pass requiered args""" """Will launch print journal report and pass requiered args"""
_inherit = "account.common.account.report" _inherit = "account.common.account.report"
@ -35,7 +35,8 @@ class AccountReportPrintJournalWizard(orm.TransientModel):
_description = "Journals Report" _description = "Journals Report"
_columns = { _columns = {
'amount_currency': fields.boolean("With Currency", help="It adds the currency column"),
'amount_currency': fields.boolean("With Currency",
help="It adds the currency column"),
} }
_defaults = { _defaults = {
@ -45,17 +46,20 @@ class AccountReportPrintJournalWizard(orm.TransientModel):
} }
def _check_fiscalyear(self, cr, uid, ids, context=None): def _check_fiscalyear(self, cr, uid, ids, context=None):
obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'filter'],
context=context)
if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no': if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no':
return False return False
return True return True
_constraints = [ _constraints = [
(_check_fiscalyear, 'When no Fiscal year is selected, you must choose to filter by periods or by date.', ['filter']),
(_check_fiscalyear, 'When no Fiscal year is selected, you must choose \
to filter by periods or by date.', ['filter']),
] ]
def pre_print_report(self, cr, uid, ids, data, context=None): def pre_print_report(self, cr, uid, ids, data, context=None):
data = super(AccountReportPrintJournalWizard, self).pre_print_report(cr, uid, ids, data, context)
data = super(AccountReportPrintJournalWizard, self).\
pre_print_report(cr, uid, ids, data, context)
# will be used to attach the report on the main account # will be used to attach the report on the main account
data['ids'] = [data['form']['chart_account_id']] data['ids'] = [data['form']['chart_account_id']]
vals = self.read(cr, uid, ids, vals = self.read(cr, uid, ids,
@ -66,24 +70,34 @@ class AccountReportPrintJournalWizard(orm.TransientModel):
data['form'].update(vals) data['form'].update(vals)
return data return data
def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):
def onchange_filter(self, cr, uid, ids, filter='filter_no',
fiscalyear_id=False, context=None):
res = {} res = {}
if filter == 'filter_no': if filter == 'filter_no':
res['value'] = {'period_from': False, 'period_to': False, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': False,
'period_to': False,
'date_from': False,
'date_to': False}
if filter == 'filter_date': if filter == 'filter_date':
if fiscalyear_id: if fiscalyear_id:
fyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id, context=context)
fyear = self.pool.get('account.fiscalyear').browse(
cr, uid, fiscalyear_id, context=context)
date_from = fyear.date_start date_from = fyear.date_start
date_to = fyear.date_stop > time.strftime('%Y-%m-%d') and time.strftime('%Y-%m-%d') or fyear.date_stop
date_to = fyear.date_stop > time.strftime(
'%Y-%m-%d') and time.strftime('%Y-%m-%d') \
or fyear.date_stop
else: else:
date_from, date_to = time.strftime('%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = {'period_from': False, 'period_to': False, 'date_from': date_from, 'date_to': date_to}
date_from, date_to = time.strftime(
'%Y-01-01'), time.strftime('%Y-%m-%d')
res['value'] = {'period_from': False, 'period_to':
False, 'date_from': date_from, 'date_to': date_to}
if filter == 'filter_period' and fiscalyear_id: if filter == 'filter_period' and fiscalyear_id:
start_period = end_period = False start_period = end_period = False
cr.execute(''' cr.execute('''
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_start ASC ORDER BY p.date_start ASC
@ -91,18 +105,21 @@ class AccountReportPrintJournalWizard(orm.TransientModel):
UNION ALL UNION ALL
SELECT * FROM (SELECT p.id SELECT * FROM (SELECT p.id
FROM account_period p FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
LEFT JOIN account_fiscalyear f
ON (p.fiscalyear_id = f.id)
WHERE f.id = %s WHERE f.id = %s
AND p.date_start < NOW() AND p.date_start < NOW()
AND COALESCE(p.special, FALSE) = FALSE AND COALESCE(p.special, FALSE) = FALSE
ORDER BY p.date_stop DESC ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
LIMIT 1) AS period_stop''',
(fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()] periods = [i[0] for i in cr.fetchall()]
if periods: if periods:
start_period = end_period = periods[0] start_period = end_period = periods[0]
if len(periods) > 1: if len(periods) > 1:
end_period = periods[1] end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period, 'date_from': False, 'date_to': False}
res['value'] = {'period_from': start_period, 'period_to':
end_period, 'date_from': False, 'date_to': False}
return res return res
def _print_report(self, cursor, uid, ids, data, context=None): def _print_report(self, cursor, uid, ids, data, context=None):
@ -112,7 +129,3 @@ class AccountReportPrintJournalWizard(orm.TransientModel):
return {'type': 'ir.actions.report.xml', return {'type': 'ir.actions.report.xml',
'report_name': 'account.account_report_print_journal_webkit', 'report_name': 'account.account_report_print_journal_webkit',
'datas': data} 'datas': data}
AccountReportPrintJournalWizard()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

2
account_financial_report_webkit/wizard/trial_balance_wizard.py

@ -37,5 +37,3 @@ class AccountTrialBalanceWizard(orm.TransientModel):
return {'type': 'ir.actions.report.xml', return {'type': 'ir.actions.report.xml',
'report_name': 'account.account_report_trial_balance_webkit', 'report_name': 'account.account_report_trial_balance_webkit',
'datas': data} 'datas': data}
AccountTrialBalanceWizard()

4
account_financial_report_webkit_xls/__init__.py

@ -25,5 +25,5 @@ try:
from . import report from . import report
except ImportError: except ImportError:
import logging import logging
logging.getLogger('openerp.module').warning('report_xls not available in addons path. account_financial_report_webkit_xls will not be usable')
logging.getLogger('openerp.module').warning('''report_xls not available in
addons path. account_financial_report_webkit_xls will not be usable''')

13
account_financial_report_webkit_xls/__openerp__.py

@ -25,7 +25,7 @@
'license': 'AGPL-3', 'license': 'AGPL-3',
'author': 'Noviat', 'author': 'Noviat',
'category': 'Generic Modules/Accounting', 'category': 'Generic Modules/Accounting',
'description': """
'description': """
This module adds XLS export to the following accounting reports: This module adds XLS export to the following accounting reports:
- general ledger - general ledger
@ -33,14 +33,13 @@
- partner ledger - partner ledger
- partner balance - partner balance
- open invoices - open invoices
""", """,
'depends': ['report_xls', 'account_financial_report_webkit'], 'depends': ['report_xls', 'account_financial_report_webkit'],
'demo_xml': [],
'init_xml': [],
'update_xml' : [
'wizard/general_ledger_wizard_view.xml',
'wizard/trial_balance_wizard_view.xml',
'demo': [],
'data': [
'wizard/general_ledger_wizard_view.xml',
'wizard/trial_balance_wizard_view.xml',
'wizard/partners_ledger_wizard_view.xml', 'wizard/partners_ledger_wizard_view.xml',
'wizard/partners_balance_wizard_view.xml', 'wizard/partners_balance_wizard_view.xml',
'wizard/open_invoices_wizard_view.xml', 'wizard/open_invoices_wizard_view.xml',

2
account_financial_report_webkit_xls/report/__init__.py

@ -25,5 +25,3 @@ from . import trial_balance_xls
from . import partners_balance_xls from . import partners_balance_xls
from . import partner_ledger_xls from . import partner_ledger_xls
from . import open_invoices_xls from . import open_invoices_xls
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

259
account_financial_report_webkit_xls/report/general_ledger_xls.py

@ -21,15 +21,14 @@
############################################################################## ##############################################################################
import xlwt import xlwt
import time
from datetime import datetime from datetime import datetime
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell from openerp.addons.report_xls.utils import rowcol_to_cell
from openerp.addons.account_financial_report_webkit.report.general_ledger import GeneralLedgerWebkit
from openerp.addons.account_financial_report_webkit.report.general_ledger \
import GeneralLedgerWebkit
from openerp.tools.translate import _ from openerp.tools.translate import _
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
_column_sizes = [ _column_sizes = [
('date', 12), ('date', 12),
@ -40,47 +39,55 @@ _column_sizes = [
('partner', 30), ('partner', 30),
('label', 45), ('label', 45),
('counterpart', 30), ('counterpart', 30),
('debit', 15),
('debit', 15),
('credit', 15), ('credit', 15),
('cumul_bal', 15), ('cumul_bal', 15),
('curr_bal', 15),
('curr_bal', 15),
('curr_code', 7), ('curr_code', 7),
] ]
class general_ledger_xls(report_xls): class general_ledger_xls(report_xls):
column_sizes = [x[1] for x in _column_sizes] column_sizes = [x[1] for x in _column_sizes]
def generate_xls_report(self, _p, _xs, data, objects, wb): def generate_xls_report(self, _p, _xs, data, objects, wb):
ws = wb.add_sheet(_p.report_name[:31]) ws = wb.add_sheet(_p.report_name[:31])
ws.panes_frozen = True ws.panes_frozen = True
ws.remove_splits = True ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1 ws.fit_width_to_pages = 1
row_pos = 0 row_pos = 0
# set print header/footer # set print header/footer
ws.header_str = self.xls_headers['standard'] ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard'] ws.footer_str = self.xls_footers['standard']
# cf. account_report_general_ledger.mako
initial_balance_text = {'initial_balance': _('Computed'), 'opening_balance': _('Opening Entries'), False: _('No')}
# cf. account_report_general_ledger.mako
initial_balance_text = {'initial_balance': _('Computed'),
'opening_balance': _('Opening Entries'),
False: _('No')}
# Title # Title
cell_style = xlwt.easyxf(_xs['xls_title']) cell_style = xlwt.easyxf(_xs['xls_title'])
report_name = ' - '.join([_p.report_name.upper(), _p.company.partner_id.name, _p.company.currency_id.name])
report_name = ' - '.join([_p.report_name.upper(),
_p.company.partner_id.name,
_p.company.currency_id.name])
c_specs = [ c_specs = [
('report_name', 1, 0, 'text', report_name), ('report_name', 1, 0, 'text', report_name),
]
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
# write empty row to define column sizes # write empty row to define column sizes
c_sizes = self.column_sizes c_sizes = self.column_sizes
c_specs = [('empty%s'%i, 1, c_sizes[i], 'text', None) for i in range(0,len(c_sizes))]
c_specs = [('empty%s' % i, 1, c_sizes[i], 'text', None)
for i in range(0, len(c_sizes))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, set_column_size=True)
row_pos = self.xls_write_row(
ws, row_pos, row_data, set_column_size=True)
# Header Table # Header Table
cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all'] cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
@ -88,14 +95,16 @@ class general_ledger_xls(report_xls):
c_specs = [ c_specs = [
('coa', 2, 0, 'text', _('Chart of Account')), ('coa', 2, 0, 'text', _('Chart of Account')),
('fy', 1, 0, 'text', _('Fiscal Year')), ('fy', 1, 0, 'text', _('Fiscal Year')),
('df', 3, 0, 'text', _p.filter_form(data) == 'filter_date' and _('Dates Filter') or _('Periods Filter')),
('df', 3, 0, 'text', _p.filter_form(data) ==
'filter_date' and _('Dates Filter') or _('Periods Filter')),
('af', 1, 0, 'text', _('Accounts Filter')), ('af', 1, 0, 'text', _('Accounts Filter')),
('tm', 2, 0, 'text', _('Target Moves')), ('tm', 2, 0, 'text', _('Target Moves')),
('ib', 2, 0, 'text', _('Initial Balance')), ('ib', 2, 0, 'text', _('Initial Balance')),
]
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style_center)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style_center)
cell_format = _xs['borders_all'] cell_format = _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
@ -106,7 +115,7 @@ class general_ledger_xls(report_xls):
] ]
df = _('From') + ': ' df = _('From') + ': '
if _p.filter_form(data) == 'filter_date': if _p.filter_form(data) == 'filter_date':
df += _p.start_date if _p.start_date else u''
df += _p.start_date if _p.start_date else u''
else: else:
df += _p.start_period.name if _p.start_period else u'' df += _p.start_period.name if _p.start_period else u''
df += ' ' + _('To') + ': ' df += ' ' + _('To') + ': '
@ -116,13 +125,16 @@ class general_ledger_xls(report_xls):
df += _p.stop_period.name if _p.stop_period else u'' df += _p.stop_period.name if _p.stop_period else u''
c_specs += [ c_specs += [
('df', 3, 0, 'text', df), ('df', 3, 0, 'text', df),
('af', 1, 0, 'text', _p.accounts(data) and ', '.join([account.code for account in _p.accounts(data)]) or _('All')),
('af', 1, 0, 'text', _p.accounts(data) and ', '.join(
[account.code for account in _p.accounts(data)]) or _('All')),
('tm', 2, 0, 'text', _p.display_target_move(data)), ('tm', 2, 0, 'text', _p.display_target_move(data)),
('ib', 2, 0, 'text', initial_balance_text[_p.initial_balance_mode]),
]
('ib', 2, 0, 'text', initial_balance_text[
_p.initial_balance_mode]),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style_center)
ws.set_horz_split_pos(row_pos)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style_center)
ws.set_horz_split_pos(row_pos)
row_pos += 1 row_pos += 1
# Column Title Row # Column Title Row
@ -134,153 +146,202 @@ class general_ledger_xls(report_xls):
c_hdr_cell_style = xlwt.easyxf(cell_format) c_hdr_cell_style = xlwt.easyxf(cell_format)
c_hdr_cell_style_right = xlwt.easyxf(cell_format + _xs['right']) c_hdr_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
c_hdr_cell_style_center = xlwt.easyxf(cell_format + _xs['center']) c_hdr_cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_hdr_cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
c_hdr_cell_style_decimal = xlwt.easyxf(
cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# Column Initial Balance Row # Column Initial Balance Row
cell_format = _xs['italic'] + _xs['borders_all'] cell_format = _xs['italic'] + _xs['borders_all']
c_init_cell_style = xlwt.easyxf(cell_format) c_init_cell_style = xlwt.easyxf(cell_format)
c_init_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
c_init_cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_init_cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
c_init_cell_style_decimal = xlwt.easyxf(
cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
c_specs = [ c_specs = [
('date', 1, 0, 'text', _('Date'), None, c_hdr_cell_style), ('date', 1, 0, 'text', _('Date'), None, c_hdr_cell_style),
('period', 1, 0, 'text', _('Period'), None, c_hdr_cell_style), ('period', 1, 0, 'text', _('Period'), None, c_hdr_cell_style),
('move', 1, 0, 'text', _('Entry'), None, c_hdr_cell_style), ('move', 1, 0, 'text', _('Entry'), None, c_hdr_cell_style),
('journal', 1, 0, 'text', _('Journal'), None, c_hdr_cell_style), ('journal', 1, 0, 'text', _('Journal'), None, c_hdr_cell_style),
('account_code', 1, 0, 'text', _('Account'), None, c_hdr_cell_style),
('account_code', 1, 0, 'text',
_('Account'), None, c_hdr_cell_style),
('partner', 1, 0, 'text', _('Partner'), None, c_hdr_cell_style), ('partner', 1, 0, 'text', _('Partner'), None, c_hdr_cell_style),
('label', 1, 0, 'text', _('Label'), None, c_hdr_cell_style), ('label', 1, 0, 'text', _('Label'), None, c_hdr_cell_style),
('counterpart', 1, 0, 'text', _('Counterpart'), None, c_hdr_cell_style),
('counterpart', 1, 0, 'text',
_('Counterpart'), None, c_hdr_cell_style),
('debit', 1, 0, 'text', _('Debit'), None, c_hdr_cell_style_right), ('debit', 1, 0, 'text', _('Debit'), None, c_hdr_cell_style_right),
('credit', 1, 0, 'text', _('Credit'), None, c_hdr_cell_style_right),
('cumul_bal', 1, 0, 'text', _('Cumul. Bal.'), None, c_hdr_cell_style_right),
]
('credit', 1, 0, 'text', _('Credit'),
None, c_hdr_cell_style_right),
('cumul_bal', 1, 0, 'text', _('Cumul. Bal.'),
None, c_hdr_cell_style_right),
]
if _p.amount_currency(data): if _p.amount_currency(data):
c_specs += [ c_specs += [
('curr_bal', 1, 0, 'text', _('Curr. Bal.'), None, c_hdr_cell_style_right),
('curr_code', 1, 0, 'text', _('Curr.'), None, c_hdr_cell_style_center),
('curr_bal', 1, 0, 'text', _('Curr. Bal.'),
None, c_hdr_cell_style_right),
('curr_code', 1, 0, 'text', _('Curr.'),
None, c_hdr_cell_style_center),
] ]
c_hdr_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) c_hdr_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
# cell styles for ledger lines # cell styles for ledger lines
ll_cell_format = _xs['borders_all'] ll_cell_format = _xs['borders_all']
ll_cell_style = xlwt.easyxf(ll_cell_format) ll_cell_style = xlwt.easyxf(ll_cell_format)
ll_cell_style_right = xlwt.easyxf(ll_cell_format + _xs['right'])
ll_cell_style_center = xlwt.easyxf(ll_cell_format + _xs['center']) ll_cell_style_center = xlwt.easyxf(ll_cell_format + _xs['center'])
ll_cell_style_date = xlwt.easyxf(ll_cell_format + _xs['left'], num_format_str = report_xls.date_format)
ll_cell_style_decimal = xlwt.easyxf(ll_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
ll_cell_style_date = xlwt.easyxf(
ll_cell_format + _xs['left'],
num_format_str=report_xls.date_format)
ll_cell_style_decimal = xlwt.easyxf(
ll_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
cnt = 0 cnt = 0
for account in objects: for account in objects:
display_initial_balance = account.init_balance and (account.init_balance.get('debit', 0.0) != 0.0 or account.init_balance.get('credit', 0.0) != 0.0)
display_initial_balance = account.init_balance and \
(account.init_balance.get(
'debit', 0.0) != 0.0 or account.
init_balance.get('credit', 0.0) != 0.0)
display_ledger_lines = account.ledger_lines display_ledger_lines = account.ledger_lines
if _p.display_account_raw(data) == 'all' or (display_ledger_lines or display_initial_balance):
#TO DO : replace cumul amounts by xls formulas
if _p.display_account_raw(data) == 'all' or \
(display_ledger_lines or display_initial_balance):
# TO DO : replace cumul amounts by xls formulas
cnt += 1 cnt += 1
cumul_debit = 0.0 cumul_debit = 0.0
cumul_credit = 0.0 cumul_credit = 0.0
cumul_balance = 0.0
cumul_balance = 0.0
cumul_balance_curr = 0.0 cumul_balance_curr = 0.0
c_specs = [ c_specs = [
('acc_title', 11, 0, 'text', ' - '.join([account.code, account.name])),
('acc_title', 11, 0, 'text',
' - '.join([account.code, account.name])),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_title_cell_style)
row_pos = self.xls_write_row(ws, row_pos, c_hdr_data)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_title_cell_style)
row_pos = self.xls_write_row(ws, row_pos, c_hdr_data)
row_start = row_pos row_start = row_pos
if display_initial_balance: if display_initial_balance:
cumul_debit = account.init_balance.get('debit') or 0.0 cumul_debit = account.init_balance.get('debit') or 0.0
cumul_credit = account.init_balance.get('credit') or 0.0 cumul_credit = account.init_balance.get('credit') or 0.0
cumul_balance = account.init_balance.get('init_balance') or 0.0
cumul_balance_curr = account.init_balance.get('init_balance_currency') or 0.0
debit_cell = rowcol_to_cell(row_pos, 8)
credit_cell = rowcol_to_cell(row_pos, 9)
bal_formula = debit_cell + '-' + credit_cell
c_specs = [('empty%s' %x, 1, 0, 'text', None) for x in range(6)]
cumul_balance = account.init_balance.get(
'init_balance') or 0.0
cumul_balance_curr = account.init_balance.get(
'init_balance_currency') or 0.0
c_specs = [('empty%s' % x, 1, 0, 'text', None)
for x in range(6)]
c_specs += [ c_specs += [
('init_bal', 1, 0, 'text', _('Initial Balance')), ('init_bal', 1, 0, 'text', _('Initial Balance')),
('counterpart', 1, 0, 'text', None), ('counterpart', 1, 0, 'text', None),
('debit', 1, 0, 'number', cumul_debit, None, c_init_cell_style_decimal),
('credit', 1, 0, 'number', cumul_credit, None, c_init_cell_style_decimal),
('cumul_bal', 1, 0, 'number', cumul_balance, None, c_init_cell_style_decimal),
]
('debit', 1, 0, 'number', cumul_debit,
None, c_init_cell_style_decimal),
('credit', 1, 0, 'number', cumul_credit,
None, c_init_cell_style_decimal),
('cumul_bal', 1, 0, 'number', cumul_balance,
None, c_init_cell_style_decimal),
]
if _p.amount_currency(data): if _p.amount_currency(data):
c_specs += [ c_specs += [
('curr_bal', 1, 0, 'number', cumul_balance_curr, None, c_init_cell_style_decimal),
('curr_code', 1, 0, 'text', None),
('curr_bal', 1, 0, 'number', cumul_balance_curr,
None, c_init_cell_style_decimal),
('curr_code', 1, 0, 'text', None),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_init_cell_style)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_init_cell_style)
for line in account.ledger_lines: for line in account.ledger_lines:
cumul_debit += line.get('debit') or 0.0 cumul_debit += line.get('debit') or 0.0
cumul_credit += line.get('credit') or 0.0 cumul_credit += line.get('credit') or 0.0
cumul_balance_curr += line.get('amount_currency') or 0.0 cumul_balance_curr += line.get('amount_currency') or 0.0
cumul_balance += line.get('balance') or 0.0 cumul_balance += line.get('balance') or 0.0
label_elements = [line.get('lname') or ''] label_elements = [line.get('lname') or '']
if line.get('invoice_number'): if line.get('invoice_number'):
label_elements.append("(%s)" % (line['invoice_number'],))
label_elements.append(
"(%s)" % (line['invoice_number'],))
label = ' '.join(label_elements) label = ' '.join(label_elements)
if line.get('ldate'): if line.get('ldate'):
c_specs = [ c_specs = [
('ldate', 1, 0, 'date', datetime.strptime(line['ldate'],'%Y-%m-%d'), None, ll_cell_style_date),
('ldate', 1, 0, 'date', datetime.strptime(
line['ldate'], '%Y-%m-%d'), None,
ll_cell_style_date),
] ]
else: else:
c_specs = [ c_specs = [
('ldate', 1, 0, 'text', None), ('ldate', 1, 0, 'text', None),
]
]
c_specs += [ c_specs += [
('period', 1, 0, 'text', line.get('period_code') or ''),
('period', 1, 0, 'text',
line.get('period_code') or ''),
('move', 1, 0, 'text', line.get('move_name') or ''), ('move', 1, 0, 'text', line.get('move_name') or ''),
('journal', 1, 0, 'text', line.get('jcode') or ''), ('journal', 1, 0, 'text', line.get('jcode') or ''),
('account_code', 1, 0, 'text', account.code), ('account_code', 1, 0, 'text', account.code),
('partner', 1, 0, 'text', line.get('partner_name') or ''),
('partner', 1, 0, 'text',
line.get('partner_name') or ''),
('label', 1, 0, 'text', label), ('label', 1, 0, 'text', label),
('counterpart', 1, 0, 'text', line.get('counterparts') or ''),
('debit', 1, 0, 'number', line.get('debit', 0.0), None, ll_cell_style_decimal),
('credit', 1, 0, 'number', line.get('credit', 0.0), None, ll_cell_style_decimal),
('cumul_bal', 1, 0, 'number', cumul_balance, None, ll_cell_style_decimal),
]
('counterpart', 1, 0, 'text',
line.get('counterparts') or ''),
('debit', 1, 0, 'number', line.get('debit', 0.0),
None, ll_cell_style_decimal),
('credit', 1, 0, 'number', line.get('credit', 0.0),
None, ll_cell_style_decimal),
('cumul_bal', 1, 0, 'number', cumul_balance,
None, ll_cell_style_decimal),
]
if _p.amount_currency(data): if _p.amount_currency(data):
c_specs += [ c_specs += [
('curr_bal', 1, 0, 'number', line.get('amount_currency') or 0.0, None, ll_cell_style_decimal),
('curr_code', 1, 0, 'text', line.get('currency_code') or '', None, ll_cell_style_center),
('curr_bal', 1, 0, 'number', line.get(
'amount_currency') or 0.0, None,
ll_cell_style_decimal),
('curr_code', 1, 0, 'text', line.get(
'currency_code') or '', None,
ll_cell_style_center),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, ll_cell_style)
debit_start = rowcol_to_cell(row_start, 8)
debit_end = rowcol_to_cell(row_pos-1, 8)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, ll_cell_style)
debit_start = rowcol_to_cell(row_start, 8)
debit_end = rowcol_to_cell(row_pos - 1, 8)
debit_formula = 'SUM(' + debit_start + ':' + debit_end + ')' debit_formula = 'SUM(' + debit_start + ':' + debit_end + ')'
credit_start = rowcol_to_cell(row_start, 9)
credit_end = rowcol_to_cell(row_pos-1, 9)
credit_start = rowcol_to_cell(row_start, 9)
credit_end = rowcol_to_cell(row_pos - 1, 9)
credit_formula = 'SUM(' + credit_start + ':' + credit_end + ')' credit_formula = 'SUM(' + credit_start + ':' + credit_end + ')'
balance_debit = rowcol_to_cell(row_pos, 8)
balance_debit = rowcol_to_cell(row_pos, 8)
balance_credit = rowcol_to_cell(row_pos, 9) balance_credit = rowcol_to_cell(row_pos, 9)
balance_formula = balance_debit + '-' + balance_credit balance_formula = balance_debit + '-' + balance_credit
c_specs = [ c_specs = [
('acc_title', 7, 0, 'text', ' - '.join([account.code, account.name])),
('cum_bal', 1, 0, 'text', _('Cumulated Balance on Account'), None, c_hdr_cell_style_right),
('debit', 1, 0, 'number', None, debit_formula, c_hdr_cell_style_decimal),
('credit', 1, 0, 'number', None, credit_formula, c_hdr_cell_style_decimal),
('balance', 1, 0, 'number', None, balance_formula, c_hdr_cell_style_decimal),
('acc_title', 7, 0, 'text',
' - '.join([account.code, account.name])),
('cum_bal', 1, 0, 'text',
_('Cumulated Balance on Account'),
None, c_hdr_cell_style_right),
('debit', 1, 0, 'number', None,
debit_formula, c_hdr_cell_style_decimal),
('credit', 1, 0, 'number', None,
credit_formula, c_hdr_cell_style_decimal),
('balance', 1, 0, 'number', None,
balance_formula, c_hdr_cell_style_decimal),
] ]
if _p.amount_currency(data): if _p.amount_currency(data):
if account.currency_id: if account.currency_id:
c_specs += [('curr_bal', 1, 0, 'number', cumul_balance_curr, None, c_hdr_cell_style_decimal)]
c_specs += [('curr_bal', 1, 0, 'number',
cumul_balance_curr, None,
c_hdr_cell_style_decimal)]
else: else:
c_specs += [('curr_bal', 1, 0, 'text', None)] c_specs += [('curr_bal', 1, 0, 'text', None)]
c_specs += [('curr_code', 1, 0, 'text', None)] c_specs += [('curr_code', 1, 0, 'text', None)]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_hdr_cell_style)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_hdr_cell_style)
row_pos += 1 row_pos += 1
general_ledger_xls('report.account.account_report_general_ledger_xls', 'account.account',
parser=GeneralLedgerWebkit)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
general_ledger_xls('report.account.account_report_general_ledger_xls',
'account.account',
parser=GeneralLedgerWebkit)

1088
account_financial_report_webkit_xls/report/open_invoices_xls.py
File diff suppressed because it is too large
View File

392
account_financial_report_webkit_xls/report/partner_ledger_xls.py

@ -21,15 +21,14 @@
############################################################################## ##############################################################################
import xlwt import xlwt
import time
from datetime import datetime from datetime import datetime
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell from openerp.addons.report_xls.utils import rowcol_to_cell
from openerp.addons.account_financial_report_webkit.report.partners_ledger import PartnersLedgerWebkit
from openerp.addons.account_financial_report_webkit.report.partners_ledger \
import PartnersLedgerWebkit
from openerp.tools.translate import _ from openerp.tools.translate import _
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
_column_sizes = [ _column_sizes = [
('date', 12), ('date', 12),
@ -39,65 +38,75 @@ _column_sizes = [
('partner', 30), ('partner', 30),
('label', 58), ('label', 58),
('rec', 12), ('rec', 12),
('debit', 15),
('debit', 15),
('credit', 15), ('credit', 15),
('cumul_bal', 15), ('cumul_bal', 15),
('curr_bal', 15),
('curr_bal', 15),
('curr_code', 7), ('curr_code', 7),
] ]
class partner_ledger_xls(report_xls): class partner_ledger_xls(report_xls):
column_sizes = [x[1] for x in _column_sizes] column_sizes = [x[1] for x in _column_sizes]
def generate_xls_report(self, _p, _xs, data, objects, wb): def generate_xls_report(self, _p, _xs, data, objects, wb):
ws = wb.add_sheet(_p.report_name[:31]) ws = wb.add_sheet(_p.report_name[:31])
ws.panes_frozen = True ws.panes_frozen = True
ws.remove_splits = True ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1 ws.fit_width_to_pages = 1
row_pos = 0 row_pos = 0
# set print header/footer # set print header/footer
ws.header_str = self.xls_headers['standard'] ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard'] ws.footer_str = self.xls_footers['standard']
# cf. account_report_partner_ledger.mako
initial_balance_text = {'initial_balance': _('Computed'), 'opening_balance': _('Opening Entries'), False: _('No')}
# cf. account_report_partner_ledger.mako
initial_balance_text = {'initial_balance': _('Computed'),
'opening_balance': _('Opening Entries'),
False: _('No')}
# Title # Title
cell_style = xlwt.easyxf(_xs['xls_title']) cell_style = xlwt.easyxf(_xs['xls_title'])
report_name = ' - '.join([_p.report_name.upper(), _p.company.partner_id.name, _p.company.currency_id.name])
report_name = ' - '.join([_p.report_name.upper(),
_p.company.partner_id.name,
_p.company.currency_id.name])
c_specs = [ c_specs = [
('report_name', 1, 0, 'text', report_name), ('report_name', 1, 0, 'text', report_name),
]
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
# write empty row to define column sizes # write empty row to define column sizes
c_sizes = self.column_sizes c_sizes = self.column_sizes
c_specs = [('empty%s'%i, 1, c_sizes[i], 'text', None) for i in range(0,len(c_sizes))]
c_specs = [('empty%s' % i, 1, c_sizes[i], 'text', None)
for i in range(0, len(c_sizes))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, set_column_size=True)
row_pos = self.xls_write_row(
ws, row_pos, row_data, set_column_size=True)
# Header Table # Header Table
nbr_columns = 10
nbr_columns = 10
if _p.amount_currency(data): if _p.amount_currency(data):
nbr_columns = 12
nbr_columns = 12
cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all'] cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_center = xlwt.easyxf(cell_format + _xs['center']) cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_specs = [ c_specs = [
('coa', 2, 0, 'text', _('Chart of Account')), ('coa', 2, 0, 'text', _('Chart of Account')),
('fy', 1, 0, 'text', _('Fiscal Year')), ('fy', 1, 0, 'text', _('Fiscal Year')),
('df', 2, 0, 'text', _p.filter_form(data) == 'filter_date' and _('Dates Filter') or _('Periods Filter')),
('df', 2, 0, 'text', _p.filter_form(data) ==
'filter_date' and _('Dates Filter') or _('Periods Filter')),
('af', 1, 0, 'text', _('Accounts Filter')), ('af', 1, 0, 'text', _('Accounts Filter')),
('tm', 2, 0, 'text', _('Target Moves')), ('tm', 2, 0, 'text', _('Target Moves')),
('ib', nbr_columns-8, 0, 'text', _('Initial Balance')),
('ib', nbr_columns - 8, 0, 'text', _('Initial Balance')),
]
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style_center)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style_center)
cell_format = _xs['borders_all'] cell_format = _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
@ -108,7 +117,7 @@ class partner_ledger_xls(report_xls):
] ]
df = _('From') + ': ' df = _('From') + ': '
if _p.filter_form(data) == 'filter_date': if _p.filter_form(data) == 'filter_date':
df += _p.start_date if _p.start_date else u''
df += _p.start_date if _p.start_date else u''
else: else:
df += _p.start_period.name if _p.start_period else u'' df += _p.start_period.name if _p.start_period else u''
df += ' ' + _('To') + ': ' df += ' ' + _('To') + ': '
@ -118,20 +127,26 @@ class partner_ledger_xls(report_xls):
df += _p.stop_period.name if _p.stop_period else u'' df += _p.stop_period.name if _p.stop_period else u''
c_specs += [ c_specs += [
('df', 2, 0, 'text', df), ('df', 2, 0, 'text', df),
('af', 1, 0, 'text', _('Custom Filter') if _p.partner_ids else _p.display_partner_account(data)),
('af', 1, 0, 'text', _('Custom Filter')
if _p.partner_ids else _p.display_partner_account(data)),
('tm', 2, 0, 'text', _p.display_target_move(data)), ('tm', 2, 0, 'text', _p.display_target_move(data)),
('ib', nbr_columns-8, 0, 'text', initial_balance_text[_p.initial_balance_mode]),
]
('ib', nbr_columns - 8, 0, 'text',
initial_balance_text[_p.initial_balance_mode]),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style_center)
ws.set_horz_split_pos(row_pos)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style_center)
ws.set_horz_split_pos(row_pos)
row_pos += 1 row_pos += 1
# Account Title Row # Account Title Row
cell_format = _xs['xls_title'] + _xs['bold'] + _xs['fill'] + _xs['borders_all']
cell_format = _xs['xls_title'] + _xs['bold'] + \
_xs['fill'] + _xs['borders_all']
account_cell_style = xlwt.easyxf(cell_format) account_cell_style = xlwt.easyxf(cell_format)
account_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
account_cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
account_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
account_cell_style_decimal = xlwt.easyxf(
cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# Column Title Row # Column Title Row
cell_format = _xs['bold'] cell_format = _xs['bold']
@ -142,26 +157,27 @@ class partner_ledger_xls(report_xls):
c_hdr_cell_style = xlwt.easyxf(cell_format) c_hdr_cell_style = xlwt.easyxf(cell_format)
c_hdr_cell_style_right = xlwt.easyxf(cell_format + _xs['right']) c_hdr_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
c_hdr_cell_style_center = xlwt.easyxf(cell_format + _xs['center']) c_hdr_cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_hdr_cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# Column Initial Balance Row # Column Initial Balance Row
cell_format = _xs['italic'] + _xs['borders_all'] cell_format = _xs['italic'] + _xs['borders_all']
c_init_cell_style = xlwt.easyxf(cell_format) c_init_cell_style = xlwt.easyxf(cell_format)
c_init_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
c_init_cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_init_cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
c_init_cell_style_decimal = xlwt.easyxf(
cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# Column Cumulated balance Row # Column Cumulated balance Row
cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all'] cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
c_cumul_cell_style = xlwt.easyxf(cell_format) c_cumul_cell_style = xlwt.easyxf(cell_format)
c_cumul_cell_style_right = xlwt.easyxf(cell_format + _xs['right']) c_cumul_cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
c_cumul_cell_style_center = xlwt.easyxf(cell_format + _xs['center']) c_cumul_cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_cumul_cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# Column Partner Row
c_cumul_cell_style_decimal = xlwt.easyxf(
cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# Column Partner Row
cell_format = _xs['bold'] cell_format = _xs['bold']
c_part_cell_style = xlwt.easyxf(cell_format) c_part_cell_style = xlwt.easyxf(cell_format)
c_specs = [ c_specs = [
('date', 1, 0, 'text', _('Date'), None, c_hdr_cell_style), ('date', 1, 0, 'text', _('Date'), None, c_hdr_cell_style),
('period', 1, 0, 'text', _('Period'), None, c_hdr_cell_style), ('period', 1, 0, 'text', _('Period'), None, c_hdr_cell_style),
@ -171,27 +187,34 @@ class partner_ledger_xls(report_xls):
('label', 1, 0, 'text', _('Label'), None, c_hdr_cell_style), ('label', 1, 0, 'text', _('Label'), None, c_hdr_cell_style),
('rec', 1, 0, 'text', _('Rec.'), None, c_hdr_cell_style), ('rec', 1, 0, 'text', _('Rec.'), None, c_hdr_cell_style),
('debit', 1, 0, 'text', _('Debit'), None, c_hdr_cell_style_right), ('debit', 1, 0, 'text', _('Debit'), None, c_hdr_cell_style_right),
('credit', 1, 0, 'text', _('Credit'), None, c_hdr_cell_style_right),
('cumul_bal', 1, 0, 'text', _('Cumul. Bal.'), None, c_hdr_cell_style_right),
('credit', 1, 0, 'text', _('Credit'),
None, c_hdr_cell_style_right),
('cumul_bal', 1, 0, 'text', _('Cumul. Bal.'),
None, c_hdr_cell_style_right),
] ]
if _p.amount_currency(data): if _p.amount_currency(data):
c_specs += [ c_specs += [
('curr_bal', 1, 0, 'text', _('Curr. Bal.'), None, c_hdr_cell_style_right),
('curr_code', 1, 0, 'text', _('Curr.'), None, c_hdr_cell_style_center),
('curr_bal', 1, 0, 'text', _('Curr. Bal.'),
None, c_hdr_cell_style_right),
('curr_code', 1, 0, 'text', _('Curr.'),
None, c_hdr_cell_style_center),
] ]
c_hdr_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) c_hdr_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
# cell styles for ledger lines # cell styles for ledger lines
ll_cell_format = _xs['borders_all'] ll_cell_format = _xs['borders_all']
ll_cell_style = xlwt.easyxf(ll_cell_format) ll_cell_style = xlwt.easyxf(ll_cell_format)
ll_cell_style_right = xlwt.easyxf(ll_cell_format + _xs['right'])
ll_cell_style_center = xlwt.easyxf(ll_cell_format + _xs['center']) ll_cell_style_center = xlwt.easyxf(ll_cell_format + _xs['center'])
ll_cell_style_date = xlwt.easyxf(ll_cell_format + _xs['left'], num_format_str = report_xls.date_format)
ll_cell_style_decimal = xlwt.easyxf(ll_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
ll_cell_style_date = xlwt.easyxf(
ll_cell_format + _xs['left'],
num_format_str=report_xls.date_format)
ll_cell_style_decimal = xlwt.easyxf(
ll_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
cnt = 0 cnt = 0
for account in objects: for account in objects:
if account.ledger_lines or account.init_balance:
if account.ledger_lines or account.init_balance:
if not account.partners_order: if not account.partners_order:
continue continue
cnt += 1 cnt += 1
@ -200,15 +223,19 @@ class partner_ledger_xls(report_xls):
account_balance_cumul = 0.0 account_balance_cumul = 0.0
account_balance_cumul_curr = 0.0 account_balance_cumul_curr = 0.0
c_specs = [ c_specs = [
('acc_title', nbr_columns, 0, 'text', ' - '.join([account.code, account.name]), None, account_cell_style),
('acc_title', nbr_columns, 0, 'text',
' - '.join([account.code, account.name]), None,
account_cell_style),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_title_cell_style)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_title_cell_style)
row_pos += 1 row_pos += 1
row_start_account = row_pos
for partner_name, p_id, p_ref, p_name in account.partners_order:
for partner_name, p_id, p_ref, p_name in \
account.partners_order:
total_debit = 0.0 total_debit = 0.0
total_credit = 0.0 total_credit = 0.0
cumul_balance = 0.0 cumul_balance = 0.0
@ -216,48 +243,67 @@ class partner_ledger_xls(report_xls):
part_cumul_balance = 0.0 part_cumul_balance = 0.0
part_cumul_balance_curr = 0.0 part_cumul_balance_curr = 0.0
c_specs = [ c_specs = [
('partner_title', nbr_columns, 0, 'text', partner_name or _('No Partner'), None, c_part_cell_style),
('partner_title', nbr_columns, 0, 'text',
partner_name or _('No Partner'), None,
c_part_cell_style),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_title_cell_style)
row_pos = self.xls_write_row(ws, row_pos, c_hdr_data)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_title_cell_style)
row_pos = self.xls_write_row(ws, row_pos, c_hdr_data)
row_start_partner = row_pos row_start_partner = row_pos
total_debit = account.init_balance.get(p_id, {}).get('debit') or 0.0
total_credit = account.init_balance.get(p_id, {}).get('credit') or 0.0
total_debit = account.init_balance.get(
p_id, {}).get('debit') or 0.0
total_credit = account.init_balance.get(
p_id, {}).get('credit') or 0.0
init_line = False init_line = False
if _p.initial_balance_mode and (total_debit or total_credit):
if _p.initial_balance_mode and \
(total_debit or total_credit):
init_line = True init_line = True
part_cumul_balance = account.init_balance.get(p_id, {}).get('init_balance') or 0.0
part_cumul_balance_curr = account.init_balance.get(p_id, {}).get('init_balance_currency') or 0.0
balance_forward_currency = account.init_balance.get(p_id, {}).get('currency_name') or ''
part_cumul_balance = account.init_balance.get(
p_id, {}).get('init_balance') or 0.0
part_cumul_balance_curr = account.init_balance.get(
p_id, {}).get('init_balance_currency') or 0.0
balance_forward_currency = account.init_balance.get(
p_id, {}).get('currency_name') or ''
cumul_balance += part_cumul_balance cumul_balance += part_cumul_balance
cumul_balance_curr += part_cumul_balance_curr cumul_balance_curr += part_cumul_balance_curr
debit_cell = rowcol_to_cell(row_pos, 7)
debit_cell = rowcol_to_cell(row_pos, 7)
credit_cell = rowcol_to_cell(row_pos, 8) credit_cell = rowcol_to_cell(row_pos, 8)
init_bal_formula = debit_cell + '-' + credit_cell
################## Print row 'Initial Balance' by partner #################
c_specs = [('empty%s' %x, 1, 0, 'text', None) for x in range(5)]
init_bal_formula = debit_cell + '-' + credit_cell
# Print row 'Initial Balance' by partn
c_specs = [('empty%s' % x, 1, 0, 'text', None)
for x in range(5)]
c_specs += [ c_specs += [
('init_bal', 1, 0, 'text', _('Initial Balance')), ('init_bal', 1, 0, 'text', _('Initial Balance')),
('rec', 1, 0, 'text', None), ('rec', 1, 0, 'text', None),
('debit', 1, 0, 'number', total_debit, None, c_init_cell_style_decimal),
('credit', 1, 0, 'number', total_credit, None, c_init_cell_style_decimal),
('cumul_bal', 1, 0, 'number', None, init_bal_formula, c_init_cell_style_decimal),
]
('debit', 1, 0, 'number', total_debit,
None, c_init_cell_style_decimal),
('credit', 1, 0, 'number', total_credit,
None, c_init_cell_style_decimal),
('cumul_bal', 1, 0, 'number', None,
init_bal_formula, c_init_cell_style_decimal),
]
if _p.amount_currency(data): if _p.amount_currency(data):
c_specs += [ c_specs += [
('curr_bal', 1, 0, 'number', part_cumul_balance_curr, None, c_init_cell_style_decimal),
('curr_code', 1, 0, 'text', balance_forward_currency),
('curr_bal', 1, 0, 'number',
part_cumul_balance_curr,
None, c_init_cell_style_decimal),
('curr_code', 1, 0, 'text',
balance_forward_currency),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_init_cell_style)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_init_cell_style)
for line in account.ledger_lines.get(p_id, []): for line in account.ledger_lines.get(p_id, []):
total_debit += line.get('debit') or 0.0 total_debit += line.get('debit') or 0.0
@ -265,101 +311,147 @@ class partner_ledger_xls(report_xls):
label_elements = [line.get('lname') or ''] label_elements = [line.get('lname') or '']
if line.get('invoice_number'): if line.get('invoice_number'):
label_elements.append("(%s)" % (line['invoice_number'],))
label_elements.append(
"(%s)" % (line['invoice_number'],))
label = ' '.join(label_elements) label = ' '.join(label_elements)
cumul_balance += line.get('balance') or 0.0 cumul_balance += line.get('balance') or 0.0
if init_line or row_pos > row_start_partner: if init_line or row_pos > row_start_partner:
cumbal_formula = rowcol_to_cell(row_pos-1, 9) + '+'
cumbal_formula = rowcol_to_cell(
row_pos - 1, 9) + '+'
else: else:
cumbal_formula = '' cumbal_formula = ''
debit_cell = rowcol_to_cell(row_pos, 7)
debit_cell = rowcol_to_cell(row_pos, 7)
credit_cell = rowcol_to_cell(row_pos, 8) credit_cell = rowcol_to_cell(row_pos, 8)
cumbal_formula += debit_cell + '-' + credit_cell
################## Print row ledger line data #################
cumbal_formula += debit_cell + '-' + credit_cell
# Print row ledger line data #
if line.get('ldate'): if line.get('ldate'):
c_specs = [ c_specs = [
('ldate', 1, 0, 'date', datetime.strptime(line['ldate'],'%Y-%m-%d'), None, ll_cell_style_date),
('ldate', 1, 0, 'date', datetime.strptime(
line['ldate'], '%Y-%m-%d'), None,
ll_cell_style_date),
] ]
else: else:
c_specs = [ c_specs = [
('ldate', 1, 0, 'text', None), ('ldate', 1, 0, 'text', None),
]
]
c_specs += [ c_specs += [
('period', 1, 0, 'text', line.get('period_code') or ''),
('move', 1, 0, 'text', line.get('move_name') or ''),
('period', 1, 0, 'text',
line.get('period_code') or ''),
('move', 1, 0, 'text',
line.get('move_name') or ''),
('journal', 1, 0, 'text', line.get('jcode') or ''), ('journal', 1, 0, 'text', line.get('jcode') or ''),
('partner', 1, 0, 'text', line.get('partner_name') or ''),
('partner', 1, 0, 'text',
line.get('partner_name') or ''),
('label', 1, 0, 'text', label), ('label', 1, 0, 'text', label),
('rec_name', 1, 0, 'text', line.get('rec_name') or ''),
('debit', 1, 0, 'number', line.get('debit'), None, ll_cell_style_decimal),
('credit', 1, 0, 'number', line.get('credit'), None, ll_cell_style_decimal),
('cumul_bal', 1, 0, 'number', None, cumbal_formula, ll_cell_style_decimal),
]
('rec_name', 1, 0, 'text',
line.get('rec_name') or ''),
('debit', 1, 0, 'number', line.get('debit'),
None, ll_cell_style_decimal),
('credit', 1, 0, 'number', line.get('credit'),
None, ll_cell_style_decimal),
('cumul_bal', 1, 0, 'number', None,
cumbal_formula, ll_cell_style_decimal),
]
if _p.amount_currency(data): if _p.amount_currency(data):
c_specs += [ c_specs += [
('curr_bal', 1, 0, 'number', line.get('amount_currency') or 0.0, None, ll_cell_style_decimal),
('curr_code', 1, 0, 'text', line.get('currency_code') or '', None, ll_cell_style_center),
('curr_bal', 1, 0, 'number', line.get(
'amount_currency') or 0.0, None,
ll_cell_style_decimal),
('curr_code', 1, 0, 'text', line.get(
'currency_code') or '', None,
ll_cell_style_center),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, ll_cell_style)
#end for line
################## Print row Cumulated Balance by partner #################
debit_partner_start = rowcol_to_cell(row_start_partner, 7)
debit_partner_end = rowcol_to_cell(row_pos-1, 7)
debit_partner_total = 'SUM(' + debit_partner_start + ':' + debit_partner_end + ')'
credit_partner_start = rowcol_to_cell(row_start_partner, 8)
credit_partner_end = rowcol_to_cell(row_pos-1, 8)
credit_partner_total = 'SUM(' + credit_partner_start + ':' + credit_partner_end + ')'
bal_partner_debit = rowcol_to_cell(row_pos, 7)
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, ll_cell_style)
# end for line
# Print row Cumulated Balance by partner #
debit_partner_start = rowcol_to_cell(row_start_partner, 7)
debit_partner_end = rowcol_to_cell(row_pos - 1, 7)
debit_partner_total = 'SUM(' + debit_partner_start + \
':' + debit_partner_end + ')'
credit_partner_start = rowcol_to_cell(row_start_partner, 8)
credit_partner_end = rowcol_to_cell(row_pos - 1, 8)
credit_partner_total = 'SUM(' + credit_partner_start + \
':' + credit_partner_end + ')'
bal_partner_debit = rowcol_to_cell(row_pos, 7)
bal_partner_credit = rowcol_to_cell(row_pos, 8) bal_partner_credit = rowcol_to_cell(row_pos, 8)
bal_partner_total = bal_partner_debit + '-' + bal_partner_credit
c_specs = [('empty%s' %x, 1, 0, 'text', None) for x in range(5)]
bal_partner_total = bal_partner_debit + \
'-' + bal_partner_credit
c_specs = [('empty%s' % x, 1, 0, 'text', None)
for x in range(5)]
c_specs += [ c_specs += [
('init_bal', 1, 0, 'text', _('Cumulated balance on Partner')),
('rec', 1, 0, 'text', None),
('debit', 1, 0, 'number', None, debit_partner_total, c_cumul_cell_style_decimal),
('credit', 1, 0, 'number', None, credit_partner_total, c_cumul_cell_style_decimal),
('cumul_bal', 1, 0, 'number', None, bal_partner_total, c_cumul_cell_style_decimal),
]
('init_bal', 1, 0, 'text',
_('Cumulated balance on Partner')),
('rec', 1, 0, 'text', None),
('debit', 1, 0, 'number', None,
debit_partner_total, c_cumul_cell_style_decimal),
('credit', 1, 0, 'number', None,
credit_partner_total, c_cumul_cell_style_decimal),
('cumul_bal', 1, 0, 'number', None,
bal_partner_total, c_cumul_cell_style_decimal),
]
if _p.amount_currency(data): if _p.amount_currency(data):
if account.currency_id: if account.currency_id:
c_specs += [('curr_bal', 1, 0, 'number', cumul_balance_curr or 0.0, None, c_cumul_cell_style_decimal)]
c_specs += [('curr_bal', 1, 0, 'number',
cumul_balance_curr or 0.0, None,
c_cumul_cell_style_decimal)]
else: else:
c_specs += [('curr_bal', 1, 0, 'text', '-', None, c_cumul_cell_style_right)]
c_specs += [('curr_code', 1, 0, 'text', account.currency_id.name if account.currency_id else u'', None, c_cumul_cell_style_center)]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, c_cumul_cell_style)
row_pos += 1
c_specs += [('curr_bal', 1, 0, 'text',
'-', None, c_cumul_cell_style_right)]
c_specs += [('curr_code', 1, 0, 'text',
account.currency_id.name if
account.currency_id else u'', None,
c_cumul_cell_style_center)]
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, c_cumul_cell_style)
row_pos += 1
account_total_debit += total_debit account_total_debit += total_debit
account_total_credit += total_credit account_total_credit += total_credit
account_balance_cumul += cumul_balance account_balance_cumul += cumul_balance
account_balance_cumul_curr += cumul_balance_curr
################## Print row Cumulated Balance by account #################
c_specs = [('acc_title', 5, 0, 'text', ' - '.join([account.code, account.name])), ]
account_balance_cumul_curr += cumul_balance_curr
# Print row Cumulated Balance by account #
c_specs = [
('acc_title', 5, 0, 'text', ' - '.
join([account.code, account.name])), ]
c_specs += [ c_specs += [
('label', 1, 0, 'text', _('Cumulated balance on Account')), ('label', 1, 0, 'text', _('Cumulated balance on Account')),
('rec', 1, 0, 'text', None), ('rec', 1, 0, 'text', None),
('debit', 1, 0, 'number', account_total_debit, None, account_cell_style_decimal),
('credit', 1, 0, 'number', account_total_credit, None, account_cell_style_decimal),
('cumul_bal', 1, 0, 'number', account_balance_cumul, None, account_cell_style_decimal),
]
('debit', 1, 0, 'number', account_total_debit,
None, account_cell_style_decimal),
('credit', 1, 0, 'number', account_total_credit,
None, account_cell_style_decimal),
('cumul_bal', 1, 0, 'number', account_balance_cumul,
None, account_cell_style_decimal),
]
if _p.amount_currency(data): if _p.amount_currency(data):
if account.currency_id: if account.currency_id:
c_specs += [('curr_bal', 1, 0, 'number', account_balance_cumul_curr or 0.0, None, account_cell_style_decimal)]
c_specs += [('curr_bal', 1, 0, 'number',
account_balance_cumul_curr or 0.0, None,
account_cell_style_decimal)]
else: else:
c_specs += [('curr_bal', 1, 0, 'text', '-', None, account_cell_style_right)]
c_specs += [('curr_code', 1, 0, 'text', account.currency_id.name if account.currency_id else u'', None, account_cell_style)]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, account_cell_style)
c_specs += [('curr_bal', 1, 0, 'text',
'-', None, account_cell_style_right)]
c_specs += [('curr_code', 1, 0, 'text',
account.currency_id.name if
account.currency_id else u'', None,
account_cell_style)]
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, account_cell_style)
row_pos += 2 row_pos += 2
partner_ledger_xls('report.account.account_report_partner_ledger_xls', 'account.account',
parser=PartnersLedgerWebkit)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
partner_ledger_xls('report.account.account_report_partner_ledger_xls',
'account.account',
parser=PartnersLedgerWebkit)

391
account_financial_report_webkit_xls/report/partners_balance_xls.py

@ -21,67 +21,84 @@
############################################################################## ##############################################################################
import xlwt import xlwt
import time
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell from openerp.addons.report_xls.utils import rowcol_to_cell
from openerp.addons.account_financial_report_webkit.report.partner_balance import PartnerBalanceWebkit
from openerp.addons.account_financial_report_webkit.report.partner_balance \
import PartnerBalanceWebkit
from openerp.tools.translate import _ from openerp.tools.translate import _
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
def display_line(all_comparison_lines): def display_line(all_comparison_lines):
return any([line.get('balance') for line in all_comparison_lines]) return any([line.get('balance') for line in all_comparison_lines])
class partners_balance_xls(report_xls): class partners_balance_xls(report_xls):
column_sizes = [12,40,25,17,17,17,17,17]
def print_title(self, ws, _p, row_position, xlwt,_xs):
cell_style = xlwt.easyxf(_xs['xls_title'])
report_name = ' - '.join([_p.report_name.upper(), _p.company.partner_id.name, _p.company.currency_id.name])
column_sizes = [12, 40, 25, 17, 17, 17, 17, 17]
def print_title(self, ws, _p, row_position, xlwt, _xs):
cell_style = xlwt.easyxf(_xs['xls_title'])
report_name = ' - '.join([_p.report_name.upper(),
_p.company.partner_id.name,
_p.company.currency_id.name])
c_specs = [ c_specs = [
('report_name', 1, 0, 'text', report_name), ('report_name', 1, 0, 'text', report_name),
]
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, row_style=cell_style)
row_position = self.xls_write_row(
ws, row_position, row_data, row_style=cell_style)
return row_position return row_position
def print_empty_row(self, ws, row_position): def print_empty_row(self, ws, row_position):
c_sizes = self.column_sizes c_sizes = self.column_sizes
c_specs = [('empty%s'%i, 1, c_sizes[i], 'text', None) for i in range(0,len(c_sizes))]
c_specs = [('empty%s' % i, 1, c_sizes[i], 'text', None)
for i in range(0, len(c_sizes))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, set_column_size=True)
return row_position
def print_header_titles(self, ws, _p, data, row_position, xlwt, _xs):
row_position = self.xls_write_row(
ws, row_position, row_data, set_column_size=True)
return row_position
def print_header_titles(self, ws, _p, data, row_position, xlwt, _xs):
cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all'] cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_center = xlwt.easyxf(cell_format + _xs['center']) cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_specs = [ c_specs = [
('fy', 1, 0, 'text', _('Fiscal Year'), None, cell_style_center), ('fy', 1, 0, 'text', _('Fiscal Year'), None, cell_style_center),
('af', 1, 0, 'text', _('Accounts Filter'), None, cell_style_center),
('df', 1, 0, 'text', _p.filter_form(data) == 'filter_date' and _('Dates Filter') or _('Periods Filter'), None, cell_style_center),
('pf', 1, 0, 'text', _('Partners Filter'), None, cell_style_center),
('af', 1, 0, 'text', _('Accounts Filter'),
None, cell_style_center),
('df', 1, 0, 'text', _p.filter_form(data) == 'filter_date' and _(
'Dates Filter') or _('Periods Filter'), None,
cell_style_center),
('pf', 1, 0, 'text', _('Partners Filter'),
None, cell_style_center),
('tm', 1, 0, 'text', _('Target Moves'), None, cell_style_center), ('tm', 1, 0, 'text', _('Target Moves'), None, cell_style_center),
('ib', 1, 0, 'text', _('Initial Balance'), None, cell_style_center),
('coa', 1, 0, 'text', _('Chart of Account'), None, cell_style_center),
]
('ib', 1, 0, 'text', _('Initial Balance'),
None, cell_style_center),
('coa', 1, 0, 'text', _('Chart of Account'),
None, cell_style_center),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, row_style=cell_style)
row_position = self.xls_write_row(
ws, row_position, row_data, row_style=cell_style)
return row_position return row_position
def print_header_data(self, ws, _p, data, row_position, xlwt, _xs, initial_balance_text):
def print_header_data(self, ws, _p, data, row_position, xlwt, _xs,
initial_balance_text):
cell_format = _xs['borders_all'] + _xs['wrap'] + _xs['top'] cell_format = _xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_center = xlwt.easyxf(cell_format + _xs['center']) cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_specs = [ c_specs = [
('fy', 1, 0, 'text', _p.fiscalyear.name if _p.fiscalyear else '-', None, cell_style_center),
('af', 1, 0, 'text', _p.accounts(data) and ', '.join([account.code for account in _p.accounts(data)]) or _('All'), None, cell_style_center),
('fy', 1, 0, 'text', _p.fiscalyear.name if _p.fiscalyear else '-',
None, cell_style_center),
('af', 1, 0, 'text', _p.accounts(data) and ', '.join(
[account.code for account in _p.accounts(data)]) or _('All'),
None, cell_style_center),
] ]
df = _('From') + ': ' df = _('From') + ': '
if _p.filter_form(data) == 'filter_date': if _p.filter_form(data) == 'filter_date':
df += _p.start_date if _p.start_date else u''
df += _p.start_date if _p.start_date else u''
else: else:
df += _p.start_period.name if _p.start_period else u'' df += _p.start_period.name if _p.start_period else u''
df += ' ' + _('\nTo') + ': ' df += ' ' + _('\nTo') + ': '
@ -91,38 +108,56 @@ class partners_balance_xls(report_xls):
df += _p.stop_period.name if _p.stop_period else u'' df += _p.stop_period.name if _p.stop_period else u''
c_specs += [ c_specs += [
('df', 1, 0, 'text', df, None, cell_style_center), ('df', 1, 0, 'text', df, None, cell_style_center),
('tm', 1, 0, 'text', _p.display_partner_account(data), None, cell_style_center),
('pf', 1, 0, 'text', _p.display_target_move(data), None, cell_style_center),
('ib', 1, 0, 'text', initial_balance_text[_p.initial_balance_mode], None, cell_style_center),
('coa', 1, 0, 'text', _p.chart_account.name, None, cell_style_center),
]
('tm', 1, 0, 'text', _p.display_partner_account(
data), None, cell_style_center),
('pf', 1, 0, 'text', _p.display_target_move(
data), None, cell_style_center),
('ib', 1, 0, 'text', initial_balance_text[
_p.initial_balance_mode], None, cell_style_center),
('coa', 1, 0, 'text', _p.chart_account.name,
None, cell_style_center),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, row_style=cell_style)
row_position = self.xls_write_row(
ws, row_position, row_data, row_style=cell_style)
return row_position return row_position
def print_comparison_header(self, _xs, xlwt, row_position, _p, ws, initial_balance_text ):
def print_comparison_header(self, _xs, xlwt, row_position, _p, ws,
initial_balance_text):
cell_format_ct = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all'] cell_format_ct = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all']
cell_style_ct = xlwt.easyxf(cell_format_ct) cell_style_ct = xlwt.easyxf(cell_format_ct)
c_specs = [('ct', 7, 0, 'text', _('Comparisons'))]
c_specs = [('ct', 7, 0, 'text', _('Comparisons'))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, row_style=cell_style_ct)
cell_format = _xs['borders_all'] + _xs['wrap'] + _xs['top']
row_position = self.xls_write_row(
ws, row_position, row_data, row_style=cell_style_ct)
cell_format = _xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_style_center = xlwt.easyxf(cell_format) cell_style_center = xlwt.easyxf(cell_format)
for index, params in enumerate(_p.comp_params): for index, params in enumerate(_p.comp_params):
c_specs = [('c', 2, 0, 'text', _('Comparison') + str(index + 1) + ' (C' + str(index + 1) + ')')]
c_specs = [
('c', 2, 0, 'text', _('Comparison') + str(index + 1) +
' (C' + str(index + 1) + ')')]
if params['comparison_filter'] == 'filter_date': if params['comparison_filter'] == 'filter_date':
c_specs += [('f', 2, 0, 'text', _('Dates Filter') + ': ' + _p.formatLang(params['start'], date=True) + ' - ' + _p.formatLang(params['stop'], date=True))]
c_specs += [('f', 2, 0, 'text', _('Dates Filter') + ': ' +
_p.formatLang(params['start'], date=True) + ' - '
+ _p.formatLang(params['stop'], date=True))]
elif params['comparison_filter'] == 'filter_period': elif params['comparison_filter'] == 'filter_period':
c_specs += [('f', 2, 0, 'text', _('Periods Filter') + ': ' + params['start'].name + ' - ' + params['stop'].name)]
c_specs += [('f', 2, 0, 'text', _('Periods Filter') +
': ' + params['start'].name + ' - ' +
params['stop'].name)]
else: else:
c_specs += [('f', 2, 0, 'text', _('Fiscal Year') + ': ' + params['fiscalyear'].name)]
c_specs += [('ib', 2, 0, 'text', _('Initial Balance') + ': ' + initial_balance_text[params['initial_balance_mode']])]
c_specs += [('f', 2, 0, 'text', _('Fiscal Year') +
': ' + params['fiscalyear'].name)]
c_specs += [('ib', 2, 0, 'text', _('Initial Balance') +
': ' +
initial_balance_text[params['initial_balance_mode']])]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, row_style=cell_style_center)
row_position = self.xls_write_row(
ws, row_position, row_data, row_style=cell_style_center)
return row_position return row_position
def print_account_header(self, ws, _p, _xs, xlwt, row_position):
cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all'] + _xs['wrap'] + _xs['top']
def print_account_header(self, ws, _p, _xs, xlwt, row_position):
cell_format = _xs['bold'] + _xs['fill'] + \
_xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_right = xlwt.easyxf(cell_format + _xs['right']) cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
cell_style_center = xlwt.easyxf(cell_format + _xs['center']) cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
@ -136,97 +171,131 @@ class partners_balance_xls(report_xls):
] ]
if _p.comparison_mode == 'no_comparison': if _p.comparison_mode == 'no_comparison':
if _p.initial_balance_mode: if _p.initial_balance_mode:
c_specs += [('init_bal', 1, 0, 'text', _('Initial Balance'), None, cell_style_right)]
c_specs += [('init_bal', 1, 0, 'text',
_('Initial Balance'), None, cell_style_right)]
c_specs += [ c_specs += [
('debit', 1, 0, 'text', _('Debit'), None, cell_style_right), ('debit', 1, 0, 'text', _('Debit'), None, cell_style_right),
('credit', 1, 0, 'text', _('Credit'), None, cell_style_right), ('credit', 1, 0, 'text', _('Credit'), None, cell_style_right),
]
]
if _p.comparison_mode == 'no_comparison' or not _p.fiscalyear: if _p.comparison_mode == 'no_comparison' or not _p.fiscalyear:
c_specs += [('balance', 1, 0, 'text', _('Balance'), None, cell_style_right)]
c_specs += [('balance', 1, 0, 'text',
_('Balance'), None, cell_style_right)]
else: else:
c_specs += [('balance_fy', 1, 0, 'text', _('Balance %s') % _p.fiscalyear.name, None, cell_style_right)]
c_specs += [('balance_fy', 1, 0, 'text', _('Balance %s') %
_p.fiscalyear.name, None, cell_style_right)]
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
for index in range(_p.nb_comparison): for index in range(_p.nb_comparison):
if _p.comp_params[index]['comparison_filter'] == 'filter_year' and _p.comp_params[index].get('fiscalyear', False):
c_specs += [('balance_%s' %index, 1, 0, 'text', _('Balance %s') % _p.comp_params[index]['fiscalyear'].name, None, cell_style_right)]
if _p.comp_params[index][
'comparison_filter'] == 'filter_year' \
and _p.comp_params[index].get('fiscalyear', False):
c_specs += [('balance_%s' % index, 1, 0, 'text',
_('Balance %s') %
_p.comp_params[index]['fiscalyear'].name,
None, cell_style_right)]
else: else:
c_specs += [('balance_%s' %index, 1, 0, 'text', _('Balance C%s') % (index + 1), None, cell_style_right)]
c_specs += [('balance_%s' % index, 1, 0, 'text',
_('Balance C%s') % (index + 1), None,
cell_style_right)]
if _p.comparison_mode == 'single': if _p.comparison_mode == 'single':
c_specs += [ c_specs += [
('diff', 1, 0, 'text', _('Difference'), None, cell_style_right),
('diff_percent', 1, 0, 'text', _('% Difference'), None, cell_style_center),
]
('diff', 1, 0, 'text', _('Difference'),
None, cell_style_right),
('diff_percent', 1, 0, 'text',
_('% Difference'), None, cell_style_center),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, row_style=cell_style)
row_position = self.xls_write_row(
ws, row_position, row_data, row_style=cell_style)
return row_position return row_position
def print_row_code_account(self, ws, current_account, row_position, _xs, xlwt):
cell_format = _xs['xls_title'] + _xs['bold'] + _xs['fill'] + _xs['borders_all']
def print_row_code_account(self, ws, current_account, row_position, _xs,
xlwt):
cell_format = _xs['xls_title'] + _xs['bold'] + \
_xs['fill'] + _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
c_specs = [ ('acc_title', 7, 0, 'text', ' - '.join([current_account.code, current_account.name])), ]
c_specs = [
('acc_title', 7, 0, 'text', ' - '.join([current_account.code,
current_account.name])), ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, cell_style)
return row_position
def print_account_totals(self, _xs, xlwt, ws, row_start_account, row_position, current_account,_p):
cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all'] + _xs['wrap'] + _xs['top']
row_position = self.xls_write_row(
ws, row_position, row_data, cell_style)
return row_position
def print_account_totals(self, _xs, xlwt, ws, row_start_account,
row_position, current_account, _p):
cell_format = _xs['bold'] + _xs['fill'] + \
_xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_decimal = xlwt.easyxf(cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
c_specs = [
('acc_title', 2, 0, 'text', current_account.name),
('code', 1, 0, 'text', current_account.code),
cell_style_decimal = xlwt.easyxf(
cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
c_specs = [
('acc_title', 2, 0, 'text', current_account.name),
('code', 1, 0, 'text', current_account.code),
] ]
for column in range(3,7):
if (_p.comparison_mode == 'single' and column == 6): #in case of one single comparison, the column 6 will contain percentages
total_diff = rowcol_to_cell(row_position, column-1)
total_balance = rowcol_to_cell(row_position, column-2)
account_formula = 'Round('+ total_diff + '/' + total_balance + '*100;0)'
else:
account_start = rowcol_to_cell(row_start_account, column)
account_end = rowcol_to_cell(row_position -1, column)
account_formula = 'Round(SUM(' + account_start + ':' + account_end + ');2)'
c_specs += [('total%s' %column, 1, 0, 'text', None, account_formula, None, cell_style_decimal)]
for column in range(3, 7):
# in case of one single comparison, the column 6 will contain
# percentages
if (_p.comparison_mode == 'single' and column == 6):
total_diff = rowcol_to_cell(row_position, column - 1)
total_balance = rowcol_to_cell(row_position, column - 2)
account_formula = 'Round(' + total_diff + \
'/' + total_balance + '*100;0)'
else:
account_start = rowcol_to_cell(row_start_account, column)
account_end = rowcol_to_cell(row_position - 1, column)
account_formula = 'Round(SUM(' + \
account_start + ':' + account_end + ');2)'
c_specs += [('total%s' % column, 1, 0, 'text', None,
account_formula, None, cell_style_decimal)]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_position = self.xls_write_row(ws, row_position, row_data, cell_style)
row_position = self.xls_write_row(
ws, row_position, row_data, cell_style)
return row_position + 1 return row_position + 1
def generate_xls_report(self, _p, _xs, data, objects, wb): def generate_xls_report(self, _p, _xs, data, objects, wb):
# Initialisations # Initialisations
ws = wb.add_sheet(_p.report_name[:31]) ws = wb.add_sheet(_p.report_name[:31])
ws.panes_frozen = True ws.panes_frozen = True
ws.remove_splits = True ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1 ws.fit_width_to_pages = 1
row_pos = 0 row_pos = 0
ws.header_str = self.xls_headers['standard'] ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard']
ws.footer_str = self.xls_footers['standard']
# Print Title # Print Title
row_pos = self.print_title(ws, _p, row_pos, xlwt, _xs)
row_pos = self.print_title(ws, _p, row_pos, xlwt, _xs)
# Print empty row to define column sizes # Print empty row to define column sizes
row_pos = self.print_empty_row(ws, row_pos)
# Print Header Table titles (Fiscal Year - Accounts Filter - Periods Filter...)
row_pos = self.print_empty_row(ws, row_pos)
# Print Header Table titles (Fiscal Year - Accounts Filter - Periods
# Filter...)
row_pos = self.print_header_titles(ws, _p, data, row_pos, xlwt, _xs) row_pos = self.print_header_titles(ws, _p, data, row_pos, xlwt, _xs)
initial_balance_text = {'initial_balance': _('Computed'), 'opening_balance': _('Opening Entries'), False: _('No')} # cf. account_report_partner_balance.mako
initial_balance_text = {
'initial_balance': _('Computed'),
'opening_balance': _('Opening Entries'),
False: _('No')} # cf. account_report_partner_balance.mako
# Print Header Table data # Print Header Table data
row_pos = self.print_header_data(ws, _p, data, row_pos, xlwt, _xs, initial_balance_text)
row_pos = self.print_header_data(
ws, _p, data, row_pos, xlwt, _xs, initial_balance_text)
# Print comparison header table # Print comparison header table
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
row_pos += 1 row_pos += 1
row_pos = self.print_comparison_header(_xs, xlwt, row_pos, _p, ws, initial_balance_text)
row_pos = self.print_comparison_header(
_xs, xlwt, row_pos, _p, ws, initial_balance_text)
# Freeze the line # Freeze the line
ws.set_horz_split_pos(row_pos)
ws.set_horz_split_pos(row_pos)
# cell styles for account data # cell styles for account data
regular_cell_format = _xs['borders_all'] regular_cell_format = _xs['borders_all']
regular_cell_style = xlwt.easyxf(regular_cell_format) regular_cell_style = xlwt.easyxf(regular_cell_format)
regular_cell_style_center = xlwt.easyxf(regular_cell_format + _xs['center'])
regular_cell_style_decimal = xlwt.easyxf(regular_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
regular_cell_style_pct = xlwt.easyxf(regular_cell_format + _xs['center'], num_format_str = '0')
regular_cell_style_decimal = xlwt.easyxf(
regular_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
row_pos += 1 row_pos += 1
for current_account in objects: for current_account in objects:
@ -238,14 +307,15 @@ class partners_balance_xls(report_xls):
continue continue
comparisons = current_account.comparisons comparisons = current_account.comparisons
# in multiple columns mode, we do not want to print accounts without any rows
# in multiple columns mode, we do not want to print accounts
# without any rows
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
all_comparison_lines = [comp['partners_amounts'][partner_id[1]] all_comparison_lines = [comp['partners_amounts'][partner_id[1]]
for partner_id in partners_order
for comp in comparisons]
for partner_id in partners_order
for comp in comparisons]
if not display_line(all_comparison_lines): if not display_line(all_comparison_lines):
continue
continue
current_partner_amounts = current_account.partners_amounts current_partner_amounts = current_account.partners_amounts
@ -255,30 +325,42 @@ class partners_balance_xls(report_xls):
comparison_total[i] = {'balance': 0.0} comparison_total[i] = {'balance': 0.0}
# print row: Code - Account name # print row: Code - Account name
row_pos = self.print_row_code_account(ws, current_account, row_pos, _xs, xlwt)
row_pos = self.print_row_code_account(
ws, current_account, row_pos, _xs, xlwt)
row_account_start = row_pos row_account_start = row_pos
# Print row: Titles "Account/Partner Name-Code/ref-Initial Balance-Debit-Credit-Balance" or "Account/Partner Name-Code/ref-Balance Year-Balance Year2-Balance C2-Balance C3"
row_pos = self.print_account_header(ws, _p, _xs, xlwt, row_pos)
# Print row: Titles "Account/Partner Name-Code/ref-Initial
# Balance-Debit-Credit-Balance" or "Account/Partner
# Name-Code/ref-Balance Year-Balance Year2-Balance C2-Balance C3"
row_pos = self.print_account_header(ws, _p, _xs, xlwt, row_pos)
for (partner_code_name, partner_id, partner_ref, partner_name) in partners_order:
for (partner_code_name, partner_id, partner_ref, partner_name) \
in partners_order:
partner = current_partner_amounts.get(partner_id, {}) partner = current_partner_amounts.get(partner_id, {})
# in single mode, we have to display all the partners even if their balance is 0.0 because the initial balance should match with the previous year closings
# in multiple columns mode, we do not want to print partners which have a balance at 0.0 in each comparison column
# in single mode, we have to display all the partners even if
# their balance is 0.0 because the initial balance should match
# with the previous year closings
# in multiple columns mode, we do not want to print partners
# which have a balance at 0.0 in each comparison column
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
all_comparison_lines = [comp['partners_amounts'][partner_id]
for comp in comparisons
if comp['partners_amounts'].get(partner_id)]
all_comparison_lines = [comp['partners_amounts']
[partner_id]
for comp in comparisons
if comp['partners_amounts'].
get(partner_id)]
if not display_line(all_comparison_lines): if not display_line(all_comparison_lines):
continue continue
# display data row # display data row
if len(_p.comp_params) == 2: if len(_p.comp_params) == 2:
account_span = 3 account_span = 3
else: else:
account_span = _p.initial_balance_mode and 2 or 3 account_span = _p.initial_balance_mode and 2 or 3
c_specs = [('acc_title', account_span, 0, 'text', partner_name if partner_name else _('Unallocated'))]
c_specs += [('partner_ref', 1, 0, 'text', partner_ref if partner_ref else '')]
c_specs = [('acc_title', account_span, 0, 'text',
partner_name if partner_name else
_('Unallocated'))]
c_specs += [('partner_ref', 1, 0, 'text',
partner_ref if partner_ref else '')]
if _p.comparison_mode == 'no_comparison': if _p.comparison_mode == 'no_comparison':
bal_formula = '' bal_formula = ''
if _p.initial_balance_mode: if _p.initial_balance_mode:
@ -286,43 +368,60 @@ class partners_balance_xls(report_xls):
bal_formula = init_bal_cell + '+' bal_formula = init_bal_cell + '+'
debit_col = 4 debit_col = 4
c_specs += [ c_specs += [
('init_bal', 1, 0, 'number', partner.get('init_balance', 0.0), None, regular_cell_style_decimal),
]
('init_bal', 1, 0, 'number', partner.get(
'init_balance', 0.0), None,
regular_cell_style_decimal),
]
else: else:
debit_col = 3 debit_col = 3
c_specs += [ c_specs += [
('debit', 1, 0, 'number', partner.get('debit', 0.0), None, regular_cell_style_decimal),
('credit', 1, 0, 'number', partner.get('credit', 0.0), None, regular_cell_style_decimal),
]
('debit', 1, 0, 'number', partner.get('debit', 0.0),
None, regular_cell_style_decimal),
('credit', 1, 0, 'number', partner.get('credit', 0.0),
None, regular_cell_style_decimal),
]
debit_cell = rowcol_to_cell(row_pos, debit_col) debit_cell = rowcol_to_cell(row_pos, debit_col)
credit_cell = rowcol_to_cell(row_pos, debit_col+1)
credit_cell = rowcol_to_cell(row_pos, debit_col + 1)
bal_formula += debit_cell + '-' + credit_cell bal_formula += debit_cell + '-' + credit_cell
c_specs += [('bal', 1, 0, 'number', None, bal_formula, regular_cell_style_decimal),]
c_specs += [('bal', 1, 0, 'number', None,
bal_formula, regular_cell_style_decimal), ]
else: else:
c_specs += [('bal', 1, 0, 'number', partner.get('balance', 0.0), None, regular_cell_style_decimal),]
c_specs += [('bal', 1, 0, 'number', partner.get('balance',
0.0),
None, regular_cell_style_decimal), ]
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
for i, comp in enumerate(comparisons): for i, comp in enumerate(comparisons):
comp_partners = comp['partners_amounts']
balance = diff = percent_diff = 0
if comp_partners.get(partner_id):
balance = comp_partners[partner_id]['balance']
diff = comp_partners[partner_id]['diff']
percent_diff = comp_partners[partner_id]['percent_diff']
comparison_total[i]['balance'] += balance
c_specs += [('balance_%s' %i, 1, 0, 'number', balance, None, regular_cell_style_decimal), ]
if _p.comparison_mode == 'single': ## no diff in multiple comparisons because it shows too much data
c_specs += [('balance_diff', 1, 0, 'number', diff, None, regular_cell_style_decimal), ]
comp_partners = comp['partners_amounts']
balance = diff = percent_diff = 0
if comp_partners.get(partner_id):
balance = comp_partners[partner_id]['balance']
diff = comp_partners[partner_id]['diff']
percent_diff = comp_partners[
partner_id]['percent_diff']
comparison_total[i]['balance'] += balance
c_specs += [('balance_%s' % i, 1, 0, 'number',
balance, None,
regular_cell_style_decimal), ]
# no diff in multiple comparisons because it shows too much
# data
if _p.comparison_mode == 'single':
c_specs += [('balance_diff', 1, 0, 'number',
diff, None, regular_cell_style_decimal), ]
if percent_diff is False: if percent_diff is False:
c_specs += [('balance', 1, 0, 'number', diff, None, regular_cell_style_decimal), ]
c_specs += [('balance', 1, 0, 'number',
diff, None, regular_cell_style_decimal), ]
else: else:
c_specs += [('perc_diff', 1, 0, 'number', int(round(percent_diff))), ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, regular_cell_style)
c_specs += [('perc_diff', 1, 0, 'number',
int(round(percent_diff))), ]
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, regular_cell_style)
row_pos = self.print_account_totals(_xs, xlwt, ws, row_account_start, row_pos, current_account,_p)
partners_balance_xls('report.account.account_report_partner_balance_xls', 'account.account',
parser=PartnerBalanceWebkit)
row_pos = self.print_account_totals(
_xs, xlwt, ws, row_account_start, row_pos, current_account, _p)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
partners_balance_xls('report.account.account_report_partner_balance_xls',
'account.account',
parser=PartnerBalanceWebkit)

263
account_financial_report_webkit_xls/report/trial_balance_xls.py

@ -21,49 +21,56 @@
############################################################################## ##############################################################################
import xlwt import xlwt
import time
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell from openerp.addons.report_xls.utils import rowcol_to_cell
from openerp.addons.account_financial_report_webkit.report.trial_balance import TrialBalanceWebkit
from openerp.addons.account_financial_report_webkit.report.trial_balance \
import TrialBalanceWebkit
from openerp.tools.translate import _ from openerp.tools.translate import _
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
class trial_balance_xls(report_xls): class trial_balance_xls(report_xls):
column_sizes = [12,60,17,17,17,17,17,17]
column_sizes = [12, 60, 17, 17, 17, 17, 17, 17]
def generate_xls_report(self, _p, _xs, data, objects, wb): def generate_xls_report(self, _p, _xs, data, objects, wb):
ws = wb.add_sheet(_p.report_name[:31]) ws = wb.add_sheet(_p.report_name[:31])
ws.panes_frozen = True ws.panes_frozen = True
ws.remove_splits = True ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1 ws.fit_width_to_pages = 1
row_pos = 0 row_pos = 0
# set print header/footer # set print header/footer
ws.header_str = self.xls_headers['standard'] ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard'] ws.footer_str = self.xls_footers['standard']
# cf. account_report_trial_balance.mako
initial_balance_text = {'initial_balance': _('Computed'), 'opening_balance': _('Opening Entries'), False: _('No')}
# cf. account_report_trial_balance.mako
initial_balance_text = {'initial_balance': _('Computed'),
'opening_balance': _('Opening Entries'),
False: _('No')}
# Title # Title
cell_style = xlwt.easyxf(_xs['xls_title']) cell_style = xlwt.easyxf(_xs['xls_title'])
report_name = ' - '.join([_p.report_name.upper(), _p.company.partner_id.name, _p.company.currency_id.name])
report_name = ' - '.join([_p.report_name.upper(),
_p.company.partner_id.name,
_p.company.currency_id.name])
c_specs = [ c_specs = [
('report_name', 1, 0, 'text', report_name), ('report_name', 1, 0, 'text', report_name),
]
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
# write empty row to define column sizes # write empty row to define column sizes
c_sizes = self.column_sizes c_sizes = self.column_sizes
c_specs = [('empty%s'%i, 1, c_sizes[i], 'text', None) for i in range(0,len(c_sizes))]
c_specs = [('empty%s' % i, 1, c_sizes[i], 'text', None)
for i in range(0, len(c_sizes))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, set_column_size=True)
row_pos = self.xls_write_row(
ws, row_pos, row_data, set_column_size=True)
# Header Table # Header Table
cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all'] cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
@ -71,24 +78,29 @@ class trial_balance_xls(report_xls):
c_specs = [ c_specs = [
('fy', 1, 0, 'text', _('Fiscal Year')), ('fy', 1, 0, 'text', _('Fiscal Year')),
('af', 2, 0, 'text', _('Accounts Filter')), ('af', 2, 0, 'text', _('Accounts Filter')),
('df', 1, 0, 'text', _p.filter_form(data) == 'filter_date' and _('Dates Filter') or _('Periods Filter')),
('df', 1, 0, 'text', _p.filter_form(data) ==
'filter_date' and _('Dates Filter') or _('Periods Filter')),
('tm', 2, 0, 'text', _('Target Moves'), None, cell_style_center), ('tm', 2, 0, 'text', _('Target Moves'), None, cell_style_center),
('ib', 1, 0, 'text', _('Initial Balance'), None, cell_style_center),
('coa', 1, 0, 'text', _('Chart of Account'), None, cell_style_center),
]
('ib', 1, 0, 'text', _('Initial Balance'),
None, cell_style_center),
('coa', 1, 0, 'text', _('Chart of Account'),
None, cell_style_center),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
cell_format = _xs['borders_all'] + _xs['wrap'] + _xs['top'] cell_format = _xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_center = xlwt.easyxf(cell_format + _xs['center']) cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
c_specs = [ c_specs = [
('fy', 1, 0, 'text', _p.fiscalyear.name if _p.fiscalyear else '-'), ('fy', 1, 0, 'text', _p.fiscalyear.name if _p.fiscalyear else '-'),
('af', 2, 0, 'text', _p.accounts(data) and ', '.join([account.code for account in _p.accounts(data)]) or _('All')),
('af', 2, 0, 'text', _p.accounts(data) and ', '.join(
[account.code for account in _p.accounts(data)]) or _('All')),
] ]
df = _('From') + ': ' df = _('From') + ': '
if _p.filter_form(data) == 'filter_date': if _p.filter_form(data) == 'filter_date':
df += _p.start_date if _p.start_date else u''
df += _p.start_date if _p.start_date else u''
else: else:
df += _p.start_period.name if _p.start_period else u'' df += _p.start_period.name if _p.start_period else u''
df += ' ' + _('\nTo') + ': ' df += ' ' + _('\nTo') + ': '
@ -98,38 +110,58 @@ class trial_balance_xls(report_xls):
df += _p.stop_period.name if _p.stop_period else u'' df += _p.stop_period.name if _p.stop_period else u''
c_specs += [ c_specs += [
('df', 1, 0, 'text', df), ('df', 1, 0, 'text', df),
('tm', 2, 0, 'text', _p.display_target_move(data), None, cell_style_center),
('ib', 1, 0, 'text', initial_balance_text[_p.initial_balance_mode], None, cell_style_center),
('coa', 1, 0, 'text', _p.chart_account.name, None, cell_style_center),
]
('tm', 2, 0, 'text', _p.display_target_move(
data), None, cell_style_center),
('ib', 1, 0, 'text', initial_balance_text[
_p.initial_balance_mode], None, cell_style_center),
('coa', 1, 0, 'text', _p.chart_account.name,
None, cell_style_center),
]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
# comparison header table # comparison header table
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
row_pos += 1 row_pos += 1
cell_format_ct = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all']
cell_format_ct = _xs['bold'] + \
_xs['fill_blue'] + _xs['borders_all']
cell_style_ct = xlwt.easyxf(cell_format_ct) cell_style_ct = xlwt.easyxf(cell_format_ct)
c_specs = [('ct', 8, 0, 'text', _('Comparisons'))]
c_specs = [('ct', 8, 0, 'text', _('Comparisons'))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style_ct)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style_ct)
cell_style_center = xlwt.easyxf(cell_format) cell_style_center = xlwt.easyxf(cell_format)
for index, params in enumerate(_p.comp_params): for index, params in enumerate(_p.comp_params):
c_specs = [('c', 3, 0, 'text', _('Comparison') + str(index + 1) + ' (C' + str(index + 1) + ')')]
c_specs = [
('c', 3, 0, 'text', _('Comparison') + str(index + 1) +
' (C' + str(index + 1) + ')')]
if params['comparison_filter'] == 'filter_date': if params['comparison_filter'] == 'filter_date':
c_specs += [('f', 3, 0, 'text', _('Dates Filter') + ': ' + _p.formatLang(params['start'], date=True) + ' - ' + _p.formatLang(params['stop'], date=True))]
c_specs += [('f', 3, 0, 'text', _('Dates Filter') + ': ' +
_p.formatLang(
params['start'], date=True) + ' - ' +
_p.formatLang(params['stop'], date=True))]
elif params['comparison_filter'] == 'filter_period': elif params['comparison_filter'] == 'filter_period':
c_specs += [('f', 3, 0, 'text', _('Periods Filter') + ': ' + params['start'].name + ' - ' + params['stop'].name)]
c_specs += [('f', 3, 0, 'text', _('Periods Filter') +
': ' + params['start'].name + ' - ' +
params['stop'].name)]
else: else:
c_specs += [('f', 3, 0, 'text', _('Fiscal Year') + ': ' + params['fiscalyear'].name)]
c_specs += [('ib', 2, 0, 'text', _('Initial Balance') + ': ' + initial_balance_text[params['initial_balance_mode']])]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style_center)
c_specs += [('f', 3, 0, 'text', _('Fiscal Year') +
': ' + params['fiscalyear'].name)]
c_specs += [('ib', 2, 0, 'text', _('Initial Balance') +
': ' +
initial_balance_text[
params['initial_balance_mode']])]
row_data = self.xls_row_template(
c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style_center)
row_pos += 1 row_pos += 1
# Column Header Row # Column Header Row
cell_format = _xs['bold'] + _xs['fill_blue'] + _xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_format = _xs['bold'] + _xs['fill_blue'] + \
_xs['borders_all'] + _xs['wrap'] + _xs['top']
cell_style = xlwt.easyxf(cell_format) cell_style = xlwt.easyxf(cell_format)
cell_style_right = xlwt.easyxf(cell_format + _xs['right']) cell_style_right = xlwt.easyxf(cell_format + _xs['right'])
cell_style_center = xlwt.easyxf(cell_format + _xs['center']) cell_style_center = xlwt.easyxf(cell_format + _xs['center'])
@ -143,46 +175,65 @@ class trial_balance_xls(report_xls):
] ]
if _p.comparison_mode == 'no_comparison': if _p.comparison_mode == 'no_comparison':
if _p.initial_balance_mode: if _p.initial_balance_mode:
c_specs += [('init_bal', 1, 0, 'text', _('Initial Balance'), None, cell_style_right)]
c_specs += [('init_bal', 1, 0, 'text',
_('Initial Balance'), None, cell_style_right)]
c_specs += [ c_specs += [
('debit', 1, 0, 'text', _('Debit'), None, cell_style_right), ('debit', 1, 0, 'text', _('Debit'), None, cell_style_right),
('credit', 1, 0, 'text', _('Credit'), None, cell_style_right), ('credit', 1, 0, 'text', _('Credit'), None, cell_style_right),
]
]
if _p.comparison_mode == 'no_comparison' or not _p.fiscalyear: if _p.comparison_mode == 'no_comparison' or not _p.fiscalyear:
c_specs += [('balance', 1, 0, 'text', _('Balance'), None, cell_style_right)]
c_specs += [('balance', 1, 0, 'text',
_('Balance'), None, cell_style_right)]
else: else:
c_specs += [('balance_fy', 1, 0, 'text', _('Balance %s') % _p.fiscalyear.name, None, cell_style_right)]
c_specs += [('balance_fy', 1, 0, 'text', _('Balance %s') %
_p.fiscalyear.name, None, cell_style_right)]
if _p.comparison_mode in ('single', 'multiple'): if _p.comparison_mode in ('single', 'multiple'):
for index in range(_p.nb_comparison): for index in range(_p.nb_comparison):
if _p.comp_params[index]['comparison_filter'] == 'filter_year' and _p.comp_params[index].get('fiscalyear', False):
c_specs += [('balance_%s' %index, 1, 0, 'text', _('Balance %s') % _p.comp_params[index]['fiscalyear'].name, None, cell_style_right)]
if _p.comp_params[index][
'comparison_filter'] == 'filter_year' \
and _p.comp_params[index].get('fiscalyear', False):
c_specs += [('balance_%s' % index, 1, 0, 'text',
_('Balance %s') %
_p.comp_params[index]['fiscalyear'].name,
None, cell_style_right)]
else: else:
c_specs += [('balance_%s' %index, 1, 0, 'text', _('Balance C%s') % (index + 1), None, cell_style_right)]
c_specs += [('balance_%s' % index, 1, 0, 'text',
_('Balance C%s') % (index + 1), None,
cell_style_right)]
if _p.comparison_mode == 'single': if _p.comparison_mode == 'single':
c_specs += [ c_specs += [
('diff', 1, 0, 'text', _('Difference'), None, cell_style_right),
('diff_percent', 1, 0, 'text', _('% Difference'), None, cell_style_center),
]
c_specs += [('type', 1, 0, 'text', _('Type'), None, cell_style_center)]
('diff', 1, 0, 'text', _('Difference'),
None, cell_style_right),
('diff_percent', 1, 0, 'text',
_('% Difference'), None, cell_style_center),
]
c_specs += [('type', 1, 0, 'text', _('Type'), None, cell_style_center)]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
ws.set_horz_split_pos(row_pos)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
ws.set_horz_split_pos(row_pos)
last_child_consol_ids = [] last_child_consol_ids = []
last_level = False
# cell styles for account data # cell styles for account data
view_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all'] view_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
view_cell_style = xlwt.easyxf(view_cell_format) view_cell_style = xlwt.easyxf(view_cell_format)
view_cell_style_center = xlwt.easyxf(view_cell_format + _xs['center']) view_cell_style_center = xlwt.easyxf(view_cell_format + _xs['center'])
view_cell_style_decimal = xlwt.easyxf(view_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
view_cell_style_pct = xlwt.easyxf(view_cell_format + _xs['center'], num_format_str = '0')
view_cell_style_decimal = xlwt.easyxf(
view_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
view_cell_style_pct = xlwt.easyxf(
view_cell_format + _xs['center'], num_format_str='0')
regular_cell_format = _xs['borders_all'] regular_cell_format = _xs['borders_all']
regular_cell_style = xlwt.easyxf(regular_cell_format) regular_cell_style = xlwt.easyxf(regular_cell_format)
regular_cell_style_center = xlwt.easyxf(regular_cell_format + _xs['center'])
regular_cell_style_decimal = xlwt.easyxf(regular_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
regular_cell_style_pct = xlwt.easyxf(regular_cell_format + _xs['center'], num_format_str = '0')
regular_cell_style_center = xlwt.easyxf(
regular_cell_format + _xs['center'])
regular_cell_style_decimal = xlwt.easyxf(
regular_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
regular_cell_style_pct = xlwt.easyxf(
regular_cell_format + _xs['center'], num_format_str='0')
for current_account in objects: for current_account in objects:
@ -199,20 +250,16 @@ class trial_balance_xls(report_xls):
cell_style_center = regular_cell_style_center cell_style_center = regular_cell_style_center
cell_style_decimal = regular_cell_style_decimal cell_style_decimal = regular_cell_style_decimal
cell_style_pct = regular_cell_style_pct cell_style_pct = regular_cell_style_pct
comparisons = current_account.comparisons comparisons = current_account.comparisons
if current_account.id in last_child_consol_ids:
# current account is a consolidation child of the last account: use the level of last account
level = last_level
level_class = 'account_level_consol'
else:
# current account is a not a consolidation child: use its own level
level = current_account.level or 0
level_class = "account_level_%s" % (level,)
last_child_consol_ids = [child_consol_id.id for child_consol_id in current_account.child_consol_ids]
last_level = current_account.level
if current_account.id not in last_child_consol_ids:
# current account is a not a consolidation child: use its own
# level
last_child_consol_ids = [
child_consol_id.id for child_consol_id in
current_account.child_consol_ids]
c_specs = [ c_specs = [
('code', 1, 0, 'text', current_account.code), ('code', 1, 0, 'text', current_account.code),
('account', account_span, 0, 'text', current_account.name), ('account', account_span, 0, 'text', current_account.name),
@ -222,37 +269,51 @@ class trial_balance_xls(report_xls):
debit_cell = rowcol_to_cell(row_pos, 4) debit_cell = rowcol_to_cell(row_pos, 4)
credit_cell = rowcol_to_cell(row_pos, 5) credit_cell = rowcol_to_cell(row_pos, 5)
bal_formula = debit_cell + '-' + credit_cell bal_formula = debit_cell + '-' + credit_cell
if _p.initial_balance_mode: if _p.initial_balance_mode:
init_cell = rowcol_to_cell(row_pos, 3) init_cell = rowcol_to_cell(row_pos, 3)
debit_cell = rowcol_to_cell(row_pos, 4)
debit_cell = rowcol_to_cell(row_pos, 4)
credit_cell = rowcol_to_cell(row_pos, 5) credit_cell = rowcol_to_cell(row_pos, 5)
bal_formula = init_cell + '+' + debit_cell + '-' + credit_cell
c_specs += [('init_bal', 1, 0, 'number', current_account.init_balance, None, cell_style_decimal)]
bal_formula = init_cell + '+' + \
debit_cell + '-' + credit_cell
c_specs += [('init_bal', 1, 0, 'number',
current_account.init_balance, None,
cell_style_decimal)]
c_specs += [ c_specs += [
('debit', 1, 0, 'number', current_account.debit, None, cell_style_decimal),
('credit', 1, 0, 'number', current_account.credit, None, cell_style_decimal),
]
c_specs += [('balance', 1, 0, 'number', None, bal_formula, cell_style_decimal)]
('debit', 1, 0, 'number', current_account.debit,
None, cell_style_decimal),
('credit', 1, 0, 'number', current_account.credit,
None, cell_style_decimal),
]
c_specs += [('balance', 1, 0, 'number', None,
bal_formula, cell_style_decimal)]
else: else:
c_specs += [('balance', 1, 0, 'number', current_account.balance, None, cell_style_decimal)]
if _p.comparison_mode in ('single', 'multiple'):
c_specs += [('balance', 1, 0, 'number',
current_account.balance, None,
cell_style_decimal)]
if _p.comparison_mode in ('single', 'multiple'):
c = 1 c = 1
for comp_account in comparisons: for comp_account in comparisons:
c_specs += [('balance_%s' %c, 1, 0, 'number', comp_account['balance'], None, cell_style_decimal)]
c_specs += [('balance_%s' % c, 1, 0, 'number',
comp_account['balance'], None,
cell_style_decimal)]
c += 1 c += 1
if _p.comparison_mode == 'single': if _p.comparison_mode == 'single':
c_specs += [ c_specs += [
('diff', 1, 0, 'number', comp_account['diff'], None, cell_style_decimal),
('diff_percent', 1, 0, 'number', comp_account['percent_diff'] and comp_account['percent_diff'] or 0, None, cell_style_pct),
]
c_specs += [('type', 1, 0, 'text', current_account.type, None, cell_style_center)]
('diff', 1, 0, 'number', comp_account[
'diff'], None, cell_style_decimal),
('diff_percent', 1, 0, 'number', comp_account[
'percent_diff'] and comp_account['percent_diff']
or 0, None, cell_style_pct),
]
c_specs += [('type', 1, 0, 'text',
current_account.type, None, cell_style_center)]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
trial_balance_xls('report.account.account_report_trial_balance_xls', 'account.account',
parser=TrialBalanceWebkit)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
trial_balance_xls('report.account.account_report_trial_balance_xls',
'account.account',
parser=TrialBalanceWebkit)

2
account_financial_report_webkit_xls/wizard/__init__.py

@ -24,4 +24,4 @@ from . import general_ledger_wizard
from . import trial_balance_wizard from . import trial_balance_wizard
from . import partners_balance_wizard from . import partners_balance_wizard
from . import partners_ledger_wizard from . import partners_ledger_wizard
from . import open_invoices_wizard
from . import open_invoices_wizard

11
account_financial_report_webkit_xls/wizard/general_ledger_wizard.py

@ -21,12 +21,13 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
class general_ledger_webkit_wizard(orm.TransientModel): class general_ledger_webkit_wizard(orm.TransientModel):
_inherit = 'general.ledger.webkit' _inherit = 'general.ledger.webkit'
def xls_export(self, cr, uid, ids, context=None): def xls_export(self, cr, uid, ids, context=None):
return self.check_report(cr, uid, ids, context=context) return self.check_report(cr, uid, ids, context=context)
@ -39,5 +40,5 @@ class general_ledger_webkit_wizard(orm.TransientModel):
'report_name': 'account.account_report_general_ledger_xls', 'report_name': 'account.account_report_general_ledger_xls',
'datas': data} 'datas': data}
else: else:
return super(general_ledger_webkit_wizard, self)._print_report(cr, uid, ids, data, context=context)
return super(general_ledger_webkit_wizard, self)._print_report(
cr, uid, ids, data, context=context)

10
account_financial_report_webkit_xls/wizard/open_invoices_wizard.py

@ -21,12 +21,13 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
class open_invoices_webkit_wizard(orm.TransientModel): class open_invoices_webkit_wizard(orm.TransientModel):
_inherit = 'open.invoices.webkit' _inherit = 'open.invoices.webkit'
def xls_export(self, cr, uid, ids, context=None): def xls_export(self, cr, uid, ids, context=None):
return self.check_report(cr, uid, ids, context=context) return self.check_report(cr, uid, ids, context=context)
@ -39,4 +40,5 @@ class open_invoices_webkit_wizard(orm.TransientModel):
'report_name': 'account.account_report_open_invoices_xls', 'report_name': 'account.account_report_open_invoices_xls',
'datas': data} 'datas': data}
else: else:
return super(open_invoices_webkit_wizard, self)._print_report(cr, uid, ids, data, context=context)
return super(open_invoices_webkit_wizard, self)._print_report(
cr, uid, ids, data, context=context)

18
account_financial_report_webkit_xls/wizard/partners_balance_wizard.py

@ -21,12 +21,13 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
class partner_balance_wizard(orm.TransientModel): class partner_balance_wizard(orm.TransientModel):
_inherit = 'partner.balance.webkit' _inherit = 'partner.balance.webkit'
def xls_export(self, cr, uid, ids, context=None): def xls_export(self, cr, uid, ids, context=None):
return self.check_report(cr, uid, ids, context=context) return self.check_report(cr, uid, ids, context=context)
@ -35,9 +36,10 @@ class partner_balance_wizard(orm.TransientModel):
if context.get('xls_export'): if context.get('xls_export'):
# we update form with display account value # we update form with display account value
data = self.pre_print_report(cr, uid, ids, data, context=context) data = self.pre_print_report(cr, uid, ids, data, context=context)
return {'type': 'ir.actions.report.xml',
'report_name': 'account.account_report_partner_balance_xls',
'datas': data}
return {
'type': 'ir.actions.report.xml',
'report_name': 'account.account_report_partner_balance_xls',
'datas': data}
else: else:
return super(partner_balance_wizard, self)._print_report(cr, uid, ids, data, context=context)
return super(partner_balance_wizard, self)._print_report(
cr, uid, ids, data, context=context)

10
account_financial_report_webkit_xls/wizard/partners_ledger_wizard.py

@ -21,12 +21,13 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
class partner_ledger_webkit_wizard(orm.TransientModel): class partner_ledger_webkit_wizard(orm.TransientModel):
_inherit = 'partners.ledger.webkit' _inherit = 'partners.ledger.webkit'
def xls_export(self, cr, uid, ids, context=None): def xls_export(self, cr, uid, ids, context=None):
return self.check_report(cr, uid, ids, context=context) return self.check_report(cr, uid, ids, context=context)
@ -39,4 +40,5 @@ class partner_ledger_webkit_wizard(orm.TransientModel):
'report_name': 'account.account_report_partner_ledger_xls', 'report_name': 'account.account_report_partner_ledger_xls',
'datas': data} 'datas': data}
else: else:
return super(partner_ledger_webkit_wizard, self)._print_report(cr, uid, ids, data, context=context)
return super(partner_ledger_webkit_wizard, self)._print_report(
cr, uid, ids, data, context=context)

11
account_financial_report_webkit_xls/wizard/trial_balance_wizard.py

@ -21,12 +21,13 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
#import logging
#_logger = logging.getLogger(__name__)
# import logging
# _logger = logging.getLogger(__name__)
class trial_balance_wizard(orm.TransientModel): class trial_balance_wizard(orm.TransientModel):
_inherit = 'trial.balance.webkit' _inherit = 'trial.balance.webkit'
def xls_export(self, cr, uid, ids, context=None): def xls_export(self, cr, uid, ids, context=None):
return self.check_report(cr, uid, ids, context=context) return self.check_report(cr, uid, ids, context=context)
@ -39,5 +40,5 @@ class trial_balance_wizard(orm.TransientModel):
'report_name': 'account.account_report_trial_balance_xls', 'report_name': 'account.account_report_trial_balance_xls',
'datas': data} 'datas': data}
else: else:
return super(trial_balance_wizard, self)._print_report(cr, uid, ids, data, context=context)
return super(trial_balance_wizard, self)._print_report(
cr, uid, ids, data, context=context)

5
account_journal_report_xls/__init__.py

@ -26,6 +26,5 @@ try:
from . import report from . import report
except ImportError: except ImportError:
import logging import logging
logging.getLogger('openerp.module').warning('report_xls not available in addons path. account_financial_report_webkit_xls will not be usable')
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
logging.getLogger('openerp.module').warning('''report_xls not available in
addons path. account_financial_report_webkit_xls will not be usable''')

2
account_journal_report_xls/__openerp__.py

@ -52,5 +52,3 @@ cf. https://launchpad.net/openerp-reporting-engines
'wizard/print_journal_wizard.xml', 'wizard/print_journal_wizard.xml',
], ],
} }
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

28
account_journal_report_xls/account_journal.py

@ -21,8 +21,6 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import _
class account_journal(orm.Model): class account_journal(orm.Model):
@ -59,17 +57,18 @@ class account_journal(orm.Model):
'credit', # account.move.line,credit 'credit', # account.move.line,credit
'balance', # debit-credit 'balance', # debit-credit
'docname', # origin document if any 'docname', # origin document if any
#'date_maturity', # account.move.line,date_maturity
#'reconcile', # account.move.line,reconcile_id.name
#'reconcile_partial', # account.move.line,reconcile_partial_id.name
#'partner_ref', # res.partner,ref
#'move_ref', # account.move,ref
#'move_id', # account.move,id
#'acc_name', # account.account,name
#'journal', # account.journal,name
#'journal_code', # account.journal,code
#'analytic_account', # account.analytic.account,name
#'analytic_account_code', # account.analytic.account,code
# 'date_maturity', # account.move.line,date_maturity
# 'reconcile', # account.move.line,reconcile_id.name
# 'reconcile_partial',
# account.move.line,reconcile_partial_id.name
# 'partner_ref', # res.partner,ref
# 'move_ref', # account.move,ref
# 'move_id', # account.move,id
# 'acc_name', # account.account,name
# 'journal', # account.journal,name
# 'journal_code', # account.journal,code
# 'analytic_account', # account.analytic.account,name
# 'analytic_account_code', # account.analytic.account,code
] ]
return res return res
@ -81,7 +80,8 @@ class account_journal(orm.Model):
my_change = { my_change = {
'move_name':{ 'move_name':{
'header': [1, 20, 'text', _render("_('My Move Title')")], 'header': [1, 20, 'text', _render("_('My Move Title')")],
'lines': [1, 0, 'text', _render("l['move_name'] != '/' and l['move_name'] or ('*'+str(l['move_id']))")],
'lines': [1, 0, 'text', _render("l['move_name'] != '/' and
l['move_name'] or ('*'+str(l['move_id']))")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
} }
return my_change return my_change

6
account_journal_report_xls/report/__init__.py

@ -20,7 +20,5 @@
# #
############################################################################## ##############################################################################
import nov_account_journal
import nov_account_journal_xls
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from . import nov_account_journal
from . import nov_account_journal_xls

215
account_journal_report_xls/report/nov_account_journal.py

@ -22,7 +22,7 @@
import time import time
from openerp.report import report_sxw from openerp.report import report_sxw
from openerp.tools.translate import translate, _
from openerp.tools.translate import translate
import logging import logging
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -32,7 +32,8 @@ _ir_translation_name = 'nov.account.journal.print'
class nov_journal_print(report_sxw.rml_parse): class nov_journal_print(report_sxw.rml_parse):
def set_context(self, objects, data, ids, report_type=None): def set_context(self, objects, data, ids, report_type=None):
#_logger.warn('set_context, objects = %s, data = %s, ids = %s', objects, data, ids)
# _logger.warn('set_context, objects = %s, data = %s,
# ids = %s', objects, data, ids)
super(nov_journal_print, self).set_context(objects, data, ids) super(nov_journal_print, self).set_context(objects, data, ids)
j_obj = self.pool.get('account.journal') j_obj = self.pool.get('account.journal')
p_obj = self.pool.get('account.period') p_obj = self.pool.get('account.period')
@ -42,7 +43,8 @@ class nov_journal_print(report_sxw.rml_parse):
self.move_states = ['posted'] self.move_states = ['posted']
else: else:
self.move_states = ['draft', 'posted'] self.move_states = ['draft', 'posted']
self.display_currency = self.localcontext['display_currency'] = data['display_currency']
self.display_currency = self.localcontext[
'display_currency'] = data['display_currency']
self.group_entries = data['group_entries'] self.group_entries = data['group_entries']
self.print_by = data['print_by'] self.print_by = data['print_by']
self.report_type = report_type self.report_type = report_type
@ -59,7 +61,8 @@ class nov_journal_print(report_sxw.rml_parse):
objects = [] objects = []
for jf in journal_fy_ids: for jf in journal_fy_ids:
journal = j_obj.browse(self.cr, self.uid, jf[0], self.context) journal = j_obj.browse(self.cr, self.uid, jf[0], self.context)
fiscalyear = fy_obj.browse(self.cr, self.uid, jf[1], self.context)
fiscalyear = fy_obj.browse(
self.cr, self.uid, jf[1], self.context)
objects.append((journal, fiscalyear)) objects.append((journal, fiscalyear))
self.localcontext['objects'] = self.objects = objects self.localcontext['objects'] = self.objects = objects
@ -82,16 +85,20 @@ class nov_journal_print(report_sxw.rml_parse):
def _(self, src): def _(self, src):
lang = self.context.get('lang', 'en_US') lang = self.context.get('lang', 'en_US')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
return translate(self.cr, _ir_translation_name, 'report', lang, src) \
or src
def _title(self, object): def _title(self, object):
return ((self.print_by == 'period' and self._('Period') or self._('Fiscal Year')) + ' ' + object[1].name, object[0].name)
return ((self.print_by == 'period' and self._('Period') or
self._('Fiscal Year')) + ' ' + object[1].name, object[0].name)
def _amount_title(self): def _amount_title(self):
return self.display_currency and (self._('Amount'), self._('Currency')) or (self._('Debit'), self._('Credit'))
return self.display_currency and \
(self._('Amount'), self._('Currency')) or (
self._('Debit'), self._('Credit'))
def _lines(self, object): def _lines(self, object):
j_obj = self.pool.get('account.journal')
j_obj = self.pool['account.journal']
_ = self._ _ = self._
journal = object[0] journal = object[0]
journal_id = journal.id journal_id = journal.id
@ -100,75 +107,116 @@ class nov_journal_print(report_sxw.rml_parse):
period_id = period.id period_id = period.id
period_ids = [period_id] period_ids = [period_id]
# update status period # update status period
ids_journal_period = self.pool.get('account.journal.period').search(self.cr, self.uid,
[('journal_id', '=', journal_id), ('period_id', '=', period_id)])
ids_journal_period = self.pool['account.journal.period'].\
search(self.cr, self.uid, [('journal_id', '=', journal_id),
('period_id', '=', period_id)])
if ids_journal_period: if ids_journal_period:
self.cr.execute( self.cr.execute(
'update account_journal_period set state=%s where journal_id=%s and period_id=%s and state=%s',
'''update account_journal_period set state=%s
where journal_id=%s and period_id=%s and state=%s''',
('printed', journal_id, period_id, 'draft')) ('printed', journal_id, period_id, 'draft'))
else: else:
self.pool.get('account.journal.period').create(self.cr, self.uid, {
'name': (journal.code or journal.name) + ':' + (period.name or ''),
'journal_id': journal.id,
'period_id': period.id,
'state': 'printed',
self.pool.get('account.journal.period').create(
self.cr, self.uid,
{'name': (journal.code or journal.name) + ':' +
(period.name or ''),
'journal_id': journal.id,
'period_id': period.id,
'state': 'printed',
}) })
_logger.error("The Entry for Period '%s', Journal '%s' was missing in 'account.journal.period' and has been fixed now !",
period.name, journal.name)
_logger.error("""The Entry for Period '%s', Journal '%s' was
missing in 'account.journal.period' and
has been fixed now !""",
period.name, journal.name)
else: else:
fiscalyear = object[1] fiscalyear = object[1]
period_ids = [x.id for x in fiscalyear.period_ids] period_ids = [x.id for x in fiscalyear.period_ids]
select_extra, join_extra, where_extra = j_obj._report_xls_query_extra(self.cr, self.uid, self.context)
select_extra, join_extra, where_extra = j_obj._report_xls_query_extra(
self.cr, self.uid, self.context)
# SQL select for performance reasons, as a consequence, there are no field value translations.
# If performance is no issue, you can adapt the _report_xls_template in an inherited module to add field value translations.
# SQL select for performance reasons, as a consequence, there are no
# field value translations.
# If performance is no issue, you can adapt the _report_xls_template in
# an inherited module to add field value translations.
self.cr.execute("SELECT l.move_id AS move_id, l.id AS aml_id, " self.cr.execute("SELECT l.move_id AS move_id, l.id AS aml_id, "
"am.name AS move_name, coalesce(am.ref,'') AS move_ref, am.date AS move_date, "
"aa.id AS account_id, aa.code AS acc_code, aa.name AS acc_name, "
"aj.name AS journal, aj.code AS journal_code, "
"coalesce(rp.name,'') AS partner_name, coalesce(rp.ref,'') AS partner_ref, rp.id AS partner_id, "
"coalesce(l.name,'') AS aml_name, "
"l.date_maturity AS date_maturity, "
"coalesce(ap.code, ap.name) AS period, "
"coalesce(atc.code,'') AS tax_code, atc.id AS tax_code_id, coalesce(l.tax_amount,0.0) AS tax_amount, "
"coalesce(l.debit,0.0) AS debit, coalesce(l.credit,0.0) AS credit, "
"coalesce(amr.name,'') AS reconcile, coalesce(amrp.name,'') AS reconcile_partial, "
"ana.name AS an_acc_name, coalesce(ana.code,'') AS an_acc_code, "
"coalesce(l.amount_currency,0.0) AS amount_currency, "
"rc.id AS currency_id, rc.name AS currency_name, rc.symbol AS currency_symbol, "
"coalesce(ai.internal_number,'-') AS inv_number, coalesce(abs.name,'-') AS st_number, coalesce(av.number,'-') AS voucher_number "
+ select_extra +
"FROM account_move_line l "
"INNER JOIN account_move am ON l.move_id = am.id "
"INNER JOIN account_account aa ON l.account_id = aa.id "
"INNER JOIN account_journal aj ON l.journal_id = aj.id "
"INNER JOIN account_period ap ON l.period_id = ap.id "
"LEFT OUTER JOIN account_invoice ai ON ai.move_id = am.id "
"LEFT OUTER JOIN account_voucher av ON av.move_id = am.id "
"LEFT OUTER JOIN account_bank_statement abs ON l.statement_id = abs.id "
"LEFT OUTER JOIN res_partner rp ON l.partner_id = rp.id "
"LEFT OUTER JOIN account_tax_code atc ON l.tax_code_id = atc.id "
"LEFT OUTER JOIN account_move_reconcile amr ON l.reconcile_id = amr.id "
"LEFT OUTER JOIN account_move_reconcile amrp ON l.reconcile_partial_id = amrp.id "
"LEFT OUTER JOIN account_analytic_account ana ON l.analytic_account_id = ana.id "
"LEFT OUTER JOIN res_currency rc ON l.currency_id = rc.id "
+ join_extra +
"WHERE l.period_id IN %s AND l.journal_id = %s "
"AND am.state IN %s "
+ where_extra +
"ORDER BY " + self.sort_selection + ", move_date, move_id, acc_code",
(tuple(period_ids), journal_id, tuple(self.move_states)))
"am.name AS move_name, "
"coalesce(am.ref,'') AS move_ref, "
"am.date AS move_date, "
"aa.id AS account_id, aa.code AS acc_code, "
"aa.name AS acc_name, "
"aj.name AS journal, aj.code AS journal_code, "
"coalesce(rp.name,'') AS partner_name, "
"coalesce(rp.ref,'') AS partner_ref, "
"rp.id AS partner_id, "
"coalesce(l.name,'') AS aml_name, "
"l.date_maturity AS date_maturity, "
"coalesce(ap.code, ap.name) AS period, "
"coalesce(atc.code,'') AS tax_code, "
"atc.id AS tax_code_id, "
"coalesce(l.tax_amount,0.0) AS tax_amount, "
"coalesce(l.debit,0.0) AS debit, "
"coalesce(l.credit,0.0) AS credit, "
"coalesce(amr.name,'') AS reconcile, "
"coalesce(amrp.name,'') AS reconcile_partial, "
"ana.name AS an_acc_name, "
"coalesce(ana.code,'') AS an_acc_code, "
"coalesce(l.amount_currency,0.0) AS amount_currency, "
"rc.id AS currency_id, rc.name AS currency_name, "
"rc.symbol AS currency_symbol, "
"coalesce(ai.internal_number,'-') AS inv_number, "
"coalesce(abs.name,'-') AS st_number, "
"coalesce(av.number,'-') AS voucher_number "
+ select_extra +
"FROM account_move_line l "
"INNER JOIN account_move am ON l.move_id = am.id "
"INNER JOIN account_account aa "
"ON l.account_id = aa.id "
"INNER JOIN account_journal aj "
"ON l.journal_id = aj.id "
"INNER JOIN account_period ap ON l.period_id = ap.id "
"LEFT OUTER JOIN account_invoice ai "
"ON ai.move_id = am.id "
"LEFT OUTER JOIN account_voucher av "
"ON av.move_id = am.id "
"LEFT OUTER JOIN account_bank_statement abs "
"ON l.statement_id = abs.id "
"LEFT OUTER JOIN res_partner rp "
"ON l.partner_id = rp.id "
"LEFT OUTER JOIN account_tax_code atc "
"ON l.tax_code_id = atc.id "
"LEFT OUTER JOIN account_move_reconcile amr "
"ON l.reconcile_id = amr.id "
"LEFT OUTER JOIN account_move_reconcile amrp "
"ON l.reconcile_partial_id = amrp.id "
"LEFT OUTER JOIN account_analytic_account ana "
"ON l.analytic_account_id = ana.id "
"LEFT OUTER JOIN res_currency rc "
"ON l.currency_id = rc.id "
+ join_extra +
"WHERE l.period_id IN %s AND l.journal_id = %s "
"AND am.state IN %s "
+ where_extra +
"ORDER BY " + self.sort_selection +
", move_date, move_id, acc_code",
(tuple(period_ids), journal_id,
tuple(self.move_states)))
lines = self.cr.dictfetchall() lines = self.cr.dictfetchall()
# add reference of corresponding origin document # add reference of corresponding origin document
if journal.type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'):
[x.update({'docname': (_('Invoice') + ': ' + x['inv_number']) or (_('Voucher') + ': ' + x['voucher_number']) or '-'}) for x in lines]
if journal.type in ('sale', 'sale_refund', 'purchase',
'purchase_refund'):
[x.update({'docname': (_('Invoice') + ': ' + x['inv_number'])
or (_('Voucher') + ': ' + x['voucher_number']) or '-'})
for x in lines]
elif journal.type in ('bank', 'cash'): elif journal.type in ('bank', 'cash'):
[x.update({'docname': (_('Statement') + ': ' + x['st_number']) or (_('Voucher') + ': ' + x['voucher_number']) or '-'}) for x in lines]
[x.update({'docname': (_('Statement') + ': ' + x['st_number'])
or (_('Voucher') + ': ' + x['voucher_number']) or '-'})
for x in lines]
else: else:
code_string = j_obj._report_xls_document_extra(self.cr, self.uid, self.context)
#_logger.warn('code_string= %s', code_string)
code_string = j_obj._report_xls_document_extra(
self.cr, self.uid, self.context)
# _logger.warn('code_string= %s', code_string)
[x.update({'docname': eval(code_string) or '-'}) for x in lines] [x.update({'docname': eval(code_string) or '-'}) for x in lines]
# group lines # group lines
@ -180,10 +228,15 @@ class nov_journal_print(report_sxw.rml_parse):
curr_obj = self.pool.get('res.currency') curr_obj = self.pool.get('res.currency')
[x.update({ [x.update({
'amount1': self.formatLang(x['debit'] - x['credit']), 'amount1': self.formatLang(x['debit'] - x['credit']),
'amount2': self.formatLang(x['amount_currency'], monetary=True, currency_obj=curr_obj.browse(self.cr, self.uid, x['currency_id'])),
}) for x in lines]
'amount2': self.formatLang(
x['amount_currency'], monetary=True,
currency_obj=curr_obj.browse(self.cr,
self.uid, x['currency_id'])),
}) for x in lines]
else: else:
[x.update({'amount1': self.formatLang(x['debit']), 'amount2': self.formatLang(x['credit'])}) for x in lines]
[x.update({'amount1': self.formatLang(x['debit']),
'amount2': self.formatLang(x['credit'])})
for x in lines]
# insert a flag in every move_line to indicate the end of a move # insert a flag in every move_line to indicate the end of a move
# this flag will be used to draw a full line between moves # this flag will be used to draw a full line between moves
@ -205,8 +258,10 @@ class nov_journal_print(report_sxw.rml_parse):
return lines_in return lines_in
lines_grouped = {} lines_grouped = {}
for line in lines_in: for line in lines_in:
key = (line['account_id'], line['tax_code_id'], line['partner_id'])
if not key in lines_grouped:
key = (line['account_id'],
line['tax_code_id'],
line['partner_id'])
if key not in lines_grouped:
lines_grouped[key] = line lines_grouped[key] = line
else: else:
lines_grouped[key]['debit'] += line['debit'] lines_grouped[key]['debit'] += line['debit']
@ -245,15 +300,19 @@ class nov_journal_print(report_sxw.rml_parse):
self.cr.execute( self.cr.execute(
"SELECT distinct tax_code_id FROM account_move_line l " "SELECT distinct tax_code_id FROM account_move_line l "
"INNER JOIN account_move am ON l.move_id = am.id " "INNER JOIN account_move am ON l.move_id = am.id "
"WHERE l.period_id in %s AND l.journal_id=%s AND l.tax_code_id IS NOT NULL AND am.state IN %s",
"WHERE l.period_id in %s AND l.journal_id=%s "
"AND l.tax_code_id IS NOT NULL AND am.state IN %s",
(tuple(period_ids), journal_id, tuple(self.move_states))) (tuple(period_ids), journal_id, tuple(self.move_states)))
ids = map(lambda x: x[0], self.cr.fetchall()) ids = map(lambda x: x[0], self.cr.fetchall())
if ids: if ids:
self.cr.execute('SELECT id FROM account_tax_code WHERE id IN %s ORDER BY code', (tuple(ids),))
self.cr.execute(
'SELECT id FROM account_tax_code WHERE id IN %s ORDER BY code',
(tuple(ids),))
tax_code_ids = map(lambda x: x[0], self.cr.fetchall()) tax_code_ids = map(lambda x: x[0], self.cr.fetchall())
else: else:
tax_code_ids = [] tax_code_ids = []
tax_codes = self.pool.get('account.tax.code').browse(self.cr, self.uid, tax_code_ids, self.context)
tax_codes = self.pool.get('account.tax.code').browse(
self.cr, self.uid, tax_code_ids, self.context)
return tax_codes return tax_codes
def _totals(self, field, object, tax_code_id=None): def _totals(self, field, object, tax_code_id=None):
@ -269,7 +328,8 @@ class nov_journal_print(report_sxw.rml_parse):
"WHERE l.period_id IN %s AND l.journal_id=%s AND am.state IN %s" "WHERE l.period_id IN %s AND l.journal_id=%s AND am.state IN %s"
if field == 'tax_amount': if field == 'tax_amount':
select += " AND tax_code_id=%s" % tax_code_id select += " AND tax_code_id=%s" % tax_code_id
self.cr.execute(select, (tuple(period_ids), journal_id, tuple(self.move_states)))
self.cr.execute(
select, (tuple(period_ids), journal_id, tuple(self.move_states)))
return self.cr.fetchone()[0] or 0.0 return self.cr.fetchone()[0] or 0.0
def _sum1(self, object): def _sum1(self, object):
@ -277,21 +337,24 @@ class nov_journal_print(report_sxw.rml_parse):
def _sum2(self, object): def _sum2(self, object):
if self.display_currency: if self.display_currency:
return ''
return ''
else: else:
return self._totals('credit', object) return self._totals('credit', object)
def _sum_vat(self, object, tax_code): def _sum_vat(self, object, tax_code):
return self._totals('tax_amount', object, tax_code.id) return self._totals('tax_amount', object, tax_code.id)
def formatLang(self, value, digits=None, date=False, date_time=False, grouping=True, monetary=False, dp=False, currency_obj=False):
def formatLang(self, value, digits=None, date=False, date_time=False,
grouping=True, monetary=False, dp=False,
currency_obj=False):
if isinstance(value, (float, int)) and not value: if isinstance(value, (float, int)) and not value:
return '' return ''
else: else:
return super(nov_journal_print, self).formatLang(value, digits, date, date_time, grouping, monetary, dp, currency_obj)
return super(nov_journal_print, self).formatLang(
value, digits,
date, date_time, grouping, monetary, dp, currency_obj)
report_sxw.report_sxw('report.nov.account.journal.print', 'account.journal',
report_sxw.report_sxw(
'report.nov.account.journal.print', 'account.journal',
'addons/account_journal_report_xls/report/nov_account_journal.rml', 'addons/account_journal_report_xls/report/nov_account_journal.rml',
parser=nov_journal_print, header=False) parser=nov_journal_print, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

199
account_journal_report_xls/report/nov_account_journal_xls.py

@ -21,10 +21,8 @@
############################################################################## ##############################################################################
import xlwt import xlwt
import time
from datetime import datetime from datetime import datetime
from openerp.osv import orm from openerp.osv import orm
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell, _render from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from .nov_account_journal import nov_journal_print from .nov_account_journal import nov_journal_print
@ -36,7 +34,8 @@ _logger = logging.getLogger(__name__)
class account_journal_xls_parser(nov_journal_print): class account_journal_xls_parser(nov_journal_print):
def __init__(self, cr, uid, name, context): def __init__(self, cr, uid, name, context):
super(account_journal_xls_parser, self).__init__(cr, uid, name, context=context)
super(account_journal_xls_parser, self).__init__(cr, uid, name,
context=context)
journal_obj = self.pool.get('account.journal') journal_obj = self.pool.get('account.journal')
self.context = context self.context = context
wanted_list = journal_obj._report_xls_fields(cr, uid, context) wanted_list = journal_obj._report_xls_fields(cr, uid, context)
@ -50,8 +49,10 @@ class account_journal_xls_parser(nov_journal_print):
class account_journal_xls(report_xls): class account_journal_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(account_journal_xls, self).__init__(name, table, rml, parser, header, store)
def __init__(self, name, table, rml=False, parser=False, header=True,
store=False):
super(account_journal_xls, self).__init__(
name, table, rml, parser, header, store)
# Cell Styles # Cell Styles
_xs = self.xls_styles _xs = self.xls_styles
@ -63,24 +64,37 @@ class account_journal_xls(report_xls):
# lines # lines
aml_cell_format = _xs['borders_all'] aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format) self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str=report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str=report_xls.decimal_format)
self.aml_cell_style_center = xlwt.easyxf(
aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(
aml_cell_format + _xs['left'],
num_format_str=report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(
aml_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# totals # totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all'] rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format) self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right']) self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str=report_xls.decimal_format)
self.rt_cell_style_decimal = xlwt.easyxf(
rt_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# XLS Template Journal Items # XLS Template Journal Items
self.col_specs_lines_template = { self.col_specs_lines_template = {
'move_name': { 'move_name': {
'header': [1, 20, 'text', _render("_('Entry')")], 'header': [1, 20, 'text', _render("_('Entry')")],
'lines': [1, 0, 'text', _render("l['move_name'] != '/' and l['move_name'] or ('*'+str(l['move_id']))")],
'lines':
[1, 0, 'text',
_render("l['move_name'] != '/' and l['move_name'] \
or ('*'+str(l['move_id']))")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'move_date': { 'move_date': {
'header': [1, 13, 'text', _render("_('Date')")], 'header': [1, 13, 'text', _render("_('Date')")],
'lines': [1, 0, 'date', _render("datetime.strptime(l['move_date'],'%Y-%m-%d')"), None, self.aml_cell_style_date],
'lines':
[1, 0, 'date',
_render("datetime.strptime(l['move_date'],'%Y-%m-%d')"),
None, self.aml_cell_style_date],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'acc_code': { 'acc_code': {
'header': [1, 12, 'text', _render("_('Account')")], 'header': [1, 12, 'text', _render("_('Account')")],
@ -124,47 +138,73 @@ class account_journal_xls(report_xls):
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'date_maturity': { 'date_maturity': {
'header': [1, 13, 'text', _render("_('Maturity Date')")], 'header': [1, 13, 'text', _render("_('Maturity Date')")],
'lines': [1, 0, _render("l['date_maturity'] and 'date' or 'text'"),
_render("l['date_maturity'] and datetime.strptime(l['date_maturity'],'%Y-%m-%d') or None"),
'lines':
[1, 0,
_render("l['date_maturity'] and 'date' or 'text'"),
_render(
"l['date_maturity'] and datetime.\
strptime(l['date_maturity'],'%Y-%m-%d') or None"),
None, self.aml_cell_style_date], None, self.aml_cell_style_date],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'debit': { 'debit': {
'header': [1, 18, 'text', _render("_('Debit')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("l['debit']"), None, self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("debit_formula"), self.rt_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Debit')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("l['debit']"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("debit_formula"),
self.rt_cell_style_decimal]},
'credit': { 'credit': {
'header': [1, 18, 'text', _render("_('Credit')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("l['credit']"), None, self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("credit_formula"), self.rt_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Credit')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("l['credit']"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("credit_formula"),
self.rt_cell_style_decimal]},
'balance': { 'balance': {
'header': [1, 18, 'text', _render("_('Balance')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', None, _render("bal_formula"), self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("bal_formula"), self.rt_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Balance')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', None, _render("bal_formula"),
self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("bal_formula"),
self.rt_cell_style_decimal]},
'reconcile': { 'reconcile': {
'header': [1, 12, 'text', _render("_('Rec.')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['reconcile']"), None, self.aml_cell_style_center],
'header': [1, 12, 'text', _render("_('Rec.')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['reconcile']"), None,
self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'reconcile_partial': { 'reconcile_partial': {
'header': [1, 12, 'text', _render("_('Part. Rec.')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['reconcile_partial']"), None, self.aml_cell_style_center],
'header': [1, 12, 'text', _render("_('Part. Rec.')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['reconcile_partial']"),
None, self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'tax_code': { 'tax_code': {
'header': [1, 6, 'text', _render("_('VAT')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['tax_code']"), None, self.aml_cell_style_center],
'header': [1, 6, 'text', _render("_('VAT')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['tax_code']"), None,
self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'tax_amount': { 'tax_amount': {
'header': [1, 18, 'text', _render("_('VAT Amount')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("l['tax_amount']"), None, self.aml_cell_style_decimal],
'header': [1, 18, 'text', _render("_('VAT Amount')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("l['tax_amount']"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'amount_currency': { 'amount_currency': {
'header': [1, 18, 'text', _render("_('Am. Currency')"), None, self.rh_cell_style_right],
'lines': [1, 0, _render("l['amount_currency'] and 'number' or 'text'"),
_render("l['amount_currency'] or None"),
None, self.aml_cell_style_decimal],
'header': [1, 18, 'text', _render("_('Am. Currency')"), None,
self.rh_cell_style_right],
'lines':
[1, 0,
_render("l['amount_currency'] and 'number' or 'text'"),
_render("l['amount_currency'] or None"),
None, self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'currency_name': { 'currency_name': {
'header': [1, 6, 'text', _render("_('Curr.')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['currency_name']"), None, self.aml_cell_style_center],
'header': [1, 6, 'text', _render("_('Curr.')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("l['currency_name']"), None,
self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'docname': { 'docname': {
'header': [1, 35, 'text', _render("_('Document')")], 'header': [1, 35, 'text', _render("_('Document')")],
@ -189,8 +229,10 @@ class account_journal_xls(report_xls):
'header': [1, 6, 'text', _render("_('Case')")], 'header': [1, 6, 'text', _render("_('Case')")],
'tax_totals': [1, 0, 'text', _render("t.code")]}, 'tax_totals': [1, 0, 'text', _render("t.code")]},
'tax_amount': { 'tax_amount': {
'header': [1, 18, 'text', _render("_('Amount')"), None, self.rh_cell_style_right],
'tax_totals': [1, 0, 'number', _render("sum_vat(o,t)"), None, self.aml_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Amount')"), None,
self.rh_cell_style_right],
'tax_totals': [1, 0, 'number', _render("sum_vat(o,t)"), None,
self.aml_cell_style_decimal]},
} }
def _journal_title(self, o, ws, _p, row_pos, xlwt, _xs): def _journal_title(self, o, ws, _p, row_pos, xlwt, _xs):
@ -200,12 +242,13 @@ class account_journal_xls(report_xls):
_p.title(o)[0], _p.title(o)[0],
_p.title(o)[1], _p.title(o)[1],
_p._("Journal Overview") + ' - ' + _p.company.currency_id.name, _p._("Journal Overview") + ' - ' + _p.company.currency_id.name,
])
])
c_specs = [ c_specs = [
('report_name', 1, 0, 'text', report_name), ('report_name', 1, 0, 'text', report_name),
] ]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
return row_pos + 1 return row_pos + 1
def _journal_lines(self, o, ws, _p, row_pos, xlwt, _xs): def _journal_lines(self, o, ws, _p, row_pos, xlwt, _xs):
@ -215,9 +258,13 @@ class account_journal_xls(report_xls):
credit_pos = self.credit_pos credit_pos = self.credit_pos
# Column headers # Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_lines_template, 'header', render_space={'_': _p._}), wanted_list)
c_specs = map(lambda x: self.render(
x, self.col_specs_lines_template, 'header',
render_space={'_': _p._}), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style, set_column_size=True)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.rh_cell_style,
set_column_size=True)
ws.set_horz_split_pos(row_pos) ws.set_horz_split_pos(row_pos)
# account move lines # account move lines
@ -229,9 +276,13 @@ class account_journal_xls(report_xls):
debit_cell = rowcol_to_cell(row_pos, debit_pos) debit_cell = rowcol_to_cell(row_pos, debit_pos)
credit_cell = rowcol_to_cell(row_pos, credit_pos) credit_cell = rowcol_to_cell(row_pos, credit_pos)
bal_formula = debit_cell + '-' + credit_cell bal_formula = debit_cell + '-' + credit_cell
c_specs = map(lambda x: self.render(x, self.col_specs_lines_template, 'lines'), wanted_list)
_logger.debug('dummy call - %s', bal_formula)
c_specs = map(
lambda x: self.render(x, self.col_specs_lines_template,
'lines'), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.aml_cell_style)
if l['draw_line'] and cnt != aml_cnt: if l['draw_line'] and cnt != aml_cnt:
row_pos += 1 row_pos += 1
@ -239,15 +290,19 @@ class account_journal_xls(report_xls):
debit_start = rowcol_to_cell(aml_start_pos, debit_pos) debit_start = rowcol_to_cell(aml_start_pos, debit_pos)
debit_stop = rowcol_to_cell(row_pos - 1, debit_pos) debit_stop = rowcol_to_cell(row_pos - 1, debit_pos)
debit_formula = 'SUM(%s:%s)' % (debit_start, debit_stop) debit_formula = 'SUM(%s:%s)' % (debit_start, debit_stop)
_logger.debug('dummy call - %s', debit_formula)
credit_start = rowcol_to_cell(aml_start_pos, credit_pos) credit_start = rowcol_to_cell(aml_start_pos, credit_pos)
credit_stop = rowcol_to_cell(row_pos - 1, credit_pos) credit_stop = rowcol_to_cell(row_pos - 1, credit_pos)
credit_formula = 'SUM(%s:%s)' % (credit_start, credit_stop) credit_formula = 'SUM(%s:%s)' % (credit_start, credit_stop)
_logger.debug('dummy call - %s', credit_formula)
debit_cell = rowcol_to_cell(row_pos, debit_pos) debit_cell = rowcol_to_cell(row_pos, debit_pos)
credit_cell = rowcol_to_cell(row_pos, credit_pos) credit_cell = rowcol_to_cell(row_pos, credit_pos)
bal_formula = debit_cell + '-' + credit_cell bal_formula = debit_cell + '-' + credit_cell
c_specs = map(lambda x: self.render(x, self.col_specs_lines_template, 'totals'), wanted_list)
c_specs = map(lambda x: self.render(
x, self.col_specs_lines_template, 'totals'), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rt_cell_style_right)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.rt_cell_style_right)
return row_pos + 1 return row_pos + 1
def _journal_vat_summary(self, o, ws, _p, row_pos, xlwt, _xs): def _journal_vat_summary(self, o, ws, _p, row_pos, xlwt, _xs):
@ -258,7 +313,8 @@ class account_journal_xls(report_xls):
title_cell_style = xlwt.easyxf(_xs['bold']) title_cell_style = xlwt.easyxf(_xs['bold'])
c_specs = [('summary_title', 1, 0, 'text', _p._("VAT Declaration"))] c_specs = [('summary_title', 1, 0, 'text', _p._("VAT Declaration"))]
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=title_cell_style) + 1
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=title_cell_style) + 1
wanted_list = self.wanted_list wanted_list = self.wanted_list
vat_summary_wanted_list = ['tax_case_name', 'tax_code', 'tax_amount'] vat_summary_wanted_list = ['tax_case_name', 'tax_code', 'tax_amount']
@ -267,33 +323,45 @@ class account_journal_xls(report_xls):
cols_number = len(wanted_list) cols_number = len(wanted_list)
vat_summary_cols_number = len(vat_summary_wanted_list) vat_summary_cols_number = len(vat_summary_wanted_list)
if vat_summary_cols_number > cols_number: if vat_summary_cols_number > cols_number:
raise orm.except_orm(_('Programming Error!'),
raise orm.except_orm(
_('Programming Error!'),
_("vat_summary_cols_number should be < cols_number !")) _("vat_summary_cols_number should be < cols_number !"))
index = 0 index = 0
for i in range(vat_summary_cols_number): for i in range(vat_summary_cols_number):
col = vat_summary_wanted_list[i] col = vat_summary_wanted_list[i]
col_size = self.col_specs_lines_template[wanted_list[index]]['header'][1]
templ_col_size = self.col_specs_vat_summary_template[col]['header'][1]
#_logger.warn("col=%s, col_size=%s, templ_col_size=%s", col, col_size, templ_col_size)
col_size = self.col_specs_lines_template[
wanted_list[index]]['header'][1]
templ_col_size = self.col_specs_vat_summary_template[
col]['header'][1]
# _logger.warn("col=%s, col_size=%s, templ_col_size=%s",
# col, col_size, templ_col_size)
col_span = 1 col_span = 1
if templ_col_size > col_size: if templ_col_size > col_size:
new_size = col_size new_size = col_size
while templ_col_size > new_size: while templ_col_size > new_size:
col_span += 1 col_span += 1
index += 1 index += 1
new_size += self.col_specs_lines_template[wanted_list[index]]['header'][1]
new_size += self.col_specs_lines_template[
wanted_list[index]]['header'][1]
self.col_specs_vat_summary_template[col]['header'][0] = col_span self.col_specs_vat_summary_template[col]['header'][0] = col_span
self.col_specs_vat_summary_template[col]['tax_totals'][0] = col_span
self.col_specs_vat_summary_template[
col]['tax_totals'][0] = col_span
index += 1 index += 1
c_specs = map(lambda x: self.render(x, self.col_specs_vat_summary_template, 'header'), vat_summary_wanted_list)
c_specs = map(lambda x: self.render(
x, self.col_specs_vat_summary_template, 'header'),
vat_summary_wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.rh_cell_style)
for t in _p.tax_codes(o): for t in _p.tax_codes(o):
c_specs = map(lambda x: self.render(x, self.col_specs_vat_summary_template, 'tax_totals'), vat_summary_wanted_list)
c_specs = map(lambda x: self.render(
x, self.col_specs_vat_summary_template, 'tax_totals'),
vat_summary_wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.aml_cell_style)
return row_pos return row_pos
@ -306,14 +374,19 @@ class account_journal_xls(report_xls):
self.col_specs_lines_template.update(_p.template_changes) self.col_specs_lines_template.update(_p.template_changes)
self.debit_pos = 'debit' in wanted_list and wanted_list.index('debit') self.debit_pos = 'debit' in wanted_list and wanted_list.index('debit')
self.credit_pos = 'credit' in wanted_list and wanted_list.index('credit')
if not (self.credit_pos and self.debit_pos) and 'balance' in wanted_list:
self.credit_pos = 'credit' in wanted_list and wanted_list.index(
'credit')
if not (self.credit_pos and self.debit_pos) and 'balance' \
in wanted_list:
raise orm.except_orm(_('Customisation Error!'), raise orm.except_orm(_('Customisation Error!'),
_("The 'Balance' field is a calculated XLS field requiring the presence of the 'Debit' and 'Credit' fields !"))
_("The 'Balance' field is a calculated XLS \
field requiring the presence of the \
'Debit' and 'Credit' fields !"))
for o in objects: for o in objects:
sheet_name = ' - '.join([o[1].code, o[0].code])[:31].replace('/', '-')
sheet_name = ' - '.join([o[1].code, o[0].code]
)[:31].replace('/', '-')
sheet_name = sheet_name[:31].replace('/', '-') sheet_name = sheet_name[:31].replace('/', '-')
ws = wb.add_sheet(sheet_name) ws = wb.add_sheet(sheet_name)
ws.panes_frozen = True ws.panes_frozen = True
@ -332,6 +405,4 @@ class account_journal_xls(report_xls):
row_pos = self._journal_vat_summary(o, ws, _p, row_pos, xlwt, _xs) row_pos = self._journal_vat_summary(o, ws, _p, row_pos, xlwt, _xs)
account_journal_xls('report.nov.account.journal.xls', 'account.journal.period', account_journal_xls('report.nov.account.journal.xls', 'account.journal.period',
parser=account_journal_xls_parser)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
parser=account_journal_xls_parser)

2
account_journal_report_xls/wizard/__init__.py

@ -21,5 +21,3 @@
############################################################################## ##############################################################################
from . import print_journal_wizard from . import print_journal_wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

80
account_journal_report_xls/wizard/print_journal_wizard.py

@ -22,8 +22,8 @@
from openerp.tools.translate import _ from openerp.tools.translate import _
from openerp.osv import orm, fields from openerp.osv import orm, fields
from openerp.addons.account.wizard.account_report_common_journal import account_common_journal_report
import time
from openerp.addons.account.wizard.account_report_common_journal \
import account_common_journal_report
import logging import logging
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -33,15 +33,19 @@ class account_print_journal_xls(orm.TransientModel):
_name = 'account.print.journal.xls' _name = 'account.print.journal.xls'
_description = 'Print/Export Journal' _description = 'Print/Export Journal'
_columns = { _columns = {
'journal_ids': fields.many2many('account.journal', string='Journals', required=True),
'group_entries': fields.boolean('Group Entries', help="Group entries with same General Account & Tax Code."),
}
'journal_ids': fields.many2many('account.journal', string='Journals',
required=True),
'group_entries': fields.boolean(
'Group Entries',
help="Group entries with same General Account & Tax Code."),
}
_defaults = { _defaults = {
'group_entries': True, 'group_entries': True,
} }
def fields_get(self, cr, uid, fields=None, context=None): def fields_get(self, cr, uid, fields=None, context=None):
res = super(account_print_journal_xls, self).fields_get(cr, uid, fields, context)
res = super(account_print_journal_xls, self).fields_get(
cr, uid, fields, context)
if context.get('print_by') == 'fiscalyear': if context.get('print_by') == 'fiscalyear':
if 'fiscalyear_id' in res: if 'fiscalyear_id' in res:
res['fiscalyear_id']['required'] = True res['fiscalyear_id']['required'] = True
@ -59,15 +63,18 @@ class account_print_journal_xls(orm.TransientModel):
def fy_period_ids(self, cr, uid, fiscalyear_id): def fy_period_ids(self, cr, uid, fiscalyear_id):
""" returns all periods from a fiscalyear sorted by date """ """ returns all periods from a fiscalyear sorted by date """
fy_period_ids = [] fy_period_ids = []
cr.execute('SELECT id, coalesce(special, False) AS special FROM account_period '
'WHERE fiscalyear_id=%s ORDER BY date_start, special DESC',
cr.execute('''
SELECT id, coalesce(special, False) AS special
FROM account_period
WHERE fiscalyear_id=%s ORDER BY date_start, special DESC''',
(fiscalyear_id,)) (fiscalyear_id,))
res = cr.fetchall() res = cr.fetchall()
if res: if res:
fy_period_ids = [x[0] for x in res] fy_period_ids = [x[0] for x in res]
return fy_period_ids return fy_period_ids
def onchange_fiscalyear_id(self, cr, uid, ids, fiscalyear_id=False, context=None):
def onchange_fiscalyear_id(self, cr, uid, ids, fiscalyear_id=False,
context=None):
res = {'value': {}} res = {'value': {}}
if context.get('print_by') == 'fiscalyear': if context.get('print_by') == 'fiscalyear':
# get period_from/to with opening/close periods # get period_from/to with opening/close periods
@ -77,9 +84,13 @@ class account_print_journal_xls(orm.TransientModel):
res['value']['period_to'] = fy_period_ids[-1] res['value']['period_to'] = fy_period_ids[-1]
return res return res
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
""" skip account.common.journal.report,fields_view_get (adds domain filter on journal type) """
return super(account_common_journal_report, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu)
def fields_view_get(self, cr, uid, view_id=None, view_type='form',
context=None, toolbar=False, submenu=False):
""" skip account.common.journal.report,fields_view_get
(adds domain filter on journal type) """
return super(account_common_journal_report, self).\
fields_view_get(cr, uid, view_id, view_type, context, toolbar,
submenu)
def xls_export(self, cr, uid, ids, context=None): def xls_export(self, cr, uid, ids, context=None):
return self.print_report(cr, uid, ids, context=context) return self.print_report(cr, uid, ids, context=context)
@ -93,15 +104,19 @@ class account_print_journal_xls(orm.TransientModel):
fiscalyear_id = wiz_form.fiscalyear_id.id fiscalyear_id = wiz_form.fiscalyear_id.id
company_id = wiz_form.company_id.id company_id = wiz_form.company_id.id
if print_by == 'fiscalyear':
if print_by == 'fiscalyear':
wiz_period_ids = self.fy_period_ids(cr, uid, fiscalyear_id) wiz_period_ids = self.fy_period_ids(cr, uid, fiscalyear_id)
else: else:
period_from = wiz_form.period_from period_from = wiz_form.period_from
period_to = wiz_form.period_to period_to = wiz_form.period_to
cr.execute("SELECT id, coalesce(special, False) AS special FROM account_period ap "
"WHERE ap.date_start>=%s AND ap.date_stop<=%s AND company_id=%s "
"ORDER BY date_start, special DESC",
(period_from.date_start, period_to.date_stop, company_id))
cr.execute("""
SELECT id, coalesce(special, False) AS special
FROM account_period ap
WHERE ap.date_start>=%s AND ap.date_stop<=%s AND company_id=%s
ORDER BY date_start, special DESC""",
(period_from.date_start,
period_to.date_stop,
company_id))
wiz_period_ids = map(lambda x: x[0], cr.fetchall()) wiz_period_ids = map(lambda x: x[0], cr.fetchall())
wiz_journal_ids = [j.id for j in wiz_form.journal_ids] wiz_journal_ids = [j.id for j in wiz_form.journal_ids]
@ -129,34 +144,43 @@ class account_print_journal_xls(orm.TransientModel):
journal_fy_ids = [] journal_fy_ids = []
for journal_id in wiz_journal_ids: for journal_id in wiz_journal_ids:
aml_ids = move_obj.search(cr, uid, aml_ids = move_obj.search(cr, uid,
[('journal_id', '=', journal_id), ('period_id', 'in', wiz_period_ids), ('state', 'in', move_states)],
limit=1)
[('journal_id', '=', journal_id),
('period_id', 'in', wiz_period_ids),
('state', 'in', move_states)],
limit=1)
if aml_ids: if aml_ids:
journal_fy_ids.append((journal_id, fiscalyear_id)) journal_fy_ids.append((journal_id, fiscalyear_id))
if not journal_fy_ids: if not journal_fy_ids:
raise orm.except_orm(_('No Data Available'), _('No records found for your selection!'))
raise orm.except_orm(
_('No Data Available'),
_('No records found for your selection!'))
datas.update({ datas.update({
'ids': [x[0] for x in journal_fy_ids],
'ids': [x[0] for x in journal_fy_ids],
'journal_fy_ids': journal_fy_ids, 'journal_fy_ids': journal_fy_ids,
}) })
else: else:
# perform account.move.line query in stead of 'account.journal.period' since this table is not always reliable
# perform account.move.line query in stead of
# 'account.journal.period' since this table is not always reliable
journal_period_ids = [] journal_period_ids = []
for journal_id in wiz_journal_ids: for journal_id in wiz_journal_ids:
period_ids = [] period_ids = []
for period_id in wiz_period_ids: for period_id in wiz_period_ids:
aml_ids = move_obj.search(cr, uid, aml_ids = move_obj.search(cr, uid,
[('journal_id', '=', journal_id), ('period_id', '=', period_id), ('state', 'in', move_states)],
limit=1)
[('journal_id', '=', journal_id),
('period_id', '=', period_id),
('state', 'in', move_states)],
limit=1)
if aml_ids: if aml_ids:
period_ids.append(period_id) period_ids.append(period_id)
if period_ids: if period_ids:
journal_period_ids.append((journal_id, period_ids)) journal_period_ids.append((journal_id, period_ids))
if not journal_period_ids: if not journal_period_ids:
raise orm.except_orm(_('No Data Available'), _('No records found for your selection!'))
raise orm.except_orm(
_('No Data Available'),
_('No records found for your selection!'))
datas.update({ datas.update({
'ids': [x[0] for x in journal_period_ids],
'journal_period_ids': journal_period_ids,
'ids': [x[0] for x in journal_period_ids],
'journal_period_ids': journal_period_ids,
}) })
if context.get('xls_export'): if context.get('xls_export'):
@ -168,5 +192,3 @@ class account_print_journal_xls(orm.TransientModel):
'type': 'ir.actions.report.xml', 'type': 'ir.actions.report.xml',
'report_name': 'nov.account.journal.print', 'report_name': 'nov.account.journal.print',
'datas': datas} 'datas': datas}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

5
account_move_line_report_xls/__init__.py

@ -25,5 +25,6 @@ try:
from . import report from . import report
except ImportError: except ImportError:
import logging import logging
logging.getLogger('openerp.module').warning('report_xls not available in addons path. account_financial_report_webkit_xls will not be usable')
logging.getLogger('openerp.module').\
warning('''report_xls not available in addons path.
account_financial_report_webkit_xls will not be usable''')

12
account_move_line_report_xls/account_move_line.py

@ -21,8 +21,6 @@
############################################################################## ##############################################################################
from openerp.osv import orm from openerp.osv import orm
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import _
class account_move_line(orm.Model): class account_move_line(orm.Model):
@ -34,11 +32,11 @@ class account_move_line(orm.Model):
'move', 'name', 'date', 'journal', 'period', 'partner', 'account', 'move', 'name', 'date', 'journal', 'period', 'partner', 'account',
'date_maturity', 'debit', 'credit', 'balance', 'date_maturity', 'debit', 'credit', 'balance',
'reconcile', 'reconcile_partial', 'analytic_account', 'reconcile', 'reconcile_partial', 'analytic_account',
#'ref', 'partner_ref', 'tax_code', 'tax_amount', 'amount_residual',
#'amount_currency', 'currency_name', 'company_currency',
#'amount_residual_currency',
#'product', 'product_ref', 'product_uom', 'quantity',
#'statement', 'invoice', 'narration', 'blocked',
# 'ref', 'partner_ref', 'tax_code', 'tax_amount',
# 'amount_residual', 'amount_currency', 'currency_name',
# 'company_currency', 'amount_residual_currency',
# 'product', 'product_ref', 'product_uom', 'quantity',
# 'statement', 'invoice', 'narration', 'blocked',
] ]
# Change/Add Template entries # Change/Add Template entries

232
account_move_line_report_xls/report/move_line_list_xls.py

@ -21,14 +21,12 @@
############################################################################## ##############################################################################
import xlwt import xlwt
import time
from datetime import datetime from datetime import datetime
from openerp.osv import orm from openerp.osv import orm
from openerp.report import report_sxw from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell, _render from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import translate, _ from openerp.tools.translate import translate, _
from openerp import pooler
import logging import logging
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -38,7 +36,8 @@ _ir_translation_name = 'move.line.list.xls'
class move_line_xls_parser(report_sxw.rml_parse): class move_line_xls_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context): def __init__(self, cr, uid, name, context):
super(move_line_xls_parser, self).__init__(cr, uid, name, context=context)
super(move_line_xls_parser, self).__init__(
cr, uid, name, context=context)
move_obj = self.pool.get('account.move.line') move_obj = self.pool.get('account.move.line')
self.context = context self.context = context
wanted_list = move_obj._report_xls_fields(cr, uid, context) wanted_list = move_obj._report_xls_fields(cr, uid, context)
@ -52,13 +51,16 @@ class move_line_xls_parser(report_sxw.rml_parse):
def _(self, src): def _(self, src):
lang = self.context.get('lang', 'en_US') lang = self.context.get('lang', 'en_US')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
return translate(self.cr, _ir_translation_name, 'report', lang, src) \
or src
class move_line_xls(report_xls): class move_line_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(move_line_xls, self).__init__(name, table, rml, parser, header, store)
def __init__(self, name, table, rml=False, parser=False, header=True,
store=False):
super(move_line_xls, self).__init__(
name, table, rml, parser, header, store)
# Cell Styles # Cell Styles
_xs = self.xls_styles _xs = self.xls_styles
@ -70,14 +72,21 @@ class move_line_xls(report_xls):
# lines # lines
aml_cell_format = _xs['borders_all'] aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format) self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str=report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str=report_xls.decimal_format)
self.aml_cell_style_center = xlwt.easyxf(
aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(
aml_cell_format + _xs['left'],
num_format_str=report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(
aml_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# totals # totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all'] rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format) self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right']) self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str=report_xls.decimal_format)
self.rt_cell_style_decimal = xlwt.easyxf(
rt_cell_format + _xs['right'],
num_format_str=report_xls.decimal_format)
# XLS Template # XLS Template
self.col_specs_template = { self.col_specs_template = {
@ -95,19 +104,27 @@ class move_line_xls(report_xls):
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'date': { 'date': {
'header': [1, 13, 'text', _render("_('Effective Date')")], 'header': [1, 13, 'text', _render("_('Effective Date')")],
'lines': [1, 0, 'date', _render("datetime.strptime(line.date,'%Y-%m-%d')"), None, self.aml_cell_style_date],
'lines': [1, 0, 'date',
_render("datetime.strptime(line.date,'%Y-%m-%d')"),
None, self.aml_cell_style_date],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'period': { 'period': {
'header': [1, 12, 'text', _render("_('Period')")], 'header': [1, 12, 'text', _render("_('Period')")],
'lines': [1, 0, 'text', _render("line.period_id.code or line.period_id.name")],
'lines':
[1, 0, 'text',
_render("line.period_id.code or line.period_id.name")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'partner': { 'partner': {
'header': [1, 36, 'text', _render("_('Partner')")], 'header': [1, 36, 'text', _render("_('Partner')")],
'lines': [1, 0, 'text', _render("line.partner_id and line.partner_id.name or ''")],
'lines':
[1, 0, 'text',
_render("line.partner_id and line.partner_id.name or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'partner_ref': { 'partner_ref': {
'header': [1, 36, 'text', _render("_('Partner Reference')")], 'header': [1, 36, 'text', _render("_('Partner Reference')")],
'lines': [1, 0, 'text', _render("line.partner_id and line.partner_id.ref or ''")],
'lines':
[1, 0, 'text',
_render("line.partner_id and line.partner_id.ref or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'account': { 'account': {
'header': [1, 12, 'text', _render("_('Account')")], 'header': [1, 12, 'text', _render("_('Account')")],
@ -115,47 +132,78 @@ class move_line_xls(report_xls):
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'date_maturity': { 'date_maturity': {
'header': [1, 13, 'text', _render("_('Maturity Date')")], 'header': [1, 13, 'text', _render("_('Maturity Date')")],
'lines': [1, 0, _render("line.date_maturity.val and 'date' or 'text'"),
_render("line.date_maturity.val and datetime.strptime(line.date_maturity,'%Y-%m-%d') or None"),
'lines':
[1, 0,
_render("line.date_maturity.val and 'date' or 'text'"),
_render(
"line.date_maturity.val \
and datetime.strptime(line.date_maturity,'%Y-%m-%d') \
or None"),
None, self.aml_cell_style_date], None, self.aml_cell_style_date],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'debit': { 'debit': {
'header': [1, 18, 'text', _render("_('Debit')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.debit"), None, self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("debit_formula"), self.rt_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Debit')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.debit"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("debit_formula"),
self.rt_cell_style_decimal]},
'credit': { 'credit': {
'header': [1, 18, 'text', _render("_('Credit')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.credit"), None, self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("credit_formula"), self.rt_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Credit')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.credit"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("credit_formula"),
self.rt_cell_style_decimal]},
'balance': { 'balance': {
'header': [1, 18, 'text', _render("_('Balance')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', None, _render("bal_formula"), self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("bal_formula"), self.rt_cell_style_decimal]},
'header': [1, 18, 'text', _render("_('Balance')"), None,
self.rh_cell_style_right],
'lines': [1, 0, 'number', None, _render("bal_formula"),
self.aml_cell_style_decimal],
'totals': [1, 0, 'number', None, _render("bal_formula"),
self.rt_cell_style_decimal]},
'reconcile': { 'reconcile': {
'header': [1, 12, 'text', _render("_('Rec.')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("line.reconcile_id.name or ''"), None, self.aml_cell_style_center],
'header': [1, 12, 'text', _render("_('Rec.')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text',
_render("line.reconcile_id.name or ''"), None,
self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'reconcile_partial': { 'reconcile_partial': {
'header': [1, 12, 'text', _render("_('Part. Rec.')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("line.reconcile_partial_id.name or ''"), None, self.aml_cell_style_center],
'header': [1, 12, 'text', _render("_('Part. Rec.')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text',
_render("line.reconcile_partial_id.name or ''"),
None, self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'tax_code': { 'tax_code': {
'header': [1, 12, 'text', _render("_('Tax Code')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("line.tax_code_id.code or ''"), None, self.aml_cell_style_center],
'header': [1, 12, 'text', _render("_('Tax Code')"), None,
self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("line.tax_code_id.code or ''"),
None, self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'tax_amount': { 'tax_amount': {
'header': [1, 18, 'text', _render("_('Tax/Base Amount')"), None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.tax_amount"), None, self.aml_cell_style_decimal],
'header': [1, 18, 'text', _render("_('Tax/Base Amount')"),
None, self.rh_cell_style_right],
'lines': [1, 0, 'number', _render("line.tax_amount"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'amount_currency': { 'amount_currency': {
'header': [1, 18, 'text', _render("_('Am. Currency')"), None, self.rh_cell_style_right],
'lines': [1, 0, _render("line.amount_currency and 'number' or 'text'"),
_render("line.amount_currency or None"),
None, self.aml_cell_style_decimal],
'header': [1, 18, 'text', _render("_('Am. Currency')"), None,
self.rh_cell_style_right],
'lines':
[1, 0,
_render("line.amount_currency and 'number' or 'text'"),
_render("line.amount_currency or None"),
None, self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'currency_name': { 'currency_name': {
'header': [1, 6, 'text', _render("_('Curr.')"), None, self.rh_cell_style_center],
'lines': [1, 0, 'text', _render("line.currency_id and line.currency_id.name or ''"), None, self.aml_cell_style_center],
'header': [1, 6, 'text', _render("_('Curr.')"), None,
self.rh_cell_style_center],
'lines':
[1, 0, 'text',
_render("line.currency_id and line.currency_id.name or ''"),
None, self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'journal': { 'journal': {
'header': [1, 12, 'text', _render("_('Journal')")], 'header': [1, 12, 'text', _render("_('Journal')")],
@ -163,11 +211,14 @@ class move_line_xls(report_xls):
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'company_currency': { 'company_currency': {
'header': [1, 10, 'text', _render("_('Comp. Curr.')")], 'header': [1, 10, 'text', _render("_('Comp. Curr.')")],
'lines': [1, 0, 'text', _render("line.company_id.currency_id.name or ''"), None, self.aml_cell_style_center],
'lines': [1, 0, 'text',
_render("line.company_id.currency_id.name or ''"),
None, self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'analytic_account': { 'analytic_account': {
'header': [1, 36, 'text', _render("_('Analytic Account')")], 'header': [1, 36, 'text', _render("_('Analytic Account')")],
'lines': [1, 0, 'text', _render("line.analytic_account_id.code or ''")],
'lines': [1, 0, 'text',
_render("line.analytic_account_id.code or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'product': { 'product': {
'header': [1, 36, 'text', _render("_('Product')")], 'header': [1, 36, 'text', _render("_('Product')")],
@ -175,44 +226,64 @@ class move_line_xls(report_xls):
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'product_ref': { 'product_ref': {
'header': [1, 36, 'text', _render("_('Product Reference')")], 'header': [1, 36, 'text', _render("_('Product Reference')")],
'lines': [1, 0, 'text', _render("line.product_id.default_code or ''")],
'lines': [1, 0, 'text',
_render("line.product_id.default_code or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'product_uom': { 'product_uom': {
'header': [1, 20, 'text', _render("_('Unit of Measure')")], 'header': [1, 20, 'text', _render("_('Unit of Measure')")],
'lines': [1, 0, 'text', _render("line.product_uom_id.name or ''")],
'lines': [1, 0, 'text',
_render("line.product_uom_id.name or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'quantity': { 'quantity': {
'header': [1, 8, 'text', _render("_('Qty')"), None, self.rh_cell_style_right],
'lines': [1, 0, _render("line.quantity and 'number' or 'text'"),
_render("line.quantity or None"), None, self.aml_cell_style_decimal],
'header': [1, 8, 'text', _render("_('Qty')"), None,
self.rh_cell_style_right],
'lines': [1, 0,
_render("line.quantity and 'number' or 'text'"),
_render("line.quantity or None"), None,
self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'statement': { 'statement': {
'header': [1, 20, 'text', _render("_('Statement')")], 'header': [1, 20, 'text', _render("_('Statement')")],
'lines': [1, 0, 'text', _render("line.statement_id and line.statement_id.name or ''")],
'lines':
[1, 0, 'text',
_render("line.statement_id and line.statement_id.name or ''")
],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'invoice': { 'invoice': {
'header': [1, 20, 'text', _render("_('Invoice')")], 'header': [1, 20, 'text', _render("_('Invoice')")],
'lines': [1, 0, 'text', _render("line.invoice and line.invoice.number or ''")],
'lines':
[1, 0, 'text',
_render("line.invoice and line.invoice.number or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'amount_residual': { 'amount_residual': {
'header': [1, 18, 'text', _render("_('Residual Amount')"), None, self.rh_cell_style_right],
'lines': [1, 0, _render("line.amount_residual and 'number' or 'text'"),
_render("line.amount_residual or None"),
None, self.aml_cell_style_decimal],
'header': [1, 18, 'text', _render("_('Residual Amount')"),
None, self.rh_cell_style_right],
'lines':
[1, 0,
_render("line.amount_residual and 'number' or 'text'"),
_render("line.amount_residual or None"),
None, self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'amount_residual_currency': { 'amount_residual_currency': {
'header': [1, 18, 'text', _render("_('Res. Am. in Curr.')"), None, self.rh_cell_style_right],
'lines': [1, 0, _render("line.amount_residual_currency and 'number' or 'text'"),
_render("line.amount_residual_currency or None"),
None, self.aml_cell_style_decimal],
'header': [1, 18, 'text', _render("_('Res. Am. in Curr.')"),
None, self.rh_cell_style_right],
'lines':
[1, 0,
_render(
"line.amount_residual_currency and 'number' or 'text'"),
_render("line.amount_residual_currency or None"),
None, self.aml_cell_style_decimal],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'narration': { 'narration': {
'header': [1, 42, 'text', _render("_('Notes')")], 'header': [1, 42, 'text', _render("_('Notes')")],
'lines': [1, 0, 'text', _render("line.move_id.narration or ''")],
'lines': [1, 0, 'text',
_render("line.move_id.narration or ''")],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
'blocked': { 'blocked': {
'header': [1, 4, 'text', _('Lit.'), None, self.rh_cell_style_right],
'lines': [1, 0, 'text', _render("line.blocked and 'x' or ''"), None, self.aml_cell_style_center],
'header': [1, 4, 'text', _('Lit.'),
None, self.rh_cell_style_right],
'lines': [1, 0, 'text', _render("line.blocked and 'x' or ''"),
None, self.aml_cell_style_center],
'totals': [1, 0, 'text', None]}, 'totals': [1, 0, 'text', None]},
} }
@ -225,10 +296,12 @@ class move_line_xls(report_xls):
debit_pos = 'debit' in wanted_list and wanted_list.index('debit') debit_pos = 'debit' in wanted_list and wanted_list.index('debit')
credit_pos = 'credit' in wanted_list and wanted_list.index('credit') credit_pos = 'credit' in wanted_list and wanted_list.index('credit')
if not (credit_pos and debit_pos) and 'balance' in wanted_list: if not (credit_pos and debit_pos) and 'balance' in wanted_list:
raise orm.except_orm(_('Customisation Error!'),
_("The 'Balance' field is a calculated XLS field requiring the presence of the 'Debit' and 'Credit' fields !"))
raise orm.except_orm(
_('Customisation Error!'),
_("The 'Balance' field is a calculated XLS field requiring \
the presence of the 'Debit' and 'Credit' fields !"))
#report_name = objects[0]._description or objects[0]._name
# report_name = objects[0]._description or objects[0]._name
report_name = _("Journal Items") report_name = _("Journal Items")
ws = wb.add_sheet(report_name[:31]) ws = wb.add_sheet(report_name[:31])
ws.panes_frozen = True ws.panes_frozen = True
@ -247,13 +320,18 @@ class move_line_xls(report_xls):
('report_name', 1, 0, 'text', report_name), ('report_name', 1, 0, 'text', report_name),
] ]
row_data = self.xls_row_template(c_specs, ['report_name']) row_data = self.xls_row_template(c_specs, ['report_name'])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=cell_style)
row_pos += 1 row_pos += 1
# Column headers # Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
c_specs = map(lambda x: self.render(
x, self.col_specs_template, 'header', render_space={'_': _p._}),
wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style, set_column_size=True)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.rh_cell_style,
set_column_size=True)
ws.set_horz_split_pos(row_pos) ws.set_horz_split_pos(row_pos)
# account move lines # account move lines
@ -261,27 +339,35 @@ class move_line_xls(report_xls):
debit_cell = rowcol_to_cell(row_pos, debit_pos) debit_cell = rowcol_to_cell(row_pos, debit_pos)
credit_cell = rowcol_to_cell(row_pos, credit_pos) credit_cell = rowcol_to_cell(row_pos, credit_pos)
bal_formula = debit_cell + '-' + credit_cell bal_formula = debit_cell + '-' + credit_cell
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'lines'), wanted_list)
_logger.debug('dummy call - %s', bal_formula)
c_specs = map(
lambda x: self.render(x, self.col_specs_template, 'lines'),
wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.aml_cell_style)
# Totals # Totals
aml_cnt = len(objects) aml_cnt = len(objects)
debit_start = rowcol_to_cell(row_pos - aml_cnt, debit_pos) debit_start = rowcol_to_cell(row_pos - aml_cnt, debit_pos)
debit_stop = rowcol_to_cell(row_pos - 1, debit_pos) debit_stop = rowcol_to_cell(row_pos - 1, debit_pos)
debit_formula = 'SUM(%s:%s)' % (debit_start, debit_stop) debit_formula = 'SUM(%s:%s)' % (debit_start, debit_stop)
_logger.debug('dummy call - %s', debit_formula)
credit_start = rowcol_to_cell(row_pos - aml_cnt, credit_pos) credit_start = rowcol_to_cell(row_pos - aml_cnt, credit_pos)
credit_stop = rowcol_to_cell(row_pos - 1, credit_pos) credit_stop = rowcol_to_cell(row_pos - 1, credit_pos)
credit_formula = 'SUM(%s:%s)' % (credit_start, credit_stop) credit_formula = 'SUM(%s:%s)' % (credit_start, credit_stop)
_logger.debug('dummy call - %s', credit_formula)
debit_cell = rowcol_to_cell(row_pos, debit_pos) debit_cell = rowcol_to_cell(row_pos, debit_pos)
credit_cell = rowcol_to_cell(row_pos, credit_pos) credit_cell = rowcol_to_cell(row_pos, credit_pos)
bal_formula = debit_cell + '-' + credit_cell bal_formula = debit_cell + '-' + credit_cell
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'totals'), wanted_list)
_logger.debug('dummy call - %s', bal_formula)
c_specs = map(
lambda x: self.render(x, self.col_specs_template, 'totals'),
wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs]) row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rt_cell_style_right)
row_pos = self.xls_write_row(
ws, row_pos, row_data, row_style=self.rt_cell_style_right)
move_line_xls('report.move.line.list.xls', move_line_xls('report.move.line.list.xls',
'account.move.line',
parser=move_line_xls_parser)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
'account.move.line',
parser=move_line_xls_parser)
Loading…
Cancel
Save