Browse Source

Aug 30 [FIX] : Bug Fixed 'dynamic_accounts_report'

pull/277/head
AjmalCybro 2 years ago
parent
commit
451b26523d
  1. 2
      dynamic_accounts_report/__manifest__.py
  2. 21
      dynamic_accounts_report/controllers/__init__.py
  3. 33
      dynamic_accounts_report/controllers/controllers.py
  4. 5
      dynamic_accounts_report/doc/RELEASE_NOTES.md
  5. 21
      dynamic_accounts_report/models/__init__.py
  6. 102
      dynamic_accounts_report/models/account_account_custom.py
  7. 88
      dynamic_accounts_report/models/move_line.py
  8. 21
      dynamic_accounts_report/report/__init__.py
  9. 29
      dynamic_accounts_report/report/ageing.py
  10. 25
      dynamic_accounts_report/report/cash_flow_report.py
  11. 28
      dynamic_accounts_report/report/daybook.py
  12. 23
      dynamic_accounts_report/report/financial_reports.py
  13. 41
      dynamic_accounts_report/report/general_ledger.py
  14. 34
      dynamic_accounts_report/report/partner_ledger.py
  15. 9
      dynamic_accounts_report/report/partner_ledger.xml
  16. 34
      dynamic_accounts_report/report/trial_balance.py
  17. 1
      dynamic_accounts_report/static/description/index.html
  18. 868
      dynamic_accounts_report/static/src/js/ageing.js
  19. 775
      dynamic_accounts_report/static/src/js/cash_flow.js
  20. 876
      dynamic_accounts_report/static/src/js/daybook.js
  21. 751
      dynamic_accounts_report/static/src/js/financial_reports.js
  22. 978
      dynamic_accounts_report/static/src/js/general_ledger.js
  23. 932
      dynamic_accounts_report/static/src/js/partner_ledger.js
  24. 672
      dynamic_accounts_report/static/src/js/trial_balance.js
  25. 356
      dynamic_accounts_report/static/src/xml/financial_reports_view.xml
  26. 409
      dynamic_accounts_report/static/src/xml/general_ledger_view.xml
  27. 115
      dynamic_accounts_report/static/src/xml/partner_ledger_view.xml
  28. 21
      dynamic_accounts_report/wizard/__init__.py
  29. 115
      dynamic_accounts_report/wizard/ageing.py
  30. 58
      dynamic_accounts_report/wizard/balance_sheet.py
  31. 79
      dynamic_accounts_report/wizard/balance_sheet_config.py
  32. 72
      dynamic_accounts_report/wizard/cash_flow.py
  33. 22
      dynamic_accounts_report/wizard/daybook.py
  34. 347
      dynamic_accounts_report/wizard/general_ledger.py
  35. 164
      dynamic_accounts_report/wizard/partner_leadger.py
  36. 21
      dynamic_accounts_report/wizard/trial_balance.py

2
dynamic_accounts_report/__manifest__.py

@ -22,7 +22,7 @@
{ {
'name': 'Dynamic Financial Reports V16', 'name': 'Dynamic Financial Reports V16',
'version': '16.0.1.0.5', 'version': '16.0.1.0.6',
'category': 'Accounting', 'category': 'Accounting',
'live_test_url': 'https://www.youtube.com/watch?v=gVQi9q9Rs-E&t=5s', 'live_test_url': 'https://www.youtube.com/watch?v=gVQi9q9Rs-E&t=5s',
'summary': """Dynamic Financial Reports with drill 'summary': """Dynamic Financial Reports with drill

21
dynamic_accounts_report/controllers/__init__.py

@ -1,3 +1,22 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from . import controllers from . import controllers

33
dynamic_accounts_report/controllers/controllers.py

@ -1,5 +1,24 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import json import json
from odoo import http from odoo import http
from odoo.http import content_disposition, request from odoo.http import content_disposition, request
@ -8,8 +27,10 @@ from odoo.tools import html_escape
class TBXLSXReportController(http.Controller): class TBXLSXReportController(http.Controller):
@http.route('/dynamic_xlsx_reports', type='http', auth='user', methods=['POST'], csrf=False) @http.route('/dynamic_xlsx_reports', type='http', auth='user',
def get_report_xlsx(self, model, options, output_format, report_data, report_name, dfr_data, **kw): methods=['POST'], csrf=False)
def get_report_xlsx(self, model, options, output_format, report_data,
report_name, dfr_data, **kw):
uid = request.session.uid uid = request.session.uid
report_obj = request.env[model].with_user(uid) report_obj = request.env[model].with_user(uid)
dfr_data = dfr_data dfr_data = dfr_data
@ -21,10 +42,12 @@ class TBXLSXReportController(http.Controller):
None, None,
headers=[ headers=[
('Content-Type', 'application/vnd.ms-excel'), ('Content-Type', 'application/vnd.ms-excel'),
('Content-Disposition', content_disposition(report_name + '.xlsx')) ('Content-Disposition',
content_disposition(report_name + '.xlsx'))
] ]
) )
report_obj.get_dynamic_xlsx_report(options, response, report_data, dfr_data) report_obj.get_dynamic_xlsx_report(options, response,
report_data, dfr_data)
response.set_cookie('fileToken', token) response.set_cookie('fileToken', token)
return response return response
except Exception as e: except Exception as e:

5
dynamic_accounts_report/doc/RELEASE_NOTES.md

@ -19,3 +19,8 @@
#### Version 16.0.1.0.5 #### Version 16.0.1.0.5
#### BUGFIX #### BUGFIX
- Report Bug Fix: Journal filter is not visible for any languages other than english, entries of all journals are taken for bank book and cash book for other languages. - Report Bug Fix: Journal filter is not visible for any languages other than english, entries of all journals are taken for bank book and cash book for other languages.
#### 24.08.2023
#### Version 16.0.1.0.6
#### BUGFIX
- Report Bug Fix: The issues with the analytic filter in the general ledger, partner ledger, and profit and loss statement have been fixed, and the problem with language while printing reports has also been addressed.

21
dynamic_accounts_report/models/__init__.py

@ -1,2 +1,23 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from . import move_line from . import move_line
from . import account_account_custom from . import account_account_custom

102
dynamic_accounts_report/models/account_account_custom.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import models, api from odoo import models, api
@ -10,39 +31,42 @@ class AccountAccountCustom(models.Model):
if res.account_type.startswith("asset"): if res.account_type.startswith("asset"):
for record in self.env['account.financial.report'].search( for record in self.env['account.financial.report'].search(
[('type', '=', 'account_type')]): [('type', '=', 'account_type')]):
if record.get_metadata()[0].get( if (record.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_assets0': 'base_accounting_kit.account_financial_report_assets0'):
record.write({"account_ids": [(4, res.id)]}) record.write({"account_ids": [(4, res.id)]})
elif res.account_type.startswith( elif res.account_type.startswith(
"liability") or res.account_type == "equity": "liability") or res.account_type == "equity":
for record in self.env['account.financial.report'].search( for record in self.env['account.financial.report'].search(
[('type', '=', 'account_type')]): [('type', '=', 'account_type')]):
if record.get_metadata()[0].get( if (record.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_liability0': 'base_accounting_kit'
'.account_financial_report_liability0'):
record.write({"account_ids": [(4, res.id)]}) record.write({"account_ids": [(4, res.id)]})
elif res.account_type in ['expense', 'expense_depreciation']: elif res.account_type in ['expense', 'expense_depreciation']:
for record in self.env['account.financial.report'].search( for record in self.env['account.financial.report'].search(
[('type', '=', 'account_type')]): [('type', '=', 'account_type')]):
if record.get_metadata()[0].get( if (record.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_expense0': 'base_accounting_kit.account_financial_report_expense0'):
record.write({"account_ids": [(4, res.id)]}) record.write({"account_ids": [(4, res.id)]})
elif res.account_type == "expense_direct_cost": elif res.account_type == "expense_direct_cost":
for record in self.env['account.financial.report'].search( for record in self.env['account.financial.report'].search(
[('type', '=', 'account_type')]): [('type', '=', 'account_type')]):
if record.get_metadata()[0].get( if (record.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.financial_report_cost_of_revenue': 'base_accounting_kit.financial_report_cost_of_revenue'):
record.write({"account_ids": [(4, res.id)]}) record.write({"account_ids": [(4, res.id)]})
elif res.account_type in ['income', 'equity_unaffected']: elif res.account_type in ['income', 'equity_unaffected']:
for record in self.env['account.financial.report'].search( for record in self.env['account.financial.report'].search(
[('type', '=', 'account_type')]): [('type', '=', 'account_type')]):
if record.get_metadata()[0].get( if (record.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_operating_income0': 'base_accounting_kit'
'.account_financial_report_operating_income0'):
record.write({"account_ids": [(4, res.id)]}) record.write({"account_ids": [(4, res.id)]})
elif res.account_type == 'income_other': elif res.account_type == 'income_other':
for record in self.env['account.financial.report'].search( for record in self.env['account.financial.report'].search(
[('type', '=', 'account_type')]): [('type', '=', 'account_type')]):
if record.get_metadata()[0].get( if (record.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_other_income0': 'base_accounting_kit'
'.account_financial_report_other_income0'):
record.write({"account_ids": [(4, res.id)]}) record.write({"account_ids": [(4, res.id)]})
return res return res
@ -55,51 +79,57 @@ class AccountAccountCustom(models.Model):
record.write({"account_ids": [(3, rec.id)]}) record.write({"account_ids": [(3, rec.id)]})
if self.account_type.startswith("asset"): if self.account_type.startswith("asset"):
for record1 in self.env[ for record1 in self.env[
'account.financial.report'].search( 'account.financial.report'].search([(
[('type', '=', 'account_type')]): 'type', '=', 'account_type')]):
if record1.get_metadata()[0].get( if (record1.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_assets0': 'base_accounting_kit'
'.account_financial_report_assets0'):
record1.write( record1.write(
{"account_ids": [(4, self._origin.id)]}) {"account_ids": [(4, self._origin.id)]})
elif self.account_type.startswith( elif self.account_type.startswith(
"liability") or self.account_type == "equity": "liability") or self.account_type == "equity":
for record1 in self.env[ for record1 in self.env[
'account.financial.report'].search( 'account.financial.report'].search([(
[('type', '=', 'account_type')]): 'type', '=', 'account_type')]):
if record1.get_metadata()[0].get( if (record1.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_liability0': 'base_accounting_kit'
'.account_financial_report_liability0'):
record1.write( record1.write(
{"account_ids": [(4, self._origin.id)]}) {"account_ids": [(4, self._origin.id)]})
elif self.account_type in ['expense', elif self.account_type in ['expense',
'expense_depreciation']: 'expense_depreciation']:
for record1 in self.env[ for record1 in self.env[
'account.financial.report'].search( 'account.financial.report'].search([(
[('type', '=', 'account_type')]): 'type', '=', 'account_type')]):
if record1.get_metadata()[0].get( if (record1.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_expense0': 'base_accounting_kit'
'.account_financial_report_expense0'):
record1.write( record1.write(
{"account_ids": [(4, self._origin.id)]}) {"account_ids": [(4, self._origin.id)]})
elif self.account_type == "expense_direct_cost": elif self.account_type == "expense_direct_cost":
for record1 in self.env[ for record1 in self.env[
'account.financial.report'].search( 'account.financial.report'].search([(
[('type', '=', 'account_type')]): 'type', '=', 'account_type')]):
if record1.get_metadata()[0].get( if (record1.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.financial_report_cost_of_revenue': 'base_accounting_kit'
'.financial_report_cost_of_revenue'):
record1.write( record1.write(
{"account_ids": [(4, self._origin.id)]}) {"account_ids": [(4, self._origin.id)]})
elif self.account_type in ['income', 'equity_unaffected']: elif self.account_type in ['income', 'equity_unaffected']:
for record1 in self.env[ for record1 in self.env[
'account.financial.report'].search( 'account.financial.report'].search([(
[('type', '=', 'account_type')]): 'type', '=', 'account_type')]):
if record1.get_metadata()[0].get( if (record1.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_operating_income0': 'base_accounting_kit'
'.account_financial_report_operating_income0'):
record1.write( record1.write(
{"account_ids": [(4, self._origin.id)]}) {"account_ids": [(4, self._origin.id)]})
elif self.account_type == 'income_other': elif self.account_type == 'income_other':
for record1 in self.env[ for record1 in self.env[
'account.financial.report'].search( 'account.financial.report'].search([(
[('type', '=', 'account_type')]): 'type', '=', 'account_type')]):
if record1.get_metadata()[0].get( if (record1.get_metadata()[0].get('xmlid') ==
'xmlid') == 'base_accounting_kit.account_financial_report_other_income0': 'base_accounting_kit'
'.account_financial_report_other_income0'):
record1.write( record1.write(
{"account_ids": [(4, self._origin.id)]}) {"account_ids": [(4, self._origin.id)]})

88
dynamic_accounts_report/models/move_line.py

@ -1,19 +1,36 @@
from odoo import fields, models, api, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
from odoo.http import request from odoo.http import request
import ast import ast
from odoo.exceptions import AccessError, UserError, AccessDenied
class AccountMoveLine(models.Model): class AccountMoveLine(models.Model):
_inherit = "account.move.line"
"""Function is updated to avoid conflict for new and old odoo V15 addons""" """Function is updated to avoid conflict for new and old odoo V15 addons"""
_inherit = "account.move.line"
@api.model @api.model
def _query_get(self, domain=None): def _query_get(self, domain=None):
self.check_access_rights('read') self.check_access_rights('read')
context = dict(self._context or {}) context = dict(self._context or {})
domain = domain or [] domain = domain or []
if not isinstance(domain, (list, tuple)): if not isinstance(domain, (list, tuple)):
@ -26,71 +43,56 @@ class AccountMoveLine(models.Model):
domain += [(date_field, '<=', context['date_to'])] domain += [(date_field, '<=', context['date_to'])]
if context.get('date_from'): if context.get('date_from'):
if not context.get('strict_range'): if not context.get('strict_range'):
domain += ['|', (date_field, '>=', context['date_from']), ('account_id.include_initial_balance', '=', True)] domain += ['|', (date_field, '>=', context['date_from']),
('account_id.include_initial_balance', '=', True)]
elif context.get('initial_bal'): elif context.get('initial_bal'):
domain += [(date_field, '<', context['date_from'])] domain += [(date_field, '<', context['date_from'])]
else: else:
domain += [(date_field, '>=', context['date_from'])] domain += [(date_field, '>=', context['date_from'])]
if context.get('journal_ids'):
domain += [('journal_id', 'in', context['journal_ids'])]
state = context.get('state') state = context.get('state')
if state and state.lower() != 'all': if state and state.lower() != 'all':
domain += [('parent_state', '=', state)] domain += [('parent_state', '=', state)]
# if context.get('company_id'):
# domain += [('company_id', '=', context['company_id'])]
# elif context.get('allowed_company_ids'):
# domain += [('company_id', 'in', self.env.companies.ids)]
# else:
# domain += [('company_id', '=', self.env.company.id)]
if context.get('reconcile_date'): if context.get('reconcile_date'):
domain += ['|', ('reconciled', '=', False), '|', ('matched_debit_ids.max_date', '>', context['reconcile_date']), ('matched_credit_ids.max_date', '>', context['reconcile_date'])] domain += ['|', ('reconciled', '=', False), '|', (
'matched_debit_ids.max_date', '>', context['reconcile_date']),
(
'matched_credit_ids.max_date', '>',
context['reconcile_date'])]
if context.get('account_tag_ids'): if context.get('account_tag_ids'):
domain += [('account_id.tag_ids', 'in', context['account_tag_ids'].ids)] domain += [
('account_id.tag_ids', 'in', context['account_tag_ids'].ids)]
if context.get('journal_ids'):
domain += [('journal_id', 'in', context['journal_ids'])]
if context.get('account_ids'): if context.get('account_ids'):
domain += [('account_id', 'in', context['account_ids'].ids)] domain += [('account_id', 'in', context['account_ids'].ids)]
if context.get('analytic_line_ids'):
# if context.get('analytic_tag_ids'): domain += [
# domain += [('analytic_tag_ids', 'in', context['analytic_tag_ids'].ids)] ('analytic_line_ids', 'in', context['analytic_line_ids'].ids)]
if context.get('analytic_account_ids'):
domain += [('analytic_account_id', 'in', context['analytic_account_ids'].ids)]
if context.get('partner_ids'): if context.get('partner_ids'):
domain += [('partner_id', 'in', context['partner_ids'].ids)] domain += [('partner_id', 'in', context['partner_ids'].ids)]
if context.get('partner_categories'): if context.get('partner_categories'):
domain += [('partner_id.category_id', 'in', context['partner_categories'].ids)] domain += [('partner_id.category_id', 'in',
context['partner_categories'].ids)]
company_ids = self.get_current_company_value() company_ids = self.get_current_company_value()
domain += [('company_id', 'in', company_ids)] domain += [('company_id', 'in', company_ids)]
where_clause = "" where_clause = ""
where_clause_params = [] where_clause_params = []
tables = '' tables = ''
if domain: if domain:
domain.append(('display_type', 'not in', ('line_section', 'line_note'))) domain.append(
('display_type', 'not in', ('line_section', 'line_note')))
domain.append(('parent_state', '!=', 'cancel')) domain.append(('parent_state', '!=', 'cancel'))
query = self._where_calc(domain) query = self._where_calc(domain)
# Wrap the query with 'company_id IN (...)' to avoid bypassing
# Wrap the query with 'company_id IN (...)' to avoid bypassing company access rights. # company access rights.
self._apply_ir_rules(query) self._apply_ir_rules(query)
tables, where_clause, where_clause_params = query.get_sql() tables, where_clause, where_clause_params = query.get_sql()
return tables, where_clause, where_clause_params return tables, where_clause, where_clause_params
def get_current_company_value(self): def get_current_company_value(self):
cookies_cids = [int(r) for r in
cookies_cids = [int(r) for r in request.httprequest.cookies.get('cids').split(",")] \ request.httprequest.cookies.get('cids').split(",")] \
if request.httprequest.cookies.get('cids') \ if request.httprequest.cookies.get('cids') \
else [request.env.user.company_id.id] else [request.env.user.company_id.id]
for company_id in cookies_cids: for company_id in cookies_cids:

21
dynamic_accounts_report/report/__init__.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from . import trial_balance from . import trial_balance
from . import general_ledger from . import general_ledger
from . import cash_flow_report from . import cash_flow_report

29
dynamic_accounts_report/report/ageing.py

@ -1,19 +1,38 @@
from odoo import api, models, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class PartnerAgeing(models.AbstractModel): class PartnerAgeing(models.AbstractModel):
_name = 'report.dynamic_accounts_report.partner_ageing' _name = 'report.dynamic_accounts_report.partner_ageing'
@api.model @api.model
def _get_report_values(self, docids, data=None): def _get_report_values(self,docids, data=None):
print(data)
if self.env.context.get('ageing_pdf_report'): if self.env.context.get('ageing_pdf_report'):
if data.get('report_data'): if data.get('report_data'):
data.update( data.update(
{'account_data': data.get('report_data')['report_lines'][0], {'account_data': data.get('report_data')['report_lines'][0],
'Filters': data.get('report_data')['filters'], 'Filters': data.get('report_data')['filters'],
'company': self.env.company, 'company': self.env.company,
}) })
return data return data

25
dynamic_accounts_report/report/cash_flow_report.py

@ -1,11 +1,32 @@
from odoo import api, models, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class GeneralLedger(models.AbstractModel): class GeneralLedger(models.AbstractModel):
_name = 'report.dynamic_accounts_report.cash_flow' _name = 'report.dynamic_accounts_report.cash_flow'
@api.model @api.model
def _get_report_values(self, docids, data=None): def _get_report_values(self,docids, data=None):
if self.env.context.get('trial_pdf_report'): if self.env.context.get('trial_pdf_report'):
if data.get('report_data'): if data.get('report_data'):

28
dynamic_accounts_report/report/daybook.py

@ -1,16 +1,38 @@
from odoo import api, models, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class DayBook(models.AbstractModel): class DayBook(models.AbstractModel):
_name = 'report.dynamic_accounts_report.day_book' _name = 'report.dynamic_accounts_report.day_book'
@api.model @api.model
def _get_report_values(self, docids, data=None): def _get_report_values(self,docids, data=None):
if self.env.context.get('daybook_pdf_report'): if self.env.context.get('daybook_pdf_report'):
if data.get('report_data'): if data.get('report_data'):
data.update({'account_data': data.get('report_data')['report_lines'], data.update({'account_data': data.get('report_data')[
'report_lines'],
'Filters': data.get('report_data')['filters'], 'Filters': data.get('report_data')['filters'],
'company': self.env.company, 'company': self.env.company,
}) })

23
dynamic_accounts_report/report/financial_reports.py

@ -1,5 +1,25 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from odoo import api, models, _ #############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class InsReportBalanceSheet(models.AbstractModel): class InsReportBalanceSheet(models.AbstractModel):
@ -10,6 +30,7 @@ class InsReportBalanceSheet(models.AbstractModel):
if self.env.context.get('bs_report'): if self.env.context.get('bs_report'):
if data.get('report_data'): if data.get('report_data'):
data.update({ data.update({
'doc_ids': docids,
'Filters': data.get('report_data')['filters'], 'Filters': data.get('report_data')['filters'],
'account_data': data.get('report_data')['report_lines'], 'account_data': data.get('report_data')['report_lines'],
'report_lines': data.get('report_data')['bs_lines'], 'report_lines': data.get('report_data')['bs_lines'],

41
dynamic_accounts_report/report/general_ledger.py

@ -1,4 +1,25 @@
from odoo import api, models, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class GeneralLedger(models.AbstractModel): class GeneralLedger(models.AbstractModel):
@ -6,14 +27,16 @@ class GeneralLedger(models.AbstractModel):
@api.model @api.model
def _get_report_values(self, docids, data=None): def _get_report_values(self, docids, data=None):
print('_get_report_values........',data)
if self.env.context.get('trial_pdf_report'): if self.env.context.get('trial_pdf_report'):
if data.get('report_data'): if data.get('report_data'):
data.update({'account_data': data.get('report_data')['report_lines'], data.update(
'Filters': data.get('report_data')['filters'], {'doc_ids': docids,
'debit_total': data.get('report_data')['debit_total'], 'account_data': data.get('report_data')['report_lines'],
'credit_total': data.get('report_data')['credit_total'], 'Filters': data.get('report_data')['filters'],
'title': data.get('report_data')['name'], 'debit_total': data.get('report_data')['debit_total'],
'eng_title': data.get('report_data')['eng_title'], 'credit_total': data.get('report_data')['credit_total'],
'company': self.env.company, 'title': data.get('report_data')['name'],
}) 'company': self.env.company,
})
return data return data

34
dynamic_accounts_report/report/partner_ledger.py

@ -1,4 +1,25 @@
from odoo import api, models, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class PartnerLedgerReport(models.AbstractModel): class PartnerLedgerReport(models.AbstractModel):
@ -7,10 +28,11 @@ class PartnerLedgerReport(models.AbstractModel):
@api.model @api.model
def _get_report_values(self, docids, data=None): def _get_report_values(self, docids, data=None):
if self.env.context.get('partner_ledger_pdf_report'): if self.env.context.get('partner_ledger_pdf_report'):
if data.get('report_data'): if data.get('report_data'):
data.update({'account_data': data.get('report_data')['report_lines'], data.update({
'Filters': data.get('report_data')['filters'], 'doc_ids': docids,
'company': self.env.company, 'account_data': data.get('report_data')['report_lines'],
}) 'Filters': data.get('report_data')['filters'],
'company': self.env.company,
})
return data return data

9
dynamic_accounts_report/report/partner_ledger.xml

@ -60,11 +60,9 @@
</div> </div>
<div class="col-2"> <div class="col-2">
<strong>Account Type:</strong> <strong>Account Type:</strong>
<t t-foreach="Filters['account_type']" t-as="ps">
<li> <li>
<t t-esc="ps"/> <t t-esc="Filters['account_type']"/>
</li> </li>
</t>
</div> </div>
<div class="col-2"> <div class="col-2">
<strong>Target move:</strong> <strong>Target move:</strong>
@ -72,14 +70,10 @@
<t t-esc="Filters['target_move']"/> <t t-esc="Filters['target_move']"/>
</li> </li>
</div> </div>
</div> </div>
<div style="text-align:centre;left:50%;" class="row"> <div style="text-align:centre;left:50%;" class="row">
</div> </div>
<br></br> <br></br>
<table class="table table-sm table-reports" style="padding:5px;"> <table class="table table-sm table-reports" style="padding:5px;">
<thead> <thead>
@ -117,7 +111,6 @@
<td><span t-esc="line['ldate']"/></td> <td><span t-esc="line['ldate']"/></td>
<td><span t-esc="line['lcode']"/></td> <td><span t-esc="line['lcode']"/></td>
<td><span t-esc="line['account_name']"/></td> <td><span t-esc="line['account_name']"/></td>
<!-- <td><span t-if="line['lref']" t-esc="line['lref']"/></td>-->
<td><span t-esc="line['move_name']"/></td> <td><span t-esc="line['move_name']"/></td>
<td><span t-esc="line['lname']"/></td> <td><span t-esc="line['lname']"/></td>
<td class="text-right"> <td class="text-right">

34
dynamic_accounts_report/report/trial_balance.py

@ -1,18 +1,42 @@
from odoo import api, models, _ # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from odoo import api, models
class TrialBalance(models.AbstractModel): class TrialBalance(models.AbstractModel):
_name = 'report.dynamic_accounts_report.trial_balance' _name = 'report.dynamic_accounts_report.trial_balance'
@api.model @api.model
def _get_report_values(self, docids, data=None): def _get_report_values(self,docids, data=None):
if self.env.context.get('trial_pdf_report'): if self.env.context.get('trial_pdf_report'):
if data.get('report_data'): if data.get('report_data'):
data.update({'account_data': data.get('report_data')['report_lines'], data.update({'account_data': data.get('report_data'
)['report_lines'],
'Filters': data.get('report_data')['filters'], 'Filters': data.get('report_data')['filters'],
'debit_total': data.get('report_data')['debit_total'], 'debit_total': data.get('report_data'
'credit_total': data.get('report_data')['credit_total'], )['debit_total'],
'credit_total': data.get('report_data'
)['credit_total'],
'company': self.env.company, 'company': self.env.company,
}) })
return data return data

1
dynamic_accounts_report/static/description/index.html

@ -612,7 +612,6 @@
</div> </div>
<div style="display: block; margin: 30px auto;"> <div style="display: block; margin: 30px auto;">
<h3 style="font-family: 'Montserrat', sans-serif; font-size: 18px; font-weight: bold;"> <h3 style="font-family: 'Montserrat', sans-serif; font-size: 18px; font-weight: bold;">
View Source move from Cash Book Report </h3>
<p style="font-weight: 400; font-family: 'Montserrat', sans-serif; font-size: 14px;"> <p style="font-weight: 400; font-family: 'Montserrat', sans-serif; font-size: 14px;">
</p> </p>
<img src="assets/screenshots/view source move from cash book.png" <img src="assets/screenshots/view source move from cash book.png"

868
dynamic_accounts_report/static/src/js/ageing.js

@ -1,438 +1,432 @@
odoo.define('dynamic_accounts_report.ageing', function (require) { odoo.define('dynamic_accounts_report.ageing', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var datepicker = require('web.datepicker'); var datepicker = require('web.datepicker');
var time = require('web.time'); var time = require('web.time');
window.click_num = 0; window.click_num = 0;
var PartnerAgeing = AbstractAction.extend({ var PartnerAgeing = AbstractAction.extend({
template: 'AgeingTemp', template: 'AgeingTemp',
events: { events: {
'click .parent-line': 'journal_line_click', 'click .parent-line': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click #apply_filter': 'apply_filter', 'click #apply_filter': 'apply_filter',
'click #pdf': 'print_pdf', 'click #pdf': 'print_pdf',
'click #xlsx': 'print_xlsx', 'click #xlsx': 'print_xlsx',
'click .gl-line': 'show_drop_down', 'click .gl-line': 'show_drop_down',
'click .view-account-move': 'view_acc_move', 'click .view-account-move': 'view_acc_move',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
}, },
init: function(parent, action) { init: function(parent, action) {
this._super(parent, action); this._super(parent, action);
this.currency=action.currency; this.currency = action.currency;
this.report_lines = action.report_lines; this.report_lines = action.report_lines;
this.wizard_id = action.context.wizard | null; this.wizard_id = action.context.wizard | null;
}, },
start: function() { start: function() {
var self = this; var self = this;
self.initial_render = true; self.initial_render = true;
rpc.query({ rpc.query({
model: 'account.partner.ageing', model: 'account.partner.ageing',
method: 'create', method: 'create',
args: [{ args: [{
}] }]
}).then(function(t_res) { }).then(function(t_res) {
self.wizard_id = t_res; self.wizard_id = t_res;
self.load_data(self.initial_render); self.load_data(self.initial_render);
}) })
}, },
_onCalendarIconClick: function (ev) { _onCalendarIconClick: function(ev) {
var $calendarInputGroup = $(ev.currentTarget); var $calendarInputGroup = $(ev.currentTarget);
var calendarOptions = { var calendarOptions = {
minDate: moment({ y: 1000 }), minDate: moment({
maxDate: moment().add(200, 'y'), y: 1000
calendarWeeks: true, }),
defaultDate: moment().format(), maxDate: moment().add(200, 'y'),
sideBySide: true, calendarWeeks: true,
buttons: { defaultDate: moment().format(),
showClear: true, sideBySide: true,
showClose: true, buttons: {
showToday: true, showClear: true,
}, showClose: true,
showToday: true,
icons : { },
date: 'fa fa-calendar',
icons: {
}, date: 'fa fa-calendar',
locale : moment.locale(),
format : time.getLangDateFormat(), },
widgetParent: 'body', locale: moment.locale(),
allowInputToggle: true, format: time.getLangDateFormat(),
}; widgetParent: 'body',
allowInputToggle: true,
$calendarInputGroup.datetimepicker(calendarOptions); };
},
$calendarInputGroup.datetimepicker(calendarOptions);
},
load_data: function (initial_render = true) {
var self = this; load_data: function(initial_render = true) {
self.$(".categ").empty(); var self = this;
try{
var self = this; self.$(".categ").empty();
self._rpc({ try {
model: 'account.partner.ageing', var self = this;
method: 'view_report', self._rpc({
args: [[this.wizard_id]], model: 'account.partner.ageing',
}).then(function(datas) { method: 'view_report',
_.each(datas['report_lines'][0], function(rep_lines) { args: [
rep_lines.total = self.format_currency(datas['currency'],rep_lines.total); [this.wizard_id]
rep_lines[4] = self.format_currency(datas['currency'],rep_lines[4]); ],
rep_lines[3] = self.format_currency(datas['currency'],rep_lines[3]); }).then(function(datas) {
rep_lines[2] = self.format_currency(datas['currency'],rep_lines[2]); _.each(datas['report_lines'][0], function(rep_lines) {
rep_lines[1] = self.format_currency(datas['currency'],rep_lines[1]); rep_lines.total = self.format_currency(datas['currency'], rep_lines.total);
rep_lines[0] = self.format_currency(datas['currency'],rep_lines[0]); rep_lines[4] = self.format_currency(datas['currency'], rep_lines[4]);
rep_lines[3] = self.format_currency(datas['currency'], rep_lines[3]);
rep_lines['direction'] = self.format_currency(datas['currency'],rep_lines['direction']); rep_lines[2] = self.format_currency(datas['currency'], rep_lines[2]);
rep_lines[1] = self.format_currency(datas['currency'], rep_lines[1]);
}); rep_lines[0] = self.format_currency(datas['currency'], rep_lines[0]);
rep_lines['direction'] = self.format_currency(datas['currency'], rep_lines['direction']);
if (initial_render) {
self.$('.filter_view_tb').html(QWeb.render('AgeingFilterView', { });
filter_data: datas['filters'],
})); if (initial_render) {
self.$el.find('.partners').select2({ self.$('.filter_view_tb').html(QWeb.render('AgeingFilterView', {
placeholder: ' Partners...', filter_data: datas['filters'],
}); }));
self.$el.find('.category').select2({ self.$el.find('.partners').select2({
placeholder: ' Partner Category...', placeholder: ' Partners...',
}); });
self.$el.find('.target_move').select2({ self.$el.find('.category').select2({
placeholder: ' Target Move...', placeholder: ' Partner Category...',
}); });
self.$el.find('.result_selection').select2({ self.$el.find('.target_move').select2({
placeholder: ' Account Type...', placeholder: ' Target Move...',
}); });
self.$el.find('.result_selection').select2({
} placeholder: ' Account Type...',
var child=[]; });
self.$('.table_view_tb').html(QWeb.render('Ageingtable', {
}
report_lines : datas['report_lines'], var child = [];
move_lines :datas['report_lines'][2], self.$('.table_view_tb').html(QWeb.render('Ageingtable', {
filter : datas['filters'],
currency : datas['currency'], report_lines: datas['report_lines'],
})); move_lines: datas['report_lines'][2],
filter: datas['filters'],
}); currency: datas['currency'],
}));
}
catch (el) { });
window.location.href
} } catch (el) {
}, window.location.href
format_currency: function(currency, amount) { }
if (typeof(amount) != 'number') { },
amount = parseFloat(amount); format_currency: function(currency, amount) {
} if (typeof(amount) != 'number') {
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ amount = parseFloat(amount);
minimumFractionDigits: 2 }
}) var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
return formatted_value minimumFractionDigits: 2
}, })
return formatted_value
print_pdf: function(e) { },
e.preventDefault();
print_pdf: function(e) {
var self = this; e.preventDefault();
self._rpc({
model: 'account.partner.ageing', var self = this;
method: 'view_report', self._rpc({
args: [ model: 'account.partner.ageing',
[self.wizard_id] method: 'view_report',
], args: [
}).then(function(data) { [self.wizard_id]
var action = { ],
'type': 'ir.actions.report', }).then(function(data) {
'report_type': 'qweb-pdf', var action = {
'report_name': 'dynamic_accounts_report.partner_ageing', 'type': 'ir.actions.report',
'report_file': 'dynamic_accounts_report.partner_ageing', 'report_type': 'qweb-pdf',
'data': { 'report_name': 'dynamic_accounts_report.partner_ageing',
'report_data': data 'report_file': 'dynamic_accounts_report.partner_ageing',
}, 'data': {
'context': { 'report_data': data
'active_model': 'account.partner.ageing', },
'landscape': 1, 'context': {
'ageing_pdf_report': true 'active_model': 'account.partner.ageing',
'landscape': 1,
}, 'ageing_pdf_report': true
'display_name': 'Partner Ageing',
}; },
'display_name': 'Partner Ageing',
return self.do_action(action); };
});
}, return self.do_action(action);
});
},
print_xlsx: function() {
var self = this;
self._rpc({ print_xlsx: function() {
model: 'account.partner.ageing', var self = this;
method: 'view_report', self._rpc({
args: [ model: 'account.partner.ageing',
[self.wizard_id] method: 'view_report',
], args: [
}).then(function(data) { [self.wizard_id]
],
var action = { }).then(function(data) {
// 'type': 'ir_actions_dynamic_xlsx_download',
'data': { var action = {
'model': 'account.partner.ageing', // 'type': 'ir_actions_dynamic_xlsx_download',
'options': JSON.stringify(data['filters']), 'data': {
'output_format': 'xlsx', 'model': 'account.partner.ageing',
'report_data': JSON.stringify(data['report_lines']), 'options': JSON.stringify(data['filters']),
'report_name': 'Partner Ageing', 'output_format': 'xlsx',
'dfr_data': JSON.stringify(data), 'report_data': JSON.stringify(data['report_lines']),
}, 'report_name': 'Partner Ageing',
}; 'dfr_data': JSON.stringify(data),
// return self.do_action(action); },
core.action_registry.map.t_b.prototype.downloadXlsx(action) };
}); // return self.do_action(action);
}, core.action_registry.map.t_b.prototype.downloadXlsx(action)
});
},
create_lines_with_style: function(rec, attr, datas) {
var temp_str = "";
var style_name = "border-bottom: 1px solid #e6e6e6;"; create_lines_with_style: function(rec, attr, datas) {
var attr_name = attr + " style="+style_name; var temp_str = "";
var style_name = "border-bottom: 1px solid #e6e6e6;";
var attr_name = attr + " style=" + style_name;
temp_str += "<td class='child_col1' "+attr_name+" >"+rec['code'] +rec['name'] +"</td>";
if(datas.currency[1]=='after'){
temp_str += "<td class='child_col2' "+attr_name+" >"+rec['debit'].toFixed(2)+datas.currency[0]+"</td>"; temp_str += "<td class='child_col1' " + attr_name + " >" + rec['code'] + rec['name'] + "</td>";
temp_str += "<td class='child_col3' "+attr_name+" >"+rec['credit'].toFixed(2) +datas.currency[0]+ "</td>"; if (datas.currency[1] == 'after') {
temp_str += "<td class='child_col2' " + attr_name + " >" + rec['debit'].toFixed(2) + datas.currency[0] + "</td>";
} temp_str += "<td class='child_col3' " + attr_name + " >" + rec['credit'].toFixed(2) + datas.currency[0] + "</td>";
else{
temp_str += "<td class='child_col2' "+attr_name+" >"+datas.currency[0]+rec['debit'].toFixed(2) + "</td>"; } else {
temp_str += "<td class='child_col3' "+attr_name+">"+datas.currency[0]+rec['credit'].toFixed(2) + "</td>"; temp_str += "<td class='child_col2' " + attr_name + " >" + datas.currency[0] + rec['debit'].toFixed(2) + "</td>";
temp_str += "<td class='child_col3' " + attr_name + ">" + datas.currency[0] + rec['credit'].toFixed(2) + "</td>";
}
return temp_str; }
}, return temp_str;
},
journal_line_click: function (el){
click_num++; journal_line_click: function(el) {
var self = this; click_num++;
var line = $(el.target).parent().data('id'); var self = this;
var line = $(el.target).parent().data('id');
return self.do_action({
type: 'ir.actions.act_window', return self.do_action({
view_type: 'form', type: 'ir.actions.act_window',
view_mode: 'form', view_type: 'form',
res_model: 'account.move', view_mode: 'form',
views: [ res_model: 'account.move',
[false, 'form'] views: [
], [false, 'form']
res_id: line, ],
target: 'current', res_id: line,
}); target: 'current',
});
},
},
show_drop_down: function(event) {
event.preventDefault(); show_drop_down: function(event) {
var self = this; event.preventDefault();
var account_id = $(event.currentTarget).data('account-id'); var self = this;
var account_id = $(event.currentTarget).data('account-id');
var partner_id = $(event.currentTarget)[0].cells[0].innerText;
var partner_id = $(event.currentTarget)[0].cells[0].innerText;
var offset = 0;
var td = $(event.currentTarget).next('tr').find('td'); var offset = 0;
if (td.length == 1) { var td = $(event.currentTarget).next('tr').find('td');
if (td.length == 1) {
self._rpc({
model: 'account.partner.ageing', self._rpc({
method: 'view_report', model: 'account.partner.ageing',
args: [ method: 'view_report',
[self.wizard_id] args: [
], [self.wizard_id]
}).then(function(data) { ],
}).then(function(data) {
_.each(data['report_lines'][0], function(rep_lines) {
_.each(rep_lines['child_lines'], function(child_line) { _.each(data['report_lines'][0], function(rep_lines) {
child_line.amount = self.format_currency(data['currency'],child_line.amount); _.each(rep_lines['child_lines'], function(child_line) {
child_line.amount = self.format_currency(data['currency'], child_line.amount);
});
}); });
});
for (var i = 0; i < data['report_lines'][0].length; i++) {
if (account_id == data['report_lines'][0][i]['partner_id'] ){ for (var i = 0; i < data['report_lines'][0].length; i++) {
$(event.currentTarget).next('tr').find('td').remove(); if (account_id == data['report_lines'][0][i]['partner_id']) {
$(event.currentTarget).next('tr').after( $(event.currentTarget).next('tr').find('td').remove();
QWeb.render('SubSectional', { $(event.currentTarget).next('tr').after(
account_data: data['report_lines'][0][i]['child_lines'], QWeb.render('SubSectional', {
id : data['report_lines'][0][i]['partner_id'] account_data: data['report_lines'][0][i]['child_lines'],
})) id: data['report_lines'][0][i]['partner_id']
$(event.currentTarget).next('tr').find('td ul li:first a').css({ }))
'background-color': '#00ede8', $(event.currentTarget).next('tr').find('td ul li:first a').css({
'font-weight': 'bold', 'background-color': '#00ede8',
}); 'font-weight': 'bold',
} });
} }
}
});
} });
}, }
},
view_acc_move: function(event) {
event.preventDefault(); view_acc_move: function(event) {
var self = this; event.preventDefault();
var context = {}; var self = this;
var show_acc_move = function(res_model, res_id, view_id) { var context = {};
var action = { var show_acc_move = function(res_model, res_id, view_id) {
type: 'ir.actions.act_window', var action = {
view_type: 'form', type: 'ir.actions.act_window',
view_mode: 'form', view_type: 'form',
res_model: res_model, view_mode: 'form',
views: [ res_model: res_model,
[view_id || false, 'form'] views: [
], [view_id || false, 'form']
res_id: res_id, ],
target: 'current', res_id: res_id,
context: context, target: 'current',
}; context: context,
return self.do_action(action); };
}; return self.do_action(action);
rpc.query({ };
model: 'account.move', rpc.query({
method: 'search_read', model: 'account.move',
domain: [ method: 'search_read',
['id', '=', $(event.currentTarget).data('move-id')] domain: [
], ['id', '=', $(event.currentTarget).data('move-id')]
fields: ['id'], ],
limit: 1, fields: ['id'],
}) limit: 1,
.then(function(record) { })
if (record.length > 0) { .then(function(record) {
show_acc_move('account.move', record[0].id); if (record.length > 0) {
} else { show_acc_move('account.move', record[0].id);
show_acc_move('account.move', $(event.currentTarget).data('move-id')); } else {
} show_acc_move('account.move', $(event.currentTarget).data('move-id'));
}); }
}, });
},
apply_filter: function(event) {
event.preventDefault(); apply_filter: function(event) {
var self = this; event.preventDefault();
self.initial_render = false; var self = this;
self.initial_render = false;
var filter_data_selected = {}; var filter_data_selected = {};
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) {
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) { filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); }
} var partner_ids = [];
var partner_text = [];
var span_res = document.getElementById("partner_res")
var partner_list = $(".partners").select2('data')
for (var i = 0; i < partner_list.length; i++) {
if (partner_list[i].element[0].selected === true) {
var partner_ids = []; partner_ids.push(parseInt(partner_list[i].id))
var partner_text = []; if (partner_text.includes(partner_list[i].text) === false) {
var span_res = document.getElementById("partner_res") partner_text.push(partner_list[i].text)
var partner_list = $(".partners").select2('data') }
for (var i = 0; i < partner_list.length; i++) { span_res.value = partner_text
if(partner_list[i].element[0].selected === true) span_res.innerHTML = span_res.value;
{partner_ids.push(parseInt(partner_list[i].id)) }
if(partner_text.includes(partner_list[i].text) === false) }
{partner_text.push(partner_list[i].text) if (partner_list.length == 0) {
} span_res.value = ""
span_res.value = partner_text span_res.innerHTML = "";
span_res.innerHTML=span_res.value; }
} filter_data_selected.partner_ids = partner_ids
}
if (partner_list.length == 0){ var partner_category_ids = [];
span_res.value = "" var partner_category_text = [];
span_res.innerHTML=""; var span_res = document.getElementById("category_res")
} var category_list = $(".category").select2('data')
filter_data_selected.partner_ids = partner_ids
for (var i = 0; i < category_list.length; i++) {
var partner_category_ids = []; if (category_list[i].element[0].selected === true) {
var partner_category_text = []; partner_category_ids.push(parseInt(category_list[i].id))
var span_res = document.getElementById("category_res") if (partner_category_text.includes(category_list[i].text) === false) {
var category_list = $(".category").select2('data') partner_category_text.push(category_list[i].text)
}
for (var i = 0; i < category_list.length; i++) { span_res.value = partner_category_text
if(category_list[i].element[0].selected === true) span_res.innerHTML = span_res.value;
{partner_category_ids.push(parseInt(category_list[i].id)) }
if(partner_category_text.includes(category_list[i].text) === false) }
{partner_category_text.push(category_list[i].text) if (category_list.length == 0) {
} span_res.value = ""
span_res.value = partner_category_text span_res.innerHTML = "";
span_res.innerHTML=span_res.value; }
} filter_data_selected.partner_category_ids = partner_category_ids
}
if (category_list.length == 0){
span_res.value = "" if ($(".target_move").length) {
span_res.innerHTML="";
} var post_res = document.getElementById("post_res")
filter_data_selected.partner_category_ids = partner_category_ids filter_data_selected.target_move = $(".target_move")[1].value
post_res.value = $(".target_move")[1].value
if ($(".target_move").length) { post_res.innerHTML = post_res.value;
if ($(".target_move")[1].value == "") {
var post_res = document.getElementById("post_res") post_res.innerHTML = "posted";
filter_data_selected.target_move = $(".target_move")[1].value
}
post_res.value = $(".target_move")[1].value }
post_res.innerHTML=post_res.value;
if ($(".target_move")[1].value == "") { if ($(".result_selection").length) {
post_res.innerHTML="posted"; var account_res = document.getElementById("account_res")
filter_data_selected.result_selection = $(".result_selection")[1].value
} account_res.value = $(".result_selection")[1].value
} account_res.innerHTML = account_res.value;
if ($(".result_selection")[1].value == "") {
if ($(".result_selection").length) { account_res.innerHTML = "customer";
var account_res = document.getElementById("account_res")
filter_data_selected.result_selection = $(".result_selection")[1].value }
account_res.value = $(".result_selection")[1].value }
account_res.innerHTML=account_res.value;
if ($(".result_selection")[1].value == "") {
account_res.innerHTML="customer"; rpc.query({
model: 'account.partner.ageing',
} method: 'write',
} args: [
self.wizard_id, filter_data_selected
],
rpc.query({ }).then(function(res) {
model: 'account.partner.ageing', self.initial_render = false;
method: 'write', self.load_data(self.initial_render);
args: [ });
self.wizard_id, filter_data_selected },
],
}).then(function(res) { });
self.initial_render = false; core.action_registry.add("p_a", PartnerAgeing);
self.load_data(self.initial_render); return PartnerAgeing;
});
},
});
core.action_registry.add("p_a", PartnerAgeing);
return PartnerAgeing;
}); });

775
dynamic_accounts_report/static/src/js/cash_flow.js

@ -1,386 +1,391 @@
odoo.define('dynamic_cash_flow_statements.cash_flow', function (require) { odoo.define('dynamic_cash_flow_statements.cash_flow', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var framework = require('web.framework'); var framework = require('web.framework');
var datepicker = require('web.datepicker'); var datepicker = require('web.datepicker');
var time = require('web.time'); var time = require('web.time');
window.click_num = 0; window.click_num = 0;
var CashFlow = AbstractAction.extend({ var CashFlow = AbstractAction.extend({
template: 'CFTemp', template: 'CFTemp',
events: { events: {
'click .parent-line': 'journal_line_click', 'click .parent-line': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click #apply_filter': 'apply_filter', 'click #apply_filter': 'apply_filter',
'click #pdf': 'print_pdf', 'click #pdf': 'print_pdf',
'click #xlsx': 'print_xlsx', 'click #xlsx': 'print_xlsx',
'click .cf-line': 'get_move_lines', 'click .cf-line': 'get_move_lines',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
}, },
init: function(parent, action) { init: function(parent, action) {
this._super(parent, action); this._super(parent, action);
this.currency=action.currency; this.currency = action.currency;
this.report_lines = action.report_lines; this.report_lines = action.report_lines;
this.wizard_id = action.context.wizard | null; this.wizard_id = action.context.wizard | null;
}, },
start: function() { start: function() {
var self = this; var self = this;
self.initial_render = true; self.initial_render = true;
rpc.query({ rpc.query({
model: 'account.cash.flow', model: 'account.cash.flow',
method: 'create', method: 'create',
args: [{ args: [{
}] }]
}).then(function(t_res) { }).then(function(t_res) {
self.wizard_id = t_res; self.wizard_id = t_res;
self.load_data(self.initial_render); self.load_data(self.initial_render);
}) })
}, },
_onCalendarIconClick: function (ev) { _onCalendarIconClick: function(ev) {
var $calendarInputGroup = $(ev.currentTarget); var $calendarInputGroup = $(ev.currentTarget);
var calendarOptions = { var calendarOptions = {
minDate: moment({ y: 1000 }), minDate: moment({
maxDate: moment().add(200, 'y'), y: 1000
calendarWeeks: true, }),
defaultDate: moment().format(), maxDate: moment().add(200, 'y'),
sideBySide: true, calendarWeeks: true,
buttons: { defaultDate: moment().format(),
showClear: true, sideBySide: true,
showClose: true, buttons: {
showToday: true, showClear: true,
}, showClose: true,
showToday: true,
icons : { },
date: 'fa fa-calendar',
icons: {
}, date: 'fa fa-calendar',
locale : moment.locale(),
format : time.getLangDateFormat(), },
widgetParent: 'body', locale: moment.locale(),
allowInputToggle: true, format: time.getLangDateFormat(),
}; widgetParent: 'body',
allowInputToggle: true,
$calendarInputGroup.datetimepicker(calendarOptions); };
},
$calendarInputGroup.datetimepicker(calendarOptions);
get_move_lines: function(event) { },
event.preventDefault();
var self = this; get_move_lines: function(event) {
var account_id = $(event.currentTarget).data('account-id'); event.preventDefault();
var offset = 0; var self = this;
var td = $(event.currentTarget).next('tr').find('td'); var account_id = $(event.currentTarget).data('account-id');
if (td.length == 1) { var offset = 0;
self._rpc({ var td = $(event.currentTarget).next('tr').find('td');
model: 'account.cash.flow', if (td.length == 1) {
method: 'view_report', self._rpc({
args: [ model: 'account.cash.flow',
[self.wizard_id] method: 'view_report',
], args: [
}).then(function(datas) { [self.wizard_id]
_.each(datas['journal_res'], function(journal_lines) { ],
_.each(journal_lines['journal_lines'], function(rep_lines) { }).then(function(datas) {
rep_lines.total_debit = self.format_currency(datas['currency'],rep_lines.total_debit); _.each(datas['journal_res'], function(journal_lines) {
rep_lines.total_credit = self.format_currency(datas['currency'],rep_lines.total_credit); _.each(journal_lines['journal_lines'], function(rep_lines) {
rep_lines.balance = self.format_currency(datas['currency'],rep_lines.balance); rep_lines.total_debit = self.format_currency(datas['currency'], rep_lines.total_debit);
rep_lines.total_credit = self.format_currency(datas['currency'], rep_lines.total_credit);
rep_lines.balance = self.format_currency(datas['currency'], rep_lines.balance);
});
}); });
_.each(datas['account_res'], function(journal_lines) {
_.each(journal_lines['journal_lines'], function(rep_lines) { });
rep_lines.total_debit = self.format_currency(datas['currency'],rep_lines.total_debit); _.each(datas['account_res'], function(journal_lines) {
rep_lines.total_credit = self.format_currency(datas['currency'],rep_lines.total_credit); _.each(journal_lines['journal_lines'], function(rep_lines) {
rep_lines.total_balance = self.format_currency(datas['currency'],rep_lines.total_balance); rep_lines.total_debit = self.format_currency(datas['currency'], rep_lines.total_debit);
rep_lines.total_credit = self.format_currency(datas['currency'], rep_lines.total_credit);
rep_lines.total_balance = self.format_currency(datas['currency'], rep_lines.total_balance);
});
_.each(journal_lines['move_lines'], function(move_lines) {
move_lines.total_debit = self.format_currency(datas['currency'],move_lines.total_debit); });
move_lines.total_credit = self.format_currency(datas['currency'],move_lines.total_credit); _.each(journal_lines['move_lines'], function(move_lines) {
move_lines.balance = self.format_currency(datas['currency'],move_lines.balance); move_lines.total_debit = self.format_currency(datas['currency'], move_lines.total_debit);
move_lines.total_credit = self.format_currency(datas['currency'], move_lines.total_credit);
move_lines.balance = self.format_currency(datas['currency'], move_lines.balance);
});
});
});
});
if(datas['levels']== 'detailed'){
$(event.currentTarget).next('tr').find('td ul').after(
QWeb.render('SubSectionCF', { if (datas['levels'] == 'detailed') {
count: 3, $(event.currentTarget).next('tr').find('td ul').after(
offset: 0, QWeb.render('SubSectionCF', {
account_data: datas['journal_res'], count: 3,
level:datas['levels'], offset: 0,
currency : datas['currency'], account_data: datas['journal_res'],
line_id:parseInt(event.currentTarget.attributes[3].value), level: datas['levels'],
})) currency: datas['currency'],
}else if(datas['levels']== 'very' || datas['levels']== false){ line_id: parseInt(event.currentTarget.attributes[3].value),
$(event.currentTarget).next('tr').find('td ul').after( }))
QWeb.render('ChildSubSectionCF', { } else if (datas['levels'] == 'very' || datas['levels'] == false) {
count: 3, $(event.currentTarget).next('tr').find('td ul').after(
offset: 0, QWeb.render('ChildSubSectionCF', {
account_data: datas['account_res'], count: 3,
level:datas['levels'], offset: 0,
currency : datas['currency'], account_data: datas['account_res'],
line_id:parseInt(event.currentTarget.attributes[3].value), level: datas['levels'],
})) currency: datas['currency'],
} line_id: parseInt(event.currentTarget.attributes[3].value),
}))
$(event.currentTarget).next('tr').find('td ul li:first a').css({ }
'background-color': '#00ede8',
'font-weight': 'bold', $(event.currentTarget).next('tr').find('td ul li:first a').css({
}); 'background-color': '#00ede8',
}) 'font-weight': 'bold',
} });
}, })
}
},
load_data: function (initial_render = true) {
var self = this;
self.$(".categ").empty(); load_data: function(initial_render = true) {
try{ var self = this;
var self = this; self.$(".categ").empty();
self._rpc({ try {
model: 'account.cash.flow', var self = this;
method: 'view_report', self._rpc({
args: [[this.wizard_id]], model: 'account.cash.flow',
}).then(function(datas) { method: 'view_report',
args: [
[this.wizard_id]
_.each(datas['fetched_data'], function(rep_lines) { ],
rep_lines.total_debit = self.format_currency(datas['currency'],rep_lines.total_debit); }).then(function(datas) {
rep_lines.total_credit = self.format_currency(datas['currency'],rep_lines.total_credit);
rep_lines.total_balance = self.format_currency(datas['currency'],rep_lines.total_balance);
_.each(datas['fetched_data'], function(rep_lines) {
rep_lines.total_debit = self.format_currency(datas['currency'], rep_lines.total_debit);
rep_lines.total_credit = self.format_currency(datas['currency'], rep_lines.total_credit);
rep_lines.total_balance = self.format_currency(datas['currency'], rep_lines.total_balance);
});
if (initial_render) {
self.$('.filter_view_tb').html(QWeb.render('CashFilterView', {
filter_data: datas['filters'],
})); });
self.$el.find('.journals').select2({ if (initial_render) {
placeholder: 'Select Journals...', self.$('.filter_view_tb').html(QWeb.render('CashFilterView', {
}); filter_data: datas['filters'],
self.$el.find('.target_move').select2({ }));
placeholder: 'Target Move...', self.$el.find('.journals').select2({
}); placeholder: 'Select Journals...',
self.$el.find('.levels').select2({ });
placeholder: 'Levels...', self.$el.find('.target_move').select2({
}); placeholder: 'Target Move...',
} });
var child=[]; self.$el.find('.levels').select2({
placeholder: 'Levels...',
self.$('.table_view_tb').html(QWeb.render('CashTable', { });
}
account_data: datas['fetched_data'], var child = [];
level:datas['levels'],
currency : datas['currency'], self.$('.table_view_tb').html(QWeb.render('CashTable', {
}));
account_data: datas['fetched_data'],
}); level: datas['levels'],
currency: datas['currency'],
} }));
catch (el) {
window.location.href });
}
}, } catch (el) {
window.location.href
format_currency: function(currency, amount) { }
if (typeof(amount) != 'number') { },
amount = parseFloat(amount);
} format_currency: function(currency, amount) {
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ if (typeof(amount) != 'number') {
minimumFractionDigits: 2 amount = parseFloat(amount);
}) }
return formatted_value var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
}, minimumFractionDigits: 2
})
show_gl: function(e) { return formatted_value
var self = this; },
var account_id = $(e.target).attr('data-account-id');
var options = { show_gl: function(e) {
account_ids: [account_id], var self = this;
} var account_id = $(e.target).attr('data-account-id');
var options = {
var action = { account_ids: [account_id],
type: 'ir.actions.client', }
name: 'GL View',
tag: 'g_l', var action = {
target: 'new', type: 'ir.actions.client',
name: 'GL View',
domain: [['account_ids','=', account_id]], tag: 'g_l',
target: 'new',
} domain: [
return this.do_action(action); ['account_ids', '=', account_id]
],
},
print_pdf: function(e) {
e.preventDefault(); }
var self = this; return this.do_action(action);
self._rpc({
model: 'account.cash.flow', },
method: 'view_report', print_pdf: function(e) {
args: [ e.preventDefault();
[self.wizard_id] var self = this;
], self._rpc({
}).then(function(data) { model: 'account.cash.flow',
var action = { method: 'view_report',
'type': 'ir.actions.report', args: [
'report_type': 'qweb-pdf', [self.wizard_id]
'report_name': 'dynamic_accounts_report.cash_flow', ],
'report_file': 'dynamic_accounts_report.cash_flow', }).then(function(data) {
'data': { var action = {
'report_data': data 'type': 'ir.actions.report',
}, 'report_type': 'qweb-pdf',
'context': { 'report_name': 'dynamic_accounts_report.cash_flow',
'active_model': 'account.cash.flow', 'report_file': 'dynamic_accounts_report.cash_flow',
'landscape': 1, 'data': {
'trial_pdf_report': true 'report_data': data
}, },
'display_name': 'Cash Flow Statements', 'context': {
}; 'active_model': 'account.cash.flow',
return self.do_action(action); 'landscape': 1,
}); 'trial_pdf_report': true
}, },
'display_name': 'Cash Flow Statements',
};
return self.do_action(action);
print_xlsx: function() { });
var self = this; },
self._rpc({
model: 'account.cash.flow',
method: 'view_report',
args: [ print_xlsx: function() {
[self.wizard_id] var self = this;
], self._rpc({
}).then(function(data) { model: 'account.cash.flow',
var action = { method: 'view_report',
// 'type': 'ir_actions_dynamic_xlsx_download', args: [
'data': { [self.wizard_id]
'model': 'account.cash.flow', ],
'options': JSON.stringify(data['filters']), }).then(function(data) {
'output_format': 'xlsx', var action = {
'report_data': JSON.stringify(data['report_lines']), // 'type': 'ir_actions_dynamic_xlsx_download',
'report_name': 'Cash Flow Statements', 'data': {
'dfr_data': JSON.stringify(data), 'model': 'account.cash.flow',
}, 'options': JSON.stringify(data['filters']),
}; 'output_format': 'xlsx',
// return self.do_action(action); 'report_data': JSON.stringify(data['report_lines']),
self.downloadXlsx(action) 'report_name': 'Cash Flow Statements',
}); 'dfr_data': JSON.stringify(data),
}, },
downloadXlsx: function (action){ };
framework.blockUI(); // return self.do_action(action);
session.get_file({ self.downloadXlsx(action)
url: '/dynamic_xlsx_reports', });
data: action.data, },
complete: framework.unblockUI, downloadXlsx: function(action) {
error: (error) => this.call('crash_manager', 'rpc_error', error), framework.blockUI();
}); session.get_file({
}, url: '/dynamic_xlsx_reports',
data: action.data,
journal_line_click: function (el){ complete: framework.unblockUI,
click_num++; error: (error) => this.call('crash_manager', 'rpc_error', error),
var self = this; });
var line = $(el.target).parent().data('id'); },
return self.do_action({
type: 'ir.actions.act_window', journal_line_click: function(el) {
view_type: 'form', click_num++;
view_mode: 'form', var self = this;
res_model: 'account.move', var line = $(el.target).parent().data('id');
views: [ return self.do_action({
[false, 'form'] type: 'ir.actions.act_window',
], view_type: 'form',
res_id: line, view_mode: 'form',
target: 'current', res_model: 'account.move',
}); views: [
[false, 'form']
}, ],
res_id: line,
target: 'current',
apply_filter: function(event) { });
event.preventDefault(); },
var self = this;
self.initial_render = false;
apply_filter: function(event) {
var filter_data_selected = {};
event.preventDefault();
var self = this;
self.initial_render = false;
if ($(".levels").length){
var level_res = document.getElementById("level_res") var filter_data_selected = {};
filter_data_selected.levels = $(".levels")[1].value
level_res.value = $(".levels")[1].value
level_res.innerHTML=level_res.value;
if ($(".levels").value==""){ if ($(".levels").length) {
type_res.innerHTML="summary"; var level_res = document.getElementById("level_res")
filter_data_selected.type = "Summary" filter_data_selected.levels = $(".levels")[1].value
} level_res.value = $(".levels")[1].value
} level_res.innerHTML = level_res.value;
if ($(".levels").value == "") {
// if ($("#date_from").val()) { type_res.innerHTML = "summary";
// var dateString = $("#date_from").val(); filter_data_selected.type = "Summary"
// filter_data_selected.date_from = dateString; }
// } }
// if ($("#date_to").val()) {
// var dateString = $("#date_to").val(); // if ($("#date_from").val()) {
// filter_data_selected.date_to = dateString; // var dateString = $("#date_from").val();
// } // filter_data_selected.date_from = dateString;
// }
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) { // if ($("#date_to").val()) {
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); // var dateString = $("#date_to").val();
} // filter_data_selected.date_to = dateString;
// }
if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) {
} filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
}
if ($(".target_move").length) {
var post_res = document.getElementById("post_res") if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
filter_data_selected.target_move = $(".target_move")[1].value filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
post_res.value = $(".target_move")[1].value }
post_res.innerHTML=post_res.value;
if ($(".target_move")[1].value == "") { if ($(".target_move").length) {
post_res.innerHTML="posted"; var post_res = document.getElementById("post_res")
filter_data_selected.target_move = $(".target_move")[1].value
} post_res.value = $(".target_move")[1].value
} post_res.innerHTML = post_res.value;
rpc.query({ if ($(".target_move")[1].value == "") {
model: 'account.cash.flow', post_res.innerHTML = "posted";
method: 'write',
args: [ }
self.wizard_id, filter_data_selected }
], rpc.query({
}).then(function(res) { model: 'account.cash.flow',
self.initial_render = false; method: 'write',
self.load_data(self.initial_render); args: [
}); self.wizard_id, filter_data_selected
}, ],
}).then(function(res) {
}); self.initial_render = false;
core.action_registry.add("c_f", CashFlow); self.load_data(self.initial_render);
return CashFlow; });
},
});
core.action_registry.add("c_f", CashFlow);
return CashFlow;
}); });

876
dynamic_accounts_report/static/src/js/daybook.js

@ -1,439 +1,439 @@
odoo.define('dynamic_partner_daybook.daybook', function (require) { odoo.define('dynamic_partner_daybook.daybook', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var datepicker = require('web.datepicker'); var datepicker = require('web.datepicker');
var time = require('web.time'); var time = require('web.time');
var framework = require('web.framework'); var framework = require('web.framework');
window.click_num = 0; window.click_num = 0;
var DayBook = AbstractAction.extend({ var DayBook = AbstractAction.extend({
template: 'DaybookTemp', template: 'DaybookTemp',
events: { events: {
'click .parent-line': 'journal_line_click', 'click .parent-line': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click #apply_filter': 'apply_filter', 'click #apply_filter': 'apply_filter',
'click #pdf': 'print_pdf', 'click #pdf': 'print_pdf',
'click #xlsx': 'print_xlsx', 'click #xlsx': 'print_xlsx',
'click .db-line': 'show_drop_down', 'click .db-line': 'show_drop_down',
'click .view-account-move': 'view_acc_move', 'click .view-account-move': 'view_acc_move',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
}, },
init: function(parent, action) { init: function(parent, action) {
this._super(parent, action); this._super(parent, action);
this.currency=action.currency; this.currency = action.currency;
this.report_lines = action.report_lines; this.report_lines = action.report_lines;
this.wizard_id = action.context.wizard | null; this.wizard_id = action.context.wizard | null;
}, },
start: function() { start: function() {
var self = this; var self = this;
self.initial_render = true; self.initial_render = true;
rpc.query({ rpc.query({
model: 'account.day.book', model: 'account.day.book',
method: 'create', method: 'create',
args: [{ args: [{
}] }]
}).then(function(t_res) { }).then(function(t_res) {
self.wizard_id = t_res; self.wizard_id = t_res;
self.load_data(self.initial_render); self.load_data(self.initial_render);
}) })
}, },
_onCalendarIconClick: function (ev) { _onCalendarIconClick: function(ev) {
var $calendarInputGroup = $(ev.currentTarget); var $calendarInputGroup = $(ev.currentTarget);
var calendarOptions = { var calendarOptions = {
minDate: moment({ y: 1000 }), minDate: moment({
maxDate: moment().add(200, 'y'), y: 1000
calendarWeeks: true, }),
defaultDate: moment().format(), maxDate: moment().add(200, 'y'),
sideBySide: true, calendarWeeks: true,
buttons: { defaultDate: moment().format(),
showClear: true, sideBySide: true,
showClose: true, buttons: {
showToday: true, showClear: true,
}, showClose: true,
showToday: true,
icons : { },
date: 'fa fa-calendar',
icons: {
}, date: 'fa fa-calendar',
locale : moment.locale(),
format : time.getLangDateFormat(), },
widgetParent: 'body', locale: moment.locale(),
allowInputToggle: true, format: time.getLangDateFormat(),
}; widgetParent: 'body',
allowInputToggle: true,
$calendarInputGroup.datetimepicker(calendarOptions); };
},
$calendarInputGroup.datetimepicker(calendarOptions);
},
load_data: function (initial_render = true) {
var self = this;
self.$(".categ").empty(); load_data: function(initial_render = true) {
try{ var self = this;
var self = this; self.$(".categ").empty();
self._rpc({ try {
model: 'account.day.book', var self = this;
method: 'view_report', self._rpc({
args: [[this.wizard_id]], model: 'account.day.book',
}).then(function(datas) { method: 'view_report',
_.each(datas['report_lines'], function(rep_lines) { args: [
rep_lines.debit = self.format_currency(datas['currency'],rep_lines.debit); [this.wizard_id]
rep_lines.credit = self.format_currency(datas['currency'],rep_lines.credit); ],
rep_lines.balance = self.format_currency(datas['currency'],rep_lines.balance); }).then(function(datas) {
_.each(datas['report_lines'], function(rep_lines) {
}); rep_lines.debit = self.format_currency(datas['currency'], rep_lines.debit);
rep_lines.credit = self.format_currency(datas['currency'], rep_lines.credit);
if (initial_render) { rep_lines.balance = self.format_currency(datas['currency'], rep_lines.balance);
self.$('.filter_view_db').html(QWeb.render('DayFilterView', { });
filter_data: datas['filters'],
})); if (initial_render) {
self.$el.find('.journals').select2({
placeholder: ' Journals...', self.$('.filter_view_db').html(QWeb.render('DayFilterView', {
}); filter_data: datas['filters'],
self.$el.find('.account-partner').select2({ }));
placeholder: ' Accounts...', self.$el.find('.journals').select2({
}); placeholder: ' Journals...',
self.$el.find('.target_move').select2({ });
placeholder: 'Target Move...', self.$el.find('.account-partner').select2({
}); placeholder: ' Accounts...',
});
self.$el.find('.target_move').select2({
} placeholder: 'Target Move...',
var child=[]; });
self.$('.table_view_db').html(QWeb.render('Daytable', {
}
report_lines : datas['report_lines'], var child = [];
filter : datas['filters'],
currency : datas['currency'], self.$('.table_view_db').html(QWeb.render('Daytable', {
}));
report_lines: datas['report_lines'],
}); filter: datas['filters'],
currency: datas['currency'],
} }));
catch (el) {
window.location.href });
}
}, } catch (el) {
window.location.href
}
format_currency: function(currency, amount) { },
if (typeof(amount) != 'number') {
amount = parseFloat(amount);
} format_currency: function(currency, amount) {
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ if (typeof(amount) != 'number') {
minimumFractionDigits: 2 amount = parseFloat(amount);
}) }
return formatted_value var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
}, minimumFractionDigits: 2
})
print_pdf: function(e) { return formatted_value
e.preventDefault(); },
var self = this; print_pdf: function(e) {
self._rpc({ e.preventDefault();
model: 'account.day.book',
method: 'view_report', var self = this;
args: [ self._rpc({
[self.wizard_id] model: 'account.day.book',
], method: 'view_report',
}).then(function(data) { args: [
[self.wizard_id]
var action = { ],
'type': 'ir.actions.report', }).then(function(data) {
'report_type': 'qweb-pdf',
'report_name': 'dynamic_accounts_report.day_book', var action = {
'report_file': 'dynamic_accounts_report.day_book', 'type': 'ir.actions.report',
'data': { 'report_type': 'qweb-pdf',
'report_data': data 'report_name': 'dynamic_accounts_report.day_book',
}, 'report_file': 'dynamic_accounts_report.day_book',
'context': { 'data': {
'active_model': 'account.day.book', 'report_data': data
'landscape': 1, },
'daybook_pdf_report': true 'context': {
}, 'active_model': 'account.day.book',
'display_name': 'Day Book', 'landscape': 1,
}; 'daybook_pdf_report': true
},
return self.do_action(action); 'display_name': 'Day Book',
}); };
},
return self.do_action(action);
print_xlsx: function() { });
var self = this; },
self._rpc({
model: 'account.day.book', print_xlsx: function() {
method: 'view_report', var self = this;
args: [ self._rpc({
[self.wizard_id] model: 'account.day.book',
], method: 'view_report',
}).then(function(data) { args: [
var action = { [self.wizard_id]
// 'type': 'ir_actions_dynamic_xlsx_download', ],
'data': { }).then(function(data) {
'model': 'account.day.book', var action = {
'options': JSON.stringify(data['filters']), // 'type': 'ir_actions_dynamic_xlsx_download',
'output_format': 'xlsx', 'data': {
'report_data': JSON.stringify(data['report_lines']), 'model': 'account.day.book',
'report_name': 'Day Book', 'options': JSON.stringify(data['filters']),
'dfr_data': JSON.stringify(data), 'output_format': 'xlsx',
}, 'report_data': JSON.stringify(data['report_lines']),
}; 'report_name': 'Day Book',
// return self.do_action(action); 'dfr_data': JSON.stringify(data),
self.downloadXlsx(action) },
}); };
}, // return self.do_action(action);
downloadXlsx: function (action){ self.downloadXlsx(action)
framework.blockUI(); });
session.get_file({ },
url: '/dynamic_xlsx_reports', downloadXlsx: function(action) {
data: action.data, framework.blockUI();
complete: framework.unblockUI, session.get_file({
error: (error) => this.call('crash_manager', 'rpc_error', error), url: '/dynamic_xlsx_reports',
}); data: action.data,
}, complete: framework.unblockUI,
error: (error) => this.call('crash_manager', 'rpc_error', error),
create_lines_with_style: function(rec, attr, datas) { });
},
var temp_str = "";
var style_name = "border-bottom: 1px solid #e6e6e6;"; create_lines_with_style: function(rec, attr, datas) {
var attr_name = attr + " style="+style_name;
temp_str += "<td class='child_col1' "+attr_name+" >"+rec['code'] +rec['name'] +"</td>"; var temp_str = "";
if(datas.currency[1]=='after'){ var style_name = "border-bottom: 1px solid #e6e6e6;";
temp_str += "<td class='child_col2' "+attr_name+" >"+rec['debit'].toFixed(2)+datas.currency[0]+"</td>"; var attr_name = attr + " style=" + style_name;
temp_str += "<td class='child_col3' "+attr_name+" >"+rec['credit'].toFixed(2) +datas.currency[0]+ "</td>"; temp_str += "<td class='child_col1' " + attr_name + " >" + rec['code'] + rec['name'] + "</td>";
} if (datas.currency[1] == 'after') {
else{ temp_str += "<td class='child_col2' " + attr_name + " >" + rec['debit'].toFixed(2) + datas.currency[0] + "</td>";
temp_str += "<td class='child_col2' "+attr_name+" >"+datas.currency[0]+rec['debit'].toFixed(2) + "</td>"; temp_str += "<td class='child_col3' " + attr_name + " >" + rec['credit'].toFixed(2) + datas.currency[0] + "</td>";
temp_str += "<td class='child_col3' "+attr_name+">"+datas.currency[0]+rec['credit'].toFixed(2) + "</td>"; } else {
} temp_str += "<td class='child_col2' " + attr_name + " >" + datas.currency[0] + rec['debit'].toFixed(2) + "</td>";
return temp_str; temp_str += "<td class='child_col3' " + attr_name + ">" + datas.currency[0] + rec['credit'].toFixed(2) + "</td>";
}, }
return temp_str;
},
journal_line_click: function (el){
click_num++;
var self = this; journal_line_click: function(el) {
var line = $(el.target).parent().data('id'); click_num++;
return self.do_action({ var self = this;
type: 'ir.actions.act_window', var line = $(el.target).parent().data('id');
view_type: 'form', return self.do_action({
view_mode: 'form', type: 'ir.actions.act_window',
res_model: 'account.move', view_type: 'form',
views: [ view_mode: 'form',
[false, 'form'] res_model: 'account.move',
], views: [
res_id: line, [false, 'form']
target: 'current', ],
}); res_id: line,
target: 'current',
}, });
show_drop_down: function(event) { },
event.preventDefault();
var self = this; show_drop_down: function(event) {
var account_id = $(event.currentTarget).data('account-id'); event.preventDefault();
var offset = 0; var self = this;
var td = $(event.currentTarget).next('tr').find('td'); var account_id = $(event.currentTarget).data('account-id');
if (td.length == 1) { var offset = 0;
var td = $(event.currentTarget).next('tr').find('td');
self._rpc({ if (td.length == 1) {
model: 'account.day.book',
method: 'view_report', self._rpc({
args: [ model: 'account.day.book',
[self.wizard_id] method: 'view_report',
], args: [
}).then(function(data) { [self.wizard_id]
_.each(data['report_lines'], function(rep_lines) { ],
_.each(rep_lines['child_lines'], function(move_line) { }).then(function(data) {
_.each(data['report_lines'], function(rep_lines) {
move_line.debit = self.format_currency(data['currency'],move_line.debit); _.each(rep_lines['child_lines'], function(move_line) {
move_line.credit = self.format_currency(data['currency'],move_line.credit);
move_line.balance = self.format_currency(data['currency'],move_line.balance); move_line.debit = self.format_currency(data['currency'], move_line.debit);
move_line.credit = self.format_currency(data['currency'], move_line.credit);
move_line.balance = self.format_currency(data['currency'], move_line.balance);
});
});
for (var i = 0; i < data['report_lines'].length; i++) { });
});
if (account_id == data['report_lines'][i]['id'] ){ for (var i = 0; i < data['report_lines'].length; i++) {
$(event.currentTarget).next('tr').find('td').remove();
$(event.currentTarget).next('tr').after( if (account_id == data['report_lines'][i]['id']) {
QWeb.render('SubSectiondb', { $(event.currentTarget).next('tr').find('td').remove();
$(event.currentTarget).next('tr').after(
account_data: data['report_lines'][i]['child_lines'], QWeb.render('SubSectiondb', {
currency_symbol : data.currency[0],
id : data['report_lines'][i]['id'], account_data: data['report_lines'][i]['child_lines'],
currency_position : data.currency[1], currency_symbol: data.currency[0],
})) id: data['report_lines'][i]['id'],
currency_position: data.currency[1],
$(event.currentTarget).next('tr').find('td ul li:first a').css({ }))
'background-color': '#00ede8',
'font-weight': 'bold', $(event.currentTarget).next('tr').find('td ul li:first a').css({
}); 'background-color': '#00ede8',
} 'font-weight': 'bold',
} });
}
}); }
}
}, });
}
view_acc_move: function(event) { },
event.preventDefault(); view_acc_move: function(event) {
var self = this;
var context = {}; event.preventDefault();
var show_acc_move = function(res_model, res_id, view_id) { var self = this;
var action = { var context = {};
type: 'ir.actions.act_window', var show_acc_move = function(res_model, res_id, view_id) {
view_type: 'form', var action = {
view_mode: 'form', type: 'ir.actions.act_window',
res_model: res_model, view_type: 'form',
views: [ view_mode: 'form',
[view_id || false, 'form'] res_model: res_model,
], views: [
res_id: res_id, [view_id || false, 'form']
target: 'current', ],
context: context, res_id: res_id,
}; target: 'current',
return self.do_action(action); context: context,
}; };
rpc.query({ return self.do_action(action);
model: 'account.move', };
method: 'search_read', rpc.query({
domain: [ model: 'account.move',
['id', '=', $(event.currentTarget).data('move-id')] method: 'search_read',
], domain: [
fields: ['id'], ['id', '=', $(event.currentTarget).data('move-id')]
limit: 1, ],
}) fields: ['id'],
.then(function(record) { limit: 1,
})
if (record.length > 0) { .then(function(record) {
show_acc_move('account.move', record[0].id);
} else { if (record.length > 0) {
show_acc_move('account.move', $(event.currentTarget).data('move-id')); show_acc_move('account.move', record[0].id);
} } else {
}); show_acc_move('account.move', $(event.currentTarget).data('move-id'));
}, }
});
},
apply_filter: function(event) {
event.preventDefault(); apply_filter: function(event) {
var self = this; event.preventDefault();
self.initial_render = false; var self = this;
self.initial_render = false;
var filter_data_selected = {};
var filter_data_selected = {};
var account_ids = [];
var account_text = []; var account_ids = [];
var account_text = [];
var account_res = document.getElementById("acc_res")
var account_res = document.getElementById("acc_res")
var account_list = $(".account-partner").select2('data') var account_list = $(".account-partner").select2('data')
for (var i = 0; i < account_list.length; i++) { for (var i = 0; i < account_list.length; i++) {
if(account_list[i].element[0].selected === true){ if (account_list[i].element[0].selected === true) {
account_ids.push(parseInt(account_list[i].id)) account_ids.push(parseInt(account_list[i].id))
if(account_text.includes(account_list[i].text) === false){ if (account_text.includes(account_list[i].text) === false) {
account_text.push(account_list[i].text) account_text.push(account_list[i].text)
} }
account_res.value = account_text account_res.value = account_text
account_res.innerHTML=account_res.value; account_res.innerHTML = account_res.value;
} }
} }
if (account_list.length == 0){ if (account_list.length == 0) {
account_res.value = "" account_res.value = ""
account_res.innerHTML=""; account_res.innerHTML = "";
} }
filter_data_selected.account_ids = account_ids filter_data_selected.account_ids = account_ids
var journal_ids = []; var journal_ids = [];
var journal_text = []; var journal_text = [];
var journal_res = document.getElementById("journal_res") var journal_res = document.getElementById("journal_res")
var journal_list = $(".journals").select2('data') var journal_list = $(".journals").select2('data')
for (var i = 0; i < journal_list.length; i++) { for (var i = 0; i < journal_list.length; i++) {
if(journal_list[i].element[0].selected === true){ if (journal_list[i].element[0].selected === true) {
journal_ids.push(parseInt(journal_list[i].id)) journal_ids.push(parseInt(journal_list[i].id))
if(journal_text.includes(journal_list[i].text) === false){ if (journal_text.includes(journal_list[i].text) === false) {
journal_text.push(journal_list[i].text) journal_text.push(journal_list[i].text)
} }
journal_res.value = journal_text journal_res.value = journal_text
journal_res.innerHTML=journal_res.value; journal_res.innerHTML = journal_res.value;
} }
} }
if (journal_list.length == 0){ if (journal_list.length == 0) {
journal_res.value = "" journal_res.value = ""
journal_res.innerHTML=""; journal_res.innerHTML = "";
} }
filter_data_selected.journal_ids = journal_ids filter_data_selected.journal_ids = journal_ids
// if ($("#date_from").val()) { // if ($("#date_from").val()) {
// var dateString = $("#date_from").val(); // var dateString = $("#date_from").val();
// //
// filter_data_selected.date_from = dateString; // filter_data_selected.date_from = dateString;
// } // }
// if ($("#date_to").val()) { // if ($("#date_to").val()) {
// var dateString = $("#date_to").val(); // var dateString = $("#date_to").val();
// filter_data_selected.date_to = dateString; // filter_data_selected.date_to = dateString;
// } // }
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) { if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) {
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
} }
if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) { if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
} }
if ($(".target_move").length) { if ($(".target_move").length) {
var post_res = document.getElementById("post_res") var post_res = document.getElementById("post_res")
filter_data_selected.target_move = $(".target_move")[1].value filter_data_selected.target_move = $(".target_move")[1].value
post_res.value = $(".target_move")[1].value post_res.value = $(".target_move")[1].value
post_res.innerHTML=post_res.value; post_res.innerHTML = post_res.value;
if ($(".target_move")[1].value == "") { if ($(".target_move")[1].value == "") {
post_res.innerHTML="posted"; post_res.innerHTML = "posted";
} }
} }
rpc.query({ rpc.query({
model: 'account.day.book', model: 'account.day.book',
method: 'write', method: 'write',
args: [ args: [
self.wizard_id, filter_data_selected self.wizard_id, filter_data_selected
], ],
}).then(function(res) { }).then(function(res) {
self.initial_render = false; self.initial_render = false;
self.load_data(self.initial_render); self.load_data(self.initial_render);
}); });
}, },
}); });
core.action_registry.add("d_b", DayBook); core.action_registry.add("d_b", DayBook);
return DayBook; return DayBook;
}); });

751
dynamic_accounts_report/static/src/js/financial_reports.js

@ -1,247 +1,246 @@
odoo.define('dynamic_accounts_report.financial_reports', function (require) { odoo.define('dynamic_accounts_report.financial_reports', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var framework = require('web.framework'); var framework = require('web.framework');
var datepicker = require('web.datepicker'); var datepicker = require('web.datepicker');
var time = require('web.time'); var time = require('web.time');
window.click_num = 0; window.click_num = 0;
var ProfitAndLoss = AbstractAction.extend({ var ProfitAndLoss = AbstractAction.extend({
template: 'dfr_template_new', template: 'dfr_template_new',
events: { events: {
'click .parent-line': 'journal_line_click', 'click .parent-line': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click #apply_filter': 'apply_filter', 'click #apply_filter': 'apply_filter',
'click #pdf': 'print_pdf', 'click #pdf': 'print_pdf',
'click #xlsx': 'print_xlsx', 'click #xlsx': 'print_xlsx',
'click .show-gl': 'show_gl', 'click .show-gl': 'show_gl',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
}, },
init: function(parent, action) { init: function(parent, action) {
this._super(parent, action); this._super(parent, action);
this.currency=action.currency; this.currency = action.currency;
this.report_lines = action.report_lines; this.report_lines = action.report_lines;
this.wizard_id = action.context.wizard | null; this.wizard_id = action.context.wizard | null;
}, },
start: function() { start: function() {
var self = this; var self = this;
self.initial_render = true; self.initial_render = true;
rpc.query({ rpc.query({
model: 'dynamic.balance.sheet.report', model: 'dynamic.balance.sheet.report',
method: 'create', method: 'create',
args: [{ args: [{}]
}] }).then(function(t_res) {
}).then(function(t_res) { self.wizard_id = t_res;
self.wizard_id = t_res; self.load_data(self.initial_render);
self.load_data(self.initial_render); })
}) },
},
_onCalendarIconClick: function(ev) {
_onCalendarIconClick: function (ev) { var $calendarInputGroup = $(ev.currentTarget);
var $calendarInputGroup = $(ev.currentTarget);
var calendarOptions = {
var calendarOptions = {
minDate: moment({
minDate: moment({ y: 1000 }), y: 1000
maxDate: moment().add(200, 'y'), }),
calendarWeeks: true, maxDate: moment().add(200, 'y'),
defaultDate: moment().format(), calendarWeeks: true,
sideBySide: true, defaultDate: moment().format(),
buttons: { sideBySide: true,
showClear: true, buttons: {
showClose: true, showClear: true,
showToday: true, showClose: true,
}, showToday: true,
},
icons : {
date: 'fa fa-calendar', icons: {
date: 'fa fa-calendar',
},
locale : moment.locale(), },
format : time.getLangDateFormat(), locale: moment.locale(),
widgetParent: 'body', format: time.getLangDateFormat(),
allowInputToggle: true, widgetParent: 'body',
}; allowInputToggle: true,
};
$calendarInputGroup.datetimepicker(calendarOptions);
}, $calendarInputGroup.datetimepicker(calendarOptions);
},
load_data: function (initial_render = true) {
var self = this; load_data: function(initial_render = true) {
var action_title = self._title; var self = this;
self.$(".categ").empty(); var action_title = self._title;
try{ self.$(".categ").empty();
var self = this; try {
self._rpc({ var self = this;
model: 'dynamic.balance.sheet.report', self._rpc({
method: 'view_report', model: 'dynamic.balance.sheet.report',
args: [[this.wizard_id], action_title, self.searchModel.config.context.lang], method: 'view_report',
}).then(function(datas) { args: [
if (initial_render) { [this.wizard_id], action_title, self.searchModel.config.context.lang
self.$('.filter_view_dfr').html(QWeb.render('DfrFilterView', { ],
filter_data: datas['filters'], }).then(function(datas) {
title : datas['name'], if (initial_render) {
})); self.$('.filter_view_dfr').html(QWeb.render('DfrFilterView', {
self.$el.find('.journals').select2({ filter_data: datas['filters'],
placeholder: ' Journals...', title: datas['name'],
}); }));
self.$el.find('.account-partner').select2({ self.$el.find('.journals').select2({
placeholder: ' Accounts...', placeholder: ' Journals...',
}); });
self.$el.find('.account-tag').select2({ self.$el.find('.account').select2({
placeholder: 'Account Tag...', placeholder: ' Accounts...',
}); });
self.$el.find('.analytics').select2({ self.$el.find('.account-tag').select2({
placeholder: 'Analytic Accounts...', placeholder: 'Account Tag...',
}); });
self.$el.find('.analytic-tag').select2({ self.$el.find('.analytics').select2({
placeholder: 'Analytic Tag...', placeholder: 'Analytic Accounts...',
}); });
self.$el.find('.target_move').select2({ self.$el.find('.analytic-tag').select2({
placeholder: 'Target Move...', placeholder: 'Analytic Tag...',
}); });
} self.$el.find('.target_move').select2({
var child=[]; placeholder: 'Target Move...',
console.log(datas, "datas") });
self.$('.table_view_dfr').html(QWeb.render('dfr_table', { }
var child = [];
report_lines : datas['report_lines'], self.$('.table_view_dfr').html(QWeb.render('dfr_table', {
filter : datas['filters'], report_lines: datas['report_lines'],
currency : datas['currency'], filter: datas['filters'],
credit_total : datas['credit_total'], currency: datas['currency'],
debit_total : datas['debit_total'], credit_total: datas['credit_total'],
debit_balance : datas['debit_balance'], debit_total: datas['debit_total'],
bs_lines : datas['bs_lines'], debit_balance: datas['debit_balance'],
lang: datas['lang'], bs_lines: datas['bs_lines'],
})); lang: datas['lang'],
}); }));
} });
catch (el) { } catch (el) {
window.location.href window.location.href
} }
}, },
format_currency: function(currency, amount) { format_currency: function(currency, amount) {
if (typeof(amount) != 'number') { if (typeof(amount) != 'number') {
amount = parseFloat(amount); amount = parseFloat(amount);
} }
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
minimumFractionDigits: 2 minimumFractionDigits: 2
}) })
return formatted_value return formatted_value
}, },
show_gl: function(e) { show_gl: function(e) {
var self = this; var self = this;
var account_id = $(e.target).attr('data-account-id'); var account_id = $(e.target).attr('data-account-id');
var options = { var options = {
account_ids: [account_id], account_ids: [account_id],
} }
var action = { var action = {
type: 'ir.actions.client', type: 'ir.actions.client',
name: 'GL View', name: 'GL View',
tag: 'g_l', tag: 'g_l',
target: 'new', target: 'new',
domain: [(['account_ids','=', account_id])], domain: [(['account_ids', '=', account_id])],
} }
return this.do_action(action); return this.do_action(action);
}, },
print_pdf: function(e) { print_pdf: function(e) {
e.preventDefault(); e.preventDefault();
var self = this; var self = this;
var action_title = self._title; var action_title = self._title;
self._rpc({ self._rpc({
model: 'dynamic.balance.sheet.report', model: 'dynamic.balance.sheet.report',
method: 'view_report', method: 'view_report',
args: [ args: [
[self.wizard_id], action_title, self.searchModel.config.context.lang [self.wizard_id], action_title, self.searchModel.config.context.lang
], ],
}).then(function(data) { }).then(function(data) {
var action = { var action = {
'type': 'ir.actions.report', 'type': 'ir.actions.report',
'report_type': 'qweb-pdf', 'report_type': 'qweb-pdf',
'report_name': 'dynamic_accounts_report.balance_sheet', 'report_name': 'dynamic_accounts_report.balance_sheet',
'report_file': 'dynamic_accounts_report.balance_sheet', 'report_file': 'dynamic_accounts_report.balance_sheet',
'data': { 'data': {
'report_data': data, 'report_data': data,
'report_name': action_title 'report_name': action_title
}, },
'context': { 'context': {
'active_model': 'dynamic.balance.sheet.report', 'active_model': 'dynamic.balance.sheet.report',
'landscape': 1, 'landscape': 1,
'bs_report': true 'bs_report': true
}, },
'display_name': action_title, 'display_name': action_title,
}; };
return self.do_action(action); return self.do_action(action);
}); });
}, },
print_xlsx: function() { print_xlsx: function() {
var self = this; var self = this;
var action_title = self._title; var action_title = self._title;
self._rpc({ self._rpc({
model: 'dynamic.balance.sheet.report', model: 'dynamic.balance.sheet.report',
method: 'view_report', method: 'view_report',
args: [ args: [
[self.wizard_id], action_title, self.searchModel.config.context.lang [self.wizard_id], action_title, self.searchModel.config.context.lang
], ],
}).then(function(data) { }).then(function(data) {
var action = { var action = {
// 'type': 'ir_actions_dynamic_xlsx_download', // 'type': 'ir_actions_dynamic_xlsx_download',
'data': { 'data': {
'model': 'dynamic.balance.sheet.report', 'model': 'dynamic.balance.sheet.report',
'options': JSON.stringify(data['filters']), 'options': JSON.stringify(data['filters']),
'output_format': 'xlsx', 'output_format': 'xlsx',
'report_data': action_title, 'report_data': action_title,
'report_name': action_title, 'report_name': action_title,
'dfr_data': JSON.stringify(data['bs_lines']), 'dfr_data': JSON.stringify(data['bs_lines']),
}, },
}; };
// return self.do_action(action); // return self.do_action(action);
self.downloadXlsx(action) self.downloadXlsx(action)
}); });
}, },
downloadXlsx: function (action){ downloadXlsx: function(action) {
framework.blockUI(); framework.blockUI();
session.get_file({ session.get_file({
url: '/dynamic_xlsx_reports', url: '/dynamic_xlsx_reports',
data: action.data, data: action.data,
complete: framework.unblockUI, complete: framework.unblockUI,
error: (error) => this.call('crash_manager', 'rpc_error', error), error: (error) => this.call('crash_manager', 'rpc_error', error),
}); });
}, },
journal_line_click: function (el){ journal_line_click: function(el) {
click_num++; click_num++;
var self = this; var self = this;
var line = $(el.target).parent().data('id'); var line = $(el.target).parent().data('id');
return self.do_action({ return self.do_action({
type: 'ir.actions.act_window', type: 'ir.actions.act_window',
view_type: 'form', view_type: 'form',
view_mode: 'form', view_mode: 'form',
res_model: 'account.move', res_model: 'account.move',
views: [ views: [
[false, 'form'] [false, 'form']
], ],
res_id: line, res_id: line,
target: 'current', target: 'current',
}); });
}, },
apply_filter: function(event) { apply_filter: function(event) {
event.preventDefault();
event.preventDefault();
var self = this; var self = this;
self.initial_render = false; self.initial_render = false;
var filter_data_selected = {}; var filter_data_selected = {};
@ -266,142 +265,138 @@ odoo.define('dynamic_accounts_report.financial_reports', function (require) {
} }
filter_data_selected.account_ids = account_ids filter_data_selected.account_ids = account_ids
var journal_ids = [];
var journal_text = [];
var journal_ids = []; var journal_res = document.getElementById("journal_res")
var journal_text = []; var journal_list = $(".journals").select2('data')
var journal_res = document.getElementById("journal_res") for (var i = 0; i < journal_list.length; i++) {
var journal_list = $(".journals").select2('data') if (journal_list[i].element[0].selected === true) {
for (var i = 0; i < journal_list.length; i++) {
if(journal_list[i].element[0].selected === true){ journal_ids.push(parseInt(journal_list[i].id))
if (journal_text.includes(journal_list[i].text) === false) {
journal_ids.push(parseInt(journal_list[i].id)) journal_text.push(journal_list[i].text)
if(journal_text.includes(journal_list[i].text) === false){ }
journal_text.push(journal_list[i].text) journal_res.value = journal_text
} journal_res.innerHTML = journal_res.value;
journal_res.value = journal_text }
journal_res.innerHTML=journal_res.value; }
} if (journal_list.length == 0) {
} journal_res.value = ""
if (journal_list.length == 0){ journal_res.innerHTML = "";
journal_res.value = ""
journal_res.innerHTML=""; }
filter_data_selected.journal_ids = journal_ids
}
filter_data_selected.journal_ids = journal_ids var account_tag_ids = [];
var account_tag_text = [];
var account_tag_ids = []; var account_tag_res = document.getElementById("acc_tag_res")
var account_tag_text = [];
var account_tag_res = document.getElementById("acc_tag_res") var account_tag_list = $(".account-tag").select2('data')
for (var i = 0; i < account_tag_list.length; i++) {
var account_tag_list = $(".account-tag").select2('data') if (account_tag_list[i].element[0].selected === true) {
for (var i = 0; i < account_tag_list.length; i++) {
if(account_tag_list[i].element[0].selected === true){ account_tag_ids.push(parseInt(account_tag_list[i].id))
if (account_tag_text.includes(account_tag_list[i].text) === false) {
account_tag_ids.push(parseInt(account_tag_list[i].id)) account_tag_text.push(account_tag_list[i].text)
if(account_tag_text.includes(account_tag_list[i].text) === false){ }
account_tag_text.push(account_tag_list[i].text)
} account_tag_res.value = account_tag_text
account_tag_res.innerHTML = account_tag_res.value;
account_tag_res.value = account_tag_text }
account_tag_res.innerHTML=account_tag_res.value; }
} if (account_tag_list.length == 0) {
} account_tag_res.value = ""
if (account_tag_list.length == 0){ account_tag_res.innerHTML = "";
account_tag_res.value = ""
account_tag_res.innerHTML=""; }
filter_data_selected.account_tag_ids = account_tag_ids
}
filter_data_selected.account_tag_ids = account_tag_ids var analytic_ids = []
var analytic_text = [];
// var analytic_ids = [] var analytic_res = document.getElementById("analytic_res")
// var analytic_text = []; var analytic_list = $(".analytics").select2('data')
// var analytic_res = document.getElementById("analytic_res")
// var analytic_list = $(".analytics").select2('data') for (var i = 0; i < analytic_list.length; i++) {
// if (analytic_list[i].element[0].selected === true) {
// for (var i = 0; i < analytic_list.length; i++) {
// if(analytic_list[i].element[0].selected === true){ analytic_ids.push(parseInt(analytic_list[i].id))
if (analytic_text.includes(analytic_list[i].text) === false) {
analytic_text.push(analytic_list[i].text)
}
analytic_res.value = analytic_text
analytic_res.innerHTML = analytic_res.value;
}
}
if (analytic_list.length == 0) {
analytic_res.value = ""
analytic_res.innerHTML = "";
}
filter_data_selected.analytic_ids = analytic_ids
// var analytic_tag_ids = [];
// var analytic_tag_text = [];
// var analytic_tag_res = document.getElementById("analic_tag_res")
// var analytic_tag_list = $(".analytic-tag").select2('data')
// for (var i = 0; i < analytic_tag_list.length; i++) {
// if (analytic_tag_list[i].element[0].selected === true) {
// //
// analytic_ids.push(parseInt(analytic_list[i].id)) // analytic_tag_ids.push(parseInt(analytic_tag_list[i].id))
// if(analytic_text.includes(analytic_list[i].text) === false){ // if (analytic_tag_text.includes(analytic_tag_list[i].text) === false) {
// analytic_text.push(analytic_list[i].text) // analytic_tag_text.push(analytic_tag_list[i].text)
// }
// analytic_res.value = analytic_text
// analytic_res.innerHTML=analytic_res.value;
// }
// }
// if (analytic_list.length == 0){
// analytic_res.value = ""
// analytic_res.innerHTML="";
// //
// } // }
// filter_data_selected.analytic_ids = analytic_ids
// var analytic_tag_ids = [];
// var analytic_tag_text = [];
//// var analytic_tag_res = document.getElementById("analic_tag_res")
// var analytic_tag_list = $(".analytic-tag").select2('data')
// for (var i = 0; i < analytic_tag_list.length; i++) {
// if(analytic_tag_list[i].element[0].selected === true){
// //
// analytic_tag_ids.push(parseInt(analytic_tag_list[i].id)) // analytic_tag_res.value = analytic_tag_text
// if(analytic_tag_text.includes(analytic_tag_list[i].text) === false){ // analytic_tag_res.innerHTML = analytic_tag_res.value;
// analytic_tag_text.push(analytic_tag_list[i].text) // }
// }
// if (analytic_tag_list.length == 0) {
// analytic_tag_res.value = ""
// analytic_tag_res.innerHTML = "";
// //
// } // }
// // filter_data_selected.analytic_tag_ids = analytic_tag_ids
// analytic_tag_res.value = analytic_tag_text
// analytic_tag_res.innerHTML=analytic_tag_res.value; if ($("#date_from").val()) {
// } var dateString = $("#date_from").val();
// } filter_data_selected.date_from = dateString;
// if (analytic_tag_list.length == 0){ }
// analytic_tag_res.value = "" if ($("#date_to").val()) {
// analytic_tag_res.innerHTML=""; var dateString = $("#date_to").val();
// filter_data_selected.date_to = dateString;
// } }
// filter_data_selected.analytic_tag_ids = analytic_tag_ids if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) {
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
}
if ($("#date_from").val()) {
var dateString = $("#date_from").val(); if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
filter_data_selected.date_from = dateString; filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
} }
if ($("#date_to").val()) {
var dateString = $("#date_to").val(); if ($(".target_move").length) {
filter_data_selected.date_to = dateString; var post_res = document.getElementById("post_res")
} filter_data_selected.target_move = $(".target_move")[1].value
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) { post_res.value = $(".target_move")[1].value
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); post_res.innerHTML = post_res.value;
} if ($(".target_move")[1].value == "") {
post_res.innerHTML = "posted";
if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); }
} }
rpc.query({
if ($(".target_move").length) { model: 'dynamic.balance.sheet.report',
var post_res = document.getElementById("post_res") method: 'write',
filter_data_selected.target_move = $(".target_move")[1].value args: [
post_res.value = $(".target_move")[1].value self.wizard_id, filter_data_selected
post_res.innerHTML=post_res.value; ],
if ($(".target_move")[1].value == "") { }).then(function(res) {
post_res.innerHTML="posted"; self.initial_render = false;
self.load_data(self.initial_render);
} });
} },
rpc.query({ });
model: 'dynamic.balance.sheet.report', core.action_registry.add("dfr_n", ProfitAndLoss);
method: 'write', return ProfitAndLoss;
args: [
self.wizard_id, filter_data_selected
],
}).then(function(res) {
self.initial_render = false;
self.load_data(self.initial_render);
});
},
});
core.action_registry.add("dfr_n", ProfitAndLoss);
return ProfitAndLoss;
}); });

978
dynamic_accounts_report/static/src/js/general_ledger.js

@ -1,509 +1,471 @@
odoo.define('dynamic_accounts_report.general_ledger', function (require) { odoo.define('dynamic_accounts_report.general_ledger', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var trial = require('dynamic_accounts_report.trial_balance'); var trial = require('dynamic_accounts_report.trial_balance');
var framework = require('web.framework'); var framework = require('web.framework');
var datepicker = require('web.datepicker'); var datepicker = require('web.datepicker');
var time = require('web.time'); var time = require('web.time');
window.click_num = 0;
window.click_num = 0; var GeneralLedger = AbstractAction.extend({
var GeneralLedger = AbstractAction.extend({ template: 'GeneralTemp',
template: 'GeneralTemp', events: {
events: { 'click .parent-line': 'journal_line_click',
'click .parent-line': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click #apply_filter': 'apply_filter',
'click #apply_filter': 'apply_filter', 'click #pdf': 'print_pdf',
'click #pdf': 'print_pdf', 'click #xlsx': 'print_xlsx',
'click #xlsx': 'print_xlsx', 'click .gl-line': 'show_drop_down',
'click .gl-line': 'show_drop_down', 'click .view-account-move': 'view_acc_move',
'click .view-account-move': 'view_acc_move', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', },
}, init: function(parent, action) {
this._super(parent, action);
init: function(parent, action) { this.currency = action.currency;
this._super(parent, action); this.report_lines = action.report_lines;
this.currency=action.currency; this.wizard_id = action.context.wizard | null;
this.report_lines = action.report_lines; },
this.wizard_id = action.context.wizard | null; start: function() {
}, var self = this;
self.initial_render = true;
if (this.searchModel.config.domain.length != 0) {
start: function() { rpc.query({
var self = this; model: 'account.general.ledger',
self.initial_render = true; method: 'create',
if (this.searchModel.config.domain.length != 0) { args: [{
rpc.query({ account_ids: [this.searchModel.config.domain[0][2]]
model: 'account.general.ledger', }]
method: 'create', }).then(function(t_res) {
args: [{ self.wizard_id = t_res;
account_ids : [this.searchModel.config.domain[0][2]] self.load_data(self.initial_render);
}] })
}).then(function(t_res) { } else {
self.wizard_id = t_res; rpc.query({
self.load_data(self.initial_render); model: 'account.general.ledger',
}) method: 'create',
}else{ args: [{}]
rpc.query({ }).then(function(t_res) {
model: 'account.general.ledger', self.wizard_id = t_res;
method: 'create', self.load_data(self.initial_render);
args: [{ })
}
}] },
}).then(function(t_res) {
self.wizard_id = t_res; _onCalendarIconClick: function(ev) {
self.load_data(self.initial_render); var $calendarInputGroup = $(ev.currentTarget);
}) var calendarOptions = {
} minDate: moment({
}, y: 1000
}),
maxDate: moment().add(200, 'y'),
_onCalendarIconClick: function (ev) { calendarWeeks: true,
var $calendarInputGroup = $(ev.currentTarget); defaultDate: moment().format(),
sideBySide: true,
var calendarOptions = { buttons: {
showClear: true,
minDate: moment({ y: 1000 }), showClose: true,
maxDate: moment().add(200, 'y'), showToday: true,
calendarWeeks: true, },
defaultDate: moment().format(), icons: {
sideBySide: true, date: 'fa fa-calendar',
buttons: { },
showClear: true, locale: moment.locale(),
showClose: true, format: time.getLangDateFormat(),
showToday: true, widgetParent: 'body',
}, allowInputToggle: true,
};
icons : {
date: 'fa fa-calendar', $calendarInputGroup.datetimepicker(calendarOptions);
},
},
locale : moment.locale(), load_data: function(initial_render = true) {
format : time.getLangDateFormat(), var self = this;
widgetParent: 'body', self.$(".categ").empty();
allowInputToggle: true, try {
}; var self = this;
var action_title = self._title
$calendarInputGroup.datetimepicker(calendarOptions); self._rpc({
}, model: 'account.general.ledger',
method: 'view_report',
args: [
load_data: function (initial_render = true) { [this.wizard_id], action_title
var self = this; ],
self.$(".categ").empty(); }).then(function(datas) {
try{ // _.each(datas['report_lines'], function(rep_lines) {
var self = this; // rep_lines.debit = self.format_currency(datas['currency'],rep_lines.debit);
var action_title = self._title // rep_lines.credit = self.format_currency(datas['currency'],rep_lines.credit);
self._rpc({ // rep_lines.balance = self.format_currency(datas['currency'],rep_lines.balance);
model: 'account.general.ledger', // });
method: 'view_report',
args: [[this.wizard_id], action_title], if (initial_render) {
}).then(function(datas) { self.$('.filter_view_tb').html(QWeb.render('GLFilterView', {
// _.each(datas['report_lines'], function(rep_lines) { filter_data: datas['filters'],
// rep_lines.debit = self.format_currency(datas['currency'],rep_lines.debit); title: datas['name'],
// rep_lines.credit = self.format_currency(datas['currency'],rep_lines.credit); // eng_title : datas['eng_title'],
// rep_lines.balance = self.format_currency(datas['currency'],rep_lines.balance); }));
// self.$el.find('.journals').select2({
// placeholder: ' Journals...',
// });
// self.$el.find('.account-partner').select2({
// }); placeholder: ' Accounts...',
});
if (initial_render) { self.$el.find('.account-tag').select2({
self.$('.filter_view_tb').html(QWeb.render('GLFilterView', { placeholder: ' Account Tag...',
filter_data: datas['filters'], });
title : datas['name'], self.$el.find('.analytics').select2({
// eng_title : datas['eng_title'], placeholder: 'Analytic Accounts...',
})); });
self.$el.find('.journals').select2({ self.$el.find('.target_move').select2({
placeholder: ' Journals...', placeholder: 'Target Move...',
}); });
self.$el.find('.account-partner').select2({ }
placeholder: ' Accounts...', var child = [];
}); self.$('.table_view_tb').html(QWeb.render('GLTable', {
self.$el.find('.analytics').select2({ report_lines: datas['report_lines'],
placeholder: 'Analytic Accounts...', filter: datas['filters'],
}); currency: datas['currency'],
// self.$el.find('.analytic_tags').select2({ credit_total: datas['credit_total'],
// placeholder: 'Analytic Tags...', debit_total: datas['debit_total'],
// }); debit_balance: datas['debit_balance']
self.$el.find('.target_move').select2({ }));
placeholder: 'Target Move...', });
}); } catch (el) {
window.location.href
} }
var child=[]; },
self.$('.table_view_tb').html(QWeb.render('GLTable', {
print_pdf: function(e) {
report_lines : datas['report_lines'], e.preventDefault();
filter : datas['filters'], var self = this;
currency : datas['currency'], var action_title = self._title
credit_total : datas['credit_total'], self._rpc({
debit_total : datas['debit_total'], model: 'account.general.ledger',
debit_balance : datas['debit_balance'] method: 'view_report',
})); args: [
[self.wizard_id], action_title
}); ],
}).then(function(data) {
} var action = {
catch (el) { 'type': 'ir.actions.report',
window.location.href 'report_type': 'qweb-pdf',
} 'report_name': 'dynamic_accounts_report.general_ledger',
}, 'report_file': 'dynamic_accounts_report.general_ledger',
'data': {
print_pdf: function(e) { 'report_data': data
e.preventDefault(); },
var self = this; 'context': {
var action_title = self._title 'active_model': 'account.general.ledger',
self._rpc({ 'landscape': 1,
model: 'account.general.ledger', 'trial_pdf_report': true
method: 'view_report', },
args: [ 'display_name': action_title,
[self.wizard_id], action_title };
], return self.do_action(action);
}).then(function(data) { });
var action = { },
'type': 'ir.actions.report',
'report_type': 'qweb-pdf', print_xlsx: function() {
'report_name': 'dynamic_accounts_report.general_ledger', var self = this;
'report_file': 'dynamic_accounts_report.general_ledger', var action_title = self._title
'data': { self._rpc({
'report_data': data model: 'account.general.ledger',
}, method: 'view_report',
'context': { args: [
'active_model': 'account.general.ledger', [self.wizard_id], action_title
'landscape': 1, ],
'trial_pdf_report': true }).then(function(data) {
}, var action = {
'display_name': action_title, // 'type': 'ir_actions_dynamic_xlsx_download',
}; 'data': {
return self.do_action(action); 'model': 'account.general.ledger',
}); 'options': JSON.stringify(data['filters']),
}, 'output_format': 'xlsx',
'report_data': JSON.stringify(data['report_lines']),
print_xlsx: function() { 'report_name': action_title,
var self = this; 'dfr_data': JSON.stringify(data),
var action_title = self._title },
self._rpc({ };
model: 'account.general.ledger', // return self.do_action(action);
method: 'view_report', self.downloadXlsx(action)
args: [ });
[self.wizard_id], action_title },
],
}).then(function(data) { downloadXlsx: function(action) {
var action = { framework.blockUI();
// 'type': 'ir_actions_dynamic_xlsx_download', session.get_file({
'data': { url: '/dynamic_xlsx_reports',
'model': 'account.general.ledger', data: action.data,
'options': JSON.stringify(data['filters']), complete: framework.unblockUI,
'output_format': 'xlsx', error: (error) => this.call('crash_manager', 'rpc_error', error),
'report_data': JSON.stringify(data['report_lines']), });
'report_name': action_title, },
'dfr_data': JSON.stringify(data),
}, create_lines_with_style: function(rec, attr, datas) {
}; var temp_str = "";
// return self.do_action(action); var style_name = "border-bottom: 1px solid #e6e6e6;";
self.downloadXlsx(action) var attr_name = attr + " style=" + style_name;
});
}, temp_str += "<td class='child_col1' " + attr_name + " >" + rec['code'] + rec['name'] + "</td>";
if (datas.currency[1] == 'after') {
downloadXlsx: function (action){ temp_str += "<td class='child_col2' " + attr_name + " >" + rec['debit'].toFixed(2) + datas.currency[0] + "</td>";
framework.blockUI(); temp_str += "<td class='child_col3' " + attr_name + " >" + rec['credit'].toFixed(2) + datas.currency[0] + "</td>";
session.get_file({ } else {
url: '/dynamic_xlsx_reports', temp_str += "<td class='child_col2' " + attr_name + " >" + datas.currency[0] + rec['debit'].toFixed(2) + "</td>";
data: action.data, temp_str += "<td class='child_col3' " + attr_name + ">" + datas.currency[0] + rec['credit'].toFixed(2) + "</td>";
complete: framework.unblockUI,
error: (error) => this.call('crash_manager', 'rpc_error', error), }
}); return temp_str;
}, },
journal_line_click: function(el) {
click_num++;
create_lines_with_style: function(rec, attr, datas) { var self = this;
var temp_str = ""; var line = $(el.target).parent().data('id');
var style_name = "border-bottom: 1px solid #e6e6e6;"; return self.do_action({
var attr_name = attr + " style="+style_name; type: 'ir.actions.act_window',
view_type: 'form',
temp_str += "<td class='child_col1' "+attr_name+" >"+rec['code'] +rec['name'] +"</td>"; view_mode: 'form',
if(datas.currency[1]=='after'){ res_model: 'account.move',
temp_str += "<td class='child_col2' "+attr_name+" >"+rec['debit'].toFixed(2)+datas.currency[0]+"</td>"; views: [
temp_str += "<td class='child_col3' "+attr_name+" >"+rec['credit'].toFixed(2) +datas.currency[0]+ "</td>"; [false, 'form']
} ],
else{ res_id: line,
temp_str += "<td class='child_col2' "+attr_name+" >"+datas.currency[0]+rec['debit'].toFixed(2) + "</td>"; target: 'current',
temp_str += "<td class='child_col3' "+attr_name+">"+datas.currency[0]+rec['credit'].toFixed(2) + "</td>"; });
} },
return temp_str;
}, format_currency: function(currency, amount) {
if (typeof(amount) != 'number') {
amount = parseFloat(amount);
journal_line_click: function (el){ }
click_num++; var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
var self = this; minimumFractionDigits: 2
var line = $(el.target).parent().data('id'); })
return self.do_action({ return formatted_value
type: 'ir.actions.act_window', },
view_type: 'form',
view_mode: 'form', show_drop_down: function(event) {
res_model: 'account.move', event.preventDefault();
views: [ var self = this;
[false, 'form'] var account_id = $(event.currentTarget).data('account-id');
], var offset = 0;
res_id: line, var td = $(event.currentTarget).next('tr').find('td');
target: 'current', if (td.length == 1) {
}); var action_title = self._title
self._rpc({
}, model: 'account.general.ledger',
format_currency: function(currency, amount) { method: 'get_accounts_line',
if (typeof(amount) != 'number') { args: [
amount = parseFloat(amount); [self.wizard_id], account_id, action_title
} ],
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ }).then(function(data) {
minimumFractionDigits: 2 // _.each(data['report_lines'], function(rep_lines) {
}) // _.each(rep_lines['move_lines'], function(move_line) {
return formatted_value //
}, // move_line.debit = self.format_currency(data['currency'],move_line.debit);
// move_line.credit = self.format_currency(data['currency'],move_line.credit);
show_drop_down: function(event) { // move_line.balance = self.format_currency(data['currency'],move_line.balance);
event.preventDefault(); //
var self = this; //
var account_id = $(event.currentTarget).data('account-id'); // });
var offset = 0; // });
var td = $(event.currentTarget).next('tr').find('td');
if (td.length == 1) { for (var i = 0; i < data['report_lines'].length; i++) {
var action_title = self._title
self._rpc({ if (account_id == data['report_lines'][i]['id']) {
model: 'account.general.ledger', $(event.currentTarget).next('tr').find('td').remove();
method: 'get_accounts_line', $(event.currentTarget).next('tr').after(
args: [ QWeb.render('SubSection', {
[self.wizard_id], account_id, action_title account_data: data['report_lines'][i]['move_lines'],
], currency_symbol: data.currency[0],
}).then(function(data) { id: data['report_lines'][i]['id'],
// _.each(data['report_lines'], function(rep_lines) { currency_position: data.currency[1],
// _.each(rep_lines['move_lines'], function(move_line) {
// }))
// move_line.debit = self.format_currency(data['currency'],move_line.debit); $(event.currentTarget).next('tr').find('td ul li:first a').css({
// move_line.credit = self.format_currency(data['currency'],move_line.credit); 'background-color': '#00ede8',
// move_line.balance = self.format_currency(data['currency'],move_line.balance); 'font-weight': 'bold',
// });
// }
// }); }
// });
});
for (var i = 0; i < data['report_lines'].length; i++) { }
},
if (account_id == data['report_lines'][i]['id'] ){
$(event.currentTarget).next('tr').find('td').remove(); view_acc_move: function(event) {
$(event.currentTarget).next('tr').after( event.preventDefault();
QWeb.render('SubSection', { var self = this;
account_data: data['report_lines'][i]['move_lines'], var context = {};
currency_symbol : data.currency[0], var show_acc_move = function(res_model, res_id, view_id) {
id : data['report_lines'][i]['id'], var action = {
currency_position : data.currency[1], type: 'ir.actions.act_window',
view_type: 'form',
})) view_mode: 'form',
$(event.currentTarget).next('tr').find('td ul li:first a').css({ res_model: res_model,
'background-color': '#00ede8', views: [
'font-weight': 'bold', [view_id || false, 'form']
}); ],
} res_id: res_id,
} target: 'current',
context: context,
}); };
} return self.do_action(action);
}, };
rpc.query({
view_acc_move: function(event) { model: 'account.move',
event.preventDefault(); method: 'search_read',
var self = this; domain: [
var context = {}; ['id', '=', $(event.currentTarget).data('move-id')]
var show_acc_move = function(res_model, res_id, view_id) { ],
var action = { fields: ['id'],
type: 'ir.actions.act_window', limit: 1,
view_type: 'form', })
view_mode: 'form', .then(function(record) {
res_model: res_model, if (record.length > 0) {
views: [ show_acc_move('account.move', record[0].id);
[view_id || false, 'form'] } else {
], show_acc_move('account.move', $(event.currentTarget).data('move-id'));
res_id: res_id, }
target: 'current', });
context: context, },
};
return self.do_action(action); apply_filter: function(event) {
}; event.preventDefault();
rpc.query({ var self = this;
model: 'account.move', self.initial_render = false;
method: 'search_read', var filter_data_selected = {};
domain: [
['id', '=', $(event.currentTarget).data('move-id')] //Account filter
], var account_ids = [];
fields: ['id'], var account_text = [];
limit: 1, var account_res = document.getElementById("account_res")
}) var account_list = $(".account-partner").select2('data')
.then(function(record) { for (var i = 0; i < account_list.length; i++) {
if (record.length > 0) { if (account_list[i].element[0].selected === true) {
show_acc_move('account.move', record[0].id); account_ids.push(parseInt(account_list[i].id))
} else { if (account_text.includes(account_list[i].text) === false) {
show_acc_move('account.move', $(event.currentTarget).data('move-id')); account_text.push(account_list[i].text)
} }
}); account_res.value = account_text
}, account_res.innerHTML = account_res.value;
}
apply_filter: function(event) { }
event.preventDefault(); if (account_list.length == 0) {
var self = this; account_res.value = ""
self.initial_render = false; account_res.innerHTML = "";
}
var filter_data_selected = {}; filter_data_selected.account_ids = account_ids
//Account Tag filter
var account_ids = []; var account_tag_ids = [];
var account_text = []; var account_tag_text = [];
var account_tag_res = document.getElementById("acc_tag_res")
var account_res = document.getElementById("acc_res")
var account_list = $(".account-partner").select2('data') var account_tag_list = $(".account-tag").select2('data')
for (var i = 0; i < account_list.length; i++) { for (var i = 0; i < account_tag_list.length; i++) {
if(account_list[i].element[0].selected === true){ if (account_tag_list[i].element[0].selected === true) {
account_ids.push(parseInt(account_list[i].id))
if(account_text.includes(account_list[i].text) === false){ account_tag_ids.push(parseInt(account_tag_list[i].id))
account_text.push(account_list[i].text) if (account_tag_text.includes(account_tag_list[i].text) === false) {
} account_tag_text.push(account_tag_list[i].text)
account_res.value = account_text }
account_res.innerHTML=account_res.value;
} account_tag_res.value = account_tag_text
} account_tag_res.innerHTML = account_tag_res.value;
if (account_list.length == 0){ }
account_res.value = "" }
account_res.innerHTML=""; if (account_tag_list.length == 0) {
account_tag_res.value = ""
} account_tag_res.innerHTML = "";
filter_data_selected.account_ids = account_ids
}
filter_data_selected.account_tag_ids = account_tag_ids
if(!(this._title == 'Bank Book' || this._title == 'Cash Book')){
//Journal Filter
var journal_ids = []; if (!(this._title == 'Bank Book' || this._title == 'Cash Book')) {
var journal_text = []; var journal_ids = [];
var journal_res = document.getElementById("journal_res") var journal_text = [];
var journal_list = $(".journals").select2('data') var journal_res = document.getElementById("journal_res")
var journal_list = $(".journals").select2('data')
for (var i = 0; i < journal_list.length; i++) { for (var i = 0; i < journal_list.length; i++) {
if(journal_list[i].element[0].selected === true){ if (journal_list[i].element[0].selected === true) {
journal_ids.push(parseInt(journal_list[i].id))
journal_ids.push(parseInt(journal_list[i].id)) if (journal_text.includes(journal_list[i].text) === false) {
if(journal_text.includes(journal_list[i].text) === false){ journal_text.push(journal_list[i].text)
journal_text.push(journal_list[i].text) }
} journal_res.value = journal_text
journal_res.value = journal_text journal_res.innerHTML = journal_res.value;
journal_res.innerHTML=journal_res.value; }
} }
} if (journal_list.length == 0) {
if (journal_list.length == 0){ journal_res.value = ""
journal_res.value = "" journal_res.innerHTML = "";
journal_res.innerHTML=""; }
filter_data_selected.journal_ids = journal_ids
} }
filter_data_selected.journal_ids = journal_ids
//Analytic Filter
} var analytic_ids = [];
var analytic_text = [];
var analytic_res = document.getElementById("analytic_res")
var analytic_list = $(".analytics").select2('data')
// var analytic_ids = [] for (var i = 0; i < analytic_list.length; i++) {
// var analytic_text = []; if (analytic_list[i].element[0].selected === true) {
//// var analytic_res = document.getElementById("analytic_res") analytic_ids.push(parseInt(analytic_list[i].id))
// var analytic_list = $(".analytics").select2('data') if (analytic_text.includes(analytic_list[i].text) === false) {
// analytic_text.push(analytic_list[i].text)
// for (var i = 0; i < analytic_list.length; i++) { }
// if(analytic_list[i].element[0].selected === true){ analytic_res.value = analytic_text
// analytic_res.innerHTML = analytic_res.value;
// analytic_ids.push(parseInt(analytic_list[i].id)) }
// if(analytic_text.includes(analytic_list[i].text) === false){ }
// analytic_text.push(analytic_list[i].text) if (analytic_list.length == 0) {
// } analytic_res.value = ""
// analytic_res.value = analytic_text analytic_res.innerHTML = "";
// analytic_res.innerHTML=analytic_res.value; }
// } filter_data_selected.analytic_ids = analytic_ids
// }
// if (analytic_list.length == 0){ //Date range filter
// analytic_res.value = "" if (this.$el.find('.datetimepicker-input[name="gen_date_from"]').val()) {
// analytic_res.innerHTML=""; filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="gen_date_from"]').val(),
// time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
// } }
// filter_data_selected.analytic_ids = analytic_ids if (this.$el.find('.datetimepicker-input[name="gen_date_to"]').val()) {
// filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="gen_date_to"]').val(),
// var analytic_tag_ids = [] time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
// var analytic_tag_text = []; }
// var analytic_tag_res = document.getElementById("analytic_tag_res")
// var analytic_tag_list = $(".analytic_tags").select2('data') //Target Move Filter
// for (var i = 0; i < analytic_tag_list.length; i++) { if ($(".target_move").length) {
// if(analytic_tag_list[i].element[0].selected === true){ var post_res = document.getElementById("post_res")
// filter_data_selected.target_move = $(".target_move")[1].value
// analytic_tag_ids.push(parseInt(analytic_tag_list[i].id)) post_res.value = $(".target_move")[1].value
// if(analytic_tag_text.includes(analytic_tag_list[i].text) === false){ post_res.innerHTML = post_res.value;
// analytic_tag_text.push(analytic_tag_list[i].text) if ($(".target_move")[1].value == "") {
// } post_res.innerHTML = "posted";
// analytic_tag_res.value = analytic_tag_text }
// analytic_tag_res.innerHTML=analytic_tag_res.value; }
// } rpc.query({
// } model: 'account.general.ledger',
// if (analytic_tag_list.length == 0){ method: 'write',
// analytic_tag_res.value = "" args: [
// analytic_tag_res.innerHTML=""; self.wizard_id, filter_data_selected
// ],
// } }).then(function(res) {
// filter_data_selected.analytic_tag_ids = analytic_tag_ids self.initial_render = false;
self.load_data(self.initial_render);
// if ($("#date_from").val()) { });
// },
// var dateString = $("#date_from").val(); });
// filter_data_selected.date_from = dateString; core.action_registry.add("g_l", GeneralLedger);
// } return GeneralLedger;
// if ($("#date_to").val()) {
// var dateString = $("#date_to").val();
// filter_data_selected.date_to = dateString;
// }
if (this.$el.find('.datetimepicker-input[name="gen_date_from"]').val()) {
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="gen_date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
}
if (this.$el.find('.datetimepicker-input[name="gen_date_to"]').val()) {
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="gen_date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
}
if ($(".target_move").length) {
var post_res = document.getElementById("post_res")
filter_data_selected.target_move = $(".target_move")[1].value
post_res.value = $(".target_move")[1].value
post_res.innerHTML=post_res.value;
if ($(".target_move")[1].value == "") {
post_res.innerHTML="posted";
}
}
rpc.query({
model: 'account.general.ledger',
method: 'write',
args: [
self.wizard_id, filter_data_selected
],
}).then(function(res) {
self.initial_render = false;
self.load_data(self.initial_render);
});
},
});
core.action_registry.add("g_l", GeneralLedger);
return GeneralLedger;
}); });

932
dynamic_accounts_report/static/src/js/partner_ledger.js

@ -1,473 +1,461 @@
odoo.define('dynamic_accounts_report.partner_ledger', function (require) { odoo.define('dynamic_accounts_report.partner_ledger', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var datepicker = require('web.datepicker');
var datepicker = require('web.datepicker'); var time = require('web.time');
var time = require('web.time'); var framework = require('web.framework');
window.click_num = 0; window.click_num = 0;
var PartnerLedger = AbstractAction.extend({ var PartnerLedger = AbstractAction.extend({
template: 'PartnerTemp', template: 'PartnerTemp',
events: { events: {
'click .parent-line': 'journal_line_click', 'click .parent-line': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click #apply_filter': 'apply_filter', 'click #apply_filter': 'apply_filter',
'click #pdf': 'print_pdf', 'click #pdf': 'print_pdf',
'click #xlsx': 'print_xlsx', 'click #xlsx': 'print_xlsx',
'click .pl-line': 'show_drop_down', 'click .pl-line': 'show_drop_down',
'click .view-account-move': 'view_acc_move', 'click .view-account-move': 'view_acc_move',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
}, },
init: function(parent, action) { init: function(parent, action) {
this._super(parent, action); this._super(parent, action);
this.currency=action.currency; this.currency = action.currency;
this.report_lines = action.report_lines; this.report_lines = action.report_lines;
this.wizard_id = action.context.wizard | null; this.wizard_id = action.context.wizard | null;
}, },
start: function() { start: function() {
var self = this; var self = this;
self.initial_render = true; self.initial_render = true;
rpc.query({ rpc.query({
model: 'account.partner.ledger', model: 'account.partner.ledger',
method: 'create', method: 'create',
args: [{ args: [{}]
}] }).then(function(t_res) {
}).then(function(t_res) { self.wizard_id = t_res;
self.wizard_id = t_res; self.load_data(self.initial_render);
self.load_data(self.initial_render); })
}) },
},
_onCalendarIconClick: function(ev) {
_onCalendarIconClick: function (ev) { var $calendarInputGroup = $(ev.currentTarget);
var $calendarInputGroup = $(ev.currentTarget);
var calendarOptions = {
var calendarOptions = {
minDate: moment({
minDate: moment({ y: 1000 }), y: 1000
maxDate: moment().add(200, 'y'), }),
calendarWeeks: true, maxDate: moment().add(200, 'y'),
defaultDate: moment().format(), calendarWeeks: true,
sideBySide: true, defaultDate: moment().format(),
buttons: { sideBySide: true,
showClear: true, buttons: {
showClose: true, showClear: true,
showToday: true, showClose: true,
}, showToday: true,
},
icons : {
date: 'fa fa-calendar', icons: {
date: 'fa fa-calendar',
},
locale : moment.locale(), },
format : time.getLangDateFormat(), locale: moment.locale(),
widgetParent: 'body', format: time.getLangDateFormat(),
allowInputToggle: true, widgetParent: 'body',
}; allowInputToggle: true,
};
$calendarInputGroup.datetimepicker(calendarOptions);
}, $calendarInputGroup.datetimepicker(calendarOptions);
},
load_data: function (initial_render = true) {
var self = this; load_data: function(initial_render = true) {
self.$(".categ").empty(); var self = this;
try{ self.$(".categ").empty();
var self = this; try {
self._rpc({ var self = this;
model: 'account.partner.ledger', self._rpc({
method: 'view_report', model: 'account.partner.ledger',
args: [[this.wizard_id]], method: 'view_report',
}).then(function(datas) { args: [
_.each(datas['report_lines'], function(rep_lines) { [this.wizard_id]
rep_lines.debit = self.format_currency(datas['currency'],rep_lines.debit); ],
rep_lines.credit = self.format_currency(datas['currency'],rep_lines.credit); }).then(function(datas) {
rep_lines.balance = self.format_currency(datas['currency'],rep_lines.balance); _.each(datas['report_lines'], function(rep_lines) {
rep_lines.debit = self.format_currency(datas['currency'], rep_lines.debit);
rep_lines.credit = self.format_currency(datas['currency'], rep_lines.credit);
rep_lines.balance = self.format_currency(datas['currency'], rep_lines.balance)
});
}); if (initial_render) {
self.$('.filter_view_tb').html(QWeb.render('PLFilterView', {
filter_data: datas['filters'],
}));
if (initial_render) { self.$el.find('.journals').select2({
self.$('.filter_view_tb').html(QWeb.render('PLFilterView', { placeholder: ' Journals...',
filter_data: datas['filters'], });
}));
self.$el.find('.journals').select2({ self.$el.find('.account-partner').select2({
placeholder: ' Journals...', placeholder: ' Accounts...',
}); });
self.$el.find('.partners').select2({
self.$el.find('.account-partner').select2({ placeholder: 'Partners...',
placeholder: ' Accounts...', });
}); self.$el.find('.reconciled').select2({
self.$el.find('.partners').select2({ placeholder: 'Reconciled status...',
placeholder: 'Partners...', });
}); self.$el.find('.type').select2({
self.$el.find('.reconciled').select2({ placeholder: 'Account Type...',
placeholder: 'Reconciled status...', });
}); self.$el.find('.category').select2({
self.$el.find('.type').select2({ placeholder: 'Partner Tag...',
placeholder: 'Account Type...', });
}); self.$el.find('.acc').select2({
self.$el.find('.category').select2({ placeholder: 'Select Acc...',
placeholder: 'Partner Tag...', });
}); self.$el.find('.target_move').select2({
self.$el.find('.acc').select2({ placeholder: 'Target Move...',
placeholder: 'Select Acc...', });
}); }
self.$el.find('.target_move').select2({ var child = [];
placeholder: 'Target Move...', self.$('.table_view_tb').html(QWeb.render('PLTable', {
}); report_lines: datas['report_lines'],
} filter: datas['filters'],
var child=[]; currency: datas['currency'],
self.$('.table_view_tb').html(QWeb.render('PLTable', { credit_total: datas['credit_total'],
report_lines : datas['report_lines'], debit_total: datas['debit_total'],
filter : datas['filters'], debit_balance: datas['debit_balance']
currency : datas['currency'], }));
credit_total : datas['credit_total'], });
debit_total : datas['debit_total'],
debit_balance : datas['debit_balance'] } catch (el) {
})); window.location.href
}); }
},
}
catch (el) { format_currency: function(currency, amount) {
window.location.href if (typeof(amount) != 'number') {
} amount = parseFloat(amount);
}, }
var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
minimumFractionDigits: 2
})
format_currency: function(currency, amount) { return formatted_value
if (typeof(amount) != 'number') { },
amount = parseFloat(amount);
} print_pdf: function(e) {
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ e.preventDefault();
minimumFractionDigits: 2 var self = this;
}) self._rpc({
return formatted_value model: 'account.partner.ledger',
}, method: 'view_report',
args: [
print_pdf: function(e) { [self.wizard_id]
e.preventDefault(); ],
var self = this; }).then(function(data) {
self._rpc({ var action = {
model: 'account.partner.ledger', 'type': 'ir.actions.report',
method: 'view_report', 'report_type': 'qweb-pdf',
args: [ 'report_name': 'dynamic_accounts_report.partner_ledger',
[self.wizard_id] 'report_file': 'dynamic_accounts_report.partner_ledger',
], 'data': {
}).then(function(data) { 'report_data': data
var action = { },
'type': 'ir.actions.report', 'context': {
'report_type': 'qweb-pdf', 'active_model': 'account.partner.ledger',
'report_name': 'dynamic_accounts_report.partner_ledger', 'landscape': 1,
'report_file': 'dynamic_accounts_report.partner_ledger', 'partner_ledger_pdf_report': true
'data': { },
'report_data': data 'display_name': 'Partner Ledger',
}, };
'context': { return self.do_action(action);
'active_model': 'account.partner.ledger', });
'landscape': 1, },
'partner_ledger_pdf_report': true
}, print_xlsx: function() {
'display_name': 'Partner Ledger', var self = this;
}; var action_title = self._title
return self.do_action(action); self._rpc({
}); model: 'account.partner.ledger',
}, method: 'view_report',
args: [
[self.wizard_id]
],
print_xlsx: function() { }).then(function(data) {
var self = this; var action = {
self._rpc({ // 'type': 'ir_actions_dynamic_xlsx_download',
model: 'account.partner.ledger', 'data': {
method: 'view_report', 'model': 'account.partner.ledger',
args: [ 'options': JSON.stringify(data['filters']),
[self.wizard_id] 'output_format': 'xlsx',
], 'report_data': JSON.stringify(data['report_lines']),
}).then(function(data) { 'report_name': action_title,
var action = { 'dfr_data': JSON.stringify(data),
// 'type': 'ir_actions_dynamic_xlsx_download', },
'data': { };
'model': 'account.partner.ledger', // return self.do_action(action);
'options': JSON.stringify(data['filters']), // core.action_registry.map.t_b.prototype.downloadXlsx(action)
'output_format': 'xlsx', self.downloadXlsx(action)
'report_data': JSON.stringify(data['report_lines']), });
'report_name': 'Partner Ledger', },
'dfr_data': JSON.stringify(data), downloadXlsx: function(action) {
}, framework.blockUI();
}; session.get_file({
// return self.do_action(action); url: '/dynamic_xlsx_reports',
core.action_registry.map.t_b.prototype.downloadXlsx(action) data: action.data,
}); complete: framework.unblockUI,
}, error: (error) => this.call('crash_manager', 'rpc_error', error),
});
journal_line_click: function (el){ },
click_num++;
var self = this; journal_line_click: function(el) {
var line = $(el.target).parent().data('id'); click_num++;
return self.do_action({ var self = this;
type: 'ir.actions.act_window', var line = $(el.target).parent().data('id');
view_type: 'form', return self.do_action({
view_mode: 'form', type: 'ir.actions.act_window',
res_model: 'account.move', view_type: 'form',
views: [ view_mode: 'form',
[false, 'form'] res_model: 'account.move',
], views: [
res_id: line, [false, 'form']
target: 'current', ],
}); res_id: line,
}, target: 'current',
});
show_drop_down: function(event) { },
event.preventDefault();
var self = this; show_drop_down: function(event) {
var account_id = $(event.currentTarget).data('account-id'); event.preventDefault();
var offset = 0; var self = this;
var td = $(event.currentTarget).next('tr').find('td'); var account_id = $(event.currentTarget).data('account-id');
if (td.length == 1) { var offset = 0;
self._rpc({ var td = $(event.currentTarget).next('tr').find('td');
model: 'account.partner.ledger', if (td.length == 1) {
method: 'view_report', self._rpc({
args: [ model: 'account.partner.ledger',
[self.wizard_id] method: 'view_report',
], args: [
}).then(function(data) { [self.wizard_id]
_.each(data['report_lines'], function(rep_lines) { ],
_.each(rep_lines['move_lines'], function(move_line) { }).then(function(data) {
_.each(data['report_lines'], function(rep_lines) {
move_line.debit = self.format_currency(data['currency'],move_line.debit); _.each(rep_lines['move_lines'], function(move_line) {
move_line.credit = self.format_currency(data['currency'],move_line.credit);
move_line.balance = self.format_currency(data['currency'],move_line.balance); move_line.debit = self.format_currency(data['currency'], move_line.debit);
move_line.credit = self.format_currency(data['currency'], move_line.credit);
move_line.balance = self.format_currency(data['currency'], move_line.balance);
}); });
}); });
for (var i = 0; i < data['report_lines'].length; i++) { for (var i = 0; i < data['report_lines'].length; i++) {
if (account_id == data['report_lines'][i]['id'] ){ if (account_id == data['report_lines'][i]['id']) {
$(event.currentTarget).next('tr').find('td').remove(); $(event.currentTarget).next('tr').find('td').remove();
$(event.currentTarget).next('tr').after( $(event.currentTarget).next('tr').after(
QWeb.render('SubSectionPL', { QWeb.render('SubSectionPL', {
account_data: data['report_lines'][i]['move_lines'], account_data: data['report_lines'][i]['move_lines'],
id : data['report_lines'][i]['id'] id: data['report_lines'][i]['id']
})) }))
$(event.currentTarget).next('tr').find('td ul li:first a').css({ $(event.currentTarget).next('tr').find('td ul li:first a').css({
'background-color': '#00ede8', 'background-color': '#00ede8',
'font-weight': 'bold', 'font-weight': 'bold',
}); });
} }
} }
}); });
} }
}, },
view_acc_move: function(event) { view_acc_move: function(event) {
event.preventDefault(); event.preventDefault();
var self = this; var self = this;
var context = {}; var context = {};
var show_acc_move = function(res_model, res_id, view_id) { var show_acc_move = function(res_model, res_id, view_id) {
var action = { var action = {
type: 'ir.actions.act_window', type: 'ir.actions.act_window',
view_type: 'form', view_type: 'form',
view_mode: 'form', view_mode: 'form',
res_model: res_model, res_model: res_model,
views: [ views: [
[view_id || false, 'form'] [view_id || false, 'form']
], ],
res_id: res_id, res_id: res_id,
target: 'current', target: 'current',
context: context, context: context,
}; };
return self.do_action(action); return self.do_action(action);
}; };
rpc.query({ rpc.query({
model: 'account.move', model: 'account.move',
method: 'search_read', method: 'search_read',
domain: [ domain: [
['id', '=', $(event.currentTarget).data('move-id')] ['id', '=', $(event.currentTarget).data('move-id')]
], ],
fields: ['id'], fields: ['id'],
limit: 1, limit: 1,
}) })
.then(function(record) { .then(function(record) {
if (record.length > 0) { if (record.length > 0) {
show_acc_move('account.move', record[0].id); show_acc_move('account.move', record[0].id);
} else { } else {
show_acc_move('account.move', $(event.currentTarget).data('move-id')); show_acc_move('account.move', $(event.currentTarget).data('move-id'));
} }
}); });
}, },
apply_filter: function(event) { apply_filter: function(event) {
event.preventDefault(); event.preventDefault();
var self = this; var self = this;
self.initial_render = false; self.initial_render = false;
var filter_data_selected = {}; var filter_data_selected = {};
var account_ids = []; //Account filter
var account_text = []; var account_ids = [];
var span_res = document.getElementById("account_res") var account_text = [];
var account_list = $(".account-partner").select2('data') var span_res = document.getElementById("account_res")
for (var i = 0; i < account_list.length; i++) { var account_list = $(".account-partner").select2('data')
if(account_list[i].element[0].selected === true) for (var i = 0; i < account_list.length; i++) {
{account_ids.push(parseInt(account_list[i].id)) if (account_list[i].element[0].selected === true) {
if(account_text.includes(account_list[i].text) === false) account_ids.push(parseInt(account_list[i].id))
{account_text.push(account_list[i].text) if (account_text.includes(account_list[i].text) === false) {
} account_text.push(account_list[i].text)
span_res.value = account_text }
span_res.innerHTML=span_res.value; span_res.value = account_text
} span_res.innerHTML = span_res.value;
} }
if (account_list.length == 0){ }
span_res.value = "" if (account_list.length == 0) {
span_res.innerHTML=""; } span_res.value = ""
filter_data_selected.account_ids = account_ids span_res.innerHTML = "";
}
filter_data_selected.account_ids = account_ids
var journal_ids = [];
var journal_text = []; //Journal Filter
var journal_res = document.getElementById("journal_res") var journal_ids = [];
var journal_list = $(".journals").select2('data') var journal_text = [];
for (var i = 0; i < journal_list.length; i++) { var journal_res = document.getElementById("journal_res")
if(journal_list[i].element[0].selected === true){ var journal_list = $(".journals").select2('data')
journal_ids.push(parseInt(journal_list[i].id)) for (var i = 0; i < journal_list.length; i++) {
if(journal_text.includes(journal_list[i].text) === false){ if (journal_list[i].element[0].selected === true) {
journal_text.push(journal_list[i].text) journal_ids.push(parseInt(journal_list[i].id))
} if (journal_text.includes(journal_list[i].text) === false) {
journal_res.value = journal_text journal_text.push(journal_list[i].text)
journal_res.innerHTML=journal_res.value; }
} journal_res.value = journal_text
} journal_res.innerHTML = journal_res.value;
if (journal_list.length == 0){ }
journal_res.value = "" }
journal_res.innerHTML=""; if (journal_list.length == 0) {
} journal_res.value = ""
filter_data_selected.journal_ids = journal_ids journal_res.innerHTML = "";
}
var partner_ids = []; filter_data_selected.journal_ids = journal_ids
var partner_text = [];
var span_res = document.getElementById("partner_res") //Partner Filter
var partner_list = $(".partners").select2('data') var partner_ids = [];
for (var i = 0; i < partner_list.length; i++) { var partner_text = [];
if(partner_list[i].element[0].selected === true) var span_res = document.getElementById("partner_res")
{partner_ids.push(parseInt(partner_list[i].id)) var partner_list = $(".partners").select2('data')
if(partner_text.includes(partner_list[i].text) === false) for (var i = 0; i < partner_list.length; i++) {
{partner_text.push(partner_list[i].text) if (partner_list[i].element[0].selected === true) {
} partner_ids.push(parseInt(partner_list[i].id))
span_res.value = partner_text if (partner_text.includes(partner_list[i].text) === false) {
span_res.innerHTML=span_res.value; partner_text.push(partner_list[i].text)
} }
} span_res.value = partner_text
if (partner_list.length == 0){ span_res.innerHTML = span_res.value;
span_res.value = "" }
span_res.innerHTML=""; }
} if (partner_list.length == 0) {
filter_data_selected.partner_ids = partner_ids span_res.value = ""
span_res.innerHTML = "";
var account_type_id = []; }
var account_type_ids_text = []; filter_data_selected.partner_ids = partner_ids
var span_res = document.getElementById("type_res")
var type_list = $(".type").select2('data') //Account Type Filter
for (var i = 0; i < type_list.length; i++) { if ($(".type").length) {
if(type_list[i].element[0].selected === true) var type_res = document.getElementById("type_res")
{account_type_id.push(parseInt(type_list[i].id)) filter_data_selected.account_type = $(".type")[1].value
if(account_type_ids_text.includes(type_list[i].text) === false) type_res.value = $(".type")[1].value
{account_type_ids_text.push(type_list[i].text) type_res.innerHTML = account_type.value;
} if ($(".type").value == "") {
span_res.value = account_type_ids_text type_res.innerHTML = "asset_receivable";
span_res.innerHTML=span_res.value; filter_data_selected.account_type = "asset_receivable"
} }
} }
if (type_list.length == 0){
span_res.value = "" //Partner Category Filter
span_res.innerHTML=""; var partner_category_ids = [];
} var partner_category_text = [];
filter_data_selected.account_type_id = account_type_id var span_res = document.getElementById("category_res")
var category_list = $(".category").select2('data')
var partner_category_ids = []; for (var i = 0; i < category_list.length; i++) {
var partner_category_text = []; if (category_list[i].element[0].selected === true) {
var span_res = document.getElementById("category_res") partner_category_ids.push(parseInt(category_list[i].id))
var category_list = $(".category").select2('data') if (partner_category_text.includes(category_list[i].text) === false) {
for (var i = 0; i < category_list.length; i++) { partner_category_text.push(category_list[i].text)
if(category_list[i].element[0].selected === true) }
{partner_category_ids.push(parseInt(category_list[i].id)) span_res.value = partner_category_text
if(partner_category_text.includes(category_list[i].text) === false) span_res.innerHTML = span_res.value;
{partner_category_text.push(category_list[i].text) }
} }
span_res.value = partner_category_text if (category_list.length == 0) {
span_res.innerHTML=span_res.value; span_res.value = ""
} span_res.innerHTML = "";
} }
if (category_list.length == 0){ filter_data_selected.partner_category_ids = partner_category_ids
span_res.value = ""
span_res.innerHTML=""; //Date range filter
} if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) {
filter_data_selected.partner_category_ids = partner_category_ids filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
}
// if ($("#date_from").val()) { if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
// var dateString = $("#date_from").val(); filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
// filter_data_selected.date_from = dateString; }
// }
// if ($("#date_to").val()) { //Reconciled Filter
// var dateString = $("#date_to").val(); if ($(".reconciled").length) {
// filter_data_selected.date_to = dateString; var reconciled_res = document.getElementById("reconciled_res")
// } filter_data_selected.reconciled = $(".reconciled")[1].value
reconciled_res.value = $(".reconciled")[1].value
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) { reconciled_res.innerHTML = reconciled_res.value;
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); if ($(".reconciled").value == "") {
} reconciled_res.innerHTML = "unreconciled";
filter_data_selected.reconciled = "unreconciled"
if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) { }
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); }
}
//Target Move Filter
if ($(".reconciled").length){ if ($(".target_move").length) {
var reconciled_res = document.getElementById("reconciled_res") var post_res = document.getElementById("post_res")
filter_data_selected.reconciled = $(".reconciled")[1].value filter_data_selected.target_move = $(".target_move")[1].value
reconciled_res.value = $(".reconciled")[1].value post_res.value = $(".target_move")[1].value
reconciled_res.innerHTML=reconciled_res.value; post_res.innerHTML = post_res.value;
if ($(".reconciled").value==""){ if ($(".target_move")[1].value == "") {
reconciled_res.innerHTML="unreconciled"; post_res.innerHTML = "posted";
filter_data_selected.reconciled = "unreconciled" }
} }
} rpc.query({
model: 'account.partner.ledger',
if ($(".target_move").length) { method: 'write',
var post_res = document.getElementById("post_res") args: [
filter_data_selected.target_move = $(".target_move")[1].value self.wizard_id, filter_data_selected
post_res.value = $(".target_move")[1].value ],
post_res.innerHTML=post_res.value; }).then(function(res) {
if ($(".target_move")[1].value == "") { self.initial_render = false;
post_res.innerHTML="posted"; self.load_data(self.initial_render);
});
} },
}
rpc.query({ });
model: 'account.partner.ledger', core.action_registry.add("p_l", PartnerLedger);
method: 'write', return PartnerLedger;
args: [
self.wizard_id, filter_data_selected
],
}).then(function(res) {
self.initial_render = false;
self.load_data(self.initial_render);
});
},
});
core.action_registry.add("p_l", PartnerLedger);
return PartnerLedger;
}); });

672
dynamic_accounts_report/static/src/js/trial_balance.js

@ -1,338 +1,336 @@
odoo.define('dynamic_accounts_report.trial_balance', function (require) { odoo.define('dynamic_accounts_report.trial_balance', function(require) {
'use strict'; 'use strict';
var AbstractAction = require('web.AbstractAction'); var AbstractAction = require('web.AbstractAction');
var core = require('web.core'); var core = require('web.core');
var field_utils = require('web.field_utils'); var field_utils = require('web.field_utils');
var rpc = require('web.rpc'); var rpc = require('web.rpc');
var session = require('web.session'); var session = require('web.session');
var utils = require('web.utils'); var utils = require('web.utils');
var QWeb = core.qweb; var QWeb = core.qweb;
var _t = core._t; var _t = core._t;
var framework = require('web.framework'); var framework = require('web.framework');
var datepicker = require('web.datepicker'); var datepicker = require('web.datepicker');
var time = require('web.time'); var time = require('web.time');
// import framework from 'web.framework'; // import framework from 'web.framework';
// import { download } from "@web/core/network/download"; // import { download } from "@web/core/network/download";
// import { registry } from "@web/core/registry"; // import { registry } from "@web/core/registry";
// const serviceRegistry = registry.category("services"); // const serviceRegistry = registry.category("services");
window.click_num = 0; window.click_num = 0;
var TrialBalance = AbstractAction.extend({ var TrialBalance = AbstractAction.extend({
template: 'TrialTemp', template: 'TrialTemp',
events: { events: {
'click .parent-line': 'journal_line_click', 'click .parent-line': 'journal_line_click',
'click .child_col1': 'journal_line_click', 'click .child_col1': 'journal_line_click',
'click #apply_filter': 'apply_filter', 'click #apply_filter': 'apply_filter',
'click #pdf': 'print_pdf', 'click #pdf': 'print_pdf',
'click #xlsx': 'print_xlsx', 'click #xlsx': 'print_xlsx',
'click .show-gl': 'show_gl', 'click .show-gl': 'show_gl',
'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick', 'mousedown div.input-group.date[data-target-input="nearest"]': '_onCalendarIconClick',
}, },
init: function(parent, action) { init: function(parent, action) {
this._super(parent, action); this._super(parent, action);
this.currency=action.currency; this.currency = action.currency;
this.report_lines = action.report_lines; this.report_lines = action.report_lines;
this.wizard_id = action.context.wizard | null; this.wizard_id = action.context.wizard | null;
}, },
start: function() { start: function() {
var self = this; var self = this;
self.initial_render = true; self.initial_render = true;
rpc.query({ rpc.query({
model: 'account.trial.balance', model: 'account.trial.balance',
method: 'create', method: 'create',
args: [{ args: [{
}] }]
}).then(function(t_res) { }).then(function(t_res) {
self.wizard_id = t_res; self.wizard_id = t_res;
self.load_data(self.initial_render); self.load_data(self.initial_render);
}) })
}, },
load_data: function (initial_render = true) { load_data: function(initial_render = true) {
var self = this; var self = this;
self.$(".categ").empty(); self.$(".categ").empty();
try{ try {
var self = this; var self = this;
self._rpc({ self._rpc({
model: 'account.trial.balance', model: 'account.trial.balance',
method: 'view_report', method: 'view_report',
args: [[this.wizard_id]], args: [
}).then(function(datas) { [this.wizard_id]
],
}).then(function(datas) {
_.each(datas['report_lines'], function(rep_lines) {
rep_lines.debit = self.format_currency(datas['currency'],rep_lines.debit);
rep_lines.credit = self.format_currency(datas['currency'],rep_lines.credit); _.each(datas['report_lines'], function(rep_lines) {
rep_lines.balance = self.format_currency(datas['currency'],rep_lines.balance); rep_lines.debit = self.format_currency(datas['currency'], rep_lines.debit);
rep_lines.credit = self.format_currency(datas['currency'], rep_lines.credit);
rep_lines.balance = self.format_currency(datas['currency'], rep_lines.balance);
});
if (initial_render) {
self.$('.filter_view_tb').html(QWeb.render('TrialFilterView', { });
filter_data: datas['filters'], if (initial_render) {
})); self.$('.filter_view_tb').html(QWeb.render('TrialFilterView', {
self.$el.find('.journals').select2({ filter_data: datas['filters'],
placeholder: 'Select Journals...', }));
}); self.$el.find('.journals').select2({
self.$el.find('.target_move').select2({ placeholder: 'Select Journals...',
placeholder: 'Target Move...', });
}); self.$el.find('.target_move').select2({
// self.$el.find('#start_dateee').select2({ placeholder: 'Target Move...',
// placeholder: 'Date.', });
// }); // self.$el.find('#start_dateee').select2({
} // placeholder: 'Date.',
var child=[]; // });
}
self.$('.table_view_tb').html(QWeb.render('TrialTable', { var child = [];
report_lines : datas['report_lines'], self.$('.table_view_tb').html(QWeb.render('TrialTable', {
filter : datas['filters'],
currency : datas['currency'], report_lines: datas['report_lines'],
credit_total : self.format_currency(datas['currency'],datas['debit_total']), filter: datas['filters'],
debit_total : self.format_currency(datas['currency'],datas['debit_total']), currency: datas['currency'],
})); credit_total: self.format_currency(datas['currency'], datas['debit_total']),
debit_total: self.format_currency(datas['currency'], datas['debit_total']),
}); }));
} });
catch (el) {
window.location.href } catch (el) {
} window.location.href
}, }
},
show_gl: function(e) {
var self = this; show_gl: function(e) {
var account_id = $(e.target).attr('data-account-id'); var self = this;
var options = { var account_id = $(e.target).attr('data-account-id');
account_ids: [account_id], var options = {
} account_ids: [account_id],
}
var action = {
type: 'ir.actions.client', var action = {
name: 'GL View', type: 'ir.actions.client',
tag: 'g_l', name: 'GL View',
target: 'new', tag: 'g_l',
target: 'new',
domain: [['account_ids','=', account_id]],
domain: [
['account_ids', '=', account_id]
} ],
return this.do_action(action);
}, }
return this.do_action(action);
print_pdf: function(e) {
e.preventDefault(); },
var self = this;
self._rpc({ print_pdf: function(e) {
model: 'account.trial.balance', e.preventDefault();
method: 'view_report', var self = this;
args: [ self._rpc({
[self.wizard_id] model: 'account.trial.balance',
], method: 'view_report',
}).then(function(data) { args: [
var action = { [self.wizard_id]
'type': 'ir.actions.report', ],
'report_type': 'qweb-pdf', }).then(function(data) {
'report_name': 'dynamic_accounts_report.trial_balance', var action = {
'report_file': 'dynamic_accounts_report.trial_balance', 'type': 'ir.actions.report',
'data': { 'report_type': 'qweb-pdf',
'report_data': data 'report_name': 'dynamic_accounts_report.trial_balance',
}, 'report_file': 'dynamic_accounts_report.trial_balance',
'context': { 'data': {
'active_model': 'account.trial.balance', 'report_data': data
'landscape': 1, },
'trial_pdf_report': true 'context': {
}, 'active_model': 'account.trial.balance',
'display_name': 'Trial Balance', 'landscape': 1,
}; 'trial_pdf_report': true
return self.do_action(action); },
}); 'display_name': 'Trial Balance',
}, };
return self.do_action(action);
_onCalendarIconClick: function (ev) { });
var $calendarInputGroup = $(ev.currentTarget); },
var calendarOptions = { _onCalendarIconClick: function(ev) {
var $calendarInputGroup = $(ev.currentTarget);
// minDate: moment({ y: 1000 }),
// maxDate: moment().add(200, 'y'), var calendarOptions = {
// calendarWeeks: true,
// defaultDate: moment().format(), // minDate: moment({ y: 1000 }),
// sideBySide: true, // maxDate: moment().add(200, 'y'),
// buttons: { // calendarWeeks: true,
// showClear: true, // defaultDate: moment().format(),
// showClose: true, // sideBySide: true,
// showToday: true, // buttons: {
// }, // showClear: true,
// showClose: true,
icons : { // showToday: true,
date: 'fa fa-calendar', // },
}, icons: {
locale : moment.locale(), date: 'fa fa-calendar',
format : time.getLangDateFormat(),
widgetParent: 'body', },
allowInputToggle: true, locale: moment.locale(),
}; format: time.getLangDateFormat(),
widgetParent: 'body',
$calendarInputGroup.datetimepicker(calendarOptions); allowInputToggle: true,
}, };
$calendarInputGroup.datetimepicker(calendarOptions);
},
format_currency: function(currency, amount) {
if (typeof(amount) != 'number') {
amount = parseFloat(amount);
} format_currency: function(currency, amount) {
var formatted_value = (parseInt(amount)).toLocaleString(currency[2],{ if (typeof(amount) != 'number') {
minimumFractionDigits: 2 amount = parseFloat(amount);
}) }
return formatted_value var formatted_value = (parseInt(amount)).toLocaleString(currency[2], {
}, minimumFractionDigits: 2
})
print_xlsx: function() { return formatted_value
var self = this; },
self._rpc({
model: 'account.trial.balance', print_xlsx: function() {
method: 'view_report', var self = this;
args: [ self._rpc({
[self.wizard_id] model: 'account.trial.balance',
], method: 'view_report',
}).then(function(data) { args: [
var action = { [self.wizard_id]
// 'type': 'ir_actions_dynamic_xlsx_download', ],
'data': { }).then(function(data) {
'model': 'account.trial.balance', var action = {
'options': JSON.stringify(data['filters']), // 'type': 'ir_actions_dynamic_xlsx_download',
'output_format': 'xlsx', 'data': {
'report_data': JSON.stringify(data['report_lines']), 'model': 'account.trial.balance',
'report_name': 'Trial Balance', 'options': JSON.stringify(data['filters']),
'dfr_data': JSON.stringify(data), 'output_format': 'xlsx',
}, 'report_data': JSON.stringify(data['report_lines']),
}; 'report_name': 'Trial Balance',
'dfr_data': JSON.stringify(data),
// return self.do_action(action); },
self.downloadXlsx(action); };
});
}, // return self.do_action(action);
self.downloadXlsx(action);
downloadXlsx: function (action){ });
framework.blockUI(); },
session.get_file({
url: '/dynamic_xlsx_reports', downloadXlsx: function(action) {
data: action.data, framework.blockUI();
complete: framework.unblockUI, session.get_file({
error: (error) => this.call('crash_manager', 'rpc_error', error), url: '/dynamic_xlsx_reports',
}); data: action.data,
}, complete: framework.unblockUI,
error: (error) => this.call('crash_manager', 'rpc_error', error),
journal_line_click: function (el){ });
click_num++; },
var self = this;
var line = $(el.target).parent().data('id'); journal_line_click: function(el) {
return self.do_action({ click_num++;
type: 'ir.actions.act_window', var self = this;
view_type: 'form', var line = $(el.target).parent().data('id');
view_mode: 'form', return self.do_action({
res_model: 'account.move', type: 'ir.actions.act_window',
views: [ view_type: 'form',
[false, 'form'] view_mode: 'form',
], res_model: 'account.move',
res_id: line, views: [
target: 'current', [false, 'form']
}); ],
res_id: line,
}, target: 'current',
});
apply_filter: function(event) { },
event.preventDefault();
var self = this; apply_filter: function(event) {
self.initial_render = false; event.preventDefault();
var self = this;
self.initial_render = false;
var filter_data_selected = {};
var journal_ids = [];
var filter_data_selected = {}; var journal_text = [];
var journal_ids = []; var journal_res = document.getElementById("journal_res")
var journal_text = []; var journal_list = $(".journals").select2('data')
var journal_res = document.getElementById("journal_res")
var journal_list = $(".journals").select2('data') for (var i = 0; i < journal_list.length; i++) {
if (journal_list[i].element[0].selected === true) {
for (var i = 0; i < journal_list.length; i++) {
if(journal_list[i].element[0].selected === true){ journal_ids.push(parseInt(journal_list[i].id))
if (journal_text.includes(journal_list[i].text) === false) {
journal_ids.push(parseInt(journal_list[i].id)) journal_text.push(journal_list[i].text)
if(journal_text.includes(journal_list[i].text) === false){ }
journal_text.push(journal_list[i].text) journal_res.value = journal_text
} journal_res.innerHTML = journal_res.value;
journal_res.value = journal_text }
journal_res.innerHTML=journal_res.value; }
} if (journal_list.length == 0) {
} journal_res.value = ""
if (journal_list.length == 0){ journal_res.innerHTML = "";
journal_res.value = ""
journal_res.innerHTML=""; }
filter_data_selected.journal_ids = journal_ids
}
filter_data_selected.journal_ids = journal_ids if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) {
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
if (this.$el.find('.datetimepicker-input[name="date_from"]').val()) { }
filter_data_selected.date_from = moment(this.$el.find('.datetimepicker-input[name="date_from"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
} if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) {
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD');
if (this.$el.find('.datetimepicker-input[name="date_to"]').val()) { }
filter_data_selected.date_to = moment(this.$el.find('.datetimepicker-input[name="date_to"]').val(), time.getLangDateFormat()).locale('en').format('YYYY-MM-DD'); // if ($("#date_from").val()) {
} // var dateString = $("#date_from").val();
// if ($("#date_from").val()) { // filter_data_selected.date_from = dateString;
// var dateString = $("#date_from").val(); // }
// filter_data_selected.date_from = dateString;
// }
// if ($("#date_to").val()) {
// var dateString = $("#date_to").val();
// if ($("#date_to").val()) { // filter_data_selected.date_to = dateString;
// var dateString = $("#date_to").val(); // }
// filter_data_selected.date_to = dateString;
// } if ($(".target_move").length) {
var post_res = document.getElementById("post_res")
if ($(".target_move").length) { filter_data_selected.target_move = $(".target_move")[1].value
var post_res = document.getElementById("post_res") post_res.value = $(".target_move")[1].value
filter_data_selected.target_move = $(".target_move")[1].value post_res.innerHTML = post_res.value;
post_res.value = $(".target_move")[1].value if ($(".target_move")[1].value == "") {
post_res.innerHTML=post_res.value; post_res.innerHTML = "posted";
if ($(".target_move")[1].value == "") {
post_res.innerHTML="posted"; }
}
} rpc.query({
} model: 'account.trial.balance',
rpc.query({ method: 'write',
model: 'account.trial.balance', args: [
method: 'write', self.wizard_id, filter_data_selected
args: [ ],
self.wizard_id, filter_data_selected }).then(function(res) {
], self.initial_render = false;
}).then(function(res) { self.load_data(self.initial_render);
self.initial_render = false; });
self.load_data(self.initial_render); },
});
}, });
core.action_registry.add("t_b", TrialBalance);
}); return TrialBalance;
core.action_registry.add("t_b", TrialBalance);
return TrialBalance;
}); });

356
dynamic_accounts_report/static/src/xml/financial_reports_view.xml

@ -2,392 +2,238 @@
<t t-name="dfr_template_new"> <t t-name="dfr_template_new">
<div class=""> <div class="">
<div> <div>
<div class="filter_view_dfr"></div> <div class="filter_view_dfr" />
</div> </div>
<br></br> <br></br>
<div> <div>
<div class="table_view_dfr" style="right:20px;"></div> <div class="table_view_dfr" style="right:20px;" />
</div> </div>
</div> </div>
</t> </t>
<t t-name="dfr_table"> <t t-name="dfr_table">
<div> <div>
<div class="table_main_view"> <div class="table_main_view">
<table cellspacing="0" width="100%"> <table cellspacing="0" width="100%">
<thead> <thead>
<tr> <tr>
<th colspan="6"></th> <th colspan="6" />f <th style="text-align: right; padding-right: 50px;"> Debit </th>
<th style="text-align: right; padding-right: 50px;"> <th style="text-align: right; padding-right: 50px;"> Credit </th>
Debit <th style="text-align: right; padding-right: 50px;"> Balance </th>
</th>
<th style="text-align: right; padding-right: 50px;">
Credit
</th>
<th style="text-align: right; padding-right: 50px;">
Balance
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<t t-set="none_value" t-value="_" />
<t t-set="none_value" t-value="_"/>
<t t-foreach="bs_lines" t-as="a"> <t t-foreach="bs_lines" t-as="a">
<t t-if="a['code']"> <t t-if="a['code']">
<t t-foreach="report_lines" t-as="account"> <t t-foreach="report_lines" t-as="account">
<t t-set="common_id" t-value="0" />
<t t-set="common_id" t-value="0"/>
<t t-if="account['id'] == a['account']"> <t t-if="account['id'] == a['account']">
<tr style="border: 1.5px solid black;" <tr style="border: 1.5px solid black;" class="gl-line" data-bs-toggle="collapse" t-att-data-account-id="account['id']" t-attf-data-target=".a{{account['id']}}">
class="gl-line" <td colspan="6" style="border: 0px solid black; padding-left: 50px;">
data-bs-toggle="collapse"
t-att-data-account-id="account['id']"
t-attf-data-target=".a{{account['id']}}">
<td colspan="6"
style="border: 0px solid black; padding-left: 50px;">
<span> <span>
<t t-esc="account['code']"/> <t t-esc="account['code']" /> - <t t-if="account['name'][lang] and lang != 'en_US'">
- <t t-esc="account['name'][lang]" />
<t t-if="account['name'][lang] and lang != 'en_US'"> </t>
<t t-esc="account['name'][lang]"/>
</t>
<t t-elif="account['name']['en_US']"> <t t-elif="account['name']['en_US']">
<t t-esc="account['name']['en_US']"/> <t t-esc="account['name']['en_US']" />
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="account['name']"/> <t t-esc="account['name']" />
</t> </t>
</span> </span>
<div class="" <div class="" style="display: inline-block;">
style="display: inline-block;"> <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"></a>
<a type="button" <div class="dropdown-menu" role="menu">
class="dropdown-toggle"
data-bs-toggle="dropdown"
aria-expanded="false">
</a>
<div class="dropdown-menu"
role="menu">
<div class="o_foldable_menu o_closed_menu "> <div class="o_foldable_menu o_closed_menu ">
<div class="form-group "> <div class="form-group ">
<div class="show-gl" <div class="show-gl" aria-atomic="true" id="" data-target-input="">
aria-atomic="true"
id=""
data-target-input="">
<li role="presentation"> <li role="presentation">
<a role="menuitem" <a role="menuitem" style="background-color:aqua; font-weight:bold;" t-att-data-account-id="account['id']" class="show-gl"> View General Ledger </a>
style="background-color:aqua; font-weight:bold;"
t-att-data-account-id="account['id']"
class="show-gl">
View
General
Ledger
</a>
</li> </li>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</td> </td>
<td t-att-style="fr_padding"> <td t-att-style="fr_padding">
<t t-esc="a['m_debit']" <t t-esc="a['m_debit']" t-att-style="style" />
t-att-style="style"/>
</td> </td>
<td t-att-style="fr_padding"> <td t-att-style="fr_padding">
<t t-esc="a['m_credit']" <t t-esc="a['m_credit']" t-att-style="style" />
t-att-style="style"/>
</td> </td>
<td t-att-style="fr_padding"> <td t-att-style="fr_padding">
<t t-esc="a['m_balance']" <t t-esc="a['m_balance']" t-att-style="style" />
t-att-style="style"/>
</td> </td>
<t t-set="common_id" t-value="'a'+account['id']" />
<t t-set="common_id"
t-value="'a'+account['id']"/>
</tr> </tr>
</t> </t>
</t> </t>
</t> </t>
<t t-else=""> <t t-else="">
<t t-set="style" <t t-set="style" t-value="'padding: 5px;padding-left: 25px;'" />
t-value="'padding: 5px;padding-left: 25px;'"/> <t t-set="fr_head" t-value="'border-bottom: double;'" />
<t t-set="fr_head" <t t-set="fr_padding" t-value="'padding-top: 5px; text-align: right;padding-right: 50px; vertical-align: bottom;'" />
t-value="'border-bottom: double;'"/>
<t t-set="fr_padding"
t-value="'padding-top: 5px; text-align: right;padding-right: 50px; vertical-align: bottom;'"/>
<t t-if="a['level'] == 1"> <t t-if="a['level'] == 1">
<t t-set="style" <t t-set="style" t-value="'padding: 5px;padding-left: 15px; padding-top: 15px;'" />
t-value="'padding: 5px;padding-left: 15px; padding-top: 15px;'"/>
</t> </t>
<t t-if="a['level'] == 2"> <t t-if="a['level'] == 2">
<t t-set="style" <t t-set="style" t-value="'padding: 5px;padding-left: 25px; padding-top: 25px;'" />
t-value="'padding: 5px;padding-left: 25px; padding-top: 25px;'"/>
</t> </t>
<t t-if="a['level'] == 3"> <t t-if="a['level'] == 3">
<t t-set="style" <t t-set="style" t-value="'padding: 5px;padding-left: 50px;'" />
t-value="'padding: 5px;padding-left: 50px;'"/> <t t-set="fr_head" t-value="'border-bottom: 1px solid black;'" />
<t t-set="fr_head"
t-value="'border-bottom: 1px solid black;'"/>
</t> </t>
<t t-if="a['level'] &gt; 3"> <t t-if="a['level'] &gt; 3">
<t t-set="style" <t t-set="style" t-value="'padding: 5px;padding-left: 50px;'" />
t-value="'padding: 5px;padding-left: 50px;'"/> <t t-set="fr_head" t-value="'border-bottom: 1px solid black;'" />
<t t-set="fr_head"
t-value="'border-bottom: 1px solid black;'"/>
</t> </t>
<tr t-att-style="fr_head"> <tr t-att-style="fr_head">
<th colspan="6" t-att-style="style"> <th colspan="6" t-att-style="style">
<t t-esc="a['name']"/> <t t-esc="a['name']" />
</th> </th>
<td t-att-style="fr_padding"> <td t-att-style="fr_padding">
<t t-esc="a['m_debit']"/> <t t-esc="a['m_debit']" />
</td> </td>
<td t-att-style="fr_padding"> <td t-att-style="fr_padding">
<t t-esc="a['m_credit']"/> <t t-esc="a['m_credit']" />
</td> </td>
<td t-att-style="fr_padding"> <td t-att-style="fr_padding">
<t t-esc="a['m_balance']"/> <t t-esc="a['m_balance']" />
</td> </td>
</tr> </tr>
</t> </t>
</t> </t>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</t> </t>
<t t-name="DfrFilterView"> <t t-name="DfrFilterView">
<div class=""> <div class="">
<h1 style="padding:10px"> <h1 style="padding:10px">
<t t-esc="title"/> <t t-esc="title" />
</h1> </h1>
</div> </div>
<div class="row" style="margin-right: 10px; margin-left: 10px;"> <div class="row" style="margin-right: 10px; margin-left: 10px;">
<div class="sub_container_left" style="width:70%;"> <div class="sub_container_left" style="width:70%;">
<div class="report_print"> <div class="report_print">
<button type="button" class="btn btn-primary" id="pdf" <button type="button" class="btn btn-primary" id="pdf" style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;"> Print (PDF) </button>
style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;"> <button type="button" class="btn btn-primary" id="xlsx" style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;"> Export (XLSX) </button>
Print (PDF)
</button>
<button type="button" class="btn btn-primary" id="xlsx"
style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;">
Export (XLSX)
</button>
</div> </div>
</div> </div>
<br></br> <br></br>
<div class="sub_container_right row" <div class="sub_container_right row" style="width:30%;height:3%;top:0px;position: relative;">
style="width:30%;height:3%;top:0px;position: relative;">
<div class="time_range" style=""> <div class="time_range" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-calendar" title="Dates" role="img" aria-label="Dates" /> Date Range </a>
<span class="fa fa-calendar" title="Dates" role="img"
aria-label="Dates"></span>
Date Range
</a>
<div class="dropdown-menu" role="menu"> <div class="dropdown-menu" role="menu">
<div class="form-group"> <div class="form-group">
<label class="" for="date_from">Start Date : <label class="" for="date_from">Start Date : </label>
</label> <div class="input-group date" id="date_from" data-target-input="nearest">
<div class="input-group date" id="date_from" <input type="text" name="date_from" class="form-control datetimepicker-input" data-target="#date_from" t-att-name="prefix" />
data-target-input="nearest"> <div class="input-group-append" data-target="#date_from" data-bs-toggle="datetimepicker">
<input type="text" name="date_from"
class="form-control datetimepicker-input"
data-target="#date_from"
t-att-name="prefix"/>
<div class="input-group-append"
data-target="#date_from"
data-bs-toggle="datetimepicker">
<span class="input-group-text"> <span class="input-group-text">
<span class="fa fa-calendar" role="img" <span class="fa fa-calendar" role="img" aria-label="Calendar" /></span>
aria-label="Calendar"></span>
</span>
</div> </div>
</div> </div>
<label class="" for="date_to">End Date :</label> <label class="" for="date_to">End Date :</label>
<div class="input-group date" id="date_to" <div class="input-group date" id="date_to" data-target-input="nearest">
data-target-input="nearest"> <input type="text" name="date_to" class="form-control datetimepicker-input" data-target="#date_to" t-att-name="prefix" />
<div class="input-group-append" data-target="#date_to" data-bs-toggle="datetimepicker">
<input type="text" name="date_to"
class="form-control datetimepicker-input"
data-target="#date_to"
t-att-name="prefix"/>
<div class="input-group-append"
data-target="#date_to"
data-bs-toggle="datetimepicker">
<span class="input-group-text"> <span class="input-group-text">
<span class="fa fa-calendar" role="img" <span class="fa fa-calendar" role="img" aria-label="Calendar" /></span>
aria-label="Calendar"></span>
</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="journals_filter dropdown" style=""> <div class="journals_filter dropdown" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-book" /> Journals: </a>
<span class="fa fa-book"></span> <select class="dropdown-menu journals" name="states[]" multiple="multiple">
Journals: <div role="separator" class="dropdown-divider" />
</a> <t t-foreach="filter_data.journals_list" t-as="journal">
<select class="dropdown-menu journals" name="states[]"
multiple="multiple">
<div role="separator" class="dropdown-divider"></div>
<t t-foreach="filter_data.journals_list"
t-as="journal">
<t t-if="journal[0]=='divider'"> <t t-if="journal[0]=='divider'">
<div role="separator" <div role="separator" class="dropdown-divider" />
class="dropdown-divider"/> <option disabled="disabled" role="menuitem" t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]" />
<option disabled="disabled" role="menuitem"
t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]"/>
</option> </option>
<div role="separator" <div role="separator" class="dropdown-divider" />
class="dropdown-divider"/>
</t> </t>
<t t-else=""> <t t-else="">
<option t-attf-value="{{journal[0]}}"> <option t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]"/> <t t-esc="journal[1]" />
</option> </option>
</t> </t>
</t> </t>
</select> </select>
<span id="journal_res"></span> <span id="journal_res" />
</div> </div>
<div class="accounts_filter"> <div class="accounts_filter">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-book" /> Accounts: </a>
<span class="fa fa-book"></span> <select class="dropdown-menu account" name="states[]" multiple="multiple">
Accounts: <t t-foreach="filter_data.accounts_list" t-as="account">
</a>
<select class="dropdown-menu account" name="states[]"
multiple="multiple">
<t t-foreach="filter_data.accounts_list"
t-as="account">
<t t-if="account[0]=='divider'"> <t t-if="account[0]=='divider'">
<div role="separator" <div role="separator" class="dropdown-divider" />
class="dropdown-divider"/> <option disabled="disabled" role="menuitem" t-attf-value="{{account[0]}}">
<t t-esc="account[1]" />
<option disabled="disabled" role="menuitem"
t-attf-value="{{account[0]}}">
<t t-esc="account[1]"/>
</option> </option>
<div role="separator" <div role="separator" class="dropdown-divider" />
class="dropdown-divider"/>
</t> </t>
<t t-else=""> <t t-else="">
<option t-attf-value="{{account[0]}}"> <option t-attf-value="{{account[0]}}">
<t t-esc="account[1]"/> <t t-esc="account[1]" />
</option> </option>
</t> </t>
</t> </t>
</select> </select>
<span id="acc_res"></span> <span id="acc_res" />
</div> </div>
<div class="account_tags_filter"> <div class="account_tags_filter">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-book" /> Account Tags: </a>
<span class="fa fa-book"></span> <select class="dropdown-menu account-tag" name="states[]" multiple="multiple">
Account Tags: <t t-foreach="filter_data.account_tag_list" t-as="account_tag">
</a> <option t-attf-value="{{account_tag[0]}}">
<div class="dropdown-menu"> <t t-esc="account_tag[1]" />
<select class="account-tag" </option>
name="states[]" multiple="multiple"> </t>
<t t-foreach="filter_data.account_tag_list" </select>
t-as="account_tag"> <span id="acc_tag_res" />
<option t-attf-value="{{account_tag[0]}}"> </div>
<t t-esc="account_tag[1]"/> <div class="analytics_filter">
</option> <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
</t> <span class="fa fa-book" /> Analytic Accounts: </a>
</select> <select class="dropdown-menu analytics" name="states[]" multiple="multiple">
</div> <t t-foreach="filter_data.analytic_list" t-as="analytic">
<span id="acc_tag_res"></span> <option t-attf-value="{{analytic[0]}}">
<t t-esc="analytic[1]" />
</option>
</t>
</select>
<span id="analytic_res" />
</div> </div>
<!-- <div class="analytics_filter">-->
<!-- <a type="button" class="dropdown-toggle"-->
<!-- data-bs-toggle="dropdown">-->
<!-- <span class="fa fa-book"></span>-->
<!-- Analytic Accounts:-->
<!-- </a>-->
<!-- <select class="dropdown-menu analytics" name="states[]"-->
<!-- multiple="multiple">-->
<!-- <t t-foreach="filter_data.analytic_list"-->
<!-- t-as="analytic">-->
<!-- <option t-attf-value="{{analytic[0]}}">-->
<!-- <t t-esc="analytic[1]"/>-->
<!-- </option>-->
<!-- </t>-->
<!-- </select>-->
<!-- <span id="analytic_res"></span>-->
<!-- </div>-->
<!-- <div class="analytic_tags_filter">-->
<!-- <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">-->
<!-- <span class="fa fa-book"></span>-->
<!-- Analytic Tags:-->
<!-- </a>-->
<!-- <select class="dropdown-menu analytic-tag" name="states[]" multiple="multiple">-->
<!-- <t t-foreach="filter_data.analytic_tag_list" t-as="analytic_tag">-->
<!-- <option t-attf-value="{{analytic_tag[0]}}">-->
<!-- <t t-esc="analytic_tag[1]"/>-->
<!-- </option>-->
<!-- </t>-->
<!-- </select>-->
<!-- <span id="analic_tag_res"></span>-->
<!-- </div>-->
<div class="search-Target-move" style=""> <div class="search-Target-move" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-filter" /> Target Move: </a>
<span class="fa fa-filter"></span> <select id="entries" class="dropdown-menu target_move" name="states[]">
Target Move: <div role="separator" class="dropdown-divider" />
</a>
<select id="entries" class="dropdown-menu target_move"
name="states[]">
<div role="separator" class="dropdown-divider"></div>
<option value="Posted">Posted Entries</option> <option value="Posted">Posted Entries</option>
<option value="All">All Entries</option> <option value="All">All Entries</option>
</select> </select>
<span id="post_res"></span> <span id="post_res" />
</div> </div>
<div style=""> <div style="">
<button type="button" id="apply_filter" <button type="button" id="apply_filter" class="btn btn-primary" style="top:0px;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD;"> Apply </button>
class="btn btn-primary"
style="top:0px;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD;">
Apply
</button>
</div> </div>
</div> </div>
<!-- </div>-->
<!-- -->
<!-- </div>-->
</div> </div>
</t> </t>
</templates> </templates>

409
dynamic_accounts_report/static/src/xml/general_ledger_view.xml

@ -2,11 +2,11 @@
<t t-name="GeneralTemp"> <t t-name="GeneralTemp">
<div> <div>
<div> <div>
<div class="filter_view_tb"></div> <div class="filter_view_tb" />
</div> </div>
<br></br> <br />
<div> <div>
<div class="table_view_tb" style="right:20px;"></div> <div class="table_view_tb" style="right:20px;" />
</div> </div>
</div> </div>
</t> </t>
@ -23,34 +23,32 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<t t-set="none_value" t-value="_"/> <t t-set="none_value" t-value="_" />
<t t-foreach="report_lines" t-as="account"> <t t-foreach="report_lines" t-as="account">
<t t-set="common_id" t-value="0"/> <t t-set="common_id" t-value="0" />
<tr style="border: 1.5px solid black;" <tr style="border: 1.5px solid black;" class="gl-line" data-bs-toggle="collapse" t-att-data-account-id="account['id']" t-attf-data-bs-target=".a{{account['id']}}">
class="gl-line" <td colspan="6" style="border: 0px solid black;">
data-bs-toggle="collapse" <i class="fa fa-caret-down" role="img" aria-label="Unfolded" title="Unfolded" />
t-att-data-account-id="account['id']"
t-attf-data-bs-target=".a{{account['id']}}">
<td colspan="6"
style="border: 0px solid black;">
<i class="fa fa-caret-down" role="img"
aria-label="Unfolded"
title="Unfolded"></i>
<span> <span>
<t t-esc="account['code']"/> <t t-esc="account['code']" /> - <t t-if="account['name'][lang] and lang != 'en_US'">
- <t t-esc="account['name'][lang]" />
<t t-esc="account['name']"/> </t>
<t t-elif="account['name']['en_US']">
<t t-esc="account['name']['en_US']" />
</t>
<t t-else="">
<t t-esc="account['name']" />
</t>
</span> </span>
</td> </td>
<t t-if="currency[1] == 'before'"> <t t-if="currency[1] == 'before'">
<td class="mon_fld"> <td class="mon_fld">
<t t-if="account['debit'] == 0"> <t t-if="account['debit'] == 0">
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="currency[0]"/> <t t-esc="currency[0]" />
<t t-esc="account['debit']"/> <t t-esc="account['debit']" />
<!-- <t t-raw="Math.round(account['debit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-raw="Math.round(account['debit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
</t> </t>
</td> </td>
@ -59,8 +57,8 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="currency[0]"/> <t t-esc="currency[0]" />
<t t-esc="account['credit']"/> <t t-esc="account['credit']" />
<!-- <t t-raw="Math.round(account['credit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-raw="Math.round(account['credit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
</t> </t>
</td> </td>
@ -69,12 +67,11 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="currency[0]"/> <t t-esc="currency[0]" />
<t t-esc="account['balance']"/> <t t-esc="account['balance']" />
<!-- <t t-raw="Math.round(account['balance'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-raw="Math.round(account['balance'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
</t> </t>
</td> </td>
</t> </t>
<t t-else=""> <t t-else="">
<td class="mon_fld"> <td class="mon_fld">
@ -82,9 +79,9 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="account['debit']"/> <t t-esc="account['debit']" />
<!-- <t t-raw="Math.round(account['debit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-raw="Math.round(account['debit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
<t t-esc="currency[0]"/> <t t-esc="currency[0]" />
</t> </t>
</td> </td>
<td class="mon_fld"> <td class="mon_fld">
@ -92,9 +89,9 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="account['credit']"/> <t t-esc="account['credit']" />
<!-- <t t-raw="Math.round(account['credit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-raw="Math.round(account['credit'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
<t t-esc="currency[0]"/> <t t-esc="currency[0]" />
</t> </t>
</td> </td>
<td class="mon_fld"> <td class="mon_fld">
@ -102,258 +99,168 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="account['balance']"/> <t t-esc="account['balance']" />
<!-- <t t-raw="Math.round(account['balance'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-raw="Math.round(account['balance'] * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
<t t-esc="currency[0]"/> <t t-esc="currency[0]" />
</t> </t>
</td> </td>
</t> </t>
<t t-set="common_id" t-value="'a'+account['id']" />
<t t-set="common_id"
t-value="'a'+account['id']"/>
</tr> </tr>
<tr t-attf-class="collapse a{{account['id']}}"> <tr t-attf-class="collapse a{{account['id']}}">
<td colspan="10"> <td colspan="10">
<ul class="div_block"> <ul class="div_block"></ul>
</ul>
</td> </td>
</tr> </tr>
</t> </t>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</t> </t>
<t t-name="GLFilterView"> <t t-name="GLFilterView">
<div> <div>
<h1 style="padding:10px"> <h1 style="padding:10px">
<t t-esc="title"/> <t t-esc="title" />
</h1> </h1>
</div> </div>
<div class="row" style="margin-right: 10px; margin-left: 10px;"> <div class="row" style="margin-right: 10px; margin-left: 10px;">
<div class="sub_container_left" style="width:70%;"> <div class="sub_container_left" style="width:70%;">
<div class="report_print"> <div class="report_print">
<button type="button" class="btn btn-primary" id="pdf" <button type="button" class="btn btn-primary" id="pdf" style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;"> Print (PDF) </button>
style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;"> <button type="button" class="btn btn-primary" id="xlsx" style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;"> Export (XLSX) </button>
Print (PDF)
</button>
<button type="button" class="btn btn-primary" id="xlsx"
style="position: relative;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD; padding:3px;">
Export (XLSX)
</button>
</div> </div>
</div> </div>
<br></br> <br />
<div class="sub_container_right row" <div class="sub_container_right" style="width:30%;height:3%;top:0px;position: relative;">
style="width:30%;height:3%;top:0px;position: relative;"> <!--Time Range filter-->
<div class="time_range" style=""> <div class="time_range" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-calendar" title="Dates" role="img" aria-label="Dates" /> Date Range </a>
<span class="fa fa-calendar" title="Dates" role="img"
aria-label="Dates"></span>
Date Range
</a>
<div class="dropdown-menu" role="menu"> <div class="dropdown-menu" role="menu">
<div class="form-group"> <div class="form-group">
<label class="" for="gen_date_from">Start Date : <label class="" for="gen_date_from">Start Date : </label>
</label> <div class="input-group date" id="gen_date_from" data-target-input="nearest">
<div class="input-group date" id="gen_date_from" <input type="text" name="gen_date_from" class="form-control datetimepicker-input" data-target="#gen_date_from" t-att-name="prefix" />
data-target-input="nearest"> <div class="input-group-append" data-target="#gen_date_from" data-bs-toggle="datetimepicker">
<input type="text" name="gen_date_from"
class="form-control datetimepicker-input"
data-target="#gen_date_from"
t-att-name="prefix"/>
<div class="input-group-append"
data-target="#gen_date_from"
data-bs-toggle="datetimepicker">
<span class="input-group-text"> <span class="input-group-text">
<span class="fa fa-calendar" role="img" <span class="fa fa-calendar" role="img" aria-label="Calendar" /></span>
aria-label="Calendar"></span>
</span>
</div> </div>
</div> </div>
<label class="" for="gen_date_to">End Date : </label>
<label class="" for="gen_date_to">End Date : <div class="input-group date" id="gen_date_to" data-target-input="nearest">
</label> <input type="text" name="gen_date_to" class="form-control datetimepicker-input" data-target="#gen_date_to" t-att-name="prefix" />
<div class="input-group date" id="gen_date_to" <div class="input-group-append" data-target="#gen_date_to" data-bs-toggle="datetimepicker">
data-target-input="nearest">
<input type="text" name="gen_date_to"
class="form-control datetimepicker-input"
data-target="#gen_date_to"
t-att-name="prefix"/>
<div class="input-group-append"
data-target="#gen_date_to"
data-bs-toggle="datetimepicker">
<span class="input-group-text"> <span class="input-group-text">
<span class="fa fa-calendar" role="img" <span class="fa fa-calendar" role="img" aria-label="Calendar" /></span>
aria-label="Calendar"/>
</span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<br />
<t t-if="title == 'General Ledger'"> <t t-if="title == 'General Ledger'">
<!--journals_filter-->
<div class="journals_filter" style=""> <div class="journals_filter" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-book" /> Journals: </a>
<span class="fa fa-book"></span> <select class="dropdown-menu journals" name="states[]" multiple="multiple">
Journals: <div role="separator" class="dropdown-divider" />
</a> <t t-foreach="filter_data.journals_list" t-as="journal">
<select class="dropdown-menu journals" name="states[]"
multiple="multiple">
<div role="separator"
class="dropdown-divider"></div>
<t t-foreach="filter_data.journals_list"
t-as="journal">
<t t-if="journal[0]=='divider'"> <t t-if="journal[0]=='divider'">
<div role="separator" <div role="separator" class="dropdown-divider" />
class="dropdown-divider"/> <option disabled="disabled" role="menuitem" t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]" />
<option disabled="disabled" role="menuitem"
t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]"/>
</option> </option>
<div role="separator" <div role="separator" class="dropdown-divider" />
class="dropdown-divider"/>
</t> </t>
<t t-else=""> <t t-else="">
<option t-attf-value="{{journal[0]}}"> <option t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]"/> <t t-esc="journal[1]" />
</option> </option>
</t> </t>
</t> </t>
</select> </select>
<span id="journal_res"></span> <span id="journal_res" />
</div> </div>
<br />
</t> </t>
<!--Account filter-->
<div class="accounts_filter"> <div class="accounts_filter">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-book" /> Accounts: </a>
<span class="fa fa-book"></span> <select class="dropdown-menu account-partner" name="states[]" multiple="multiple">
Accounts: <t t-foreach="filter_data.accounts_list" t-as="account">
</a> <t t-if="account[0]=='divider'">
<select class="dropdown-menu account" name="states[]" <div role="separator" class="dropdown-divider" />
multiple="multiple"> <option disabled="disabled" role="menuitem" t-attf-value="{{account[0]}}">
<t t-foreach="filter_data.accounts_list" <t t-esc="account[1]" />
t-as="account"> </option>
<div role="separator" class="dropdown-divider" />
<t t-if="account[0]=='divider'"> </t>
<div role="separator" <t t-else="">
class="dropdown-divider"/> <option t-attf-value="{{account[0]}}">
<t t-esc="account[1]" />
<option disabled="disabled" role="menuitem" </option>
t-attf-value="{{account[0]}}"> </t>
<t t-esc="account[1]"/> </t>
</select>
<span id="account_res" />
</div>
<br />
<!-- account tags-->
<div class="account_tags_filter">
<a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
<span class="fa fa-book" /> Account Tags: </a>
<select class="dropdown-menu account-tag" name="states[]" multiple="multiple">
<t t-foreach="filter_data.account_tag_list" t-as="account_tag">
<option t-attf-value="{{account_tag[0]}}">
<t t-esc="account_tag[1]" />
</option> </option>
<div role="separator"
class="dropdown-divider"/>
</t> </t>
</select>
<span id="acc_tag_res" />
</div>
<br />
<t t-else=""> <!--Analytics filter-->
<div class="analytics_filter">
<option t-attf-value="{{account[0]}}"> <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
<t t-esc="account[1]"/> <span class="fa fa-book" /> Analytic Accounts: </a>
<select class="dropdown-menu analytics" name="states[]" multiple="multiple">
<t t-foreach="filter_data.analytic_list" t-as="analytic">
<option t-attf-value="{{analytic[0]}}">
<t t-esc="analytic[1]" />
</option> </option>
</t> </t>
</t> </select>
</select> <t t-log="filter_data" />
<span id="acc_res"></span> <span id="analytic_res" />
</div> </div>
<!-- </t>-->
<!-- <div class="analytics_filter">-->
<!-- <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">-->
<!-- <span class="fa fa-book"></span>-->
<!-- Analytic Accounts:-->
<!-- </a>-->
<!-- <select class="dropdown-menu analytics" name="states[]" multiple="multiple">-->
<!-- <t t-foreach="filter_data.analytic_list" t-as="analytic">-->
<!-- <option t-attf-value="{{analytic[0]}}">-->
<!-- <t t-esc="analytic[1]"/>-->
<!-- </option>-->
<!-- </t>-->
<!-- </select>-->
<!-- <span id="analytic_res"></span>-->
<!-- </div>-->
<!-- <div class="analytic_tags_filter">-->
<!-- <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">-->
<!-- <span class="fa fa-book"></span>-->
<!-- Analytic Tags:-->
<!-- </a>-->
<!-- <select class="dropdown-menu analytic_tags" name="states[]" multiple="multiple">-->
<!-- <t t-foreach="filter_data.analytic_tag_list" t-as="analytic_tag">-->
<!-- <option t-attf-value="{{analytic_tag[0]}}">-->
<!-- <t t-esc="analytic_tag[1]"/>-->
<!-- </option>-->
<!-- </t>-->
<!-- </select>-->
<!-- <span id="analytic_tag_res"></span>-->
<!-- </div>-->
<div class="search-Target-move" style=""> <div class="search-Target-move" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle" data-bs-toggle="dropdown">
data-bs-toggle="dropdown"> <span class="fa fa-filter"></span> Target Move: </a>
<span class="fa fa-filter"></span> <select id="entries" class="dropdown-menu target_move" name="states[]">
Target Move:
</a>
<select id="entries" class="dropdown-menu target_move"
name="states[]">
<div role="separator" class="dropdown-divider"></div> <div role="separator" class="dropdown-divider"></div>
<option value="Posted">Posted Entries</option> <option value="Posted">Posted Entries</option>
<option value="All">All Entries</option> <option value="All">All Entries</option>
</select> </select>
<span id="post_res"></span> <span id="post_res"></span>
</div> </div>
<br />
<div style=""> <div style="">
<button type="button" id="apply_filter" <button type="button" id="apply_filter" class="btn btn-primary" style="top:0px;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD;"> Apply </button>
class="btn btn-primary"
style="top:0px;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD;">
Apply
</button>
</div> </div>
</div> </div>
<!-- </div>-->
<!-- <div style="">-->
<!-- <button type="button" id="apply_filter" class="btn btn-primary"-->
<!-- style="top:0px;height:30px;right:20px;position: absolute;color:white;background-color: #00A0AD;border-color: #00A0AD;">-->
<!-- Apply-->
<!-- </button>-->
<!-- </div>-->
<!-- </div>-->
</div> </div>
</t> </t>
<t t-name="SubSection"> <t t-name="SubSection">
<tr t-attf-class="gl-table-div a{{id}}"> <tr t-attf-class="gl-table-div a{{id}}">
<td colspan="10"> <td colspan="10">
<table class="table table-sm o_main_table" <table class="table table-sm o_main_table" style="display compact;margin-bottom:0 !important;">
style="display compact;margin-bottom:0 !important;">
<thead> <thead>
<tr style=""> <tr style="">
<th>Date</th> <th>Date</th>
@ -367,11 +274,10 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<t t-set="t_balance" t-value="0"/> <t t-set="t_balance" t-value="0" />
<t t-foreach="account_data" t-as="account_line"> <t t-foreach="account_data" t-as="account_line">
<t t-set="style" t-value="''"/> <t t-set="style" t-value="''" />
<t t-set="style_right" <t t-set="style_right" t-value="'text-align:right;'" />
t-value="'text-align:right;'"/>
<tr> <tr>
<td> <td>
<t t-if="account_line.ldate"> <t t-if="account_line.ldate">
@ -379,35 +285,28 @@
<a data-bs-toggle="dropdown" href="#"> <a data-bs-toggle="dropdown" href="#">
<span class="caret"></span> <span class="caret"></span>
<span> <span>
<t t-esc="account_line.ldate"/> <t t-esc="account_line.ldate" />
</span> </span>
</a> </a>
<ul class="dropdown-menu" <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
role="menu"
aria-labelledby="dropdownMenu">
<li> <li>
<a class="view-account-move" <a class="view-account-move" tabindex="-1" href="#" t-att-data-move-id="account_line.move_id"> View Source move </a>
tabindex="-1" href="#"
t-att-data-move-id="account_line.move_id">
View Source move
</a>
</li> </li>
</ul> </ul>
</div> </div>
</t> </t>
</td> </td>
<td> <td>
<t t-esc="account_line.lcode"/> <t t-esc="account_line.lcode" />
</td> </td>
<td> <td>
<t t-esc="account_line.partner_name"/> <t t-esc="account_line.partner_name" />
</td> </td>
<td t-att-style="style"> <td t-att-style="style">
<t t-esc="account_line.move_name"/> <t t-esc="account_line.move_name" />
</td> </td>
<td t-att-style="style"> <td t-att-style="style">
<t t-esc="account_line.lname"/> <t t-esc="account_line.lname" />
</td> </td>
<t t-if="currency_position == 'before'"> <t t-if="currency_position == 'before'">
<td t-att-style="style_right" class="amt"> <td t-att-style="style_right" class="amt">
@ -415,9 +314,9 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<!-- <t t-esc="account_line.currency_code"/>--> <!-- <t t-esc="account_line.currency_code"/>-->
<t t-esc="currency_symbol"/> <t t-esc="currency_symbol" />
<t t-esc="account_line.debit"/> <t t-esc="account_line.debit" />
<!-- <t t-esc="Math.round(account_line.debit * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-esc="Math.round(account_line.debit * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
</t> </t>
</td> </td>
@ -426,9 +325,9 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<!-- <t t-esc="account_line.currency_code"/>--> <!-- <t t-esc="account_line.currency_code"/>-->
<t t-esc="currency_symbol"/> <t t-esc="currency_symbol" />
<t t-esc="account_line.credit"/> <t t-esc="account_line.credit" />
<!-- <t t-esc="Math.round(account_line.credit * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-esc="Math.round(account_line.credit * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
</t> </t>
</td> </td>
@ -437,13 +336,11 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-set="t_balance" <t t-set="t_balance" t-value="Math.round((t_balance+account_line.balance)* 100) / 100" />
t-value="Math.round((t_balance+account_line.balance)* 100) / 100"/> <!-- <t t-esc="account_line.currency_code"/>-->
<!-- <t t-esc="account_line.currency_code"/>--> <t t-esc="currency_symbol" />
<t t-esc="currency_symbol"/>
<!-- <t t-esc="account_line.balance"/>--> <!-- <t t-esc="account_line.balance"/>-->
<t t-esc="t_balance" <t t-esc="t_balance" t-options='{"widget": "float", "precision": 2}' />
t-options='{"widget": "float", "precision": 2}'/>
<!-- <t t-esc="Math.round(account_line.balance * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-esc="Math.round(account_line.balance * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
</t> </t>
</td> </td>
@ -454,10 +351,10 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="account_line.debit"/> <t t-esc="account_line.debit" />
<!-- <t t-esc="Math.round(account_line.debit * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-esc="Math.round(account_line.debit * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
<!-- <t t-esc="account_line.currency_code"/>--> <!-- <t t-esc="account_line.currency_code"/>-->
<t t-esc="currency_symbol"/> <t t-esc="currency_symbol" />
</t> </t>
</td> </td>
<td t-att-style="style_right" class="amt"> <td t-att-style="style_right" class="amt">
@ -465,10 +362,10 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-esc="account_line.credit"/> <t t-esc="account_line.credit" />
<!-- <t t-esc="Math.round(account_line.credit * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-esc="Math.round(account_line.credit * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
<!-- <t t-esc="account_line.currency_code"/>--> <!-- <t t-esc="account_line.currency_code"/>-->
<t t-esc="currency_symbol"/> <t t-esc="currency_symbol" />
</t> </t>
</td> </td>
<td t-att-style="style_right" class="amt"> <td t-att-style="style_right" class="amt">
@ -476,26 +373,20 @@
<span>-</span> <span>-</span>
</t> </t>
<t t-else=""> <t t-else="">
<t t-set="t_balance" <t t-set="t_balance" t-value="Math.round(t_balance+account_line.balance,2)" />
t-value="Math.round(t_balance+account_line.balance,2)"/> <t t-esc="t_balance" t-options='{"widget": "float", "precision": 2}' />
<t t-esc="t_balance"
t-options='{"widget": "float", "precision": 2}'/>
<!-- <t t-esc="account_line.balance"/>--> <!-- <t t-esc="account_line.balance"/>-->
<!-- <t t-esc="Math.round(account_line.balance * Math.pow(10, 2)) / Math.pow(10, 2)"/>--> <!-- <t t-esc="Math.round(account_line.balance * Math.pow(10, 2)) / Math.pow(10, 2)"/>-->
<!-- <t t-esc="account_line.currency_code"/>--> <!-- <t t-esc="account_line.currency_code"/>-->
<t t-esc="currency_symbol"/> <t t-esc="currency_symbol" />
</t> </t>
</td> </td>
</t> </t>
</tr> </tr>
</t> </t>
</tbody> </tbody>
</table> </table>
</td> </td>
</tr> </tr>
</t> </t>
</templates> </templates>

115
dynamic_accounts_report/static/src/xml/partner_ledger_view.xml

@ -6,13 +6,12 @@
Partner Ledger Partner Ledger
</h1> </h1>
</div> </div>
<div> <div>
<div class="filter_view_tb"></div> <div class="filter_view_tb"/>
</div> </div>
<br></br> <br/>
<div> <div>
<div class="table_view_tb" style="right:20px;"></div> <div class="table_view_tb" style="right:20px;"/>
</div> </div>
</div> </div>
</t> </t>
@ -28,7 +27,6 @@
<th style="text-align:right;">Balance</th> <th style="text-align:right;">Balance</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<t t-set="none_value" t-value="_"/> <t t-set="none_value" t-value="_"/>
<t t-foreach="report_lines" t-as="account"> <t t-foreach="report_lines" t-as="account">
@ -42,12 +40,11 @@
style="border: 0px solid black;"> style="border: 0px solid black;">
<i class="fa fa-caret-down" role="img" <i class="fa fa-caret-down" role="img"
aria-label="Unfolded" aria-label="Unfolded"
title="Unfolded"></i> title="Unfolded"/>
<span> <span>
<t t-esc="account['name']"/> <t t-esc="account['name']"/>
</span> </span>
</td> </td>
<t t-if="currency[1] == 'before'"> <t t-if="currency[1] == 'before'">
<td style="text-align:right;"> <td style="text-align:right;">
<t t-esc="currency[0]"/> <t t-esc="currency[0]"/>
@ -61,7 +58,6 @@
<t t-esc="currency[0]"/> <t t-esc="currency[0]"/>
<t t-raw="account['balance']"/> <t t-raw="account['balance']"/>
</td> </td>
</t> </t>
<t t-else=""> <t t-else="">
<td style="text-align:right;"> <td style="text-align:right;">
@ -112,12 +108,12 @@
<br></br> <br></br>
<div class="sub_container_right row" <div class="sub_container_right row"
style="width:30%;height:3%;top:0px;position: relative;"> style="width:30%;height:3%;top:0px;position: relative;">
<!--Time Range filter-->
<div class="time_range" style=""> <div class="time_range" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-calendar" title="Dates" role="img" <span class="fa fa-calendar" title="Dates" role="img"
aria-label="Dates"></span> aria-label="Dates"/>
Date Range Date Range
</a> </a>
<div class="dropdown-menu" role="menu"> <div class="dropdown-menu" role="menu">
@ -135,15 +131,13 @@
data-bs-toggle="datetimepicker"> data-bs-toggle="datetimepicker">
<span class="input-group-text"> <span class="input-group-text">
<span class="fa fa-calendar" role="img" <span class="fa fa-calendar" role="img"
aria-label="Calendar"></span> aria-label="Calendar"/>
</span> </span>
</div> </div>
</div> </div>
<label class="" for="date_to">End Date :</label> <label class="" for="date_to">End Date :</label>
<div class="input-group date" id="date_to" <div class="input-group date" id="date_to"
data-target-input="nearest"> data-target-input="nearest">
<input type="text" name="date_to" <input type="text" name="date_to"
class="form-control datetimepicker-input" class="form-control datetimepicker-input"
data-target="#date_to" data-target="#date_to"
@ -153,7 +147,7 @@
data-bs-toggle="datetimepicker"> data-bs-toggle="datetimepicker">
<span class="input-group-text"> <span class="input-group-text">
<span class="fa fa-calendar" role="img" <span class="fa fa-calendar" role="img"
aria-label="Calendar"></span> aria-label="Calendar"/>
</span> </span>
</div> </div>
</div> </div>
@ -161,10 +155,11 @@
</div> </div>
</div> </div>
</div> </div>
<!--Partner filter-->
<div class="partner_filter" style=""> <div class="partner_filter" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-users"></span> <span class="fa fa-users"/>
Partners: Partners:
</a> </a>
<select class="dropdown-menu partners " name="states[]" <select class="dropdown-menu partners " name="states[]"
@ -176,56 +171,52 @@
</option> </option>
</t> </t>
</select> </select>
<span id="partner_res"></span> <span id="partner_res"/>
</div> </div>
<!--Account type filter-->
<div class="acccount_type_filter"> <div class="account_type_filter">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-book"></span> <span class="fa fa-book"/>
Account Type Account Type
</a> </a>
<select class="dropdown-menu type" name="states[]" <select id="account_type" class="dropdown-menu type" name="states[]">
multiple="multiple"> <div role="separator" class="dropdown-divider"/>
<t t-foreach="filter_data.account_type_list" <option value="all">All</option>
t-as="type"> <option value="asset_receivable">Receivable</option>
<option t-attf-value="{{type[0]}}"> <option value="liability_payable">Payable</option>
<t t-esc="type[1]"/>
</option>
</t>
</select> </select>
<span id="type_res"></span> <span id="type_res"/>
</div> </div>
<!--category_filter-->
<div class="category_filter"> <div class="category_filter">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-filter"></span> <span class="fa fa-filter"/>
Partner tag: Partner tag:
</a> </a>
<select class="dropdown-menu category" name="states[]" <select class="dropdown-menu category" name="states[]"
multiple="multiple"> multiple="multiple">
<t t-foreach="filter_data.category_list" <t t-foreach="filter_data.category_list"
t-as="category"> t-as="category">
<t t-log="category"/>
<option t-attf-value="{{category[0]}}"> <option t-attf-value="{{category[0]}}">
<t t-esc="category[1]"/> <t t-esc="category[1]"/>
</option> </option>
</t> </t>
</select> </select>
<span id="category_res"></span> <span id="category_res"/>
</div> </div>
<!--journals_filter-->
<div class="journals_filter" style=""> <div class="journals_filter" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-book"></span> <span class="fa fa-book"/>
Journals: Journals:
</a> </a>
<select class="dropdown-menu journals" name="states[]" <select class="dropdown-menu journals" name="states[]"
multiple="multiple"> multiple="multiple">
<div role="separator" class="dropdown-divider"></div> <div role="separator" class="dropdown-divider"/>
<t t-foreach="filter_data.journals_list" <t t-foreach="filter_data.journals_list"
t-as="journal"> t-as="journal">
@ -240,8 +231,6 @@
<div role="separator" <div role="separator"
class="dropdown-divider"/> class="dropdown-divider"/>
</t> </t>
<t t-else=""> <t t-else="">
<option t-attf-value="{{journal[0]}}"> <option t-attf-value="{{journal[0]}}">
<t t-esc="journal[1]"/> <t t-esc="journal[1]"/>
@ -249,22 +238,22 @@
</t> </t>
</t> </t>
</select> </select>
<span id="journal_res"></span> <span id="journal_res"/>
</div> </div>
<!--Account filter-->
<div class="acc_filter"> <div class="acc_filter">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-book"></span> <span class="fa fa-book"/>
Accounts: Accounts:
</a> </a>
<select class="dropdown-menu account" name="states[]" <select class="dropdown-menu account-partner" name="states[]"
multiple="multiple"> multiple="multiple">
<t t-foreach="filter_data.accounts_list" <t t-foreach="filter_data.accounts_list"
t-as="account"> t-as="account">
<t t-if="account[0]=='divider'"> <t t-if="account[0]=='divider'">
<div role="separator" <div role="separator"
class="dropdown-divider"/> class="dropdown-divider"/>
<option disabled="disabled" role="menuitem" <option disabled="disabled" role="menuitem"
t-attf-value="{{account[0]}}"> t-attf-value="{{account[0]}}">
<t t-esc="account[1]"/> <t t-esc="account[1]"/>
@ -272,8 +261,6 @@
<div role="separator" <div role="separator"
class="dropdown-divider"/> class="dropdown-divider"/>
</t> </t>
<t t-else=""> <t t-else="">
<option t-attf-value="{{account[0]}}"> <option t-attf-value="{{account[0]}}">
<t t-esc="account[1]"/> <t t-esc="account[1]"/>
@ -281,40 +268,37 @@
</t> </t>
</t> </t>
</select> </select>
<span id="account_res"></span> <span id="account_res"/>
</div> </div>
<!--Target filter-->
<div class="search-Target-move" style=""> <div class="search-Target-move" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-filter"></span> <span class="fa fa-filter"/>
Target Move: Target Move:
</a> </a>
<select id="entries" class="dropdown-menu target_move" <select id="entries" class="dropdown-menu target_move"
name="states[]"> name="states[]">
<div role="separator" class="dropdown-divider"></div> <div role="separator" class="dropdown-divider"/>
<option value="Posted">Posted Entries</option> <option value="Posted">Posted Entries</option>
<option value="All">All Entries</option> <option value="All">All Entries</option>
</select> </select>
<span id="post_res"></span> <span id="post_res"/>
</div> </div>
<!--Reconciled filter-->
<div class="search-Reconciled" style=""> <div class="search-Reconciled" style="">
<a type="button" class="dropdown-toggle" <a type="button" class="dropdown-toggle"
data-bs-toggle="dropdown"> data-bs-toggle="dropdown">
<span class="fa fa-filter"></span> <span class="fa fa-filter"/>
Reconciled status: Reconciled status:
</a> </a>
<select id="reconciled" class="dropdown-menu reconciled" <select id="reconciled" class="dropdown-menu reconciled"
name="states[]"> name="states[]">
<div role="separator" class="dropdown-divider"></div> <div role="separator" class="dropdown-divider"/>
<option value="unreconciled">Unreconciled</option>
<option value="all">All</option> <option value="all">All</option>
<option value="unreconciled">Unreconciled</option>
</select> </select>
<span id="reconciled_res"></span> <span id="reconciled_res"/>
</div> </div>
<div style=""> <div style="">
<button type="button" id="apply_filter" <button type="button" id="apply_filter"
@ -322,12 +306,7 @@
style="top:0px;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD;"> style="top:0px;height:30px;color:white;background-color: #00A0AD;border-color: #00A0AD;">
Apply Apply
</button> </button>
</div> </div>
<!-- </div>-->
<!-- </div>-->
</div> </div>
</div> </div>
</t> </t>
@ -351,7 +330,6 @@
</thead> </thead>
<tbody> <tbody>
<t t-foreach="account_data" t-as="account_line"> <t t-foreach="account_data" t-as="account_line">
<t t-set="style" t-value="'text-align:right;'"/> <t t-set="style" t-value="'text-align:right;'"/>
<t t-set="styleleft" t-value="'text-align:left;'"/> <t t-set="styleleft" t-value="'text-align:left;'"/>
<tr> <tr>
@ -360,7 +338,7 @@
<div class="dropdown dropdown-toggle"> <div class="dropdown dropdown-toggle">
<a data-bs-toggle="dropdown" <a data-bs-toggle="dropdown"
href="#"> href="#">
<span class="caret"></span> <span class="caret"/>
<span> <span>
<t t-esc="account_line.ldate"/> <t t-esc="account_line.ldate"/>
</span> </span>
@ -373,7 +351,6 @@
tabindex="-1" href="#" tabindex="-1" href="#"
t-att-data-move-id="account_line.move_id"> t-att-data-move-id="account_line.move_id">
View Source move View Source move
</a> </a>
</li> </li>
</ul> </ul>
@ -382,7 +359,6 @@
</td> </td>
<td> <td>
<t t-esc="account_line.lcode"/> <t t-esc="account_line.lcode"/>
</td> </td>
<td> <td>
<span> <span>
@ -399,19 +375,15 @@
<td t-att-style="style" class="amt"> <td t-att-style="style" class="amt">
<t t-raw="account_line.currency_code"/> <t t-raw="account_line.currency_code"/>
<t t-raw="account_line.debit"/> <t t-raw="account_line.debit"/>
</td> </td>
<td t-att-style="style" class="amt"> <td t-att-style="style" class="amt">
<t t-raw="account_line.currency_code"/> <t t-raw="account_line.currency_code"/>
<t t-raw="account_line.credit"/> <t t-raw="account_line.credit"/>
</td> </td>
<td t-att-style="style" class="amt"> <td t-att-style="style" class="amt">
<t t-raw="account_line.currency_code"/> <t t-raw="account_line.currency_code"/>
<t t-raw="account_line.balance"/> <t t-raw="account_line.balance"/>
</td> </td>
</t> </t>
<t t-else=""> <t t-else="">
<td t-att-style="style" class="amt"> <td t-att-style="style" class="amt">
@ -426,9 +398,7 @@
<t t-raw="account_line.balance"/> <t t-raw="account_line.balance"/>
<t t-raw="account_line.currency_code"/> <t t-raw="account_line.currency_code"/>
</td> </td>
</t> </t>
</tr> </tr>
</t> </t>
</tbody> </tbody>
@ -436,5 +406,4 @@
</td> </td>
</tr> </tr>
</t> </t>
</templates> </templates>

21
dynamic_accounts_report/wizard/__init__.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from . import general_ledger from . import general_ledger
from . import trial_balance from . import trial_balance
from . import cash_flow from . import cash_flow

115
dynamic_accounts_report/wizard/ageing.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import time import time
from datetime import datetime from datetime import datetime
@ -21,24 +42,20 @@ class AgeingView(models.TransientModel):
period_length = fields.Integer(string='Period Length (days)', period_length = fields.Integer(string='Period Length (days)',
required=True, default=30) required=True, default=30)
date_from = fields.Date(default=lambda *a: time.strftime('%Y-%m-%d')) date_from = fields.Date(default=lambda *a: time.strftime('%Y-%m-%d'))
result_selection = fields.Selection([('customer', 'Receivable Accounts'), result_selection = fields.Selection([('customer',
'Receivable Accounts'),
('supplier', 'Payable Accounts'), ('supplier', 'Payable Accounts'),
('customer_supplier', ('customer_supplier',
'Receivable and Payable Accounts') 'Receivable and Payable Accounts')
], string="Partner's", required=True, ], string="Partner's", required=True,
default='customer') default='customer')
partner_ids = fields.Many2many('res.partner', string='Partner')
partner_ids = fields.Many2many( partner_category_ids = fields.Many2many('res.partner.category',
'res.partner', string='Partner' string='Partner Tag')
)
partner_category_ids = fields.Many2many(
'res.partner.category', string='Partner Tag',
)
@api.model @api.model
def view_report(self, option): def view_report(self, option):
r = self.env['account.partner.ageing'].search([('id', '=', option[0])]) r = self.env['account.partner.ageing'].search([('id', '=', option[0])])
data = { data = {
'result_selection': r.result_selection, 'result_selection': r.result_selection,
'model': self, 'model': self,
@ -47,17 +64,13 @@ class AgeingView(models.TransientModel):
'period_length': r.period_length, 'period_length': r.period_length,
'partners': r.partner_ids, 'partners': r.partner_ids,
'partner_tags': r.partner_category_ids, 'partner_tags': r.partner_category_ids,
} }
if r.date_from: if r.date_from:
data.update({ data.update({
'date_from': r.date_from, 'date_from': r.date_from,
}) })
filters = self.get_filter(option) filters = self.get_filter(option)
records = self._get_report_values(data) records = self._get_report_values(data)
currency = self._get_currency() currency = self._get_currency()
return { return {
'name': "Partner Ageing", 'name': "Partner Ageing",
@ -71,7 +84,6 @@ class AgeingView(models.TransientModel):
def get_filter(self, option): def get_filter(self, option):
data = self.get_filter_data(option) data = self.get_filter_data(option)
filters = {} filters = {}
if data.get('target_move'): if data.get('target_move'):
filters['target_move'] = data.get('target_move') filters['target_move'] = data.get('target_move')
if data.get('date_from'): if data.get('date_from'):
@ -82,48 +94,42 @@ class AgeingView(models.TransientModel):
filters['result_selection'] = 'Payable' filters['result_selection'] = 'Payable'
else: else:
filters['result_selection'] = 'Receivable and Payable' filters['result_selection'] = 'Receivable and Payable'
if data.get('partners'): if data.get('partners'):
filters['partners'] = self.env['res.partner'].browse( filters['partners'] = self.env['res.partner'].browse(
data.get('partners')).mapped('name') data.get('partners')).mapped('name')
else: else:
filters['partners'] = ['All'] filters['partners'] = ['All']
if data.get('partner_tags', []): if data.get('partner_tags', []):
filters['partner_tags'] = self.env['res.partner.category'].browse( filters['partner_tags'] = self.env['res.partner.category'].browse(
data.get('partner_tags', [])).mapped('name') data.get('partner_tags', [])).mapped('name')
else: else:
filters['partner_tags'] = ['All'] filters['partner_tags'] = ['All']
filters['company_id'] = '' filters['company_id'] = ''
filters['company_name'] = data.get('company_name') filters['company_name'] = data.get('company_name')
filters['partners_list'] = data.get('partners_list') filters['partners_list'] = data.get('partners_list')
filters['category_list'] = data.get('category_list') filters['category_list'] = data.get('category_list')
filters['company_name'] = data.get('company_name') filters['company_name'] = data.get('company_name')
filters['target_move'] = data.get('target_move').capitalize() filters['target_move'] = data.get('target_move').capitalize()
return filters return filters
def get_filter_data(self, option): def get_filter_data(self, option):
r = self.env['account.partner.ageing'].search([('id', '=', option[0])]) r = self.env['account.partner.ageing'].search([('id', '=', option[0])])
default_filters = {} default_filters = {}
company_id = self.env.companies company_id = self.env.companies
company_domain = [('company_id', 'in', company_id.ids)] # company_domain = [('company_id', 'in', company_id.ids)]
partner = r.partner_ids if r.partner_ids else self.env[ partner = r.partner_ids if r.partner_ids else self.env[
'res.partner'].search([]) 'res.partner'].search([])
categories = r.partner_category_ids if r.partner_category_ids \ categories = r.partner_category_ids if r.partner_category_ids \
else self.env['res.partner.category'].search([]) else self.env['res.partner.category'].search([])
filter_dict = { filter_dict = {
'partners': r.partner_ids.ids, 'partners': r.partner_ids.ids,
'partner_tags': r.partner_category_ids.ids, 'partner_tags': r.partner_category_ids.ids,
'company_id': company_id.ids, 'company_id': company_id.ids,
'date_from': r.date_from, 'date_from': r.date_from,
'target_move': r.target_move, 'target_move': r.target_move,
'result_selection': r.result_selection, 'result_selection': r.result_selection,
'partners_list': [(p.id, p.name) for p in partner], 'partners_list': [(p.id, p.name) for p in partner],
'category_list': [(c.id, c.name) for c in categories], 'category_list': [(c.id, c.display_name) for c in categories],
'company_name': ', '.join(self.env.companies.mapped('name')), 'company_name': ', '.join(self.env.companies.mapped('name')),
} }
filter_dict.update(default_filters) filter_dict.update(default_filters)
@ -137,18 +143,16 @@ class AgeingView(models.TransientModel):
elif data['result_selection'] == 'supplier': elif data['result_selection'] == 'supplier':
account_type = ['liability_payable'] account_type = ['liability_payable']
else: else:
account_type = ['liability_payable', 'asset_receivable'] account_type = ['payable', 'receivable']
target_move = data['target_move'] target_move = data['target_move']
partners = data.get('partners') partners = data.get('partners')
if data['partner_tags']: if data['partner_tags']:
partners = self.env['res.partner'].search( partners = self.env['res.partner'].search(
[('category_id', 'in', data['partner_tags'].ids)]) [('category_id', 'in', data['partner_tags'].ids)])
account_res = self._get_partner_move_lines(data, partners, date_from, account_res = self._get_partner_move_lines(data, partners, date_from,
target_move, target_move,
account_type, account_type,
data['period_length']) data['period_length'])
return { return {
'doc_ids': self.ids, 'doc_ids': self.ids,
'docs': docs, 'docs': docs,
@ -185,7 +189,6 @@ class AgeingView(models.TransientModel):
def _get_partner_move_lines(self, data, partners, date_from, target_move, def _get_partner_move_lines(self, data, partners, date_from, target_move,
account_type, account_type,
period_length): period_length):
periods = {} periods = {}
start = datetime.strptime(date_from, "%Y-%m-%d") start = datetime.strptime(date_from, "%Y-%m-%d")
date_from = datetime.strptime(date_from, "%Y-%m-%d").date() date_from = datetime.strptime(date_from, "%Y-%m-%d").date()
@ -206,17 +209,13 @@ class AgeingView(models.TransientModel):
total = [] total = []
cr = self.env.cr cr = self.env.cr
user_company = self.env.company user_company = self.env.company
user_currency = user_company.currency_id user_currency = user_company.currency_id
ResCurrency = self.env['res.currency'].with_context(date=date_from) ResCurrency = self.env['res.currency'].with_context(date=date_from)
# company_ids = self._context.get('company_ids') or [user_company.id]
company_ids = self.env.companies.ids company_ids = self.env.companies.ids
move_state = ['draft', 'posted'] move_state = ['draft', 'posted']
if target_move == 'posted': if target_move == 'posted':
move_state = ['posted'] move_state = ['posted']
arg_list = (tuple(move_state), tuple(account_type)) arg_list = (tuple(move_state), tuple(account_type))
reconciliation_clause = '(l.reconciled IS FALSE)' reconciliation_clause = '(l.reconciled IS FALSE)'
cr.execute( cr.execute(
'SELECT debit_move_id, credit_move_id FROM account_partial_reconcile where max_date > %s', 'SELECT debit_move_id, credit_move_id FROM account_partial_reconcile where max_date > %s',
@ -241,7 +240,6 @@ class AgeingView(models.TransientModel):
AND (l.move_id = am.id) AND (l.move_id = am.id)
AND (am.state IN %s) AND (am.state IN %s)
AND (account_account.account_type IN %s) AND (account_account.account_type IN %s)
AND ''' + reconciliation_clause + ''' AND ''' + reconciliation_clause + '''
AND (l.date <= %s) AND (l.date <= %s)
AND l.company_id IN %s AND l.company_id IN %s
@ -249,33 +247,29 @@ class AgeingView(models.TransientModel):
ORDER BY UPPER(res_partner.name)''' ORDER BY UPPER(res_partner.name)'''
cr.execute(query, arg_list) cr.execute(query, arg_list)
partners = cr.dictfetchall() partners = cr.dictfetchall()
# put a total of 0 # put a total of 0
for i in range(7): for i in range(7):
total.append(0) total.append(0)
# Build a string like (1,2,3) for easy use in SQL query # Build a string like (1,2,3) for easy use in SQL query
partner_ids = [partner['partner_id'] for partner in partners if partner_ids = [partner['partner_id'] for partner in partners if
partner['partner_id']] partner['partner_id']]
lines = dict( lines = dict(
(partner['partner_id'] or False, []) for partner in partners) (partner['partner_id'] or False, []) for partner in partners)
if not partner_ids: if not partner_ids:
return [], [], {} return [], [], {}
# This dictionary will store the not due amount of all partners # This dictionary will store the not due amount of all partners
undue_amounts = {} undue_amounts = {}
query = '''SELECT l.id query = '''SELECT l.id
FROM account_move_line AS l, account_account, account_move am FROM account_move_line AS l, account_account, account_move am
WHERE (l.account_id = account_account.id) AND (l.move_id = am.id) WHERE (l.account_id = account_account.id)
AND (am.state IN %s) AND (l.move_id = am.id)
AND (account_account.account_type IN %s) AND (am.state IN %s)
AND (COALESCE(l.date_maturity,l.date) >= %s)\ AND (account_account.account_type IN %s)
AND ((l.partner_id IN %s) OR (l.partner_id IS NULL)) AND (COALESCE(l.date_maturity,l.date) >= %s)\
AND (l.date <= %s) AND ((l.partner_id IN %s) OR (l.partner_id IS NULL))
AND l.company_id IN %s''' AND (l.date <= %s)
AND l.company_id IN %s'''
cr.execute(query, ( cr.execute(query, (
tuple(move_state), tuple(account_type), date_from, tuple(move_state), tuple(account_type), date_from,
tuple(partner_ids), date_from, tuple(company_ids))) tuple(partner_ids), date_from, tuple(company_ids)))
@ -291,7 +285,6 @@ class AgeingView(models.TransientModel):
jrnl_id = line.journal_id.name jrnl_id = line.journal_id.name
currency_id = line.company_id.currency_id.position currency_id = line.company_id.currency_id.position
currency_symbol = line.company_id.currency_id.symbol currency_symbol = line.company_id.currency_id.symbol
if partner_id not in undue_amounts: if partner_id not in undue_amounts:
undue_amounts[partner_id] = 0.0 undue_amounts[partner_id] = 0.0
line_amount = ResCurrency._compute(line.company_id.currency_id, line_amount = ResCurrency._compute(line.company_id.currency_id,
@ -325,42 +318,35 @@ class AgeingView(models.TransientModel):
'period6': 6, 'period6': 6,
}) })
# Use one query per period and store results in history (a list variable) # Use one query per period and store results in history (a list
# Each history will contain: history[1] = {'<partner_id>': <partner_debit-credit>} # variable) Each history will contain: history[1] = {'<partner_id>':
# <partner_debit-credit>}
history = [] history = []
for i in range(5): for i in range(5):
args_list = ( args_list = (
tuple(move_state), tuple(account_type), tuple(partner_ids),) tuple(move_state), tuple(account_type), tuple(partner_ids),)
dates_query = '(COALESCE(l.date_maturity,l.date)' dates_query = '(COALESCE(l.date_maturity,l.date)'
if periods[str(i)]['start'] and periods[str(i)]['stop']: if periods[str(i)]['start'] and periods[str(i)]['stop']:
dates_query += ' BETWEEN %s AND %s)' dates_query += ' BETWEEN %s AND %s)'
args_list += ( args_list += (
periods[str(i)]['start'], periods[str(i)]['stop']) periods[str(i)]['start'], periods[str(i)]['stop'])
elif periods[str(i)]['start']: elif periods[str(i)]['start']:
dates_query += ' >= %s)' dates_query += ' >= %s)'
args_list += (periods[str(i)]['start'],) args_list += (periods[str(i)]['start'],)
else: else:
dates_query += ' <= %s)' dates_query += ' <= %s)'
args_list += (periods[str(i)]['stop'],) args_list += (periods[str(i)]['stop'],)
args_list += (date_from, tuple(company_ids)) args_list += (date_from, tuple(company_ids))
query = '''SELECT l.id query = '''SELECT l.id
FROM account_move_line AS l, account_account, account_move am FROM account_move_line AS l, account_account, account_move am
WHERE (l.account_id = account_account.id) AND (l.move_id = am.id) WHERE (l.account_id = account_account.id) AND (l.move_id = am.id)
AND (am.state IN %s) AND (am.state IN %s)
AND (account_account.account_type IN %s) AND (account_account.account_type IN %s)
AND ((l.partner_id IN %s) OR (l.partner_id IS NULL)) AND ((l.partner_id IN %s) OR (l.partner_id IS NULL))
AND ''' + dates_query + ''' AND ''' + dates_query + '''
AND (l.date <= %s) AND (l.date <= %s)
AND l.company_id IN %s''' AND l.company_id IN %s'''
cr.execute(query, args_list) cr.execute(query, args_list)
partners_amount = {} partners_amount = {}
aml_ids = cr.fetchall() aml_ids = cr.fetchall()
aml_ids = aml_ids and [x[0] for x in aml_ids] or [] aml_ids = aml_ids and [x[0] for x in aml_ids] or []
@ -495,7 +481,6 @@ class AgeingView(models.TransientModel):
if partner[ if partner[
'partner_id'] in undue_amounts: # Making sure this partner actually was found by the query 'partner_id'] in undue_amounts: # Making sure this partner actually was found by the query
undue_amt = undue_amounts[partner['partner_id']] undue_amt = undue_amounts[partner['partner_id']]
total[6] = total[6] + undue_amt total[6] = total[6] + undue_amt
values['direction'] = undue_amt values['direction'] = undue_amt
for rec in lines: for rec in lines:
@ -505,7 +490,6 @@ class AgeingView(models.TransientModel):
if not float_is_zero(values['direction'], if not float_is_zero(values['direction'],
precision_rounding=self.env.company.currency_id.rounding): precision_rounding=self.env.company.currency_id.rounding):
at_least_one_amount = True at_least_one_amount = True
for i in range(5): for i in range(5):
during = False during = False
if partner['partner_id'] in history[i]: if partner['partner_id'] in history[i]:
@ -531,7 +515,6 @@ class AgeingView(models.TransientModel):
else: else:
values['name'] = _('Unknown Partner') values['name'] = _('Unknown Partner')
values['trust'] = False values['trust'] = False
if at_least_one_amount or ( if at_least_one_amount or (
self._context.get('include_nullified_amount') and lines[ self._context.get('include_nullified_amount') and lines[
partner['partner_id']]): partner['partner_id']]):
@ -556,9 +539,7 @@ class AgeingView(models.TransientModel):
report_data_main = json.loads(report_data) report_data_main = json.loads(report_data)
output = io.BytesIO() output = io.BytesIO()
filters = json.loads(data) filters = json.loads(data)
workbook = xlsxwriter.Workbook(output, {'in_memory': True}) workbook = xlsxwriter.Workbook(output, {'in_memory': True})
sheet = workbook.add_worksheet() sheet = workbook.add_worksheet()
head = workbook.add_format({'align': 'center', 'bold': True, head = workbook.add_format({'align': 'center', 'bold': True,
@ -601,7 +582,6 @@ class AgeingView(models.TransientModel):
[lt or '' for lt in [lt or '' for lt in
filters['partner_tags']]), filters['partner_tags']]),
date_head) date_head)
sheet.merge_range('A7:C7', 'Partner', heading) sheet.merge_range('A7:C7', 'Partner', heading)
sheet.write('D7', 'Total', heading) sheet.write('D7', 'Total', heading)
sheet.write('E7', 'Not Due', heading) sheet.write('E7', 'Not Due', heading)
@ -610,7 +590,6 @@ class AgeingView(models.TransientModel):
sheet.write('H7', '60-90', heading) sheet.write('H7', '60-90', heading)
sheet.write('I7', '90-120', heading) sheet.write('I7', '90-120', heading)
sheet.write('J7', '120+', heading) sheet.write('J7', '120+', heading)
lst = [] lst = []
for rec in report_data_main[0]: for rec in report_data_main[0]:
lst.append(rec) lst.append(rec)
@ -623,11 +602,9 @@ class AgeingView(models.TransientModel):
sheet.set_column(9, 4, 15) sheet.set_column(9, 4, 15)
sheet.set_column(10, 5, 15) sheet.set_column(10, 5, 15)
sheet.set_column(11, 6, 15) sheet.set_column(11, 6, 15)
for rec_data in report_data_main[0]: for rec_data in report_data_main[0]:
one_lst = [] one_lst = []
two_lst = [] two_lst = []
row += 1 row += 1
sheet.merge_range(row, col, row, col + 2, rec_data['name'], txt_l) sheet.merge_range(row, col, row, col + 2, rec_data['name'], txt_l)
sheet.write(row, col + 3, rec_data['total'], txt_l) sheet.write(row, col + 3, rec_data['total'], txt_l)
@ -648,7 +625,6 @@ class AgeingView(models.TransientModel):
sheet.write(row, col + 7, '60 - 90', sub_heading) sheet.write(row, col + 7, '60 - 90', sub_heading)
sheet.write(row, col + 8, '90 - 120', sub_heading) sheet.write(row, col + 8, '90 - 120', sub_heading)
sheet.write(row, col + 9, '120 +', sub_heading) sheet.write(row, col + 9, '120 +', sub_heading)
for line_data in rec_data['child_lines']: for line_data in rec_data['child_lines']:
row += 1 row += 1
sheet.write(row, col, line_data.get('move'), txt) sheet.write(row, col, line_data.get('move'), txt)
@ -679,7 +655,6 @@ class AgeingView(models.TransientModel):
sheet.write(row, col + 9, line_data.get('amount'), txt) sheet.write(row, col + 9, line_data.get('amount'), txt)
else: else:
sheet.write(row, col + 9, "0", txt_v) sheet.write(row, col + 9, "0", txt_v)
workbook.close() workbook.close()
output.seek(0) output.seek(0)
response.stream.write(output.read()) response.stream.write(output.read())

58
dynamic_accounts_report/wizard/balance_sheet.py

@ -89,9 +89,9 @@ class BalanceSheetView(models.TransientModel):
# tag_upd = trans_tag # tag_upd = trans_tag
# else: # else:
tag_upd = tag tag_upd = tag
lang = self.env.context.get('lang') or 'en_US'
account_report_id = self.env['account.financial.report'].with_context( account_report_id = self.env['account.financial.report'].with_context(
lang='en_US').search([ lang=lang).search([
('name', 'ilike', tag_upd)]) ('name', 'ilike', tag_upd)])
new_data = {'id': self.id, 'date_from': False, new_data = {'id': self.id, 'date_from': False,
@ -107,7 +107,7 @@ class BalanceSheetView(models.TransientModel):
'date_to': filters['date_to'], 'date_to': filters['date_to'],
'strict_range': False, 'strict_range': False,
'company_id': self.company_id, 'company_id': self.company_id,
'lang': 'en_US'}} 'lang': lang}}
account_lines = self.get_account_lines(new_data) account_lines = self.get_account_lines(new_data)
report_lines = self.view_report_pdf(account_lines, new_data)[ report_lines = self.view_report_pdf(account_lines, new_data)[
@ -390,7 +390,6 @@ class BalanceSheetView(models.TransientModel):
return res return res
def write(self, vals): def write(self, vals):
if vals.get('target_move'): if vals.get('target_move'):
vals.update({'target_move': vals.get('target_move').lower()}) vals.update({'target_move': vals.get('target_move').lower()})
if vals.get('journal_ids'): if vals.get('journal_ids'):
@ -414,12 +413,6 @@ class BalanceSheetView(models.TransientModel):
if not vals.get('account_tag_ids'): if not vals.get('account_tag_ids'):
vals.update({'account_tag_ids': [(5,)]}) vals.update({'account_tag_ids': [(5,)]})
# if vals.get('analytic_tag_ids'):
# vals.update({'analytic_tag_ids': [(4, j) for j in
# vals.get('analytic_tag_ids')]})
# if not vals.get('analytic_tag_ids'):
# vals.update({'analytic_tag_ids': [(5,)]})
res = super(BalanceSheetView, self).write(vals) res = super(BalanceSheetView, self).write(vals)
return res return res
@ -439,53 +432,64 @@ class BalanceSheetView(models.TransientModel):
'm').replace( 'm').replace(
'account_move_line', 'l') 'account_move_line', 'l')
new_final_filter = final_filters new_final_filter = final_filters
if data['target_move'] == 'posted': if data['target_move'] == 'posted':
new_final_filter += " AND m.state = 'posted'" new_final_filter += " AND m.state = 'posted'"
else: else:
new_final_filter += " AND m.state in ('draft','posted')" new_final_filter += " AND m.state in ('draft','posted')"
if data.get('date_from'): if data.get('date_from'):
new_final_filter += " AND l.date >= '%s'" % data.get('date_from') new_final_filter += " AND l.date >= '%s'" % data.get('date_from')
if data.get('date_to'): if data.get('date_to'):
new_final_filter += " AND l.date <= '%s'" % data.get('date_to') new_final_filter += " AND l.date <= '%s'" % data.get('date_to')
if data['journals']: if data['journals']:
new_final_filter += ' AND j.id IN %s' % str( new_final_filter += ' AND j.id IN %s' % str(
tuple(data['journals'].ids) + tuple([0])) tuple(data['journals'].ids) + tuple([0]))
if data.get('accounts'): if data.get('accounts'):
WHERE = "WHERE l.account_id IN %s" % str( WHERE = "WHERE l.account_id IN %s" % str(
tuple(data.get('accounts').ids) + tuple([0])) tuple(data.get('accounts').ids) + tuple([0]))
else: else:
WHERE = "WHERE l.account_id IN %s" WHERE = "WHERE l.account_id IN %s"
if data.get('analytics'):
if data['analytics']: WHERE += ' AND an.id IN %s' % str(
WHERE += ' AND anl.id IN %s' % str(
tuple(data.get('analytics').ids) + tuple([0])) tuple(data.get('analytics').ids) + tuple([0]))
if data.get('account_tags'):
WHERE += ' AND act.id IN %s' % str(tuple(data.get('account_tags').ids)+ tuple([0]))
# if data['analytic_tags']: # if data['analytic_tags']:
# WHERE += ' AND anltag.account_analytic_tag_id IN %s' % str( # WHERE += ' AND anltag.account_analytic_tag_id IN %s' % str(
# tuple(data.get('analytic_tags').ids) + tuple([0])) # tuple(data.get('analytic_tags').ids) + tuple([0]))
# Get move lines base on sql query and Calculate the total balance of move lines # Get move lines base on sql query and Calculate the total balance of move lines
sql = ('''SELECT l.account_id AS account_id, a.code AS code,a.id AS id, a.name AS name, ROUND(COALESCE(SUM(l.debit),0),2) AS debit, ROUND(COALESCE(SUM(l.credit),0),2) AS credit, ROUND(COALESCE(SUM(l.balance),0),2) AS balance sql = ('''SELECT l.account_id AS account_id, a.code AS code,a.id AS id, a.name AS name,
ROUND(COALESCE(SUM(l.debit),0),2) AS debit,
FROM account_move_line l\ ROUND(COALESCE(SUM(l.credit),0),2) AS credit,
JOIN account_move m ON (l.move_id=m.id)\ ROUND(COALESCE(SUM(l.balance),0),2) AS balance,
LEFT JOIN res_currency c ON (l.currency_id=c.id)\ anl.keys, act.name as tag
LEFT JOIN res_partner p ON (l.partner_id=p.id)\ FROM account_move_line l
LEFT JOIN account_account_tag_account_move_line_rel acc ON (acc.account_move_line_id=l.id) JOIN account_move m ON (l.move_id=m.id)
JOIN account_journal j ON (l.journal_id=j.id)\ LEFT JOIN res_currency c ON (l.currency_id=c.id)
JOIN account_account a ON (l.account_id = a.id) ''' LEFT JOIN res_partner p ON (l.partner_id=p.id)
+ WHERE + new_final_filter + ''' GROUP BY l.account_id, a.code, a.name, a.id''') LEFT JOIN account_account_tag_account_move_line_rel acc ON (acc.account_move_line_id=l.id)
JOIN account_journal j ON (l.journal_id=j.id)
JOIN account_account a ON (l.account_id = a.id) LEFT JOIN account_account_account_tag acct ON
(acct.account_account_id = l.account_id)
LEFT JOIN account_account_tag act ON
(act.id = acct.account_account_tag_id)
LEFT JOIN LATERAL (
SELECT jsonb_object_keys(l.analytic_distribution)::INT
AS keys) anl ON true
LEFT JOIN account_analytic_account an
ON (anl.keys = an.id)'''
+ WHERE + final_filters + ''' GROUP BY l.account_id,
a.code,a.id,a.name,anl.keys, act.name''')
if data.get('accounts'): if data.get('accounts'):
params = tuple(where_params) params = tuple(where_params)
else: else:
params = (tuple(accounts.ids),) + tuple(where_params) params = (tuple(accounts.ids),) + tuple(where_params)
cr.execute(sql, params) cr.execute(sql, params)
account_res = cr.dictfetchall() account_res = cr.dictfetchall()
return account_res return account_res
# for row in cr.dictfetchall(): # for row in cr.dictfetchall():

79
dynamic_accounts_report/wizard/balance_sheet_config.py

@ -1,5 +1,26 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import re import re
from odoo import models, fields, api from odoo import models
class BalanceSheet(models.TransientModel): class BalanceSheet(models.TransientModel):
@ -15,8 +36,8 @@ class BalanceSheet(models.TransientModel):
def set_report_level(rec): def set_report_level(rec):
"""This function is used to set the level of each item. """This function is used to set the level of each item.
This level will be used to set the alignment in the dynamic reports.""" This level will be used to set the alignment in the dynamic
reports."""
level = 1 level = 1
if not rec['parent']: if not rec['parent']:
return level return level
@ -42,10 +63,7 @@ class BalanceSheet(models.TransientModel):
return data return data
def _compute_account_balance(self, accounts): def _compute_account_balance(self, accounts):
""" compute the balance, debit """ compute the balance, debit and credit for the provided accounts"""
and credit for the provided accounts
"""
mapping = { mapping = {
'balance': 'balance':
"COALESCE(SUM(debit),0) - COALESCE(SUM(credit), 0)" "COALESCE(SUM(debit),0) - COALESCE(SUM(credit), 0)"
@ -53,11 +71,9 @@ class BalanceSheet(models.TransientModel):
'debit': "COALESCE(SUM(debit), 0) as debit", 'debit': "COALESCE(SUM(debit), 0) as debit",
'credit': "COALESCE(SUM(credit), 0) as credit", 'credit': "COALESCE(SUM(credit), 0) as credit",
} }
res = {} res = {}
for account in accounts: for account in accounts:
res[account.id] = dict((fn, 0.0) res[account.id] = dict((fn, 0.0) for fn in mapping.keys())
for fn in mapping.keys())
if accounts: if accounts:
tables, where_clause, where_params = ( tables, where_clause, where_params = (
self.env['account.move.line']._query_get()) self.env['account.move.line']._query_get())
@ -74,11 +90,9 @@ class BalanceSheet(models.TransientModel):
filters + filters +
" GROUP BY account_id") " GROUP BY account_id")
params = (tuple(accounts._ids),) + tuple(where_params) params = (tuple(accounts._ids),) + tuple(where_params)
self.env.cr.execute(request, params) self.env.cr.execute(request, params)
for row in self.env.cr.dictfetchall(): for row in self.env.cr.dictfetchall():
res[row['id']] = row res[row['id']] = row
return res return res
def _compute_report_balance(self, reports): def _compute_report_balance(self, reports):
@ -101,28 +115,13 @@ class BalanceSheet(models.TransientModel):
if report.type == 'accounts': if report.type == 'accounts':
# it's the sum of the linked accounts # it's the sum of the linked accounts
res[report.id]['account'] = self._compute_account_balance( res[report.id]['account'] = self._compute_account_balance(
report.account_ids report.account_ids)
) for value in res[report.id]['account'].values():
for value in \
res[report.id]['account'].values():
for field in fields: for field in fields:
res[report.id][field] += value.get(field) res[report.id][field] += value.get(field)
elif report.type == 'account_type': elif report.type == 'account_type':
# it's the sum the leaf accounts # it's the sum the leaf accounts
# with such an account type # with such an account type
"""Eccccc"""
# if report.id == 11:
# states = ['liability_payable','equity','liability_non_current','liability_current']
# elif report.id ==9:
# states = ['asset_fixed','asset_non_current','asset_current','asset_cash','asset_receivable']
# elif report.id ==9:
# states = ['asset_fixed','asset_non_current','asset_current','asset_cash','asset_receivable']
# else:
# states = [report.account_type_ids]
"""end"""
accounts = self.env['account.account'].search([ accounts = self.env['account.account'].search([
('account_type', 'in', ('account_type', 'in',
report.account_ids.mapped('account_type')) report.account_ids.mapped('account_type'))
@ -159,8 +158,8 @@ class BalanceSheet(models.TransientModel):
res[report_id]['comp_bal'] = value['balance'] res[report_id]['comp_bal'] = value['balance']
report_acc = res[report_id].get('account') report_acc = res[report_id].get('account')
if report_acc: if report_acc:
for account_id, val in \ for account_id, val in comparison_res[report_id
comparison_res[report_id].get('account').items(): ].get('account').items():
report_acc[account_id]['comp_bal'] = val['balance'] report_acc[account_id]['comp_bal'] = val['balance']
for report in child_reports: for report in child_reports:
r_name = str(report.name) r_name = str(report.name)
@ -171,11 +170,9 @@ class BalanceSheet(models.TransientModel):
report.parent_id.id) report.parent_id.id)
else: else:
p_name = False p_name = False
child_ids = [] child_ids = []
for chd in report.children_ids: for chd in report.children_ids:
child_ids.append(chd.id) child_ids.append(chd.id)
vals = { vals = {
'r_id': report.id, 'r_id': report.id,
'p_id': report.parent_id.id, 'p_id': report.parent_id.id,
@ -201,7 +198,6 @@ class BalanceSheet(models.TransientModel):
if data['enable_filter']: if data['enable_filter']:
vals['balance_cmp'] = res[report.id]['comp_bal'] * int( vals['balance_cmp'] = res[report.id]['comp_bal'] * int(
report.sign) report.sign)
lines.append(vals) lines.append(vals)
if report.display_detail == 'no_detail': if report.display_detail == 'no_detail':
# the rest of the loop is # the rest of the loop is
@ -209,7 +205,6 @@ class BalanceSheet(models.TransientModel):
# financial report, so it's not needed here. # financial report, so it's not needed here.
continue continue
if res[report.id].get('account'): if res[report.id].get('account'):
sub_lines = [] sub_lines = []
for account_id, value \ for account_id, value \
in res[report.id]['account'].items(): in res[report.id]['account'].items():
@ -228,16 +223,16 @@ class BalanceSheet(models.TransientModel):
'c_ids': [], 'c_ids': [],
'account': account.id, 'account': account.id,
'code': account.code, 'code': account.code,
'a_id': account.code + re.sub('[^0-9a-zA-Z]+', 'acnt', 'a_id': account.code + re.sub('[^0-9a-zA-Z]+',
'acnt',
account.name) + str( account.name) + str(
account.id), account.id),
'name': account.code + '-' + account.name, 'name': account.code + '-' + account.name,
'balance': value['balance'] * int(report.sign) or 0.0, 'balance': value['balance'] * int(report.sign) or 0.0,
'type': 'account', 'type': 'account',
'parent': r_name + str(report.id), 'parent': r_name + str(report.id),
'level': ( 'level': (report.display_detail ==
report.display_detail == 'detail_with_hierarchy' and 'detail_with_hierarchy' and 4),
4),
'account_type': account.account_type, 'account_type': account.account_type,
} }
if data['debit_credit']: if data['debit_credit']:
@ -259,8 +254,6 @@ class BalanceSheet(models.TransientModel):
flag = True flag = True
if flag: if flag:
sub_lines.append(vals) sub_lines.append(vals)
# sub_lines.append({'r_id': False, 'p_id': 11, 'report_type': 'accounts', 'c_ids': [], 'account': 14, 'code': '211000', 'a_id': '211000AccountacntPayable14', 'name': '211000-Account Payable', 'balance': -2036.77, 'type': 'account', 'parent': 'Liability11', 'level': 4, 'debit': 0.0, 'credit': 2036.77, 'balance_cmp': -2036.77})
lines += sorted(sub_lines, lines += sorted(sub_lines,
key=lambda sub_line: sub_line['name']) key=lambda sub_line: sub_line['name'])
return lines return lines
@ -303,8 +296,8 @@ class BalanceSheet(models.TransientModel):
for j in items: for j in items:
temp = j['id'] temp = j['id']
j['id'] = re.sub('[^0-9a-zA-Z]+', '', i['name']) + str( j['id'] = re.sub('[^0-9a-zA-Z]+', '',
temp) i['name']) + str(temp)
j['p_id'] = str(i['a_id']) j['p_id'] = str(i['a_id'])
j['type'] = 'journal_item' j['type'] = 'journal_item'
journal_items.append(j) journal_items.append(j)

72
dynamic_accounts_report/wizard/cash_flow.py

@ -1,4 +1,24 @@
import time # -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
from datetime import datetime from datetime import datetime
from odoo import models, api, fields from odoo import models, api, fields
@ -18,7 +38,7 @@ class AccountCasgFlow(models.TransientModel):
date_from = fields.Date(string="Start Date", default=str(year)+'-01-01') date_from = fields.Date(string="Start Date", default=str(year)+'-01-01')
date_to = fields.Date(string="End Date", default=fields.Date.today) date_to = fields.Date(string="End Date", default=fields.Date.today)
today = fields.Date("Report Date", default=fields.Date.today) today = fields.Date(string="Report Date", default=fields.Date.today)
levels = fields.Selection([('summary', 'Summary'), levels = fields.Selection([('summary', 'Summary'),
('consolidated', 'Consolidated'), ('consolidated', 'Consolidated'),
('detailed', 'Detailed'), ('detailed', 'Detailed'),
@ -29,11 +49,8 @@ class AccountCasgFlow(models.TransientModel):
'Consolidated: Based on account types.\n' 'Consolidated: Based on account types.\n'
'Detailed: Based on accounts.\n' 'Detailed: Based on accounts.\n'
'Very Detailed: Accounts with their move lines') 'Very Detailed: Accounts with their move lines')
account_ids = fields.Many2many("account.account",
account_ids = fields.Many2many( string="Accounts")
"account.account",
string="Accounts",
)
@api.model @api.model
def view_report(self, option): def view_report(self, option):
@ -52,7 +69,6 @@ class AccountCasgFlow(models.TransientModel):
data.update({ data.update({
'date_to': r.date_to, 'date_to': r.date_to,
}) })
filters = self.get_filter(option) filters = self.get_filter(option)
report_lines = self._get_report_values(data, option) report_lines = self._get_report_values(data, option)
fetched_data = report_lines['fetched_data'] fetched_data = report_lines['fetched_data']
@ -61,7 +77,6 @@ class AccountCasgFlow(models.TransientModel):
journal_res = report_lines['journal_res'] journal_res = report_lines['journal_res']
levels = report_lines['levels'] levels = report_lines['levels']
currency = self._get_currency() currency = self._get_currency()
return { return {
'name': "Cash Flow Statements", 'name': "Cash Flow Statements",
'type': 'ir.actions.client', 'type': 'ir.actions.client',
@ -80,11 +95,13 @@ class AccountCasgFlow(models.TransientModel):
data = self.get_filter_data(option) data = self.get_filter_data(option)
filters = {} filters = {}
if data.get('journal_ids'): if data.get('journal_ids'):
filters['journals'] = self.env['account.journal'].browse(data.get('journal_ids')).mapped('code') filters['journals'] = self.env['account.journal'].browse(
data.get('journal_ids')).mapped('code')
else: else:
filters['journals'] = ['All'] filters['journals'] = ['All']
if data.get('account_ids', []): if data.get('account_ids', []):
filters['accounts'] = self.env['account.account'].browse(data.get('account_ids', [])).mapped('code') filters['accounts'] = self.env['account.account'].browse(
data.get('account_ids', [])).mapped('code')
else: else:
filters['accounts'] = ['All'] filters['accounts'] = ['All']
if data.get('target_move'): if data.get('target_move'):
@ -95,13 +112,11 @@ class AccountCasgFlow(models.TransientModel):
filters['date_to'] = data.get('date_to') filters['date_to'] = data.get('date_to')
if data.get('levels'): if data.get('levels'):
filters['levels'] = data.get('levels') filters['levels'] = data.get('levels')
filters['company_id'] = '' filters['company_id'] = ''
filters['accounts_list'] = data.get('accounts_list') filters['accounts_list'] = data.get('accounts_list')
filters['journals_list'] = data.get('journals_list') filters['journals_list'] = data.get('journals_list')
filters['company_name'] = data.get('company_name') filters['company_name'] = data.get('company_name')
filters['target_move'] = data.get('target_move').capitalize() filters['target_move'] = data.get('target_move').capitalize()
return filters return filters
def get_filter_data(self, option): def get_filter_data(self, option):
@ -109,9 +124,10 @@ class AccountCasgFlow(models.TransientModel):
default_filters = {} default_filters = {}
company_id = self.env.companies company_id = self.env.companies
company_domain = [('company_id', 'in', company_id.ids)] company_domain = [('company_id', 'in', company_id.ids)]
journals = r.journal_ids if r.journal_ids else self.env['account.journal'].search(company_domain) journals = r.journal_ids if r.journal_ids else (
accounts = self.account_ids if self.account_ids else self.env['account.account'].search(company_domain) self.env[('account.journal')].search(company_domain))
accounts = self.account_ids if self.account_ids else (
self.env['account.account'].search(company_domain))
filter_dict = { filter_dict = {
'journal_ids': r.journal_ids.ids, 'journal_ids': r.journal_ids.ids,
'account_ids': self.account_ids.ids, 'account_ids': self.account_ids.ids,
@ -127,7 +143,7 @@ class AccountCasgFlow(models.TransientModel):
filter_dict.update(default_filters) filter_dict.update(default_filters)
return filter_dict return filter_dict
def _get_report_values(self, data, option): def _get_report_values(self, data,option):
cr = self.env.cr cr = self.env.cr
data = self.get_filter(option) data = self.get_filter(option)
company_id = self.env.company company_id = self.env.company
@ -135,7 +151,6 @@ class AccountCasgFlow(models.TransientModel):
symbol = company_id.currency_id.symbol symbol = company_id.currency_id.symbol
rounding = company_id.currency_id.rounding rounding = company_id.currency_id.rounding
position = company_id.currency_id.position position = company_id.currency_id.position
fetched_data = [] fetched_data = []
account_res = [] account_res = []
journal_res = [] journal_res = []
@ -145,18 +160,21 @@ class AccountCasgFlow(models.TransientModel):
if data.get('levels') == 'summary': if data.get('levels') == 'summary':
state = """ AND am.state = 'posted' """ if data.get('target_move') == 'Posted' else '' state = """ AND am.state = 'posted' """ if data.get('target_move') == 'Posted' else ''
state2 = ' AND aml.company_id IN %s' % str(tuple(self.env.companies.ids) + tuple([0])) state2 = ' AND aml.company_id IN %s' % str(tuple(self.env.companies.ids) + tuple([0]))
query3 = """SELECT to_char(am.date, 'Month') as month_part, extract(YEAR from am.date) as year_part, query3 = """SELECT to_char(am.date, 'Month') as month_part,
sum(aml.debit) AS total_debit, sum(aml.credit) AS total_credit, extract(YEAR from am.date) as year_part,
sum(aml.balance) AS total_balance FROM (SELECT am.date, am.id, am.state FROM account_move as am sum(aml.debit) AS total_debit, sum(aml.credit) AS
LEFT JOIN account_move_line aml ON aml.move_id = am.id total_credit,
LEFT JOIN account_account aa ON aa.id = aml.account_id sum(aml.balance) AS total_balance FROM (SELECT am.date,
WHERE am.date BETWEEN '""" + str( am.id, am.state FROM account_move as am
LEFT JOIN account_move_line aml ON aml.move_id = am.id
LEFT JOIN account_account aa ON aa.id = aml.account_id
WHERE am.date BETWEEN '""" + str(
data.get('date_from')) + """' and '""" + str( data.get('date_from')) + """' and '""" + str(
data.get('date_to')) + """' AND aa.account_type='""" + str( data.get('date_to')) + """' AND aa.account_type='""" + str(
account_type_id) + """' """ + state + state2 +""") am account_type_id) + """' """ + state + state2 +""") am
LEFT JOIN account_move_line aml ON aml.move_id = am.id LEFT JOIN account_move_line aml ON aml.move_id = am.id
LEFT JOIN account_account aa ON aa.id = aml.account_id LEFT JOIN account_account aa ON aa.id = aml.account_id
GROUP BY month_part,year_part""" GROUP BY month_part,year_part"""
cr = self._cr cr = self._cr
cr.execute(query3) cr.execute(query3)
fetched_data = cr.dictfetchall() fetched_data = cr.dictfetchall()

22
dynamic_accounts_report/wizard/daybook.py

@ -1,4 +1,26 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import time import time
from datetime import date from datetime import date
from datetime import timedelta, datetime from datetime import timedelta, datetime
from odoo import fields, models, api, _ from odoo import fields, models, api, _

347
dynamic_accounts_report/wizard/general_ledger.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import time import time
from odoo import fields, models, api, _ from odoo import fields, models, api, _
@ -16,21 +37,14 @@ class GeneralView(models.TransientModel):
_name = 'account.general.ledger' _name = 'account.general.ledger'
journal_ids = fields.Many2many('account.journal', journal_ids = fields.Many2many('account.journal',
string='Journals', required=True, string='Journals', required=True,
default=[]) default=[])
account_ids = fields.Many2many( account_ids = fields.Many2many("account.account",
"account.account", string="Accounts")
string="Accounts",
)
account_tag_ids = fields.Many2many("account.account.tag", account_tag_ids = fields.Many2many("account.account.tag",
string="Account Tags") string="Account Tags")
analytic_ids = fields.Many2many("account.analytic.account",
analytic_ids = fields.Many2many( string="Analytic Accounts")
"account.analytic.account", string="Analytic Accounts"
)
# analytic_tag_ids = fields.Many2many("account.analytic.tag", string="Analytic Tags")
display_account = fields.Selection( display_account = fields.Selection(
[('all', 'All'), ('movement', 'With movements'), [('all', 'All'), ('movement', 'With movements'),
('not_zero', 'With balance is not equal to 0')], ('not_zero', 'With balance is not equal to 0')],
@ -39,7 +53,6 @@ class GeneralView(models.TransientModel):
target_move = fields.Selection([('posted', 'All Posted Entries'), target_move = fields.Selection([('posted', 'All Posted Entries'),
('all', 'All Entries')], ('all', 'All Entries')],
string='Target Moves', required=True) string='Target Moves', required=True)
date_from = fields.Date(string='Start Date') date_from = fields.Date(string='Start Date')
date_to = fields.Date(string='End Date') date_to = fields.Date(string='End Date')
@ -47,42 +60,33 @@ class GeneralView(models.TransientModel):
def view_report(self, option, title): def view_report(self, option, title):
r = self.env['account.general.ledger'].search([('id', '=', option[0])]) r = self.env['account.general.ledger'].search([('id', '=', option[0])])
self = r self = r
new_title = '' # Create a dictionary for title to journal type mapping
# todo: title_mapping = {
'General Ledger': 'all',
# to get the english translation of the title 'Bank Book': 'bank',
record_id = self.env['ir.actions.client'].with_context(lang=self.env.user.lang). \ 'Cash Book': 'cash',
search([('name', '=', title)]).id }
trans_title = self.env['ir.actions.client'].with_context(lang='en_US').search([('id', '=', record_id)]).name # Get the translated title if available, or fallback to the original
company_id = self.env.companies.ids # title
if r.journal_ids: trans_title = self.env['ir.actions.client'].with_context(
journals = r.journal_ids lang=self.env.user.lang).search([('name', '=', title)]).name
title_key = trans_title if trans_title else title
# Get journal type based on the title mapping, default to 'all' if not
# found
if title_key in title_mapping:
journal_type = title_mapping[title_key]
else: else:
journals = self.env['account.journal'].search( journal_type = 'all'
company_id = self.env.companies.ids
# Initialize 'journals' based on journal type
if journal_type == 'all':
journals = r.journal_ids or self.env['account.journal'].search(
[('company_id', 'in', company_id)]) [('company_id', 'in', company_id)])
if title == 'General Ledger' or trans_title == 'General Ledger': else:
if r.journal_ids:
journals = r.journal_ids
else:
journals = self.env['account.journal'].search(
[('company_id', 'in', company_id)])
new_title = title
eng_title = 'General Ledger'
if title == 'Bank Book' or trans_title == 'Bank Book':
journals = self.env['account.journal'].search(
[('type', '=', 'bank'), ('company_id', 'in', company_id)])
new_title = title
eng_title = 'Bank Book'
if title == 'Cash Book' or trans_title == 'Cash Book':
journals = self.env['account.journal'].search( journals = self.env['account.journal'].search(
[('type', '=', 'cash'), ('company_id', 'in', company_id)]) [('type', '=', journal_type),
new_title = title ('company_id', 'in', company_id)])
eng_title = 'Cash Book' r.write({'titles': title})
r.write({
'titles': new_title,
})
data = { data = {
'display_account': r.display_account, 'display_account': r.display_account,
'model': self, 'model': self,
@ -91,8 +95,6 @@ class GeneralView(models.TransientModel):
'accounts': r.account_ids, 'accounts': r.account_ids,
'account_tags': r.account_tag_ids, 'account_tags': r.account_tag_ids,
'analytics': r.analytic_ids, 'analytics': r.analytic_ids,
# 'analytic_tags': r.analytic_tag_ids,
} }
if r.date_from: if r.date_from:
data.update({ data.update({
@ -102,13 +104,11 @@ class GeneralView(models.TransientModel):
data.update({ data.update({
'date_to': r.date_to, 'date_to': r.date_to,
}) })
filters = self.get_filter(option) filters = self.get_filter(option)
records = self._get_report_values(data) records = self._get_report_value(data)
currency = self._get_currency() currency = self._get_currency()
return { return {
'name': new_title, 'name': title,
'type': 'ir.actions.client', 'type': 'ir.actions.client',
'tag': 'g_l', 'tag': 'g_l',
'filters': filters, 'filters': filters,
@ -122,46 +122,43 @@ class GeneralView(models.TransientModel):
def get_filter(self, option): def get_filter(self, option):
data = self.get_filter_data(option) data = self.get_filter_data(option)
filters = {} filters = {}
# filter on journal
if data.get('journal_ids'): if data.get('journal_ids'):
filters['journals'] = self.env['account.journal'].browse( filters['journals'] = self.env['account.journal'].browse(
data.get('journal_ids')).mapped('code') data.get('journal_ids')).mapped('code')
else: else:
filters['journals'] = ['All'] filters['journals'] = ['All']
if data.get('account_ids', []):
filters['accounts'] = self.env['account.account'].browse(
data.get('account_ids', [])).mapped('code')
else:
filters['accounts'] = ['All']
if data.get('account_tag_ids', []): if data.get('account_tag_ids', []):
filters['account_tags'] = data.get('account_tag_ids') filters['account_tags'] = data.get('account_tag_ids')
else: else:
filters['account_tags'] = ['All'] filters['account_tags'] = ['All']
# filter on target move
if data.get('target_move'): if data.get('target_move'):
filters['target_move'] = data.get('target_move') filters['target_move'] = data.get('target_move')
# filter on date range
if data.get('date_from'): if data.get('date_from'):
filters['date_from'] = data.get('date_from') filters['date_from'] = data.get('date_from')
if data.get('date_to'): if data.get('date_to'):
filters['date_to'] = data.get('date_to') filters['date_to'] = data.get('date_to')
# filter on accounts
if data.get('account_ids', []):
filters['accounts'] = self.env['account.account'].browse(
data.get('account_ids', [])).mapped('name')
else:
filters['accounts'] = ['All']
# filter on analytic accounts
if data.get('analytic_ids', []): if data.get('analytic_ids', []):
filters['analytics'] = self.env['account.analytic.account'].browse( filters['analytics'] = self.env['account.analytic.account'].browse(
data.get('analytic_ids', [])).mapped('name') data.get('analytic_ids', [])).mapped('name')
else: else:
filters['analytics'] = ['All'] filters['analytics'] = ['All']
# if data.get('analytic_tag_ids', []):
# filters['account_tags'] = self.env['account.account.tag'].browse(
# data.get('account_tag_ids', [])).mapped('name')
# else:
# filters['analytic_tags'] = ['All']
filters['company_id'] = '' filters['company_id'] = ''
filters['accounts_list'] = data.get('accounts_list') filters['accounts_list'] = data.get('accounts_list')
filters['account_tag_list'] = data.get('account_tag_list') filters['account_tag_list'] = data.get('account_tag_list')
filters['journals_list'] = data.get('journals_list') filters['journals_list'] = data.get('journals_list')
filters['analytic_list'] = data.get('analytic_list') filters['analytic_list'] = data.get('analytic_list')
filters['analytic_tag_list'] = data.get('analytic_tag_list')
filters['company_name'] = data.get('company_name') filters['company_name'] = data.get('company_name')
filters['target_move'] = data.get('target_move').capitalize() filters['target_move'] = data.get('target_move').capitalize()
return filters return filters
def get_filter_data(self, option): def get_filter_data(self, option):
@ -172,12 +169,9 @@ class GeneralView(models.TransientModel):
account_tags = r.account_tag_ids if r.account_tag_ids else self.env[ account_tags = r.account_tag_ids if r.account_tag_ids else self.env[
'account.account.tag'].search([]) 'account.account.tag'].search([])
analytics = r.analytic_ids if r.analytic_ids else self.env[ analytics_ids = r.analytic_ids if r.analytic_ids else self.env[
'account.analytic.account'].search( 'account.analytic.account'].search(company_domain,
company_domain) order="company_id, name")
# analytic_tags = r.analytic_tag_ids if r.analytic_tag_ids else self.env[
# 'account.analytic.tag'].search([])
journal_ids = r.journal_ids if r.journal_ids else self.env[ journal_ids = r.journal_ids if r.journal_ids else self.env[
'account.journal'].search(company_domain, order="company_id, name") 'account.journal'].search(company_domain, order="company_id, name")
accounts_ids = self.account_ids if self.account_ids else self.env[ accounts_ids = self.account_ids if self.account_ids else self.env[
@ -189,47 +183,46 @@ class GeneralView(models.TransientModel):
journals.append(('divider', j.company_id.name)) journals.append(('divider', j.company_id.name))
o_company = j.company_id o_company = j.company_id
journals.append((j.id, j.name, j.code)) journals.append((j.id, j.name, j.code))
accounts = [] accounts = []
o_company = False o_company = False
for j in accounts_ids: for j in accounts_ids:
if j.company_id != o_company: if j.company_id != o_company:
accounts.append(('divider', j.company_id.name)) accounts.append(('divider', j.company_id.name))
o_company = j.company_id o_company = j.company_id
accounts.append((j.id, j.name)) accounts.append((j.id, j.name))
analytics = []
o_company = False
for j in analytics_ids:
if j.company_id != o_company:
analytics.append(('divider', j.company_id.name))
o_company = j.company_id
analytics.append((j.id, j.name))
filter_dict = { filter_dict = {
'journal_ids': r.journal_ids.ids, 'journal_ids': r.journal_ids.ids,
'analytic_ids': r.analytic_ids.ids, 'analytic_ids': r.analytic_ids.ids,
# 'analytic_tag_ids': r.analytic_tag_ids.ids,
'account_ids': r.account_ids.ids, 'account_ids': r.account_ids.ids,
'account_tag_ids': r.account_tag_ids.ids, 'account_tags': r.account_tag_ids.ids,
'company_id': company_id.ids, 'company_id': company_id.ids,
'date_from': r.date_from, 'date_from': r.date_from,
'date_to': r.date_to, 'date_to': r.date_to,
'target_move': r.target_move, 'target_move': r.target_move,
# 'journals_list': [(j.id, j.name, j.code) for j in journals],
'journals_list': journals, 'journals_list': journals,
# 'accounts_list': [(a.id, a.name) for a in accounts],
'accounts_list': accounts, 'accounts_list': accounts,
'account_tag_list': [(a.id, a.name) for a in account_tags], 'account_tag_list': [(a.id, a.name) for a in account_tags],
# 'analytic_list': [(anl.id, anl.name) for anl in analytics], 'analytic_list': analytics,
# 'analytic_tag_list': [(anltag.id, anltag.name) for anltag in analytic_tags],
'company_name': ', '.join(self.env.companies.mapped('name')), 'company_name': ', '.join(self.env.companies.mapped('name')),
} }
filter_dict.update(default_filters) filter_dict.update(default_filters)
return filter_dict return filter_dict
def _get_report_values(self, data): def _get_report_value(self, data):
docs = data['model'] docs = data['model']
display_account = data['display_account'] display_account = data['display_account']
init_balance = True init_balance = True
# journal report values
journals = data['journals'] journals = data['journals']
if not journals: if not journals:
raise UserError(_("No journals Found! Please Add One")) raise UserError(_("No journals Found! Please Add One"))
company_id = self.env.companies company_id = self.env.companies
company_domain = [('company_id', 'in', company_id.ids)] company_domain = [('company_id', 'in', company_id.ids)]
accounts = self.env['account.account'].search(company_domain) accounts = self.env['account.account'].search(company_domain)
@ -237,11 +230,26 @@ class GeneralView(models.TransientModel):
raise UserError(_("No Accounts Found! Please Add One")) raise UserError(_("No Accounts Found! Please Add One"))
account_res = self._get_accounts(accounts, init_balance, account_res = self._get_accounts(accounts, init_balance,
display_account, data) display_account, data)
list_ac = []
for rec in account_res:
list_ac.append(rec['account_id'])
title = "General Ledger"
account_line = self.get_accounts_line(list_ac, title)['report_lines']
acc_line_list = []
acc_line_list.clear()
for line in account_line[0]['move_lines']:
acc_line_list.append(line)
for res in account_res:
line_list = []
line_list.clear()
for line in acc_line_list:
if line['account_id'] == res['account_id']:
line_list.append(line)
res['move_lines'] = line_list
debit_total = 0 debit_total = 0
debit_total = sum(x['debit'] for x in account_res) debit_total = sum(x['debit'] for x in account_res)
credit_total = sum(x['credit'] for x in account_res) credit_total = sum(x['credit'] for x in account_res)
debit_balance = round(debit_total, 2) - round(credit_total, 2) debit_balance = round(debit_total, 2) - round(credit_total, 2)
return { return {
'doc_ids': self.ids, 'doc_ids': self.ids,
'debit_total': debit_total, 'debit_total': debit_total,
@ -262,33 +270,37 @@ class GeneralView(models.TransientModel):
def write(self, vals): def write(self, vals):
if vals.get('target_move'): if vals.get('target_move'):
vals.update({'target_move': vals.get('target_move').lower()}) vals.update({'target_move': vals.get('target_move').lower()})
# journal filter
if vals.get('journal_ids'): if vals.get('journal_ids'):
vals.update({'journal_ids': [(6, 0, vals.get('journal_ids'))]}) vals.update({'journal_ids': [(6, 0, vals.get('journal_ids'))]})
if vals.get('journal_ids') == []: if vals.get('journal_ids') == []:
vals.update({'journal_ids': [(5,)]}) vals.update({'journal_ids': [(5,)]})
# Accounts filter
if vals.get('account_ids'): if vals.get('account_ids'):
vals.update( vals.update(
{'account_ids': [(4, j) for j in vals.get('account_ids')]}) {'account_ids': [(6, 0, vals.get('account_ids'))]})
if vals.get('account_ids') == []: if vals.get('account_ids') == []:
vals.update({'account_ids': [(5,)]}) vals.update({'account_ids': [(5,)]})
# Account Tag filter
if vals.get('account_tag_ids'): if vals.get('account_tag_ids'):
vals.update({'account_tag_ids': [(4, j) for j in vals.update({'account_tag_ids': [(6, 0,
vals.get('account_tag_ids')]}) vals.get('account_tag_ids'))]})
if vals.get('account_tag_ids') == []: if vals.get('account_tag_ids') == []:
vals.update({'account_tag_ids': [(5,)]}) vals.update({'account_tag_ids': [(5,)]})
# Analytic filter
if vals.get('analytic_ids'): if vals.get('analytic_ids'):
vals.update( # print("lllllllllllllll",vals['analytic_ids'])
{'analytic_ids': [(4, j) for j in vals.get('analytic_ids')]}) vals.update({'analytic_ids': [(6, 0, vals.get('analytic_ids'))]})
if vals.get('analytic_ids') == []: if vals.get('analytic_ids') == []:
vals.update({'analytic_ids': [(5,)]}) vals.update({'analytic_ids': [(5,)]})
res = super(GeneralView, self).write(vals) res = super(GeneralView, self).write(vals)
return res return res
def _get_accounts(self, accounts, init_balance, display_account, data): def _get_accounts(self, accounts, init_balance, display_account, data):
cr = self.env.cr cr = self.env.cr
MoveLine = self.env['account.move.line'] MoveLine = self.env['account.move.line']
move_lines = {x: [] for x in accounts.ids} move_lines = {x: [] for x in accounts.ids}
# Prepare initial sql query and Get the initial move lines # Prepare initial sql query and Get the initial move lines
if init_balance and data.get('date_from'): if init_balance and data.get('date_from'):
init_tables, init_where_clause, init_where_params = MoveLine.with_context( init_tables, init_where_clause, init_where_params = MoveLine.with_context(
@ -317,19 +329,36 @@ class GeneralView(models.TransientModel):
else: else:
WHERE = "WHERE l.account_id IN %s" WHERE = "WHERE l.account_id IN %s"
sql = ("""SELECT 0 AS lid, l.account_id AS account_id, '' AS ldate, '' AS lcode, 0.0 AS amount_currency, '' AS lref, 'Initial Balance' AS lname, COALESCE(SUM(l.debit),0.0) AS debit, COALESCE(SUM(l.credit),0.0) AS credit, COALESCE(SUM(l.debit),0) - COALESCE(SUM(l.credit), 0) as balance, '' AS lpartner_id,\ if data.get('analytics'):
'' AS move_name, '' AS mmove_id, '' AS currency_code,\ # print("Analytic account filter woking in GL")
NULL AS currency_id,\ WHERE += ' AND an.id IN %s' % str(
'' AS invoice_id, '' AS invoice_type, '' AS invoice_number,\ tuple(data.get('analytics').ids) + tuple([0]))
'' AS partner_name\ if data['account_tags']:
FROM account_move_line l\ WHERE += ' AND tag IN %s' % str(data.get('account_tags'))
LEFT JOIN account_move m ON (l.move_id=m.id)\ sql = ('''SELECT l.account_id AS account_id, a.code AS code,
LEFT JOIN res_currency c ON (l.currency_id=c.id)\ a.id AS id, a.name AS name,
LEFT JOIN res_partner p ON (l.partner_id=p.id)\ ROUND(COALESCE(SUM(l.debit),0),2) AS debit,
LEFT JOIN account_move i ON (m.id =i.id)\ ROUND(COALESCE(SUM(l.credit),0),2) AS credit,
LEFT JOIN account_account_tag_account_move_line_rel acc ON (acc.account_move_line_id=l.id) ROUND(COALESCE(SUM(l.balance),0),2) AS balance,
JOIN account_journal j ON (l.journal_id=j.id)""" anl.keys, act.name as tag
+ WHERE + new_filter + ' GROUP BY l.account_id') FROM account_move_line l
LEFT JOIN account_move m ON (l.move_id = m.id)
LEFT JOIN res_currency c ON (l.currency_id = c.id)
LEFT JOIN res_partner p ON (l.partner_id = p.id)
JOIN account_journal j ON (l.journal_id = j.id)
JOIN account_account a ON (l.account_id = a.id)
LEFT JOIN account_account_account_tag acct ON
(acct.account_account_id = l.account_id)
LEFT JOIN account_account_tag act ON
(act.id = acct.account_account_tag_id)
LEFT JOIN LATERAL (
SELECT jsonb_object_keys(l.analytic_distribution)::INT
AS keys) anl ON true
LEFT JOIN account_analytic_account an
ON (anl.keys = an.id)'''
+ WHERE + new_filter + ''' GROUP BY l.account_id,
a.code,a.id,a.name,anl.keys, act.name''')
if data.get('accounts'): if data.get('accounts'):
params = tuple(init_where_params) params = tuple(init_where_params)
else: else:
@ -338,7 +367,6 @@ class GeneralView(models.TransientModel):
for row in cr.dictfetchall(): for row in cr.dictfetchall():
row['m_id'] = row['account_id'] row['m_id'] = row['account_id']
move_lines[row.pop('account_id')].append(row) move_lines[row.pop('account_id')].append(row)
tables, where_clause, where_params = MoveLine._query_get() tables, where_clause, where_params = MoveLine._query_get()
wheres = [""] wheres = [""]
if where_clause.strip(): if where_clause.strip():
@ -356,7 +384,6 @@ class GeneralView(models.TransientModel):
new_final_filter += " AND l.date >= '%s'" % data.get('date_from') new_final_filter += " AND l.date >= '%s'" % data.get('date_from')
if data.get('date_to'): if data.get('date_to'):
new_final_filter += " AND l.date <= '%s'" % data.get('date_to') new_final_filter += " AND l.date <= '%s'" % data.get('date_to')
if data['journals']: if data['journals']:
new_final_filter += ' AND j.id IN %s' % str( new_final_filter += ' AND j.id IN %s' % str(
tuple(data['journals'].ids) + tuple([0])) tuple(data['journals'].ids) + tuple([0]))
@ -365,17 +392,38 @@ class GeneralView(models.TransientModel):
tuple(data.get('accounts').ids) + tuple([0])) tuple(data.get('accounts').ids) + tuple([0]))
else: else:
WHERE = "WHERE l.account_id IN %s" WHERE = "WHERE l.account_id IN %s"
if data.get('analytics'):
# Get move lines base on sql query and Calculate the total balance of move lines WHERE += ' AND an.id IN %s' % str(
sql = ('''SELECT l.account_id AS account_id, a.code AS code,a.id AS id, a.name AS name, ROUND(COALESCE(SUM(l.debit),0),2) AS debit, ROUND(COALESCE(SUM(l.credit),0),2) AS credit, ROUND(COALESCE(SUM(l.balance),0),2) AS balance tuple(data.get('analytics').ids) + tuple([0]))
if data.get('account_tags'):
FROM account_move_line l\ WHERE += ' AND act.id IN %s' % str(tuple(data.get('account_tags').ids)+ tuple([0]))
JOIN account_move m ON (l.move_id=m.id)\ print('genrl ledger where !!!',WHERE)
LEFT JOIN res_currency c ON (l.currency_id=c.id)\
LEFT JOIN res_partner p ON (l.partner_id=p.id)\ # Get move lines base on sql query and Calculate the total balance
JOIN account_journal j ON (l.journal_id=j.id)\ # of move lines
JOIN account_account a ON (l.account_id = a.id) ''' sql = ('''SELECT l.account_id AS account_id, a.code AS code,
+ WHERE + new_final_filter + ''' GROUP BY l.account_id, a.code, a.name, a.id''') a.id AS id, a.name AS name,
ROUND(COALESCE(SUM(l.debit),0),2) AS debit,
ROUND(COALESCE(SUM(l.credit),0),2) AS credit,
ROUND(COALESCE(SUM(l.balance),0),2) AS balance,
anl.keys, act.name as tag
FROM account_move_line l
LEFT JOIN account_move m ON (l.move_id = m.id)
LEFT JOIN res_currency c ON (l.currency_id = c.id)
LEFT JOIN res_partner p ON (l.partner_id = p.id)
JOIN account_journal j ON (l.journal_id = j.id)
JOIN account_account a ON (l.account_id = a.id)
LEFT JOIN account_account_account_tag acct ON
(acct.account_account_id = l.account_id)
LEFT JOIN account_account_tag act ON
(act.id = acct.account_account_tag_id)
LEFT JOIN LATERAL (
SELECT jsonb_object_keys(l.analytic_distribution)::INT
AS keys) anl ON true
LEFT JOIN account_analytic_account an
ON (anl.keys = an.id)'''
+ WHERE + new_final_filter + ''' GROUP BY l.account_id,
a.code,a.id,a.name,anl.keys, act.name''')
if data.get('accounts'): if data.get('accounts'):
params = tuple(where_params) params = tuple(where_params)
else: else:
@ -400,11 +448,13 @@ class GeneralView(models.TransientModel):
def get_accounts_line(self, account_id, title): def get_accounts_line(self, account_id, title):
# to get the english translation of the title # to get the english translation of the title
record_id = self.env['ir.actions.client'].with_context(lang=self.env.user.lang). \ record_id = self.env['ir.actions.client'].with_context(
lang=self.env.user.lang). \
search([('name', '=', title)]).id search([('name', '=', title)]).id
trans_title = self.env['ir.actions.client'].with_context(lang='en_US').search([('id', '=', record_id)]).name trans_title = self.env['ir.actions.client'].with_context(
lang='en_US').search([('id', '=', record_id)]).name
company_id = self.env.companies.ids company_id = self.env.companies.ids
# Journal based account lines
if self.journal_ids: if self.journal_ids:
journals = self.journal_ids journals = self.journal_ids
else: else:
@ -422,7 +472,7 @@ class GeneralView(models.TransientModel):
if title == 'Cash Book' or trans_title == 'Cash Book': if title == 'Cash Book' or trans_title == 'Cash Book':
journals = self.env['account.journal'].search( journals = self.env['account.journal'].search(
[('type', '=', 'cash'), ('company_id', 'in', company_id)]) [('type', '=', 'cash'), ('company_id', 'in', company_id)])
# account based move lines
if account_id: if account_id:
accounts = self.env['account.account'].search( accounts = self.env['account.account'].search(
[('id', '=', account_id)]) [('id', '=', account_id)])
@ -430,11 +480,15 @@ class GeneralView(models.TransientModel):
company_id = self.env.companies company_id = self.env.companies
company_domain = [('company_id', 'in', company_id.ids)] company_domain = [('company_id', 'in', company_id.ids)]
accounts = self.env['account.account'].search(company_domain) accounts = self.env['account.account'].search(company_domain)
cr = self.env.cr cr = self.env.cr
MoveLine = self.env['account.move.line'] MoveLine = self.env['account.move.line']
move_lines = {x: [] for x in accounts.ids} move_lines = {x: [] for x in accounts.ids}
# Prepare initial sql query and Get the initial move lines
if self.date_from:
init_tables, init_where_clause, init_where_params = MoveLine.with_context(
date_from=self.env.context.get('date_from'), date_to=False,
initial_bal=True)._query_get()
tables, where_clause, where_params = MoveLine._query_get() tables, where_clause, where_params = MoveLine._query_get()
wheres = [""] wheres = [""]
if where_clause.strip(): if where_clause.strip():
@ -452,7 +506,6 @@ class GeneralView(models.TransientModel):
new_final_filter += " AND l.date >= '%s'" % self.date_from new_final_filter += " AND l.date >= '%s'" % self.date_from
if self.date_to: if self.date_to:
new_final_filter += " AND l.date <= '%s'" % self.date_to new_final_filter += " AND l.date <= '%s'" % self.date_to
if journals: if journals:
new_final_filter += ' AND j.id IN %s' % str( new_final_filter += ' AND j.id IN %s' % str(
tuple(journals.ids) + tuple([0])) tuple(journals.ids) + tuple([0]))
@ -461,20 +514,31 @@ class GeneralView(models.TransientModel):
tuple(accounts.ids) + tuple([0])) tuple(accounts.ids) + tuple([0]))
else: else:
WHERE = "WHERE l.account_id IN %s" WHERE = "WHERE l.account_id IN %s"
if self.analytic_ids:
WHERE += ' AND an.id IN %s' % str(
tuple(self.analytic_ids.ids) + tuple([0]))
# Get move lines base on sql query and Calculate the total balance of move lines # Get move lines base on sql query and Calculate the total balance of
# move lines
sql = ('''SELECT l.id AS lid,m.id AS move_id, l.account_id AS account_id, sql = ('''SELECT l.id AS lid,m.id AS move_id, l.account_id AS account_id,
l.date AS ldate, j.code AS lcode, l.currency_id, l.amount_currency, l.date AS ldate, j.code AS lcode, l.currency_id, l.amount_currency,
l.ref AS lref, l.name AS lname, COALESCE(l.debit,0) AS debit, l.ref AS lref, l.name AS lname, COALESCE(l.debit,0) AS debit,
COALESCE(l.credit,0) AS credit, COALESCE(SUM(l.balance),0) AS balance, COALESCE(l.credit,0) AS credit, COALESCE(SUM(l.balance),0) AS balance,
m.name AS move_name, c.symbol AS currency_code, p.name AS partner_name m.name AS move_name, c.symbol AS currency_code,
FROM account_move_line l p.name AS partner_name, anl.keys
JOIN account_move m ON (l.move_id=m.id) FROM account_move_line l
LEFT JOIN res_currency c ON (l.currency_id=c.id) JOIN account_move m ON (l.move_id=m.id)
LEFT JOIN res_partner p ON (l.partner_id=p.id) LEFT JOIN res_currency c ON (l.currency_id=c.id)
JOIN account_journal j ON (l.journal_id=j.id) LEFT JOIN res_partner p ON (l.partner_id=p.id)
JOIN account_account a ON (l.account_id = a.id) ''' LEFT JOIN LATERAL (
+ WHERE + new_final_filter + ''' GROUP BY l.id, m.id, l.account_id, l.date, j.code, l.currency_id, l.amount_currency, l.ref, l.name, m.name, c.symbol, c.position, p.name''') SELECT jsonb_object_keys(l.analytic_distribution)::INT
AS keys) anl ON true
LEFT JOIN account_analytic_account an ON (anl.keys = an.id)
JOIN account_journal j ON (l.journal_id=j.id)
JOIN account_account a ON (l.account_id = a.id) '''
+ WHERE + new_final_filter + ''' GROUP BY l.id, m.id,
l.account_id, l.date, j.code, l.currency_id, l.amount_currency,
l.ref, l.name, m.name, c.symbol, c.position, p.name, anl.keys''')
params = tuple(where_params) params = tuple(where_params)
cr.execute(sql, params) cr.execute(sql, params)
account_ress = cr.dictfetchall() account_ress = cr.dictfetchall()
@ -482,17 +546,16 @@ class GeneralView(models.TransientModel):
# Calculate the debit, credit and balance for Accounts # Calculate the debit, credit and balance for Accounts
account_res = [] account_res = []
for account in accounts: for account in accounts:
currency = account.currency_id and account.currency_id or account.company_id.currency_id currency = (account.currency_id and account.currency_id or
account.company_id.currency_id)
res = dict((fn, 0.0) for fn in ['credit', 'debit', 'balance']) res = dict((fn, 0.0) for fn in ['credit', 'debit', 'balance'])
res['code'] = account.code res['code'] = account.code
res['name'] = account.name res['name'] = account.name
res['id'] = account.id res['id'] = account.id
res['move_lines'] = account_ress res['move_lines'] = account_ress
account_res.append(res) account_res.append(res)
currency = self._get_currency() currency = self._get_currency()
return { return {
'report_lines': account_res, 'report_lines': account_res,
'currency': currency, 'currency': currency,
} }
@ -526,9 +589,6 @@ class GeneralView(models.TransientModel):
if filters.get('date_to'): if filters.get('date_to'):
sheet.merge_range('H4:I4', 'To: ' + filters.get('date_to'), sheet.merge_range('H4:I4', 'To: ' + filters.get('date_to'),
date_head) date_head)
# sheet.merge_range('A5:J6', 'Journals: ' + ', '.join(
# [lt or '' for lt in filters['journals']]) + ' Target Moves: ' + filters.get('target_move'), date_head)
sheet.merge_range('A5:J6', ' Journals: ' + ', '.join( sheet.merge_range('A5:J6', ' Journals: ' + ', '.join(
[lt or '' for lt in [lt or '' for lt in
filters['journals']]) + ' Accounts: ' + ', '.join( filters['journals']]) + ' Accounts: ' + ', '.join(
@ -536,9 +596,7 @@ class GeneralView(models.TransientModel):
filters['accounts']]) + ' Account Tags: ' + ', '.join( filters['accounts']]) + ' Account Tags: ' + ', '.join(
[at or '' for at in [at or '' for at in
filters['analytics']]) + ' Target Moves : ' + filters.get( filters['analytics']]) + ' Target Moves : ' + filters.get(
'target_move'), 'target_move'), date_head)
date_head)
sheet.write('A8', 'Code', sub_heading) sheet.write('A8', 'Code', sub_heading)
sheet.write('B8', 'Amount', sub_heading) sheet.write('B8', 'Amount', sub_heading)
sheet.write('C8', 'Date', sub_heading) sheet.write('C8', 'Date', sub_heading)
@ -549,7 +607,6 @@ class GeneralView(models.TransientModel):
sheet.write('H8', 'Debit', sub_heading) sheet.write('H8', 'Debit', sub_heading)
sheet.write('I8', 'Credit', sub_heading) sheet.write('I8', 'Credit', sub_heading)
sheet.write('J8', 'Balance', sub_heading) sheet.write('J8', 'Balance', sub_heading)
row = 6 row = 6
col = 0 col = 0
sheet.set_column(8, 0, 15) sheet.set_column(8, 0, 15)
@ -562,9 +619,7 @@ class GeneralView(models.TransientModel):
sheet.set_column(8, 7, 26) sheet.set_column(8, 7, 26)
sheet.set_column(8, 8, 15) sheet.set_column(8, 8, 15)
sheet.set_column(8, 9, 15) sheet.set_column(8, 9, 15)
for rec_data in report_data_main: for rec_data in report_data_main:
row += 1 row += 1
sheet.write(row + 1, col, rec_data['code'], txt) sheet.write(row + 1, col, rec_data['code'], txt)
sheet.write(row + 1, col + 1, rec_data['name'], txt) sheet.write(row + 1, col + 1, rec_data['name'], txt)
@ -573,7 +628,6 @@ class GeneralView(models.TransientModel):
sheet.write(row + 1, col + 4, '', txt) sheet.write(row + 1, col + 4, '', txt)
sheet.write(row + 1, col + 5, '', txt) sheet.write(row + 1, col + 5, '', txt)
sheet.write(row + 1, col + 6, '', txt) sheet.write(row + 1, col + 6, '', txt)
sheet.write(row + 1, col + 7, rec_data['debit'], txt) sheet.write(row + 1, col + 7, rec_data['debit'], txt)
sheet.write(row + 1, col + 8, rec_data['credit'], txt) sheet.write(row + 1, col + 8, rec_data['credit'], txt)
sheet.write(row + 1, col + 9, rec_data['balance'], txt) sheet.write(row + 1, col + 9, rec_data['balance'], txt)
@ -590,7 +644,6 @@ class GeneralView(models.TransientModel):
sheet.write(row + 1, col + 7, line_data.get('debit'), txt) sheet.write(row + 1, col + 7, line_data.get('debit'), txt)
sheet.write(row + 1, col + 8, line_data.get('credit'), txt) sheet.write(row + 1, col + 8, line_data.get('credit'), txt)
sheet.write(row + 1, col + 9, line_data.get('balance'), txt) sheet.write(row + 1, col + 9, line_data.get('balance'), txt)
workbook.close() workbook.close()
output.seek(0) output.seek(0)
response.stream.write(output.read()) response.stream.write(output.read())

164
dynamic_accounts_report/wizard/partner_leadger.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import time import time
from odoo import fields, models, api, _ from odoo import fields, models, api, _
@ -31,13 +52,13 @@ class PartnerView(models.TransientModel):
partner_ids = fields.Many2many('res.partner', string='Partner') partner_ids = fields.Many2many('res.partner', string='Partner')
partner_category_ids = fields.Many2many('res.partner.category', partner_category_ids = fields.Many2many('res.partner.category',
string='Partner tags') string='Partner tags')
reconciled = fields.Selection([ reconciled = fields.Selection([('all', 'All'),
('unreconciled', 'Unreconciled Only'), ('all', 'All')], ('unreconciled', 'Unreconciled Only')],
string='Reconcile Type', default='all') string='Reconcile Type', default='all')
account_type_id = fields.Selection([ account_type = fields.Selection([
("asset_receivable", "Receivable"), ("liability_payable", "Payable")], ("asset_receivable", "Receivable"), ("liability_payable", "Payable"),
string="Account Type") ('all', 'All')], string="Account Type", default='all')
@api.model @api.model
def view_report(self, option): def view_report(self, option):
@ -50,7 +71,7 @@ class PartnerView(models.TransientModel):
'target_move': r.target_move, 'target_move': r.target_move,
'partners': r.partner_ids, 'partners': r.partner_ids,
'reconciled': r.reconciled, 'reconciled': r.reconciled,
'account_type': r.account_type_id, 'account_type': r.account_type,
'partner_tags': r.partner_category_ids, 'partner_tags': r.partner_category_ids,
} }
@ -62,11 +83,9 @@ class PartnerView(models.TransientModel):
data.update({ data.update({
'date_to': r.date_to, 'date_to': r.date_to,
}) })
filters = self.get_filter(option) filters = self.get_filter(option)
records = self._get_report_values(data) records = self._get_report_value(data)
currency = self._get_currency() currency = self._get_currency()
return { return {
'name': "partner Ledger", 'name': "partner Ledger",
'type': 'ir.actions.client', 'type': 'ir.actions.client',
@ -82,16 +101,19 @@ class PartnerView(models.TransientModel):
def get_filter(self, option): def get_filter(self, option):
data = self.get_filter_data(option) data = self.get_filter_data(option)
filters = {} filters = {}
# journal filter
if data.get('journal_ids'): if data.get('journal_ids'):
filters['journals'] = self.env['account.journal'].browse( filters['journals'] = self.env['account.journal'].browse(
data.get('journal_ids')).mapped('code') data.get('journal_ids')).mapped('code')
else: else:
filters['journals'] = ['All'] filters['journals'] = ['All']
# Accounts filter
if data.get('account_ids', []): if data.get('account_ids', []):
filters['accounts'] = self.env['account.account'].browse( filters['accounts'] = self.env['account.account'].browse(
data.get('account_ids', [])).mapped('code') data.get('account_ids', [])).mapped('name')
else: else:
filters['accounts'] = ['All Payable and Receivable'] filters['accounts'] = ['All Payable and Receivable']
# target move filter
if data.get('target_move'): if data.get('target_move'):
filters['target_move'] = data.get('target_move').capitalize() filters['target_move'] = data.get('target_move').capitalize()
if data.get('date_from'): if data.get('date_from'):
@ -114,12 +136,14 @@ class PartnerView(models.TransientModel):
if data.get('reconciled') == 'unreconciled': if data.get('reconciled') == 'unreconciled':
filters['reconciled'] = 'Unreconciled' filters['reconciled'] = 'Unreconciled'
if data.get('account_type', []): if data.get('account_type') == 'asset_receivable':
filters['account_type'] = self.env[ filters['account_type'] = 'asset_receivable'
'account.account.type'].sudo().browse(
data.get('account_type', [])).mapped('name') elif data.get('account_type') == 'liability_payable':
filters['account_type'] = 'liability_payable'
else: else:
filters['account_type'] = ['Receivable and Payable'] filters['account_type'] = 'Receivable and Payable'
if data.get('partner_tags', []): if data.get('partner_tags', []):
filters['partner_tags'] = self.env['res.partner.category'].browse( filters['partner_tags'] = self.env['res.partner.category'].browse(
@ -147,7 +171,8 @@ class PartnerView(models.TransientModel):
'res.partner'].search([]) 'res.partner'].search([])
categories = self.partner_category_ids if self.partner_category_ids \ categories = self.partner_category_ids if self.partner_category_ids \
else self.env['res.partner.category'].search([]) else self.env['res.partner.category'].search([])
account_types = r.account_type_id
journals = [] journals = []
o_company = False o_company = False
@ -158,14 +183,15 @@ class PartnerView(models.TransientModel):
journals.append((j.id, j.name, j.code)) journals.append((j.id, j.name, j.code))
accounts = [] accounts = []
o_company = False o_company = False
for j in accounts_ids: for j in accounts_ids:
if j.company_id != o_company: if j.company_id != o_company:
accounts.append(('divider', j.company_id.name)) accounts.append(('divider', j.company_id.name))
o_company = j.company_id o_company = j.company_id
accounts.append((j.id, j.name)) accounts.append((j.id, j.name))
partner_data = []
for p in partner:
partner_data.append((p.id, p.name))
filter_dict = { filter_dict = {
'journal_ids': r.journal_ids.ids, 'journal_ids': r.journal_ids.ids,
'account_ids': r.account_ids.ids, 'account_ids': r.account_ids.ids,
@ -175,21 +201,18 @@ class PartnerView(models.TransientModel):
'target_move': r.target_move, 'target_move': r.target_move,
'journals_list': journals, 'journals_list': journals,
'accounts_list': accounts, 'accounts_list': accounts,
# 'company_name': company_id and company_id.name,
'company_name': ', '.join(self.env.companies.mapped('name')), 'company_name': ', '.join(self.env.companies.mapped('name')),
'partners': r.partner_ids.ids, 'partners': r.partner_ids.ids,
'reconciled': r.reconciled, 'reconciled': r.reconciled,
'account_type': r.account_type_id, 'account_type': r.account_type,
'partner_tags': r.partner_category_ids.ids, 'partner_tags': r.partner_category_ids.ids,
'partners_list': [(p.id, p.name) for p in partner], 'partners_list': partner_data,
'category_list': [(c.id, c.name) for c in categories], 'category_list': [(c.id, c.display_name) for c in categories],
'account_type_list': account_types
} }
filter_dict.update(default_filters) filter_dict.update(default_filters)
return filter_dict return filter_dict
def _get_report_values(self, data): def _get_report_value(self, data):
docs = data['model'] docs = data['model']
display_account = data['display_account'] display_account = data['display_account']
init_balance = True init_balance = True
@ -199,11 +222,11 @@ class PartnerView(models.TransientModel):
('company_id', 'in', company_id)]) ('company_id', 'in', company_id)])
if data['account_type']: if data['account_type']:
accounts = self.env['account.account'].search( accounts = self.env['account.account'].search(
[('account_type', 'in', data['account_type'].ids), [('account_type', 'in',
('asset_receivable', 'liability_payable')),
('company_id', 'in', company_id)]) ('company_id', 'in', company_id)])
partners = self.env['res.partner'].search([]) partners = self.env['res.partner'].search([])
if data['partner_tags']: if data['partner_tags']:
partners = self.env['res.partner'].search( partners = self.env['res.partner'].search(
[('category_id', 'in', data['partner_tags'].ids)]) [('category_id', 'in', data['partner_tags'].ids)])
@ -211,7 +234,6 @@ class PartnerView(models.TransientModel):
raise UserError(_("No Accounts Found! Please Add One")) raise UserError(_("No Accounts Found! Please Add One"))
partner_res = self._get_partners(partners, accounts, init_balance, partner_res = self._get_partners(partners, accounts, init_balance,
display_account, data) display_account, data)
debit_total = 0 debit_total = 0
debit_total = sum(x['debit'] for x in partner_res) debit_total = sum(x['debit'] for x in partner_res)
credit_total = sum(x['credit'] for x in partner_res) credit_total = sum(x['credit'] for x in partner_res)
@ -236,44 +258,43 @@ class PartnerView(models.TransientModel):
def write(self, vals): def write(self, vals):
if vals.get('target_move'): if vals.get('target_move'):
vals.update({'target_move': vals.get('target_move').lower()}) vals.update({'target_move': vals.get('target_move').lower()})
# journal filter
if vals.get('journal_ids'): if vals.get('journal_ids'):
vals.update({'journal_ids': [(6, 0, vals.get('journal_ids'))]}) vals.update({'journal_ids': [(6, 0, vals.get('journal_ids'))]})
if not vals.get('journal_ids'): if not vals.get('journal_ids'):
vals.update({'journal_ids': [(5,)]}) vals.update({'journal_ids': [(5,)]})
# Accounts filter
if vals.get('account_ids'): if vals.get('account_ids'):
vals.update( vals.update({'account_ids': [(6, 0, vals.get('account_ids'))]})
{'account_ids': [(4, j) for j in vals.get('account_ids')]})
if not vals.get('account_ids'): if not vals.get('account_ids'):
vals.update({'account_ids': [(5,)]}) vals.update({'account_ids': [(5,)]})
# Partner filter
if vals.get('partner_ids'): if vals.get('partner_ids'):
vals.update( vals.update({'partner_ids': [(6, 0, vals.get('partner_ids'))]})
{'partner_ids': [(4, j) for j in vals.get('partner_ids')]})
if not vals.get('partner_ids'): if not vals.get('partner_ids'):
vals.update({'partner_ids': [(5,)]}) vals.update({'partner_ids': [(5,)]})
# Partner Category filter
if vals.get('partner_category_ids'): if vals.get('partner_category_ids'):
vals.update({'partner_category_ids': [(4, j) for j in vals.get( vals.update({'partner_category_ids': [(6, 0, vals.get(
'partner_category_ids')]}) 'partner_category_ids'))]})
if not vals.get('partner_category_ids'): if not vals.get('partner_category_ids'):
vals.update({'partner_category_ids': [(5,)]}) vals.update({'partner_category_ids': [(5,)]})
# Account Type filter
# if vals.get('account_type-ids'): # if vals.get('account_type'):
# print('vals.get account_type..........',vals.get('account_type'))
# vals.update( # vals.update(
# {'account_type_ids': [(4, j) for j in # {'account_type': [(6, 0, vals.get('account_type'))]})
# vals.get('account_type_ids')]}) # if not vals.get('account_type'):
# if not vals.get('account_type_ids'): # vals.update({'account_type': [(5,)]})
# vals.update({'account_type_ids': [(5,)]})
res = super(PartnerView, self).write(vals) res = super(PartnerView, self).write(vals)
return res return res
def _get_partners(self, partners, accounts, init_balance, display_account, def _get_partners(self, partners, accounts, init_balance, display_account,
data): data, asset_receivable=None):
cr = self.env.cr cr = self.env.cr
move_line = self.env['account.move.line'] move_line = self.env['account.move.line']
move_lines = {x: [] for x in partners.ids} move_lines = {x: [] for x in partners.ids}
currency_id = self.env.company.currency_id currency_id = self.env.company.currency_id
tables, where_clause, where_params = move_line._query_get() tables, where_clause, where_params = move_line._query_get()
wheres = [""] wheres = [""]
if where_clause.strip(): if where_clause.strip():
@ -295,7 +316,6 @@ class PartnerView(models.TransientModel):
if data['journals']: if data['journals']:
new_final_filter += ' AND j.id IN %s' % str( new_final_filter += ' AND j.id IN %s' % str(
tuple(data['journals'].ids) + tuple([0])) tuple(data['journals'].ids) + tuple([0]))
if data.get('accounts'): if data.get('accounts'):
WHERE = "WHERE l.account_id IN %s" % str( WHERE = "WHERE l.account_id IN %s" % str(
tuple(data.get('accounts').ids) + tuple([0])) tuple(data.get('accounts').ids) + tuple([0]))
@ -305,34 +325,49 @@ class PartnerView(models.TransientModel):
if data.get('partners'): if data.get('partners'):
WHERE += ' AND p.id IN %s' % str( WHERE += ' AND p.id IN %s' % str(
tuple(data.get('partners').ids) + tuple([0])) tuple(data.get('partners').ids) + tuple([0]))
if data.get('reconciled') == 'unreconciled': if data.get('reconciled') == 'unreconciled':
WHERE += ' AND l.full_reconcile_id is null AND' \ WHERE += ' AND l.full_reconcile_id is null AND' \
' l.balance != 0 AND a.reconcile is true' ' l.balance != 0 AND acc.reconcile is true'
sql = ('''SELECT l.id AS lid,l.partner_id AS partner_id,m.id AS move_id, if data.get('account_type') == 'asset_receivable':
l.account_id AS account_id, l.date AS ldate, j.code AS lcode, l.currency_id, WHERE += " AND acc.account_type = 'asset_receivable' "
l.amount_currency, l.ref AS lref, l.name AS lname,
COALESCE(l.debit,0) AS debit, COALESCE(l.credit,0) AS credit, elif data.get('account_type') == 'liability_payable':
COALESCE(SUM(l.balance),0) AS balance,\ WHERE += " AND acc.account_type = 'liability_payable' "
m.name AS move_name, c.symbol AS currency_code,c.position AS currency_position, p.name AS partner_name\
FROM account_move_line l\ sql = ('''SELECT l.id AS lid,l.partner_id AS partner_id,
JOIN account_move m ON (l.move_id=m.id)\ m.id AS move_id,
JOIN account_account a ON (l.account_id=a.id) l.account_id AS account_id, l.date AS ldate,
LEFT JOIN res_currency c ON (l.currency_id=c.id)\ acc.account_type AS account_type,
LEFT JOIN res_partner p ON (l.partner_id=p.id)\ j.code AS lcode, l.currency_id,
JOIN account_journal j ON (l.journal_id=j.id)\ l.amount_currency, l.ref AS lref, l.name AS lname,
JOIN account_account acc ON (l.account_id = acc.id) ''' COALESCE(l.debit,0) AS debit, COALESCE(l.credit,0) AS credit,
+ WHERE + new_final_filter + ''' GROUP BY l.id, m.id, l.account_id, l.date, j.code, l.currency_id, l.amount_currency, l.ref, l.name, m.name, c.symbol, c.position, p.name ORDER BY l.date''') COALESCE(SUM(l.balance),0) AS balance,
m.name AS move_name, c.symbol AS currency_code,c.position
AS currency_position, p.name AS partner_name
FROM account_move_line l
JOIN account_move m ON (l.move_id=m.id)
LEFT JOIN res_currency c ON (l.currency_id=c.id)
LEFT JOIN res_partner p ON (l.partner_id=p.id)
JOIN account_journal j ON (l.journal_id=j.id)
JOIN account_account acc ON (l.account_id = acc.id)
''' + WHERE + new_final_filter +
''' GROUP BY l.id, m.id,
l.account_id, l.date, j.code, l.currency_id,
l.amount_currency, l.ref, l.name, m.name, c.symbol,
c.position, p.name, acc.account_type ORDER BY l.date
'''
)
if data.get('accounts'): if data.get('accounts'):
params = tuple(where_params) params = tuple(where_params)
else: else:
params = (tuple(accounts.ids),) + tuple(where_params) params = (tuple(accounts.ids),) + tuple(where_params)
cr.execute(sql, params) cr.execute(sql, params)
account_list = {x.id: {'name': x.name, 'code': x.code} for x in account_list = {x.id: {'name': x.name, 'code': x.code} for x in
accounts} accounts}
a=cr.dictfetchall()
for row in cr.dictfetchall(): for row in a:
balance = 0 balance = 0
if row['partner_id'] in move_lines: if row['partner_id'] in move_lines:
for line in move_lines.get(row['partner_id']): for line in move_lines.get(row['partner_id']):
@ -384,7 +419,6 @@ class PartnerView(models.TransientModel):
def get_dynamic_xlsx_report(self, data, response, report_data, dfr_data): def get_dynamic_xlsx_report(self, data, response, report_data, dfr_data):
report_data = json.loads(report_data) report_data = json.loads(report_data)
filters = json.loads(data) filters = json.loads(data)
output = io.BytesIO() output = io.BytesIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True}) workbook = xlsxwriter.Workbook(output, {'in_memory': True})
cell_format = workbook.add_format( cell_format = workbook.add_format(

21
dynamic_accounts_report/wizard/trial_balance.py

@ -1,3 +1,24 @@
# -*- coding: utf-8 -*-
#############################################################################
#
# Cybrosys Technologies Pvt. Ltd.
#
# Copyright (C) 2022-TODAY Cybrosys Technologies(<https://www.cybrosys.com>)
# Author: Cybrosys Techno Solutions(<https://www.cybrosys.com>)
#
# You can modify it under the terms of the GNU LESSER
# GENERAL PUBLIC LICENSE (LGPL v3), Version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LESSER GENERAL PUBLIC LICENSE (LGPL v3) for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# (LGPL v3) along with this program.
# If not, see <http://www.gnu.org/licenses/>.
#
#############################################################################
import time import time
from odoo import fields, models, api, _ from odoo import fields, models, api, _

Loading…
Cancel
Save